1

So I have 4 custom meta boxes for each post on a wordpress site relating to the product this client sells.

I have 3 dropdown boxes, one for category, and two for two of the custom meta boxes. The meta boxes I'm dealing with are adhesion_box and substrate_box.

My AJAX script works fine when I query the post titles, but when I try to grab the meta values, it won't work. I'm attempting to use WP_Query for this instead of $wpdb. Here is the php bit that isn't working:

$cat   = $post['cat'];
$query = new WP_Query( array( 'cat' => '$cat' ) );

if($query->have_posts()){
    $posts = $query->get_posts();
    foreach( $posts as $post ) {
        $return[$post->id] = $post->meta_value;
    }
}

Right now the JSON object it returns is:

OBJECT: {"":""}

So I'm a little lost. Here is the long $wpdb query that my friend wrote that grabs the post titles by category - it works just fine, but I need the adhesion_box meta value, not the post title.

$query = $wpdb->get_results(
    "SELECT p.`id`,p.`post_title`
    FROM $wpdb->posts `p`
    JOIN $wpdb->term_relationships `tr` ON (`p`.`ID` = `tr`.`object_id`)
    JOIN $wpdb->term_taxonomy `tt` ON (`tr`.`term_taxonomy_id` = `tt`.`term_taxonomy_id`)
    JOIN $wpdb->terms `t` ON (`tt`.`term_id` = `t`.`term_id`)
    WHERE `p`.`post_type`='post'
    AND `p`.`post_status` = 'publish'
    AND `tt`.`taxonomy` = 'category'
    AND `t`.`term_id` = '$cat'");

I'm having a hard time figuring out how to grab that value, and do it in the simplest way.

Any help appreciated.

Here is the demo, so you can see it.

  • There the property meta_value isn't part of the $post object, so naturally you won't get anything back by trying to access it. There are extra functions for accessing post meta data. – Nicolai Sep 4 '14 at 14:49
  • So I should change that line to: $return[$post->id] = get_post_meta($post->id, 'adhesion_box', true); – Remy Sheppard Sep 4 '14 at 14:59
  • Should work, if thats actually the name of the custom field. – Nicolai Sep 4 '14 at 15:03
  • returns OBJECT: {"":false} – Remy Sheppard Sep 4 '14 at 15:14
0

The best way to go about this is with $wpdb. The query to draw out meta_value by category is:

$query = $wpdb->get_results(
    "SELECT p.`ID`, pm.`meta_value` FROM {$wpdb->postmeta} pm
    LEFT JOIN {$wpdb->posts} `p` ON `p`.`ID` = pm.`post_id`
    LEFT JOIN {$wpdb->term_relationships} `tr` ON `p`.`ID` = `tr`.`object_id`
    LEFT JOIN {$wpdb->term_taxonomy} `tt` ON `tr`.`term_taxonomy_id` = `tt`.`term_taxonomy_id`
    WHERE `pm`.`meta_key` = 'adhesion_box'
    AND `p`.`post_status` = 'publish'
    AND `p`.`post_type` = 'post'
    AND `tt`.`taxonomy` = 'category'
    AND `tt`.`term_id` = $cat
");

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.