How can I add dropdown widget/box to admin post page?

Since this is very similar to post formats (see ) I would use a custom taxonomy.

That makes it easy to control the access level, and you get the meta box without writing extra code.

enter image description here

Then you insert the new post classes with a simple filter. Your theme must use the function post_class() – of course.

Example:

<?php # -*- coding: utf-8 -*-
/* Plugin Name: Post Class Taxonomy */

add_action( 'wp_loaded', 'register_post_class_taxonomy' );

function register_post_class_taxonomy()
{
    $caps = array(
        'manage_terms' => 'manage_options',
        'edit_terms'   => 'manage_options',
        'delete_terms' => 'manage_options',
        'assign_terms' => 'edit_others_posts',
    );

    $labels = array(
        'name'                       => 'Post Classes',
        'singular_name'              => 'Post Class',
        'search_items'               => 'Search Post Classes',
        'popular_items'              => 'Popular Post Classes',
        'all_items'                  => 'All Post Classes',
        'edit_item'                  => 'Edit Post Class',
        'view_item'                  => 'View Post Class',
        'update_item'                => 'Update Post Class',
        'add_new_item'               => 'Add New Post Class',
        'new_item_name'              => 'New Post Class',
        'separate_items_with_commas' => 'Separate Post Classes with commas',
        'add_or_remove_items'        => 'Add or remove Post Classes',
        'choose_from_most_used'      => 'Choose from the most used Post Classes',
    );
    $args = array (
        'rewrite'           => FALSE,
        'public'            => FALSE,
        'show_ui'           => TRUE,
        'labels'            => $labels,
        'capabilities'      => $caps,
        'show_in_nav_menus' => FALSE,
    );
    register_taxonomy( 'post_classes', 'post', $args );
}

add_filter( 'post_class', 'insert_custom_post_classes' );

function insert_custom_post_classes( $classes, $class="", $post_ID = NULL )
{
    NULL === $post_ID && $post_ID = get_the_ID();

    $post = get_post( $post_ID );

    if ( ! is_object_in_taxonomy( $post->post_type, 'post_classes' ) )
        return $classes;

    if ( ! $post_classes = get_the_terms( $post_ID, 'post_classes' ) )
        return $classes;

    foreach ( $post_classes as $post_class )
        if ( ! empty ( $post_class->slug ) )
            $classes[] = 'post-class-' . esc_attr( $post_class->slug );

    return $classes;
}

Leave a Comment