web-dev-qa-db-fra.com

Comment réparer une double barre oblique dans les permaliens personnalisés avec les taxonomies hiérarchiques?

Suivant la solution de Jeff @ Permaliens personnalisés - type de message - taxonomie hiérarchique

J'ai réussi à réécrire mon URL pour une taxonomie personnalisée. Cependant, j'ai une chose qui me dérange et c'est une double barre oblique dans la sortie à cause du séparateur.

http://www.domain.nl/product/televisies/led/55-inch//product-naam-4/

Je ne peux pas changer cela dans la section permalinks de de admin. (/% category% /% postname% /)

register_post_type( "products", 
            array(  'label'             => CUSTOM_MENU_TITLE,
                    'labels'            => array(   'name'                  =>  CUSTOM_MENU_NAME,
                                                    'singular_name'         =>  CUSTOM_MENU_SIGULAR_NAME,
                                                    'add_new'               =>  CUSTOM_MENU_ADD_NEW,
                                                    'add_new_item'          =>  CUSTOM_MENU_ADD_NEW_ITEM,
                                                    'edit'                  =>  CUSTOM_MENU_EDIT,
                                                    'edit_item'             =>  CUSTOM_MENU_EDIT_ITEM,
                                                    'new_item'              =>  CUSTOM_MENU_NEW,
                                                    'view_item'             =>  CUSTOM_MENU_VIEW,
                                                    'search_items'          =>  CUSTOM_MENU_SEARCH,
                                                    'not_found'             =>  CUSTOM_MENU_NOT_FOUND,
                                                    'not_found_in_trash'    =>  CUSTOM_MENU_NOT_FOUND_TRASH ),
                    'public'            => true,
                    'can_export'        => true,
                    'show_ui'           => true, // UI in admin panel
                    '_builtin'          => false, // It's a custom post type, not built in
                    '_edit_link'        => 'post.php?post=%d',
                    'capability_type'   => 'post',
                    'menu_icon'         => get_bloginfo('template_url').'/images/favicon.ico',
                    'hierarchical'      => true,
                    'rewrite'           => array('slug' => 'product/%taxonomy_name%','with_front' => true,'hierarchical'=>true), // Permalinks
                    'query_var'         => "products", // This goes to the WP_Query schema
                    'supports'          => array(   'title',
                                                    'author', 
                                                    'excerpt',
                                                    'thumbnail',
                                                    'comments',
                                                    'editor', 
                                                    'trackbacks',
                                                    'custom-fields',
                                                    'revisions') ,
                    'show_in_nav_menus' => true ,
                    'taxonomies'        => array("pcategory","ptags")
                )
            );

// Register custom taxonomy
register_taxonomy(  "pcategory", 
            array(  "products"  ), 
            array ( "hierarchical"      => true, 
                    "label"             => CUSTOM_MENU_CAT_LABEL, 
                    'labels'            => array(   'name'              =>  CUSTOM_MENU_CAT_TITLE,
                                                    'singular_name'     =>  CUSTOM_MENU_SIGULAR_CAT,
                                                    'search_items'      =>  CUSTOM_MENU_CAT_SEARCH,
                                                    'popular_items'     =>  CUSTOM_MENU_CAT_SEARCH,
                                                    'all_items'         =>  CUSTOM_MENU_CAT_ALL,
                                                    'parent_item'       =>  CUSTOM_MENU_CAT_PARENT,
                                                    'parent_item_colon' =>  CUSTOM_MENU_CAT_PARENT_COL,
                                                    'edit_item'         =>  CUSTOM_MENU_CAT_EDIT,
                                                    'update_item'       =>  CUSTOM_MENU_CAT_UPDATE,
                                                    'add_new_item'      =>  CUSTOM_MENU_CAT_ADDNEW,
                                                    'new_item_name'     =>  CUSTOM_MENU_CAT_NEW_NAME,   ), 
                    'public'            => true,
                    'show_ui'           => true,
                    "rewrite"           => array('slug' => 'product','with_front' => true,'hierarchical'=>true))
            ); 

Mon functions.php comprend:

add_filter('rewrite_rules_array', 'mmp_rewrite_rules');
function mmp_rewrite_rules($rules) {
$newRules  = array();
$newRules['product/(.+)/(.+)/(.+)/(.+)/?$'] = 'index.php?products=$matches[4]';
$newRules['product/(.+)/?$']                = 'index.php?pcategory=$matches[1]'; 

return array_merge($newRules, $rules);
}
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'products')
    return $link;

if ($cats = get_the_terms($post->ID, 'pcategory'))
{
    $link = str_replace('%taxonomy_name%', get_taxonomy_parents(array_pop($cats)->term_id, 'pcategory', false, '/', true), $link);
}
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;    
}

Quelqu'un sait-il comment résoudre ceci?

2
jochem

Après avoir changé quelque chose, j'ai le code final qui le fait fonctionner.

C'est là que vous enregistrez les types de publication. (inchangé)

