Agregue la base de categorías a la URL en el tipo de publicación / taxonomía personalizada
-
-
Recientemente,me enfrento aesteproblema.** ¡Resuelto! ** [# 188834] [1] [1]: http://wordpress.stackexchange.com/questions/94817/add-category-base-to-url-in-custom-post-type-taxonomy/188834#188834Recently, I face this issue. **Solved!** [#188834][1] [1]: http://wordpress.stackexchange.com/questions/94817/add-category-base-to-url-in-custom-post-type-taxonomy/188834#188834
- 0
- 2015-05-20
- maheshwaghmare
-
** SOLUCIÓN! ** (Después de unainvestigacióninterminable)
debesmodificarelfiltro `post_type_link`.másen: http://wordpress.stackexchange.com/a/167992/33667)**SOLUTION!** (After endless research)
you should modify the `post_type_link` filter. more at: http://wordpress.stackexchange.com/a/167992/33667 )- 0
- 2015-07-26
- T.Todua
-
posible duplicado de [¿Cómo cambiar laestructura delenlacepermanenteparaeltipo depublicaciónpersonalizada y sustaxonomías?] (http://wordpress.stackexchange.com/questions/28979/how-to-change-permalink-structure-for-custom-post-type-y-sus-taxonomías)possible duplicate of [How to change permalink structure for custom post type and it's taxonomies?](http://wordpress.stackexchange.com/questions/28979/how-to-change-permalink-structure-for-custom-post-type-and-its-taxonomies)
- 0
- 2015-07-26
- T.Todua
-
9 respuestas
- votos
-
- 2013-04-06
Cambie su reescriturapara agregar la consulta del curso var:
'rewrite' => array('slug' => 'courses/%course%')
Luego,filtre
post_type_link
parainsertarel curso seleccionadoen elenlacepermanente:function wpa_course_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'course' ); if( $terms ){ return str_replace( '%course%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 );
También hay complementos como enlacespermanentes detipo depublicaciónpersonalizados quepueden hacerestopor usted.
Change your rewrite to add the course query var:
'rewrite' => array('slug' => 'courses/%course%')
Then filter
post_type_link
to insert the selected course into the permalink:function wpa_course_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'course' ); if( $terms ){ return str_replace( '%course%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 );
There are also plugins like Custom Post Type Permalinks that can do this for you.
-
Gracias,agradezco su rápida respuesta.Estotiene mucho sentido.Sinembargo,tengo curiosidad,¿dóndeinsertoelfiltropost_type_linken?¿Puedoir alfinal detodoel documento?Thank you, I appreciate your swift answer. This makes complete sense. I'm curious though, where do I insert the filter post_type_link at? can i just go at the bottom of the entire document?
- 0
- 2013-04-06
- Zach Russell
-
Lo agregué alfinal y 404es lapágina.I added it to the bottom and it 404's the page.
- 0
- 2013-04-06
- Zach Russell
-
tienes queeliminar las reescrituras,visita lapágina de configuración deenlacespermanentes.you have to flush rewrites, visit the permalinks settings page.
- 1
- 2013-04-06
- Milo
-
tambiéntengaen cuenta queesprobable quetenga un conflicto con unataxonomía y untipo depublicación que comparten lamismababosa.also note you'll likely have a clash with a taxonomy and a post type both sharing the same slug.
- 0
- 2013-04-06
- Milo
-
En lo queestoy ahoraesen hacerbien losenlacespermanentes,perono seestáejecutando correctamente (es 404ing suave).¿Alguna recomendación sobre lo quepuedo hacerpara queestofuncione correctamente?Estoy lejos de las reescrituras deenlacespermanentes.Simplemente haga clicen 'guardar' y actualizael archivo (esnginx,por lo queestá controladoen el archivonginx.conf)Where i'm at now is it's making the permalinks right, but it's not executing correctly (it's soft 404ing). Any recommendations on what I can do to get this working right? I'm away of the permalink flush rewrites. Just click 'save' and it updates the file (it's nginx so it's controlled in the nginx.conf file)
- 0
- 2013-04-06
- Zach Russell
-
¡Entendido!Fue un conflicto.Got it! It was a conflict.
- 0
- 2013-04-06
- Zach Russell
-
Downvote -página de archivo 404Downvote - archive page 404
- 1
- 2020-04-04
- Dev
-
Estonofuncionaparapublicacionestraducidasen un sitiomultilingüe (porejemplo,usando WPML).This doesn't work for translated posts on a multilingual site (for example using WPML).
- 0
- 2020-08-05
- montrealist
-
Estome muestra lapáginaprincipalen la URL recién creada.Debes usar add_rewrite_rule () que se veen la respuesta de @ Florispara quefuncione.Tambiéntengaen cuenta que laspáginas de archivo dejan defuncionar,obtengo 404para/my-post-type ypara/my-post-type/my-categoryThis shows frontpage for me on the newly created URL. You gotta use the add_rewrite_rule() seen in @Floris's answer to make it work. Also note, archive pages stop working, I get 404 for /my-post-type and for /my-post-type/my-category
- 0
- 2020-09-01
- trainoasis
-
- 2019-02-11
La soluciónparamíteníatrespartes. Enmi caso,eltipo depublicación se llama
trainings
.- Agregue
'rewrite' => array('slug' => 'trainings/%cat%')
a lafunciónregister_post_type
. - Cambieel slugparatener una categoría dinámica.
- "Escuche" lanueva URL dinámica y cargue laplantilla adecuada.
Así que aquí seexplica cómo cambiarelenlacepermanente deforma dinámicapara untipo depublicación determinado. Agregar a
functions.php
:function vx_soon_training_post_link( $post_link, $id = 0 ) { $post = get_post( $id ); if ( is_object( $post ) ) { $terms = wp_get_object_terms( $post->ID, 'training_cat' ); if ( $terms ) { return str_replace( '%cat%', $terms[0]->slug, $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'vx_soon_training_post_link', 1, 3 );
... y asíes como cargar laplantilla adecuadaen lanueva URL dinámica. Agregar a
functions.php
:function archive_rewrite_rules() { add_rewrite_rule( '^training/(.*)/(.*)/?$', 'index.php?post_type=trainings&name=$matches[2]', 'top' ); //flush_rewrite_rules(); // use only once } add_action( 'init', 'archive_rewrite_rules' );
¡Esoestodo! Recuerde actualizar losenlacespermanentesguardando losenlacespermanentesnuevamenteen elbackend. O use lafunción
flush_rewrite_rules()
.The solution for me had three parts. In my case the post type is called
trainings
.- Add
'rewrite' => array('slug' => 'trainings/%cat%')
to theregister_post_type
function. - Change the slug to have a dynamic category.
- "Listen" to the new dynamic URL and load the appropriate template.
So here is how to change the permalink dynamically for a given post type. Add to
functions.php
:function vx_soon_training_post_link( $post_link, $id = 0 ) { $post = get_post( $id ); if ( is_object( $post ) ) { $terms = wp_get_object_terms( $post->ID, 'training_cat' ); if ( $terms ) { return str_replace( '%cat%', $terms[0]->slug, $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'vx_soon_training_post_link', 1, 3 );
...and this is how to load the appropriate template on the new dynamic URL. Add to
functions.php
:function archive_rewrite_rules() { add_rewrite_rule( '^training/(.*)/(.*)/?$', 'index.php?post_type=trainings&name=$matches[2]', 'top' ); //flush_rewrite_rules(); // use only once } add_action( 'init', 'archive_rewrite_rules' );
Thats it! Remember to refresh the permalinks by saving the permalinks again in de backend. Or use the
flush_rewrite_rules()
function. -
- 2017-10-06
¡Tengo la solución!
Paratener vínculospermanentesjerárquicosparaeltipo depublicaciónpersonalizada,instale Vínculospermanentes detipo depublicaciónpersonalizada ( https://wordpress.org/plugins/custom-post-type-permalinks/) complemento.
Actualizaeltipo depublicación registrada. Tengoelnombre deltipo depublicación como centro de ayuda
function help_centre_post_type(){ register_post_type('helpcentre', array( 'labels' => array( 'name' => __('Help Center'), 'singular_name' => __('Help Center'), 'all_items' => __('View Posts'), 'add_new' => __('New Post'), 'add_new_item' => __('New Help Center'), 'edit_item' => __('Edit Help Center'), 'view_item' => __('View Help Center'), 'search_items' => __('Search Help Center'), 'no_found' => __('No Help Center Post Found'), 'not_found_in_trash' => __('No Help Center Post in Trash') ), 'public' => true, 'publicly_queryable'=> true, 'show_ui' => true, 'query_var' => true, 'show_in_nav_menus' => false, 'capability_type' => 'page', 'hierarchical' => true, 'rewrite'=> [ 'slug' => 'help-center', "with_front" => false ], "cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/", 'menu_position' => 21, 'supports' => array('title','editor', 'thumbnail'), 'has_archive' => true )); flush_rewrite_rules(); } add_action('init', 'help_centre_post_type');
Y aquíestá lataxonomía registrada
function themes_taxonomy() { register_taxonomy( 'help_centre_category', 'helpcentre', array( 'label' => __( 'Categories' ), 'rewrite'=> [ 'slug' => 'help-center', "with_front" => false ], "cptp_permalink_structure" => "/%help_centre_category%/", 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'query_var' => true ) ); } add_action( 'init', 'themes_taxonomy');
Esta línea hace que suenlacepermanentefuncione
"cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/",
puedeeliminar
%post_id%
ypuede conservar/%help_centre_category%/%postname%/"
No olvideeliminar losenlacespermanentes delpanel.
Got the solution!
To have hierarchical permalinks for custom post type install Custom Post Type Permalinks(https://wordpress.org/plugins/custom-post-type-permalinks/) plugin.
Update registered post type. I have post type name as help center
function help_centre_post_type(){ register_post_type('helpcentre', array( 'labels' => array( 'name' => __('Help Center'), 'singular_name' => __('Help Center'), 'all_items' => __('View Posts'), 'add_new' => __('New Post'), 'add_new_item' => __('New Help Center'), 'edit_item' => __('Edit Help Center'), 'view_item' => __('View Help Center'), 'search_items' => __('Search Help Center'), 'no_found' => __('No Help Center Post Found'), 'not_found_in_trash' => __('No Help Center Post in Trash') ), 'public' => true, 'publicly_queryable'=> true, 'show_ui' => true, 'query_var' => true, 'show_in_nav_menus' => false, 'capability_type' => 'page', 'hierarchical' => true, 'rewrite'=> [ 'slug' => 'help-center', "with_front" => false ], "cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/", 'menu_position' => 21, 'supports' => array('title','editor', 'thumbnail'), 'has_archive' => true )); flush_rewrite_rules(); } add_action('init', 'help_centre_post_type');
And here is registered taxonomy
function themes_taxonomy() { register_taxonomy( 'help_centre_category', 'helpcentre', array( 'label' => __( 'Categories' ), 'rewrite'=> [ 'slug' => 'help-center', "with_front" => false ], "cptp_permalink_structure" => "/%help_centre_category%/", 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'query_var' => true ) ); } add_action( 'init', 'themes_taxonomy');
This is line makes your permalink work
"cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/",
you can remove
%post_id%
and can keep/%help_centre_category%/%postname%/"
Don't forget to flush permalinks from dashboard.
-
- 2015-05-20
¡Sí! Después demuchainvestigación,obtuveel complemento ' Enlacespermanentespersonalizados '.Lo cual cumple conmis requisitos.
- para la categoría
- parapublicación
- parapublicacionespersonalizadas
- parataxonomíapersonalizada etc.
Comoeste Tipo depublicaciónpersonalizada:publicación :
Yep! After a lot of research I got plugin 'Custom Permalinks'. Which fulfils my requirement regards - custom URL e.g.
- for Category
- for Post
- for Custom Post
- for Custom Taxonomy etc.
Like this Custom Post Type - Post:
-
- 2019-06-12
Debe actualizar la siguiente líneaen la que registró untipo depublicaciónpersonalizada utilizando lafunción register_post_type.
'rewrite'=> array ('slug'=> 'cursos/% cat%')
Para cambiarelenlacepermanente deforma dinámica deltipo depublicación,debe agregarel siguiente códigoen el archivofunctions.php:
function change_link( $post_link, $id = 0 ) { $post = get_post( $id ); if( $post->post_type == 'courses' ) { if ( is_object( $post ) ) { $terms = wp_get_object_terms( $post->ID, array('course') ); if ( $terms ) { return str_replace( '%cat%', $terms[0]->slug, $post_link ); } } } return $post_link ; } add_filter( 'post_type_link', 'change_link', 1, 3 ); //load the template on the new generated URL otherwise you will get 404's the page function generated_rewrite_rules() { add_rewrite_rule( '^courses/(.*)/(.*)/?$', 'index.php?post_type=courses&name=$matches[2]', 'top' ); } add_action( 'init', 'generated_rewrite_rules' );
Después deeso,debeeliminar losenlacespermanentes reescritos,vaya a wp-admin> Configuración>enlacespermanentes . simplemente actualice la configuración delenlacepermanente conelbotón "Guardar cambios".
devolverá URL como las siguientes:
- dominio.com/cursos/[nombre-del-curso{category}]/nombre-lección
¡Gracias!
You need to update below line at where you have register a custom post type using register_post_type function.
'rewrite' => array('slug' => 'courses/%cat%')
To change permalink dynamically of post type you have to add below code in functions.php file :
function change_link( $post_link, $id = 0 ) { $post = get_post( $id ); if( $post->post_type == 'courses' ) { if ( is_object( $post ) ) { $terms = wp_get_object_terms( $post->ID, array('course') ); if ( $terms ) { return str_replace( '%cat%', $terms[0]->slug, $post_link ); } } } return $post_link ; } add_filter( 'post_type_link', 'change_link', 1, 3 ); //load the template on the new generated URL otherwise you will get 404's the page function generated_rewrite_rules() { add_rewrite_rule( '^courses/(.*)/(.*)/?$', 'index.php?post_type=courses&name=$matches[2]', 'top' ); } add_action( 'init', 'generated_rewrite_rules' );
After that, you need to flush rewrites permalinks, goto the wp-admin > Settings > permalinks. just update permalink setting using "Save Changes" button.
it'll return urls like below :
- domain.com/courses/[course-name{category}]/lesson-name
Thank you!
-
Votoen contra: 404en tipos depágina de archivo CPT y CTPindividualesDown vote - 404 on both single CPT and CTP archive page types
- 0
- 2020-04-04
- Dev
-
@dev,¿siguiótodos lospasos quemencionéen mi respuesta?¿Limpiastetusenlacespermanentes de reescritura?Lo heprobado yestáfuncionandobien.@dev did you follow all steps which i have mentioned in my answer ? did you flush your rewrite permalinks? I have tested and it is working fine.
- 0
- 2020-04-04
- Chetan Vaghela
-
- 2017-05-03
Estofuncionóparamí:
'rewrite' => array( 'slug' => 'portfolio', 'with_front' => false, 'hierarchical' => true // to display category/subcategroy ),
This is worked for me :
'rewrite' => array( 'slug' => 'portfolio', 'with_front' => false, 'hierarchical' => true // to display category/subcategroy ),
-
Estono hace uso de las categorías o su ruta,solo hace queeltipo depublicaciónpersonalizada seajerárquico.This does not make use of the categories or their path it only makes the custom post type hierarchical.
- 5
- 2017-08-25
- Joris Kroos
-
- 2019-07-01
Para cualquierpersonainteresadaen la solución,sintener quejugar conel código PHP sinprocesar,le recomiendoel complemento Permalink Manager Lite de Maciej Bis.Es un salvavidas.
Tiene unmecanismo visualparaeliminar o agregar cualquierparte que deseeen la URL deltipo depublicaciónpersonalizadaen función de 'permastructs':
(Contodoel dolor queimplica laestructuración de URL simple contipos depublicacionespersonalizadas,estábamos apunto de renunciar a WP ypasar a otro CMS. Peroeste complementojunto con ACF y CPTUI o Pods hace que Wordpress seabastanteprofesional).
/p>
To anyone interested in the solution, without having to tinker with raw PHP code, I highly recommend the plugin Permalink Manager Lite by Maciej Bis. It's a life saver.
It has a visual mechanism to remove or add whatever part you want in the custom post type's URL based on 'permastructs':
(With all the pain involved in simple URL structuring with custom post types, we were about to give up on WP and move to another CMS. But this plugin in conjunction with ACF and CPTUI or Pods makes Wordpress fairly professional.)
-
- 2020-05-29
Siestá utilizando
get_post_type_archive_link()
,tal vez debaeliminar/%cat%/
de la URLmedianteelfiltropost_type_archive_link
.If you're using
get_post_type_archive_link()
, maybe you will need to remove/%cat%/
from the URL usingpost_type_archive_link
filter. -
- 2020-08-18
Encontré la respuesta de @ chetan-vaghela casiperfecta;enmi caso de uso,también queríapoder ver una lista detodas laspublicaciones deestetipo depublicación como unapágina de archivotípica (es decir,/cursos/,sinningunataxonomía después).Solotuve que agregar una regla de reescritura adicional de la siguientemanera:
function generated_rewrite_rules() { add_rewrite_rule( '^courses/(.*)/(.*)/?$', 'index.php?post_type=courses&name=$matches[2]', 'top' ); }
I found @chetan-vaghela 's answer almost perfect; in my use case I also wanted to be able to see a list of all posts by this post type like a typical archive page (i.e. /courses/, without any taxonomy after it). I just had to add one additional rewrite rule as follows:
function generated_rewrite_rules() { add_rewrite_rule( '^courses/(.*)/(.*)/?$', 'index.php?post_type=courses&name=$matches[2]', 'top' ); }
Estoy construyendo un sistema detipo LMSen WordPress,controladopor
Custom Post types
.Eltipo depublicación se llama
Lessons
(con unabarra decourses
) ytiene unacustom taxonomy
(categoría) llamadacourses
.Laestructura de la URL del dominio semuestra ahora como:
domain.com/courses/lesson-name
.Quiero que se conviertaen:
domain.com/courses/[course-name{category}]/lesson-name
oesencialmente:
/[cpt]/%category%/%postname%/
aquíestáel complemento queescribí que ahora controla los
CPTs
.