WordPress 限定用戶更新或刪除文章的時間期限

對於一個開放註冊的多用戶WordPress站點,默認情況下,有文章編輯權限的用戶是可以更新和刪除自己的文章的,如果我們要限制用戶隻在文章發佈後的指定的時間段(比如30天)內才可以更新和刪除文章,該如何實現呢?

block-wordpress-post-updates-and-deletion-wpdaxue

將下面的代碼添加到當前主題的 functions.php 文件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function wpbeginner_restrict_editing( $allcaps, $cap, $args ) {
 
    // Bail out if we're not asking to edit or delete a post ...
    if( 'edit_post' != $args[0] && 'delete_post' != $args[0]
      // ... or user is admin
      || !empty( $allcaps['manage_options'] )
      // ... or user already cannot edit the post
      || empty( $allcaps['edit_posts'] ) )
        return $allcaps;
 
    // Load the post data:
    $post = get_post( $args[2] );
 
    // Bail out if the post isn't published:
    if( 'publish' != $post->post_status )
        return $allcaps;
 
    //如果文章超過30天。請根據自己的需要修改
    if( strtotime( $post->post_date ) < strtotime( '-30 day' ) ) {
        //Then disallow editing.
        $allcaps[$cap[0]] = FALSE;
    }
    return $allcaps;
}
add_filter( 'user_has_cap', 'wpbeginner_restrict_editing', 10, 3 );

function wpbeginner_restrict_editing( $allcaps, $cap, $args ) { // Bail out if we’re not asking to edit or delete a post …
if( ‘edit_post’ != $args[0] && ‘delete_post’ != $args[0]
// … or user is admin
|| !empty( $allcaps[‘manage_options’] )
// … or user already cannot edit the post
|| empty( $allcaps[‘edit_posts’] ) )
return $allcaps; // Load the post data:
$post = get_post( $args[2] ); // Bail out if the post isn’t published:
if( ‘publish’ != $post->post_status )
return $allcaps; //如果文章超過30天。請根據自己的需要修改
if( strtotime( $post->post_date ) < strtotime( ‘-30 day’ ) ) {
//Then disallow editing.
$allcaps[$cap[0]] = FALSE;
}
return $allcaps;
}
add_filter( ‘user_has_cap’, ‘wpbeginner_restrict_editing’, 10, 3 );

上面的函數會檢測用戶是否有編輯和刪除文章的能力,之後檢測文章的發佈狀態,30天內,用戶還可以編輯或刪除該文章,如果超過30天,用戶就沒辦法再更新或刪除這篇文章(超級管理員還是可以編輯或刪除所有文章的)。

參考資料:http://www.wpbeginner.com/wp-tutorials/how-to-block-wordpress-post-updates-and-deletion-after-a-set-period/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *