query - add_query_arg() and empty variables inside

I have link:<a href="'.esc_url(add_query_arg(array('search' => $search, 'category' =

I have link:

<a href="'.esc_url(add_query_arg(array('search' => $search, 'category' => $category, 'filter' => $filter), '/site')).'">Click</a>

And some variables sometimes exist and sometimes don't, like $filter, which sometimes does not exist. Now I would like the variable does not exist, that it would not appear in the link, because the debugger displays the Notice "Undefined variable".

How should it be coded correctly?

I have link:

<a href="'.esc_url(add_query_arg(array('search' => $search, 'category' => $category, 'filter' => $filter), '/site')).'">Click</a>

And some variables sometimes exist and sometimes don't, like $filter, which sometimes does not exist. Now I would like the variable does not exist, that it would not appear in the link, because the debugger displays the Notice "Undefined variable".

How should it be coded correctly?

Share Improve this question asked Aug 26, 2019 at 14:04 manandmanmanandman 352 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can instantiate your array before-hand, optionally populate it, and pass it to the add_query_arg() function like so:

$url_query_args = array();

if( isset( $search ) ) {
    $url_query_args['search'] = $search;
}

if( isset( $category ) ) {
    $url_query_args['category'] = $category;
}

if( isset( $filter ) ) {
    $url_query_args['filter'] = $filter;
}

esc_url( add_query_arg( $url_query_args, '/site' ) );

Or you could loop through an array of possible query args:

$url_query_args = array();
$possible_args  = array(
    'search',
    'category',
    'filter',
);

foreach( $possible_args as $arg ) {

    if( ! isset( ${$arg} ) ) {
        continue;
    }

    $url_query_args[ $arg ] = ${$arg};

}

esc_url( add_query_arg( $url_query_args, '/site' ) );

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745211832a4616887.html

相关推荐

  • query - add_query_arg() and empty variables inside

    I have link:<a href="'.esc_url(add_query_arg(array('search' => $search, 'category' =

    4小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信