How does one programmatically get and set the position of a product within a category?
$category_id = 101;
$query = "SELECT product_id, position
FROM catalog_category_product
WHERE category_id = $category_id";
$query = mysqli_query($link, $query);
while ($q = mysqli_fetch_array($query)) {
$product_id = $q['product_id'];
$position = $q['position'];
echo $product_id." - ".$position."
";
}
The above code gets the product ID and position of each product in a category through an SQL query, but how can this same result be accomplished through Magento’s Object Manager? For example:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$category_id = 101;
$category = $objectManager->create('MagentoCatalogModelCategory')->load($category_id);
$category_products = $category->getProducts(); //PSEUDOCODE
foreach ($category_products as $product) { //PSEUDOCODE
echo $product->getPosition(); //PSEUDOCODE
} //PSEUDOCODE
I’ve asked this question nearly half a dozen times here in every different way imaginable. It seems that even the most expert Magento 2 developers have no clue how to accomplish this result which was rather simple in Magento 1.