【问题标题】:wp_pagenavi plugin with custom query not working in index.php - Wordpress带有自定义查询的 wp_pagenavi 插件在 index.php 中不起作用 - Wordpress
【发布时间】:2014-06-09 18:22:42
【问题描述】:

我有一个 Wordpress 网站,我想在我的主页上显示最近 5 条新闻,它们是自定义类型。所以我正在使用 wp_pagenavi 插件,但它在“index.php”中不起作用。在 www.mysite.com 中,它显示最后 5 条新闻和分页,但是当我尝试移动到第二个(或另一个)页面时,它不显示任何新闻。例如,点击第 2 页后,它会将我重定向到 www.mysite.com/page/2/。

我在 index.php 中有这段代码:

...
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$news = new WP_Query('post_type=news&cat=-5&paged='.$paged);

if ($news->have_posts()) :
?>
    <ul>
    <?php while ($news->have_posts()) : $news->the_post(); $do_not_duplicate = $post->ID; ?>
        <li>
        // Code for displaying news
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif;?>
<?php if(function_exists('wp_pagenavi')) : ?>
    <div class="navi"><?php wp_pagenavi(array( 'query' => $news )); ?></div>
<?php endif; ?>
...

谢谢。

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    我刚刚解决了。

    我在functions.php中添加了以下代码:

    function news_index($query) {
        if (!is_admin() && $query->is_main_query() ) {
            if ($query->is_home()) {
                $query->set('post_type', 'news');
                $query->set('cat', -5);
            }
        }
    }
    add_action('pre_get_posts', 'news_index');
    

    在 index.php 中我删除了自定义查询:

    ...
    <?php
    if ($have_posts()) :
    ?>
        <ul>
        <?php while (have_posts()) : the_post(); $do_not_duplicate = $post->ID; ?>
            <li>
            // Code for displaying news
            </li>
        <?php endwhile; ?>
        </ul>
    <?php endif;?>
    <?php if(function_exists('wp_pagenavi')) : ?>
        <div class="navi"><?php wp_pagenavi(); ?></div>
    <?php endif; ?>
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多