Поддержка Проблемы и решения ЧПУ для register_post_type

  • $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post', // создаем по типу страниц
    'has_archive' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'menu_icon' => 'dashicons-admin-home',
    'supports' => array('title','editor','author','thumbnail','excerpt','custom-fields')
    );
    register_post_type('my_post_type', $args);

    После такого кода появляется произвольный тип записей. Вот только ЧПУ выглядит так: my.site/my_post_type/onepost всегда. Вне зависимости от того, что у нас прописано в «настройки» — «постоянные ссылки». Например это «http://mysite.ru/sample-post/»

    Как все же подружить произвольный тип постов с ЧПУ.
    Чтобы например можно было к примеру выводить ссылки типа Сайт.ру/названиеПроизвольногоПоста (т.е. убрать my_post_type из урл).

    Стал гуглить. Возможно на это влияет аргумент permalink_epmask, но как им пользоваться… А может я вообще не в ту сторону копаю…

Просмотр 1 ответа (всего 1)
  • Модератор Denis Yanchevskiy

    (@denisco)

    WordPress-разработчик, denisco.pro

    Решал как-то давно. Было что-то вроде этого:

    /**
     * Remove the slug from published post permalinks. Only affect our custom post type, though.
     */
    function gp_remove_cpt_slug( $post_link, $post, $leavename ) {
    
        if ( 'race' != $post->post_type || 'publish' != $post->post_status ) {
            return $post_link;
        }
    
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
    
        return $post_link;
    }
    add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );
    
    /**
     * Have WordPress match postname to any of our public post types (post, page, race)
     * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
     * By default, core only accounts for posts and pages where the slug is /post-name/
     */
    function gp_parse_request_trick( $query ) {
    
        // Only noop the main query
        if ( ! $query->is_main_query() )
            return;
    
        // Only noop our very specific rewrite rule match
        if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
            return;
        }
    
        // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
        if ( ! empty( $query->query['name'] ) ) {
            $query->set( 'post_type', array( 'post', 'page', 'race' ) );
        }
    }
    add_action( 'pre_get_posts', 'gp_parse_request_trick' );

    race нужно заменить на my_post_type.

Просмотр 1 ответа (всего 1)
  • Тема «ЧПУ для register_post_type» закрыта для новых ответов.