問題描述

創建新帖子之前,如何強制用户先繼續編輯之前先選擇一個類別?我想要 set some default content,但是這是基於類別,所以我需要知道,在顯示編輯器之前 (除非我做了一些奇怪的 Ajax 的東西,但在這種情況下我不想這樣做) 。

最佳解決方案

我通過掛接到 post-new.php 並檢查 category_id 請求參數來解決這個問題。如果不存在,我會顯示一個帶有類別下拉列表的表單,提交給該頁面,然後調用 exit(),以便不顯示常規的表單。如果存在,我將為 wp_insert_post 設置一個鈎子,將添加該類別。這是因為通過 get_default_post_to_edit()函數在數據庫中創建了一個新帖子,我們可以添加類別,標籤或其他 (元) 內容。此後,使用”fresh” 新內容生成表單。

add_filter( 'load-post-new.php', 'wpse14403_load_post_new' );
function wpse14403_load_post_new()
{
    $post_type = 'post';
    if ( isset( $_REQUEST['post_type'] ) ) {
        $post_type = $_REQUEST['post_type'];
    }

    // Only do this for posts
    if ( 'post' != $post_type ) {
        return;
    }

    if ( array_key_exists( 'category_id', $_REQUEST ) ) {
        add_action( 'wp_insert_post', 'wpse14403_wp_insert_post' );
        return;
    }

    // Show intermediate screen
    extract( $GLOBALS );
    $post_type_object = get_post_type_object( $post_type );
    $title = $post_type_object->labels->add_new_item;

    include( ABSPATH . 'wp-admin/admin-header.php' );

    $dropdown = wp_dropdown_categories( array(
        'name' => 'category_id[]',
        'hide_empty' => false,
        'echo' => false,
    ) );

    $category_label = __( 'Category:' );
    $continue_label = __( 'Continue' );
    echo <<<HTML
<div class="wrap">
    <h2>{$title}</h2>

    <form method="get">
        <table class="form-table">
            <tbody>
                <tr valign="top">
                    <th scope="row">{$category_label}</th>
                    <td>{$dropdown}</td>
                </tr>
                <tr>
                    <td></td>
                    <th><input name="continue" type="submit" class="button-primary" value="{$continue_label}" /></th>
            </tbody>
        </table>
        <input type="hidden" name="post_type" value="{$post_type}" />
    </form>
</div>
HTML;
    include( ABSPATH . 'wp-admin/admin-footer.php' );
    exit();
}

// This function will only be called when creating an empty post,
// via `get_default_post_to_edit()`, called in post-new.php
function wpse14403_wp_insert_post( $post_id )
{
    wp_set_post_categories( $post_id, $_REQUEST['category_id'] );
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。