我正在为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查询帖子?
谢谢!
#1
深入研究文档后, 我发现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;
评论前必须登录!
注册