首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查当前发布的wordpress

检查当前发布的wordpress
EN

Stack Overflow用户
提问于 2013-11-22 14:36:20
回答 2查看 249关注 0票数 0

我已经注册了一个定制的post类型,并输入了我的归档-myCPT.php,我想检索,当前发布的文章。下面是我的存档-myCPT.php中的相关片段:

代码语言:javascript
复制
if( have_posts() ){ 

$x = 1;
while ( have_posts() ){
 the_post(); 
  if ( 0 === (int) $post->post_parent) {
   get_template_part( 'inc/post-format/content-debate');

 }

我如何在这个循环中添加一个条件来检查当前发布的帖子并只检索一个(最近的)?这有可能吗?如果是的话,我怎样才能做到呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-23 14:05:18

我们可以直接检索post,过滤wp_query参数中的选择

代码语言:javascript
复制
<?php 
// The Query
$args=array(
'post_type'=>'custom-post-type',
'posts_per_page'=>1,
'post_parent'=>'parent-page-id',
'order'=>'DESC'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
    $the_query->the_post();?>

/*title*/    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
/*image*/    <?php the_post_thumbnail();  ?>

<?php }} 

wp_reset_postdata();?>

因此,不需要在循环中进行过滤。希望这能有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2013-11-22 16:04:45

在循环中,您只得到已发布的帖子,因此这不是您所关心的问题。

如果您希望得到最后一篇发表的文章,请在if(have_posts())函数query_posts('posts_per_page=1&order=DESC&orderby=date&post_type=my_custom_post_type')之前添加

通过query_posts,您可以轻松地修改您的循环。

编辑:

要具体检索一个post而不是循环,请使用get_posts

代码语言:javascript
复制
$posts = get_posts('posts_per_page=1&post_type=my_custom_post_type');

//do not use reserved variable name $post
foreach($posts as $single_post)  setup_postdata($single_post);
    //you can use the_title(), the_content()...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20147438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档