要求作者为帖子设置特色图片

时间:2012-09-13 16:03:31

标签: php image wordpress function featured

我已经定制了我的Wordpress网站设计,以便过度使用特色图片。这就是为什么我需要要求非管理员发布的所有帖子都需要设置特色图片。

这怎么可能?

3 个答案:

答案 0 :(得分:6)

您需要在自己编写的自定义插件中挂钩发布操作。虽然这需要一个标题,但这应该让你开始,你只需要检查是否已经分配了特色图像。

add_action( 'pre_post_update', 'bawdp_dont_publish' );

function bawdp_dont_publish()
{
    global $post;
    if ( strlen( $post->title ) < 10 ) {
        wp_die( 'The title of your post have to be 10 or more !' );
    }
}

查看(has_post_thumbnail( $post->ID ))以确定帖子是否包含精选图片。

答案 1 :(得分:5)

鉴于Gary的上述例子,我已将以下内容写入我的functions.php文件:

function featured_image_requirement() {
     if(!has_post_thumbnail()) {
          wp_die( 'You forgot to set the featured image. Click the back button on your browser and set it.' ); 
     } 
}
add_action( 'pre_post_update', 'featured_image_requirement' );

我更喜欢在插件中看到这个 - 有一个名为强制字段,但它不适用于预定的帖子。两者都不是真正雄辩的解决方案。

答案 2 :(得分:2)

你可以使用插件

https://wordpress.org/plugins/require-featured-image/

或者您可以在wordpress主题functions.php文件中复制并粘贴以下代码:

<?php
/**
 * Require a featured image to be set before a post can be published.
 */
add_filter( 'wp_insert_post_data', function ( $data, $postarr ) {
    $post_id              = $postarr['ID'];
    $post_status          = $data['post_status'];
    $original_post_status = $postarr['original_post_status'];
    if ( $post_id && 'publish' === $post_status && 'publish' !== $original_post_status ) {
        $post_type = get_post_type( $post_id );
        if ( post_type_supports( $post_type, 'thumbnail' ) && ! has_post_thumbnail( $post_id ) ) {
            $data['post_status'] = 'draft';
        }
    }
    return $data;
}, 10, 2 );
add_action( 'admin_notices', function () {
    $post = get_post();
    if ( 'publish' !== get_post_status( $post->ID ) && ! has_post_thumbnail( $post->ID ) ) { ?>
        <div id="message" class="error">
            <p>
                <strong><?php _e( 'Please set a Featured Image. This post cannot be published without one.' ); ?></strong>
            </p>
        </div>
    <?php
    }
} );
相关问题