【问题标题】:Getting first & last post in custom post type outside of loop在循环之外以自定义帖子类型获取第一个和最后一个帖子
【发布时间】:2013-09-26 20:21:14
【问题描述】:

我正在使用 WP,并且有一个脚本,当单击图像时,单个帖子内容使用 .load() 加载。导航每个帖子的箭头位于使用 .load() 加载的 .project div 内。

问题是,在第一篇和最后一篇文章中,我只想显示某些箭头。

例如,帖子中的第一项被加载,它不应该有“上一个”箭头,因为没有以前的帖子。与上一篇文章和“下一个”箭头相同。

所以基本上为了解决这个问题,我试图提出一个 PHP 语句(不在循环中)来判断当前帖子是自定义帖子类型中的最后一个帖子还是第一个帖子。

这是我到目前为止所拥有的......只是不确定如何在循环之外获取第一篇文章和最后一篇文章的 ID。除此之外的所有其他东西都已经过测试并且可以正常工作。下面主要是代码背后的“逻辑”。

<?php
// Get other posts in post type
$next_post = get_next_post();
$previous_post = get_previous_post();
$current_id = get_the_ID();

// Get ID's of posts
$next_id = $next_post->ID;
$previous_id = $previous_post->ID;

// if($next_id == $previous_id) because on first/last posts, get_next_post
// and get_previous_post return the same value.
if($next_id == $previous_id) {
    if() { 
        // if last post in custom post type
    } else() {
        // if first post in custom post type
    }
}
?>

<?php if(isnt first post) { ?>
    <li class="left" data-projectid="<?php echo $next_id; ?>"></li>
<?php } ?>
<li class="grid"></li>
<?php if(isnt last post) { ?>
    <li class="right" data-projectid="<?php echo $previous_id; ?>"></li>
<?php } ?>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    我没有太多地使用 WP,但是由于 WP 模板都是 PHP 文件,并且 WP 向用户公开了自己的 API,因此您可以在其中使用任何 PHP 语法。如果您不担心每次浏览页面时都运行两个查询,那么这将帮助您了解这个想法。

    <?php
    
    global  $wpdb;
    $last_one = FALSE;
    $first_one = FALSE;
    
    // Get last one
    $last_result = $wpdb->get_results("SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 0, 1", ARRAY_A);
    if($last_result){ if($last_result['id'] == $next_post){ $last_one = TRUE; } }
    
    // Get first one
    $first_result = $wpdb->get_results("SELECT `id` FROM `posts` ORDER BY `id` ASC LIMIT 0, 1", ARRAY_A);
    if($first_result){ if($first_result['id'] == $previous_post){ $first_one = TRUE; } }
    
    ?>
    

    记得检查字段和表的名称,因为我不知道名称。

    【讨论】:

      【解决方案2】:

      最终使用了这段代码,它工作正常......

      编辑:更新代码..如果出于任何原因其他人需要它:

      $args = array('post_type'=>'your_post_type', 'posts_per_page' => -1);
      $posts = get_posts($args);
      $first_id = $posts[0]->ID; // To get ID of first post in custom post type 
      // outside of loop
      
      
      $last_id = end($posts);
      echo $last_id->ID; // To get ID of last post in custom post type outside of loop
      
      if($current_id != $first_id) { ?>
          <li class="left" data-projectid="<?php echo $previous_id; ?>"></li>
      <?php } ?>
      <?php if($current_id != $last_id->ID) { ?>
          <li class="right" data-projectid="<?php echo $next_id; ?>"></li>
      <?php } ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-21
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 2014-11-18
        • 2015-10-11
        • 2016-11-30
        • 1970-01-01
        相关资源
        最近更新 更多