5

I have made a custom post type for my WordPress Theme and a page where the custom post types are displayed. But does anyone know how to make a shortcode that displays posts of a custom post type?

1
  • Possible yes, but what have tried yourself to solve this issue and where are you stuck Commented Apr 8, 2015 at 7:15

1 Answer 1

5

I think, basically your question is, how to query posts of a custom post type in a shortcode. You should have a look into the WP_Query section of WordPress: https://codex.wordpress.org/Class_Reference/WP_Query

In my example code I create a shortcode, which shows the title of the latest published posts of the type 'my-custom-post-type':

<?php
    add_shortcode( 'shortcodename', 'display_custom_post_type' );

    function display_custom_post_type(){
        $args = array(
            'post_type' => 'my-custom-post-type',
            'post_status' => 'publish'
        );

        $string = '';
        $query = new WP_Query( $args );
        if( $query->have_posts() ){
            $string .= '<ul>';
            while( $query->have_posts() ){
                $query->the_post();
                $string .= '<li>' . get_the_title() . '</li>';
            }
            $string .= '</ul>';
        }
        wp_reset_postdata();
        return $string;
    }
?>

Since a shortcode is executed in the loop, you should use wp_reset_postdata() after you are done with your query, so the Main Loop works again like expected. More information for this function will be found here: https://codex.wordpress.org/Function_Reference/wp_reset_postdata

I hope, this gives you a headstart.

1
  • 4
    you should use wp_reset_postdata after a secondary loop. wp_reset_query is only necessary to restore the $wp_query global, which was not overwritten in this case. wp_reset_query also calls wp_reset_postdata internally, which is why it works here, but is unnecessary.
    – Milo
    Commented Feb 11, 2016 at 16:15

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.