在页面上显示自定义帖子类型摘录

时间:2014-09-20 11:16:12

标签: php wordpress custom-post-type

我创建了一个简单的自定义帖子类型:

add_action( 'init', 'create_services_post_type' );

function create_services_post_type() {
    $args = array(
                  'description' => 'Services post type',
                  'show_ui' => true,
                  'menu_position' => 4,
                  'exclude_from_search' => true,
                  'labels' => array(
                                    'name'=> 'Services',
                                    'singular_name' => 'Service',
                                    'add_new' => 'Add New Service',
                                    'add_new_item' => 'Add New Service',
                                    'edit' => 'Edit Services',
                                    'edit_item' => 'Edit Service',
                                    'new-item' => 'New Service',
                                    'view' => 'View Services',
                                    'view_item' => 'View Service',
                                    'search_items' => 'Search Services',
                                    'not_found' => 'No Services Found',
                                    'not_found_in_trash' => 'No Services Found in Trash',
                                    'parent' => 'Parent Service'
                                   ),
                 'public' => true,
                 'capability_type' => 'post',
                 'hierarchical' => false,
                 'rewrite' => true,
                 'supports' => array('title', 'editor', 'thumbnail', 'comments')
                 );
    register_post_type( 'services' , $args );
}

这很简单,它的工作原理应该如此。现在,我创建了一个新的页面模板,我希望在该模板上显示该类别(服务)的3个最新帖子摘录,但由于我是一个PHP新手,无论如何我尝试了多少,我无法让它发挥作用。

任何善良的灵魂都想帮助我? 非常感谢!

1 个答案:

答案 0 :(得分:2)

尝试使用此代码显示结果:

$args = array( 'post_type' => 'services', 'posts_per_page' => 3,'cat' => cat_id_of_services_category );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
  the_title();
  echo '<div class="entry-content">';
  the_excerpt();
  echo '</div>';
endwhile;

如果在某种情况下您无法获得所需的结果,请在此处查看:http://codex.wordpress.org/Class_Reference/WP_Query