Reputation: 3978
I'm displaying a list of sibling pages using the below code. As well as retrieving the page title and link. I need to grab a custom field called excerpt
and output it for each sibling item. How do I do this using get_pages
? Currently the var_dump I'm using is grabbing the current pages excerpt, which is incorrect.
<?php
global $post;
if ( is_page() && $post->post_parent ) {
$children = get_pages('child_of='.$post->ID);
$parent = $post->post_parent;
$our_pages = get_pages('child_of='.$parent.'&exclude='.$post->ID);
$ex = get_field('excerpt', $our_pages);
if (!empty($our_pages)):
foreach ($our_pages as $key => $page_item):
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" title="<?php the_title(); ?>">
<?php echo $page_item->post_title ; ?>
<?php var_dump($ex) ?>
<?php endforeach;
endif;
}
UPDATE
Ok so I have put in <?php print_r($page_item); ?>
as suggested and it has returned the following:
I don't see any of my ACF fields here, so how do I retrieve those? What are my next steps?
Upvotes: 1
Views: 2685
Reputation: 181
I've got the same problem with AFC and get_pages().
Try to access ACF fields by retrieving all posts by page type.
$args = array(
'post_type' => 'page',
'numberposts' => -1, // Accepts -1 for all. Default 5.
);
$pages = get_posts($args);
Now ACF get_field('excerpt');
function will work, because get_pages() doesn't return all needed data.
If you'd like to get specific pages like siblings you could pass theirs id's as get_posts() 'include'
argument (arr).
Read more about get_posts()
in documentation.
Upvotes: 0
Reputation: 2928
You full code like below:
<?php
global $post;
if ( is_page() && $post->post_parent ) {
$children = get_pages('child_of='.$post->ID);
$parent = $post->post_parent;
$our_pages = get_pages('child_of='.$parent.'&exclude='.$post->ID);
$ex = get_field('excerpt', $our_pages);
if (!empty($our_pages)):
foreach ($our_pages as $key => $page_item):
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" title="<?php the_title(); ?>">
<?php echo $page_item->post_title ; ?>
<?php echo get_post_meta( $page_item->ID, 'excerpt', true); ?>
<?php endforeach;
endif;
}
If you didn't get the data like above then change you custom filed name with any other name and then try.
Upvotes: 1
Reputation: 27092
You should be using the_field()
, or echo get_field()
, within your forloop, and should pass the post ID as the second parameter of the function:
if (!empty($our_pages)):
foreach ($our_pages as $key => $page_item):
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" title="<?php the_title(); ?>">
<?php echo $page_item->post_title ; ?>
<?php the_field('excerpt', $page_item->ID); ?>
</a>
<?php endforeach;
endif;
You can read more about how get_field()
works, in the documentation.
Upvotes: 2