I'm currently looking for a method to programmatically change the product status of all my products if a certain amount of stock is reached.
Ideally I would like to set all products to status Disabled if the Stock level is under 10. All others that are 10 and more , the product status should become Enabled.
You can try with this code by creating one php file to the root directory or you can create cron scheduler if you want to do this process for some time period.
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ini_set('memory_limit', '600M');
ini_set('max_execution_time', 1800);
umask(0);
Mage::app('admin');
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToSelect('*');
foreach ($collection as $_data) {
$productCat = $_data->getCategoryIds();
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_data);
$productqty = $stock->getQty();
if (intval($productqty) < 10) {
$productModel = Mage::getModel('catalog/product');
$productUpdate = $productModel->load($_data->getId());
$productUpdate->setStatus(2);
$productUpdate->save();
}
else
{
$productModel = Mage::getModel('catalog/product');
$productUpdate = $productModel->load($_data->getId());
$productUpdate->setStatus(1);
$productUpdate->save();
}
}
Related
For the below code, where I am trying to update a custom attribute called branding. The for loop is running only for one iteration and stopping. It is updating only the first product in the list and not looping any further.
Can anyone kindly let me know why this is happening?
<?php
set_time_limit(0);
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $product){
echo $product->getSku();
$product->setData('branding', 'kib');
$product->save();
}
Instead of saving total product just save attribute for product by using saveAttribute
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
echo $products->getSelect();//this will give sql query just run your db.
foreach($products as $product)
{
$product->setBranding('kib');
$product->getResource()->saveAttribute($product, 'branding');
}
One more solution without loops
$store_id = 0;
$product_ids = Mage::getModel('catalog/product')
->getCollection()
->getAllIds();//you can apply some filters also
Mage::getSingleton('catalog/product_action')->updateAttributes(
$product_ids,//array of ids
array('branding' => 'kib'),//you can add some other attributes also as key value pair
$store_id
);
I want to update from my script the meta title, the meta description and the meta keywords for all of my products.
The meta title = the name of the product
The meta description = the short description of the product
The meta keywords is the meta keywords i've put from the category of the product.
I can loop and get the informations i want to make the update (except the meta keywords of the description) and after how i can make the update inside the loop ?
Thanks
<?php require_once 'app/Mage.php';
umask(0);
set_time_limit(0); // ignore php timeout
ignore_user_abort(true); // keep on going even if user pulls the plug*
while(ob_get_level())ob_end_clean(); // remove output buffers
ob_implicit_flush(true); // output stuff directly
//error_reporting(E_ALL);
/* not Mage::run(); */
Mage::app('default');
// get product collection (All product)
$storeId = Mage::app()->getStore()->getId();
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->setStoreId($storeId)
->addStoreFilter($storeId);
foreach ($_productCollection as $pro) { // loop each product
$meta_title = $pro['meta_title'];
$meta_description = $pro['meta_description'];
$name = $pro['name'];
$short_description = $pro['short_description'];
// I want to update the meta_title, meta_description, meta_keywords
// meta_description = short_description
// meta_title = name
// meta_keywords = meta keywords from the category of the product
}
?>
You can easy set keyword and description by using standard setters.
Inside foreach loop just use :
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$product->setMetaTitle('Product Title')
->setMetaKeyword('Product keywords')
->setMetaDescription('Product Description')
->save();
endforeach;
Try this,
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$cats = $product->getCategoryIds();
$meta_keys = '';
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($_cat->getMetaKeywords())
$meta_keys .= $_cat->getMetaKeywords().', ';
}
$product->setMetaTitle($pro->getName())
->setMetaKeyword($meta_keys)
->setMetaDescription($pro->getShortDescription())
->save();
endforeach;
I want to use url http://mydomain.test/categoru-name.html?cat=9,10,40 . I need to get all products from category category-name and sub-categories with category ids (9,10,40).
How can i do this? Maybe there is such an extension.
Add a php page (categoru-name.php) to Magento root with following code. You need to do few modifications to get it to work.
/** START Include Magento **/
define('MAGENTO_ROOT', getcwd());
$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
include $compilerConfig;
}else{exit;}
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
if (file_exists($mageFilename)) {
require_once $mageFilename;
}else{exit;}
Mage::app();
/** END Include Magento **/
// This is not a complete code. You need to fill in.
// Add from query paramter
$categoryIds = array("Insert IDs from URL");
$categoryIdList = array();
array_push($categoryIdList,$categoryIds); //Collect child category IDs
foreach($categoryIds as $Catid){
$cat = Mage::getModel('catalog/category')->load($Catid);
$subCats = $cat->getChildren();
$arrSubCats = explode(',',$subCats);
array_push($categoryIdList,$arrSubCats); //Collect child category IDs
// Go another level down
foreach($arrSubCats as $Catid){
$cat = Mage::getModel('catalog/category')->load($Catid);
$subSubCats = $cat->getChildren();
$arrSubSubCats = explode(',',$subSubCats);
array_push($categoryIdList,$arrSubSubCats); //Collect child category IDs
// Go another level down
// Another foreach loop for $arrSubSubCats
}
}
// Now we have all categoryIds in the tree.
// Get all products.
$collection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array('in' => $categoryIdList))
this is the code I am using, it returns a server error. I am not sure why or what to do for it to work. any help would be greatly appreciated.
<?php
//product = Mage::getModel('catalog/product');
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$product = new Mage_Catalog_Model_Product();
$product->setSku("ABC123");
$product->setName("Type 7 Widget");
$product->setDescription("This widget will give you years of trouble-free widgeting.");
$product->setShortDescription("High-end widget.");
$product->setPrice(70.50);
$product->setTypeId('simple');
$product->setAttributeSetId(9); // need to look this up
$product->setCategoryIds("20,24"); // need to look these up
$product->setWeight(1.0);
$product->setTaxClassId(2); // taxable goods
$product->setVisibility(4); // catalog, search
$product->setStatus(1); // enabled
// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
$product->save();
// for stock
$stockData = $product->getStockData();
$stockData['qty'] = 10;
$stockData['is_in_stock'] = 1;
$stockData['manage_stock'] = 1;
$stockData['use_config_manage_stock'] = 0;
$product->setStockData($stockData);
?>
With Magento we can have several different ways to add products to the catalog. The way you are try to achieve need a few changes to work well. Please keep in mind that you should use as much of the Magento's functionalities, such as models, configs and so on.
A good approach for what you are looking for would be:
<?php
...
$product = Mage::getModel('catalog/product');
$product->setSku("SKUPROD123");
$product->setName("Name of The Product");
$product->setDescription("Some description of the product.");
$product->setShortDescription("Short one.");
$product->setPrice(299.50);
$product->setTypeId('simple');
$product->setAttributeSetId(9); // need to look this up
$product->setCategoryIds("20,24"); // need to look these up
$product->setWeight(1.8);
$product->setTaxClassId(2); // taxable goods
$product->setVisibility(4); // sets visibility as 'catalog, search'
$product->setStatus(1); // enabled
// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
$product->save();
I hope it helps
Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>
I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}