0

I want to search a meta field for a value in all posts.

Code below shows what I want to accomplish (I'm a WP and PHP beginner and can't manage to make it work by myself). If in meta field "voted_IP" there's value $ip (current user ip) then echo something, else echo something else.

I need to search in all posts, not just current, so I can't use get_post_meta. I found somewhere that I can make it work with query but it doesn't work.

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$query = new WP_Query( array( 
    'meta_key' => 'voted_IP', 
    'meta_value' => $ip
) );
if ($query == $ip) {
    echo 'one';
} else {
    echo 'two';
}
?>

1 Answer 1

0

WP_Query will return a WP_Query object. An object will never match the string $ip that you are comparing it to. What you need to be doing is checking whether results were returned, which you can do by checking the found_posts property:

$ip = $_SERVER['REMOTE_ADDR'];
$query = new WP_Query( array( 
    'ignore_sticky_posts' => true,
    'meta_key' => 'voted_IP', 
    'meta_value' => $ip
) );
if (0 !== $query->found_posts) {
    echo 'one';
} else {
    echo 'two';
}

Or you can use the WP_Query method have_posts:

$ip = $_SERVER['REMOTE_ADDR'];
$query = new WP_Query( array( 
    'ignore_sticky_posts' => true,
    'meta_key' => 'voted_IP', 
    'meta_value' => $ip
) );
if ($query->have_posts()) {
    echo 'one';
} else {
    echo 'two';
}

Note that I added an ignore_sticky_posts condition. You need that to make this work reliably

By default the query will check for published posts, if you need other post types or post statuses you will need to add more conditions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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