代码之家  ›  专栏  ›  技术社区  ›  Tasos

以编程方式添加附件会设置错误的永久链接

  •  0
  • Tasos  · 技术社区  · 5 年前

    我有几百个PDF,我尝试用Wordpress编程上传它们,并将它们附加到带有高级自定义字段的自定义文章类型中。

    这是我创建附件的代码的一部分

    function update_attachment( $f, $pid, $file_url ){
            
        wp_update_attachment_metadata( $pid, $f );
        
        if( empty( $file_url ) ) 
            return false;
    
        $wp_upload_dir = wp_upload_dir();
        $filetype = wp_check_filetype( basename( $file_url ), null );
    
        // Prepare an array of post data for the attachment.
        $attachment = array(
            'guid'           => $wp_upload_dir['url'] . '/' . basename( $file_url ), 
            
            'post_parent'    => $pid,
            'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $file_url ) ),
            'post_type'      => 'attachment',
            'post_content'   => '',
            'post_status'    => 'inherit',
            'post_mime_type' => $filetype['type'],
        );
    
          $attach_id = wp_insert_attachment( $attachment, $file_url );
    
        return array(
            'pid' => $pid,
            'url' => $file_url,
            'attach_id' => $attach_id
        );
    
    }
    
    //create the custom post type
    $post_id = wp_insert_post(array (
        'post_type' => 'resources',
        'post_title' => $file['Title'],
        'post_status' => 'publish',
        'comment_status' => 'closed',  
        'ping_status' => 'closed',   
    ));
    
    //Create the attachment in Media
    $att = update_attachment( 'file', $post_id , 'migration/' . $file['FileName'] );
    
    //Save the attachment to the ACF field
    update_field('field_5eeb34e23731c', $att['attach_id'], $post_id );
    

    这个 $file 变量是我在此代码之前创建的数组,它包含pdf的信息。

    帖子是用正确的附件创建的。但是,媒体文件的永久链接是我创建的帖子中的永久链接。

    mydomain.org/resources/filename/‎

    所以,当我打开url时 mydomain.org/wp-content/uploads/migration/filename.pdf

    0 回复  |  直到 5 年前