dongyao9762 2019-06-20 09:40
浏览 62
已采纳

wordpress中的php函数仅在用户不是admin时才适用

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' );
  • 写回答

3条回答 默认 最新

  • dongqiaogouk86049 2019-06-20 09:58
    关注

    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' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