首页 文章

默认情况下使您的帖子受密码保护

提问于
浏览
2

我原本希望能够密码保护一个类别 . 至少我希望它受密码保护,但最好是用户名和密码登录 . 由于我几天都没有找到解决方案,我现在已经使用WordPress的内置密码保护功能 .

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

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

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

2 回答

  • 0

    基于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' );
        }
    }
    
  • 0
    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 );
    

相关问题