利用add_meta_boxes为WordPress文章添加来源功能

当你使用WordPress发布文章的时候,有时或许会偷一下懒,直接从某个网站转载文章,为了尊重原作者的版权,你可能会注明来源。在WordPress中,你可以直接将来源放置在内容中,也可以单独利用meta字段记录下来。今天就教大家使用后者来实现来源功能。

首先按照惯例我们需要在 WordPress 的 functions.php 文件添加以下代码:

if ( !function_exists( 'post_meta_boxes_setup' ) ) {
function post_meta_boxes_setup() {
/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'add_post_meta_boxes' );
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'save_post_source_meta', 10, 2 );
 
}
}
 
if ( !function_exists( 'add_post_meta_boxes' ) ) {
function add_post_meta_boxes() {
add_meta_box(
'post-source', // Unique ID
esc_html__( '文章来源', 'low-text' ), // Title
'post_source_meta_box', // Callback function
'post', // Admin page (or post type)
'normal', // Context
'high' // Priority
);
}
}
 
/* Display the post meta box. */
if ( !function_exists( 'post_source_meta_box' ) ) {
function post_source_meta_box( $object, $box ) { ?>
 

 


post_type ); /* Check if the current user has permission to edit the post. */ if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ) return $post_id; /* Get the posted data and sanitize it for use as an HTML class. */ $new_meta_value = ( isset( $_POST['post-source'] ) ? balanceTags( $_POST['post-source'] ) : '' ); /* Get the meta key. */ $meta_key = 'post_source'; /* Get the meta value of the custom field key. */ $meta_value = get_post_meta( $post_id, $meta_key, true ); /* If a new meta value was added and there was no previous value, add it. */ if ( $new_meta_value && '' == $meta_value ) add_post_meta( $post_id, $meta_key, $new_meta_value, true ); /* If the new meta value does not match the old value, update it. */ elseif ( $new_meta_value && $new_meta_value != $meta_value ) update_post_meta( $post_id, $meta_key, $new_meta_value ); /* If there is no new meta value but an old value exists, delete it. */ elseif ( '' == $new_meta_value && $meta_value ) delete_post_meta( $post_id, $meta_key, $meta_value ); } }

添加了上面代码之后我们就可以在后台编辑文章的时候看到我们的成果了,如下图所示。

add_meta_boxes

利用add_meta_boxes为WordPress文章添加来源功能

前端文章页显示的代码

在single.php或根据实际情况,放置下面的代码:


ID, "post_source", true)): ?>

来源:ID, "post_source", true)); ?>

我们把来源字体的颜色设置为比正常文章内容字体的颜色淡一点,在css文件中添加如下CSS代码:

#content-area p.source{
text-indent: 0px;
font-size: 15px;
color: #999;
}
 
#content-area p.source a{
font-weight: 500;
}
 
#content-area p.source i{
margin-right:10px;
}

现在我们来看看完成之后前端显示情况

add_meta_boxes

利用add_meta_boxes为WordPress文章添加来源功能

到这里就全部完成了。
PS:add_meta_boxes除了添加文章来源之外,你还可以利用它作其他的用途,比如某些下载站可以利用它用作下载地址的添加。

© 版权声明
THE END
打赏一根烟,继续保持。
点赞2打赏作者 分享
评论 共3条
头像
友好交流,请勿发纯表情,请勿灌水,违者封号喔
提交
头像

昵称

取消
昵称表情代码图片
    • 头像boke112导航0
    • 头像憧憬点滴记忆0