Products
GG网络技术分享 2025-03-18 16:12 2
I have a php function in Wordpress which automatically assigns a users first and last name to a post title. This is intended in the frontend. However, in the backend when an administrator edits the same post it should not overwrite the post with the administrators values.
How can this be modified so that A) either it does not run in the backend i.e. only frontend or B) only executes if the user is not an admin? Any help is much appreciated. Thank you all.
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\' );
I have written some comments for you inside your function here - But everything should make sense
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\' );
A little cleaner function could be :
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\' );
###
You can try this to disable post title
jQuery(document).ready(function() {post_status = /* your post status here */
if( post_status != \\\"auto-draft\\\" ) {
jQuery( \\\"#title\\\" ).attr( \'disabled\', true );
});
###
You could check if the current user is admin with something like that :
if ( current_user_can( \'administrator\' ) ) {/* A user with admin privileges */
} else {
/* A user without admin privileges */
}
current_user_can function documentation : https://codex.wordpress.org/Function_Reference/current_user_can
Demand feedback