Using Post Objects – Advanced Custom Fields

A recent project required that the client was able to create a list of links to internal posts.

There’s a few ways this can be achieved within WordPress but, ultimately, the client required a quick and easy solution that required nothing more taxing than a few clicks.
Using Advanced Custom Fields we could simply create a text field for each element and have the client manually add relevant content. This is ok to start with but a PITA having to go back/ forth/ copy/ pasting.

The more ‘proper’ (re: easier for the client) way of building this is to use ACF Post Objects but we also needed to include this option as a repeating option.
The client also wanted a single text field for manually adding title text and to not show the div if there wasn’t any content to show.

So, the brief would be:
– Repeater – Client could add as few/ many objects as required.
– Text field for title.
– Post Objects – Easiest option for pulling in the selected content.
– If no content, don’t show the div.

The steps:
First off, create the ACF panel:

Using Post Objects - Advanced Custom Fields

On the write page, this will then give the client:
Using Post Objects - Advanced Custom Fields

Then comes the coding.
At this stage it’s best to brush up on the semantics of building repeater and post object fields – I got confused myself, which lead me to Googling for the answer, which was an arduous task, which lead me to write this tutorial.

Using Post Objects - Advanced Custom Fields

or if you just want to copy/ paste the code:

<?php if ( get_field(‘test_object_repeater’) ) { ?>

   <div>

        <?php if( get_field(‘test_object_repeater’) )

           { while(has_sub_field(‘test_object_repeater’)) { ?>

               <span><?php the_sub_field(‘test_title’); ?></span>

       <?php $post_object = get_sub_field(‘test_link’);

        if( $post_object ):

           $post = $post_object;

           setup_postdata( $post ); ?>

               <h3><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></h3>

           <?php wp_reset_postdata(); ?>

       <?php endif; }} ?>

</div>

<?php } ?>

Let’s break it down:
First we need to check if the repeater exists:
if ( get_field(‘test_object_repeater’) )

If it does exist, has it got any sub fields?
if( get_field(‘test_object_repeater’) ) { while(has_sub_field(‘test_object_repeater’))

Finally, load all the post object stuff:
$post_object = get_sub_field(‘test_link’)

We’re finding ACF more and more powerful and it helps cut time, and therefore costs, but mainly makes life so much easier for the client.

If any of the above confuses you, or you just need help with your WordPress project, get in touch.

FURTHER READING