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
1 Answer
Reset to default 5I 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
版权声明:本文标题:Display custom post type with shortcode 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742380019a2463914.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论