私はカスタム投稿タイプproducts
とスラッグproducts
を持つカスタム分類法 'Product Categories'を持っています。
私の目標: 私は次のようにURL構造を作成しようとしています:
製品の投稿タイプアーカイブ:products/
製品最上位カテゴリのアーカイブ:products/product-category
製品カテゴリアーカイブ:products/product-category/product-sub-category
製品ページ:products/product-category/product-sub-category/product-page
問題: 商品ページは実際のカテゴリのみを使いたいようです。そのため、URL構造はproducts/uncategorized/product-page
のようになります。カテゴリアーカイブページはcptベースを維持しません。それで彼らはcategory/sub-category
のようなものを見つけます。
試してみたこと: 膨大な数のグーグル検索、かなりの数のスニペット(私が覚えているもの)、いくつかのカスタム関数、そしていくつかのプラグイン役立たず。
次のようなコードがあります。
add_action( 'init', 'products_cpt', 0);
add_action( 'init', 'register_taxonomies', 0 );
//A custom post type for all products
function products_cpt(){
$labels = array(
'name' => _x('Products', 'Post Type General Name'),
'singular_name' => _x('Product', 'Post Type Singluar Name'),
'menu_name' => __('Products'),
'parent_item_colon' => __('Parent Product'),
'all_items' => __('All Products'),
'view_item' => __('View Product'),
'add_new_item' => __('Add New Product'),
'add_new' => __('Add New'),
'edit_item' => __('Edit Product'),
'update_item' => __('Update Product'),
'search_items' => __('Search Products'),
'not_found' => __('Not Found'),
'not_found_in_trash' => __('Not Found in Trash')
);
$supports = array(
'title',
'editor',
'excerpt',
'thumbnail',
'custom-fields',
'revisions'
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'exclude_from_search' => false,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'query_var' => true,
'taxonomies' => array( 'chemicals' ),
'supports' => $supports,
'has_archive' => 'products'
);
register_post_type('products', $args);
}
function register_taxonomies() {
$taxonomies = array(
'products' => array(
'Product',
'Products'
),
);
foreach($taxonomies as $slug => $name){
create_product_taxonomy($slug,$name[0],$name[1]);
}
}
function create_product_taxonomy($slug, $singular, $plural) {
$labels = array(
'name' => _x( $singular.' Categories', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( $singular.' Category', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( $singular.' Categories', 'text_domain' ),
'all_items' => __( 'All '.$singular.' Categories', 'text_domain' ),
'parent_item' => __( 'Parent '.$singular.' Category', 'text_domain' ),
'parent_item_colon' => __( 'Parent '.$singular.' Category:', 'text_domain' ),
'new_item_name' => __( 'New '.$singular.' Category Name', 'text_domain' ),
'add_new_item' => __( 'Add New '.$singular.' Category', 'text_domain' ),
'edit_item' => __( 'Edit '.$singular.' Category', 'text_domain' ),
'update_item' => __( 'Update '.$singular.' Category', 'text_domain' ),
'view_item' => __( 'View '.$singular.' Category', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate '.$singular.' Categories with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove '.$singular.' Categories', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used '.$singular.' Categories', 'text_domain' ),
'popular_items' => __( 'Popular '.$singular.' Categories', 'text_domain' ),
'search_items' => __( 'Search '.$singular.' Categories', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No '.$singular.' Categories', 'text_domain' ),
'items_list' => __( $singular.' Categories list', 'text_domain' ),
'items_list_navigation' => __( $singular.' Categories list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'has_archive' => $plural,
'rewrite' => array(
'slug' => 'products',
'with_front' => true,
'hierarchical' => true
)
);
register_taxonomy( $slug, 'products', $args );
}
次に、次のコードを追加してみましたが、商品ページでしか機能しませんでした。製品カテゴリアーカイブはまだ404'dです。
add_filter( 'post_type_link', 'products_post_link', 1, 3 );
function products_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) ){
$terms = wp_get_object_terms( $post->ID, 'products_category' );
$slug_url = '';
$last_id = 0;
if( $terms ){
foreach($terms as $term) {
if ($term === reset($terms)){
foreach($terms as $termInner){
if($termInner->term_id == 0){
$slug_url .= $termInner->slug.'/';
}
}
}elseif ($term === end($terms)){
foreach($terms as $termInner){
if($termInner->parent == $last_id){
$slug_url .= $termInner->slug;
$last_id = $termInner->term_id;
}
}
}else{
foreach($terms as $termInner){
if($termInner->parent == $last_id){
$slug_url .= $termInner->slug.'/';
$last_id = $termInner->term_id;
}
}
}
}
return str_replace( '%category%' , $slug_url , $post_link );
}
}
return $post_link;
}
そしてこれはCPTのinit関数です。
'rewrite' => array(
'slug' => 'products/%category%',
'with_front' => false,
'hierarchical' => true,
),
私はまた次のことを試みました、何が起こったのか覚えていないでください、しかし私はそれがうまくいかなかったことを覚えています:
add_action('init', 'custom_resource_rewrite_rules');
function custom_resource_rewrite_rules() {
add_rewrite_rule('products/([A-Za-z0-9\-\_]+)/?', '$matches[1]', 'top');
}
私はterm_link
フィルタでも試してみました。いいえブエノ。
最後に、私は以下のプラグインを試しました。
誰もがこれに対する解決策を持っていますか?髪を引き抜いています。
永遠に、私は答えを考え出した!
まず、カスタムポストとカスタム分類を登録します。
add_action( 'init', 'register_sps_products_post_type' );
function register_sps_products_post_type() {
register_post_type( 'sps-product',
array(
'labels' => array(
'name' => 'Products',
'menu_name' => 'Product Manager',
'singular_name' => 'Product',
'all_items' => 'All Products'
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ),
'hierarchical' => false,
'has_archive' => 'products',
'taxonomies' => array('product-category'),
'rewrite' => array( 'slug' => 'products/%product_category%', 'hierarchical' => true, 'with_front' => false )
)
);
register_taxonomy( 'product-category', array( 'sps-product' ),
array(
'labels' => array(
'name' => 'Product Categories',
'menu_name' => 'Product Categories',
'singular_name' => 'Product Category',
'all_items' => 'All Categories'
),
'public' => true,
'hierarchical' => true,
'show_ui' => true,
'rewrite' => array( 'slug' => 'products', 'hierarchical' => true, 'with_front' => false ),
)
);
}
次に、Wordpressが新しいパーマリンク構造を解釈する方法を認識できるように、新しい書き換え規則を追加します。
add_action( 'generate_rewrite_rules', 'register_product_rewrite_rules' );
function register_product_rewrite_rules( $wp_rewrite ) {
$new_rules = array(
'products/([^/]+)/?$' => 'index.php?product-category=' . $wp_rewrite->preg_index( 1 ), // 'products/any-character/'
'products/([^/]+)/([^/]+)/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 1 ) . '&sps-product=' . $wp_rewrite->preg_index( 2 ), // 'products/any-character/post-slug/'
'products/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ), // match paginated results for a sub-category archive
'products/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 2 ) . '&sps-product=' . $wp_rewrite->preg_index( 3 ), // 'products/any-character/sub-category/post-slug/'
'products/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 3 ) . '&sps-product=' . $wp_rewrite->preg_index( 4 ), // 'products/any-character/sub-category/sub-sub-category/post-slug/'
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
一方、次の機能はサブカテゴリの問題を解決します。問題自体は、URL faq/category/child-category /でページを読み込もうとすると、WordPressがslug "のサブカテゴリではなくslug" child-category "で投稿を読み込もうとすることです。 「子カテゴリ」.
// A hacky way of adding support for flexible custom permalinks
// There is one case in which the rewrite rules from register_kb_rewrite_rules() fail:
// When you visit the archive page for a child section(for example: http://example.com/faq/category/child-category)
// The deal is that in this situation, the URL is parsed as a Knowledgebase post with slug "child-category" from the "category" section
function fix_product_subcategory_query($query) {
if ( isset( $query['post_type'] ) && 'sps-product' == $query['post_type'] ) {
if ( isset( $query['sps-product'] ) && $query['sps-product'] && isset( $query['product-category'] ) && $query['product-category'] ) {
$query_old = $query;
// Check if this is a paginated result(like search results)
if ( 'page' == $query['product-category'] ) {
$query['paged'] = $query['name'];
unset( $query['product-category'], $query['name'], $query['sps-product'] );
}
// Make it easier on the DB
$query['fields'] = 'ids';
$query['posts_per_page'] = 1;
// See if we have results or not
$_query = new WP_Query( $query );
if ( ! $_query->posts ) {
$query = array( 'product-category' => $query['sps-product'] );
if ( isset( $query_old['product-category'] ) && 'page' == $query_old['product-category'] ) {
$query['paged'] = $query_old['name'];
}
}
}
}
return $query;
}
add_filter( 'request', 'fix_product_subcategory_query', 10 );
この関数はWordPressにあなたのカスタム投稿タイプ書き換えスラッグ構造の中の%product_category%の扱い方を知らせます:
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'sps-product')
return $link;
if ($cats = get_the_terms($post->ID, 'product-category'))
{
$link = str_replace('%product_category%', get_taxonomy_parents(array_pop($cats)->term_id, 'product-category', false, '/', true), $link); // see custom function defined below\
$link = str_replace('//', '/', $link);
$link = str_replace('http:/', 'http://', $link);
}
return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);
get_category_parents
を基にしたカスタム関数です。それは分類学の両親を取得します:
// 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;
}