Creating a component
Heads up!
This article contains PHP code and is intended for developers. We offer this code as a courtesy, but don’t provide support for code customizations or 3rd party development.
Let’s say we want to create a “Blue Button” Component.
This component is going to display a button with dynamic text and link.
To achieve that, we are going to follow those steps:
We can restrict the component choices to the “Blue Button” component.
Assign that layout to Posts (for example).
<?php
// Get layout fields
$text = get_sub_field( 'text' );
$link = get_sub_field( 'link' );
$alignment = get_sub_field( 'alignment' );
// Component loop
while ( have_component( 'button_type' ) ):
the_component();
// Get component fields
$classes = get_sub_field( 'classes' );
$default_text = get_sub_field( 'default_text' );
?>
<div class="<?php echo $alignment; ?>">
<a href="<?php echo $link['url']; ?>" class="<?php echo $classes; ?>">
<?php echo $text ? $text : $default_text; ?>
</a>
</div>
<?php endwhile; // End component loop ?>
As you can see in the code, we have used the functions have_component( ‘your_field’ ) and the_component();.
Thanks to those functions, you can use ACF functions in the loop, in the exact same way of have_rows() and the_row().
Our home port
15 Rue Cavenne, 69007 Lyon
And from everywhere in the world thanks to Hangout and Skype !
Useful links