How To Display WooCommerce Featured Products Without a Shortcode
WooCommerce comes with a number of useful shortcodes to allow quick insertion of WooCommerce related content within posts and pages. One of these shortcodes can be used to display featured products like so:
[featured_products per_page="12" columns="4"]
The above would output the featured products in a grid.
This is great, however, what if we want go one step further and have more control over the products shown, or if we’re already using the shortcode elsewhere on our site?
Specifying Featured Products in WordPress
First, let’s take a look at how we set featured products. When logged into WordPress simply navigate to the ‘Products’ section and you’ll notice that there is a column containing stars.
If a star in this column is black it means it is featured. To add or remove a product to the list of featured products you simply click the star.
Obtaining The Featured Products
We can obtain the products in question much like we can obtain posts normally by using the WP_Query class like so:
$args = array( 'post_type' => 'product', 'meta_key' => '_featured', 'meta_value' => 'yes', 'posts_per_page' => 1 ); $featured_query = new WP_Query( $args ); if ($featured_query->have_posts()) : while ($featured_query->have_posts()) : $featured_query->the_post(); $product = get_product( $featured_query->post->ID ); // Output product information here endwhile; endif; wp_reset_query(); // Remember to reset
The first thing that is happening above is to set the arguments for the query we want to run. You’ll notice we are only getting posts where the post_type is ‘product’, and where the meta_value, ‘_featured’, is set to ‘yes’. We’ve also specified that we only want to get one featured product so simply increase this number if you want to obtain more.
The next part is pretty standard in terms of looping through posts. The only other important line is:
$product = get_product( $featured_query->post->ID );
By doing this we can then access all the product related information, for example SKU, that isn’t available in a normal post object.