Wordpress Url rewriting not working - wordpress

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;
}
}
}
?>

Related

add rewrite_rules in WordPress custom plugin

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.

Custom permalink for custom post type

I have created a system for a WordPress site using fake pages, and some plugins like More Types (for custom post types), Advanced Custom Fields, and More Taxonomies. The site have a post type for bands and releases.
Everything works very well on frontend, and if a user wanna read about a band, he clicks the menu and ends up at /band/[bandname]. If he wanna read about a release he ends up at /band/[bandname]/releases/[releasename].
As I said, everything works fine in frontend. But when I create a release in backend I'm having a hard time to add the /band/[bandname] part to the permalink for the post type releases. I tried with /band/%band%/releases/, but %band% will be written literally, as it doesn't know where to get the band name from. Any ideas?
I tried to use this code. Band is a post object input in the releases submit form.
add_filter('post_type_link', 'custom_permalinks', 10, 3);
function custom_permalinks($permalink, $post, $leavename)
{
$post_id = get_post_meta($_POST['band'], 'bands', true);
if($post->post_type != 'utgivelse' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
return $permalink;
$var1 = get_post_meta($post_id, 'bands', true);
$var1 = sanitize_title($var1);
$permalink = str_replace('%band%', $var1, $permalink);
return $permalink;
}
You could do it like this:
<?php
add_filter('rewrite_rules_array','customRewriteRules');
add_filter('query_vars','customRewriteVars');
// Remember to flush_rules() when adding rules
add_filter('init','flushRules');
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
// Adding a new rule
function customRewriteRules($rules)
{
$newrules = array();
$newrules['bands-page/([^/]+)/([^/]+)/?'] = 'index.php?pagename=bands-page&customvar1=$matches[1]&customvar2=$matches[2]';
$newrules['bands-page/([^/]+)/?'] = 'index.php?pagename=bands-page&customvar1=$matches[1]'; // pagename could be band/
$finalrules = $newrules + $rules;
return $finalrules;
}
function customRewriteVars($vars)
{
array_push($vars, 'customvar1', 'customvar2');
return $vars;
}
You can pass as many as query vars as you want, and then use that var ($_GET['customvar1']) to do a custom loop or something like that.
By doing some small tweaks, I got it working good. I added the following permalink rule to my releasestype: /band/%band%/releases/
Then I created this to replace variable %band% in permalink:
add_filter('post_type_link', 'custom_permalinks', 10, 3);
function custom_permalinks($permalink, $post, $leavename)
{
$post_id = $post->ID;
if($post->post_type != 'utgivelse' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
return $permalink;
$var1 = get_the_title(get_post_meta($post_id, 'band', true));
$var1 = sanitize_title($var1);
$permalink = str_replace('%band%', $var1, $permalink);
return $permalink;
}

Override a function with child themes functions.php

As the title reads I'm trying to modify a function called by a parent theme in my child, I know that the child theme is set to be loaded beforehand so I'm curious if this is even possible?
My parent theme has a function called ajax_search_box() that I'd like to modify a query in, and I'd rather not modify the parent theme files in case I need to update it down the road.. what would be the best way to do this?
Also, for bonus points, how would I go about doing this with a widget as well? Thanks in advance!
function SearchFilter($query) {
// If 's' request variable is set but empty
if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
$query->is_search = true;
$query->is_home = false;
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
function ajax_search_box() {
if (isset($_GET["q"]))
{
$q = $_GET["q"];
global $wpdb;
$q = mysql_real_escape_string($q);
$q = $wpdb->escape($q);
$query = array(
'post_status' => 'publish',
'order' => 'DESC',
's' => $q
);
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );
// Check if any posts were found.
if ( ! $get_posts->post_count )
die();
//Create an array with the results
foreach ( $posts as $post )
echo $post->post_title . "|" . $post->ID . "\n";
}
die();
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_ajax_search_box', 'ajax_search_box' );
add_action( 'wp_ajax_ajax_search_box', 'ajax_search_box' );
the parent theme needs to check if(function_exists('ajax_search_box')) and if it doesn't exist then it will declare it.
If the parent theme checks to see if the function exists, then you can declare it first and have it do what you want.
If the parent theme does not check, get in touch with the theme author to see if they will throw that change in for the next update....and code it yourself too. That way when the theme updates then you will still be good to go.
Break free of functions.php, write your own plugin.
<?php
/**
* Plugin Name: Manipulate the Parent
* Requires: PHP5.3+
*/
add_action( 'after_setup_theme', function()
{
remove_filter( 'pre_get_posts','SearchFilter' );
// now add your own filter
add_filter( 'pre_get_posts', 'your_callback_for_your_filter' );
});
function your_callback_for_your_filter()
{
// do stuff
}

Wordpress Add custom permalink

I have a dynamic page setup in wordpress which uses a $_GET['id'] php variable to make a query to the database. The problem is that my url format looks like the following:
http://site.com/business/id?=123
What's the best way to make the url look like:
http://site.com/business/business-name-here
Is it done using rewrite rules in the .htaccess file?
Thanks in advance
I've found a great class to do just that by Kyle E try it.
<?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;
}
}
}
?>
Add the following function to the init of your plugin / functions file.
public function rewriteRules()
{
//Add the query variables to the list so wordpress doesn't discard them or worse use them to try and find by itself what page to serve.
$options = array(
'query_vars' => array('trainingid', 'vakname'),
'rules' =>
array( 'uncategorized/vak/([^/]+)/([^/]+)/?$' => 'index.php?p=1316&vakname=$matches[1]&level=$matches[2]'
)
);
//I use a autoloader but if you don't you have to include the class.
//include_once('path/to/AddRewriteRules.php');
$rewrite = new AddRewriteRules($options);
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'));
}

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