I am trying to create a custom shortcode for WooCommerce, I want to display featured products from a specific catagory at the end of a post.
There is a standard shortcode:
[featured_products per_page="12" columns="4" orderby="date" order="desc"]
I want to add catagory to this, so the new shortcode will be:
[featured_category_products category="13" per_page="4" columns="4" orderby="date" order="desc"]
To get it work it’s officiously necessary to create a function for it, so I found the class-wc-shortcodes.php file with all the default shortcodes.
I add a new function based on the default featured product:
public function featured_category_products( $atts ) {
global $woocommerce_loop;
extract(shortcode_atts(array(
'category' => '',
'per_page' => '4',
'columns' => '4',
'orderby' => 'date',
'order' => 'desc'
), $atts));
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $per_page,
'orderby' => $orderby,
'order' => $order,
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
),
array(
'key' => '_featured',
'value' => 'yes'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr($category) ),
'field' => 'slug',
'operator' => 'IN'
)
)
);
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
I added the category variable extraction (and checked if it worked) and added tax-query part (found it from another function that show product based on categories). So I thought this should work, but off course not. I don’t get any results nor a error.
Anybody an idea how the get this to work?
If you’re only looking for one product category, use
'terms' => $category
. Or you can do anexplode()
to split a comma separated string into an array.See Wp Query : Taxonomy Parameters.
Other notes:
Don’t touch the plugin files, your changes will be lost in the next update.
Create your own plugin.
Copy the function you created to it.
Register the shortcode to make it available (using your custom function as callback):