WordPress.org

Ready to get started?Download WordPress

Forums

Create image and save to media library (5 posts)

  1. Scott
    Member
    Posted 2 years ago #

    Hi,

    I have a page that allows users to create an image in canvas and save it. I want to be able to save it to the WP media library, but I don't know how to get WP to recognize the image. So far, my code looks like this:

    <?php
    if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
    $filteredData=substr($imageData, strpos($imageData, ",")+1);
    $unencodedData=base64_decode($filteredData);
    function getNewFilename($dir = '../wp-content/uploads/') {
    return $dir."image_".time().".png";
    }
    $filename = getNewFilename();
    $fp = fopen( $filename, 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
    }
    ?>

    I'm really new to coding, and I don't have much experience with server-side stuff. It would be really great if I could save this image along with post text to WP and publish it after admin approval.

    Thanks in advance,
    Scott

  2. Peter Baylies
    Member
    Posted 2 years ago #

    Scott,

    The way to add an attachment to the media library is to use the wp_insert_attachment function. For an example of a plugin that does something similar to you want to do, take a look at the code for the Grab & Save plugin.

  3. Scott
    Member
    Posted 2 years ago #

    Hi Peter,

    Thanks. I bumped into Grab & Save just after I posted. I'll look closer at it. Just to be sure, do i insert the wp_insert_attachment function into my code for saving to the server?

    Thanks for the help.

  4. Peter Baylies
    Member
    Posted 2 years ago #

    Scott,

    Provided that you're doing that within WordPress, yes, that's a fine place for it; in any case you'll want to do it after you've uploaded the attachment and moved it where you want it.

  5. Scott
    Member
    Posted 2 years ago #

    Thanks. It'll take me a bit to learn it, but I'm on the right track.

Topic Closed

This topic has been closed to new replies.

About this Topic