如果没有检查类别,如何在帖子标题的顶部显示错误消息?

时间:2016-11-11 05:05:47

标签: wordpress post

如果在添加新帖子时未选择任何类别,我想显示错误消息吗?

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以通过jquery检查:

/* Checks if cat is selected when publish button is clicked */
jQuery( '#submitdiv' ).on( 'click', '#publish', function( e ) {
    var $checked = jQuery( '#category-all li input:checked' );

    //Checks if cat is selected
    if( $checked.length <= 0 ) {
        alert( "Please Select atleast one category" );
        return false;
    } else { 
        return true;
    }
} );

并输出您想要的错误信息。

答案 1 :(得分:0)

您可以使用admin_notices挂钩来完成此操作。只需在functions.php文件中添加以下代码:

function wp_823232_admin_notice__no_category_error()
{

    ?>
    <div class="notice notice-error is-dismissible">
        <p><?php _e('Warning: No category is selected for this post!', 'sample-text-domain'); ?></p>
    </div>
    <?php
}


function wp_823232_check_category()
{

    global $pagenow;
    global $post;

    if ($pagenow == 'post-new.php' || $pagenow == 'post.php') {
        if (count(get_categories($post->ID)) == 1 && has_category("uncategorized", $post->ID)) {
            add_action('admin_notices', 'wp_823232_admin_notice__no_category_error');
        }

    }


}

add_action('in_admin_header', 'wp_823232_check_category');