0

Below is the custom query am running on my wordpress site to get the results from postmeta table. When I var_dump the results then I can see the values correctly but when am trying to access a single field from the array, it doesn't work.

Am I missing something?

    <?php
        $key = "sc_event_year";
        $value = $today_year;
        global $wpdb;       
        $query = new WP_Query( array( 'meta_key' => $key, 'meta_value' => $value ) );
        //var_dump($query);
        foreach($query as $result){
            echo $result->post_id;
        }
    ?>
2
  • 1
    Why are you doing this? Why not use WP_Query?
    – vancoder
    Commented Sep 3, 2013 at 23:22
  • Okay thanks for your reply. I have changed my code now. Now can you tell me what am doing wrong? I' am editing the new code above Commented Sep 3, 2013 at 23:34

1 Answer 1

0

You've asked for an array and you are trying to use an object.

$key = "sc_event_year";
$value = $today_year;
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = 'sc_event_year' AND meta_value = $value", ARRAY_A);
foreach ($results as $result){
    echo $post_id = $result['post_id']; // <-- here was the problem
}

Unless $value is a number you could have have trouble with that query and I can't tell if there is user-supplied data but prepare is pretty good habit if you are going to be cooking up your own queries.

$key = "sc_event_year";
$value = $today_year;
global $wpdb;
$results = $wpdb->get_results(
  $wpdb->prepare(
    "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = 'sc_event_year' AND meta_value = %s",
    $value
  ),
  ARRAY_A
);
foreach ($results as $result){
 echo $post_id = $result['post_id'];
}

That said, are you sure there are no Core functions or methods that will server your purpose?

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.