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


Require authors to set featured image for post

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

这怎么可能?

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

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 ))以确定帖子是否具有特色图像。

以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' );

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

您可以使用插件

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

或者,您可以在wordpress主题函数.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
    }
} );