最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

json - Zip a file and add as attachment

matteradmin6PV0评论

I first add support for mime type attachments

// ADD MIME TYPEs FOR ATTACHMENTS
add_filter( 'upload_mimes', 'my_myme_types', 1, 1 );
function my_myme_types( $mime_types ) {
  $mime_types['txt'] = 'text/plain';
  $mime_types['json'] = 'application/json';
  $mime_types['zip'] = 'application/zip';

  return $mime_types;
}

Now I have the way that I would add a json object to to a json file and then attach

$user_id = absint($_POST["uid"]);
$post_title = sanitize_text_field($_POST["post_title"]);
$post_object = get_page_by_title($post_title, OBJECT, 'chat');
$post_id = $post_object->ID;
$msg_array = $_POST["msg_data"];
$ext = ".json";
$path = "/wp/wp-content/uploads/";
$file = $user_id . $post_title . $ext;
$wp_upload_dir = wp_upload_dir();
echo $wp_upload_dir;
file_put_contents($wp_upload_dir['path'] .'/'. basename( $file ), $msg_array);
file_put_contents($file, $msg_array);
$attachment = array(
    'guid'=> $wp_upload_dir['url'] .'/'. basename( $file ), 
    'post_mime_type' => 'application/json',
    'post_title' => $user_id . $post_title,
    'post_content' => $user_id . $post_title,
    'post_status' => 'inherit'
     );

$mid = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($mid) ){
    wp_update_attachment_metadata( $mid, wp_generate_attachment_metadata( $mid, $file ) );
}

But I want to save space and zip this json file and then add the zip as the attachment. How do I adapt this?

This being the method for zipping a file

$zip = new ZipArchive;
if ($zip->open('test_new.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file
    $zip->addFile('test.json');

    // All files are added, so close the zip file.
    $zip->close();
}

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far