Hay dos puntos de ataque para cubrir cuando agrega reglas de reescritura de tipo de publicación personalizadas:
Reglas de reescritura
Esto sucede cuando las reglas de reescritura se generan en wp-includes/rewrite.php
en WP_Rewrite::rewrite_rules()
. WordPress le permite filtrar las reglas de reescritura para elementos específicos como publicaciones, páginas y varios tipos de archivo. Donde vea posttype_rewrite_rules
, la parte posttype
debe ser el nombre de su tipo de publicación personalizada. Alternativamente, puede usar el filtro post_rewrite_rules
siempre que no borre las reglas estándar de publicación también.
A continuación, necesitamos la función para generar las reglas de reescritura:
// add our new permastruct to the rewrite rules
add_filter( 'posttype_rewrite_rules', 'add_permastruct' );
function add_permastruct( $rules ) {
global $wp_rewrite;
// set your desired permalink structure here
$struct = '/%category%/%year%/%monthnum%/%postname%/';
// use the WP rewrite rule generating function
$rules = $wp_rewrite->generate_rewrite_rules(
$struct, // the permalink structure
EP_PERMALINK, // Endpoint mask: adds rewrite rules for single post endpoints like comments pages etc...
false, // Paged: add rewrite rules for paging eg. for archives (not needed here)
true, // Feed: add rewrite rules for feed endpoints
true, // For comments: whether the feed rules should be for post comments - on a singular page adds endpoints for comments feed
false, // Walk directories: whether to generate rules for each segment of the permastruct delimited by '/'. Always set to false otherwise custom rewrite rules will be too greedy, they appear at the top of the rules
true // Add custom endpoints
);
return $rules;
}
Lo principal a tener en cuenta aquí si decides jugar es el booleano 'Caminar directorios'. Genera reglas de reescritura para cada segmento de un permastruct y puede causar discrepancias de reglas de reescritura. Cuando se solicita una URL de WordPress, la matriz de reglas de reescritura se verifica de arriba a abajo. Tan pronto como se encuentre una coincidencia, se cargará lo que haya encontrado, por ejemplo, si su permastruct tiene una coincidencia codiciosa, por ejemplo. para los directorios /%category%/%postname%/
y walk está activado, generará reglas de reescritura tanto para /%category%/%postname%/
Y /%category%/
que coincidirán con cualquier cosa. Si eso sucede demasiado pronto, estás jodido.
Permalinks
Esta es la función que analiza los permalinks de tipo de publicación y convierte un permastruct (por ejemplo, '/% year% /% monthnum% /% postname% /') en una URL real.
La siguiente parte es un ejemplo simple de lo que idealmente sería una versión de la función get_permalink()
encontrada en wp-includes/link-template.php
. Los enlaces permanentes personalizados se generan mediante get_post_permalink()
, que es una versión muy diluida de get_permalink()
. get_post_permalink()
se filtra por post_type_link
, así que lo estamos utilizando para crear una estructura de estructura personalizada.
// parse the generated links
add_filter( 'post_type_link', 'custom_post_permalink', 10, 4 );
function custom_post_permalink( $permalink, $post, $leavename, $sample ) {
// only do our stuff if we're using pretty permalinks
// and if it's our target post type
if ( $post->post_type == 'posttype' && get_option( 'permalink_structure' ) ) {
// remember our desired permalink structure here
// we need to generate the equivalent with real data
// to match the rewrite rules set up from before
$struct = '/%category%/%year%/%monthnum%/%postname%/';
$rewritecodes = array(
'%category%',
'%year%',
'%monthnum%',
'%postname%'
);
// setup data
$terms = get_the_terms($post->ID, 'category');
$unixtime = strtotime( $post->post_date );
// this code is from get_permalink()
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_category( get_option( 'default_category' ) );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$replacements = array(
$category,
date( 'Y', $unixtime ),
date( 'm', $unixtime ),
$post->post_name
);
// finish off the permalink
$permalink = home_url( str_replace( $rewritecodes, $replacements, $struct ) );
$permalink = user_trailingslashit($permalink, 'single');
}
return $permalink;
}
Como se mencionó, este es un caso muy simplificado para generar un conjunto de reglas y enlaces permanentes de reescritura personalizado, y no es particularmente flexible, pero debería ser suficiente para comenzar.
Hacer trampa
Escribí un complemento que te permite definir permastructs para cualquier tipo de publicación personalizada, pero al igual que puedes usar %category%
en la estructura de permalink para las publicaciones, mi complemento admite %custom_taxonomy_name%
para cualquier taxonomía personalizada que tengas, donde custom_taxonomy_name
es el nombre de su taxonomía por ej. %club%
.
Funcionará como cabría esperar con taxonomías jerárquicas / no jerárquicas.
enlace