lundi 5 octobre 2015

How to add custom taxonomy slug in CPT permalink?

This is the code i have until now to add a CPT articles and taxonomy articles-category.

The code works, sort off. The pages are displaing correct (when i access them directly):

articles/

articles/categ-slug/

articles/categ-slug/post-slug/

The problem appears when the permalink are generated automatically (eg: yoast breadcrumbs)

<span typeof="v:Breadcrumb">
<a href="example.com" rel="v:url" property="v:title">Example</a> /
<span rel="v:child" typeof="v:Breadcrumb"><a href="http://ift.tt/1j9PLY0" rel="v:url" property="v:title">Articles</a> /
<span rel="v:child" typeof="v:Breadcrumb"><a href="http://ift.tt/1VBOXH8" rel="v:url" property="v:title">Category name</a> /
<span class="breadcrumb_last">Post Name</span></span></span></span>

Notice http://ift.tt/1q0pU4q%articles-category%/ where it should be just http://ift.tt/1q0pU4q

What is wrong in the code and how can i make it work?

function custom_post_articles() {

    $labels = array(
        // labels
    );

    $args = array(
        'labels'        => $labels,
        'public'        => true,
        'menu_position' => 5,
        'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
        'has_archive'   => true,
        'hierarchical'  => true,
        'rewrite'       => array('slug' => 'articles/%articles-category%','with_front' => false),
        'query_var'     => true,
        //'rewrite'     => true,
        //'publicly_queryable' => false,
    );
    register_post_type( 'articles', $args );
}
add_action( 'init', 'custom_post_articles' );


function my_taxonomies_product() {
    $labels = array(
        //labels
    );
    $args = array(
        'labels' => $labels,
        'hierarchical'  => true,
        'public'        => true,
        'query_var'     => 'articles-category',

        'rewrite'       =>  array('slug' => 'articles' ),
        '_builtin'      => false,
    );
    register_taxonomy( 'articles-category', 'articles', $args );
}
add_action( 'init', 'my_taxonomies_product', 0 );

add_filter('post_link', 'articles_category_permalink', 1, 3);
add_filter('post_type_link', 'articles_category_permalink', 1, 3);

function articles_category_permalink($permalink, $post_id, $leavename) {

    if (strpos($permalink, '%articles-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, 'articles-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('%articles-category%', $taxonomy_slug, $permalink);
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire