dpg76975 2018-06-06 13:01
浏览 100

WordPress:使用帖子ID和帖子标题作为上传图像的文件名

I am trying to add the post ID and the post title to all uploaded images in my WordPress posts.

I have already found a function, which renames my images like a charm, but I cannot get the post id and post title. What am I doing wrong?

function new_filename($filename, $filename_raw) {

    global $post;
    $post_id = $post->ID; 
    $post_slug = $post->post_name;

    $info = pathinfo($filename);
    $ext  = empty($info['extension']) ? '' : '.' . $info['extension'];
    $new = $post_id . $post_slug . $ext;

    if( $new != $filename_raw ) {
        $new = sanitize_file_name( $new );
    }

    return $new;

}
add_filter('sanitize_file_name', 'new_filename', 10, 2);

Thank you.

  • 写回答

1条回答 默认 最新

  • dongyouzhui1969 2018-06-06 13:41
    关注

    Your images are uploaded in /wp-admin and in the admin area it is unfortunatly not always easy to get the post ID and the post title.

    First of all you have to check if there even is a post ID and title. Because if somebody upload an image within the media library itself, there simple is no post title or id.

    If somebody is uploading an image to a page / post / custom post type edit page instead, there should be a post ID.

    Try:

     $post_id = $_GET['post'];
    

    In general I would recommend the following procedure:

    function new_filename($filename, $filename_raw) {
    
        $post = admin_find_current_post();
    
        if($post) {
             // proceed as you have proposed
         } else {
              return $filename;
         }
    
    }
    add_filter('sanitize_file_name', 'new_filename', 10, 2);
    
    
    function admin_find_current_post() {
        if(isset($_GET['post']) && intval($_GET['post']) > 0 ) {
             return get_post($_GET['post']);
        }
    
        global $post;
        if($post) {
            return $post;
        }
    
        // and maybe more possibilities?
    
    }
    

    Therefore the rest of the challange for you is to complete this function and check if it can be improved further ;-)

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题