Enqueue script/style if certain widget has certain value

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
    }
}
 
?>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x