Last active
January 23, 2024 01:35
-
-
Save carlodaniele/1ca4110fa06902123349a0651d454057 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
Obrigado!