0

I have a custom template. I want to output some JavaScript based on the type of page I am on. My current setup includes a static front page, with a template assigned it to it. This template is also a taxonomy archive page. I did this since I wanted the home page to be a taxonomy archive. When I hook into the pre_get_posts, I get different results in different areas of the page. Here is what I get:

add_action('pre_get_posts', 'do_something');
function do_something($query) {
    echo '<pre>';
    echo 'Front: ' . $query->is_front_page .'<br>';
    echo 'Home: ' . $query->is_home .'<br>';
    echo 'Tax: ' . $query->is_tax .'<br>';
    echo 'Page: ' . $query->is_page .'<br>';
    echo 'Archive: ' . $query->is_archive('label') .'<br>';
    echo '</pre>';
}


//Homepage
Oustide the wrapper: Page - 1,
Sidebar: Home - 1
Content area: Tax - 1, Archive - 1

//On an archive page
Outside the wrapper: Tax - 1, Archive - 1,
Header: Archive - 1,
Sidebar: Home - 1,
Content: Tax - 1, Archive - 1

How can I make sure the conditionals return the appropriate page type? Do I need to change something in my code?

0

I may have misinterpreted what you are asking here but you don't need to do this using pre_get_posts().

Instead you could either add this to your functions file:

function output_page_type() {
    global $post;
    $pagename = $post->post_name;
    return $pagename;
}

and then on the relevant page echo output_page_type(); to get the page title.

Or you could use switch and the appropriate conditional tags i.e. is_page() is_home() is_tax() is_archive() etc. You can then output the correct page type that way. I like to do this in the header so its only needed once. For example:

    switch (n)
    {
    case is_home() :
      echo "Home";
      break;

    case is_page() :
      echo "Page";
      break;

    case is_category() : // Category
      echo "Category";
      break;

    case is_tag() : // Tags
      echo "Tag";
      break;

    case is_single() : // Single
      echo "Single";
      break;

    case $wp->query_vars['post_type'] : // Custom Post Type
      echo $wp->query_vars['post_type'];
      break;

    case is_tax() : // Custom Taxonomies
      echo "Tax";
      break;

    case is_archive() : // Standard Archive
      echo "Archive";
      break;

    default:
      echo "Some other randomness";
      break;
    }
  • Thanks! My code actually does the same thing, I just have avoided the conditional checking! What I need to do is, accurately identify the type of page I am on and output some JavaScript. – Rutwick Gangurde Feb 5 '16 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.