如果用户没有撰写帖子,此代码将引导其退出。在本示例中,状态为的帖子publish
被视为“作者”。
我在代码中添加了一些注释,以引导您了解正在发生的事情-如果您有任何问题,请联系我。
<?php
// Ensure non-published users can\'t see what\'s going on.
add_action( \'init\', function() {
// Don\'t run in the admin area.
if ( is_admin() ) {
return;
}
// Only display this on "single" pages.
if ( ! is_single() ) {
return;
}
$user_id = get_current_user_id();
// The user isn\'t a user, bail.
if ( ! $user_id ) {
return;
}
$query = <<<SQL
SELECT
COUNT(*) published
FROM
{$GLOBALS[\'wpdb\']->posts}
WHERE
post_author = %d
AND
post_type = %s
AND
post_status = \'publish\'
SQL;
$result = $GLOBALS[\'wpdb\']->get_results(
$GLOBALS[\'wpdb\']->prepare(
$query,
$user_id,
\'post\' // Replace this with your Custom Post Type, if you\'re not using Post.
)
);
// The current user has author posts, bail.
if ( ! empty( $result ) ) {
return;
}
// Handle code to kick people out.
wp_safe_redirect( \'/error-page/\' );
exit;
} );