在自定义帖子类型中设置页面模板数组

时间:2012-06-13 作者:Rob Myrick

下面是一个“案例”(在自定义帖子类型中),用于拉取所有类别并将其显示为下拉菜单。我怎样才能做同样的事情,但把它变成一个复选框列表?

    //tax_select - this lists all of the categories in a drop-down, we want to change to a checkbox
case \'tax_select\':
echo \'<select name="\'.$field[\'id\'].\'" id="\'.$field[\'id\'].\'">
        //<option value="">Select One</option>\'; // Select One
$terms = get_terms($field[\'id\'], \'get=all\');
$selected = wp_get_object_terms($post->ID, $field[\'id\']);
foreach ($terms as $term) {
    if (!empty($selected) && !strcmp($term->slug, $selected[0]->slug))
        echo \'<option value="\'.$term->slug.\'" selected="selected">\'.$term->name.\'</option>\';
    else
        echo \'<option value="\'.$term->slug.\'">\'.$term->name.\'</option>\';
}
$taxonomy = get_taxonomy($field[\'id\']);
echo \'</select><br /><span class="description"><a href="\'.get_bloginfo(\'home\').\'/wp-admin/edit-tags.php?taxonomy=\'.$field[\'id\'].\'">Manage \'.$taxonomy->label.\'</a></span>\';
break;
如何保存数据:

    // Save the Data
function save_custom_meta($post_id) {
global $custom_meta_fields;

// verify nonce
if (!wp_verify_nonce($_POST[\'custom_meta_box_nonce\'], basename(__FILE__)))
    return $post_id;
// check autosave
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE)
    return $post_id;
// check permissions
if (\'page\' == $_POST[\'post_type\']) {
    if (!current_user_can(\'edit_page\', $post_id))
        return $post_id;
    } elseif (!current_user_can(\'edit_post\', $post_id)) {
        return $post_id;
}

// loop through fields and save the data
foreach ($custom_meta_fields as $field) {
            if($field[\'type\'] == \'tax_select\') continue;
    $old = get_post_meta($post_id, $field[\'id\'], true);
    $new = $_POST[$field[\'id\']];
    if ($new && $new != $old) {
        update_post_meta($post_id, $field[\'id\'], $new);
    } elseif (\'\' == $new && $old) {
        delete_post_meta($post_id, $field[\'id\'], $old);
    }
} // end foreach

    // save taxonomies
$post = get_post($post_id);
$category = $_POST[\'category\'];
wp_set_object_terms( $post_id, $category, \'category\' );
}
add_action(\'save_post\', \'save_custom_meta\');  

1 个回复
最合适的回答,由SO网友:Eugene Manuilov 整理而成
//tax_select - this lists all of the categories in a drop-down, we want to change to a checkbox
case \'tax_select\':
    $terms = get_terms( $field[\'id\'], \'get=all\' );
    $selected = wp_get_object_terms( $post->ID, $field[\'id\'] );
    foreach ( $terms as $term ) {
        printf( \'<input type="checkbox" name="%s[]" value="%s" %s/><br />\', $field[\'id\'], $term->slug, !empty( $selected ) && !strcmp( $term->slug, $selected[0]->slug ) ? \' checked="checked"\' : \'\' );
    }
    $taxonomy = get_taxonomy( $field[\'id\'] );
    echo \'<span class="description"><a href="\' . get_bloginfo( \'home\' ) . \'/wp-admin/edit-tags.php?taxonomy=\' . $field[\'id\'] . \'">Manage \' . $taxonomy->label . \'</a></span>\';
break;
结束