WordPress内置了一种文章短链接,型如 www.yoursite.com?p=1 (其中 1 为文章的ID),你可以在后台发布文章的时候查看到:

而自定义文章类型默认是生成短链接的,所以我们需要添加相应的函数。比如我们要给 book 这种自定义文章类型添加短链接功能,可以在你的插件文件或者当前主题的 functions.php 添加类似下面的代码:
/**
* 给自定义文章类型“book”添加短链接
*/
function wpdaxue_shortlinks_for_book( $shortlink, $id, $context ) {
// 上下文可以是一篇文章、附件、或查询
$post_id = 0;
if ( 'query' == $context && is_singular( 'book' ) ) {
// 如果上下文是查询,使用get_queried_object_id 获取ID
$post_id = get_queried_object_id();
}
elseif ( 'post' == $context ) {
// 如果上下文是文章,使用以传递的 $id
$post_id = $id;
}
// 只对 book这种自定义文章类型操作
if ( 'book' == get_post_type( $post_id ) ) {
$shortlink = home_url( '?p=' . $post_id );
}
return $shortlink;
}
add_filter( 'pre_get_shortlink', 'wpdaxue_shortlinks_for_book', 10, 3 ); |
/**
* 给自定义文章类型“book”添加短链接
*/
function wpdaxue_shortlinks_for_book( $shortlink, $id, $context ) {
// 上下文可以是一篇文章、附件、或查询
$post_id = 0;
if ( 'query' == $context && is_singular( 'book' ) ) {
// 如果上下文是查询,使用get_queried_object_id 获取ID
$post_id = get_queried_object_id();
}
elseif ( 'post' == $context ) {
// 如果上下文是文章,使用以传递的 $id
$post_id = $id;
}
// 只对 book这种自定义文章类型操作
if ( 'book' == get_post_type( $post_id ) ) {
$shortlink = home_url( '?p=' . $post_id );
}
return $shortlink;
}
add_filter( 'pre_get_shortlink', 'wpdaxue_shortlinks_for_book', 10, 3 );
然后在循环中使用 wp_get_shortlink() 函数获取短链接:
<?php echo wp_get_shortlink(); ?> |
<?php echo wp_get_shortlink(); ?>
注:本文的用途不是给后台自定义文章类型发布时添加“获取短链接地址”的功能,而是让自定义文章类型生成短链接,然后可以在需要显示的地方输出。
参考资料:http://wp.tutsplus.com/articles/tips-articles/quick-tip-add-shortlinks-to-custom-post-types/
来源:
https://www.wpdaxue.com/add-shortlinks-to-custom-post-types.html
微信公众号
手机浏览(小程序)
Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(): Failed to enable crypto in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32778.jpg): failed to open stream: operation failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57