Skip to content

Instantly share code, notes, and snippets.

@mikeoberdick
Created August 20, 2016 13:28
Show Gist options
  • Save mikeoberdick/22dec3452614dd6d28cb903ca53f2e1b to your computer and use it in GitHub Desktop.
Save mikeoberdick/22dec3452614dd6d28cb903ca53f2e1b to your computer and use it in GitHub Desktop.
How to register an ACF widget area in WordPress
//The ACF widget
class ACF_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'acf_widget', // Base ID
'Work Logos', // Name
array( 'description' => 'Display your work experience.', ) // 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'];
}
$wid = 'widget_' . $args["widget_id"];
if( have_rows('job', $wid) ): ?>
<div class="jobs">
<?php while ( have_rows('job', $wid) ) : the_row(); ?>
<a href = "<?php the_sub_field("website"); ?>" alt = "<?php the_sub_field("name"); ?>"><img src="<?php the_sub_field("logo"); ?>" /></a>
<?php endwhile; ?>
</div>
<?php endif;
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.
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // class ACF_Widget
// register ACF_Widget widget
add_action( 'widgets_init', function(){
register_widget( 'ACF_Widget' );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment