Problem: I have a View of child posts that I would like to filter by the value of a custom field on their parent post.
Solution: There's not a good way to filter based on parent post custom fields, so it's necessary to automatically set a custom field on the child post to match the field on its parent. You can use the following code:
function copy_parent_gender_field ( $post_id ) { // when parent narrator post type is saved, copy its gender field to child audio posts $post_type = get_post_type( $post_id ); if ( $post_type == 'narrator' ) { $gender = get_post_meta( $post_id, 'wpcf-gender', true ); $audio_args = array( 'numberposts' => -1, 'post_type' => 'audio-sample', 'meta_query' => array( 'relation' => 'AND', array( 'key' => '_wpcf_belongs_narrator_id', 'value' => $post_id, 'compare' => '=', 'type' => 'NUMERIC' ) ) ); $audios = get_posts( $audio_args ); foreach( $audios as $audio ) { update_post_meta( $audio->ID, 'wpcf-gender', $gender ); } } } add_action( 'save_post', 'copy_parent_gender_field', 100 );
Relevant Documentation:
https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
https://developer.wordpress.org/reference/functions/get_post_meta/
https://codex.wordpress.org/Function_Reference/update_post_meta
Everyone can read this forum, but only Toolset clients and people who registered for Types community support can post in it.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 17 replies, has 2 voices.
Last updated by taih 6 years, 7 months ago.
Assisted by: Christian Cox.
The forum ‘Types Community Support’ is closed to new topics and replies.