是否在设置特色图片之前阻止发布帖子?

时间:2011-05-04 作者:BIALY

正如标题所说,我想要一个插件/函数,当用户试图在不设置特色图片的情况下发布帖子时,阻止/通知用户。

有什么帮助吗???

2 个回复
SO网友:Tiago Vergutz

这个has_post_thumbnail() 适用于我,在WP版本3.4.1和其他最新版本中。但按照这种逻辑,因为WP将发布帖子,即使exitwp_die() 或任何终止PHP脚本的操作。为了防止帖子保持已发布状态,您需要在终止之前更新帖子。查看以下代码:

add_action(\'save_post\', \'prevent_post_publishing\', -1);
function prevent_post_publishing($post_id)
{
    $post = get_post($post_id);

    // You also add a post type verification here,
    // like $post->post_type == \'your_custom_post_type\'
    if($post->post_status == \'publish\' && !has_post_thumbnail($post_id)) {
        $post->post_status = \'draft\';
        wp_update_post($post);

        $message = \'<p>Please, add a thumbnail!</p>\'
                 . \'<p><a href="\' . admin_url(\'post.php?post=\' . $post_id . \'&action=edit\') . \'">Go back and edit the post</a></p>\';
        wp_die($message, \'Error - Missing thumbnail!\');
    }               
}

SO网友:kaiser
<?php
// Something like that should help, but you\'ll have to play with it to get it working:
// inside your functions.php file
function wpse16372_prevent_publish()
{
    if ( ! is_admin() )
        return;

    // This should be ok, but should be tested:
    $post_id = $GLOBALS[\'post\']->ID;
    echo \'<pre>Test for post ID: \'; print_r( $post_id ); echo \'</pre>\';// the actual test

    // has_post_thumbnail() doesn\'t work/exist on/for admin screens (see your error msg). You need to find another way to test if the post has a thumbnail. Maybe some Javascript?
    //if ( ! has_post_thumbnail( $post_id );
    if ( ! has_post_thumbnail( $post_id ) )
    {
        ?>
        <!-- // 
        <script language="javascript" type="text/javascript">
            alert( \'you have to use a featured image\' );
        </script>
        // -->
        <?php
        exit; // abort
    }
}
add_action( \'save_post\', \'wpse16372_prevent_publish\', 100 );
?>
结束