最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Retrieve wordpress image filename as it is loaded - Stack Overflow

programmeradmin0浏览0评论

I use CF7 to capture some user input and i want to add the functionality for the user to attach an image to that submission. I use ACF to configure my custom post types and meta data fields.

Documentation says that CF7 does not save images to the media folder by default but I'm finding that they are being saved. Some investigation suggests the ACF plugin causes this to happen. [Update: further investigation showed it was the Tablesome plugin causing the issue]. Now for me this works just fine as my aim is to save the image anyway BUT the uploaded filename (to the media library) gets 'tweeked' somewhere between CF7 capturing the file and it being saved into the media library.

I can grab the CF7 temp upload file (wp-content/uploads/wpcf7_uploads/0099184201/IMG_2780.jpeg) but this is then saved in the media library as wp-content/uploads/2025/02/1738853730-IMG_2780.jpeg.

As you can see the filename has been modified somehow (adding '/1738853730-' to it)

How do i get this media library filename / url ?

I have tried various event triggers on the CF7 side of things (before send mail etc) but all i can capture is what CF7 is doing with the file - which is saving it to a temp folder prior to sending an email and then deleting it (as expected).

I need the media library filename to be saved as a url on a CPT for later use.

I use CF7 to capture some user input and i want to add the functionality for the user to attach an image to that submission. I use ACF to configure my custom post types and meta data fields.

Documentation says that CF7 does not save images to the media folder by default but I'm finding that they are being saved. Some investigation suggests the ACF plugin causes this to happen. [Update: further investigation showed it was the Tablesome plugin causing the issue]. Now for me this works just fine as my aim is to save the image anyway BUT the uploaded filename (to the media library) gets 'tweeked' somewhere between CF7 capturing the file and it being saved into the media library.

I can grab the CF7 temp upload file (wp-content/uploads/wpcf7_uploads/0099184201/IMG_2780.jpeg) but this is then saved in the media library as wp-content/uploads/2025/02/1738853730-IMG_2780.jpeg.

As you can see the filename has been modified somehow (adding '/1738853730-' to it)

How do i get this media library filename / url ?

I have tried various event triggers on the CF7 side of things (before send mail etc) but all i can capture is what CF7 is doing with the file - which is saving it to a temp folder prior to sending an email and then deleting it (as expected).

I need the media library filename to be saved as a url on a CPT for later use.

Share Improve this question edited Feb 8 at 19:03 Stu asked Feb 6 at 15:46 StuStu 234 bronze badges 2
  • ACF relies on the native WP media uploading functionality, so you can use the wp_get_attachment_url to retrieve the URL for an attachment. – Richard Commented Feb 7 at 8:48
  • if you need the name send by the browser, you can find it in $_FILES. – mmm Commented Feb 7 at 9:04
Add a comment  | 

2 Answers 2

Reset to default 2

For this I would suggest to capture the CF7 file temp path. From this you can exreact the original filename. Once you get the original name of the file, query for the attachment with the original filename in DB. Get the attachment url from attachment id and save it in the ACF field.

add_action('wpcf7_mail_sent', function($contact_form) {
    $submission = WPCF7_Submission::get_instance();
    if (!$submission) {
        return;
    }

    $uploaded_files = $submission->uploaded_files();
    if (empty($uploaded_files)) {
        return;
    }

    foreach ($uploaded_files as $field_name => $file_path) {
        $file_name = basename($file_path); // Original filename (IMG_2780.jpeg)
        
        // Search for the uploaded file in the media library
        $args = [
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'posts_per_page' => 1,
            'meta_query'     => [
                [
                    'key'     => '_wp_attached_file',
                    'value'   => $file_name,
                    'compare' => 'LIKE', // Since filename gets prefixed
                ],
            ],
        ];

        $query = new WP_Query($args);
        if ($query->have_posts()) {
            $attachment_id = $query->posts[0]->ID;
            $media_url = wp_get_attachment_url($attachment_id);

            // Save to a custom post type (modify this based on your CPT setup)
            $post_id = YOUR_CPT_POST_ID; // Replace with your actual CPT post ID
            update_field('your_acf_field', $media_url, $post_id);
        }
    }
});

I've tested this locally and it works.

So what this does is it hooks into the cf7 submission and gets the uploaded file from the wpcf7_uploads directory, and then converts into a proper media item with all various image sizes.

It then adds the media item to your your_custom_post_type as a new post, and updates an ACF image field your_image_field with the attachment.

This function save_uploaded_file_to_cpt() is just an example of how you can handle the attachment after its been created, I'm not exactly sure what you want do after attachment has been created.

This will work on all forms if you put this in your functions, you will need to modify it if you only want it to work on specific forms.

Just follow the comments in code below so you know what is happening.

// when our form submits and send email notification
add_action('wpcf7_mail_sent', function($contact_form) {

    // get the submission instance
    $submission = WPCF7_Submission::get_instance();
    if (!$submission) return;

    // get uploaded files
    $uploaded_files = $submission->uploaded_files();

    // bail early if we have no files
    if (empty($uploaded_files)) return;

    // loop through uploaded files
    foreach ($uploaded_files as $field_name => $file_paths) {

        // make sure we handle both single and multiple file uploads
        $file_paths = is_array($file_paths) ? $file_paths : [$file_paths];

        foreach ($file_paths as $file_path) {
            if (!empty($file_path) && file_exists($file_path)) {

                // move the file to the media library
                $attachment_id = insert_attachment_from_cf7($file_path);
 
                // if we have attachment
                if ($attachment_id) {

                    // get the final url
                    $final_url = wp_get_attachment_url($attachment_id);

                    // save to a custom post type (modify to match your cpt setup)
                    // this function is just an example of how you can handle the image after its been made into attachment
                    $post_id = save_uploaded_file_to_cpt($final_url, $attachment_id);
                }
            }
        }
    }
});

/**
 * insert attachment from cf7 file upload into the media library
 * @param string $file_path the full file path of the uploaded file
 * @return int|false attachment id if successful, false on failure
 */
function insert_attachment_from_cf7($file_path) {

    // get file type info
    $filetype = wp_check_filetype($file_path);
    $filename = basename($file_path);

    // get the upload directory
    $upload_dir = wp_upload_dir();
    $new_file_path = $upload_dir['path'] . '/' . $filename;

    // copy the file to the upload directory
    if (!copy($file_path, $new_file_path)) {
        return false;
    }

    // prepare attachment metadata
    $attachment = array(
        'guid'           => $upload_dir['url'] . '/' . $filename,
        'post_mime_type' => $filetype['type'],
        'post_title'     => sanitize_file_name(pathinfo($filename, PATHINFO_FILENAME)),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    // insert into the media library
    $attach_id = wp_insert_attachment($attachment, $new_file_path);

    // generate and update attachment metadata
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $new_file_path);
    wp_update_attachment_metadata($attach_id, $attach_data);

    // return attachment id
    return $attach_id;
}

/**
 * save uploaded file to a custom post type
 * @param string $image_url the url of the uploaded image
 * @param int $attachment_id the id of the media library attachment
 * @return int|false the post id of the saved custom post type entry, false on failure
 */
function save_uploaded_file_to_cpt($image_url, $attachment_id) {
    
    // create a new custom post type entry (modify 'your_custom_post_type' to match your cpt slug)
    $post_data = array(
        'post_title'   => basename($image_url),
        'post_status'  => 'publish',
        'post_type'    => 'your_custom_post_type',
    );

    // insert the post
    $post_id = wp_insert_post($post_data);

    // if we have post id
    if ($post_id) {

        // update the acf field with the attachment id (modify 'your_image_field' to match your acf field)
        update_field('your_image_field', $attachment_id, $post_id);
    
    }

    // return the post id
    return $post_id;
}
发布评论

评论列表(0)

  1. 暂无评论