0

I have created a shortcode to show custom single custom post type to another post. Here is the code:

function clients_shortcode(){

    $output = '';
    //Attributes
    $defaults = array(
        'c_name'        => '',
        'c_session' => ''
    );

    $atts = shortcode_atts($defaults, $atts);
    $name = $atts['c_name'];
    $session = $atts['c_session'];

    $args = array(

        'post_type'     => 'client',
        'meta_query'    => array(
            'relation'      => 'AND',
            array(
                'key'       => 'client_name',
                'value'     => $name,
                'compare'   => '='  
            ),
            array(
                'key'       => 'session_number',
                'value'     => $session,
                'compare'   => '='
            )
        )

    );

    $client_sess = new WP_Query ($args);

    if($client_sess->have_posts()): while($client_sess->have_posts()): $client_sess -> the_post();

    $output .= '<h1>' . get_the_title() . '</h1>';
    $output .= '<div>' . get_field('session_hypnosis') . '</div>';
    $output .= '<div>' . get_field('session_video') . '</div>';

    endwhile;
    endif;
    wp_reset_query();

    return $output;
}

add_shortcode('clients', 'clients_shortcode');

The output is showing nothing but if I change the code to static like this

$args = array(
        'post_type'     => 'client',
        'meta_query'    => array(
            'relation'      => 'AND',
            array(
                'key'       => 'client_name',
                'value'     => 'Nayan',
                'compare'   => '='  
            ),
            array(
                'key'       => 'session_number',
                'value'     => 1,
                'compare'   => '='
            )
        )

    );

The shortcode then show the post for client Nayan and session 1. But when I am passing arguments to the shortcode, it is not working.

NOTE: I am using ACF to generate custom fields.

Thanks In Advance

1 Answer 1

0

You haven't defined $atts, so your function isn't receiving any of the attributes passed by the user. This isn't sufficient:

$atts = shortcode_atts($defaults, $atts);

That just combines $atts and $defaults into $atts, but the original $atts hasn't been defined. You need to accept $atts as the first argument passed to your function:

function clients_shortcode( $atts ) {
1
  • Oh silly me. I missed that. Thank you so much. Commented Jan 22, 2020 at 7:11

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.