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 Answer
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.
-
4you 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 callswp_reset_postdata
internally, which is why it works here, but is unnecessary.– MiloCommented Feb 11, 2016 at 16:15