I have Post Object field set up for pages. What I want to do is to output title of the posts associated with the page as a class of the div surrounding the page listing. But, the code inside the foreach loop is not being executed. I've tried with setup_postdata($post) and without, per ACF documentation, the result is always the same.

Here is the code:

function pages() {
$args = array(
    'post_type' => 'page'
$pages = get_posts($args);
    foreach ($pages as $page) {?>
        <div class=" <?php 
            $ancestors = get_field('ancestor');
                foreach ($ancestors as $ancestor) {
                    $class_ancestor_raw = get_the_title($ancestor->ID);
                    $class_ancestor_temp = explode(' ', $class_ancestor_raw);
                    $class_ancestor_str = implode('-', $class_ancestor_temp);
                    $class_ancestor = strtolower($class_ancestor_str);
                    echo $class_ancestor;

            <?php echo $page->post_title; ?>
    <?php } ?> 

  • Just double checking, but you have the 'ancestor' post object field set up as a multi-select, correct? Otherwise the foreach won't do anything. – socki03 Feb 7 '14 at 15:45
  • yes it's multiselect – Bojana Šekeljić Feb 7 '14 at 15:46
  • 1
    Are you attempting to select the ancestor for each page? because it looks like you're missing the "$page->ID" on the get_field function $ancestors = get_field('ancestor', $page->ID); – socki03 Feb 7 '14 at 15:52
  • 1
    that's it! thank you, if you post it as an answer i ll accept it as @Milo posted the answer after your comment. thanks! – Bojana Šekeljić Feb 7 '14 at 16:07

Looks like you're missing the $page->ID from the get_field function.

$ancestors = get_field('ancestor', $page->ID);

You don't pass the page ID to get_field, so you're trying to fetch ancestor for the page you have this code on, not the pages within your foreach.

$ancestors = get_field('ancestor', $page->ID);

You can also simplify your code with the sanitize_title function-

$class_ancestor = sanitize_title( get_the_title($ancestor->ID) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.