Aggiungere parametri extra dopo un permalink?
Come posso aggiungere parametri extra dopo un permalink, in particolare se sto utilizzando un custom post type?
Ad esempio, mettiamo che http://mysite/album/record-name
sia il permalink. Come posso fare in modo che http://mysite/album/record-name/related
non generi un errore 404 o un reindirizzamento?
WordPress non sembra richiamare il template del post se il post non esiste... quindi sono un po' perso su come realizzare questa funzionalità.
Puoi aggiungere un endpoint ai tuoi URI per gestire richieste speciali.
Ecco un esempio base sotto forma di plugin. Per capire cosa succede, leggi il fantastico tutorial di Christopher Davis Una guida (quasi) completa alla WordPress Rewrite API.
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: Esempio Endpoint T5
* Description: Aggiunge un endpoint permalink ai post chiamato <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' );
/**
* Gestisce le chiamate all'endpoint.
*/
function t5_render_epex()
{
if ( ! is_singular() or ! get_query_var( 'epex' ) )
{
return;
}
// Probabilmente farai qualcosa di più produttivo.
$post = get_queried_object();
print '<pre>' . htmlspecialchars( print_r( $post, TRUE ) ) . '</pre>';
exit;
}
add_filter( 'request', 't5_set_epex_var' );
/**
* Assicura che 'get_query_var( 'epex' )' non restituisca solo una stringa vuota se è impostato.
*
* @param array $vars
* @return array
*/
function t5_set_epex_var( $vars )
{
isset( $vars['epex'] ) and $vars['epex'] = true;
return $vars;
}

Puoi farlo con l'API di Rewrite utilizzando 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 ){
// aggiunge 'related' all'array delle query vars riconosciute
$query_vars[] = 'related';
return $query_vars;
}
Nel template puoi verificare quando la tua query var 'related' è presente:
if( array_key_exists( 'related' , $wp_query->query_vars ) ):
// la richiesta corrente termina con 'related'
endif;

Cosa significa wpse51444? È solo una stringa lunga per assicurarsi di non entrare in conflitto con qualcosa?

@Hexodus sì, wpse sta per wp stackexchange, 51444 è l'id di questa domanda. Puoi cambiarlo con quello che preferisci, ma è bene usare qualcosa che sai sarà univoco.

Non dimenticare di aggiornare i permalink.

per aggiungere un parametro all'URL del post (permalink), utilizzo in questo modo:
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
