Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've got this in header.php in <head> section:

$page_color = get_post_meta($post->ID, 'page_color', true);

It works fine because it gets correct page_color for posts and pages but when I perform some search and search.php is run, it occasionally gets page_color of first post it finds. This is the content of search.php:

<?php
  if( have_posts() ) : 
    while (have_posts()) : the_post(); ?>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
        <?php the_excerpt(); ?>
    <?php endwhile; ?>
  <?php else : ?>
        Nothing found.
    <?php endif; ?>

Any ideas why is that?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

I don't think it's just occasionally, that will always get you the post meta of the first post on a search results page, a taxonomy page, an archive page - any page where there are multiple posts, because the $post global will always be populated with the first post of any main query result.

EDIT-

if ( is_singular() ) :
    // we are viewing a single post or page
    $page_color = get_post_meta($post->ID, 'page_color', true);
else :
    // not a single post or page, use a default color
    $page_color = 'blue';
endif;
share|improve this answer
    
Hmm, I see, so what would be the workaround to get page_color of current page or post? Search.php should never have any page_color - there is no way to specify it in admin panel. I already tried the_ID(); but it doesn't work. –  Paul Aug 22 '12 at 15:00
    
This is where Conditional Tags come in handy, see my edit above. You can check what type of page you're viewing and set and output what you need based on those conditions. –  Milo Aug 22 '12 at 15:25
1  
You might simplify it with a ternary: $page_color = ( is_singular() ? get_post_meta($post->ID, 'page_color', true); : 'blue' );. But the key is the is_singular() conditional. Note that is_singular() will return true for post, page, and attachment post types. So if you only allow page_color for single blog posts, use is_single() instead. –  Chip Bennett Aug 22 '12 at 15:25
    
Thank you guys. This obviously works fine but isn't there any "correct" way to do that? I mean - to obtain correct ID of current post/page (search.php may return null) and return false when trying to access page_color if such ID doesn't exist? Making it work for posts and pages using if() seems like workaround. –  Paul Aug 22 '12 at 15:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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