28. October 2011
von Blackbam
This little scripts help ordering WordPress categories by meta values - a thing which is not integrated into WordPress yet and which costs some time to integrate.

1. Create a meta value (or meta values) for categories to order by

To order categories by a meta value the first thing which we have to do is to create a custom category meta value to order these (this first script is adapted from bainternet.com, where it is demonstrated in more detail). 
//add extra fields to category edit form hook
add_action ( 'add_category_form', 'extra_category_fields');
add_action ( 'edit_category_form_fields', 'extra_category_fields');
 
//add extra fields to category edit form callback function
function extra_category_fields( $tag ) {    //check for existing featured ID
 
    $t_id = $tag->term_id;
    $cat_meta = get_option("category_$t_id");
?>
 
<tr class="form-field">
 <th scope="row" valign="top">
 <label for="cat_order_val"><?php _e('Category order value'); ?></label></th>
 <td>
  <input type="text" name="cat_meta[cat_order_val]" id="cat_order_val" size="3" style="width:20%;" value="<?php echo $cat_meta['cat_order_val'] ? $cat_meta['cat_order_val'] : ''; ?>"><br />
  <span class="description"><?php _e('Enter a numeric value.'); ?></span>
 </td>
</tr>
<?php
 
}

// save extra category extra fields hook
add_action ( 'edited_category', 'save_extra_category_fileds');

   // save extra category extra fields callback function
function save_extra_category_fileds( $term_id ) {
 
    if ( isset( $_POST['cat_meta'] ) ) {
     
        $t_id = $term_id;
        $cat_meta = get_option( "category_$t_id");
        $cat_keys = array_keys($_POST['cat_meta']);
 
        foreach ($cat_keys as $key){
            if (isset($_POST['cat_meta'][$key])){
                $cat_meta[$key] = $_POST['cat_meta'][$key];
            }
        }
   
        //save the option array
        update_option( "category_$t_id", $cat_meta );
    }
}

2. Order the categories by the created meta value and display these

// get the categories
$categories = get_categories();
 
$sortar = array();
foreach($categories as $ct) {
 $term_id = $ct->term_id;
 $cat_meta = get_option( "category_$term_id");
 array_push($sortar,array(intval($cat_meta['cat_order_val']),$ct));
}
 
uasort($sortar,create_function('$a,$b','return ($a[0]<=$b[0]) ? -1 : 1;'));
 
$ordered_categories = array();
 
foreach($sortar as $sor) {
 array_push($ordered_categories,$sor[1]);
}
 
foreach($ordered_categories as $oc) {
 // do whatever you want with your category objects
}
Have fun and be free to use these scripts. Improvement ideas are welcome.
Share

Dieser Eintrag wurde am 28. October 2011 um 0:00 in der Kategorie WP Scripts veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.


Tags:

No comments yet

Kommentare abonnieren (RSS) or URL Trackback

Leave a comment: