I have created a custom post type with shortcode so I can add dynamic attributes from the shortcode

function myCPT($query,  $attr) {
    $option = shortcode_atts(array('cat' => ''), $attr); 

    $query = new WP_query(array(
         'post_type' => 'myposttype',
         'category_name' =>   $option['cat']
    if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
    $output .=  '<h2>' . get_the_title() . '</h2><div>' . 
                '<div>' . get_the_post_thumbnail() . '</div></div>' . 
                '<p>' . get_the_content() .  '</p><p>' . 
                '<a>DONATE NOW</a></p></div></div>';
    return $output;
add_shortcode('myshortcode', 'myCPT');

I'm calling it using [myshortcode cat="mycategory"]

I was expecting that cat="mycategory" should reflect on the 'category_name' => $option['cat'] from the custom query

But it is not working, maybe I'm missing something.

1 Answer 1


The arguments for your myCPT() function are incorrect. Callbacks used for add_shortcode() received two arguments, in this order:

  1. An array that contains the parameters used with the shortcode.
  2. The that is between the opening and closing shortcode, if supported.

You code is assigning the attributes to $query (and then overwriting them), and trying to get the attributes from the shortcode content.

So you code needs to be:

function myCPT( $atts, $content ) {
    $option = shortcode_atts( array( 'cat' => '' ), $atts ); // This needs to be the same as the first argument. 

    $query = new WP_query( array(
        'post_type'     => 'myposttype',
        'category_name' => $option['cat']
    ) );

    // etc.
add_shortcode( 'myshortcode', 'myCPT' );
  • thank you! works like a charm Apr 14, 2020 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.