I'm creating a plugin and I want to get the list of all scripts and CSS used by other plugins.
This is my function:
function crunchify_print_scripts_styles() {
$result = [];
$result['scripts'] = [];
$result['styles'] = [];
// Print all loaded Scripts
global $wp_scripts;
foreach( $wp_scripts->queue as $script ) :
$result['scripts'][] = $wp_scripts->registered[$script]->src . ";";
endforeach;
// Print all loaded Styles (CSS)
global $wp_styles;
foreach( $wp_styles->queue as $style ) :
$result['styles'][] = $wp_styles->registered[$style]->src . ";";
endforeach;
return $result;
}
add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles');
I want to get the returned value inside a variable.
I tried this:
$toto = do_action( 'crunchify_print_scripts_styles' );
var_dump( $toto );
And this is my result:
NULL
If I write echo
inside every foreach
loop, I get the correct results, but how to store these values inside a variable?
[edit]
My code inside a pluginm which is not working too
/**
* Get all scripts and styles from Wordpress
*/
function print_scripts_styles() {
$result = [];
$result['scripts'] = [];
$result['styles'] = [];
// Print all loaded Scripts
global $wp_scripts;
foreach( $wp_scripts->queue as $script ) :
$result['scripts'][] = $wp_scripts->registered[$script]->src . ";";
endforeach;
// Print all loaded Styles (CSS)
global $wp_styles;
foreach( $wp_styles->queue as $style ) :
$result['styles'][] = $wp_styles->registered[$style]->src . ";";
endforeach;
return $result;
}
add_action( 'wp_head', 'wp_rest_assets_init');
/**
* Init JSON REST API Assets routes.
*
* @since 1.0.0
*/
function wp_rest_assets_init() {
$all_the_scripts_and_styles = print_scripts_styles();
if ( ! defined( 'JSON_API_VERSION' ) &&
! in_array( 'json-rest-api/plugin.php', get_option( 'active_plugins' ) ) ) {
$class = new WP_REST_Assets();
$class::$scriptsAndStyles = $all_the_scripts_and_styles;
add_filter( 'rest_api_init', array( $class, 'register_routes' ) );
} else {
$class = new WP_JSON_Menus();
add_filter( 'json_endpoints', array( $class, 'register_routes' ) );
}
}
add_action( 'init', 'wp_rest_assets_init' );
do_action
does not return a result, and besides, the action has already taken place atwp_enqueue_scripts
... easier just to create a global, eg.global $crunchifyenqueued; $crunchifyenqueued = $result;
then again call the global in your later function to access the variable.apply_filters
then? you can easily get the return value from that.