skip to Main Content

I’m trying to execute a simple code via my functions.php file (child theme) on my wordpress website.

The code should return "yes blog" when I open the blog post page, and return "no blog" for any other page. But it only returns "no blog" whatever the page.
I tried different conditionnal tags :

  • is_home()
  • is_front_page() && is_home()
  • !is_front_page() && is_home()
  • is_page_template()
  • is_page(”)

It always returns "no blog"
I have a default front page and a default blog page on my website.

Here is my code:

   if(is_home()){
    echo '<script language="javascript">';
    echo 'alert("yes blog")';
    echo '</script>';
        } else {
        echo '<script language="javascript">';
        echo 'alert("no blog")';
        echo '</script>';
            }

3

Answers


  1. You could replace the if condition with something like:

    if($_SERVER["REQUEST_URI"] == "/blog")
    
    Login or Signup to reply.
  2. The "blog" page is a page and has an ID, so you can write something like:

    if (is_page(345)) {
       // content/code for page whose ID is 345
    } else {
      // content/code for pages whose ID is not 345
    }
    
    Login or Signup to reply.
  3. Checking if you’re on the blog page by looking at the request URI or the page ID is a bad thing since it’s hard coded.

    You should use these conditions :

    if ( is_front_page() && is_home() ) {
      // Default homepage
    } elseif ( is_front_page() ) {
      // static homepage
    } elseif ( is_home() ) {
      // blog page
    } else {
      //everyting else
    }
    

    Make sure you have registered a front page (for is_front_page() cond.) or a blog page (is_home() cond.) in your WordPress permalinks options

    This thread will maybe help : https://wordpress.stackexchange.com/questions/107141/check-if-current-page-is-the-blog-page

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search