I want to only return one value for this query, it's in my functions.php file. The idea is to return a value that I need once post_meta has been updated. It's returning the same (correct) value 5 times... I only want the value to be returned once.

add_action( 'added_post_meta', 
    function ( $mid, $object_id, $meta_key, $_meta_value) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'postmeta';
        $results = $wpdb->get_var(
            "SELECT meta_value FROM " . $table_name . 
            " WHERE meta_key = 'data19' AND post_id = " .$object_id. " " );
    10, 4 );

Any ideas how I can get just one value returned? I've tried:

  • adding Group by to the end
  • adding OBJECT_K to the end
  • using MAX before each value
  • using FIRST before each value
  • using wp_reset_query()

and some more I can't even recall.


The most likely cause is that the hook is probably running multiple times (e.g. once per meta field). You may need to qualify/filter your function like so…

add_action( 'added_post_meta', function ( $mid, $object_id, $meta_key, $_meta_value) {
  global $wpdb;

  if ( $meta_key != 'data19' ) {

  $table_name = $wpdb->prefix . 'postmeta';
  $results = $wpdb->get_var(
    "SELECT meta_value FROM " . $table_name . 
    " WHERE meta_key = 'data19' AND post_id = " .$object_id. " " );

}, 10, 4 );
  • 1
    added_post_meta is a WP hook, and should check $meta_key != 'data19' (not $mid) based on sql query... – bonger Aug 1 '15 at 2:40
  • updated_{$meta_type}_meta is the hook. It's called once per add_metadata() call on the post post type. – Matt van Andel Aug 1 '15 at 2:58
  • 1
    Yes- the hook was being called multiple times... once for each of the meta_value that were created. Using @MattvanAndel 'filter/qualify' idea, and replacing the code with what @bonger suggested... I now have the value being returned just once. So, when I inserted this as the qualification code: if ( $meta_key != 'data19' ) {return;} ... it worked perfectly. I've updated the code. – Jonirish Aug 1 '15 at 21:56

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.