admin管理员组

文章数量:1336631

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?

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?

Share Improve this question edited Apr 8, 2015 at 7:14 Pieter Goosen 55.4k23 gold badges115 silver badges210 bronze badges asked Apr 8, 2015 at 6:35 jorenwoutersjorenwouters 511 gold badge1 silver badge2 bronze badges 1
  • Possible yes, but what have tried yourself to solve this issue and where are you stuck – Pieter Goosen Commented Apr 8, 2015 at 7:15
Add a comment  | 

1 Answer 1

Reset to default 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/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/Function_Reference/wp_reset_postdata

I hope, this gives you a headstart.

本文标签: Display custom post type with shortcode