Create a shortcode to display custom post types with a specific taxonomy

The question:

I created a page template to list all products of a specific product line.
Now I want to list all posts from this custom post type (products) based on the taxonomy described in the shortcode for each page.

Example:

Page “List of all Prime products”

[products line=”prime”]

I tried this code:

function shortcode_mostra_produtos ( $atts ) {
  $atts = shortcode_atts( array(
    'default' => ''
  ), $atts );
    $terms = get_terms('linhas');
    wp_reset_query();
    $args = array('post_type' => 'produtos',
      'tax_query' => array(
        array(
          'taxonomy' => 'linhas',
          'field' => 'slug',
          'terms' => $atts,
        ),
      ),
     );
     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        while($loop->have_posts()) : $loop->the_post();
            echo ' "'.get_the_title().'" ';
        endwhile;
     }
}
add_shortcode( 'produtos','shortcode_mostra_produtos' );

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

First off, it’s always good to register shortcode during init versus just in your general functions.php file. At the very least add_shortcode() should be in init. Anyway, let’s begin!

Whenever you use add_shortcode() the first parameter is going to be the name of the shortcode and the 2nd will be the callback function. This means that:

[products line="prime"]

Should be instead:

[produtos line="prime"]

So far we have this:

/**
 * Register all shortcodes
 *
 * @return null
 */
function register_shortcodes() {
    add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );

/**
 * Produtos Shortcode Callback
 * - [produtos]
 * 
 * @param Array $atts
 *
 * @return string
 */
function shortcode_mostra_produtos( $atts ) {
    /** Our outline will go here
}

Let’s take a look at processing attributes. The way shortcode_atts() works is that it will try to match attributes passed to the shortcode with attributes in the passed array, left side being the key and the right side being the defaults. So we need to change defaults to line instead – if we want to default to a category, this would be the place:

$atts = shortcode_atts( array(
    'line' => ''
), $atts );

IF the user adds a attribute to the shortcode line="test" then our array index line will hold test:

echo $atts['line']; // Prints 'test'

All other attributes will be ignored unless we add them to the shortcode_atts() array. Finally it’s just the WP_Query and printing what you need:

/**
 * Register all shortcodes
 *
 * @return null
 */
function register_shortcodes() {
    add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );

/**
 * Produtos Shortcode Callback
 * 
 * @param Array $atts
 *
 * @return string
 */
function shortcode_mostra_produtos( $atts ) {
    global $wp_query,
        $post;

    $atts = shortcode_atts( array(
        'line' => ''
    ), $atts );

    $loop = new WP_Query( array(
        'posts_per_page'    => 200,
        'post_type'         => 'produtos',
        'orderby'           => 'menu_order title',
        'order'             => 'ASC',
        'tax_query'         => array( array(
            'taxonomy'  => 'linhas',
            'field'     => 'slug',
            'terms'     => array( sanitize_title( $atts['line'] ) )
        ) )
    ) );

    if( ! $loop->have_posts() ) {
        return false;
    }

    while( $loop->have_posts() ) {
        $loop->the_post();
        echo the_title();
    }

    wp_reset_postdata();
}

Method 2

    add_shortcode( 'product-list','bpo_product_list' );
function bpo_product_list ( $atts ) {
  $atts = shortcode_atts( array(
    'category' => ''
  ), $atts );
    $terms = get_terms('product_category');
    wp_reset_query();
    $args = array('post_type' => 'product',
      'tax_query' => array(
        array(
          'taxonomy' => 'product_category',
          'field' => 'slug',
          'terms' => $atts,
        ),
      ),
     );
     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        while($loop->have_posts()) : $loop->the_post();
            echo ' "'.get_the_title().'" ';
        endwhile;
     }

     else {
            echo  'Sorry, no posts were found';
          }
}

In above code, I have created product CPT and product_category taxonomy for product CPT.

[product-list category=”shirts”]

The above code is perfectly works!

Method 3

**Try this **

function shortcode_bws_quiz_maker($id)
{
  if($id!='')
  {
    $post_id=$id[0];
    $html='';
    global $wpdb;
   $args=array('post_type'=>'post_type','p'=>$post_id);
   $wp_posts=new WP_Query($args);
   $posts=$wp_posts->posts;
  $html.="What you to get write here";
    return $html;

  }
  else
  {
    return 'Please enter correct shortcode';    
  }

}
add_shortcode('bws_quiz_maker','shortcode_bws_quiz_maker');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment