Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Adam Duffield
Adam Duffield
30,494 Points

How to display only the products that can be divided by three in the woocommerce shop?

Hi All,

I'm trying to display only products dividable by three in one column. e.g. Products 1, 4, 7, 10 and 13. I'm using woocommerce but having difficulty finding the function I need to manipulate to make this happen. I'm quite familiar with PHP i'm just not overly that familiar with where to find what I'm after in thewoocommerce file structure.

If anyone could point me in the right direction or help me with an answer I would really appriciate it!

For anyone asking why I want them divisable by three, I'm making a masonary grid for a photography company with 3 columns that will display the shop as a gallery without the add to cart, price e.c.t.

Regards,

Adam

1 Answer

Erik McClintock
Erik McClintock
45,783 Points

Adam,

Have you tried using the modulus operator? To check divisibility in PHP (and many other programming languages), we have access to the arithmetic operator known as "modulus". The modulus operator ( % ) divides "a" by "b", and returns the result. Thus, all you need to do is check if a divided by b is equal to zero, where "b" is the number you want to divide by (in this case, 3), and if that equates to true, then whatever "a" represented is indeed divisible by "b" (in this case, 3).

Let's take a look at an example:

<?php
$myVar = 9;
$myOtherVar = 10;

$remainder = $myVar % 3;
$otherRemainder = $myOtherVar % 3;

echo "Remainder: " . $remainder;
echo "Other remainder: " . $otherRemainder;

If you ran that, you would see that "Remainder: 0", and "Other remainder: 1". This is just to illustrate how the % ("modulus") operator works. It returns the remainder of "a" divided by "b". So in your code, you should be able to just perform a conditional check on whatever item(s) you want to verify divisibility on, and run the appropriate code should the modulus check return 0.

<?php
$thingToCheck = 15;

if( $thingToCheck % 3 == 0 ) {
    // success, whatever is stored in $thingToCheck is divisible by three, so run whatever code you need to run on those items here!
} else {
    // looks like whatever is stored in $thingToCheck is NOT divisible by three, so run whatever other code you need to for those items
}

Hope this helps!

Erik