在永久链接中使用自定义帖子类型的帖子ID而不是帖子标题

问题描述 投票:0回答:2

我有一个自定义帖子类型的'员工'。我正在尝试重写slug以使用帖子ID而不是默认的帖子标题。有没有一种简单的方法在“重写”下的自定义帖子类型功能中执行此操作?

像这样的东西:

   'rewrite' => [
        'with_front' => false,
        'slug' => 'employee/' . %post_id%,
    ]
php wordpress url-rewriting custom-post-type slug
2个回答
1
投票

以下在旧项目(未经测试)中对我的工作类似:

'rewrite' => array(
    'with_front' => false,
    'slug' => 'news/events/%employee_id%'
)


add_filter('post_type_link', 'custom_employee_permalink', 1, 3);
function custom_employee_permalink($post_link, $id = 0, $leavename) {
    if ( strpos('%employee_id%', $post_link) === 'FALSE' ) {
        return $post_link;
    }
    $post = &get_post($id);
    if ( is_wp_error($post) || $post->post_type != 'employee' ) {
        return $post_link;
    }
    return str_replace('%employee_id%', $post->ID, $post_link);
}

1
投票

这是一种用自定义帖子类型永久链接结构中的帖子ID替换帖子slug的方法。

更改

some domain.com/some-permalink/post_slug

some domain.com/some-permalink/123

假设帖子类型已经存在

'rewrite'=> array('slug'=>'some-type')

function _post_type_rewrite() {
global $wp_rewrite;

// Set the query arguments used by WordPress
$queryarg = 'post_type=some-type&p=';

// Concatenate %cpt_id% to $queryarg (eg.. &p=123)
$wp_rewrite->add_rewrite_tag( '%cpt_id%', '([^/]+)', $queryarg );

// Add the permalink structure
$wp_rewrite->add_permastruct( 'some-type', '/some-type/%cpt_id%/', false );
}
  add_action( 'init', '_post_type_rewrite' );

/**
  * Replace permalink segment with post ID
  *
  */
function _post_type_permalink( $post_link, $id = 0, $leavename ) {
global $wp_rewrite;
$post = get_post( $id );
if ( is_wp_error( $post ) )
    return $post;

    // Get post permalink (should be something like /some-type/%cpt_id%/
    $newlink = $wp_rewrite->get_extra_permastruct( 'some-type' );

    // Replace %cpt_id% in permalink structure with actual post ID
    $newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
    $newlink = home_url( user_trailingslashit( $newlink ) );
return $newlink;
  }
 add_filter('post_type_link', '_post_type_permalink', 1, 3);

资料来源:https://joebuckle.me/quickie/wordpress-replace-post-name-slug-post-id-custom-post-types/

© www.soinside.com 2019 - 2024. All rights reserved.