【问题标题】:How to rewrite url ?post_type= WordPress如何重写 url ?post_type= WordPress
【发布时间】:2017-02-26 00:55:53
【问题描述】:

我在 WordPress 中重写 url 自定义帖子类型有一点问题。

我有这个链接:www.domain.com/?post_type=review_smartphone 我想改成这样:www.domain.com/smartphone

如何制作,请帮忙。我尝试了这个解决方案:https://wordpress.stackexchange.com/questions/248758/rewrite-rules-for-custom-post-type-slug 但我不明白如何实现它。

【问题讨论】:

  • 你正在使用什么 parmalink 结构?
  • 用下面的代码修复。,

标签: wordpress


【解决方案1】:

已使用此代码修复。

/**
* Re-write post type urls
*/
function rewrite_post_type_init() {
    // semua post type
    global $wpdb;
    $query_type = $wpdb->get_results( "
        SELECT *
        FROM " . $wpdb->prefix . "mf_posttypes
        ORDER BY name
        ASC
    " );

    // tampilkan post type
    foreach ( $query_type as $type ) {
        $args = array(
            'label'                 => __( $type->name, 'oelas' ),
            'supports'              => array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', 'page-attributes' ),
            'taxonomies'            => array( strtolower($type->name).'_brand', 'post_tag' ),
            'hierarchical'          => true,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => true,
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'rewrite'               => array( 'slug' => strtolower($type->name) ),
        );

        register_post_type( $type->type, $args );

        add_rewrite_rule( 
            '^'.strtolower($type->name).'/([^/]+)/?$',
            'index.php?post_type='.$type->type.'&name=$matches[1]',
            'top'
        );
    }
}

add_action( 'init', 'rewrite_post_type_init' );

function rewrite_post_type_flatten_hierarchies( $post_link, $post ) {
    // semua post type
    global $wpdb;
    $query_type = $wpdb->get_results( "
        SELECT *
        FROM " . $wpdb->prefix . "mf_posttypes
        ORDER BY name
        ASC
    " );

    // tampilkan post type
    foreach ( $query_type as $type ) {
        if ( strtolower($type->name) != $post->post_type ) {
            return $post_link;
        }

        $uri = '';
        foreach ( $post->ancestors as $parent ) {
            $uri = get_post( $parent )->post_name . "/" . $uri;
        }

        return str_replace( $uri, '', $post_link );
    }
}

add_filter( 'post_type_link', 'rewrite_post_type_flatten_hierarchies', 10, 2 );
/***************** akhir */

【讨论】:

    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多