Shamoon
Shamoon

Reputation: 43501

How can I add tags to a category in WordPress?

I want to be able to sort my category listings by different fields. I figure tags (or any arbitrary field) is a good way to do this. But I can't see how to add tags to a Category.

Ideas?

Upvotes: 0

Views: 243

Answers (1)

brasofilo
brasofilo

Reputation: 26065

From this WordPress StackExchange Q&A:

Add custom taxonomy fields when creating a new taxonomy

These are not tags, but custom fields being saved in wp_options table. And they are saved and retrieved using the category ID, e.g., get_option( "taxonomy_$t_id" ).
Check the full Q&A for other solutions. Revised code:

add_action( 'category_edit_form_fields', 'extra_edit_tax_fields_wpse_29322', 15, 2 );
add_action( 'category_add_form_fields', 'extra_add_tax_fields_wpse_29322', 10, 2 );
add_action( 'edited_category', 'save_extra_taxonomy_fields_wpse_29322', 10, 2 );
add_action( 'create_category', 'save_extra_taxonomy_fields_wpse_29322', 10, 2 );   

// Edit existing taxonomy
function extra_edit_tax_fields_wpse_29322( $tag ) 
{
    // Check for existing taxonomy meta for term ID.
    $t_id = $tag->term_id;
    $term_meta = get_option( "taxonomy_$t_id" ); 
    ?>
    <tr class="form-field">
    <th scope="row" valign="top">
        <label for="cat_Image_url"><?php _e( 'Category Navigation Image URL' ); ?></label>
    </th>
        <td>
            <input type="text" name="term_meta[img]" id="term_meta[img]" value="<?php echo esc_attr( $term_meta['img'] ) ? esc_attr( $term_meta['img'] ) : ''; ?>">
            <p class="description"><?php _e( 'Enter the full URL to the navigation image used for this category.' ); ?></p>
        </td>
    </tr>
    <?php
}

// Add taxonomy page
function extra_add_tax_fields_wpse_29322( $tag ) 
{
    ?>
    <div class="form-field">
        <label for="cat_Image_url"><?php _e( 'Category Navigation Image URL' ); ?></label>
        <input type="text" name="term_meta[img]" id="term_meta[img]" value="">
        <p class="description"><?php _e( 'Enter the full URL to the navigation image used for this category.' ); ?></p>
    </div>
    <?php
}

// Save extra taxonomy fields callback function.
function save_extra_taxonomy_fields_wpse_29322( $term_id ) 
{
    if ( isset( $_POST['term_meta'] ) ) 
    {
        $t_id = $term_id;
        $term_meta = get_option( "taxonomy_$t_id" );
        $cat_keys = array_keys( $_POST['term_meta'] );
        foreach ( $cat_keys as $key ) 
        {
            if ( isset ( $_POST['term_meta'][$key] ) )
                $term_meta[$key] = $_POST['term_meta'][$key];
        }
        // Save the option array.
        update_option( "taxonomy_$t_id", $term_meta );
    }
}   

Upvotes: 1

Related Questions