Updating custom query var with multiple values

I'm using set_query_var to bookmark snippets that were already published, in order to exclude them from other independent loops on the page. Basically, so that no title ever comes up twice.

Basically something like...

set_query_var('exclude', $post-ID);

...and later...

'post__not_in' = get_query_var('exclude');

The problem is that the function updates the field every time, so if I run it in a loop it would become next to useless.

So I came up with this function:

function update_query_var($name,$value) {
    $oldvalue = get_query_var($name);
    if(is_array($value)) {
        $newvalue = array_merge($oldvalue,$value);
        } else {
        $newvalue = $oldvalue . ',' . $value;
    }
    set_query_var($name, $newvalue);
}

Which does the job, appending the new values to the old every time, but I'm not sure if it doesn't break something or if there's a performance hit, with its dozens of iteration on a page. I feel that I'm missing something here, so before pushing this into production I have some questions:

Is this good practice?

Is there a native way to do it?

Is there a better approach?

Topic functions variables wp-query Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.