add rewrite_rules in WordPress custom plugin - wordpress

i try to short url of my custome page that in my-pugin
when i use my custom page i will url like bellow
http://localhost/wordpress/wp-content/plugins/my-plugin/testurl.php
but i want this
http://localhost/wordpress/testurl
i write this code in my plugin
function create_rewrite_rules($rules) {
//print_r($rules);
global $wp_rewrite;
$newRule = array('/testurl' => 'wp-content/plugins/my-plugin/testurl.php');
//echo $newRule;
$newRules = $newRule + $rules;
//$newRules = $newRule;
// echo "<pre>";
// print_r($newRules);
return $newRules;
}
function flush_rewrite_rules() {
//echo 1;
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
if(class_exists('MyPlugin'))
$myPlugin = new MyPlugin();
add_filter('rewrite_rules_array', array($myPlugin, 'create_rewrite_rules'));
add_filter('init', array($myPlugin, 'flush_rewrite_rules'));
but it cant help.

There's a few things you have to pay attention to :
You have to flush the rewrite rules only on plugin activation/deactivation, not on init, in order to prevent performance issues.
The rewrite_rule first parameter must be a regex.
The init hook is an action, not a filter.
Below plugin code does work :
<?php
/*
Plugin Name: Rewrite test
*/
function custom_rewrite_basic() {
add_rewrite_rule('^testurl?', 'wp-content/plugins/my-plugin/testurl.php', 'top');
}
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
register_activation_hook( __FILE__, 'myplugin_flush_rewrites' );
function myplugin_flush_rewrites() {
custom_rewrite_basic();
flush_rewrite_rules();
}
Hope this will help.

Related

Error with wp_redirect

I want to redirect admin users to a maintenance page (https://mysite/maintenance/), but firefox tells me the redirection is not correctly made
add_action( 'template_redirect', 'custom_redirect' );
function custom_redirect()
{
if (current_user_can('administrator')) {
wp_redirect( home_url('/maintenance/') );
exit;
}
}
Have you an idea ?
You should be using the template_include filter for this:
add_filter('template_include', 'wpse_44239_template_include', 1, 1);
function wpse_44239_template_include($template){
if (current_user_can('administrator')) {
wp_redirect( home_url('/maintenance/') );
exit;
}
return $template;
}
template_redirect is the action called directly before headers are sent for the output of the rendered template. It's a convenient hook to do 404 redirects, etc... but shouldn't be used for including other templates paths as WordPress does this innately with the 'template_include' filter.
template_include and single_template hooks deal ONLY with the path of the template used for rendering the content. This is the proper place to adjust a template path.
What is the specific error Firefox is reporting? Sounds like it could be an infinite redirect loop. I would suggest adding a check to make sure you're not already on the maintenance page, ie:
add_action( 'template_redirect', 'custom_redirect' );
function custom_redirect()
{
if (current_user_can('administrator'))
{
global $wp;
$current_url = home_url( $wp->request );
$position = strpos( $current_url , '/maintenance/' );
if ($position===FALSE) {
wp_redirect( home_url('/maintenance/') );
exit;
}
}
}

Add custom frontend page without menu item - wordpress

Im trying to do something like this.
Add "custom page" without page
I know about adding a wordpress page from admin panel, Pages->Add New, and then link this page to PHP file using the slug. I've already done that. I just want to make this page work without adding it from admin panel, in case if page gets deleted from admin panel it won't work even if exists in the directory.
Please let me know if my question isn't clear enough. Any help is highly appreciated.
Thanks!
Update:
Thanks to #Mike i was able to solve the problem by modifying his code. I just had to add add_rewrite_rule() and its working good now. Don't forget to flush permalinks.
function add_application_endpoint() {
add_rewrite_endpoint( 'view', EP_PERMALINK );
}
add_action( 'init', 'add_application_endpoint' );
function add_endpoint_queryvar( $query_vars ) {
$query_vars[] = 'view';
$query_vars[] = 'ptag';
$query_vars[] = 'product_cat';
return $query_vars;
}
add_filter( 'query_vars', 'add_endpoint_queryvar' );
add_rewrite_rule( '^view/([^/]+)/([^/]+)/?$', 'index.php?pagename=custom-product-tags&ptag=$matches[1]&product_cat=$matches[2]', 'top' );
/**
* Setting up job app template redirect for custom end point rewrite
*/
function job_application_template_redirect() {
global $wp_query;
if ( $wp_query->query_vars['name'] != 'custom-product-tags' ) {
return;
}
include dirname( __FILE__ ) . '/page-custom-product-tags.php';
exit;
}
add_action( 'template_redirect', 'job_application_template_redirect' );
You can do it by creating a custom endpoint and setting up a template redirect in your functions.php file.. Here is an example for a job application page. With this code added to my functions.php file, if I visit '/apply' on my site, the page-job_application.php template is rendered.
Hope this works for your needs.
/**
* Rewrite custom endpoint for job post applications
*/
function add_application_endpoint() {
add_rewrite_endpoint('apply', EP_PERMALINK);
}
add_action( 'init', 'add_application_endpoint');
/**
* Register our custom endpoint as a query var
*/
function add_endpoint_queryvar( $query_vars ) {
$query_vars[] = 'apply';
return $query_vars;
}
add_filter( 'query_vars', 'add_endpoint_queryvar' );
/**
* Setting up job app template redirect for custom end point rewrite
*/
function job_application_template_redirect() {
global $wp_query;
if ( ! isset( $wp_query->query_vars['apply'] ) || ! is_singular() )
return;
include dirname( __FILE__ ) . '/page-job_application.php';
exit;
}
add_action( 'template_redirect', 'job_application_template_redirect' );

WordPress URL rewrite for WooCommerce attributes

I'm using WooCommerce with the "YITH WooCommerce Ajax Navigation" plugin to filter brands. The result is a link that appears as https://example.com/products/racquets/tennis-racquets/?filter_brands=47
Ideally, I would like to use https://example.com/products/racquets/tennis-racquets/brands/wilson instead.
I've tried using an Apache mod_rewrite rule such as:
RewriteRule ^products/racquets/tennis-racquets/?filter_brands=47 /products/racquets/tennis-racquets/wilson [QSA,L]
I've also tried writing a function for my functions.php file but that doesn't seem to catch either. Here's a sample of the code I tried using.
function brand_rewrite_rules() {
add_rewrite_rule( 'products/racquets/tennis-racquets/?filter_brands=47', 'products/racquets/tennis-racquets/wilson', 'top' );
flush_rewrite_rules();
}
add_action( 'init', 'brand_rewrite_rules' );
I did try updating my permalink settings but the function did not do anything. Can anyone propose a solution for this?
It's a matter of adding a Rewrite Endpoint:
Adding an endpoint creates extra rewrite rules for each of the matching places specified by the provided bitmask. A new query var with the same name as the endpoint will also be created. The string following the endpoint definition supplies the value for this query var (e.g. "/foo/bar/" becomes "?foo=bar").
<?php
/**
* Plugin Name: Add a Brand endpoint to the URLs
* Plugin URI: http://stackoverflow.com/a/24331768/1287812
*/
add_action( 'init', function()
{
add_rewrite_endpoint( 'brands', EP_ALL );
});
add_filter( 'query_vars', function( $vars )
{
$vars[] = 'brands';
return $vars;
});
/**
* Refresh permalinks on plugin activation
* Source: http://wordpress.stackexchange.com/a/108517/12615
*/
function WCM_Setup_Demo_on_activation()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
$plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
check_admin_referer( "activate-plugin_{$plugin}" );
add_rewrite_endpoint( 'brands', EP_ALL ); #source: http://wordpress.stackexchange.com/a/118694/12615
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'WCM_Setup_Demo_on_activation' );
Then, in the templates use it like:
$brand = get_query_var('brand') ? urldecode( get_query_var('brand') ) : 'Empty endpoint';
echo $brand;

Wordpress Url rewriting not working

I am using Wordpress 3.5. I have created a page with name tpage. I want to pass query string like this tpage/param1. For this i have paste following code in functions.php but it is not working
add_rewrite_tag('%var1%','([^&]+)');`
add_rewrite_rule('^tpage/([^&]+)/?','index.php?page_id=4&var1=$matches[1]','top');
//Ensure the $wp_rewrite global is loaded
global $wp_rewrite;
//Call flush_rules() as a method of the $wp_rewrite object
$wp_rewrite->flush_rules();
What thing i am missing out here?
Theres a great class for this by someone called Kyle E that does all the heavy lifting for you.. you have to use get_query_var('Your-Var'); to get the var out. $_GET doesnt work. good luck!
<?php
/*
//Author Kyle E Gentile
//To use this class you must first include the file.
//After including the file, you need to create an options array. For example:
$options = array(
'query_vars' => array('var1', 'var2'),
'rules' => array('(.+?)/(.+?)/(.+?)/?$' => 'index.php?pagename=$matches[1]&var1=$matches[2]&var2=$matches[3]')
);
//After creating our $option array,
//we will need to create a new instance of the class as below:
$rewrite = new Add_rewrite_rules($options);
//You must pass the options array, this way. (If you don't there could be problems)
//Then you can call the filters and action functions as below:
add_action('wp_head', array(&$rewrite, 'flush_rules'));
add_action( 'generate_rewrite_rules', array(&$rewrite, 'add_rewrite_rules') );
add_filter( 'query_vars', array(&$rewrite, 'add_query_vars') );
//That is it.
*/
//prevent duplicate loading of the class if you are using this in multiply plugins
if(!class_exists('add_rewrite_rules')){
class Add_rewrite_rules{
var $query_vars;
var $rules;
function __construct($options){
$this->init($options);
}
function init($options){
foreach($options as $key => $value){
$this->$key = $value;
}
}
function rules_exist(){
global $wp_rewrite;
$has_rules = TRUE;
foreach($this->rules as $key => $value){
if(!in_array($value, $wp_rewrite->rules)){
$has_rules = FALSE;
}
}
return $has_rules;
}
//to be used add_action with the hook 'wp_head'
//flushing rewrite rules is labor intense so we better test to see if our rules exist first
//if the rules don't exist flush its like after a night of drinking
function flush_rules(){
global $wp_rewrite;
if(!$this->rules_exist()){
//echo "flushed"; // If want to see this in action uncomment this line and remove this text and you will see it flushed before your eyes
$wp_rewrite->flush_rules();
}
}
//filter function to be used with add_filter() with the hook "query_vars"
function add_query_vars($query_vars){
foreach($this->query_vars as $var){
$query_vars[] = $var;
}
return $query_vars;
}
//to be used with a the add_action() with the hook "generate_rewrite_rules"
function add_rewrite_rules(){
global $wp_rewrite;
$wp_rewrite->rules = $this->rules + $wp_rewrite->rules;
}
}
}
?>

Rewrite URL with WordPress Framework from code... How?

I created a plugin... I use my custom variable in this plugin and I want to rewrite this url for SEO, but I can't. If I use the Permalink generator of WordPress, then rewrite is work, but if I want to use the offical codes in my plugin for rewrite then it doesn't work.
Here it is a simple code what is not work. I don't no why.
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');
// Remember to flush_rules() when adding rules
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules['(project)/(\d*)$'] = 'index.php?pagename=$matches[1]&id=$matches[2]';
return $newrules + $rules;
}
// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
array_push($vars, 'id');
return $vars;
}
function search_url_rewrite_rule() {
if ( is_search() && !empty($_GET['s'])) {
wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'search_url_rewrite_rule');
I wrote a new code into my plugin, but it has not effect:
add_action('admin_init', 'flush_rewrite_rules');
add_action('generate_rewrite_rules', 'geotags_add_rewrite_rules');
function geotags_add_rewrite_rules( $wp_rewrite )
{
$new_rules = array(
'p/(.+)' => 'index.php?p=' .
$wp_rewrite->preg_index(1) );
// Add the new rewrite rule into the top of the global rules array
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
have you tried looking at this page
http://codex.wordpress.org/Class_Reference/WP_Rewrite
and i think you have to flush the rules every time..

Resources