Support

Account

Home Forums ACF PRO ACF & Widgets

Helping

ACF & Widgets

  • Hi,

    I’m trying to add ACF to a widget I have created and call it out where I need it. I have managed to create the widget and add the ACF fields to it I want, but the issue I’m having is calling those fields into the page from the widget.

    My widget (Banner Widget) uses a Post Object field called ‘Banner Locations’. This is filtering by post type (Banner, a custom post type I have created). The return format is set to Post ID.

    I can see the field within the widget I have created within the admin screens, but as I say I can’t call on the field.

    I have looked at the documentation on how to call from a widget, but it doesn’t cover the post object being used here ( http://www.advancedcustomfields.com/resources/get-values-widget/ )

    I have gone around in circles for hours, so I thought it best to layout the sort of thing I want to do.

    add_filter(‘dynamic_sidebar_params’, __NAMESPACE__ . ‘\\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 Banners widget
    if( $widget_name != ‘Banners’ ) {

    return $params;

    }

    /*
    Get the post from the widget’s post object (ACF)
    */

    /*
    Query the post type for banners
    */
    $bannerQuery = new WP_Query(array(“post_type” => “banner”, “posts_per_page” => 10, “banner_locations” => “footer_banners”));

    if ($bannerQuery) { // if there are banners for the footer then lets show them

    while ($bannerQuery->have_posts()) : $bannerQuery->the_post();

    /*
    More calls to ACF here from the post to show images text etc from repeater field
    */

    endwhile; // End the loop. Whew.

    }

    wp_reset_query();

    // return
    return $params;

    }

    Please can anyone help me?

    Thanks
    Ash

  • First thing I noticed is that you are not referencing the global $post variable. Add this at the beginning of your function:

    global $post;

    Without that, using a loop that uses the_post() will not get anything.

    The code for getting a field from a widget is:

    $my_value = get_field('field_name', 'widget_'.$widget_id);

    Getting the fields from the banner posts, because you are doing a loop, is the same as getting a field anywhere else `get_field(‘field_name’);

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘ACF & Widgets’ is closed to new replies.