2
votes

i would like to create a shortcode which will display a loop for CPT = testimonials. I've prepared such code:

function testimonials_loop_shortcode() {
        $args = array(
            'post_type' => 'testimonials',
            'post_status' => 'publish',
        );

        $my_query = null;
        $my_query = new WP_query($args);
        while ($my_query->have_posts()) : $my_query->the_post();

        $custom = get_post_custom( get_the_ID() );

        ?><p><?php the_title();?></p><?php
        ?><p>the_content();</p><?php

    wp_reset_postdata();
    else :
    _e( 'Sorry, no posts matched your criteria.' );
    endif;
}

add_shortcode( 'testimonials_loop', 'testimonials_loop_shortcode' );

It's prepared to be pasted inside functions.php. But the code breaks the website / error 500. what im doing wrong?

1

1 Answers

1
votes

I reviewed your code, there are many fixes which has to be done. Here is the list below of fixes:

  1. You have not opened the if condition, but closed it with endif.
  2. You have opend while loop, but didn't closed it.
  3. You have not placed <?php ?> tag around the_content() function.

Therefore, i have modified your code, please find the updated code below:

function testimonials_loop_shortcode() {
    $args = array(
        'post_type' => 'testimonials',
        'post_status' => 'publish',
    );

    $my_query = null;
    $my_query = new WP_query($args);
    if($my_query->have_posts()):
        while($my_query->have_posts()) : $my_query->the_post();
            $custom = get_post_custom( get_the_ID() );
            echo "<p>".get_the_title()."</p>";
            echo "<p>".get_the_content()."</p>";
        endwhile;
        wp_reset_postdata();
    else :
    _e( 'Sorry, no posts matched your criteria.' );
    endif;
}

add_shortcode( 'testimonials_loop', 'testimonials_loop_shortcode' );

Hope, it may be helpful to you.

Please feel free, if you have any query. Thanks