Magento 1.9 – How to Get All Product SKUs in Selected Category

magento-1.9productproduct-collection

I'm trying to set up a form in an external that will give me all Sku's of configurable or simple products in a category entered by the user. Instead, I'm ending up with a list of all products in the store, so my filter doesn't seem to be working:

<?php

function getProductSkus(){
    if(isset($_POST['submit'])){
        $categoryId = $_POST['categoryId'];
        $productType = $_POST['productType'];
        require_once('../app/Mage.php');
        Mage::app();
        $category = Mage::getModel('catalog/category')->load($categoryId);
        if($category){
            $productList = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('type_id', $productType)
                ->addCategoryFilter($category)
            foreach($productList as $product){
                echo $product->getName() . "<br>";
            }
        }
    }
}
?>

<html>
<body>

<form action="getproducts.php" method="post">
<p>Category ID: <input name="categoryId" type="text" /></p>
<p>Product Type: <select name="productType">
    <option value="configurable">Configurable</option>
    <option value="simple">Simple</options>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
<?php getProductSkus(); ?>
</body>
</html>

Can anyone tell me what I'm doing wrong here? I'm essentially following the method here, but using load() after the category filter doesn't seem to have any effect:

https://stackoverflow.com/questions/29124232/magento-get-all-products-in-the-current-category

I've also used the prepareProductCollection method here with the same results:

https://stackoverflow.com/questions/14318488/magento-get-all-products-in-a-certain-category-ordered-by-the-position-field

Best Answer

I found the problem. It turns out that the current store has to be set where I currently have the app initialized at Mage::app();.

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
Related Topic