Ещё один вопрос по ЧПУ (почти готово, нужен пинок в правильном направлении)
Формирую url для типа поста product:
/** * Уничтожаем слаг product из структуры url */ add_action( 'init', 'product_permastructure', 1 ); add_action( 'pre_get_posts', 'rewrite_product_rules', 10, 1 ); function product_permastructure() { global $wp_rewrite; $structure = get_option( 'product_permalink' ) . '%product%'; $wp_rewrite->add_rewrite_tag( "%product%", '([^/]+)', "product=" ); $wp_rewrite->add_permastruct( 'product', $structure, false ); } function rewrite_product_rules( $query ) { if( is_admin() || ! $query->is_main_query() ) return; if( ! isset( $query->query['page'] ) || empty( $query->query['name'] ) || count( $query->query ) != 2 ) return; $query->set( 'post_type', array( 'post', 'page', 'product' ) ); } // Меняем структуру url типа записей product. add_filter( 'post_type_link', 'gallery_permalink', 20, 3 ); function gallery_permalink( $permalink, $post_id, $leavename ) { $post = get_post( $post_id ); $rewritecode = array( '%year%', '%monthnum%', '%day%', '%hour%', '%minute%', '%second%', $leavename? '' : '%postname%', '%post_id%', '%category%', '%author%', $leavename? '' : '%pagename%', ); if ( '' != $permalink && !in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) { $unixtime = strtotime( $post->post_date ); $category = ''; if ( strpos( $permalink, '%category%' ) !== false ) { if ( $post->post_type == 'product' ) { if ( $terms = get_terms_hierarchicaly( $post->ID ) ) { foreach( $terms as $term ) { $category .= $term->slug . '/'; } $category = untrailingslashit( $category ); } if ( empty( $terms ) ) { $category = 'un'; } } else { $cats = get_the_category( $post->ID ); if ( $cats ) { usort($cats, '_usort_terms_by_ID'); // order by ID $category = $cats[0]->slug; if ( $parent = $cats[0]->parent ) $category = get_category_parents($parent, false, '/', true) . $category; } // show default category in permalinks, without // having to assign it explicitly if ( empty($category) ) { $default_category = get_category( get_option( 'default_category' ) ); $category = is_wp_error( $default_category ) ? '' : $default_category->slug; } } } $author = ''; if ( strpos( $permalink, '%author%' ) !== false ) { $authordata = get_userdata( $post->post_author ); $author = $authordata->user_nicename; } $date = explode(" ",date('Y m d H i s', $unixtime)); $rewritereplace = array( $date[0], $date[1], $date[2], $date[3], $date[4], $date[5], $post->post_name, $post->ID, $category, $author, $post->post_name, ); $permalink = str_replace( $rewritecode, $rewritereplace, $permalink ); } else { // if they're not using the fancy permalink option } return $permalink; }
В коде своя функция get_terms_hierarchicaly, формирующая parent-category/child-category/child-category для таксономий product_cat. Поэтому на это не обращайте внимание.
Данные берутся из своей опции, get_option( 'product_permalink' ). Есть несколько вариаций этой настройки:
- опция == '', тогда вместо example.com/product/tovar/ выводит example.com/tovar/
- опция == '/product/', тогда вместо example.com/product/tovar/ оставляет example.com/product/tovar/
- опция == '/product/%category%/', вместо example.com/product/tovar/ выводит example.com/product/parent/child/child/tovar/
С этим всё в порядке. ЧПУ работают правильно. Тестирую дальше.
- опция == '/%category%/', вместо example.com/product/tovar/ выводит example.com/parent/child/child/tovar/
- опция == '/%author%/%category%/', вместо example.com/product/tovar/ выводит example.com/admin/parent/child/child/tovar/
Две последние настройки также отрабатывают правильно. Но. Ломается настройка пермалинков страниц, записей и всего остального. Выдаёт 404 ошибку. Получается вся беда только когда удаляю из url слаг product.
Буду благодарен за любую помощь
Ты реально думаешь что кто то прочитав это мессиво что то поймет? ))
Тут совет один, ДЕБАЖИТЬ, смотри все необходимые переменные, sql запрос который формируется, и тд и тп, так и найдешь причину почему чего и где не хватает.