admin管理员组

文章数量:1415664

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' ) );

本文标签: queryaddqueryarg() and empty variables inside