Skip to content

Instantly share code, notes, and snippets.

@haraldmartin
Forked from carlodaniele/custom-queries.php
Created January 31, 2018 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haraldmartin/6a22ebbd6f0476485486c59b859f4e4f to your computer and use it in GitHub Desktop.
Save haraldmartin/6a22ebbd6f0476485486c59b859f4e4f to your computer and use it in GitHub Desktop.
An example plugin showing how to add custom query vars, rewrite tags and rewrite rules to WordPress
<?php
/**
* @package Custom_queries
* @version 1.0
*/
/*
Plugin Name: Custom queries
Plugin URI: http://wordpress.org/extend/plugins/#
Description: This is an example plugin
Author: Carlo Daniele
Version: 1.0
Author URI: http://carlodaniele.it/en/
*/
/**
* Register custom query vars
*
* @param array $vars The array of available query variables
*
* @link https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars
*/
function myplugin_register_query_vars( $vars ) {
$vars[] = 'city';
return $vars;
}
add_filter( 'query_vars', 'myplugin_register_query_vars' );
/**
* Add rewrite tags and rules
*
* @link https://codex.wordpress.org/Rewrite_API/add_rewrite_tag
* @link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule
*/
/**
* Add rewrite tags and rules
*/
function myplugin_rewrite_tag_rule() {
add_rewrite_tag( '%city%', '([^&]+)' );
add_rewrite_rule( '^city/([^/]*)/?', 'index.php?city=$matches[1]','top' );
// remove comments and customize for custom post types
// add_rewrite_rule( '^event/city/([^/]*)/?', 'index.php?post_type=event&city=$matches[1]','top' );
}
add_action('init', 'myplugin_rewrite_tag_rule', 10, 0);
/**
* Build a custom query
*
* @param $query obj The WP_Query instance (passed by reference)
*
* @link https://codex.wordpress.org/Class_Reference/WP_Query
* @link https://codex.wordpress.org/Class_Reference/WP_Meta_Query
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
*/
function myplugin_pre_get_posts( $query ) {
// check if the user is requesting an admin page
// or current query is not the main query
if ( is_admin() || ! $query->is_main_query() ){
return;
}
// remove comments if you want to retrieve a specific post type
/*
if ( !is_post_type_archive( 'event' ) ){
return;
}
*/
$city = get_query_var( 'city' );
// add meta_query elements
if( !empty( $city ) ){
$query->set( 'meta_key', 'city' );
$query->set( 'meta_value', $city );
$query->set( 'meta_compare', 'LIKE' );
}
}
add_action( 'pre_get_posts', 'myplugin_pre_get_posts', 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment