Support

Account

Home Forums Backend Issues (wp-admin) Read content of uploaded PDF file and save it ACF field

Helping

Read content of uploaded PDF file and save it ACF field

  • I have a custom post type “movies” with ACF file upload field called “document_file”. I would like to save the content of the uploaded PDF document to another ACF textarea field called “document_content”. I have a working PHP code using XPDF binaries and a PHP library, that reads PDF content and returns a string with this content.

    I’m using following code to update ACF field:

    function set_field_value( $post_id ) {
        global $post;
        $post_id = $post->ID;
        $posttype = get_post_type($post_id);
        $value = 'some sample text'; // this should be a string which we get from uploaded pdf documentcontent 
    
        $document_content = get_field('document_content', $post_id);
    
        if ($posttype == 'movies' & empty($document_content)) {
            update_field('document_content', $value, $post_id);
        }
    }
    add_action('acf/save_post', 'set_field_value');

    This works, but I would like to pass a $value variable from a function attached to file upload hook to a function set_field_value() in acf/save_post hook, but I’m not sure how to do it – which hook to use on ACF file upload. Example function, which reads PDF content:

    function read_pdf_content( $post_id ) {
        require __DIR__ . '/vendor/autoload.php';
        $logger = null;
    
        $document_file = get_field('document_file', $post_id);
    
        if( $document_file ) {
        
            $pdfToText = XPDF\PdfToText::create(array(
                    'pdftotext.binaries' => '../../../../usr/bin/xpdf/bin64/pdftotext'
                ), $logger);
    
            $document_content_txt = $pdfToText->getText($document_file['filename']);
            // remove non-latin characters
            $pdf_content = preg_replace('/[^\00-\255]+/u', '', $document_content_txt);
    
            //update_field('document_content', $pdf_content, $post_id);
        } else {
            $pdf_content = '';
        }
    
        return $pdf_content;
    }

    So in this case I would like to pass $pdf_content variable to acf/save_post’ hook, so I could save it in ACF field called ‘document_content’.

    Is wp_handle_upload hook a way to go?

    Regards.

  • change

    
    $document_file = get_field('document_file', $post_id);
    

    to

    
    $document_file = get_attachment_file(get_field('document_file', $post_id, false));
    

    setting the last parameter false for ACF gets the unformatted value, in this case the attachment ID. The WP function get_attachment_file() loads that file into the variable. Then you can pass this to convert it to text.

    Then you call update_field() to update the text field with what is returned.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.