Display custom post type with shortcode

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.

Leave a Comment