Display ACF field(s) from widget in FE

admin2025-06-03  6

I have a problem with displaying ACF fields that I've connected with a custom created widget. Here what I have so far. I've registered a sidebar

function myfunction_init() {
register_sidebar( array(
    'name'          => esc_html__( 'Sidebar', 'adfas' ),
    'id'            => 'sidebar-1',
    'description'   => esc_html__( 'Add widgets here.', 'adfas' ),
    'before_widget' => '<section id="%1$s" class="widget %2$s">',
    'after_widget'  => '</section>',
    'before_title'  => '<h2 class="widget-title">',
    'after_title'   => '</h2>',
) ); 
} 
add_action( 'widgets_init', 'myfunction_init' );

Then I've created a custom widget

if(!class_exists('HeroWidget')) {

class HeroWidget extends WP_Widget {

    public function __construct() {
        $widget_ops = array(
            'classname' => 'hero_widget',
            'description' => 'Hero Widget built with ACF Pro',
        );
        parent::__construct( 'hero_widget', 'Hero Widget', $widget_ops );
    }

    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 get_field('title', 'widget_' . $args['widget_id']);


        // BEGIN ACF CODE
            echo get_field('pricecalc_form');
        // END ACF CODE


        echo $args['after_widget'];
    }

    public function form( $instance ) {
        if ( isset($instance['title']) ) {
            $title = $instance['title'];
        }
        ?>
        <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
    }

    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';

        return $instance;
    }

}
}
function register_widgets()
{
register_widget( 'HeroWidget' );
}
add_action( 'widgets_init', 'register_widgets' );

And after that I wanted to output the content with

<?php dynamic_sidebar( 'sidebar-1' ); ?>

But I don not get any content displayed on FE. Any idea where I went wrong?

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748931467a314923.html

最新回复(0)