Pregunta:
Sé que la gente ha preguntado esto antes y ha ido tan lejos como para agregar el tipo de publicación personalizada y reescribir para el enlace permanente.
El problema es que tengo 340 categorías existentes que me gustaría seguir usando. Solía poder ver / categoría / subcategoría / postname
Ahora tengo el slug de customposttype / postname. La selección de la categoría ya no aparece en el enlace permanente … No he cambiado la configuración del enlace permanente en el administrador a nada diferente.
¿Hay algo que me falta o necesito agregar a este código?
function jcj_club_post_types() {
register_post_type( 'jcj_club', array(
'labels' => array(
'name' => __( 'Jazz Clubs' ),
'singular_name' => __( 'Jazz Club' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Jazz Club' ),
'edit' => __( 'Edit' ),
'edit_item' => __( 'Edit Jazz Clubs' ),
'new_item' => __( 'New Jazz Club' ),
'view' => __( 'View Jazz Club' ),
'view_item' => __( 'View Jazz Club' ),
'search_items' => __( 'Search Jazz Clubs' ),
'not_found' => __( 'No jazz clubs found' ),
'not_found_in_trash' => __( 'No jazz clubs found in Trash' ),
'parent' => __( 'Parent Jazz Club' ),
),
'public' => true,
'show_ui' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'menu_position' => 5,
'query_var' => true,
'supports' => array(
'title',
'editor',
'comments',
'revisions',
'trackbacks',
'author',
'excerpt',
'thumbnail',
'custom-fields',
),
'rewrite' => array( 'slug' => 'jazz-clubs-in', 'with_front' => true ),
'taxonomies' => array( 'category','post_tag'),
'can_export' => true,
)
);
Respuesta:
Hay 2 puntos de ataque que cubrir cuando agrega reglas de reescritura de tipo de publicación personalizada:
Reescribir las reglas
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 de posttype
debe ser el nombre de su tipo de publicación personalizada. Alternativamente, puede usar el filtro post_rewrite_rules
siempre que no elimine las reglas de publicación estándar también.
A continuación, necesitamos la función para generar realmente 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 decide jugar es el booleano 'Walk directorios'. Genera reglas de reescritura para cada segmento de un permastruct y puede causar desajustes en las reglas de reescritura. Cuando se solicita una URL de WordPress, la matriz de reglas de reescritura se comprueba de arriba a abajo. Tan pronto como se encuentre una coincidencia, cargará lo que haya encontrado, por ejemplo, si su permastruct tiene una coincidencia codiciosa, por ejemplo. para /%category%/%postname%/
y los directorios walk están /%category%/%postname%/
, generará reglas de reescritura para ambos /%category%/%postname%/
AND /%category%/
que coincidirá con cualquier cosa. Si eso sucede demasiado pronto, estás jodido.
Enlaces permanentes
Esta es la función que analiza los enlaces permanentes del tipo de publicación y convierte una estructura permanente (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()
que se encuentra en wp-includes/link-template.php
. Los get_post_permalink()
permanentes de las publicaciones personalizadas son generados por get_post_permalink()
que es una versión mucho más diluida de get_permalink()
. get_post_permalink()
está filtrado por post_type_link
por lo que lo estamos usando para hacer una estructura de perma 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 de reescritura personalizado y enlaces permanentes, y no es particularmente flexible, pero debería ser suficiente para comenzar.
Infiel
Escribí un complemento que te permite definir permastructs para cualquier tipo de publicación personalizada, pero como puedes usar %category%
en la estructura de %custom_taxonomy_name%
permanente para publicaciones, mi complemento admite %custom_taxonomy_name%
para cualquier taxonomía personalizada que tengas donde custom_taxonomy_name
es el nombre de tu taxonomía p.ej. %club%
.
Funcionará como cabría esperar con taxonomías jerárquicas / no jerárquicas.