Is it possible to create a shortcode that will query a post based on taxonomies?

I am working on a site that will be listing a few hundred products and we wanted to be able to quickly/easily show specific products on a page based on taxonomies. I have been doing some research and thought I was on the right track.

First, I found this article on digwp.com which I thought was going to work great. I can not get it to pull the posts based on taxonomy though – just post_type. The Post Type is “Used Items” and I created a taxonomy named Color where one of the slugs was Red.

Read More
[loop the_query="post_type=used-items&color=red&ord=ASC"]

I also found this plugin for doing a query by shortcode, but same situation with it not pulling by taxonomy.

My question
Does anyone know what I can do to pull posts based on post type/taxonomies (would be using multiple each query) directly from a WordPress page. We want to be able to quickly query products without having to program the query into a page template for each possible option.

Related posts

Leave a Reply

1 comment

  1. here is a simple shortcode that can handle taxonomies, post types and any other parameter that WP_Query takes:

    add_shortcode('posts','posts_shortcode_handler');
    function posts_shortcode_handler($atts, $content){
        extract(shortcode_atts(array(
            'posts_per_page' => '5',
        ), $atts));
    
        global $post;
        $temp = $post;
    
        $posts = new WP_Query($atts);
        $retVal = '';
        if ($posts->have_posts()){
            while ($posts->have_posts()){
                $posts->the_post();
    
                // these arguments will be available from inside $content
                $parameters = array(
                    'PERMALINK' => get_permalink(),
                    'TITLE' => get_the_title(),
                    'CONTENT' => get_the_content(),
                    'CATEGORIES' => get_the_category_list(', '),
                    'THUMBNAIL' => get_the_post_thumbnail()
                );
    
                $finds = $replaces = array();
                foreach($parameters as $find => $replace){
                    $finds[] = '{'.$find.'}';
                    $replaces[] = $replace;
                }
                $retVal .= str_replace($finds, $replaces, $content);
    
            }
        }
        wp_reset_query();
        $post = $temp;
        return $retVal;
    }
    

    usage:

    [posts post_type="page" posts_per_page=5 taxonomy_name="taxonomy_term"]
        <h5><a href="{PERMALINK}">{TITLE}</a></h5>
        <div>{THUMBNAIL} <br />{CONTENT}</div>
    [/posts]
    

    replace page with your post type name, taxonomy_name with your taxonomy name and taxonomy_term with the taxonomy term