WordPress.org

Ready to get started?Download WordPress

Forums

Insert category of taxonomy between custom post type and post (21 posts)

  1. lopinsjk
    Member
    Posted 1 year ago #

    Hello everybody

    I'm implementing a testing project and from 2 days I'm fighting with the permalink. I want to share with you my problem:

    I created a custom post type products;
    I created a custom taxonomy brand associated to products;
    into taxonomy I created 2 categories: nike and adidas;
    I finally created a product t-shirt and I categorized it as nike.

    What I would obtain is a permalink like this:

    www.example.com/products/nike/t-shirt

    Instead this it happens:

    I can visit the page of category nike
    /products/nike/
    where there are links to t-shirt posts.

    On the t-shirt page the permalink changes and becomes
    /products/t-shirt/

    In practice, I lose the reference to category /nike/

    what I get: /products/t-shirt/
    what I would like: /products/nike/t-shirt/

    I fix this with a static solution:

    into the custom post type I added
    'rewrite' => array('slug' => 'products/nike','with_front' => false),

    can I replace nike with something filter?

    Any idea?

  2. lopinsjk
    Member
    Posted 1 year ago #

    Solve it!

    /*Creo il custom post type Prodotti*/
    function my_custom_post_product() {
    	$labels = array(
    		'name'               => _x( 'Prodotti', 'post type general name' ),
    		'singular_name'      => _x( 'Prodotto', 'post type singular name' ),
    		'add_new'            => _x( 'Aggiungi Nuovo', 'book' ),
    		'add_new_item'       => __( 'Aggiungi Nuovo Prodotto' ),
    		'edit_item'          => __( 'Modifica Prodotto' ),
    		'new_item'           => __( 'Nuovo Prodotto' ),
    		'all_items'          => __( 'Tutti i Prodotti' ),
    		'view_item'          => __( 'Vedi Prodotto' ),
    		'search_items'       => __( 'Cerca Prodotti' ),
    		'not_found'          => __( 'Nessun Prodotto Trovato' ),
    		'not_found_in_trash' => __( 'Nessun Prodotto Trovato nel Cestino' ),
    		'parent_item_colon'  => '',
    		'menu_name'          => 'Prodotti'
    	);
    	$args = array(
    		'labels'        => $labels,
    		'description'   => 'Inserisci un nuovo prodotto',
    		'public'        => true,
    		'menu_position' => 5,
    		'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
    		'has_archive'   => true,
    		'hierarchical'	=> true,
    		'rewrite'		=> array('slug' => 'prodotto/%brand%','with_front' => false),
    		'query_var'		=> true,
    		//'rewrite'		=> true,
    		//'publicly_queryable' => false,
    	);
    	register_post_type( 'prodotto', $args );
    }
    add_action( 'init', 'my_custom_post_product' );
    /*Creo la custom taxonomy Brand associata a Prodotti*/
    function my_taxonomies_product() {
    	$labels = array(
    		'name'              => _x( 'Brand', 'taxonomy general name' ),
    		'singular_name'     => _x( 'Brand', 'taxonomy singular name' ),
    		'search_items'      => __( 'Search Product Categories' ),
    		'all_items'         => __( 'All Product Categories' ),
    		'parent_item'       => __( 'Parent Product Category' ),
    		'parent_item_colon' => __( 'Parent Product Category:' ),
    		'edit_item'         => __( 'Edit Product Category' ),
    		'update_item'       => __( 'Update Product Category' ),
    		'add_new_item'      => __( 'Add New Product Category' ),
    		'new_item_name'     => __( 'New Product Category' ),
    		'menu_name'         => __( 'Brand' ),
    	);
    	$args = array(
    		'labels' => $labels,
    		'hierarchical' 	=> true,
    		'public'		=> true,
    		'query_var'		=> 'brand',
    		//slug prodotto deve coincidere con il primo parametro dello slug del Custom Post Type correlato
    		'rewrite'		=>  array('slug' => 'prodotto' ),
    		'_builtin'		=> false,
    	);
    	register_taxonomy( 'brand', 'prodotto', $args );
    }
    add_action( 'init', 'my_taxonomies_product', 0 );
    /*Filtro per modificare il permalink*/
    add_filter('post_link', 'brand_permalink', 1, 3);
    add_filter('post_type_link', 'brand_permalink', 1, 3);
    
    function brand_permalink($permalink, $post_id, $leavename) {
    	//con %brand% catturo il rewrite del Custom Post Type
        if (strpos($permalink, '%brand%') === FALSE) return $permalink;
            // Get post
            $post = get_post($post_id);
            if (!$post) return $permalink;
    
            // Get taxonomy terms
            $terms = wp_get_object_terms($post->ID, 'brand');
            if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
            	$taxonomy_slug = $terms[0]->slug;
            else $taxonomy_slug = 'no-brand';
    
        return str_replace('%brand%', $taxonomy_slug, $permalink);
    }

    now create 2 categories inside brand:

    nike and adidas;

    create two products:

    t-shirt with nike category;
    sneaker with adidas category.

    Now check the permalink inside nike/adidas category page and inside t-shirt/snaker products.

    Is it all right?

  3. Leaniebiz
    Member
    Posted 1 year ago #

    Wow very nice work. I've been looking very long for a function like this since it will give you filter possibility's in a custom post type.

    How can I call the function results in the custom post type loop?

    <?php
    
    // The Query
    $query = new WP_Query( 'post_type' => 'prodotto', 'posts_per_page' => 12 );
    
    // The Loop
    if ( $query->have_posts() ) {
    	while ( $query->have_posts() ) {
    		$query->the_post(); ?>
    
    <HTML content>
    
    <?php } endwhile; ?>

    This loop will show the main custom post type: prodotto. In this page I want to make a category menu with adidas, nike etc.. And when a user clicks on adidas it needs to show them the loop of prodotto/adidas.

    Is this possible without creating a load of new archive-name.php pages?

  4. lopinsjk
    Member
    Posted 1 year ago #

    First you need to create a menu with your categories. After you need to create a file taxonomy-brand.php:

    <?php get_header(); ?>
    
    <?php if ( have_posts() ) : ?>
    	<?php while ( have_posts() ) : the_post(); ?>
    		<a href="<?php the_permalink() ?>">
    			<?php the_title( '<h1>', '</h1>' ); ?>
    		</a>
    		<?php the_content(); ?>
    	<?php endwhile; ?>
    <?php endif; ?>
    
    <?php //get_sidebar(); ?>
    <?php get_footer(); ?>

    This loop shows the products by brand.

    Now create another file named single-prodotto.php like this:

    <?php get_header(); ?>
    
    <?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php
    	the_title();
    	the_content();
    ?>
    <?php endwhile; ?>
    <?php endif; ?>
    <?php get_footer(); ?>

    This loop shows single product. So you don't need to use WP_Query.

  5. Leaniebiz
    Member
    Posted 1 year ago #

    Thanks very much! It works like a charm.

  6. Wolvenx
    Member
    Posted 1 year ago #

    Hello, I created a page called "products" (to the menu bar) with custom template "taxonomy-brand.php:" but not show the loop of "products" (prodotto)

    this is my code "taxonomy-brand.php:"

    <?php get_header('home'); ?>

    <?php if ( have_posts() ) : ?>
    	<?php while ( have_posts() ) : the_post(); ?>
    		<a href="<?php the_permalink() ?>">
    			<?php the_title( '<h1>', '</h1>' ); ?>
    		</a>
    		<?php the_content(); ?>
    	<?php endwhile; ?>
    <?php endif; ?>
    
    <?php //get_sidebar(); ?>

    <?php get_footer('home'); ?>

    may be happening?

    greetings!

  7. Lrrr
    Member
    Posted 11 months ago #


  8. Robert3d
    Member
    Posted 10 months ago #

    I get index.php because I don't have 404 :( no product no brand :(

  9. lopinsjk
    Member
    Posted 10 months ago #

    @Robert3d what is your problem?

  10. Robert3d
    Member
    Posted 10 months ago #

    I create taxonomy single and archive files but I get only index page when I want see result.

  11. Robert3d
    Member
    Posted 10 months ago #

    <?php
    
    /* Register new tapy post (products) */
    
    function my_custom_post_product() {
    	$labelsProduct = array(
    		'name'               => _x( 'Produkty', 'post type general name' ),
    		'singular_name'      => _x( 'Produkty', 'post type singular name' ),
    		'add_new'            => _x( 'Dodaj nowy produkt', 'book' ),
    		'add_new_item'       => __( 'Dodawanie nowego produktu' ),
    		'edit_item'          => __( 'Edytuj produkt' ),
    		'new_item'           => __( 'Nowy produkt' ),
    		'all_items'          => __( 'Lista produktów' ),
    		'view_item'          => __( 'Zobacz produkt' ),
    		'search_items'       => __( 'Szukaj produktu' ),
    		'not_found'          => __( 'Nie znaleziono produktów' ),
    		'not_found_in_trash' => __( 'Nie znalezionko produktów w koszu' ),
    		'parent_item_colon'  => '',
    		'menu_name'          => 'Produkty'
    	);
    	$argsProduct = array(
    		'labels'        => $labelsProduct,
    		'description'   => 'Wprowadź nowy produkt.',
    		'public'        => true,
    		'menu_position' => 5,
    		'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
    		'has_archive'   => true,
    		'hierarchical'	=> true,
    		'rewrite'		=> array('slug' => 'products/%category%','with_front' => false),
    		'query_var'		=> true,
    		//'rewrite'		=> true,
    		//'publicly_queryable' => false,
    	);
    	register_post_type( 'products', $argsProduct );
    }
    
    add_action( 'init', 'my_custom_post_product' );
    
    /* A taxonomies for products (category taxonomy) */
    function my_taxonomies_product() {
    	$labelsTaxProducts = array(
    		'name'              => _x( 'Kategorie', 'taxonomy general name' ),
    		'singular_name'     => _x( 'Kategorie', 'taxonomy singular name' ),
    		'search_items'      => __( 'Wyszukaj kategorie' ),
    		'all_items'         => __( 'Wszystkie kategorie' ),
    		'parent_item'       => __( 'Rodzic kategorii' ),
    		'parent_item_colon' => __( 'Rodzic produktu:' ),
    		'edit_item'         => __( 'Edytuj kategorie' ),
    		'update_item'       => __( 'Aktualizuj kategorie' ),
    		'add_new_item'      => __( 'Dodaj nową kategorie' ),
    		'new_item_name'     => __( 'Nazwa nowej kategorii' ),
    		'menu_name'         => __( 'Kategorie' ),
    	);
    	$argsTaxProducts = array(
    		'labels' => $labelsTaxProducts,
    		'hierarchical' 	=> true,
    		'public'		=> true,
    		'query_var'		=> 'category',
    		//slug prodotto deve coincidere con il primo parametro dello slug del Custom Post Type correlato
    		'rewrite'		=>  array('slug' => 'products' ),
    		'_builtin'		=> false,
    	);
    	register_taxonomy( 'category', 'products', $argsTaxProducts );
    }
    
    add_action( 'init', 'my_taxonomies_product', 0 );
    
    /* Filter modifies the permaling */
    
    add_filter('post_link', 'category_permalink', 1, 3);
    add_filter('post_type_link', 'category_permalink', 1, 3);
    
    function category_permalink($permalink, $post_id, $leavename) {
    	//con %category% catturo il rewrite del Custom Post Type
        if (strpos($permalink, '%category%') === FALSE) return $permalink;
            // Get post
            $post = get_post($post_id);
            if (!$post) return $permalink;
    
            // Get taxonomy terms
            $terms = wp_get_object_terms($post->ID, 'category');
            if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
            	$taxonomy_slug = $terms[0]->slug;
            else $taxonomy_slug = 'no-category';
    
        return str_replace('%category%', $taxonomy_slug, $permalink);
    }

    I FIXED THIS. I had something wrong in /%category%/%postname%/ But I dont now what because i get copy (clean instalation) and paste (me project) and now work thx for good tutorial :)

  12. lopinsjk
    Member
    Posted 10 months ago #

    Good ;)

  13. Robert3d
    Member
    Posted 10 months ago #

    No :( still is something bad :( I get only Single post but taxonomy still dead.

    Now All IS CLEAR! What is bad in wordpress. When we change something in url we schould refresh this /%category%/%postname%/ and save again it is very !@#$% :)

  14. Robert3d
    Member
    Posted 10 months ago #

    Hi I have another problem. When I add pagination I lost my products.

    url ../products/page/2/ not work.

    function generate_pagination($wp_query, $getqueryvar )
    {
        $big = 999999999; // need an unlikely integer
    
        echo paginate_links(array(
            'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
            'format' => '?paged=%#%',
            'current' => max(1, $getqueryvar),
            'total' => $wp_query->max_num_pages,
            'prev_text' => '<',
            'next_text' => '>'
        ));
    }

    And call

    <?php generate_pagination($loop, get_query_var('paged')); ?>

    Please help

  15. Robert3d
    Member
    Posted 10 months ago #

    Who now how make pagination :( help.

  16. Andrew
    Forum Moderator
    Posted 10 months ago #

    You should probably make a new thread for that http://wordpress.org/support/forum/how-to-and-troubleshooting

  17. szed
    Member
    Posted 9 months ago #

    Hi guys!

    Great works, but i'm looking for something a little more...advanced :D

    I would like to have the parent taxonomy (categorie of portfolio in my case) into the URL.

    Actually, with your help, i got :

    /portfolio/hobby/project-11/ which is already a nice trick :)

    I woull like to have something like this, i check the "hobby" category for my project :
    /portfolio/hobby-parent1/hobby-parent2/hobby/project-11/

    Someone ? :)

    Thanks !

  18. dcooney
    Member
    Posted 7 months ago #

    Robert3d,
    your solution works perfectly! so thank you!
    I wish I could Up Vote!

  19. lopinsjk
    Member
    Posted 5 months ago #

    Good work guys ;)

  20. Cortez77
    Member
    Posted 4 months ago #

    I'm having the same issue as Robert3D trying to make the next / last links (pagination) work on the custom-taxonomy page using this set-up.

    I started another thread here as suggested by Barrel rider but not getting any love and thought I'd give a shout out here as it directly relates to this thread.

    Any suggestions at all are appreciated.
    Cheers

  21. nori2tae
    Member
    Posted 3 months ago #

    Very nice tuto!
    I have very few knowledge for both PHP and WordPress,
    so this tuto helped me a lot.
    I was banging my head against the wall, lol.
    I must say thank you firstly.

    Following lopinsjk's instruction, i could successfully displayed Custom Post Type(CPT) page with desired URL :)
    ex.)

    So far so good, but here I need a further instruction for sub categories.

    I have some child categories (or maybe grand child categories in future...) under the parent categories and those have some pages.

    URL looks like this for pages under the sub categories:
    http://sample.com/CPT/category/page_name/

    So I want URL to look like:
    http://sample.com/CPT/category/child-category-slug-name/page_name/
    or
    http://sample.com/CPT/category/child-category-slug-name/grand-child-category-slug-name/page_name/

    Need a little tweak for URL,
    but I have no clue how I can achieve it.

    Anyone has idea?

Topic Closed

This topic has been closed to new replies.

About this Topic