• Resolved NathanielFisher

    (@nathanielfisher)


    Hi. I’m trying to put together a list of all posts where the metadata matches a specific query. It appears to work fine until I try to output the data, at which point it is repeated continuously.

    I expected it to display 16 23 but instead it shows 16 23 16 23 16 23 16 23 16 23 16 23 16 23 16 23 16 23 16 23

    Here’s the code:

    <?php
    global $wpdb;
    $results =$wpdb->get_results("SELECT post_id FROM $wpdb->posts , $wpdb->postmeta where  $wpdb->postmeta.meta_value = '2015/06/03' AND meta_key='mymvkey'", OBJECT);
    
    foreach ($results as $result){
    print_r ($result->post_id);
    }
    ?>

    I’m still trying to get the hang of handling arrays (and not just in php) so that’s probably where I’m going wrong. But every post I’ve read suggests that this should work. Also, I’ve tried it both in and out of the loop with the same result. Is there any way to just display the data once instead of repeatedly?

Viewing 2 replies - 1 through 2 (of 2 total)
  • could be because a) the code above is inside a loop. or b) your accidentally selecting revisions instead of just post_status published posts.

    might be easier to just use get_posts() instead of $wpdb:

    $args = array(
    	'meta_key'         => 'mymvkey',
    	'meta_value'       => '2015/06/03',
    );
    $posts_array = get_posts( $args );
    foreach($posts_array as $apost) {
        echo $apost->ID;
    }
    ?>

    Thread Starter NathanielFisher

    (@nathanielfisher)

    Thanks. I did it that way because I’m still getting to grips with SQL and PHP and it seemed more straightforward that way. I just got it working by removing the reference to $wpdb->posts, as I wasn’t using that table anyway. I think the issue might have had something to do with (not properly) traversing the array. Not sure though.

    Anyway, this worked.

    <?php
    global $wpdb;
    $results =$wpdb->get_results("SELECT post_id FROM $wpdb->postmeta where  $wpdb->postmeta.meta_value = '2015/06/03' AND meta_key='mymvkey'", OBJECT);
    
    foreach ($results as $result){
    printf ($result->post_id);
    }
    ?>

    Most people seem to suggest using get_posts for stuff like this. So now I’ve got it working I’ll use your example to help me make sense of that. Thanks again.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Problem getting meta_value data from database’ is closed to new replies.