Title: Adding parent&#039;s post MetaData
Last modified: August 24, 2016

---

# Adding parent's post MetaData

 *  Resolved [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/)
 * Hi David,
 * First of all thank you for this awesome plugin!!!
 * I’m trying to map a custom field value from the parent post to the to medias,
   but with no luck until now…
 * I tried instinctively to add it with this template :
    [+parent:ref_offer+] (where“
   ref_offer” is the meta_key of the value I want to get added to the media.
 * I’ve tried [+parent+] as a starting point and it’s working as expected.
    I’ve
   checked out the documentation, but I didn’t figured out how to “reach” to the
   parent’s meta_value using it’s meta_key….
 * So could you please point me in the correct direction?
 * Thanks in advance.
 * [https://wordpress.org/plugins/media-library-assistant/](https://wordpress.org/plugins/media-library-assistant/)

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

 *  Plugin Author [David Lingren](https://wordpress.org/support/users/dglingren/)
 * (@dglingren)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064445)
 * Thank you for your kind words and for this interesting question. I want to make
   sure I understand your application so I can give you a specific answer.
 * You wrote”**_I’m trying to map a custom field value from the parent post to the
   media_**” – I can think of two ways to interpret your goal:
    1. You want to display the parent’s custom field value in a gallery composed with`[
       mla_gallery]`.
    2. You want to copy the parent’s custom field value to a standard or custom field
       in each media item, using the IPTC/EXIF or Custom Field mapping rules.
 * Either one of these can be done, but the specifics of the answer will be different.
   Can you post an update with more information about your application?
 * Your first instinct, `[+parent:ref_offer+]`, might make a useful enhancement 
   for a future MLA version. I will look into the possibility of doing something
   along those lines and let you know if I decide to proceed.
 *  Thread Starter [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064475)
 * Sorry that I was not enough clear…
 * So, es I’m more in he process of the second interpretation :
    I’ve a custom field
   which is defined in the media’s parent post with meta_key = ref_offer & meta_value
   = string
 * My wish is to copy the meta_key / meta_value in the media’s metatdatas.
 * The (actual) final purpose is to sort / filter the medias by ref_offer for management
   or display.
 * Also let me know if you need some “instinctive” testing or advice to help in 
   you researchement. It’ll be a pleasure! =)
 * Thanks!!
 *  Plugin Author [David Lingren](https://wordpress.org/support/users/dglingren/)
 * (@dglingren)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064483)
 * Thank you for your update and the additional information in answer to my questions.
   Your question is a variation on these earlier topics:
 * [Using media Path to populate att. Category](https://wordpress.org/support/topic/using-media-path-to-populate-att-category)
 * [Export metadata](https://wordpress.org/support/topic/export-metadata)
 * As in those earlier topics, the solution to your question has two parts:
    1. Define a Custom Field mapping rule to add your `ref_offer` values to the items.
    2. Develop a small custom plugin to apply the logic required to copy the `ref_offer`
       values from the parent post/page to the items when the rule is executed.
 * You can read through the earlier topics to get a sense of the solution, but I
   will work out a specific answer to your question. Give me a day or so and I will
   post my results to this topic.
 *  Thread Starter [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064507)
 * Thank you David,
 * I’ll take a look a bit later as I’m not on my dev comp right now!!
 *  Plugin Author [David Lingren](https://wordpress.org/support/users/dglingren/)
 * (@dglingren)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064529)
 * Thanks for your patience while I worked out the details of a solution for your
   application feature. I hope you can follow the instructions below for the two
   parts of the solution.
 * First, you must create a custom field mapping rule to add the field holding a
   copy of the parent data and make it available in the Media/Assistant submenu:
    1.  Navigate to the Settings/Media Library Assistant “Custom Fields” tab.
    2.  Scroll down to the “Add a new Mapping Rule” area, since you already have the
        custom field defined and used in your parent posts/pages.
    3.  In the first dropdown box, select your field name, “ref_data”.
    4.  From the Data Source dropdown list, select “- None (select a value) -“. This
        default means the custom field will be filled by the code in your custom plugin,
        not by a data mapping rule.
    5.  In the “Existing Text” dropdown list, select “Replace”.
    6.  In the “Format” dropdown list, select “Native”.
    7.  Click the “MLA Column” check box to make the field available in the Media/Assistant
        submenu table. If you want to edit the field manually, check the “Quick Edit”
        and perhaps the “Bulk Edit” checkbox as well.
    8.  In the “Option:” dropdown list, select “Text”.
    9.  Check the “Delete NULL Values” checkbox to save database space for items with
        no parent or no `ref_data` value in the parent.
    10. Click the “Add Rule” button to save your work.
 * Next, you must install and activate a small custom plugin to perform the work.
   I have created `mla-parent-data-mapping-example.php.txt` and I will add it to
   the `/examples/` directory in my next MLA version. I have also included the full
   text of the plugin below so you can use it immediately. All of the code you need
   can be put in one place; the `mla_mapping_updates()` function. This function 
   is called once, after all of the mapping rules have been evaluated and just before
   any updates are applied to the item. Here is the complete source code:
 *     ```
       <?php
       /**
        * Copies a custom field value from the parent post/page to all attached Media Library items.
        *
        * Provides an example of the filters provided by the IPTC/EXIF and Custom Field mapping features
        *
        * @package MLA Mapping Parent Data Example
        * @version 1.00
        */
   
       /*
       Plugin Name: MLA Mapping Parent Data Example
       Plugin URI: http://fairtradejudaica.org/media-library-assistant-a-wordpress-plugin/
       Description: Copies a custom field value from the parent post/page to all attached Media Library items.
       Author: David Lingren
       Version: 1.00
       Author URI: http://fairtradejudaica.org/our-story/staff/
   
       Copyright 2015 David Lingren
   
           This program is free software; you can redistribute it and/or modify
           it under the terms of the GNU General Public License as published by
           the Free Software Foundation; either version 2 of the License, or
           (at your option) any later version.
   
           This program is distributed in the hope that it will be useful,
           but WITHOUT ANY WARRANTY; without even the implied warranty of
           MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
           GNU General Public License for more details.
   
           You can get a copy of the GNU General Public License by writing to the
           Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
       */
   
       /**
        * Class MLA Mapping Parent Data Example hooks one of the filters provided by
        * the IPTC/EXIF and Custom Field mapping features
        *
        * Call it anything you want, but give it an unlikely and hopefully unique name. Hiding
        * everything else inside a class means this is the only name you have to worry about.
        *
        * @package MLA Mapping Parent Data Example
        * @since 1.00
        */
       class MLAMappingParentDataExample {
           /**
            * Initialization function, similar to __construct()
            *
            * Installs filters and actions that handle the MLA hooks for uploading and mapping.
            *
            * @since 1.00
            *
            * @return    void
            */
           public static function initialize() {
               /*
                * The filters are only useful in the admin section; exit if in the "front-end" posts/pages.
                */
               if ( ! is_admin() )
                   return;
   
               add_filter( 'mla_mapping_updates', 'MLAMappingParentDataExample::mla_mapping_updates', 10, 5 );
           }
   
           /**
            * MLA Mapping Updates Filter
            *
            * This filter is called AFTER all mapping rules are applied.
            * You can add, change or remove updates for the attachment's
            * standard fields, taxonomies and/or custom fields.
            *
            * @since 1.00
            *
            * @param    array    updates for the attachment's standard fields, taxonomies and/or custom fields
            * @param    integer post ID to be evaluated
            * @param    string     category/scope to evaluate against: custom_field_mapping or single_attachment_mapping
            * @param    array     mapping rules
            * @param    array     attachment_metadata, default NULL
            *
            * @return    array    updated attachment's updates
            */
           public static function mla_mapping_updates( $updates, $post_id, $category, $settings, $attachment_metadata ) {
   
               // Make sure our rule is defined
               if ( 'single_attachment_mapping' == $category ) {
                   if ( ! isset( $settings['ref_offer'] ) ) {
                       return $updates;
                   }
               } elseif ( 'custom_field_mapping' == $category ) {
                   foreach ( $settings as $setting ) {
                       if ( $found_it = ( $setting['name'] == 'ref_offer' ) ) {
                           break;
                       }
                   }
   
                   if ( ! $found_it ) {
                       return $updates;
                   }
               }
   
               // Get the current value, if any, to see if a change is required
               $old_value = get_metadata( 'post', $post_id, 'ref_offer', true );
   
               // Get the item to find its parent's value, if any
               $item = get_post( $post_id );
               if ( 0 < $item->post_parent ) {
                   $parent_value = get_metadata( 'post', $item->post_parent, 'ref_offer', true );
               } else {
                   $parent_value = '';
               }
   
               // Add/replace the value if it has changed
               if ( $old_value != $parent_value ) {
                   $updates['custom_updates'][ 'ref_offer' ] = $parent_value;
               }
   
               return $updates;
           } // mla_mapping_updates
       } //MLAMappingParentDataExample
   
       /*
        * Install the filters at an early opportunity
        */
       add_action('init', 'MLAMappingParentDataExample::initialize');
       ?>
       ```
   
 * You can copy the code to a file named `mla-parent-data-mapping-example.php` and
   add it to your site’s plugins directory. The go to Plugins/Installed Plugins,
   find “MLA Mapping Parent Data Example” and activate it.
 * Once the plugin is installed and active you can update your items in any of several
   ways:
    - You can go to the Settings/Media Library Assistant Custom Fields tab and click“
      Map All Attachments” just under the “ref_offer” rule. This will apply the 
      rule to all of your items.
    - You can apply the rule to a single item by going to the Media/Edit Media page
      for the item and clicking the “Map Custom Field metadata” link in the Save
      meta box at the upper right corner of the screen.
    - You can apply the rule to several items at once using the Bulk Edit feature
      of the Media/Assistant submenu. Select the items you want by checking the 
      box to the left of the thumbnail. Select “Edit” from the “Bulk Actions” dropdown
      list, then click “Apply”. Click the “Map Custom Field metadata” button in 
      the lower-right corner of the Bulk Edit area.
 * The biggest drawback to this approach is that the `ref_offer` field will not 
   be automatically maintained as parent values change or items are attached to 
   new parents. You will have to re-run the mapping rule manually when such changes
   are made. If that’s a significant problem, code can be developed and added to
   the plugin to deal with it.
 * I hope that gets you started with a solution for your application. I am marking
   this topic resolved, but please update it if you have problems or further questions
   regarding the mapping rule, plugin or mapping options. Thank you for your interest
   in the plugin.
 *  Thread Starter [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [11 years ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064553)
 * YOU ARE AN AMAZING GURU DAVID!!!!
    Your answer is perfect (if exist)!!!
 * Everything is perfectly documented! I’ve no questions…..
 * I’ll try your implementation ASAP and post my feedback.
 *  Thread Starter [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [10 years, 11 months ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064656)
 * Hi David,
 * Finally back to this project (it took a bit more than expected!) and just implemented
   your solution….
 * Just one thing to say : PERFECT!!!
 * Regarding the the “Auto update” drawback, I’m thinking to call the filter `( '
   mla_mapping_updates', 'MLAMappingParentDataExample::mla_mapping_updates', 10,
   5 )` on post update. I’m just not sure yet on how to pass the child media’s reference
   to your filter.
 * Do you think it appropriate / efficient solution?
 * Thank you again (A LOT)!
 *  Plugin Author [David Lingren](https://wordpress.org/support/users/dglingren/)
 * (@dglingren)
 * [10 years, 11 months ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064659)
 * Thank you for your update with the good news and the kind words. I am happy to
   hear that the suggested solution is helpful.
 * Regarding the “Auto update” drawback, adding some code to the post update hooks
   is a good idea. The `mla_mapping_updates` hook is one of the last steps in a 
   much larger process, and calling it out of context isn’t likely to be helpful.
 * You may have seen the “Map Custom Field Metadata” link on the Media/Edit Media
   screen. That’s closer to what you want. You can try adding the following code
   to your post update hooks:
 *     ```
       $updates = MLAOptions::mla_evaluate_custom_field_mapping( $attachment_id, 'single_attachment_mapping' );
       if ( !empty( $updates ) ) {
           $item_content = MLAData::mla_update_single_item( $attachment_id, $updates );
       }
       ```
   
 * The `$item_content` will have messages regarding the results, if you are interested.
 * Of course, you will have to put this code in a loop that goes through each of
   the Media Library items attached to the post and sets the `$attachment_id` appropriately.
 * Let me know how that works for you. Thanks again for your interest in the plugin.
 *  Thread Starter [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [10 years, 11 months ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064662)
 * Hi David,
 * Thank you again for your support.
 * So here I’m so far with my hook :
 *     ```
       function property_updated_update_attachements_fields( $post_id ) {
       	// If this is just a revision, exit.
       	if ( wp_is_post_revision( $post_id ) ) {
       		return;
       	}
   
       	$attached_medias = get_attached_media( 'image' , $post_id );
   
       		foreach ($attached_medias as $value) {
       			$value = get_object_vars($value);
       			$attachment_id = $value[ID];
   
       		$updates = MLAOptions::mla_evaluate_custom_field_mapping( $attachment_id, 'single_attachment_mapping' );
       			if ( !empty( $updates ) ) {
       			$item_content = MLAData::mla_update_single_item( $attachment_id, $updates );
       			}
       		}
       }
       add_action( 'save_post', 'property_updated_update_attachements_fields' );
       ```
   
 * I’m actually struggling on setting up the `mla_evaluate_custom_field_mapping`
   parameters…
    I’m getting `$attachment_id` as an integer, but `$updates` remains
   desperately empty…
 * I guess that something should be done with the second parameter as per the function’s
   documentation : `category/scope to evaluate against: custom_field_mapping or 
   single_attachment_mapping`, but not sure….
 * Then I’d like to be able to filter / search the media per ref_offer, when inserting
   them in a post, but myabe I’ll post another topic regarding this.
 * Thank you again!!
 *  Plugin Author [David Lingren](https://wordpress.org/support/users/dglingren/)
 * (@dglingren)
 * [10 years, 11 months ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064663)
 * Thanks for your update with the code for “save_posts”. It makes a good addition
   to the example plugin so I have created a new version 1.01 with an adaptation
   of your idea. The new version has been uploaded to the /examples directory in
   the latest Development Version dated 20150611. The correct file name, by the 
   way, is `mla-mapping-parent-data-example.php.txt` (my earlier post had it wrong).
 * My version of your code is simplified:
 *     ```
       public static function save_post( $post_id, $post, $update ) {
           // If this is just a revision, exit.
           if ( wp_is_post_revision( $post_id ) ) {
               return;
           }
   
           // You may need to add MIME types other than 'image' for your application
           foreach ( get_attached_media( 'image' , $post_id ) as $attachment_id => $value) {
               $updates = MLAOptions::mla_evaluate_custom_field_mapping( $attachment_id, 'single_attachment_mapping' );
   
               if ( !empty( $updates ) ) {
                   $item_content = MLAData::mla_update_single_item( $attachment_id, $updates );
               }
           }
       } // save_post
       ```
   
 * The `get_object_vars` call is not necessary because `get_attached_media` returns
   everything you need. In fact, the array it returns is indexed by $attachment_id,
   so you don’t even need the values. The only possible problem with your original
   code is that `$attachment_id = $value[ID];` should be `$attachment_id = $value['
   ID'];` – you need quotes around `ID`.
 * In my testing, the `$updates` array is getting the revised `ref_offer` values
   when I edit the parent post and make changes. After I change the custom field
   value and click “Update” for the field I also click “Update” for the entire Post
   to trigger the `save_post` action.
 * Give my code a try. If it still isn’t working, let me know and I will investigate
   further.
 *  Thread Starter [Projekt43](https://wordpress.org/support/users/projekt43/)
 * (@projekt43)
 * [10 years, 11 months ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064664)
 * Thanks David!
 * Yes it’s working with your leaner & correct(!) code! =)
 * Also I had to reduce the priority from your file (V1.01 @ MLA 2.11) of the `save_post`
   filter in order to get the current value of the `ref_offer` not the previous 
   one : `add_filter( 'save_post', 'MLAMappingParentDataExample::save_post',`**`
   20`**`, 3 )`
 * Thank you again for your great support!

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

The topic ‘Adding parent's post MetaData’ is closed to new replies.

 * ![](https://ps.w.org/media-library-assistant/assets/icon-256x256.png?rev=973502)
 * [Media Library Assistant](https://wordpress.org/plugins/media-library-assistant/)
 * [Frequently Asked Questions](https://wordpress.org/plugins/media-library-assistant/#faq)
 * [Support Threads](https://wordpress.org/support/plugin/media-library-assistant/)
 * [Active Topics](https://wordpress.org/support/plugin/media-library-assistant/active/)
 * [Unresolved Topics](https://wordpress.org/support/plugin/media-library-assistant/unresolved/)
 * [Reviews](https://wordpress.org/support/plugin/media-library-assistant/reviews/)

 * 11 replies
 * 2 participants
 * Last reply from: [Projekt43](https://wordpress.org/support/users/projekt43/)
 * Last activity: [10 years, 11 months ago](https://wordpress.org/support/topic/adding-parents-post-metadata/#post-6064664)
 * Status: resolved