【问题标题】:Wordpress: Check if there are previous posts before displaying linkWordpress:在显示链接之前检查是否有以前的帖子
【发布时间】:2011-02-12 23:38:36
【问题描述】:

我正在使用以下代码在我的 Wordpress 博客上显示“以前的帖子”链接。

     <nav>
            <ul>
                <li><?php previous_posts_link('Newer Entries &raquo;') ?></li>
</ul
</nav>

问题是,当没有任何以前的帖子时,虽然链接不显示,但我仍然得到 ​​p>

<nav>
            <ul>
                <li><</li>
</ul
</nav>

打印出来。是否有一个 if() 语句我可以将其全部包装起来,以便检查是否有任何以前的帖子,如果有则只打印出来?

【问题讨论】:

    标签: php wordpress navigation


    【解决方案1】:

    你可以试试这样的

    <?php
        if($link = get_previous_posts_link()) {
            echo '<ul><li>'.$link.'</li></ul>';
    ?>
    

    get_previous_posts_link 如果之前没有任何帖子,则返回 null(假值)。

    【讨论】:

    • 不应该是==而不是=吗?
    • 没有@brasofilo;这有点令人困惑,我知道。像这样写的if首先将get_previous_posts_link()的结果赋值给$link,然后检查赋值值(赋值的返回值是被赋值的值),正如我在代码下面所说,函数返回null如果没有以前的帖子,那么在这种情况下不会调用代码。
    • 需要将 get_previous_posts_link() 改为 get_previous_post_link()(单数“post”)
    【解决方案2】:

    要明确一点:

    在我看来,Colin 的回答是不正确的。 get_previous_post 未被弃用,previous_post 被弃用。

    http://codex.wordpress.org/Function_Reference/get_previous_post http://codex.wordpress.org/Function_Reference/previous_post

    对我来说,使用 get_next_post 对我来说仍然很好。

    if(get_next_post()) {  }
    if(get_previous_post()) {  }
    

    【讨论】:

    • 在 WP WordPress 4.6.1 中为我工作
    【解决方案3】:

    没有一个答案对我有用。 我是这样解决的:

    $next = get_permalink(get_adjacent_post(false,'',false)); //next post url
    $prev= get_permalink(get_adjacent_post(false,'',true)); //previous post url
    <?php if (get_the_permalink()!=$prev): ?>
        <a href='<?php echo $prev ?>'>Previous</a>
    <?php endif; ?>
    <?php if (get_the_permalink()!=$next): ?>
        <a href="<?php echo $next ?>">Next</a>
    <?php endif; ?>
    

    【讨论】:

      【解决方案4】:

      对于 2013 年检查此内容的人,get_previous_post 已贬值。

      http://codex.wordpress.org/Next_and_Previous_Links http://codex.wordpress.org/Function_Reference/previous_post

      我以前用过这个:/

      if(get_next_post()) { echo 'next'; }
      if(get_previous_post()) { echo 'last'; }
      

      但现在我用这个:)

      if(get_next_posts_link()) { echo 'next'; }
      if(get_previous_posts_link()) { echo 'last'; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多