简体   繁体   English

如何设置Wordpress中任何特定自定义帖子类型允许的最大帖子数

[英]How to set maximum number of posts allowed for any specific custom post type in Wordpress

I have an image slider on my Wordpress home page, I have created one simple custom post type home_image_slider which only has 2 fields ie. 我的Wordpress主页上有一个图像滑块,我创建了一个简单的自定义帖子类型home_image_slider,它只有2个字段即。 image url & image title. 图片网址和图片标题。

Now as I only want to show maximum 5 images on my home slider I want a simple solution using which I can limit Admin from adding more than 5 images or you can say 5 post to this custom post type (as I need to show only 5 images on slider it does not make sense to allow admin to add more than 5 posts). 现在因为我只想在我家滑块上显示最多5张图像,我想要一个简单的解决方案,我可以限制管理员添加超过5张图片,或者你可以说5张帖子到这个自定义帖子类型(因为我只需要显示5滑块上的图像允许管理员添加超过5个帖子没有意义)。

We can check this at the very beginning of /wp-admin/post-new.php : 我们可以在/wp-admin/post-new.php的最开头检查这个:

add_action('load-post-new.php', 'limit_cpt_so_23862828' );

function limit_cpt_so_23862828()
{
    global $typenow;

    # Not our post type, bail out
    if( 'home_image_slider' !== $typenow )
        return;

    # Grab all our CPT, adjust the status as needed
    $total = get_posts( array( 
        'post_type' => 'home_image_slider', 
        'numberposts' => -1, 
        'post_status' => 'publish,future,draft' 
    ));

    # Condition match, block new post
    if( $total && count( $total ) >= 5 )
        wp_die(
            'Sorry, maximum number of posts reached', 
            'Maximum reached',  
            array( 
                'response' => 500, 
                'back_link' => true 
            )
        );  
}

Maybe you can allow draft posts and make sure you're only pulling 5 slides in the frontend setting 'numberposts' => 5 in your WP_Query or get_posts . 也许你可以允许草稿帖子,并确保你只在你的WP_Queryget_posts中的前端设置'numberposts' => 5中拉5张幻灯片。

Actually It doesn't make sense to limit custom post type and normally they don't do it. 实际上限制自定义帖子类型是没有意义的,通常他们不这样做。 Whatever If you like to limit slider post to 5, using theme option page might be better approach. 无论如何您想将滑块限制为5,使用主题选项页面可能是更好的方法。 You can either try manually or use appropriate theme options frameworks like 您可以手动尝试或使用适当的主题选项框架

Options framework 选项框架

Official Documentation 官方文件

ThemeForest Discussion ThemeForest讨论

Option Tree 选项树

Redux 终极版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM