Random Taxonomy Images – Part 2

In our first instalment of this series, we looked at adding custom metadata to WordPress taxonomies. Today we’re going to take that custom metadata and display it on the frontend of our site.

If you prefer screencasts, or just want to jump down to the code see the end of the post for both.

Setting Up Our Theme

The firs thing we need to do is to open our active theme and add a new template tag to it. I’m using the Twenty Twelve theme so that means I open category.php and add my template tag.

<header class="archive-header">
    <h1 class="archive-title"><?php printf( __( 'Category Archives: %s', 'twentytwelve' ), '<span>' . single_cat_title( '', false ) . '</span>' ); ?></h1>

<?php if ( category_description() ) : // Show an optional category description ?>
    <div class="archive-meta"><?php echo category_description(); ?></div>
<?php endif; ?>
<?php wptt_taxonomy_header_image(); ?>
</header><!-- .archive-header -->

You can see above that the template tag is wptt_taxonomy_header_image().

Back to the Plugin

So let’s jump back to our plugin. Right at the bottom we are going to add our template tag.

/**
 * Template tag that shows our header image
 *
 * @since 1.1
 * @author WP Theme Tutorial, Curtis McHale
 *
 * @uses WPTT_Tax_Image->show_header_image()     Shows the header image for given taxonomy
 */
function wptt_taxonomy_header_image(){
    $wptt_tax_image = new WPTT_Tax_Image();
    $wptt_tax_image->show_header_image();
} // wptt_taxonomy_header_image

Our template tag is going to call inside the class we set up last time and it calls the show_header_image() function.

/**
 * Echos our header image.
 *
 * @since 1.1
 * @author WP Theme Tutorial
 * @access public
 *
 * @uses $this->get_header_image()     Gets the header image HTML
 */
public function show_header_image(){
    echo $this->get_header_image();
} // show_header_imag

Now our show_header_image() is simply a wrapper for another function called get_header_image() and here is why I always use a ‘show’ and ‘get’ function.

If you end up needing to use a template tag in a shortcode it needs to return it’s value. If you don’t return the value to the shortcode you’re content will end up being added right at the top of your post not where you put the shortcode. Since I set a ‘get’ function, all in need to do if I want to add a shortcode, is call the ‘get’ function, which returns the content I need.

/**
 * Returns the HTML to display our taxonomy image
 *
 * @since 1.1
 * @author WP Theme Tutorial, Curtis McHale
 * @access public
 *
 * @uses is_archive()                Returns true if we are on an archive page
 * @uses $this->term_has_image()     Returns true if term has image
 * @uses get_option()                Gets option from the DB given key
 * @uses esc_url()                   Makes sure we have a safe URL
 */
public function get_header_image(){

    // exit early if we don't have what we want
    if ( ! is_archive() ) return;
    if ( ! $this->term_has_image() ) return;

    global $wp_query;

    $term_id = $wp_query->queried_object_id;

    $term_meta = get_option( "taxonomy_$term_id" );

    $url = $term_meta['tax_image'];

    return '<img src="'. esc_url( $url ) .'" />';

} // get_header_image

Now we start to get to the meat of our template tag. The first thing we do is check if we are on an archive page by using the is_archive. If we’re not on an archive page we will return right away. Next we have a second conditional call $this->term_has_image(). We don’t see that function yet, but all it does is return true if we have a url in our metadata field. We’ll look at term_has_image shortly.

Once we know that we are on the right page, and that our term has an image we actually see about getting the image. First we declare our $wp_query global variable. Out of that we get the ID of the current object being queried, in this case it’s our term object. Then we use that $term_id to get our option from the WordPress database. Since our $term_id is 2 the code really reads $term_meta = get_option( 'taxonomy_2' ).

Now we get our image url from our option array and pass it to the $url variable.

Finally we return the HTML for our image, making sure to sanitize our data on the way out using the WordPress function esc_url. esc_url makes sure that any text passed through it is turned in to a valid URL.

taxonomy-image-display

Our Conditional

Now we haven’t actually looked at our conditional yet.

/**
 * Returns true if the term has a valid URL in the tax_image meta field
 *
 * @since 1.1
 * @author WP Theme Tutorial, Curtis McHale
 * @access private
 *
 * @uses get_option()     Gets option from the DB given key
 */
