I am creating my own widget. I need to use custom css and js files. I have used wp_register_style`wp_enqueue_styleandwp_register_script\wp_enqueue_script` functions in order to register custom styles and scripts.

I implemented this in following way.

function __construct() {
        // parent constructor
        add_action( 'wp_enqueue_scripts',array( $this,'init_widget'));

public function init_widget() {
    wp_register_style( 'accordion-category-style', plugins_url('accordion-category-style.css', __FILE__) );
    wp_enqueue_style( 'accordion-category-style' );
    // Register the script like this for a plugin:
    wp_register_script( 'accordion-category-script', plugins_url( 'accordion-categories.js', __FILE__ ) );
    wp_enqueue_script( 'accordion-category-script' );

And this works perfectly, but one problem that these files are included on each page of the site.

But I only need to include on page where my widget is visible. Is it possible to achieve such behavior ?


I tried to use solution suggested by @jdm2112 , but I used not the accepted answer from his link but just checking inside widget method like this and this works

public function widget( $args, $instance ) {
    if ( is_active_widget(false, false, $this->id_base,true) ) {

One issue is this adds scripts in the middle of html page not at the top.