WordPress Get Post Meta from Callback Function

I’m working on my first WP plugin, and am stuck.

I created a custom field (field 1) on the post page below the content editor. It saves correctly. 🙂

Read More

I created a custom field (field 2) inside the Media Library popup when adding media. It saves correctly. 🙂

What I’m wanting to do, is use the value from field 1 as the default value for field 2.

I’m suspecting that the problem lies within the attachment_fields_to_edit callback function.

I think that $post is now referring to the actual “file attachment post” rather than the post itself, so when I’m referencing my saved values:

$post_meta = get_post_meta( $post->ID );

it is actually pulling all of the meta associated with that attachment, and not with the current post. Is it possible to pull the meta from the actual post?

This code is from the Codex:

function my_add_attachment_location_field( $form_fields, $post ) {
    $field_value = get_post_meta( $post->ID, 'location', true );
    $form_fields['location'] = array(
        'value' => $field_value ? $field_value : '',
        'label' => __( 'Location' ),
        'helps' => __( 'Set a location for this attachment' )
    );
    return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'my_add_attachment_location_field', 10, 2 );

function my_save_attachment_location( $attachment_id ) {
    if ( isset( $_REQUEST['attachments'][$attachment_id]['location'] ) ) {
        $location = $_REQUEST['attachments'][$attachment_id]['location'];
        update_post_meta( $attachment_id, 'location', $location );
    }
}
add_action( 'edit_attachment', 'my_save_attachment_location' );

How would I get_post_meta for the current post that we are inserting the attachment into? This would need to happen in the my_add_attachment_location_field callback function in the codex code above.

Thanks!

Related posts

Leave a Reply

