Post Type & Taxonomy same slug issue - php

I am working on a post_type and taxonomy. I create a page template "foo_template.php" for its main page, in main page I write a query that shows all taxonomies and related (5) Five posts. When i click on any taxonomy the new page open and it shows all post titles of clicked taxonomy and its slug is "foo_taxonomy", i also create for it a page "taxonomy-foo_post.php" and when i click any title it goes on single page which i created for it "single-foo_post.php" and its slug is "foo_post".
Now the main issue is i want that post type and taxonomy slug is same when i do this my page layout is disturbed and it goes to archive.php
My friend give me some code i write it, where post_type and taxonomy slug is same, when i click on the taxonomy the page open with new same slug but when i click on the post title for single page it shows that "Page not found"
What is the issue i don't get it.
Here is my code:
Post type and Taxonomy code:
add_action('init', 'foo_articles');
function foo_articles() {
register_post_type('foo_knowledgebase', array(
'labels' => array(
'name' => 'Articles',
'singular_name' => 'Article'
),
'public' => true,
'rewrite' => array(
'slug' => 'My_slug')
));
}
add_action( 'init', 'foo_taxonomies', 0 );
function foo_taxonomies() {
register_taxonomy('foo_taxonomy', array('My_slug'), array(
'labels' => array(
'name' => 'Articles Category'
),
'show_ui' => true,
'show_admin_column' => true,
'show_tagcloud' => FALSE,
'hierarchical' => true,
'rewrite' => array('slug' => 'My_slug', 'with_front' => TRUE)
));
}
For same slug code:
$rules = array();
$taxonomies = get_taxonomies(array('_builtin' => false), 'objects');
$post_types = get_post_types(array('public' => true, '_builtin' => false), 'names');
foreach ($post_types as $post_type) {
$post_type_data = get_post_type_object( $post_type );
$post_type_slug = $post_type_data->rewrite['slug'];
foreach ($taxonomies as $taxonomy) {
if ($taxonomy->object_type[0] == $post_type_slug) {
$categories = get_categories(array('type' => $post_type_slug, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0));
/* #var $category type */
foreach ($categories as $category) {
$rules[$post_type_slug . '/' . $category->slug . '/?$'] = 'index.php?' . $category->taxonomy . '=' . $category->slug;
}
}
}
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter( 'generate_rewrite_rules', 'taxonomy_slug_rewrite' );
My friend said that this code work for him but i dont now what happen here i copied same code.
This condition is also set true
if ($taxonomy->object_type[0] == $post_type_slug)
but i don't know why my slug not work.
Please help me

For what you want to achieve you will need to define the Custom Taxonomy BEFORE the Custom Post Type.
This way will work but in the unlikely event that your Taxonomy and your Post will have the same slug won't be able to view the entry.
e.g. if you will have a taxonomy term called "press" and a CPT with the title "press".

Related

Custom permalink structure for multiple custom post_type URLs using add_permastruct returning regular posts error / 404

In my WP v6.1, I have two custom port types: company, product and custom taxonomy country.
Desired URL structure is %country%/%company_postname% and %country%/%product_postname% respectively and below is the code for $wp_rewrite:
add_action('init', 'custom_init');
function custom_init() {
global $wp_rewrite;
$company_url = '/%country%/%company_postname%';
$product_url = '/%country%/%product_postname%';
$wp_rewrite->add_permastruct('company', $company_url, false);
$wp_rewrite->add_permastruct('product', $product_url, false);
$wp_rewrite->add_rewrite_tag("%company_postname%", '([^/]+)', "company=");
$wp_rewrite->add_rewrite_tag("%product_postname%", '([^/]+)', "product=");
}
With above code and another post_type_link filter function, I am able to generate my custom URLs. However the issue is regular post and page posts are not found returning error_404.
Regular post / page standard URL structure: www.example.com/%postname%
Have tried add_permastruct for posts & pages, but that did not worked. How do I show pages and posts while having the custom URLs for my custom posts.
Update 1
Custom posts and taxonomies were created by code.
Example of company code
function company_post_type() {
$labels = array(
'name' => _x('Company', 'Post Type General Name', 'text'),
);
$args = array(
'labels' => $labels,
'supports' => array('title', 'editor', 'custom-fields'),
'taxonomies' => array('country'),
'query_var' => true,
'rewrite' => false
);
register_post_type('company', $args);
}
add_action('init', 'company_post_type', 0);
Update 2
And my post_type_link function is:
function post_type_link_function($url, $post) {
// only if post is published
if ('' != $url && !in_array($post->post_status, array('draft', 'pending', 'auto-draft'))) {
// get country terms
$terms = wp_get_object_terms($post->ID, 'country');
// country
if (strpos($url, '%country%') !== FALSE) {
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) {
$country = urlencode($terms[0]->slug);
$url = str_replace('%country%', $country, $url);
}
}
// post names
$postnames = array('%company_postname%', '%product_postname%', '%postname%');
foreach ($postnames as $postname) {
$postname = $post->post_name;
$url = str_replace($postnames, $postname, $url);
}
return $url;
}
return $url;
}
Update 3
When permalinks set to Plain www.example.com/?p=123, all posts, pages and custom posts are loading fine.
Update 4
I have observed that posts and pages are not using either single.php or page.php template. It is using index.php.
Whereas, I have not attached any templates to these pages or posts.
Update 5 - resolved
It was due the 'rewrite' => array('slug' => '/', 'with_front' => FALSE) in the country custom taxonomy.
Without this rewrite now the pages and posts are fine.
You can use the post_type_link hook.
Add your custom post type and taxonomy with your custom rewrite:
function company_post_type() {
$labels = array(
'name' => _x('Company', 'Post Type General Name', 'text'),
);
$args = array(
'labels' => $labels,
'show_ui' => true,
'public' => true,
'publicly_queryable' => true,
'supports' => array('title', 'editor', 'custom-fields'),
'taxonomies' => array('country'),
'query_var' => true,
'rewrite' => array( 'slug' => '%country%', 'with_front' => false ),
);
register_post_type('company', $args);
$tax_args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'show_in_rest' => true,
);
register_taxonomy( 'country', 'company', $tax_args );
}
add_action('init', 'company_post_type', 0);
then we run a replace on the permalink via the hook:
function replace_post_link( $post_link, $id = 0 ){
$post = get_post($id);
$post_type = get_post_type( $id );
if ( is_object( $post ) && $post_type == 'company'){
$cat = 'country';
$terms = wp_get_object_terms( $post->ID, $cat );
if( $terms && !is_wp_error($terms) ){
return str_replace( '%country%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'replace_post_link', 1, 3 );
UPDATE:
There seems to be a quirk with wordpress when using this syntax for your rewrite so you will need to preface the term with a front.
'rewrite' => array( 'slug' => 'country/%country%', 'with_front' => false )
and in the replace post link:
return str_replace( 'country/%country%', $terms[0]->slug , $post_link );
Then your URL will be:
country/%country%/%company_postname%
make sure to flush your rewrite rules when you are done by going to: Settings > Permalinks and clicking 'save changes'

How to change slug in wordpress?

I have this URL for my Resort page page-resorts.php:
http://localhost/testwordpress/resorts/
After clicking the link to a post under Resort custom page I will have this URL for my custom page template (CPT) single-resort.php:
http://localhost/testwordpress/resort/kurumba-maldives/
As you can see the resorts was changed to resort because I can't use resorts slug for the slug post.
How can I achive this kind of URL:
http://localhost/testwordpress/resorts/kurumba-maldives/
where the resorts word is used and not resort word only?
I've heard about custom slug and search for it, but I still can't understand it.
You can create your custom post type this way.
function create_posttype() {
register_post_type( 'resort',
array(
'labels' => array(
'name' => __( 'Resorts' ),
'singular_name' => __( 'Resort' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'resorts'),
)
);
}
add_action( 'init', 'create_posttype' );
'rewrite' => array('slug' => 'resorts'), this used to add the slur on URL. this way you can acheive your URL.
Or you can override your current slug in functions.php
add_filter( 'register_post_type_args', 'wpse247328_register_post_type_args', 10, 2 );
function wpse247328_register_post_type_args( $args, $post_type ) {
if ( 'resort' === $post_type ) {
$args['rewrite']['slug'] = 'resorts';
}
return $args;
}
For more, please visit.
register post type
Change Custom Post Type slug

Add category selection to custom post type

I wanna be able to post my WooCommerce products into my "posts" categories. Based based off this cod below, it's possible. Here's the code I'm using in my functions.php. The categories are clickable when I make a new product in Woo however, it's not posting to the category itself. Appreciate any insight on this matter.
Add category selection to custom post type
function reg_cat() {
register_taxonomy_for_object_type('category','CUSTOM_POST_TYPE');
}
add_action('init', 'reg_cat');
For register custom taxonomy you can try below code, for more https://codex.wordpress.org/Function_Reference/register_taxonomy
<?php
add_action( 'init', 'create_book_tax' );
function create_book_tax() {
register_taxonomy(
'genre',
'book',
array(
'label' => __( 'Genre' ),
'rewrite' => array( 'slug' => 'genre' ),
'hierarchical' => true,
)
);
}
?>
Please try This Code for register new texonomy
function custom_taxonomy() {
register_taxonomy(
'custom_categories', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'post_type', //post type name
array(
'hierarchical' => true,
'label' => 'Themes store', //Display name
'query_var' => true,
'rewrite' => array(
'slug' => 'themes', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
}
add_action( 'init', 'custom_taxonomy');
Note: Please add this code in theme function.php or your plugin
=======================================================================
function reg_cat() {
register_taxonomy_for_object_type('category','CUSTOM_POST_TYPE');
}
add_action('init', 'reg_cat');
This code working post category display in custom post type texonomy section Please refer

WordPress slug without custom post type slug

I have register custom post type with following code:
register_post_type(
array(
'labels' => // array of labels,
'public' => true,
'publicly_queryable'=> true,
'show_ui' => false,
'map_meta_cap' => true,
'show_in_menu' => false,
'query_var' => true,
'rewrite' => array( 'slug' => 'movie' ),
'capability_type' => 'post',
'has_archive' => false,
'exclude_from_search' => true,
'supports' => array('title'),
)
);
The issue is that, the URL become for this post like:
http://yourdomain.com/movie/post_slug/
But, I need like:
http://yourdomain.com/post_slug/
Is there any way to remove post type slug "movie" from URL, like posts and pages display at front-end by default?
Thanks
You must register your post type movie in init.
register_post_type('movie', $args);
To replace the movie from post link use the below code.
function remove_my_post_type($post_link, $post, $leavename) {
if ($post->post_type != 'movie' || $post->post_status != 'publish') {
return $post_link;
}
$post_link = str_replace('/' . $post->post_type . '/', '/', $post_link);
return $post_link;
}
add_filter('post_type_link', 'remove_my_post_type', 10, 3);
After that you can set your post type shold be like a default post or page.
function set_my_post($query) {
if(isset($query->query['post_type'])){
return;
}
if (!empty($query->query['name'])) {
$query->set('post_type', array('post', 'movie', 'page'));
}
}
add_action('pre_get_posts', 'set_my_post');
I do not think there is straight forward solution this. If you need this so badly you can use Custom Rewrite For Post Slug
Have you tried:
'with_front' => bool Should the permalink structure be prepended with
the front base. (example: if your permalink structure is /blog/, then
your links will be: false->/news/, true->/blog/news/). Defaults to
true
https://codex.wordpress.org/Function_Reference/register_post_type
It's simple: set 'rewrite'-> true in your args array.

Listing taxonomy terms of a custom post type

I have created a custom post type with a custom taxonomy called 'sp_casestudy_category' like so:
function zen_create_casestudy_taxonomies()
{
$labels = array(
...
);
register_taxonomy("sp_casestudy_category", array("zen_casestudy"), array(
'hierarchical' => true,
'public' => true,
'show_in_nav_menus' => true,
'labels' => $labels,
'rewrite' => true,
'query_var' => true,
'rewrite' => array('slug' => 'casestudy/category')
));
}
add_action( 'init', 'sp_create_casestudy_taxonomies', 0 );
This seems to work fine, I can assign posts to these categories. However within another custom post type I am trying to list these terms in checkboxes so I can let the user choose which category to display the post on. For example the code is something like below to do this:
foreach ($meta_fields_category_sbteaser as $field) {
$options = $field['options'];
$meta = get_terms($options['taxonomy']);
switch ($field['type']) {
case 'checkbox':
foreach ($terms as $term) {
echo '<input type="checkbox" name="'.$field['id'].'" value="" /><br/>';
}
break;
} //end switch
} // end foreach
However I cannot get this to work. How would I list these categories in a custom meta box?
Thanks
Robert

Categories