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

标签 php wordpress url-rewriting custom-post-type slug

我有一个自定义帖子类型“员工”。我正在尝试重写 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/

相关文章:

html - 移动修复 Wordpress 类问题

iis - 使用 web.config 文件在 IIS 中看似简单的重定向

apache - RewriteRules 不加载某些 css。 js 和图像

php - Mod_Rewrite 扩展移除改变了 404 的功能

php - 使用纯 Swift、PHP 代码将视频上传到服务器

php - 无法从 Google App Engine 上的 Php PDO 获取响应 header

wordpress - 如何预览Woocommerce的电子邮件模板

php - 使用关系检查其他表中的状态

php - 将mysql数据导出到csv文件

css - 在多级菜单中隔离 CSS 样式