Here is what I am trying to accomplish: turn off a True/False Advanced Custom Fields(ACF) option on a post if the current date is on or past a selected date on the same post. Also after that code, turn off a Sample Lesson True/False option inside of the lessons attached to the current post.
At first, all I had was the update_sample_child_lessons function with an 'init' action (i.e.add_action( 'init', 'update_sample_child_lessons' );), but that seemed to only run when I clicked update on the post. It did work and everything switched over, but it only ran when I manually clicked Update on the post. So then I did a little research and found that a Cron job should do the trick if I want the code to run automatically without me having to click update, but for some reason I can't seem to get it to work.
So if you know of a way to accomplish what I am trying to do with the code below, or with other code that is completely different, any suggestions or help would be much appreciated.
//CRON JOB TO RUN EVERYDAY
function myprefix_custom_cron_schedule( $schedules ) {
$schedules['every_day'] = array(
'interval' => 86400, //24 HOURS IN SECONDS
'display' => __( 'Every 24 hours' ),
);
return $schedules;
}
add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );
if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {
wp_schedule_event( time(), 'every_day', 'myprefix_cron_hook' );
}
//AUTOMATICALLY ADJUSTS SAMPLE LESSON FREE OPTIONS AND FREE BANNER IF DATE IS PASSED
add_action( 'myprefix_cron_hook', 'update_sample_child_lessons' );
function update_sample_child_lessons() {
$allcourses = array(
'post_type' => 'sfwd-courses', //CUSTOM POST TYPE: COURSES
'posts_per_page' => -1 //QUERY ALL OF THEM
);
$query = new WP_Query($allcourses);
if ($query->have_posts()) {
global $post;
if ( ( in_array( $post->post_type, array( 'sfwd-courses' ), true ) )) { //ONLY DO ACTION IF ON CPT OF COURSES
while ($query->have_posts()) {
$query->the_post();
$course_id = learndash_get_course_id( $post->ID ); //GET THE COURSE ID
$free = get_field('display_free_lessons', $course_id); //GET THE FREE COURSE OPTION (TRUE/FALSE TICKER)
if (!empty($free)) { //ONLY DO REST OF CODE IF FREE OPTION IS TURNED ON
$freeDate = get_field('free_until', $course_id); //GET THE DATE FIELD THAT THE COURSE IS FREE UNTIL
$currentDate = date('Ymd'); //GET CURRENT DATE
$diff = strtotime($freeDate) - strtotime($currentDate); //GET THE DIFFERENCE BETWEEN THE TWO DATES
if ($diff <= 0) { //ONLY DO REST OF CODE IF DATE DIFFERENCE IS LESS THAN OR EQUAL TO ZERO
$value = '';
update_field('display_free_lessons', $value, $course_id); //UPDATES THE FREE OPTION FIELD TO FALSE(OR NOTHING)
//LESSON CODE
$lessons = array_slice(learndash_course_get_lessons($course_id), 1); //GET ALL THE LESSONS FROM THE COURSE EXCEPT FOR THE FIRST ONE
foreach ($lessons as $lesson) {
$lessonID = $lesson->ID; //GET THE LESSON ID
$lesson_meta = get_post_meta($lessonID); //GET THE METADATA FOR THE LESSON
if ( is_array( $lesson_meta ) ) {
foreach ( $lesson_meta as $meta_key => $meta_value ) {
if ( '_sfwd-lessons' === $meta_key ) {
$lesson_settings = maybe_unserialize( $meta_value[0] ); //SOME OF THE ARRAYS ARE SERIALIZED, SO UNSERIALIZE IF NEEDED
if ( isset( $lesson_settings['sfwd-lessons_sample_lesson'] ) ) {
$lesson_settings['sfwd-lessons_sample_lesson'] = ''; //TURN OFF THE SAMPLE LESSON OPTION ON THE LESSONS
}
update_post_meta( $lessonID, $meta_key, $lesson_settings );
}
}
}
} //END FOREACH
} //END IF DIFF IS 0
wp_reset_postdata();
}
}
}
}
}
Thanks for the comment #Luke Chaffey, I was actually able to figure it out after finding I had my cron actions reversed. Below is the final code that I got working so that it runs every day at 12am:
//CRON JOB TO RUN EVERYDAY
function custom_cron_schedule( $schedules ) {
$schedules['every_day'] = array(
'interval' => 86400,
'display' => __( 'Every 24 hours' ),
);
return $schedules;
}
add_filter( 'cron_schedules', 'custom_cron_schedule' );
$ve = get_option('gmt_offset') > 0 ? '-' : '+';
if ( ! wp_next_scheduled('cron_sample_lesson' ) ) {
wp_schedule_event(strtotime('00:00 tomorrow ' . $ve .
absint(get_option('gmt_offset')) . ' HOURS'), 'daily','cron_sample_lesson' );
}
add_action('cron_sample_lesson', 'update_sample_child_lessons' );
function update_sample_child_lessons() {...
I am inserting data into database. It doesn't get inserted. If I do the same via raw SQL it works. Doesn't show any errors too.
$products = Context::getContext()->cart->getProducts();
foreach($products as $product){
$id_product = $product['id_product'];
$is_allowed = (bool) Db::getInstance()->execute("SELECT available_for_order FROM ps_product WHERE id_product=".$id_product); // is product availabe for order when stock is null or zero.
// $sql = 'INSERT INTO `cart_log` (`id_product`,`ids_product_attribute`,`stock`,`reference`,`available_for_order`,`created_at`)
// VALUES (' . $id_product. ', ' . $product['id_product_attribute'] . ',' . $product['stock_quantity'] . ', ' . $product['reference'] .','. $is_allowed .', NOW())';
// die($sql);
$data= array(
'id_product' => (string) $id_product,
'ids_product_attribute' =>(string) $product['id_product_attribute'],
'stock' =>(string) $product['stock_quantity'],
'reference' =>(string) $product['reference'],
'available_for_order' =>(int) $is_allowed,
'created_at' => 'NOW())'
);
echo "<pre>";
print_r($data);
echo "</pre>";
$result= Db::getInstance()->insert('cart_log',$data);
}
try replace :
$is_allowed = (bool) Db::getInstance()->execute("SELECT available_for_order FROM ps_product WHERE id_product=".$id_product); // is product availabe for order when stock is null or zero.
by
$is_allowed = (bool) Db::getInstance()->getValue("SELECT available_for_order FROM ps_product WHERE id_product=".$id_product); // is product availabe for order when stock is null or zero.
execute() will return true or false if the request has correctly been executed, but not the request result. getValue() will return you request result.
There is also getRow() to get multiple elements of a same line, and executeS() to get multiple lines.
Regards
I want to disable the cod delivery feature in the order page of prestashop 1.6.3 when 100 /50 orders ( this will be a parameter) is completed per day.
How to disable this programmatically by finding out whether 100 cod is been completed .
I will modify the hookPayment() in cashondelivery module to do this :
public function hookPayment($params)
{
if (!$this->active)
return ;
global $smarty;
// Check if cart has product download
if ($this->hasProductDownload($params['cart']))
return false;
//Check whether the cod done exceeds the daily limit if yes dont display the cod option
$cod_limit = Configuration::get('PS_KITS_COD_DAILY_LIMIT');// number of cod
$sql = "select count(*) AS cod_count from ps_orders where module='cashondelivery' and date(date_add) = CURDATE() and ( current_state= 3 or current_state=4)";
if ($row = Db::getInstance()->getRow($sql)){
$cod_count = $row['cod_count'];
}
if ($cod_count >= $cod_limit){
return ;
}
$smarty->assign(array(
'this_path' => $this->_path, //keep for retro compat
'this_path_cod' => $this->_path,
'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/'
));
return $this->display(__FILE__, 'payment.tpl');
}
I am using a module that displays new added products in home page. I need to customize the module so that this list doesnt contain products sold. In other words, if a product is out of stock before the number of days it is condidered new is over, then do not show this product in list.
I can do it in view part by using {if $product.quantity < 0}{/if} but my goal is to perform it in controller. Here is my code:
function hookHome($params)
{
global $smarty, $cookie;
$nb = intval(Configuration::get('HOME_NEW_PRODUCTS_NBR'));
$rand = intval(Configuration::get('HOME_NEW_PRODUCTS_RANDOM'));
if ($rand == 1) {
$products = Product::getNewProducts(intval($cookie->id_lang), 0, $nb);
if ( $products )
{
shuffle($products);
array_slice($products, ($nb ? $nb : 10));
}
}
else
{
$products = Product::getNewProducts(intval($cookie->id_lang), NULL - 0, (intval($nb ? $nb : 4)), false, NULL, NULL);
}
$smarty->assign(array(
....
'products' => $products,
....
);
return $this->display(__FILE__, 'homenewproducts.tpl');
}
How can I override the class Product so that the method getNewProducts take into account excluding products out of stock?
Or at least, how can I remove from $products the products with quantity =0 using PHP?
Your help is appreciated.
Well, the solution I am using now is:
In product.php, I changed the sql queries in getNewProducts method inside of NewProductsController so that it takes into account if product is available in stock
I added AND 'quantity'!=0 in line 2062 and $sql->where('p.'quantity' != 0'); in line 2086 . Prestashop 1.6.0.6.
Of course, better override the classe Product.php than modifying it.
I hope it can help.
I've got a client database with a large range of stock items, which are being uploaded to Magento as simple products.
Now I need to group them up and assign them to configurable products with their size and colour being their configurable attributes.
The Magento API has a Product_Link class, with a promising looking method: catalogue-product-link.assign (link), but I can't for the life of me figure out what arguments I need to make it work with configurable products, providing this is how assign was meant to be used.
Well the notes here helped me get this running. So I thought I'd share with you the code to add a simple product to an existing Configurable Product.
This code assumes the simple product is a valid one to add, I'm not sure what would happen if it wasn't.
private function _attachProductToConfigurable( $_childProduct, $_configurableProduct ) {
$loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load( $_configurableProduct );
$ids = $_configurableProduct->getTypeInstance()->getUsedProductIds();
$newids = array();
foreach ( $ids as $id ) {
$newids[$id] = 1;
}
$newids[$_childProduct->getId()] = 1;
$loader->saveProducts( $_configurableProduct->getId(), array_keys( $newids ) );
}
The code from the accepted answer by Scimon does not work anymore in recent versions of magento (at least in 1.7). But fortunately, you need just a small fix to get it working again:
private function _attachProductToConfigurable( $_childProduct, $_configurableProduct ) {
$loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load( $_configurableProduct, $_configurableProduct->getId() );
$ids = $_configurableProduct->getTypeInstance()->getUsedProductIds();
$newids = array();
foreach ( $ids as $id ) {
$newids[$id] = 1;
}
$newids[$_childProduct->getId()] = 1;
//$loader->saveProducts( $_configurableProduct->getid(), array_keys( $newids ) );
$loader->saveProducts( $_configurableProduct, array_keys( $newids ) );
}
I'm working on doing this right now.
So far I've found these items helpful as references:
http://snippi.net/magento-programmatically-add-configurable-product-color-api
http://www.omnisubsole.com/blog/2009/07/01/configurable-products-in-magento.html
http://www.magentocommerce.com/boards/viewthread/6941/P30/
I'll post my code so far, and hopefully update it once it works..
// Set 'item_size' as the super attribute # choose your own attribute!
// this is the 'choose-able' field that differenciates products
$super_attributes=array( Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product','item_size')
->getData('attribute_id')
);
$product_collection=Mage::getModel('catalog/product')->getCollection();
// Fetch configurable orders
$product_collection->addFieldToFilter('type_id',Array('eq'=>"configurable"));
#$product_collection->addFieldToFilter('sku',Array('eq'=>"ASMCL000002"));
$product_collection->addAttributeToSelect('*');
$count=0;
foreach($product_collection as $product) {
$sku = $product->getSku();
echo "SKU: $sku\n";
$simple_children_collection = Mage::getModel('catalog/product')->getCollection();
$simple_children_collection->addAttributeToSelect('*');
$simple_children_collection->addFieldToFilter('sku',Array('like'=>$sku . "-%"));
echo "children: ";
foreach($simple_children_collection as $child) {
$child_sku = $child->getSku();
echo "$child_sku ";
#visiblity should be 'nowhere'
}
echo "\n";
if (!$product->getTypeInstance()->getUsedProductAttributeIds()) {
# This is a new product without the Configurable Attribue Ids set
$product->getTypeInstance()
->setUsedProductAttributeIds( $super_attributes );
//$product->setConfigurableAttributesData(array($_attributeData));
$product->setCanSaveConfigurableAttributes(true); # Not sure if this is needed.
$product->setConfigurableProductsData(''); # Use this to add child products.
}
$count++;
try {
$product->save();
$productId = $product->getId();
echo $product->getId() . ", $sku updated\n";
}
catch (Exception $e){
echo "$sku not added\n";
echo "exception:$e";
}
}
echo "\nCount is $count\n";
Okay, this uses 'item_size' as the attribute that differentiates the "simple" products. Also, this assumes that the "configurable" parent SKU is the root of the child SKU. For example, ABC001 is the parent while ABC001-SMALL and ABC001-LARGE are the simple children.
Hope that helps someone.
I this is an un-educated guess, but I think what your asking for can't be done with the existing API. You will have to write your own or just got directly to the DB.
Here is the hack-y way that I did this straight with PHP. There are three related tables. I was using color and size as my attributes.
My parent products (configurable) don't actually exist in my catalog. They are essentially model level and then the products are the SKU level.
So LIKE 'parentproductsku%' works out for the children.
$query1 = "SELECT * FROM mage_catalog_product_entity WHERE type_id= 'configurable'";
//Find the parent id
$statusMessage = "Ok, found a product with a confgurable attribute";
$result1 = $this->runQuery($query1, "query1", $statusMessage);
while ($row1 = mysql_fetch_assoc($result1)) { //entering the first loop where products are configurable
$this->parentId = $row1['entity_id'];
$this->parentSku = $row1['sku'];
echo "The SKU was $this->parentSku" . "<br />";
//insert these into the link table for association
$query2 = "SELECT * FROM mage_catalog_product_entity WHERE type_id= 'simple' AND sku LIKE '" . $this->parentSku . "%';";
// find the child ids that belong to the parent
$statusMessage = "Found some children for $this->parentSku";
$result2 = $this->runQuery($query2, "query2", $statusMessage);
while ($row2 = mysql_fetch_assoc($result2)) {//entering the second loop where SKU is like model sku
$this->childId = $row2['entity_id'];
$this->childSku = $row2['sku'];
echo "Now we're working with a child SKU $this->childSku" . "<br />";
//"REPLACE INTO catalog_product_super_attribute SET product_id='".$product->entity_id."', attribute_id='".$attribute->attribute_id."', position='".$position."'";
$query3 = "REPLACE INTO mage_catalog_product_super_attribute (product_id, attribute_id, position) VALUES ('" . $this->childId . "', '76', '0');";
$message3 = "Inserted attribute for color for ID $this->childId SKU $this->childSku";
$result3 = $this->runQuery($query3, "query3", $message3);
$query4 = "REPLACE INTO mage_catalog_product_super_attribute_label (product_super_attribute_id, store_id, use_default, value) VALUES (LAST_REPLACE_ID(), '0', '0', 'Color');";
$message4 = "Inserted attribute for Color SKU $this->childSku ID was $this->db->insert_id";
$result4 = $this->runQuery($query4, "query4", $message4);
$query5 = "REPLACE INTO mage_catalog_product_super_attribute (product_id, attribute_id, position) VALUES ('" . $this->childId . "', '529', '0');";
$message5 = "Inserted attribute for Product Size SKU $this->childSku";
$result5= $this->runQuery($query5, "query5", $message5);
$query6 = "REPLACE INTO mage_catalog_product_super_attribute_label (product_super_attribute_id, store_id, use_default, value) VALUES (LAST_REPLACE_ID(), '0', '0', 'Size');";
$message6 = "Inserted attribute for Size SKU $this->childSku ID was $this->db->insert_id";
$result6 = $this->runQuery($query6, "query6", $message6);
$query7 = "REPLACE INTO mage_catalog_product_super_link (product_id, parent_id) VALUES ('" . $this->childId . "', '" . $this->parentId . "');";
$message7 = "Inserted $this->childId and $this->parentId into the link table";
$result7 = $this->runQuery($query7, "query7", $message7);
$query8 = "REPLACE INTO mage_catalog_product_relation (parent_id, child_id) VALUES ('" . $this->parentId . "', '" . $this->childId . "');";
$message8 = "Inserted $this->childId and $this->parentId into the link table";
$result8 = $this->runQuery($query8, "query8", $message8);
} //end while row 2 the child ID
} //end while row 1 the parent id
Surprisingly, this works, if all your simple products share the same price:
$childProducts = $configurable->getTypeInstance(true)->getUsedProductIds($configurable);
// Don't add this product if it's already there
if(!in_array($child->getId(), $childProducts)) {
$childProducts[] = $child->getId();
}
$existingIds = $configurable->getTypeInstance(true)->getUsedProductAttributeIds($configurable);
$newAttributes = array();
foreach($configurable->getTypeInstance(true)->getSetAttributes($configurable) as $attribute) {
if(!in_array($attribute->getId(), $existingIds) && $configurable->getTypeInstance(true)->canUseAttribute($attribute)
&& $child->getAttributeText($attribute->getAttributeCode())) {
// Init configurable attribute
$configurableAtt = Mage::getModel('catalog/product_type_configurable_attribute')
->setProductAttribute($attribute);
// Add new attribute to array
$newAttributes[] = array(
'id' => $configurableAtt->getId(),
'label' => $configurableAtt->getLabel(),
'position' => $attribute->getPosition(),
'values' => $configurableAtt->getPrices() ? $configurable->getPrices() : array(),
'attribute_id' => $attribute->getId(),
'attribute_code' => $attribute->getAttributeCode(),
'frontend_label' => $attribute->getFrontend()->getLabel(),
);
}
}
if(!empty($newAttributes)) {
$configurable->setCanSaveConfigurableAttributes(true);
$configurable->setConfigurableAttributesData($newAttributes);
}
$configurable->setConfigurableProductsData(array_flip($childProducts));
$configurable->save();
#aeno's solution did not work for me, so I refined it a bit. This has been tested using a product instantiated via the Mage::getModel( 'catalog/product' )->load() method.
private function _attachProductToConfigurable( $childProduct, $configurableProduct )
{
$childIds = $configurableProduct->getTypeInstance()->getUsedProductIds();
$childIds[] = $childProduct->getId();
$childIds = array_unique( $childIds );
Mage::getResourceModel( 'catalog/product_type_configurable' )
->saveProducts( $configurableProduct, $childIds );
}