developer-blog-content icon indicating copy to clipboard operation
developer-blog-content copied to clipboard

Tutorial: When you need query vars

Open bph opened this issue 11 months ago • 0 comments

Discussed in https://github.com/WordPress/developer-blog-content/discussions/358

Originally posted by OlaIola December 9, 2024 I found out that the idea of query vars is difficult to grasp, and even experienced developers have difficulties with it. I tried to explain the correct usage with the following example from the core but didn't succeed. So, hopefully, there is someone who can explain it better.

add_rewrite_tag( '%sitemap%', '([^?]+)' );
add_rewrite_rule( '^wp-sitemap\.xml$', 'index.php?sitemap=index', 'top' );
add_rewrite_rule(
	'^wp-sitemap-([a-z]+?)-(\d+?)\.xml$',
	'index.php?sitemap=$matches[1]&paged=$matches[2]',
	'top'
);

// Some other place
if ( get_query_var( 'sitemap' ) ) { 
	$sitemap = sanitize_text_field( get_query_var( 'sitemap' ) );
// ... 
}

So, it looks like this idea needs more explanation about its usage and when it is just unnecessary haste.

Example I have:

file1.php

<?php

const ACTIONS_FEATURED_QUERY = 'actions_featured';
const ACTIONS_FEATURED_QUERY_ENABLED = true;

add_filter( 'query_vars', 'actions_add_query_vars' );
add_action( 'pre_get_posts', 'actions_modify_featured_query' );

function actions_add_query_vars( $vars ) {
	$vars[] = ACTIONS_FEATURED_QUERY;

	return $vars;
}

function actions_modify_featured_query( WP_Query $query ): void {
	if ( ! actions_is_featured_query( $query ) ) {
		return;
	}

	$meta_query = [
		'relation' => 'AND',
		[
			ACTION_FEATURED_META . '_clause' => [
				'key'     => ACTION_FEATURED_META,
				'compare' => '=',
				'type'    => 'NUMERIC',
				'value'   => 1,
			],

			ACTION_FEATURED_PRIORITY_META . '_clause' => [
				'key'     => ACTION_FEATURED_PRIORITY_META,
				'compare' => 'EXISTS',
				'type'    => 'NUMERIC',
			],

			ACTION_START_META . '_clause'    => [
				'key'     => ACTION_START_META,
				'compare' => 'EXISTS',
				'type'    => 'NUMERIC',
			],
			[
				'key'     => ACTION_FINISH_META,
				'value'   => wp_date( 'Ymd' ),
				'compare' => '>=',
			],
		]
	];

	$orderby = [
		ACTION_FEATURED_PRIORITY_META . '_clause' => 'DESC',
		ACTION_START_META . '_clause'             => 'ASC',
	];

	$query->set( 'post_type', CPT_ACTIONS );
	$query->set( 'posts_per_page', -1 );
	$query->set( 'meta_query', $meta_query );
	$query->set( 'orderby', $orderby );
}

file2.php

<?php
//
function actions_is_featured_query( WP_Query $query ): bool {
	return ACTIONS_FEATURED_QUERY_ENABLED === $query->get( ACTIONS_FEATURED_QUERY );
}

function actions_get_featured(): array {
	$query = new WP_Query(
		[
			ACTIONS_FEATURED_QUERY => ACTIONS_FEATURED_QUERY_ENABLED,
		]
	);

	return $query->have_posts() ? $query->posts : [];
}

bph avatar Jan 09 '25 14:01 bph