Regla de reescritura para taxonomía personalizada en WordPress
Soy bastante nuevo en WordPress y estoy intentando crear un blog de recetas.
He creado una taxonomía personalizada para ingredientes:
register_taxonomy(
'ingredient',
'post',
array( 'label' => 'Ingrediente',
'hierarchical' => true
),
array( 'rewrite' => array (
'slug'=>'recipes-with'
)
);
Todo funciona y mis URLs son del tipo
www.misitio.com/recipes-with/cebolla
pero me gustaría que mis URLs fueran como
www.misitio.com/recipes-with-cebolla
He intentado usar add_rewrite_rule()
, pero no logro que funcione.
¡Cualquier ayuda sería muy apreciada!
EDITADO: Aquí está cómo resolví el problema con la ayuda de toni_lehtimaki.
1) Eliminé el array rewrite
en los argumentos de register_taxonomy quedando así:
register_taxonomy( 'ingredient', 'post', array('label'=>'Ingrediente', 'hierarchical'=>true));
2) Luego añadí algunas reglas de reescritura
add_rewrite_rule('^recipes-with-(.*)/page/([0-9]+)?$','index.php?ingredient=$matches[1]&paged=$matches[2]','top');
add_rewrite_rule('^recipes-with-(.*)/?','index.php?ingredient=$matches[1]','top');
3) Lo último que necesité hacer fue añadir un filtro
add_filter( 'term_link', 'change_ingredients_permalinks', 10, 2 );
function change_ingredients_permalinks( $permalink, $term ) {
if ($term->taxonomy == 'ingredient') $permalink = str_replace('ingredient/', 'recipes-with-', $permalink);
return $permalink;
}
4) Vaciar las reglas de reescritura (solo necesitas ir a ajustes->enlaces permanentes y hacer clic en guardar)

Se me ocurrió esto con add_rewrite_rule()
:
add_rewrite_rule('^recipes-with-([^/]*)/?','index.php?ingredient=$matches[1]','top');
Hice algunas pruebas para lo anterior y funciona bien cuando lo usas para una taxonomía a la vez. Aquí está el código de mi functions.php:
add_action( 'init', 'create_ingredient_tax' );
function create_ingredient_tax() {
register_taxonomy(
'ingredient',
'post',
array( 'label' => 'Ingrediente',
'hierarchical' => true
),
array( 'rewrite' => array (
'slug'=>'recipes-with'
))
);
}
// Recuerda usar flush_rewrite_rules(); o visitar la página de configuración de estructura de enlaces permanentes de WordPress
add_rewrite_rule('^recipes-with-([^/]*)/?','index.php?ingredient=$matches[1]','top');
Luego usé la plantilla taxonomy-post_format.php
del tema twentyfourteen de WordPress para probar que esto funciona. También limpié las reglas de reescritura para que la nueva regla surta efecto.
