WordPress Conditional Tags Help

Discussion in 'WordPress' started by Rajnish357, Apr 22, 2012.

  1. #1
    I am using this:

    <?php
    $custom=get_post_meta($post->ID, 'Main Keyword', true);
    $title=the_title();
    
    if (!empty($custom)) {
    echo $custom;
    } else {
    echo $title;
    } ?>
    PHP:

    I just want that if $custom Variable (Custom Field on New Post Page) have value then it is displayed otherwise $title (Post Title) is displayed. Currently It is showing both at once.

    I also Tried:

    <?php
    $custom=get_post_meta($post->ID, 'Main Keyword', true);
    $title=the_title();
    
    if ($custom[0]) {
    echo "$custom";
    } else {
    echo "$title";
    } ?>
    PHP:
     
    Rajnish357, Apr 22, 2012 IP
  2. kiramanic

    kiramanic Peon

    Messages:
    205
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Ok the main problem is that you're using the_title() instead of get_the_title(). Basically the former immediately echoes the title out onto the page, regardless of where it is in the code or what else is going on. The latter will just "get" the title and allow you to store it in your $title variable. An alternative would be to skip the unnecessary variable and just else { the_title(); } at the end.

    I just woke up, so I can't spot anything else particularly wrong (again you could skip the $custom variable and just do if(get_post_meta...) but whatever) so if this still doesn't work I'll give it a look after a cup of tea :p
     
    kiramanic, Apr 22, 2012 IP