I am saving user id in post meta whenever someone clicks on like button.

        $voter = Array(
                        voter => array(
                        'post_id' => $post_id,
                        'user_id' => $user_id,
                        'user_ip' => $user_ip,
                        'author_id' => $author_id,
                        'vote'    => $vote
        add_post_meta($_POST['post_id'], 'voter', $voter);
        echo "success";

I want to run this only if user does not already liked the post. So I used this:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;

    return false;

Then using if condition like this helps me to find if user id is already in meta data or not.

$voter_info = get_post_meta( get_the_ID() , 'voter', false );
if (in_array_r("1533", $voter_info)){
                        echo "User is in post meta";

But the problem is this condition is searching for user id: 1533 in all array values. I want to search it in the 'user_id' field. This is making me confused. If you have solution on this or if you know any better way to search in multi dimensional array, then please help me.

  • 1
    Try this func. pastebin.com/EhcX2JrQ . I suppose voter is an index ( in 1st snippet ), 'cause it looks like a constant and I guess that's a typo so. – Samuel Elh Jul 10 '16 at 14:30
  • 1
    This works for me. Thank You Samuel Elh. Can you add it as answer please. – Ramesh Pardhi Jul 12 '16 at 11:48

This is a simple PHP related question (and those are better asked at StackOverflow.com) and you can find if an index exists within a multi-dimensional array by iterating through it and matching. Something as:

function wpse231889_has_user_voted( $user_id, $post_id ) {
    if ( !empty( ( $voters = get_post_meta( $post_id, 'voter' ) ) ) ) {
        foreach ( $voters as $voter ) {
            if ( !empty( $voter['voter']['post_id'] ) && (int) $user_id == (int) $voter['voter']['post_id'] ) {
                return true;
    } return false;

Glad it helped.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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