如何重写网址?post_type = WordPress

时间:2017-02-26 00:55:54

标签: wordpress

我在WordPress中重写网址自定义帖子类型有问题。

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

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

1 个答案:

答案 0 :(得分:0)

已修复此代码。

/**
* 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 */