private function term_has_image(){

    global $wp_query;

    $term_id = $wp_query->queried_object_id;

    $term_meta = get_option( "taxonomy_$term_id" );

    if( ! empty( $term_meta['tax_image'] ) ) return true;

    return false;

Here we repeat some of the code I’ve already gone over so I’ll keep it brief. We start by getting our $term_id then use that to get the option. Then we make sure that our tax_image is actually populated with something and if it is we return true if not we return false.

Well that’s it. Next time we’ll add a random image default out of our theme folder.

The Code

<?php
/*
Plugin Name: Random Taxonomy Images
Plugin URI:
Description: Allows you to set images for taxonomies
Version: 1.0
Author: WP Theme Tutorial, Curtis McHale
Author URI: http://wpthemetutorial.com
License: GPLv2 or later
*/

/*
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

class WPTT_Tax_Image{

    function __construct(){

        add_action( 'category_add_form_fields', array( $this, 'add_tax_image_field' ) );
        add_action( 'category_edit_form_fields', array( $this, 'edit_tax_image_field' ) );
        // saving
        add_action( 'edited_category', array( $this, 'save_tax_meta' ), 10, 2 );
        add_action( 'create_category', array( $this, 'save_tax_meta' ), 10, 2 );


    } // __construct

    /**
     * Echos our header image.
     *
     * @since 1.1
     * @author WP Theme Tutorial
     * @access public
     *
     * @uses $this->get_header_image()     Gets the header image HTML
     */
    public function show_header_image(){
        echo $this->get_header_image();
    } // show_header_image

    /**
     * Returns the HTML to display our taxonomy image
     *
     * @since 1.1
     * @author WP Theme Tutorial, Curtis McHale
     * @access public
     *
     * @uses is_archive()                Returns true if we are on an archive page
     * @uses $this->term_has_image()     Returns true if term has image
     * @uses get_option()                Gets option from the DB given key
     * @uses esc_url()                   Makes sure we have a safe URL
     */
    public function get_header_image(){

        // exit early if we don't have what we want
        if ( ! is_archive() ) return;
        if ( ! $this->term_has_image() ) return;

        global $wp_query;

        $term_id = $wp_query->queried_object_id;

        $term_meta = get_option( "taxonomy_$term_id" );

        $url = $term_meta['tax_image'];

        return '<img src="'. esc_url( $url ) .'" />';

    } // get_header_image

    /**
     * Returns true if the term has a valid URL in the tax_image meta field
     *
     * @since 1.1
     * @author WP Theme Tutorial, Curtis McHale
     * @access private
     *
     * @uses get_option()     Gets option from the DB given key
     */
    private function term_has_image(){

        global $wp_query;

        $term_id = $wp_query->queried_object_id;

        $term_meta = get_option( "taxonomy_$term_id" );

        if( ! empty( $term_meta['tax_image'] ) ) return true;

        return false;

    } // term_has_image

    /**
     * Adds extra meta fields when you are adding a new taxonomy term
     *
     * @since 1.0
     * @author WP Theme Tutorial, Curtis McHale
     * @access public
     */
    public function add_tax_image_field(){
    ?>
        <div class="form-field">
            <label for="term_meta[tax_image]">Taxonomy Image</label>
            <input type="text" name="term_meta[tax_image]" id="term_meta[tax_image]" value="" />
            <p class="description">Add URL to image for the taxonomy image</p>
        </div><!-- /.form-field -->
    <?php
    } // add_tax_image_field

    /**
     * Adds extra meta fields when you are editing a taxonomy term
     *
     * @since 1.0
     * @author WP Theme Tutorial, Curtis McHale
     * @access public
     *
     * @uses get_option()       Returns option from the DB given string
     * @uses esc_url()          Makes sure I have a safe URL
     */
    public function edit_tax_image_field( $term ){
        $term_id = $term->term_id;
        $term_meta = get_option( "taxonomy_$term_id" );
        $image = $term_meta['tax_image'] ? $term_meta['tax_image'] : '';
    ?>
        <tr class="form-field">
            <th scope="row">
                <label for="term_meta[tax_image]">Taxonomy Image</label>
                <td>
                    <input type="text" name="term_meta[tax_image]" id="term_meta[tax_image]" value="<?php echo esc_url( $image ); ?>" />
                    <p class="description">Add URL to image for the taxonomy image</p>
                </td>
            </th>
        </tr><!-- /.form-field -->
    <?php
    } // edit_tax_image_field

    /**
     * Does the saving for our extra taxonomy meta field
     *
     * @since 1.0
     * @author WP Theme Tutorial, Curtis McHale
     * @access public
     *
     * @param   int     $term_id    req     The id of the term we are saving
     *
     * @uses get_option()       Gets option from the DB given string
     * @uses update_option()    Updates option given key and new value. Creates if !exist
     */
    public function save_tax_meta( $term_id ){

        if ( isset( $_POST['term_meta'] ) ) {

            $t_id = $term_id;
            $term_meta = array();

            $term_meta['tax_image'] = isset ( $_POST['term_meta']['tax_image'] ) ? esc_url( $_POST['term_meta']['tax_image'] ) : '';

            // Save the option array.
            update_option( "taxonomy_$t_id", $term_meta );

        } // if isset( $_POST['term_meta'] )
    } // save_tax_meta

} // WPTT_Tax_Image

$wptt_tax_image = new WPTT_Tax_Image();

/**
 * Template tag that shows our header image
 *
 * @since 1.1
 * @author WP Theme Tutorial, Curtis McHale
 *
 * @uses WPTT_Tax_Image->show_header_image()     Shows the header image for given taxonomy
 */
function wptt_taxonomy_header_image(){
    $wptt_tax_image = new WPTT_Tax_Image();
    $wptt_tax_image->show_header_image();
} // wptt_taxonomy_header_image

Screencast

Curtis McHale

Posts Twitter

Curtis is a web designer/developer specialized in WordPress eCommerce development on WooCommerce. You can get in touch with him about projects on SFNdesign.
My Blog is 4 Times Faster Than Your Blog

No Comments

Be the first to start the conversation.

Leave a Reply

*

Text formatting is available via select HTML.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>