Wordpress页面中自定义wp_query的分页不起作用

问题描述

我正在尝试为website.com/blog创建分页,此页面显示了最新帖子。 我创建了自定义wp_query来表明这一点,但是我的分页不适用于此wp_query。 我的wp_query是:

os.system(f"ssh -i ~/.ssh/my-ssh-key username@serverlocation \"sed -i '/\btest-node-1\b/s/$/ 0/' ~/{function}.txt\"")

我的分页在正常页面上工作正常,但在自定义wp_query中遇到了麻烦,

分页功能代码

<?PHP
        $paged = get_query_var('paged') ? get_query_var('paged') : 1;
        $ck_posts = new WP_Query(array(
            'post_type' => 'post','posts_per_page' =>  2,'paged' => $paged
        ));
        if ($ck_posts->have_posts()) : while ($ck_posts->have_posts()) : $ck_posts->the_post();
                get_template_part('includes/e','post-card');
            endwhile;
            pagination();
        else : endif;
        ?>

怎么了?我该如何解决此问题或为该查询创建新功能(如常规分页)?

解决方法

问题在于全局$wp_query不包含自定义查询的结果。

这可能不是一个好主意,但我不知道它是什么,这很可能是一个很好的理由,所以我的建议是在调用$wp_query之前覆盖全局pagination() >

...
if ($ck_posts->have_posts()) : while ($ck_posts->have_posts()) : $ck_posts->the_post();
                get_template_part('includes/e','post-card');
            endwhile;
            $GLOBALS['wp_query']= $ck_posts;
            pagination();
        else : endif;
?>

对于当前版本的Wordpress(5.5.1),这也是为什么内置the_pagination()函数不能与自定义查询一起正常工作的原因。参见https://developer.wordpress.org/reference/functions/get_the_posts_pagination/