Jump to content

Changing Latest Products to Random from just 1 category


Recommended Posts

As the title states I'm trying to switch the latest products on the home page to show a group of random products from just one category.  This isn't really a skin question I guess but...

I see the piece of code on line 96 in classes/cubecart.class.php

$latestProducts = $GLOBALS['db']->select('CubeCart_inventory', false, $where, array('date_added' => 'DESC', 'product_id' => 'DESC'), (int)$GLOBALS['config']->get('config', 'catalogue_latest_products_count'));

And if I jump to classes/catalogue.class.php line 617 I see this code

if (($result = $GLOBALS['db']->query('SELECT I.product_id FROM `'.$GLOBALS['config']->get('config', 'dbprefix').'CubeCart_category_index` as I,  `'.$GLOBALS['config']->get('config', 'dbprefix').'CubeCart_inventory` as INV WHERE I.cat_id = '.$category_id.' AND I.product_id = INV.product_id AND INV.status = 1'.$where2)) !== false) {

That would pull up all the products for a specified category. How would I go about making this work? I have tried and tried but with no luck. Say I wanted to use $category_id = 16

Bill

Link to comment
Share on other sites

We can start by focusing on the Latest Products code. You might notice that for each item flagged as a "Latest Product" ('featured'), CubeCart requests all the categories associated with it (line 99). Then, foreach of those categories, if any one is enabled ('status'), then CubeCart will include that product in the final list.

What we can do is to add to the test of any category enabled and make sure that the category is a specific category. So, make this edit:

From:
if ($data['status'] == 1) {

To:
if ($data['status'] == 1 && $data['cat_id'] == 16) {

We can assume Category 16 is enabled, so there may be no reason to keep the part about the 'status' but it doesn't hurt anything either.

The next step is to use the final array of items, $products on line 134, and randomly select X number from Y array.

PHP has a function, array_rand() - which is not perfect but should suffice, that will give us an array of key indexes randomly chosen from the source array.

So, let's rebuild $products by using this function.

From:
$GLOBALS['smarty']->assign('LATEST_PRODUCTS', $products);

To:
$lp_rand_keys = array_rand($products, 3); // Make sure there are 3 or more 'featured' products
foreach ($lp_rand_keys as $rand_key) $lp_rand_products[$rand_key] = $products[$rand_key];
$products = $lp_rand_products;
$GLOBALS['smarty']->assign('LATEST_PRODUCTS', $products);

Another solution would be to shuffle() the array and then array_slice() X elements of the result.

Link to comment
Share on other sites

Thank you so much. I just learned a whole lot with that info so thanks for that. I was able to make that work but I had to remove the 'where' statement from line 96.

My next question, is this too big a load on the server? Is it randomizing the whole inventory table or just the products in cat 16? I have 1,300 products and my host (hostgator) is a real pain about server load. I know rand() is sort of frowned upon so how would I use shuffle as you mentioned?

Bill

 

Link to comment
Share on other sites

OK, follow up question. I wanted to add a couple of more boxes on the home page with the most popular items in a category (other than the one already used above)

I copied this code, placed in between

$GLOBALS['smarty']->assign('LATEST_PRODUCTS', $products);

and

foreach ($GLOBALS['hooks']->load('class.cubecart.display_homepage') as $hook) include $hook;

I called it $popProducts with a hook of {POP_PRODUCTS} and added that to the homepage template. That worked, sort of... BUT all I get is photos from the correct category with no prices and it says "info" and out of stock. The links are correct. I relabeled everything that was a variable with a 2 at the end ($Products2, $category_status2, etc) hoping that was differentiate it from the latest product section but that just made it so I did not get duplicate products from the section above.

Where am I going wrong?

Link to comment
Share on other sites

There is no difference in the amount of products returned from the database in the initial query for 'featured' items. Other than now you may need to flag more products than what was originally flagged.

Also, since this query is not expected to return any different set of records than what a query performed a few minutes ago returned, the query and the results are "cached". Thus, no more hitting the database using this query.

The array_rand() function is working on a subset of the returned recordset from the database/cache. The subset contains only the remaining records from the recordset where the product has an association with Category 16. To play with some estimated numbers:

1600 total inventory, of which 100 are flagged as 'Latest Products'.

But you said you discarded the original $where. Which means -- and I misread the post subject -- you are abandoning 'featured' products and are querying strictly for a given category. So,

1600 inventory of which 300 are in Category 16
Of that 300, array_rand() is performed to return 12 random key_indexes. This is not a 'heavy load' function.

So, to answer your question, no, there will not be "too big of a load" on the server.

As for $popProducts, please put the actual statements you added in your reply.

Link to comment
Share on other sites

Also, the initial query for 'featured' products is limited to a count set in admin, Store Settings: "Number of Latest Products to display".

Also, by removing the initial $where variable, 'featured' is no longer a query condition. Thus, ALL of your inventory is being returned in the recordset. But then, that recordset is cached.

 

Link to comment
Share on other sites

OK, thanks for the info.

Here is the code I have for the new pop products. I have been playing with it since I posted last and found if I took out all the 2's I added it still works the same. Simplfies things a bit I guess as well. This is the code in classes/cubecart.class.php

  {  $products = array();

               /* $where = $GLOBALS['catalogue']->outOfStockWhere(array('status' => '1', 'featured' => '1')); */

                if ($GLOBALS['config']->get('config', 'catalogue_latest_products')) {
                        $latestProducts = $GLOBALS['db']->select('CubeCart_inventory', false, (int)$GLOBALS['config']->get('config', 'catalogue_latest_products_count'));
                        if ($latestProducts) {
                                foreach ($latestProducts as $product) {
                                        $category_data = $GLOBALS['catalogue']->getCategoryStatusByProductID($product['product_id']);
                                        $category_status = false;
                                        if (is_array($category_data)) {
                                                foreach ($category_data as $trash => $data) {
                                                        if ($data['status'] == 1 && $data['cat_id'] == 16) {
                                                                $category_status = true;
                                                        }
                                                }
                                        }
                                        if (!$category_status) {
                                                continue;
                                        }
                                        // Product Translation
                                        $GLOBALS['language']->translateProduct($product);
                                        $product['image'] = $GLOBALS['gui']->getProductImage($product['product_id'], 'small');
                                        $product['ctrl_sale'] = (!$GLOBALS['tax']->salePrice($product['price'], $product['sale_price']) || !$GLOBALS['config']->get('config', 'catalogue_sale_mode')) ? false : true;

                                        $GLOBALS['catalogue']->getProductPrice($product);
                                        $sale = $GLOBALS['tax']->salePrice($product['price'], $product['sale_price']);
                                        $product['price_unformatted'] = $product['price'];
                                        $product['sale_price_unformatted'] = ($sale) ? $product['sale_price'] : null;
                                        $product['price'] = $GLOBALS['tax']->priceFormat($product['price']);
                                        $product['sale_price'] = ($sale) ? $GLOBALS['tax']->priceFormat($product['sale_price']) : null;

                                        $product['ctrl_stock'] = (!$product['use_stock_level'] || $GLOBALS['config']->get('config', 'basket_out_of_stock_purchase') || ($product['use_stock_level'] && $GLOBALS['catalogue']->getProductStock($product['product_id'], null, true))) ? true : false;
                                        $product['url'] = $GLOBALS['seo']->buildURL('prod', $product['product_id'], '&');

                                        $GLOBALS['smarty']->assign('CTRL_REVIEW', (bool)$GLOBALS['config']->get('config', 'enable_reviews'));
                                        if (($product_review = $GLOBALS['db']->select('CubeCart_reviews', 'SUM(`rating`) AS Score, COUNT(`id`) as Count', array('approved' => 1, 'product_id' => $product['product_id']))) !== false) {
                                                if ($product_review[0]['Score'] !== "") {
                                                        $product['review_score'] = round($product_review[0]['Score']/$product_review[0]['Count'], 1);
                                                }
                                        }
                                        $products[] = $product;
                                }
                                $lp_rand_keys = array_rand($products, 4);
                                // Make sure there are 3 or more 'featured' products
                                foreach ($lp_rand_keys as $rand_key) $lp_rand_products[$rand_key] = $products[$rand_key];
                                $products = $lp_rand_products;
                                $GLOBALS['smarty']->assign('LATEST_PRODUCTS', $products);

                        }
                }
                }
                /* end latest products */
                
                /* Start Popular Products*/
                
            {    $products = array();

              //  $where = $GLOBALS['catalogue']->outOfStockWhere(array('status' => '1', 'featured' => '1'));

                if ($GLOBALS['config']->get('config', 'catalogue_latest_products')) {
                        $popProducts = $GLOBALS['db']->select('CubeCart_inventory', false, (int)$GLOBALS['config']->get('config', 'catalogue_latest_products_count'));
                        if ($popProducts) {
                                foreach ($popProducts as $product) {
                                        $category_data = $GLOBALS['catalogue']->getCategoryStatusByProductID($product['product_id']);
                                        $category_status = false;
                                        if (is_array($category_data)) {
                                                foreach ($category_data as $trash => $data) {
                                                        if ($data['status'] == 1  && $data['cat_id'] == 67) {
                                                                $category_status = true;
                                                        }
                                                }
                                        }
                                        if (!$category_status) {
                                                continue;
                                        }
                                        // Product Translation
                                        $GLOBALS['language']->translateProduct($product);
                                        $product['image'] = $GLOBALS['gui']->getProductImage($product['product_id'], 'small');
                                        $product['ctrl_sale'] = (!$GLOBALS['tax']->salePrice($product['price'], $product['sale_price']) || !$GLOBALS['config']->get('config', 'catalogue_sale_mode')) ? false : true;

                                        $GLOBALS['catalogue']->getProductPrice($product);
                                        $sale = $GLOBALS['tax']->salePrice($product['price'], $product['sale_price']);
                                        $product['price_unformatted'] = $product['price'];
                                        $product['sale_price_unformatted'] = ($sale) ? $product['sale_price'] : null;
                                        $product['price'] = $GLOBALS['tax']->priceFormat($product['price']);
                                        $product['sale_price'] = ($sale2) ? $GLOBALS['tax']->priceFormat($product['sale_price']) : null;

                                        $product['ctrl_stock'] = (!$product['use_stock_level'] || $GLOBALS['config']->get('config', 'basket_out_of_stock_purchase') || ($product['use_stock_level'] && $GLOBALS['catalogue']->getProductStock($product['product_id'], null, true))) ? true : false;
                                        $product['url'] = $GLOBALS['seo']->buildURL('prod', $product['product_id'], '&');

                                        $GLOBALS['smarty']->assign('CTRL_REVIEW', (bool)$GLOBALS['config']->get('config', 'enable_reviews'));
                                        if (($product_review = $GLOBALS['db']->select('CubeCart_reviews', 'SUM(`rating`) AS Score, COUNT(`id`) as Count', array('approved' => 1, 'product_id' => $product['product_id']))) !== false) {
                                                if ($product_review[0]['Score'] !== "") {
                                                        $product['review_score'] = round($product_review[0]['Score']/$product_review[0]['Count'], 1);
                                                }
                                        }
                                        $products[] = $product;
                                }
                                $pp_rand_keys = array_rand($products, 4);
                                // Make sure there are 3 or more 'featured' products
                                foreach ($pp_rand_keys as $rand_key) $pp_rand_products[$rand_key] = $products[$rand_key];
                                $products = $pp_rand_products;
                                $GLOBALS['smarty']->assign('POP_PRODUCTS', $products);
                                }
                        }
                }

                foreach ($GLOBALS['hooks']->load('class.cubecart.display_homepage') as $hook) include $hook;
                $content = $GLOBALS['smarty']->fetch('templates/content.homepage.php');
                $GLOBALS['smarty']->assign('PAGE_CONTENT', $content);
        }

and here is what was added to the home page template ( it's the e-scaler skin )

 <h2>Most Popular</h2>

        <div class="product-list">

                {foreach from=$POP_PRODUCTS item=product}
                <div class="product">
                        <form action="{$VAL_SELF}" method="post" class="addForm" id="P{$product.product_id}">
                                <p class="image">
                                        <a href="{$product.url}" title="{$product.name}">
                                                <img src="{$product.image}" alt="{$product.name}" />
                                        </a>
                                        {if $product.review_score && $CTRL_REVIEW}
                                        <span class="rating">
                                                {for $i = 1; $i <= 5; $i++}
                                                {if $product.review_score >= $i}
                                                <span class="icon icon-star3"></span>
                                                {elseif $product.review_score > ($i - 1) && $product.review_score < $i}
                                                <span class="icon icon-star2"></span>
                                                {else}
                                                <span class="icon icon-star"></span>
                                                {/if}
                                                {/for}
                                        </span>
                                        {/if}
                                </p>
                                <div class="info">
                                        <p class="title"><a href="{$product.url}" title="{$product.name}">{$product.name|truncate:40:"&hellip;"}</a></p>

                                        {if $product.ctrl_sale}
                                        <p class="price"><span class="old_price_cat">{$product.price}</span> <span class="sale_price_cat">{$product.sale_price}</span></p>
                                        {else}
                                        <p class="price">{$product.price}</p>
                                        {/if}
                                        <p class="actions">
                                                <a href="{$product.url}" title="{$product.name}">{$LANG.common.info}</a>
                                                <input type="hidden" name="add" value="{$product.product_id}" />
                                                {if $product.ctrl_stock && !$CATALOGUE_MODE}
                                                <button type="submit" class="button_add_basket" onclick="$.add2cart('P{$product.product_id}')">{$LANG.catalogue.buy_now}</button>
                                                {elseif !$CATALOGUE_MODE}
                                                <button type="submit" class="button_add_basket disabled" disabled="disabled">{$LANG.catalogue.out_of_stock_short}</button>
                                                {/if}
                                        </p>
                                </div>
                        </form>
                </div>
                {/foreach}
        </div>
</div>

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...