How to inherit field value from parent post into in child / sub post

I have created a custom post type, called 'centres'. This CPT is hierarchical, ie, I can create child pages under each custom post.

Centre1

  • Location1
  • Contact1

Centre 2

  • Location2
  • Contact2

I've defined a custom field called phone_number. This field is populated at the 'parent' level. Ie, Centre1, Centre2.

I want to display the phone number on each child page. I don't want to have to add the phone number every time to each page, so would like to get or inherit the phone_number field from its parent.

Simply speaking, I'd like to just add the shortcode [acf field=phone_number] in any given child page (eg, contact page) and have it pull the values from it's parent.

I've searched everywhere, but can't find a solution. I'm a novice wordpress user (not a php developer). Is there code I can add into my functions.php file that can get the values of a particular field (or all fields) from the parent?

Much appreciated.

Topic advanced-custom-fields functions custom-field custom-post-types Wordpress

Category Web


You can use get_post_field( 'post_parent' ) to get the parent ID of the current post.

Whilst ACF is technically off-topic, FWIW you can pass the ID of a post as the second parameter to get_field.

Combined together we can fashion a shortcode centre_field that will return any field value for the post's parent. I've skipped the need for an attribute name as I think the shortcode looks a little cleaner...

e.g. [centre_field phone_number]

And the code behind it:

function wpse_405660_centre_field( $atts ) {
    // Just grab the first value of the attribute array
    $field_name = current( $atts );

    $parent_id = get_post_field( 'post_parent' );

    return get_field( $field_name, $parent_id );
}

add_shortcode( 'centre_field', 'wpse_405660_centre_field' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.