How to check if the current page is at a specified path in the URL?
-
19-05-2021 - |
Question
I have a page marked as the Posts page that lists most recent blog posts.
It is at path /blog
.
I want to know when the user is on this page so that I can display a list of categories of blog posts at the beginning of the page. I already did this in singular.php and in the rest of the cases in index.php
.
For me is_home() returns true when on the landing page. And I use its behavior in index.php.
I tried a little to use this but it does not work:
get_page_by_path('/blog') == get_post()
So my current code is:
if (!is_home() || get_page_by_path('/blog') == get_post()) {
get_template_part('template-parts/blog-categories');
}
and in the /blog page the blog categories are not shown. I am sure it is because of this condition in the if above.
Update 1
This condition does not work:
$_SERVER['PHP_SELF'] === '/blog'
because it is not /blog
, but index.php
(behavior build through .htaccess
I guess).
Update 2
Translated: Blog - Articles Page
This is not considered front page.
Update 3
From this screenshot I think that home is Start (LP) and Blog is Posts page. Because of this I do not get why the is_front_page call is there:
if (!is_front_page() && is_home() || is_archive()) {
get_template_part('template-parts/blog-categories');
}
Solution
You could try this instead
if (!is_front_page() && is_home()) {
get_template_part('template-parts/blog-categories');
}
Explanation for the difference between front_page an home is here: https://wordpress.stackexchange.com/a/239838 if you set a page as a blog-page it is "home", in your case the landing-page is the so called "front_page". This is WordPress specific.