从自定义帖子类型中删除父级

时间:2013-12-11 16:28:31

标签: php wordpress wordpress-plugin wordpress-theming

我使用WordPress创建了一个新的自定义帖子类型。但是,slug会将帖子添加到父级,如下所示:

http://example.com/UNNCESSARY-PARENT/post-title

但是,我想要创建:

http://example.com/post-title

这可能吗?这就是我注册帖子类型的方式:

function create_films() {
  register_post_type( 'films',
    array(
      'labels' => array(
        'name' => 'Films' ,
        'singular_name' =>  'Films'

      ),
    'public' => true,
    'has_archive' => false,
    'taxonomies' => array('category', 'post_tag') 
    )
  );

}

add_action( 'init', 'create_films' );

这是documentation.

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。您需要为此使用 WordPress操作挂钩

在主题 functions.php

中添加此内容
/**
 * Remove the slug from custom post permalinks. 
 * 
 */
function remove_custom_post_type_slug( $post_link, $post, $leavename ) {

    //check if the post type matches our custom post type
    if ( ! in_array( $post->post_type, array( 'films' ) ) || 'publish' != $post->post_status )
        return $post_link;

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'remove_custom_post_type_slug', 10, 3 );



/**
 * Hack to have WordPress match postname to any of our public post types
 * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
 * 
 * Typically core only accounts for posts and pages where the slug is /post-name/
 */
function parse_post_type_request( $query ) {

    if ( ! $query->is_main_query() )
        return;

    if ( 2 != count( $query->query )
    || ! isset( $query->query['page'] ) )
        return;

    if ( ! empty( $query->query['name'] ) )
        $query->set( 'post_type', array( 'post', 'films', 'page' ) );
}
add_action( 'pre_get_posts', 'parse_post_type_request' );

希望这适合你: - )