Creating a custom widget with Advanced Custom Fields Pro in WordPress
- Create a custom widget (check the example code in WordPress docs)
- Install the awesome Advanced Custom Fields Pro plugin (you need to buy the Pro version because the free one doesn’t provide the widget support)
- Add some custom fields (in this example: text_field and image_field) with ACF and assign them to the custom widget
- Go back to the widget code and add in the function
widget
the fields you want to show in the frontend. Done.
Here is the whole code (you only need to paste it in your functions.php
):
/**
* Adds custom widget.
*/
class Custom_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'custom_widget', // Base ID
__('Custom Widget Title', 'text_domain'), // Name
array( 'description' => __( 'This is a custom widget', 'text_domain' ), ) // Args
);
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
echo $args['before_widget'];
if ( !empty($instance['title']) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
}
echo "<h1>Text field</h1>";
echo get_field('text_field', 'widget_' . $args['widget_id']);
echo "<h1>Image</h1>";
$image = get_field('image_field', 'widget_' . $args['widget_id']);
$image_url = $image['sizes']['thumbnail'];
echo "<img src='". $image_url ."' />";
echo $args['after_widget'];
}
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
public function form( $instance ) {
if ( isset($instance['title']) ) {
$title = $instance['title'];
}
else {
$title = __( 'New title', 'text_domain' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // class Custom_Widget
// register Custom_Widget widget
add_action( 'widgets_init', function(){
register_widget( 'Custom_Widget' );
});
-
Huw Rowlands
-
Mike Oberdick