I've tried so many different thing, and read 30 different posts and I just can't get the custom rewrite to work with a custom post_type and custom taxonomy.
Here's my code:
function product_register() {
$labels = array(
'name' => __('My Products', 'post type general name'),
'singular_name' => __('Product', 'post type singular name'),
'add_new' => __('Add New', 'Product'),
'add_new_item' => __('Add New Product'),
'edit_item' => __('Edit Product'),
'new_item' => __('New Product'),
'view_item' => __('View This Product'),
'search_items' => __('Search Products'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' =>$labels,
'public' => true,
'publicly_queryable' =>true,
'show_ui' =>true,
'query_var' => true,
'menu_icon' => plugin_dir_url( __FILE__ ).'/icon.png',
'rewrite' => array( 'slug' => 'products/%taxonomy_name%', 'with_front' => false,'hierarchical' => true),
'capability_type' => 'post',
'hierarchical' >= false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail','revisions')
);
register_post_type( 'products' , $args );
}
function create_product_taxonomies() {
$labels = array(
'name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Categories' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category Name' ),
'menu_name' => __( 'Categories' ),
);
$rewrite = array(
'slug' => 'products',
'with_front' => false,
'hierarchical' => true
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => $rewrite, // this makes hierarchical URLs
);
register_taxonomy( 'product_category', array( 'products' ), $args );
$labels = array(
'name' => _x( 'Sales', 'taxonomy general name' ),
'singular_name' => _x( 'Sale', 'taxonomy singular name' ),
'search_items' => __( 'Search Sales' ),
'all_items' => __( 'All Sales' ),
'parent_item' => __( 'Parent Sale' ),
'parent_item_colon' => __( 'Parent Sale:' ),
'edit_item' => __( 'Edit Sale' ),
'update_item' => __( 'Update Sale' ),
'add_new_item' => __( 'Add New Sale' ),
'new_item_name' => __( 'New Sale Name' ),
'menu_name' => __( 'Sale' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'product_sale', 'hierarchical' =>true ),
);
register_taxonomy( 'product_sale', array( 'products' ), $args );
}
function add_rules(){
add_rewrite_rule( '^products/(.+?)/(.+?)/$', 'products.php?posttype=$matches[2]', 'top' );
add_rewrite_rule( '^products/(.+?)/(.+?)/(.+?)$', 'products.php?taxonomy=$matches[3]', 'top' );
add_rewrite_rule( '^products/(.+?)/(.+?)/?$', 'products.php?taxonomy=$matches[2]', 'top' );
add_rewrite_rule( '^products/(.+?)/(.+?)/(.+?)/(.+?)$', 'products.php?taxonomy=$matches[3]&products=$matches[4]', 'top' );
}
/* Register products taxonomies */
add_action('init', 'create_product_taxonomies', 0 );
/* Register custom post types on the 'init' hook. */
add_action('init', 'product_register');
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'products')
return $link;
if ($cats = get_the_terms($post->ID, 'product_category'))
{
$replace = get_taxonomy_parents(array_pop($cats)->term_id, 'product_category', false, '/', true);
$link = str_replace('%taxonomy_name%', rtrim($replace, '/'), $link); // see custom function defined below
}
return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);
// my own function to do what get_category_parents does for other taxonomies
function get_taxonomy_parents($id, $taxonomy, $link = false, $separator = '/', $nicename = false, $visited = array()) {
$chain = '';
$parent = &get_term($id, $taxonomy);
if (is_wp_error($parent)) {
return $parent;
}
if ($nicename)
$name = $parent -> slug;
else
$name = $parent -> name;
if ($parent -> parent && ($parent -> parent != $parent -> term_id) && !in_array($parent -> parent, $visited)) {
$visited[] = $parent -> parent;
$chain .= get_taxonomy_parents($parent -> parent, $taxonomy, $link, $separator, $nicename, $visited);
}
if ($link) {
// nothing, can't get this working :(
} else
$chain .= $name . $separator;
return $chain;
}
So, when I go to example.com/cat_1/cat_2/cat_3, it all works. It shows the proper category. When I add the actual product on the end, it gives me a error 404. I should also note that even though the rewrite is for products.php, I actually have to use taxonomy.php for it to show up.
Am I missing some configuration details somewhere?
DUH! Answered my question, and now I'm beating my head against the wall really hard....
Changed:
add_rewrite_rule( '^products/(.+?)/(.+?)/(.+?)/(.+?)$', 'products.php?taxonomy=$matches[3]&products=$matches[4]', 'top' );
To:
add_rewrite_rule( '^products/(.+?)/(.+?)/(.+?)/(.+?)$', 'index.php?taxonomy=$matches[3]&products=$matches[4]', 'top' );
Need to use index.php to show the post details. Man alive....
Related
I simply want two custom post type meta propertys to be the identifiers for the URL. I implements a solution but it just 404's
registering post type:
final private static function register_post_types ()
{
$labels = array(
'name' => _x( 'Properties', 'post type general name', ' propertystreambootstrap' ),
'singular_name' => _x( 'Property', 'post type singular name', ' propertystreambootstrap' ),
'menu_name' => _x( 'Properties', 'admin menu', ' propertystreambootstrap' ),
'name_admin_bar' => _x( 'Property', 'add new on admin bar', ' propertystreambootstrap' ),
'add_new' => _x( 'Add New', 'property', ' propertystreambootstrap' ),
'add_new_item' => __( 'Add New Property', ' propertystreambootstrap' ),
'new_item' => __( 'New Property', ' propertystreambootstrap' ),
'edit_item' => __( 'Edit Property', ' propertystreambootstrap' ),
'view_item' => __( 'View Property', ' propertystreambootstrap' ),
'all_items' => __( 'All Properties', ' propertystreambootstrap' ),
'search_items' => __( 'Search Properties', ' propertystreambootstrap' ),
'parent_item_colon' => __( 'Parent Properties:', ' propertystreambootstrap' ),
'not_found' => __( 'No properties found.', ' propertystreambootstrap' ),
'not_found_in_trash' => __( 'No properties found in Trash.', ' propertystreambootstrap' )
);
$args = array(
'labels' => $labels,
'description' => __( 'Properties for your website.', ' propertystreambootstrap' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-building',
'query_var' => true,
//'rewrite' => array( 'slug' => 'malta-property/%department%/%location%/%reference%' ),
'rewrite' => array( 'slug' => 'malta-property/%location%/%reference%'),
'has_archive' => 'about-cool-post-types',
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title', 'editor', 'excerpt', 'post-thumbnails', 'thumbnail')
);
register_post_type( 'property', $args );
}
Url rewrites:
final public static function url_rewrite()
{
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag('%reference%', '([^&]+)', 'reference=');
$wp_rewrite->add_rewrite_tag('%location%', '([^&]+)', 'location=');
return null;
}
filter function:
final public static function permalink_structure ($permalink, $post, $leavename)
{
if (false !== strpos($permalink, '%reference%')) {
$reference = get_post_meta($post->ID, 'propertystream_agent_ref', true);
$location = wp_get_post_terms($post->ID, 'location');
$location = str_replace('-cat', '', $location[0]->slug);
// die($location);
// $department = wp_get_post_terms($post->ID, 'department');
$rewritecode = array(
'%reference%',
'%location%',
// '%department%',
$post->post_name,
);
$rewritereplace = array(
$reference,
$location,
// $department,
$leavename? $post->post_name : '',
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
}
return $permalink;
}
This all generates the code I want but it just 404's - to get it to work I have to add $leavename = true in the filter function but that adds the postname to the URL and I do not want that.
I've looked at other examples and solutions, but there has to be something I am missing. I've tried everything the other posts answers have suggested, but to no avail.
I'm not sure what exactly the issue is, but I can use get_terms without any parameters, and I get every term on my site, but clearly I want to isolate this to only the taxonomy declared. I am running this outside a loop, so I cannot pass an ID, nor do I want to pass an ID.
Any insight is helpful!
I am getting this when using get_terms().
object(WP_Error)#992 (2) {
["errors"]=>
array(1) {
["invalid_taxonomy"]=>
array(1) {
[0]=>
string(17) "Invalid taxonomy."
}
}
["error_data"]=>
array(0) {
}
}
My Code:
Taxonomy
if ( ! function_exists( 'car_ctax_catalog' ) ) {
// Register Custom Taxonomy
function car_ctax_catalog() {
$labels = array(
'name' => _x( 'Categories', 'Taxonomy General Name', 'carmon' ),
'singular_name' => _x( 'Category', 'Taxonomy Singular Name', 'carmon' ),
'menu_name' => __( 'Category', 'carmon' ),
'all_items' => __( 'All Categories', 'carmon' ),
'parent_item' => __( 'Parent Category', 'carmon' ),
'parent_item_colon' => __( 'Parent Category:', 'carmon' ),
'new_item_name' => __( 'New Category Name', 'carmon' ),
'add_new_item' => __( 'Add New Category', 'carmon' ),
'edit_item' => __( 'Edit Category', 'carmon' ),
'update_item' => __( 'Update Category', 'carmon' ),
'view_item' => __( 'View Category', 'carmon' ),
'separate_items_with_commas' => __( 'Separate categories with commas', 'carmon' ),
'add_or_remove_items' => __( 'Add or remove categories', 'carmon' ),
'choose_from_most_used' => __( 'Choose from the most used', 'carmon' ),
'popular_items' => __( 'Popular Categories', 'carmon' ),
'search_items' => __( 'Search Categories', 'carmon' ),
'not_found' => __( 'Not Found', 'carmon' ),
'no_terms' => __( 'No categories', 'carmon' ),
'items_list' => __( 'Categories list', 'carmon' ),
'items_list_navigation' => __( 'Categories list navigation', 'carmon' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => false,
'rewrite' => false,
'show_in_rest' => true,
'rest_base' => 'ctax_catalog',
);
register_taxonomy( 'ctax_catalog', array( 'cpt_catalog' ), $args );
}
add_action( 'init', 'car_ctax_catalog', 0 );
}
Get Terms
$args = array (
'post_type' => 'catalog',
'taxonomy' => 'ctax_catalog',
'hide_emoty' => false
);
$tax = array ( 'ctax_catalog' );
$terms = get_terms($tax, $args);
echo"<pre>";var_dump($terms);echo"</pre>";
EDIT
I've also tried this with the same result.
Get Terms Try 2
$terms = get_terms('ctax_catalog');
$tterms = get_terms( array ('taxonomy' => 'ctax_catalog' ) );
echo"<pre>";var_dump($terms);echo"</pre>";
echo"<pre>";var_dump($tterms);echo"</pre>";
I came up with the following hackish work-around, until a better solution could be found:
$terms = get_terms();
$gradeOptions = "";
foreach ($terms as $term) {
if ($term->taxonomy === "pa_grade") {
$gradeOptions .= "<options value=\"{$term->term_id}\">{$term->name}</options>";
}
}
var_dump($gradeOptions);
die();
I need to create a custom permalink structure, I want to show m custom taxonomy in the url, something like:
www.example.com/ristoranti/italia/milano/my-post-slug
The first segment is the post category, added with WP Categories menu.
italia and milano are taxonomies created with a custom plugin where milano is child of italia:
function mlt_create_custom_taxonomies()
{
$labels = [
'name' => _x( 'Locations', 'taxonomy general name', 'mlt' ),
'singular_name' => _x( 'Location', 'taxonomy singular name', 'mlt' ),
'search_items' => __( 'Search Locations', 'mlt' ),
'all_items' => __( 'All Locations', 'mlt' ),
'parent_item' => __( 'Parent Location', 'mlt' ),
'parent_item_colon' => __( 'Parent Location:', 'mlt' ),
'edit_item' => __( 'Edit Location', 'mlt' ),
'update_item' => __( 'Update Location', 'mlt' ),
'add_new_item' => __( 'Add New Location', 'mlt' ),
'new_item_name' => __( 'New Location Name', 'mlt' ),
'menu_name' => __( 'Location', 'mlt' ),
];
$args = [
'labels' => $labels,
'exclude_from_search' => true,
'has_archive' => true,
'hierarchical' => true,
'rewrite' => array( 'with_front' => false, 'hierarchical' => true, ),
'show_ui' => true,
'show_tagcloud' => false,
];
register_taxonomy( 'location', [ 'post' ], $args );
}
add_action('init', 'mlt_create_custom_taxonomies');
To add the custom taxonomies to the url I have edited my permalink structure like that:
/%category%/%location%/%postname%/
I have also added a rewrite rule for %location% in order to add the taxonomies:
function location_post_type_link( $link, $post ) {
if ('post' == $post->post_type) {
if ( $terms = get_the_terms( $post->ID, 'location' ) ) {
foreach ($terms as $term) {
$tax_array[] = $term->slug;
}
$link = str_replace( '%location%', implode('/',$tax_array), $link );
}
}
return $link;
}
add_filter( 'post_link', 'location_post_type_link', 10, 2 );
With this code I'm able to create the link.
The problem is that if I create a fake url like:
www.example.com/ristoranti/XXXXX/XXXX/my-post-slug I'm able to see the post, while the XXXX/XXX are completely wrong.
How is this possibile? How can I make sure that the taxonomy are correct in the url?
I tried to ask this question in the Wordpress Devlopment network with no success, I'm trying to display only 3 specific categories in permalinks for custom-post-type categories.
Right now the permalinks structure (that is the structure given by the theme i'm using and that i'm modifying through a child theme)is as follows:
www.myfoodblog.com/recipes/the-post-title/
^ ^ ^
root custom-post-type title
some post are under 3 categories that i would like to display in permalinks which are restaurant, users and admin to get something like this
www.myfoodblog.com/recipes/restaurant/the-post-title/
www.myfoodblog.com/recipes/users/the-post-title/
www.myfoodblog.com/recipes/admin/the-post-title/
leaving the original structure for posts that are not in those categories.
I tried using this plugin but it will display the custom post type category for all posts.
I also tried to follow the instructions provided in this question but it's not working, no changes are made in the permalinks structure.
Any advice is much appreciated.
You have to work with both post_type_link and add a rewrite rule
function recipes_post_link( $post_link, $id = 0 ){
$post = get_post( $id );
if ( is_object( $post ) ){
$terms = get_the_terms( $post->ID, 'recipe-category' );
foreach($terms as $term) {
if( $term->slug == 'restaurants' || $term->slug == 'users'){
return str_replace( site_url()."/recipes" , site_url()."/recipes/".$term->slug , $post_link );
}
}
}
return $post_link;
}
add_filter( 'post_type_link', 'recipes_post_link', 1, 3 );
function custom_rewrite_basic() {
add_rewrite_rule('^recipes/(.+)/(.+)', 'index.php?recipe=$matches[2]', 'top');
}
add_action('init', 'custom_rewrite_basic');
Create Post Type
add_action( 'init', 'codex_recipes_init' );
/**
* Register a recipes post type.
*
* #link http://codex.wordpress.org/Function_Reference/register_post_type
*/
function codex_recipes_init() {
$labels = array(
'name' => _x( 'Recipes', 'post type general name', 'your-plugin-textdomain' ),
'singular_name' => _x( 'Recipe', 'post type singular name', 'your-plugin-textdomain' ),
'menu_name' => _x( 'Recipes', 'admin menu', 'your-plugin-textdomain' ),
'name_admin_bar' => _x( 'Recipe', 'add new on admin bar', 'your-plugin-textdomain' ),
'add_new' => _x( 'Add New', 'recipe', 'your-plugin-textdomain' ),
'add_new_item' => __( 'Add New Recipe', 'your-plugin-textdomain' ),
'new_item' => __( 'New Recipe', 'your-plugin-textdomain' ),
'edit_item' => __( 'Edit Recipe', 'your-plugin-textdomain' ),
'view_item' => __( 'View Recipe', 'your-plugin-textdomain' ),
'all_items' => __( 'All Recipes', 'your-plugin-textdomain' ),
'search_items' => __( 'Search Recipes', 'your-plugin-textdomain' ),
'parent_item_colon' => __( 'Parent Recipes:', 'your-plugin-textdomain' ),
'not_found' => __( 'No recipes found.', 'your-plugin-textdomain' ),
'not_found_in_trash' => __( 'No recipes found in Trash.', 'your-plugin-textdomain' )
);
$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'your-plugin-textdomain' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'recipes/%type%' ),
'capability_type' => 'post',
'has_archive' => 'recipes',
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
);
register_post_type( 'recipes', $args );
}
Important: look on rewrite rule: 'rewrite'=> array( 'slug' => 'recipes/%type%' ),
Create Custom Taxonomy
// hook into the init action and call create_recipes_taxonomies when it fires
add_action( 'init', 'create_recipes_taxonomies', 0 );
function create_recipes_taxonomies() {
// Add new taxonomy, NOT hierarchical (like tags)
$labels = array(
'name' => _x( 'Type', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'Type', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search Types', 'textdomain' ),
'popular_items' => __( 'Popular Types', 'textdomain' ),
'all_items' => __( 'All Types', 'textdomain' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Type', 'textdomain' ),
'update_item' => __( 'Update Type', 'textdomain' ),
'add_new_item' => __( 'Add New Type', 'textdomain' ),
'new_item_name' => __( 'New Type Name', 'textdomain' ),
'separate_items_with_commas' => __( 'Separate types with commas', 'textdomain' ),
'add_or_remove_items' => __( 'Add or remove types', 'textdomain' ),
'choose_from_most_used' => __( 'Choose from the most used types', 'textdomain' ),
'not_found' => __( 'No types found.', 'textdomain' ),
'menu_name' => __( 'Types', 'textdomain' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'type' ),
);
register_taxonomy( 'type', 'recipes', $args );
}
Add Filter Post Type Link
function recipes_post_link( $post_link, $id = 0 ){
$post = get_post( $id );
if ( is_object( $post ) ){
$terms = wp_get_object_terms( $post->ID, 'type' );
if( $terms ){
return str_replace( '%type%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'recipes_post_link', 1, 3 );
Important: After all go to permalink options and reset it.
I have Custom Post Type.
Permalinks looks like /%postname%
My CPT function:
function cpt_lyrics() {
$labels = array(
'name' => _x( 'Lyrics', 'Post Type General Name', 'Lyrics' ),
'singular_name' => _x( 'Lyrics', 'Post Type Singular Name', 'Lyrics' ),
'menu_name' => __( 'Lyrics', 'Lyrics' ),
'parent_item_colon' => __( 'Parent Lyrics:', 'Lyrics' ),
'all_items' => __( 'All Lyrics', 'Lyrics' ),
'view_item' => __( 'View Lyrics', 'Lyrics' ),
'add_new_item' => __( 'Add New Lyrics', 'Lyrics' ),
'add_new' => __( 'Add New', 'Lyrics' ),
'edit_item' => __( 'Edit Lyrics', 'Lyrics' ),
'update_item' => __( 'Update Lyrics', 'Lyrics' ),
'search_items' => __( 'Search Lyrics', 'Lyrics' ),
'not_found' => __( 'Not found', 'Lyrics' ),
'not_found_in_trash' => __( 'Not found in Trash', 'Lyrics' ),
);
$args = array(
'label' => __( 'lyrics', 'Lyrics' ),
'description' => __( 'Lyrics Name', 'Lyrics' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'comments', 'page-attributes', 'post-formats', ),
'taxonomies' => array( 'bands', 'albums' ),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 7,
'menu_icon' => '',
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'lyrics', $args );
}
Pagination function works, but it displays links like this: domain.com/page/2 and I get an error 404.
But the pages are available at url like: domain.com/?page=2.
Why this happening?
u can also used pagination plugion for the same.
https://wordpress.org/plugins/wp-paginate/
or
https://wordpress.org/plugins/wp-smart-pagination/
such as many more plugion..
You need to add the paged query above your loop to make the pagination work for Custom Post Types I believe.
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('posts_per_page=3&paged=' . $paged);
?>
or
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
query_posts('posts_per_page=12&post_type=lyrics&paged=' . $paged);
May be it will be usefull for somebody... Add this to functions.php:
function my_post_queries( $query ) {
if (!is_admin() && $query->is_main_query()){
$taxonomies = array ('YOUR_TAXONOMY');
if(is_tax($taxonomies) || is_home()) {
$query->set ('post_type', 'YOUR_POST_TYPE');
}
}
}
add_action( 'pre_get_posts', 'my_post_queries' );