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

query - add_query_arg() and empty variables inside

programmeradmin0浏览0评论

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' ) );
发布评论

评论列表(0)

  1. 暂无评论