我在Wordpress中有一个php函数,该函数自动将用户的名字和姓氏分配给帖子标题。这是在前端。但是,在后端中,当管理员编辑相同的帖子时,不应使用管理员的值覆盖该帖子。
如何对此进行修改,以使A)不在后端运行,即仅在前端运行,或者B)仅在用户不是管理员的情况下执行?任何帮助深表感谢。谢谢大家。
function wpse67262_change_title( $data ) {
if( 'gd_place' != $data['post_type'] )
return $data;
$user = wp_get_current_user();
$data['post_title'] = $user->first_name . ' ' . $user->last_name;
return $data;
}
add_filter( 'wp_insert_post_data', 'wpse67262_change_title' );
答案 0 :(得分:0)
您可以尝试禁用帖子标题
jQuery(document).ready(function() {
post_status = /* your post status here */
if( post_status != "auto-draft" ) {
jQuery( "#title" ).attr( 'disabled', true );
});
答案 1 :(得分:0)
您可以通过以下方式检查当前用户是否为管理员:
if ( current_user_can( 'administrator' ) ) {
/* A user with admin privileges */
} else {
/* A user without admin privileges */
}
current_user_can函数文档:https://codex.wordpress.org/Function_Reference/current_user_can
答案 2 :(得分:0)
我在这里在您的函数中为您写了一些评论-但一切都应该有意义
function wpse67262_change_title( $data ) {
if( 'gd_place' != $data['post_type'] ){
return $data;
//This is for your pos type only?
}
$user = wp_get_current_user();
if(!is_admin() && !current_user_can('administrator')){
//So this makes sure, that the following does NOT run in the backend and also takes the admin role into account
$data['post_title'] = $user->first_name . ' ' . $user->last_name;
return $data;
} else {
//one of the conditions failed - So do nothing new
return $data;
}
}
add_filter( 'wp_insert_post_data', 'wpse67262_change_title' );
更清洁的功能可能是:
function wpse67262_change_title( $data ) {
if(!is_admin() && !current_user_can('administrator') && 'gd_place' == $data['post_type']){
//So this makes sure, that the following does NOT run in the backend and also takes the admin role into account, and checks the post type
$user = wp_get_current_user();
$data['post_title'] = $user->first_name . ' ' . $user->last_name;
return $data;
} else {
//one of the conditions failed - So do nothing new
return $data;
}
}
add_filter( 'wp_insert_post_data', 'wpse67262_change_title' );