【问题标题】:Remove parent from custom post type从自定义帖子类型中删除父级
【发布时间】:2013-12-29 17:56:21
【问题描述】:

我使用 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.

【问题讨论】:

  • 我从未见过__( 'Films' ), 是什么。是函数吗?
  • 现在删除了括号,我从另一个来源复制了这个例子,所以我不知道它们不应该在那里!
  • 是的,WordPress 再次成为 WordPress。无论如何,我认为你最好在WordPress.StackExchange.com(另一个 SO 姐妹网站)中询问它
  • 你现在可以删除这个问题了。

标签: php wordpress wordpress-theming


【解决方案1】:

是的,这是可能的。您需要为此使用 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' );

希望这对你有用:-)

【讨论】:

    【解决方案2】:

    在快速测试中,我惊讶地发现它开箱即用。
    也就是说,子帖子的规范 URI 仍然在路径中包含父帖子,但子帖子也可以正常工作没有它(不 404,不重定向)。
    因此,应该只是过滤 post_type_link 以使其按您的要求工作!
    将此代码添加到您当前的活动主题 functions.php 文件
    以下代码应该做到这一点:

    function wpgeek_hierarchies( $post_link, $post ) {
    if ( 'service' != $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', 'wpgeek_hierarchies', 10, 2 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 2020-06-11
      • 1970-01-01
      • 2020-02-23
      • 2015-07-10
      • 2013-01-28
      • 1970-01-01
      相关资源
      最近更新 更多