首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在循环外获取自定义post类型中的第一篇和最后一篇文章

在循环外获取自定义post类型中的第一篇和最后一篇文章
EN

Stack Overflow用户
提问于 2013-09-27 04:21:14
回答 2查看 2.3K关注 0票数 0

我使用可湿性粉剂,并有一个脚本,当一个图像被点击时,单个帖子内容加载使用.load()。浏览每个帖子的箭头位于使用.load()加载的.project div中。

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

例如,帖子中的第一个项目被加载,它不应该有‘上一个’箭头,因为没有以前的帖子。上一篇文章和“下一步”箭头也是如此。

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

这是我到目前为止所做的..只是不确定如何在循环之外获取第一个帖子和最后一个帖子的ID。除此之外,其他一切都经过了测试并正常工作。下面主要是代码背后的“逻辑”。

代码语言:javascript
运行
复制
<?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 } ?>
EN

回答 2

Stack Overflow用户

发布于 2013-09-27 05:06:26

我没有这么多的工作与可湿性粉剂,但由于可湿性粉剂模板都是PHP文件和可湿性粉剂暴露自己的API给用户,你可以使用任何PHP语法在他们。如果你不担心每次浏览页面都要运行两个查询,那么这将帮助你理解这个想法。

代码语言:javascript
运行
复制
<?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; } }

?>

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

票数 1
EN

Stack Overflow用户

发布于 2013-09-27 05:21:40

最终使用了这段代码,它工作得很好。

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

代码语言:javascript
运行
复制
$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 } ?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19037947

复制
相关文章

相似问题

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