What I am looking to do is check if a page is private, give the users the option to register and see the page. Here is what I have now:
<?php
if (have_posts()) :
/* Print the most as normal */
else :
if ($post->post_status = 'private')
{
/* Print login/register box */
}
else
{
/* Print page not found message */
}
endif; ?>
My problem is that it is always falling through and displaying the login box even when the page does not exists. How do I fix this?
When a POST is set to private, non-logged in users will receive a 404 message. If you dump the global variable
$wp_query
,..you will notice that no
post_status
is present in the parameters returned therefore using the slug (orname
parameter ofquery_vars
array for example) we can get the post status of the POST that is trying to be accessed like so,Helpful Codex resources:
http://codex.wordpress.org/Function_Reference/get_page_by_path
Update:
On the basis that you are trying to perform this action for the “PAGE” post type (as per your comments) the above code should change
'post'
to'page'
accordingly inget_page_by_path()
.Now the reason why it still was not working while using
$wp_query->query_vars['name'];
is then related to the fact that your page is a CHILD page of another page, in otherwords it has a PARENT.Because the function we are using is getting our page by its path, it needs to know its full path so the parent page matters. Therefore we must change,
to
Elaborating further what we are doing is accessing the full path from a different array within the
$wp_query
and here’s an example (sample snippet) of what is$wp_query
is actually comprised of when dumping the resultsTherefore the modified code in full will look like;
As Kaiser mentioned you can also use,
get_post_status()
function to retrieve the post status and that can be done like so,Was just looking around for this answer myself in 2020 and it seems this is a great way to do it now.