【问题标题】:making your posts password-protected by default使您的帖子默认受密码保护
【发布时间】:2012-03-07 08:31:15
【问题描述】:

我原本希望能够用密码保护一个类别。至少我希望它受密码保护,但最好是用户名和密码登录。由于我几天来一直未能找到解决方案,因此我现在求助于使用 WordPress 的内置密码保护来保护帖子。

我遇到的问题是我将通过电子邮件发帖,为了让这些帖子受密码保护,我需要登录到 Wordpress,然后手动选择受密码保护并在仪表板中输入密码。

我希望能够让出现在特定类别中的所有帖子在默认情况下使用相同的密码进行密码保护。无需登录 Wordpress 并手动选择密码保护。

我知道我需要使用一个函数<?php post_password_required( $post ); ?>,但我不知道如何实现它或在哪里实现它。

【问题讨论】:

    标签: wordpress function passwords categories


    【解决方案1】:
        add_filter( 'wp_insert_post_data', function( $data, $postarr ){
        if ( 'book' == $data['post_type'] && 'auto-draft' == $data['post_status'] ) {
            $data['post_password'] = wp_generate_password();
        }
        return $data;
    }, '99', 2 );
    

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些即时帮助。正确的解释将greatly improve 其教育价值通过说明为什么这是解决问题的好方法,并使其对未来有类似但不相同的问题的读者更有用。请编辑您的答案以添加解释,并说明适用的限制和假设。
    【解决方案2】:

    基于this WordPress StackExchange answer。仅使用常规仪表板进行测试。通过电子邮件发布必须经过测试,但我想在这种发布中会调用钩子。

    add_action( 'save_post', 'wpse51363_save_post' );
    
    function wpse51363_save_post( $post_id ) {
    
        //Check it's not an auto save routine
         if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
              return;
    
        //Check it's not an auto save routine
         if ( wp_is_post_revision( $post_id ) ) 
              return;
    
        //Perform permission checks! For example:
        if ( !current_user_can( 'edit_post', $post_id ) ) 
              return;
    
        $term_list = wp_get_post_terms(
            $post_id, 
            'category', 
            array( 'fields' => 'slugs' ) 
        );
    
        if( in_array ( 'the-category-slug', $term_list ) )
        {
            // Unhook this function so it doesn't loop infinitely
            remove_action( 'save_post', 'wpse51363_save_post' );
    
            // Call wp_update_post update, which calls save_post again. 
            wp_update_post( array( 
                'ID' => $post_id,
                'post_password' => 'default-password' ) 
            );
    
            // Re-hook this function
            add_action( 'save_post', 'wpse51363_save_post' );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 2011-11-15
      • 2011-12-23
      • 2014-10-07
      • 2010-09-27
      • 2013-11-16
      相关资源
      最近更新 更多