Wordpress - Add extra parameters after permalink?
You can add an endpoint to your URIs to handle special requests.
Here is a basic example as plugin. To understand what's going on read Christopher Davis's fantastic tutorial A (Mostly) Complete Guide to the WordPress Rewrite API.
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Endpoint Example
* Description: Adds a permalink endpoint to posts named <code>epex</code>
*/
add_action( 'init', 't5_add_epex' );
function t5_add_epex()
{
add_rewrite_endpoint( 'epex', EP_PERMALINK );
}
add_action( 'template_redirect', 't5_render_epex' );
/**
* Handle calls to the endpoint.
*/
function t5_render_epex()
{
if ( ! is_singular() or ! get_query_var( 'epex' ) )
{
return;
}
// You will probably do something more productive.
$post = get_queried_object();
print '<pre>' . htmlspecialchars( print_r( $post, TRUE ) ) . '</pre>';
exit;
}
add_filter( 'request', 't5_set_epex_var' );
/**
* Make sure that 'get_query_var( 'epex' )' will not return just an empty string if it is set.
*
* @param array $vars
* @return array
*/
function t5_set_epex_var( $vars )
{
isset( $vars['epex'] ) and $vars['epex'] = true;
return $vars;
}
You can do this with the Rewrite API's add_rewrite_endpoint:
add_action( 'init', 'wpse51444_endpoint' );
function wpse51444_endpoint(){
add_rewrite_endpoint( 'related', EP_ALL );
}
add_filter( 'query_vars', 'wpse51444_query_vars' );
function wpse51444_query_vars( $query_vars ){
// add related to the array of recognized query vars
$query_vars[] = 'related';
return $query_vars;
}
In the template you can detect when your related query var is present:
if( array_key_exists( 'related' , $wp_query->query_vars ) ):
// current request ends in related
endif;
to add parameter to post url (permalink), i use like this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return $url.'?my_pid='.$post->ID;
}
output:
http://yoursite.com/pagename?my_pid=12345678