我在主页上有两个不同的WP查询。我需要检查函数中的$home\\u查询条件。php然后,如果$home\\u query返回null,我想做些什么。我尝试了pre\\u get\\u posts操作,但我无法捕获$home\\u查询数据,而且它运行了两次,因为页面上有两个WP\\u查询。
使用If$home\\u query返回null的分页方式,我想将页面重定向到404页面并获取404响应的代码。
例如https://example.com/page/200/ 页码是200,但在页面中没有200页码,我想重定向404页面并得到404响应,而不是;“不显示结果文本”;
指数php
$home_query = new WP_Query( array(\'posts_per_page\' => get_query_var(\'posts_per_page\'),\'paged\' => $current_page ) );
$featured_post = new WP_Query(array(\'p\'=>get_theme_mod(\'featured-content-callout-post\'),\'order\' => \'DESC\',\'posts_per_page\'=> 1));
            if($home_query->have_posts()):
                    while ($home_query->have_posts()):
                        $home_query->the_post();
                        get_template_part(\'template-parts/content\',\'list\');
                    endwhile;
            else;
                   // get_template_part(\'template-parts/content\',\'none\');
                      // I tried to use redirect code in here but I couldn\'t.
            endif;
 谢谢你的帮助
 
                SO网友:vlatkorun
                您可以使用两个挂钩来实现所需的结果:
使用parse_query 操作钩子(查询变量在此钩子中初始化)来创建$home_query 并使用wp_cache_set 函数(缓存中的内容仅为当前请求存储)使用template_redirect 用于从缓存中提取内容的操作挂钩,使用wp_cache_get 函数并查看是否有结果。从这里可以重定向到其他页面。请查看本页底部的钩子文档和示例:https://developer.wordpress.org/reference/hooks/template_redirect/下面是一个示例代码:
function custom_parse_query() {
    $home_query = new WP_Query( array(\'posts_per_page\' => get_query_var(\'posts_per_page\'), \'paged\' => get_query_var(\'page\') ) );
    wp_cache_set(\'home_query\', $home_query);
}
add_action( \'parse_query\', \'custom_parse_query\' );
function custom_template_redirect() {
    $home_query = wp_cache_get(\'home_query\');
    if( $home_query instanceof WP_Query && ! $home_query->have_posts() ) {
        wp_redirect( home_url( \'/signup/\' ) );
        exit();
    }
}
add_action( \'template_redirect\', \'custom_template_redirect\' );