使用WP_Query()检查slug是否存在帖子

时间:2017-03-13 03:46:00

标签: wordpress wordpress-theming

我正在为wordpress写一个404.php。我安装了插件'rolescoper',有些页面要求用户登录才能查看。 Rolescoper没有提供任何方法来区分未找到的页面(404)和拒绝的权限(403)。

我已经能够使用以下代码在我的页面中构建此功能:

$the_query = new WP_Query ( 'pagename=' . $_SERVER['REQUEST_URI'] );
$is_valid_page = ! empty ( $the_query -> queried_object -> post_title );

但令人惊讶的是,同样的方法对帖子不起作用:

$args = array (
   'post_type' => 'post',
   'name' => str_replace ( "/", "", $_SERVER['REQUEST_URI'] )  
);

$the_post_query = new WP_Query ( $args );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );

当我在$the_post_query上执行var_dump时,我得到一些显示0结果的内容。我确信我正在检查的页面存在。

知道如何使用wp_query()来查询slug的帖子吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

在深入研究文档之后,我发现Rolescoper为解决这个问题提供了一个很好的函数is_restricted_rs()

//get the slug requested
$slug = $_SERVER [ 'REQUEST_URI' ];

//First check if it's a page and restricted
$page_id = get_page_by_path ( $slug )->ID;
$page_restricted = is_restricted_rs ( $page_id );

//Then check if it's a post and restricted
$args = array(
  'name'        => $slug,
  'post_type'   => 'post',
  'post_status' => 'publish',
  'numberposts' => 1
);

$my_posts = get_posts($args);

if ( $my_posts ) {
   $post_id = $my_posts[0]->ID;
}

$post_restricted = is_restricted_rs ( $post_id );

//then set $content_restricted for use below
$content_restricted = $post_restricted || $page_restricted;

答案 1 :(得分:0)

试试这个:

$the_post_query = new WP_Query ( 'name' => $_SERVER['REQUEST_URI'] );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );

我没有测试过,但它应该有用。

来自codex的参考:

https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter