How do we build a Shortcode for Wordpress?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom

How do we build a Shortcode for Wordpress?

Post by simonmlewis »

Code: Select all

// Note: products shortcode docs
// In order for the snippet to work, you must add the parameter orderby = "stock" to the shortcode
// You can add more parameters to it of course e.g. limit, paginate, etc. It's all in the docs
add_filter('woocommerce_shortcode_products_query', 'bbloomer_sort_by_stock_status_shortcode', 999, 3);
function bbloomer_sort_by_stock_status_shortcode( $args, $atts, $type ) {
    if ( $atts['orderby'] == "stock" ) {
        $args['orderby']  = array( 'meta_value' => 'ASC' );
        $args['meta_key'] = array('_stock_status';
    return $args;
This is a function we found to add 'stock' to the Shortcode "orderby".
Trouble is, we want it to sort by Stock then by Title.

So the page ends up showing it in Alpha order, but with all the 'in stock' coming first.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Forum Regular
Posts: 574
Joined: Fri Sep 05, 2008 3:34 pm
Location: Victoria, BC

Re: How do we build a Shortcode for Wordpress?

Post by Vegan »

you might want to talk to the people with woocommerce who might be able to help with their code base
Hardcore Games™ Legendary is the Only Way to Play™
My site is powered by LAMP
Post Reply