请注意,重定向必须在发送HTTP头之前发生。
您可以尝试以下方法,将我们的逻辑放在template_redirect
挂钩回调(PHP 5.4+):
/**
* Redirect logged-in users to the admin dashboard
* if the have written \'student_form\' posts
* else display [wpuf_form id="414"]
*/
add_action( \'template_redirect\', function()
{
if( ! is_user_logged_in() )
return;
if( wpse_current_user_has_posts( \'student_form\' ) )
{
// Redirect to the admin dashboard:
wp_safe_redirect( admin_url() ); // Edit to your needs!
exit();
}
else
{
// Note that here you might instead do a redirect to a page containing that shortcode.
get_header();
echo do_shortcode( \'[wpuf_form id="414"]\' );
get_footer();
exit();
}
} );
我们在何处使用此助手函数:
/**
* Check if the current user has written any posts in a given post type
*
* @param string $post_type
* @return bool
*/
function wpse_current_user_has_posts( $post_type = \'post\' )
{
$posts = [];
if( $uid = get_current_user_id() )
{
$posts = get_posts(
[
\'posts_per_page\' => 1,
\'post_type\' => sanitize_key( $post_type ),
\'author\' => $uid,
\'fields\' => \'ids\'
]
);
}
return 0 < count( $posts );
}