php 一个示例插件,显示如何向WordPress添加自定义查询变量,重写标记和重写规则

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 一个示例插件,显示如何向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 );

以上是关于php 一个示例插件,显示如何向WordPress添加自定义查询变量,重写标记和重写规则的主要内容,如果未能解决你的问题,请参考以下文章

PHP 自定义屏幕示例(向wordpress管理员添加新菜单)

如何编码 WordPress 插件软件更新?

如何在 Wordpress 插件中加载 Javascript

PHP Wordpress:显示所有活动插件

Wordpress中如何根据坐标显示用户?

PHP WordPress短代码:仅向注册用户显示内容