Skip to content

Instantly share code, notes, and snippets.

@ControlledChaos
Created December 28, 2016 22:00
Show Gist options
  • Save ControlledChaos/6e1635643d3a3dbde9a0402b28110a88 to your computer and use it in GitHub Desktop.
Save ControlledChaos/6e1635643d3a3dbde9a0402b28110a88 to your computer and use it in GitHub Desktop.
Merge an array of query variables with an existing WordPress query.

Merge Query Variables

WordPress Snippet

I was tasked with alphabetizing the archive of a custom post type using an off-the-shelf theme. The theme's archive.php file used the global variable global $wp_post to set the query.

The example here was placed in a custom post type archive (archive-example.php) following the global variable to merge with the default query. One can use this with any of the query variables.

<?php
// Default query
global $wp_post;
// Merge with default query
$args = array_merge( $wp_query->query_vars, array( 'orderby' => 'title', 'order' => 'ASC' ) );
query_posts( $args );
?>
@perrelet
Copy link

perrelet commented Jun 12, 2023

Note: This will fail for meta_query and tax_query. Also arrays such as tag_slug__and should be merged + special values such as any for post_type need to be handled correctly. For these you need something like:

    function merge_query_vars ($query_vars, $query) {

        if ($query_vars) foreach ($query_vars as $key => $value) {

            if (isset($query->query_vars[$key]) && ($existing_value = $query->query_vars[$key])) {

                switch ($key) {

                    case 'post_type':
                    case 'post_status':
    
                        if (($value == 'any') || ($existing_value == 'any')) {

                            $value = 'any';
                            break;

                        }

                        if (!is_array($value)) $value = [$value];
                        if (!is_array($existing_value)) $existing_value = [$existing_value];

                        $value = array_merge($existing_value, $value);
                        break;
    
                    case 'tax_query':
                    case 'meta_query':

                        $value = array_merge($existing_value, $value);
                        break;

                    default:

                        if (is_array($value) && is_array($existing_value)) $value = array_merge($existing_value, $value);
                    
                }

            }

            $query->query_vars[$key] = $value;

        }

        return $query;

    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment