我正在创建一个插件,我想获取其他插件使用的所有脚本和CSS的列表。
这是我的功能:
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');
我想在变量中获取返回值。
我尝试了这个:
$toto = do_action( 'crunchify_print_scripts_styles' );
var_dump( $toto );
这是我的结果:
NULL
如果我echo
在每个foreach
循环中编写代码,都会得到正确的结果,但是如何将这些值存储在变量中?
[编辑]
我的插件内部的代码也无法正常工作
/**
* 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' );
apply_filters
呢?您可以轻松地从中获得返回值。
do_action
不会返回结果,此外,该操作已经在wp_enqueue_scripts
... 处发生,更容易创建一个全局变量,例如。global $crunchifyenqueued; $crunchifyenqueued = $result;
然后在以后的函数中再次调用global来访问变量。