-3

I have created a shortcode for a custom post type query but when I add meta_query values to it, it throws an error:

Notice: Undefined variable: my in E:\xampp\htdocs\test\wp-content\themes\test-theme\functions.php on line 182

Here is the shortcode code:

function list_unit( $atts ) {
    $args = array( 
        'post_type' => 'unit',
        'posts_per_page' => -1,
        'post_parent' => '0',
        'orderby' => 'menu_order',
        'meta_query' => array(
                    array(
                        'key' => 'first_item_key', 
                        'value' => 'false',
                        'compare' => '='
                    )
        ),

    );

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) {
        $my = '<table>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $my .= '<tr><td><a href="'. get_the_permalink() .'">'; 
            $my .=  get_the_title() ; 
            $my .= '</a></td></tr>';
        }
        $my .= '</table>';
    } else {
        // no posts found
    }

    return $my;

}
add_shortcode( 'unit', 'list_unit' );

Not sure what's going wrong.

1

As the error states, your $my variable is not defined.

The reason behind it is that you only defines $my when $the_query->have_posts().

Adding

$my = 'No results found';

right after

$the_query = new WP_Query( $args );

would solve your problem. $my would then be redefined if results are found.

-2

try change

return $my;

to

if (isset($my)) return $my;

return 'Not found post';
  • You should edit the explanation into the answer. Comments are not meant for critical information. Please review the site's help center. – s_ha_dum Jan 14 '16 at 16:17

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