JCHASE11
JCHASE11

Reputation: 3941

Wordpress show parents content on child page using custom loop

I created a hierarchical custom post type called "films." It is hierarchical so it can have children elements.

I am using a conditional statement in my single-films.php to show different content for the parent page from the children pages like so:

<?php while(have_posts()) : the_post(); ?>

<?php if( $post->post_parent != 0 ) {
    echo "Child Page";
} else {
    echo "Film Page";
} ?>
<?php endwhile; ?>

In the condition that the page is a child, I want to use the values entered on the parents page, not the child page. Because the loop has already been created, I need to figure out a way to pull content from the parent page JUST on the children pages. I need it to pull any content I wish (custom field, title, featured image, etc) from it's parent. Any idea how I can modify this loop to pull content from it's parent?

Upvotes: 0

Views: 2954

Answers (2)

Adewale George
Adewale George

Reputation: 279

I know this is a bit late but yeah it does work with the ACF but it only fetches you the thumbnail(cropped image). To get the the exact full image you will need to modify the code a bit.

<?php
$image = wp_get_attachment_image_src(get_post_meta($post->post_parent, 'custom-field-key', true), 'full');
echo '<img src="' . $image[0] . '" />';
?>

have fun.

Just thinking this might help someone in the future.

Upvotes: 1

sbstjn
sbstjn

Reputation: 2214

Wordpress has a nice get_post function, you can use it like this to get the parent's title for example:

<?php 

if ($post->post_parent != 0) {
  $parent = get_post($post->post_parent); 
  echo $parent->post_title;
} ?>

You can access any custom field by its key/name and the parent's post id:

<?php

$image = wp_get_attachment_image_src(get_post_meta($post->post_parent, 'custom-field-key', true));
echo '<img src="' . $image[0] . '" />';
?>

This works for sure with the Advanced Custom Fields Plugin for Wordpress.

Upvotes: 4

Related Questions