How to add 2 different taxonomies to Wordpress CPT permalink structure - wordpress

I have problem to add a second taxonomy to my cpt permalink structure.
With one register_taxonomy (pxlr-products-category) everything works fine and looks like this: https://example.com/products/my_category/my_productname
But I want a second register_taxonomy (pxlr-products-status). When I do that I see in my permalink instead of the tax slug just this %status% https://example.com/products/my_category/%status%/my_productname and I get an 404 error. Of cause I'ved flushed my permalinks
A second thing is, (pxlr-products-status) can have a value like (discontinued) but it is not a must, it can be empty as well
My permalinks should look like this https://example.com/products/my_category/my_status/my_productname
Or look like this https://example.com/products/my_category/my_productname
Here is my CPT, I can't find my error and need help, thanks :-/
class PXLR_Products
{
function __construct(){
// register post type
add_action('init', array($this, 'register_products_post_type'));
// register taxonomy
add_action('init', array($this, 'register_products_taxonomy'));
// slug - category filter
add_filter('post_type_link', [$this,'products_post_link'], 1, 3 );
// Rewrite support
add_action('init', [$this, 'custom_rewrite_rules']);
}
function custom_rewrite_rules() {
add_rewrite_rule(
'products/(.+?)/?$',
'index.php?pxlr-products-category=$matches[1]',
'bottom');
// add_rewrite_rule(
// 'products/(.+?)/(.+?)/?$',
// 'index.php?pxlr-products-category=$matches[1]&pxlr-products-status=$matches[2]',
// 'bottom');
}
public function register_products_post_type()
{
$labels = array(
'name' => _x('Products', 'Post Type General Name', 'pxlr-products'),
'singular_name' => _x('Products', 'Post Type Singular Name', 'pxlr-products'),
'menu_name' => __('PXLR Products', 'pxlr-products'),
'all_items' => __('All Products', 'pxlr-products'),
'view_item' => __('Show product', 'pxlr-products'),
'add_new_item' => __('Add product', 'pxlr-products'),
'add_new' => __('Add Product', 'pxlr-products'),
'edit_item' => __('Edit product', 'pxlr-products'),
'update_item' => __('Update product', 'pxlr-products'),
'search_items' => __('Search products', 'pxlr-products'),
'not_found' => __('No products found', 'pxlr-products'),
'not_found_in_trash' => __('No products found in trash.', 'pxlr-products'),
);
$args = array(
'labels' => $labels,
'name' => 'Products',
'name_admin_bar' => 'Products',
'singular_name' => 'Products',
'menu_icon' => 'dashicons-microphone',
'label' => __('Products', 'pxlr-products'),
'hierarchical' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'show_in_nav_menus' => false,
'menu_position' => 28,
'supports' => array('title', 'editor', 'revisions', 'thumbnail', 'page-attributes', 'excerpt', 'custom-fields'),
'rest_base' => 'products',
'public' => true,
'show_ui' => true,
'has_archive' => 'products',
'can_export' => false,
'taxonomies' => array('pxlr-products-category', 'pxlr-products-status'),
'publicaly_queryable' => true,
'query_var' => true,
'exclude_from_search' => false,
//'rewrite' => ['slug' => _x('products/%category%', 'Post Type Slug', 'pxlr-products'), 'with_front' => true ], // for one taxonomy if working fine!!!!
'rewrite' => ['slug' => _x('products/%category%/%status%', 'Post Type Slug', 'pxlr-products'), 'with_front' => true ], // for two taxonomies
'template_lock' => 'all',
);
register_post_type('pxlr-products', $args);
}
public function products_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) ){
$terms = wp_get_object_terms( $post->ID, 'pxlr-products-category' );
if( $terms ){
return str_replace( '%category%' , $terms[0]->slug , $post_link );
}
$terms = wp_get_object_terms( $post->ID, 'pxlr-products-status' );
if( $terms ){
return str_replace( '%status%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
public function register_products_taxonomy()
{
register_taxonomy(
'pxlr-products-category',
'pxlr-products',
array(
'label' => __('Categories Product', 'pxlr-products'),
'hierarchical' => true,
'with_front' => false,
'show_in_rest' => true,
'rewrite'=> ['slug' => _x('products', 'Category Slug', 'pxlr-products'),
'with_front' => false,
'hierarchical' => true
],
'show_admin_column' => true,
'show_in_nav_menus' => true,
'has_archive' => true,
)
);
register_taxonomy(
'pxlr-products-status',
'pxlr-products',
array(
'label' => __('Status Product', 'pxlr-products'),
'hierarchical' => true,
'with_front' => false,
'show_in_rest' => true,
'rewrite'=> ['slug' => _x('products/%category%', 'Status Slug', 'pxlr-products'),
'with_front' => false,
'hierarchical' => true
],
'show_admin_column' => true,
'show_in_nav_menus' => true,
'has_archive' => true,
)
);
}
}

Related

Adding Custom Taxonomies to all posts page

I've got a custom post type, Staff, and this post type has a custom taxonomy, Roles. I would like to be able to sort by/see roles on all staff page in the wp-admin backend like how categories and tags work by default for posts.
Thanks
Custom post type
function register_staff(){
$labels = array(
'name' => 'Staff',
'singular_name' => 'Staff',
'add_new' => 'Add Staff',
'all_items' => 'All Staff',
'add_new_item' => 'Add Staff Member',
'edit_item' => 'Edit Staff Member',
'new_item' => 'New Staff Member',
'view_item' => 'View staff',
'search_item' => 'Search staff',
'not_found' => 'No Items Found',
'not_found_in_trash' => 'No staff found in trash',
);
$args = array(
'labels' => $labels,
'public' => false,
'show_ui' => true,
'has_index' => true,
'has_archive' => true,
'publicly_queryable' => true,
'query_var' => true,
'has_archive' => true,
'rewrite' => true,
'capability_type' => "post",
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'page-attributes',
'excerpt',
'thumbnail',
'revisions',
),
'taxonomies' => array("role"),
'menu_position' => 5,
'menu_icon' => "dashicons-businessperson",
'exclude_from_search' => false,
);
register_post_type('staff', $args);
}
add_action( "init", "register_staff");
Custom Taxonomy
add_action( "init", "register_staff");
function build_taxonomies() {
register_taxonomy('role', 'staff', array(
'label' => 'Roles',
'public' => true,
));
}
add_action( 'init', 'build_taxonomies', 0 );
See https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column
Untested like this:
if ( !function_exists('AddTaxColumn') ) {
function AddTaxColumn($cols) {
$cols['yourtaxonomy'] = __('My Taxonomy');
return $cols;
}
function AddTaxValue($column_name, $post_id) {
if ( 'yourtaxonomy' == $column_name ) {
$tax_id = wp_get_post_terms( $post_id, 'yourtaxonomy' );
if ($tax_id) {
$taxonomies = join( ", ", $tax_id );
echo $taxonomies;
}
}
}
add_filter( 'manage_team_posts_columns', 'AddTaxColumn' );
add_action( 'manage_team_posts_custom_column', 'AddTaxValue', 10, 2 );
add_filter( 'manage_edit-team_sortable_columns', 'AddTaxColumn' );
}

I created cpt in WP and did not show the taxonomy, what did I do wrong?

I created the Wordpress plugin below to show a CPT called articles within the admin panel.
Within this CPT I created a taxonomy item to register the categories.
But I'm having trouble creating the part that shows the CPT taxonomy.
Apparently the code part is correct but I do not find the problem.
I need help finding out what I wrote wrong in the code and why it does not show the taxonomy item in the CPT menu I created.
<?php
/*
Plugin Name: Artigos
Version: 1.0
*/
/*POST TYPE*/
add_action('init', 'cpt_artigos');
function cpt_artigos() {
$labels = array(
'menu_name' => __('Artigos'),
'name' => __('Artigos'),
'singular_name' => __('Artigo'),
'all_items' => __('Todos os cadastros'),
'add_new' => __('Adicionar novo cadastro', 'Novo cadastro'),
'add_new_item' => __('Novo cadastro'),
'edit' => __('Editar'),
'edit_item' => __('Editar cadastro'),
'new_item' => __('Novo cadastro'),
'view' => __('Ver'),
'view_item' => __('Ver cadastro'),
'search_items' => __('Procurar cadastros'),
'not_found' => __('Nenhum registro encontrado'),
'not_found_in_trash' => __('Nenhum registro encontrado na lixeira'),
);
$args = array(
'labels' => $labels,
'menu_icon' => 'dashicons-star-filled',
'capability_type' => 'post',
'menu_position' => 5,
'supports' => array('title','editor','thumbnail'),
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'query_var' => true,
'can_export' => true,
'has_archive' => true,
'hierarchical' => true,
'rewrite' => true
);
register_post_type( 'artigos' , $args );
flush_rewrite_rules();
}
//TAXONOMY
add_action( 'init', 'taxonomyartigos');
function taxonomyartigos() {
$labels = array(
'menu_name' => __( 'Categorias de Artigos' ),
'name' => __( 'Categorias de Artigos' ),
'singular_name' => __( 'Categoria de Artigo' ),
'search_items' => __( 'Procurar Cadastros' ),
'all_items' => __( 'Todos os Cadastros' ),
'parent_item' => __( 'Categoria de Artigo Principal' ),
'parent_item_colon' => __( 'Categoria de Artigo Principal:' ),
'edit_item' => __( 'Editar Cadastro' ),
'update_item' => __( 'Atualizar Cadastro' ),
'add_new_item' => __( 'Adicionar novo cadastro' ),
'new_item_name' => __( 'Novo Cadastro' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'hierarchical' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'show_in_nav_menus' => true,
'has_archive' => true,
'rewrite' => true,
);
register_taxonomy( 'taxonomyartigos', array( 'cpt_artigos' ), $args );
flush_rewrite_rules();
}
function cpt_artigos_flush_rewrite() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action('init', 'cpt_artigos_flush_rewrite');
?>
You need to write the post type name instead of the function
register_taxonomy( 'taxonomyartigos', 'artigos', $args );
Hope it will do.
Follow the documentation is a good idea in any case.
Below function takes 3 arguments in order.
taxonomy string which will be registered
post_type of CPT taxonomy will be attached with ( array or multiple CPT type or single CPT string)
Taxomony args as an array.
register_taxonomy( string $taxonomy, array|string $object_type, array|string $args = array() )
Ref: Here

Rewrite Custom Post Type(with taxonomies) URL

I have a Custom Post Type with 1 taxonomy and this is the link structure:
mywebsite.com/casos-legal (Show the post in archive-casos-legal.php)
And when I click on any post:
mywebsite.com/casos-legal/lima/this-is-the-post-title
In the case above, "lima" is a term of the taxonomy.
Is there a way to add a path before "casos-legal"? something like this:
mywebsite.com/temas/legal/casos-legal
and:
mywebsite.com/temas/legal/casos-legal/lima/this-is-the-post-title
And much better, change the post slug for just "casos" to get something like this:
mywebsite.com/temas/legal/casos/lima/this-is-the-post-title
Thank in advance!
This is how it looks the CTP
function aprodeh_casos(){
$labels = array(
'name' => 'Casos - legal',
'singular_name' => 'Caso',
'add_new' => 'Agregar',
'all_items' => 'Todos',
'add_new_item' => 'Agregar',
'edit_item' => 'Editar',
'new_item' => 'Nuevo',
'view_item' => 'Ver',
'search_item' => 'Buscar',
'not_found' => 'No se encontraron casos',
'not_found_in_trash' => 'No se encontraron casos en la papelera',
'parent_item_colon' => 'Parent Item',
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'query_var' => true,
'rewrite' => array( 'slug' => '/casos-legal/%categoria_casos%', 'with_front' => false ),
'has_archive' => 'casos-legal',
'capability_type' => 'post',
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'thumbnail',
),
'menu_position' => 5,
'exclude_from_search' => false,
'taxonomies' => array('post_tag'),
);
register_post_type('casos-legal',$args);
} add_action('init','aprodeh_casos');
This is how it looks the Taxonomy:
function aprodeh_casos_taxonomia(){
$labels = array(
'name' => 'Categorías',
'singular_name' => 'Categoría',
'search_items' => 'Buscar categoría',
'all_items' => 'Todas las categorías',
'edit_item' => 'Editar categoría',
'update_item' => 'Actualizar categoría',
'add_new_item' => 'Agregar categoría',
'new_item_name' => 'Nuevo categoría',
'menu_name' => 'Categorías',
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'casos-legal', 'with_front' => false ),
);
register_taxonomy('categoria_casos', array('casos-legal'), $args);
}
add_action('init', 'aprodeh_casos_taxonomia');
And finally, this code in order to get this link structure:
mywebsite.com/casos-legal/lima/this-is-the-post-title
function wpa_casos_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'casos-legal' ){
$terms = wp_get_object_terms( $post->ID, 'categoria_casos' );
if( $terms ){
return str_replace( '%categoria_casos%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_casos_permalinks', 1, 2 );
Try updating
'rewrite' => array( 'slug' => '/casos-legal/%categoria_casos%', 'with_front' => false ),
to
'rewrite' => array( 'slug' => '/tema/legal/casos/%categoria_casos%', 'with_front' => false ),

Unable to get custom post type name with get_post_type()

Unable to get my custom post type name to load single-jobs.php page can some please help me where i'm doing something wrong in code or is there any permalink issue.
Code to load single page template for jobs post type
function wwp_job_portal_single_page($original_template){
//check post type to job portal single page
$type=get_post_types();
if(get_query_var( 'post_type' ) !== 'jobs'){
return ;
}
elseif(is_single('jobs')){
//check if file exit of single job page template
if(file_exists(file_exists( get_stylesheet_directory(). '/single-jobs.php' ))){
return get_stylesheet_directory() . '/single-jobs.php';
}
else{
return plugin_dir_path( __FILE__ ) . 'templates/single-jobs.php';
}
}
else{
echo "<h1>jobs page loaded</h1>";
return plugin_dir_path( __FILE__ ) . 'templates/single-jobs.php';
}
return $original_template;
}
add_action('template_include','wwp_job_portal_single_page');
Custom post type registration code
function create_jobs_post_type(){
// set up labels
$labels = array(
'name' => 'Job',
'singular_name' => 'Job',
'add_new' => 'Post New Job',
'add_new_item' => 'Post New Job',
'edit_item' => 'Edit Job',
'new_item' => 'New Job',
'all_items' => 'All jobs',
'view_item' => 'View jobs',
'search_items' => 'Search Job',
'not_found' => 'No Job Found',
'not_found_in_trash' => 'No Job found in Trash',
'parent_item_colon' => '',
'menu_name' => 'Jobs',
);
//register post type
register_post_type( 'jobs', array(
'labels' => $labels,
'has_archive' => true,
'public' => true,
'supports' => array('title','thumbnail'),
'publicly_queryable' => true,
'exclude_from_search' => true,
'show_in_nav_menus' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-id-alt',
'can_export' => true,
'delete_with_user' => false,
'hierarchical' => false,
'has_archive' => true,
'query_var' => true,
'capability_type' => 'post',
'map_meta_cap' => true,
// 'capabilities' => array(),
'rewrite' => array(
'slug' => 'jobs',
'with_front' => true,
'pages' => true,
'feeds' => false,
),
)
);
$taxonomy_args = array(
'labels' => array( 'name' => 'Job Category' ),
'show_ui' => true,
'hierarchical' => true,
'rewrite' => array( 'slug' => 'jobs' )
);
register_taxonomy(
'jobs_category',
'jobs',
$taxonomy_args
);
}
//hook for theme setup
add_action('init','create_jobs_post_type');
The function get_post_type() can be use outside the loop but then require the optional argument ($post_id) to be set.
In your code, you'll need to set the post ID as argument.
function wwp_job_portal_single_page($original_template){
global $post;
//check post type to job portal single page
$type=get_post_types($post->ID);
.....
Then your function will be able to find the related post ID you are looking for.
Can you please try the same function with the post ID, just like :
get_post_type( get_the_ID() )
Hope that will do

Wordpress Custom Type permalink with custom Taxonomy slug

I have a custom post type on my site called Homes, with a custom taxonomy called homes-category. They are both working correctly, but I am having trouble with the permalinks. I need the permalink to be homes/homes-category/pagename. I wrote a rewrite function, so the permalink is showing up correctly whenever I go to a homes item, but I get a 404 on the page itself. I am not sure what is causing this and have no ideas on how to fix it. The homes items work fine without the custom taxonomy in the permalink, but not with it. Does anyone have any ideas on how to fix this? I've been searching for days with no luck.
Here is the code for my custom post type:
register_post_type( 'Homes',
array(
'labels' => array(
'name' => __( 'Homes' ),
'singular_name' => __( 'Homes Item' ),
'add_new_item' => __('Add New Homes Item'),
'edit_item' => __('Edit Homes Item'),
'new_item' => __('New Homes Item'),
),
'supports' => array('title', 'thumbnail', 'editor'),
'taxonomies' => array('homes-category'),
'public' => true,
'has_archive' => false,
'show_in_nav_menus' => TRUE,
'show_in_menu' => TRUE,
'rewrite' => array(
'slug' => 'homes/%homes-category%',
'with_front' => true,
'hierarchical' => true,
),
)
);
Here is the code for my custom taxonomy
register_taxonomy(
'homes-category',
'homes',
array(
'hierarchical' => true,
'label' => __( 'Availability Category' ),
'rewrite' => array(
'slug' => 'homes',
'with_front' => false,
),
)
);
And here is the rewrite function
function custom_post_link($post_link, $id = 0)
{
$post = get_post($id);
if(!is_object($post) || $post->post_type != 'homes')
{
return $post_link;
}
$homes = 'misc';
if($terms = wp_get_object_terms($post->ID, 'homes-category'))
{
$client = $terms[0]->slug;
//Replace the query var surrounded by % with the slug of
//the first taxonomy it belongs to.
return str_replace('%homes-category%', $homes, $post_link);
}
//If all else fails, just return the $post_link.
return $post_link;
}
add_filter('post_type_link', 'custom_post_link', 1, 3);
You need to add rewrite_tag for, '%homes-category%'
Even you need to add, custom rewrite_rule, to interpret it correctly.
You can use below code,
add_action('init','wdm_register_post_types');
function wdm_register_post_types()
{
global $wp_rewrite;
register_post_type( 'Homes',
array(
'labels' => array(
'name' => __( 'Homes' ),
'singular_name' => __( 'Homes Item' ),
'add_new_item' => __('Add New Homes Item'),
'edit_item' => __('Edit Homes Item'),
'new_item' => __('New Homes Item'),
),
'supports' => array('title', 'thumbnail', 'editor'),
'taxonomies' => array('homes-category'),
'public' => true,
'has_archive' => false,
'show_in_nav_menus' => TRUE,
'show_in_menu' => TRUE,
'rewrite' => array(
'slug' => 'homes/%homes-cat%',
'with_front' => true,
'hierarchical' => true
),
)
);
register_taxonomy(
'homes-category',
'homes',
array(
'hierarchical' => true,
'label' => __( 'Availability Category' ),
'rewrite' => array(
'slug' => 'homes-category',
'with_front' => true,
),
)
);
$wp_rewrite->add_rewrite_tag( '%homes-cat%', '[a-zA-Z0-9_]');
add_rewrite_rule('^homes/([^/]+)/([^/]+)/?$','index.php?homes=$matches[2]','top');
}
function wp_tuts_filter_post_link( $permalink, $post ) {
if ( false === strpos( $permalink, '%homes-cat%' ) )
return $permalink;
$terms = current(wp_get_post_terms( $post->ID, 'homes-category', array('fields' => 'slugs')));
$permalink = str_replace( '%homes-cat%', $terms , $permalink );
return $permalink;
}
add_filter( 'post_link', 'wp_tuts_filter_post_link' , 10, 2 );
add_filter('post_type_link','wp_tuts_filter_post_link' , 10, 2 );
This will interpret,
http://domain.com/homes/2-bhk/home-1/
properly.
For more details you can also check out this blog post on Creating Custom WordPress Rewrite Rules for Pretty Permalinks

Resources