Adicionar base de categoria ao URL no tipo personalizado tipo / taxonomia
-
-
Recentemente,enfrentoesseproblema.** Resolvido! ** [# 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
-
** Solução! ** (Apóspesquisa semfim)
Você devemodificar ofiltro "post_type_link`.Maisem: 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
-
Possível duplicado de [Como alterar aestrutura Permalinkpara otipo depostagempersonalizadae suastaxonomias?] (http://wordpress.stackexchange.com/Questions/28979/How-to-change-permalink-structur-for-custom-post-type-e - suastaxonomias)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 respostas
- votos
-
- 2013-04-06
Altere sua reescritapara adicionar a consulta do curso var:
'rewrite' => array('slug' => 'courses/%course%')
Entãofiltre
post_type_link
parainserir o curso selecionadopara o 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 );
Hátambémplugins como Tipo depostpersonalizado Permalinks Issopodefazerissopor você.
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.
-
Obrigado,agradeço sua resposta rápida.Issofaztodo o sentido.Euestou curioso,porém,ondeeuinsiro ofiltropost_type_linkem?Posso apenasirnaparteinferior do documentointeiro?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
-
Eu adicionei aofundoe apágina 404.I added it to the bottom and it 404's the page.
- 0
- 2013-04-06
- Zach Russell
-
Vocêtem que lavar a reescrita,visite apágina Configurações do Permalinks.you have to flush rewrites, visit the permalinks settings page.
- 1
- 2013-04-06
- Milo
-
Observetambém que vocêprovavelmenteterá um choque com umataxonomiae umtipo depostagem,ambos compartilhando amesma lesma.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
-
Ondeestou agora éfazer o Permalinks certo,masnão éexecutado corretamente (émacio 404ing).Alguma recomendação sobre o quepossofazerparafazerissofuncionando certo?Euestou longe das reescritas deflush de Permalink.Basta clicarem 'Salvar'e atualiza o arquivo (énginxpara queele seja controladono arquivonginx.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
-
Entendi!Foi um conflito.Got it! It was a conflict.
- 0
- 2013-04-06
- Zach Russell
-
Downvote - Arquivo Page 404Downvote - archive page 404
- 1
- 2020-04-04
- Dev
-
Issonãofuncionaparapoststraduzidosem um sitemultilíngüe (porexemplo,usando WPML).This doesn't work for translated posts on a multilingual site (for example using WPML).
- 0
- 2020-08-05
- montrealist
-
Issomostra ofrontpageparamim no URL recém-criado.Vocêtem que usar o add_rewrite_rule () vistona resposta @ Florisparafazerissofuncionar.Observaçãotambém,Arquivarpáginas Param defuncionar,recebo 404para/My-Post-Typee For/My-Post-Type/My-CategoriaThis 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
A soluçãoparamim tevetrêspartes. Nomeu caso,otipo depost é chamado detreinamentos .
- .
- adicionar
'reescrever'=> array ('slug'=> 'Treinings/% cat%')
para oregister_post_type
função. - Altere a Slugparater uma categoria dinâmica.
- "Ouça"para onovo URL dinâmicoe carregue omodelo apropriado.
Então aqui é como alterar o Permalink dinamicamentepara um determinadotipo depostagem. Adicionar a
funções.php : função vx_soon_training_post_link ($post_link,$id=0) { $post=get_post ($ ID); if (is_object ($post)) { $ Termos=WP_GET_OBJECT_TERMS ($post-egt;id,'treinamento_cat'); if ($ TERMES) { retorno str_replace ('% cat%',$ Termos [0] - > slug,$post_link); } } retornar $post_link; } add_filter ('post_type_link','vx_soon_training_post_link',1,3);
...e é como carregar omodelo apropriadononovo URL dinâmico. Adicionar a
funções.php : Função Archive_REWRITE_RULES () { add_rewrite_rule ( '^treinamento/(.*)/(.*)/?$', 'index.php?post_type=treinamentose amp;nome=$ correspondentes [2]', 'topo' ); //flush_rewrite_rules ();//use apenas uma vez } add_action ('init','archive_rewrite_rules');
isso éisso! Lembre-se de atualizar os Permalinks salvando aspermalinksnovamenteem debackend. Ou usar o
flush_rewrite_rules ()
função.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
Tem a solução!
Paraterpermalinks hierárquicospara otipo depostagempersonalizado Instalar otipo depostagempersonalizado Permalinks ( https://wordpress.org/plugins/custom-post-type-permalinks/)plugin.
Atualizar otipo depostagem registrado. Eutenho umnome detipo como centro de ajuda
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');
e aqui é ataxonomia 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 é a linhafaz o seutrabalho de Permalink
"cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/",
Vocêpode remover
%post_id%
e podemanter/%help_centre_category%/%postname%/"
Não seesqueça de lavarpermalinks dopainel.
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
sim! Apósmuitapesquisaeu recebiplugin ' Permalinkspersonalizados '.Que cumpremeu requisito cumprimentos - URLpersonalizadoe.g.
- para categoria
- parapost
- parapostpersonalizado
- parataxonomiapersonalizada etc.
Comoeste Tipo depostagempersonalizado - Post :
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
Vocêprecisa atualizar abaixo da linha onde você registra umtipo depostagempersonalizado usando afunção Register_Post_Type.
'rewrite'=>matriz ('slug'=> 'cursos/% cat%')
Para alterar o Permalink dinamicamente dotipo depostagem Você deve adicionar código abaixono arquivo Functions.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' );
Depois disso,vocêprecisaflush rewriting Permalinks,goto o wp-admin> Configurações> Permalinks . Basta atualizar a configuração Permalink usando obotão "Salvar alterações".
Devolverá URLs como abaixo:
- domain.com/courses/[Nome do curso {Categoria}]/Lesson-Name
Obrigado!
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!
-
Down voto - 404em tipos depágina de arquivo CPTe CTPindividuaisDown vote - 404 on both single CPT and CTP archive page types
- 0
- 2020-04-04
- Dev
-
@Dev Você seguiutodos ospassos queeumencioneinaminha resposta?Você lavou sua reescrita Permalinks?Eutesteie estáfuncionandobem.@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
Isso étrabalhadoparamim:
'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 ),
-
Issonãofaz uso das categorias ou do seu caminho que sófaz otipopersonalizadotipo hierá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 qualquerpessoainteressadana solução,semter quemexer com código PHP cru,eu recomendo altamente oplugin Permalink Manager Lite por Maciej Bis.É umpoupador de vida.
Tem ummecanismo visualpara remover ou adicionar qualquerparte que você desejana URL dotipo Postpersonalizado combaseem 'peremastructs':
(comtoda a dorenvolvidaem estruturas simples de URL comtipospersonalizados,estávamosprestes a desistir do WPe passarpara outro CMS. Masestepluginem conjunto com ACFe CPII ou vagenstorna o WordPressbastanteprofissional.)/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
Se vocêestiver usando
get_post_type_archive_link()
,talvezprecise remover/%cat%/
apartir do URL usandopost_type_archive_link
filtro.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
Euencontrei @ a resposta de Chetan-Vaghela quaseperfeita;Nomeu caso de uso,eutambém queriapoder ver uma lista detodas aspostagens destetipotipo como umapágina de arquivotípica (isto é,cursos/,semtaxonomia depois).Eu sótive que adicionar uma regra de reescrita adicional da seguinteforma:
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' ); }
Euestou construindo um sistema detipo LMSno WordPress,controladopor
)e tem um
Tipos depostpersonalizados
.Otipo depost é chamado
lições
(com uma lesma de códigostaxonomiapersonalizada
(categoria) chamadaCursos
.Aestrutura do URL do domíniomostra agora como:
domain.com/courses/lesson-name
.Eu quero que setorne:
domain.com/courses/[Nome do curso {Categoria}]/Lição-Nome
ouessencialmente:
/[CPT]/% Categoria%/% PostName%/
Aquiestá oplugin queeuescrevi queestá controlando os CPOS agora.