0

I was using this solution for my problem, create a taxonomy for images without using any plugin, finded here: How to add upload field in a custom taxonomy?

This is the code I use:

    function edit_form_tag( ) {
    echo ' enctype="multipart/form-data"';
}
add_action( 'category_term_edit_form_tag' , 'edit_form_tag' );
add_action( 'tax_projects_term_edit_form_tag' , 'edit_form_tag' );

add_action( 'tax_projects_term_edit_form_tag' , 'edit_form_tag' );

/** Add New Field To Category **/
function additional_category_fields( $term, $tax ) {
    $uploadID   = get_option( "{$tax}_image_{$term->term_id}" );            // Retrieve our Attachment ID from the Options Database Table
    $feedback   = get_option( "{$tax}_image_{$term->term_id}_feedback" );   // Retrieve any upload feedback from the Optoins Database Table
?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="meta-order"><?php _e( 'Category Image' ); ?></label></th>
        <td>
            <div id="catImage">

                <!-- Create a nonce to validate against -->
                <input type="hidden" name="upload_meta_nonce" value="<?php echo wp_create_nonce( basename( __FILE__ ) ); ?>" />

                <!-- Define our actual upload field -->
                Please choose an image: <input type="file" name="_uploaded_file" value="" />

                <?php 
                  if( is_numeric( $uploadID ) ) :                                       // IF our upload ID is actually numeric, proceed

                    /***
                    /*  In this case we are pulling an image, if we are uploading
                    /*  something such as a PDF we could use the built-in function
                    /*  wp_get_attachment_url( $id );
                    /*  codex.wordpress.org/Function_Reference/wp_get_attachment_url
                    ***/
                    $imageArr = wp_get_attachment_image_src( $uploadID, 'medium' );     // Get the URL of the medium sized image
                    $imageURL = $imageArr[0];                                           // wp_get_attachment_image_src() returns an array, index 0 is our URL
                ?>

                    <div id="uploaded_image">
                        <a href="post.php?post=<?php echo $uploadID; ?>&action=edit" target="_blank">Edit Image</a><br />

                        <!-- Display our image using the URL retrieved earlier -->
                        <a href="post.php?post=<?php echo $uploadID; ?>&action=edit" target="_blank"><img src="<?php echo $imageURL; ?>" /></a><br /><br />
                    </div>

                <!-- IF we received feedback, something went wrong and we need to show that feedback. -->               
                <?php elseif( ! empty( $feedback ) ) : ?>

                    <p style="color:red;font-size:12px;font-weight;bold;font-style:italic;"><?php echo $feedback; ?></p>

                <?php endif; ?>

            </div>
            <span class="description"><?php _e( 'Upload an appropriate image.' ); ?></span>
                <br />
                <br />

            <!-- This link is for our deletion process -->
            <?php if( ! empty( $uploadID ) ) : ?>

                <a href="javascript:void(0)" class="deleteImage" style="color:red;text-decoration:underline;">Delete</a>

            <?php endif; ?>

        </td> 
    </tr>
<?php
    /** Since we've shown the user the feedback they need to see, we can delete our option **/
    delete_option( "{$tax}_image_{$term->term_id}_feedback" );
}
add_action( 'category_edit_form_fields', 'additional_category_fields', 10, 2 ); 

/** Save Category Meta **/
function save_category_fields( $term_id ) {

    // Make sure that the nonce is set, taxonomy is set, and that our uploaded file is not empty
    if(
      isset( $_POST['upload_meta_nonce'] ) && wp_verify_nonce( $_POST['upload_meta_nonce'], basename( __FILE__ ) ) &&
      isset( $_POST['taxonomy'] ) && isset( $_FILES['_uploaded_file'] ) && !empty( $_FILES['_uploaded_file'] )
    ) {
        $tax            = $_POST['taxonomy'];                                                   // Store our taxonomy, used for the option naming convention
        $supportedTypes = array( 'image/gif', 'image/jpeg', 'image/png' );                      // Only accept image mime types. - List of mimetypes: http://en.wikipedia.org/wiki/Internet_media_type
        $fileArray      = wp_check_filetype( basename( $_FILES['_uploaded_file']['name'] ) );   // Get the mime type and extension.
        $fileType       = $fileArray['type'];                                                   // Store our file type

        // Verify that the type given is what we're expecting
        if( in_array( $fileType, $supportedTypes ) ) {
            $uploadStatus = wp_handle_upload( $_FILES['_uploaded_file'], array( 'test_form' => false ) );   // Let WordPress handle the upload

            // Make sure that the file was uploaded correctly, without error
            if( isset( $uploadStatus['file'] ) ) {
                require_once(ABSPATH . "wp-admin" . '/includes/image.php');

                // Let's add the image to our media library so we get access to metadata
                $imageID = wp_insert_attachment( array(
                        'post_mime_type'    => $uploadStatus['type'],
                        'post_title'        => preg_replace( '/\.[^.]+$/', '', basename( $uploadStatus['file'] ) ),
                        'post_content'      => '',
                        'post_status'       => 'publish'
                    ),
                    $uploadStatus['file']
                );

                // Generate our attachment metadata then update the file.
                $attachmentData = wp_generate_attachment_metadata( $imageID, $uploadStatus['file'] );
                wp_update_attachment_metadata( $imageID,  $attachmentData );


                $existingImage = get_option( "{$tax}_image_{$term_id}" );               // IF a file already exists in this option, grab it
                if( ! empty( $existingImage ) && is_numeric( $existingImage ) ) {       // IF the option does exist, delete it.
                    wp_delete_attachment( $existingImage );
                }

                update_option( "{$tax}_image_{$term_id}", $imageID );                   // Update our option with the new attachment ID
                delete_option( "{$tax}_image_{$term_id}_feedback" );                    // Just in case there's a feedback option, delete it - theoretically it shouldn't exist at this point.
            }
            else {
                $uploadFeedback = 'There was a problem with your uploaded file. Contact Administrator.';    // Something major went wrong, enable debugging
            }
        }
        else {
            $uploadFeedback = 'Image Files only: JPEG/JPG, GIF, PNG';   // Wrong file type
        }

        // Update our Feedback Option
        if( isset( $uploadFeedback ) ) {
            update_option( "{$tax}_image_{$term_id}_feedback", $uploadFeedback );
        }
    }
}
add_action ( 'edited_category', 'save_category_fields');

My question in easy, I'm new to php and I want to know how I can output this value. I've tried in this way:

<?php
$image_of = get_option('category_image_1');
echo $image_of;
?>

I use "get_option('category_image_1')" as the link above say into step 3, but I have no idea of what I have to put before echo .. any suggestions?

Thanks! Noemi

0

Found a solution:

<?php 
    $cat = get_the_category();
    $category_id = $cat[0]->term_id;


                foreach (get_the_category() as $cat) :




                $attachmentId = get_option("category_image_{$category_id}", 'null');
                $imageArr = wp_get_attachment_image_src( $attachmentId, 'medium' );     
                $imageURL = $imageArr[0];                                           
                echo '<img src="' .  $imageURL . '" />';

                endforeach; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.