1

I want to build a widget by which various social media sharing buttons can be added to front end. In the widget form there will be many checkboxes for social media. Since these sharing buttons require different scripts or html tags I have to enqueue it from back end. While enqueueing I have to check which checkbox(s) are selected. But how can I get those values from outside of my widget class? Say my code is as follows:

<?php
 
class My_Widget extends WP_Widget {
 
    public function __construct() {
        // some stuff goes here
    }

    
 
    public function form( $instance ) {
?>
<label for="<?php echo $this->get_field_name( 'facebook' ); ?>">Facebook</label>
<input type="checkbox" id="<?php echo $this->get_field_id( 'facebook' ); ?>" name="<?php echo $this->get_field_name( 'facebook' ); ?>" value="facebook">
<br>
<label for="<?php echo $this->get_field_name( 'twitter' ); ?>">Twitter</label>
<input type="checkbox" id="<?php echo $this->get_field_id( 'twitter' ); ?>" name="<?php echo $this->get_field_name( 'twitter' ); ?>" value="twitter">
   <?php 
/* And I also take some input such an icon image
 that will be used to render widget in front end */
}
 public function widget( $args, $instance ) {
        /* Here I render widget output
such as social icon. But I also have to enqueu
some scripts(based on what user selected/checked)
 some maybe should be added just after 
opening body tag or in head and some may be
 in footer. In footer it can be added from here 
but in head or after opening body tag
 it cannot be because it is too late 
 */
    }
    public function update( $new_instance, $old_instance ) {
        // saving process goes here
    }
}
 
?>
3
  • 1
    You should be able to check which ones are set when you're loading your widget output. The key is to register all of your scripts normally using wp_register_script() but then enqueue them using wp_enqueue_script() within the widget's output using conditional if() checks. Provide your widget code and it'll be a lot easier for someone to help you. Feb 8 at 0:49
  • @Djukic Sample code aded Feb 8 at 7:28
  • Where's the public output? All you have there is a comment? Feb 8 at 13:49
0

Actually these types of task is for plugin not for widget. Based on the value of widget instance scripts can be enqueued to footer not in head or just after body tag. Reason behind this is the instance value can be checked inside the function widget of widget class. The function widget is called when a certain dynamic sidebar is called and this must occurs when wp_head() and wp_body_open hook is already fired but still there is a chance to enqueue scripts to footer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.