Get values from a widget

Last updated Mar 25, 2015

Overview

All the template functions (get_field, the_field, etc) can be used to load values from a widget, however, a second parameter is required to target the term. This is similar to passing through a $post_id parameter to target a specific post object.

The $post_id parameter needed is a string containing the the word ‘widget_’ and the widget’s ID in the following format; "widget_{$widget_id}"

To display custom field values within a widget, you will need to use a filter to modify the HTML arguments. If the widget is custom made, you can also customize the HTML output within the widget function in your widget class.

Requirements

Custom fields for comments requires at least ACF version 5

Examples

Basic parameter use

This example shows how the second parameter is used to target the specific comment.

<p><?php the_field('field_name', 'widget_' . $widget_id); ?></p>

Basic widget customization

This example shows how to customize the ‘Text’ widget to display with a background color and show an image. Because widgets do not yet contain actions or callbacks to add extra HTML, we must use a filter (dynamic_sidebar_params) to modify the before_widget and after_widget HTML.

The following code is placed in the functions.php file.

add_filter('dynamic_sidebar_params', 'my_dynamic_sidebar_params');

function my_dynamic_sidebar_params( $params ) {
    
    // get widget vars
    $widget_name = $params[0]['widget_name'];
    $widget_id = $params[0]['widget_id'];
    
    
    // bail early if this widget is not a Text widget
    if( $widget_name != 'Text' ) {
        
        return $params;
        
    }
    
    
    // add color style to before_widget
    $color = get_field('color', 'widget_' . $widget_id);
    
    if( $color ) {
        
        $params[0]['before_widget'] .= '<style type="text/css">';
        $params[0]['before_widget'] .= sprintf('#%s { background-color: %s; }', $widget_id, $color);
        $params[0]['before_widget'] .= '</style>';
        
    }
    
    
    // add image to after_widget
    $image = get_field('image', 'widget_' . $widget_id);
    
    if( $image ) {
        
        $params[0]['after_widget'] = '<img src="' . $image['url'] . '">' . $params[0]['after_widget'];        
    }

    
    // return
    return $params;

}

Related