Display custom field if it exists and has a specific value

I am trying to display the post title if the custom field exists and has a value of apple…

<?php if ( isset ( get_post_meta($post->ID, 'mycustomvalue', true ) ) ) && if ( get_post_meta($post->ID, 'mycustomvalue', true ) == 'apple' ) : ?>

<?php the_title(); ?>

I am getting a white screen, anyone spot where I am going wrong?

Related posts

2 comments

  1. You can hook into the_title() to alter the output.

    In functions.php paste this:

    function my_change_title( $title, $post_id ) {
        $custom_title = get_post_meta($post_id, 'mycustomvalue', true);
    
        if( isset($custom_title) && $custom_title == 'apple' )
            return $custom_title;
    
        return $title;
    }
    add_filter('the_title', 'my_change_title', 10, 2);
    

    In your template, you can just use <?php the_title(); ?>


    To use your custom value in your template:

    <?php $custom_value = get_post_meta(get_the_ID(), 'mycustomvalue', true); ?>
    <?php if( isset($custom_value) && $custom_value == "apple" ) : ?>
        Do something
    <?php endif; ?>
    
  2. Because, in your code you didn’t close the IF condition.

    I have modified your code but NOT tested.

    <?PHP
    $post_meta = get_post_meta(get_the_ID(), 'mycustomvalue', true);
    if( !empty( $post_meta ) && $post_meta == 'apple'){
        the_title();
    }
    ?>
    

    NOTE: if you don’t want pass the third parameter, you will get the result as an array and you have to change your code from !empty( $post_meta ) to count( $post_meta ) > 0

Comments are closed.