WordPress发布文章前强制要求上传特色图像

如果你的网站需要给每篇文章设置特色图像才能达到理想的显示效果,而且允许其他用户在后台发布文章的,那么您可能需要强制要求他们给文章上传特色图像,否者就无法发布。Require Featured Image 就可以实现这个功能,如果没有上传特色图像,发布按钮就无法点击。

 

 

将代码添加到主题的 functions.php 即可:

/**
 * WordPress发布文章前强制要求上传特色图像
 * http://www.wpdaxue.com/require-featured-image.html
 */
add_action('save_post', 'pu_validate_thumbnail');
function pu_validate_thumbnail($post_id)
{
    // 只验证文章(post)
    if(get_post_type($post_id) != 'post')
        return;
    // 检查是否有缩略图
    if ( !has_post_thumbnail( $post_id ) ) {
        // 确认验证缩略图失败,设置临时状态(transient)
        set_transient( "pu_validate_thumbnail_failed", "true" );
        // 移除save_post钩子,以便保存文章且重新链接文章
        remove_action('save_post', 'pu_validate_thumbnail');
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
        add_action('save_post', 'pu_validate_thumbnail');
    } else {
        // 如果文章有缩略图,删除临时状态(transient)
        delete_transient( "pu_validate_thumbnail_failed" );
    }
}
add_action('admin_notices', 'pu_validate_thumbnail_error');
function pu_validate_thumbnail_error()
{
    // 检查是否设置了临时状态(transient),如果是,显示提示信息
    if ( get_transient( "pu_validate_thumbnail_failed" ) == "true" ) {
        echo "<div id='message' class='error'><p><strong>发布文章前,您必须设置一个特色图像</strong></p></div>";
        delete_transient( "pu_validate_thumbnail_failed" );
    }
}

 

posted on 2014-01-16 17:43  ※WYF※  阅读(646)  评论(0编辑  收藏  举报