Frage

I am trying to add a css file specific to 3 pages using the is_page(postid) for a WordPress website in the functions.php

 if (is_page(1) || is_page(2) || is_page(3) ) {
           echo "<script>console.log('insideIf');</script>";
           wp_enqueue_style( 'custom_css', get_template_directory_child() . path);  
        }

So considering 1,2 and 3 are the ids of the pages, the pages with the ids 2 and 3 are logging the message in the console and loading the css file whereas is_page(1) does not respond.

I tried changing it to is_page('1') or is_single() or is_single(1). The page that is not getting detected is a blog page and i even tried with the title is_page('blog').

Ps. Cross checked the id many times, so I am definitely not using the wrong id.

War es hilfreich?

Lösung

If the page you’re trying to check is set as Page for posts, then is_page conditional won’t be true.

In such case you should check if is_home.

Why? All these conditional tags are based on global wp_query. For page that is set as page for posts (home of your blog), the global query doesn’t contain singular page - it contains list of blog posts.

Andere Tipps

The conditional is_page is mapped to the is_page method of the wp_query class. As you can see in the source a couple of things are tested.

First if the method does not apply to the object that is passed (for instance because it is not a wp_query instance), it returns false.

Then the queried object is retrieved. This gets either the data for a page/post or, if the query is for an archive, data for that specific archive. Note that this method does nothing with the page ID that you have called is_page with. It retrieves the queried object regardless of that.

Next it tests the queried object against the page ID (or page name, or post title) that you passed. This is where it goes wrong in your case. The queried object is a blog archive, so it does not have a page ID in the context of this conditional test. As a result is_page returns false.

Most likely is_home will do the trick, because that tests for the main blog archive. Otherwise you may need a more complicated set of tests to target this page.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit wordpress.stackexchange
scroll top