WordPress get_post_meta – how can I check for multiple keys?

So I’m trying to work out conditionals with WordPress post meta. I’ve been using get_post_meta() to display content if user had populated the post meta, but I need to improve the rule and add some additional conditionals to it.

Basically, what I need to do is extend this condition to multiple keys. If the user typed in both post_meta_1 and post_meta_2 some code will run, if not then some other code will run.

Read More

This is the code I’m currently using:

if (!((get_post_meta($post->ID, 'post_meta_1', TRUE))=='')) {
    // code here
} elseif {
    // code here as well
}?>

Here’s how far my PHP logic goes:

if (!((get_post_meta($post->ID, array('post_meta_1', 'post_meta_2'), false))=='')) {
    // code here
} elseif {
    // code here as well
}?>

EDIT

Somehow I managed to get it to work by using this method:

<?php

$post_meta_1 = get_post_meta($post->ID, 'post_meta_1', TRUE);
$post_meta_2 = get_post_meta($post->ID, 'post_meta_2', TRUE);

if ($post_meta_1 && $post_meta_2) : ?>

CODE HERE

<?php endif; ?>

Related posts

Leave a Reply

1 comment

  1. You will need to call get_post_meta() individually for each meta_key that you would like a value for. You can have multiple values stored under a single meta_key which is what the third parameter is for – true returns a single value, false an array of values for that meta_key. The result of get_post_meta() will be === false if there is no value in the database, or you can just check for empty() as well.

    $capacity = get_post_meta( $post->ID, 'post_meta_1', true );
    $approved_environment = get_post_meta( $post->ID, 'post_meta_2', true );
    
    if ( $capacity && $approved_environment ){
        // post_meta_1 AND post_meta_2 are set
    }
    
    if ( false !== $capacity && false !== $approved_environment ){
        // post_meta_1 AND post_meta_2 are not set
    }
    
    if ( false !== $capacity || false !== $approved_environment ){
        // post_meta_1 AND/OR post_meta_2 are not set
    }
    
    if ( empty( $capacity ) && empty( $approved_environment ) ){
        // post_meta_1 AND post_meta_2 are not set or are equal to "", null, or 0
    }
    
    if ( empty( $capacity ) || empty( $approved_environment ) ){
        // post_meta_1 AND/OR post_meta_2 are not set or are equal to "", null, or 0
    }