gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:04:52 24 4
gpt4 key购买 nike

我有一个自定义帖子类型“员工”。我正在尝试重写 slug 以使用帖子 ID 而不是默认的帖子标题。在“重写”下的自定义帖子类型功能中是否有一种简单的方法可以做到这一点?

类似这样的事情:

   'rewrite' => [
'with_front' => false,
'slug' => 'employee/' . %post_id%,
]

最佳答案

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

改变

somedomain.com/some-permalink/post_slug

somedomain.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/

关于php - 在永久链接中使用自定义帖子类型帖子 ID 而不是帖子标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39982358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com