最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Can I make get_users() query global?

programmeradmin0浏览0评论

I have the following query

$args = [
        'meta_key' => 'mycred_default',
        'orderby'  => [ 'meta_value_num' => 'DESC' ],
        'order'    => 'desc',
        'number' => 10
];

$users = get_users( $args );

Can I make it global to access the parameters from an ajax function?

I have the following query

$args = [
        'meta_key' => 'mycred_default',
        'orderby'  => [ 'meta_value_num' => 'DESC' ],
        'order'    => 'desc',
        'number' => 10
];

$users = get_users( $args );

Can I make it global to access the parameters from an ajax function?

Share Improve this question asked Jan 5, 2021 at 18:03 Giselle BoyerGiselle Boyer 1 4
  • Hi, Giselle, welcome to WPSE. It is not clear what you mean exactly. Depending on what you want to achieve you could either define the parameters of the query as a global using $GLOBALS['varname'], or send the parameters in the ajax response or other strategy. – Celso Bessa Commented Jan 5, 2021 at 19:06
  • Hi @CelsoBessa, thank you! I wanna get the number because the idea is that it will be updated each time ajax is executed. I have been saving the parameters I need inside wp_localize_script(), can I access $GLOBALS['varname'] inside this function? – Giselle Boyer Commented Jan 5, 2021 at 19:15
  • Global variables are usually the last choice when it comes to working with variables inside PHP - you could use either a function or a WordPress specific filter to store, update and retrieve the variable. – Q Studio Commented Jan 5, 2021 at 20:23
  • @QStudio hi! I'm sorry if this is too obvious, but please could you explain to me how a filter would work for this? – Giselle Boyer Commented Jan 5, 2021 at 21:39
Add a comment  | 

1 Answer 1

Reset to default 1

You can use the WordPress functions apply_filters and add_filters to store and retrieve data, like so:


// The filter callback function.
function so_wp_380975_get_user_args( $array ) {
    
    // (maybe) modify $array.

    // for now, we just return the array
    return [
        'meta_key' => 'mycred_default',
        'orderby'  => [ 'meta_value_num' => 'DESC' ],
        'order'    => 'desc',
        'number' => 10
    ];

}
add_filter( 'get_user_args', 'so_wp_380975_get_user_args', 10, 1 );

// get the stored args from the filter
$args = apply_filters( 'get_user_args', [] );

Note that you can do a lot more, such as passing additional arguments to the filter to modify the args - or a default value, in case the filter returns nothing.

https://developer.wordpress/reference/functions/apply_filters/

发布评论

评论列表(0)

  1. 暂无评论