Adding Custom Meta to WordPress Taxonomies

Custom Meta on WordPress Categories

Custom Meta on WordPress Categories


This is the 1st part in a 3 part series. Our first installment will add custom metadata fields to the WordPress built in categories which we will use to add a URL to an image. Our second instalment will show them on the frontend of the site on our taxonomies and the final installment will let us create a random default image out of a folder in our plugin.

You can jump to the end for the screencast and full code.

Getting Set Up

To start with we need to create a plugin in our WordPress plugins folder. So create a folder called wptt-random-taxonomy-image and inside that create a file called wptt-random-taxonomy-image.php. The first thing we need to do is place a proper plugin header in our file.

<?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.
*
?>

Now that we have a proper plugin header we can start to build out the functionality we need. We’ll do that by creating a new class to wrap our functions.

<?php
class WPTT_Tax_Image{

    function __construct(){

    } // __construct

} // WPTT_Tax_Image

$wptt_tax_image = new WPTT_Tax_Image();
?>

Now that we have our basic class set up we can start adding our actions which will add the meta data fields to our taxonomies. Remember when you use a class the __construct function will always be called first. It’s inside this __construct function that we place all our actions and filters.

So lets look at our first 2 actions which add fields to our the taxonomy forms.

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' ) );

} // __construct

Here we are using 2 generic hooks which are called $taxonomy_add_form_fields and $taxonomy_edit_form_fields. Since we want to add to our categories we use category_add_form_fields and category_edit_form_fields. If you had a custom taxonomy of region you would use region_edit_form_fields and region_add_form_fields.

The edit version of the hook adds our metadata fields when we are editing a taxonomy term, and the add version adds the extra form fields when we are adding a new taxonomy term.

Now we can jump in to the functions that are called with the above actions.

Our Form Fields

<?php
/**
 * 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
?>

The first function adds our form fields when we are adding a new term to our taxonomy. It’s a pretty basic form, but you should note how I’m naming my fields. As I said earlier, there is no place to officially store taxonomy meta so we are storing in the WordPress options table. Littering the options table with individual entries for each item on each term we are going to save each term in an array. So when you see term_meta[tax_image] I’m building out the array.

Our second function is mostly a repeat of the first, but it is invoked when you a editing a taxonomy term. Since we are editing our term, it’s possible that the metadata will already have values. So here we get our option out of the database and then look inside it for the array item that matches our key. Of course we escape our url properly with esc_url.

Saving our Fields

So we have our fields on the forms, but if we added data and tried to save it nothing would happen. We need to add 2 more actions to our __construct function.

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

Here the first one is fired when we save a category we are editing and the second fires when we are adding a new term. Just like our actions to add the fields if we wanted to save a taxonomy called region the hooks would be edited_region and create_region. Now the function that saves the metadata.

/**
 * 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'] ) ) {

        $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_$term_id", $term_meta );

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

We start here by making sure that our term_meta key exists in our $_POST data. Then we define an empty array that will hold all the data we want to save. Next we use a one line conditional conditional statement that says $term_meta['tax_image'] is equal to $_POST['term_meta']['tax_image'] if it has a value, if it doesn’t have a value then it’s equal to nothing.

Finally we save our metadata in a since option as an array. We tie it to our $term_id so that each term has a single entry for all it’s metadata.

Adding another metadata field

No what if you want to add another field of metadata, say a special link for the header. Well we’d simply copy the form fields and use the name/label of term_meta[link] and when we save we’d add 2 lines to the saving like this:

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

Then our database option would have 2 values in it’s array.

That’s it for now. Next time we’ll use our header image on the term archive page.

Full 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

    /**
     * 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();

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

Trackbacks and Pingbacks:

  1. Adding Custom Meta to WordPress Taxonomies : Post Status - February 21, 2013

    [...] Adding Custom Meta to WordPress Taxonomies » [...]

  2. Random Taxonomy Images - Part 2 - February 28, 2013

    [...] 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 [...]

  3. Random WordPress Taxonomy Images - Part 3 - March 7, 2013

    [...] Adding Custom Meta to WordPress Taxonomies [...]

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>