Passing values from a widget to a function within a plugin

First of all I can say why your code doesn’t work.

The custom css is created inside the widget function that is called by WordPress in the moment that the widget is displayed.

I guess, that you on document ready send an ajax request that call advanced_widget_pack_css() function. But every ajax request is a completely new http request that the only scope is running a function, sure not embed widget.

For this reason, the new request via ajax never call the widget() method in your widget class and so of course no css are added.

Said that, think one minute for what you are doing.

Assuming your workflow will work, it fail if user has no js enabled. And even if the the js are enabled, the page is loaded withou custom css, that should be loaded on ajax request (and Ajax in WordPress are not very fast…) so:

  • if no js no css as well
  • even if js page load with no css, so you have unstyled widget for a
    second or more
  • browser are not allowed to cache the css

So your code does’t work (an I explained yopu why) but even if you find a way to make it works is not a great solution.

What can be a solution?

First of all in the widget isolate the function that generates the custom css.

After that, you should call the function not on the widget() method but on the update method. In this way the css is generated everytime the widget is updated, and you can save the newly generated css to store it in a css file.

As a good practise is better saving this file in the uploads folder, because you are sure that folder is writable from WP.

Pseudo code:

class Advanced_Widget_Pack_Widget_Archives extends WP_Widget {

   function generate_css( $instance ) {
     // some code here to generate css from instance arguments...
     return $sc_css;
   }

   function update( $new_instance, $old_instance ) {
     // some code here to update the widget instance...
     $css = $this->generate_css( $new_instance );
     $upload_dir = wp_upload_dir();
     $path = $upload_dir['basedir'] . '/myplugin/myplugin-customwidget.css';
     if ( ! file_exists($upload_dir['basedir'] . '/myplugin') )
       mkdir($upload_dir['basedir'] . '/myplugin');
     file_put_contents($path, $css);
   }

}

After that, you can enqueue the file just created using WordPress standard way…

Alternative to this method is generate the css in the widget() method (as you are already doing) and just output as inline style in the markup.