1

I come from Drupal 8, where I am used to template files for each entity (piece of data). As far as I understood in WP every page template does look after it's own content via theming it via code that sits in the (page / post) tpl file itself.

I believe there must be a nicer way to theme an "ACF Flexible Field" than duplicating my template code into each page tpl the field maybe could be outputted in.

Can I define "one" tpl file that is used for every output instead?

Are there any Objects? Or inc's that I can create to deal with the field? I understand that putting all the code into each page tpl makes it easy... but its also very static and it produces double code.

3 Answers 3

2

And to add to previous answers, you can not only use get_template_part, but also use it's second param and combine it with ACFs get_row_layout.

So let's say that somewhere in your template is:

<?php while ( have_posts() ) : the_post(); ?>
<article>
    ... SOME CODE

    <?php while ( have_rows( 'YOUR_FIELD_NAME' ) ) : the_row(); ?>
    ... HERE SHOULD GO THE CODE FOR ACF FIELD
    <?php endwhile; ?>

    ... SOME OTHER CODE
</article>
<?php endwhile; ?>

You can change it to:

<?php while ( have_posts() ) : the_post(); ?>
<article>
    ... SOME CODE

    <?php
        while ( have_rows( 'YOUR_FIELD_NAME' ) ) :
            the_row();
            get_template_part( 'block', get_row_layout() );

        endwhile;
    ?>

    ... SOME OTHER CODE
</article>
<?php endwhile; ?>

Then you can create your custom templates named: block.php (it will be used as fallback), block-layout_1.php (it will be used for layout called "layout_1", and so on.

2
  • fantastic answer. Exactly what I was after for. Thanks
    – mogio
    Commented Jun 8, 2018 at 12:39
  • I'm glad it was helpful :) Commented Jun 8, 2018 at 12:40
1

You can include template partials via get_template_part(). You can pass variables to template parts via set_query_var().

1

WordPress allows you to chop up template files into chunks that then can be included into the main template using get_template_part. So you could isolate your template for the ACF-field in a separate file and call that from any other template.

Beware that it is not directly possible to pass variables from the main template to the template part, though there are bypasses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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