5 comments

  1. You can try the following:

    /**
     * Display custom 'location' attachment field
     */
    
    function so_22850878_attachment_fields_to_edit( $form_fields, $post )
    {
        $field_value = get_post_meta( $post->post_parent, 'location', true );
    
        $form_fields['location'] = array(
            'value' => $field_value ? $field_value : '',
            'label' => __( 'Location' ),
            'helps' => __( 'Set a location for this attachment' )
        );  
    
        return $form_fields;
    }
    
    add_filter( 'attachment_fields_to_edit', 
                'so_22850878_attachment_fields_to_edit', 10, 2 );
    

    and

    /**
     * Edit attachment fields
     */
    
    function so_22850878_edit_attachment( $attachment_id )
    {
        $p = get_post( $attachment_id );
    
        if ( isset( $_REQUEST['attachments'][$attachment_id]['location'] ) )
        {
            $location = $_REQUEST['attachments'][$attachment_id]['location'];
    
            // Save the value of the 'location' attachment field 
            // to the 'location' post meta of the post parent if it exists:
    
            if( ! is_null( $p )
                && 0 < $p->post_parent 
            )
                update_post_meta( $p->post_parent, 
                                  'location', 
                                   sanitize_text_field( $location ) 
                );
        }
    }
    
    add_action( 'edit_attachment', 'so_22850878_edit_attachment' );
    

    to update the location post meta value of the parent post, from the media popup.

    You might also want to check this out, if you edit the attachment directly from the media library pages:

    /**
     * Save attachment fields
     */
    
     function so_22850878_attachment_fields_to_save( $post, $attachment )
    {
        $p = get_post( $post['ID'] );
    
        // Save the value of the 'location' attachment field 
        // to the 'location' post meta of the post parent if it exists:
    
        if( isset( $attachment['location'] ) 
            && ! is_null( $p ) 
            && 0 < $p->post_parent 
        )
            update_post_meta( $p->post_parent, 
                              'location', 
                               sanitize_text_field( $attachment['location'] ) 
            );
    
        return $post;
    }
    
    add_action( 'attachment_fields_to_save', 
                'so_22850878_attachment_fields_to_save', 10, 2 );
    

    I’m not sure what kind of workflow you have in mind, but I think there’s a problem with your idea, as I understand it:

    When you update the location field in the media popup, it looks like
    you want to update the location post meta value for the parent post.
    But since the post edit screen doesn’t update when you insert the
    image into the post editor, your location value will be overwritten
    with the old value when you update the post.

    So I wonder if you could use a hidden post meta value instead, for example _location?

    Hope this helps.

  2. ok try a different way……you wont be easily able to get the post id whilst in the navigator. Im not sure what the location is but if you want to save images as post meta, i use this…………

    steps:

    1.create a new js file + visit http://jsfiddle.net/dheffernan/BB37U/2/ and copy the js there into the js file. call it miu_script.js or if you want to change it you need to make some mods to the code below. Save it in your plugin folder (change path below if you want to move it into subfolder.

    1. enter in the code below into your functions – it will save the image location as a serialized url and in a field called “_images” again change if you want by modifying the code.

    2. There may be errors below, i had this in Oop format so let me know if there are issues. . If there are, note php errors, if no php errors but it dosent work, check the console in chrome or firefox. Ill be able to debug.

    in your functions php

    function add_image_meta_box() {
       add_meta_box(
                    'multi_image_upload_meta_box'
                    , __('Upload Multiple Images', 'miu_textdomain')
                    , 'render_meta_box_content'
                    , $post_type
                    , 'advanced'
                    , 'high'
            ); 
    }
    
    add_action( 'add_meta_boxes', 'add_image_meta_box' );
    
    
    
    
    function render_meta_box_content($post) {
    
        wp_nonce_field('miu_inner_custom_box', 'miu_inner_custom_box_nonce');
    
        $value = get_post_meta($post->ID, '_images', true); // <-- change field if wanted, there is 1 more below that will need the same name
    
        $metabox_content = '<div id="miu_images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />';
        echo $metabox_content;
    
        $images = unserialize($value); //<--- when using the images use this!!
    
        $script = "<script>
            itemsCount= 0;";
        if (!empty($images))
        {
            foreach ($images as $image)
            {
                $script.="addRow('{$image}');";
            }
        }
        $script .="</script>";
        echo $script;
    }
    
    
    
    
    
    function save_image($post_id){
    
        if (!isset($_POST['miu_inner_custom_box_nonce']))
            return $post_id;
    
        $nonce = $_POST['miu_inner_custom_box_nonce'];
    
        if (!wp_verify_nonce($nonce, 'miu_inner_custom_box'))
            return $post_id;
    
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return $post_id;
    
    
        if ('page' == $_POST['post_type']) {
    
            if (!current_user_can('edit_page', $post_id))
                return $post_id;
        } else {
    
            if (!current_user_can('edit_post', $post_id))
                return $post_id;
        }
    
        $posted_images = $_POST['miu_images'];
        $miu_images = array();
        foreach ($posted_images as $image_url) {
            if(!empty ($image_url))
                $miu_images[] = esc_url_raw($image_url);
        }
    
    
        update_post_meta($post_id, '_images', serialize($miu_images));<--if you changed this above.......make sure they match
      }
    
      add_action( 'save_post', 'save_image' );
    
    
      function enqueue_scripts($hook){
        if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
            return;
        wp_enqueue_script('miu_script', plugin_dir_url(__FILE__) . 'miu_script.js', array('jquery')); //<--this is the path!!! change if wanted (prob a good idea to add to js folder)
    }
      add_action('admin_enqueue_scripts', 'enqueue_scripts');
    
  3. just a simple solution

    function my_add_attachment_location_field( $form_fields, $post ) {
        $field_value = get_post_meta( $post->ID, 'location', true );
    
        $default = get_post_meta( $_REQUEST['post_id'] , 'location', true ) ? get_post_meta( $_REQUEST['post_id'] , 'location', true ): "Location Not Yet Set";
    
        $form_fields['location'] = array(
            'value' => $field_value ? $field_value : $default,
            'label' => __( 'Location' ),
            'helps' => __( 'Set a location for this attachment' )
        );
        return $form_fields;
    }
    add_filter( 'attachment_fields_to_edit', 'my_add_attachment_location_field', 10, 2 );
    

    working fine with my plugin

    $_REQUEST[‘post_id’] is actual wp post ID
    and with get_post_meta you can get your metabox location ..
    🙂