register_post_type( "products", 
            array(  'label'             => CUSTOM_MENU_TITLE,
                    'labels'            => array(   'name'                  =>  CUSTOM_MENU_NAME,
                                                    'singular_name'         =>  CUSTOM_MENU_SIGULAR_NAME,
                                                    'add_new'               =>  CUSTOM_MENU_ADD_NEW,
                                                    'add_new_item'          =>  CUSTOM_MENU_ADD_NEW_ITEM,
                                                    'edit'                  =>  CUSTOM_MENU_EDIT,
                                                    'edit_item'             =>  CUSTOM_MENU_EDIT_ITEM,
                                                    'new_item'              =>  CUSTOM_MENU_NEW,
                                                    'view_item'             =>  CUSTOM_MENU_VIEW,
                                                    'search_items'          =>  CUSTOM_MENU_SEARCH,
                                                    'not_found'             =>  CUSTOM_MENU_NOT_FOUND,
                                                    'not_found_in_trash'    =>  CUSTOM_MENU_NOT_FOUND_TRASH ),
                    'public'            => true,
                    'can_export'        => true,
                    'show_ui'           => true, // UI in admin panel
                    '_builtin'          => false, // It's a custom post type, not built in
                    '_edit_link'        => 'post.php?post=%d',
                    'capability_type'   => 'post',
                    'menu_icon'         => get_bloginfo('template_url').'/images/favicon.ico',
                    'hierarchical'      => true,
                    'rewrite'           => array('slug' => 'product/%taxonomy_name%','with_front' => true,'hierarchical'=>true), // Permalinks
                    'query_var'         => "products", // This goes to the WP_Query schema
                    'supports'          => array(   'title',
                                                    'author', 
                                                    'excerpt',
                                                    'thumbnail',
                                                    'comments',
                                                    'editor', 
                                                    'trackbacks',
                                                    'custom-fields',
                                                    'revisions') ,
                    'show_in_nav_menus' => true ,
                    'taxonomies'        => array("pcategory","ptags")
                )
            );

// Register custom taxonomy
register_taxonomy(  "pcategory", 
            array(  "products"  ), 
            array ( "hierarchical"      => true, 
                    "label"             => CUSTOM_MENU_CAT_LABEL, 
                    'labels'            => array(   'name'              =>  CUSTOM_MENU_CAT_TITLE,
                                                    'singular_name'     =>  CUSTOM_MENU_SIGULAR_CAT,
                                                    'search_items'      =>  CUSTOM_MENU_CAT_SEARCH,
                                                    'popular_items'     =>  CUSTOM_MENU_CAT_SEARCH,
                                                    'all_items'         =>  CUSTOM_MENU_CAT_ALL,
                                                    'parent_item'       =>  CUSTOM_MENU_CAT_PARENT,
                                                    'parent_item_colon' =>  CUSTOM_MENU_CAT_PARENT_COL,
                                                    'edit_item'         =>  CUSTOM_MENU_CAT_EDIT,
                                                    'update_item'       =>  CUSTOM_MENU_CAT_UPDATE,
                                                    'add_new_item'      =>  CUSTOM_MENU_CAT_ADDNEW,
                                                    'new_item_name'     =>  CUSTOM_MENU_CAT_NEW_NAME,   ), 
                    'public'            => true,
                    'show_ui'           => true,
                    "rewrite"           => array('slug' => 'product','with_front' => true,'hierarchical'=>true))
            ); 

Mon functions.php comprend:

add_filter('rewrite_rules_array', 'mmp_rewrite_rules');
function mmp_rewrite_rules($rules) {
$newRules  = array();
$newRules['product/(.+)/(.+)/(.+)/(.+)/?$'] = 'index.php?products=$matches[4]';
$newRules['product/(.+)/?$']                = 'index.php?pcategory=$matches[1]'; 

return array_merge($newRules, $rules);
}
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'products')
    return $link;

if ($cats = get_the_terms($post->ID, 'pcategory'))
{
    $link = str_replace('%taxonomy_name%', get_taxonomy_parents(array_pop($cats)->term_id, 'pcategory', false, '/', true), $link);
}
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, $nicename = false, $visited = array()) {    
// removed $seperator="/" after $link, otherwise there was a double slash before the post name in the link    
$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, $nicename, $visited); //removed $seperator after $link
    $chain .= "/"; //add a / after every category
}

if ($link) {
    // nothing, can't get this working :(
} else    
    $chain .= $name; //don't need the . $separator anymore
return $chain;    
}
0
jochem

Il existe une solution potentielle rapide et quelque peu sale à cela. Je dis "potentiel" parce que je ne peux pas détecter le problème en regardant le code. Je n'ai que mes soupçons. Au lieu de passer un séparateur comme ça. Essayez trailingslashit .

} else    
    $chain .= trailingslashit($name);
return $chain;  

Je devine où le problème est basé sur votre description, mais c'est le seul endroit où $separator est appliqué.

Il existe un cas où cette solution simple ne fonctionnera pas. Si $name est vide, vous aurez une barre oblique supplémentaire dans votre chaîne. Il serait donc préférable de vérifier cela, juste au cas où.

} elseif (!empty($name))     
    $chain .= trailingslashit($name);
return $chain;

Essayez ça.

1
s_ha_dum
    $link = str_replace('%taxonomy_name%', get_taxonomy_parents(array_pop($cats)->term_id, 'pcategory', false, '/', true), $link);

doit devenir

    $link = str_replace('%taxonomy_name%', get_taxonomy_parents(array_pop($cats)->term_id, 'pcategory', false, true), $link);

Sinon, la fonction révisée se met à chercher le séparateur.

1
user48107

peut-être que cette publication a le postID parent (vérifiez leurs identifiants de publication parent). Je doute que leur publication parente n'existe pas, et lorsque wordpress tente d'obtenir le lien permanent (avec slugname inclus de son parent), il ajoute uniquement la barre oblique vide.

0
T.Todua