Skip to content

Instantly share code, notes, and snippets.

@froger-me
Last active April 11, 2022 02:53
Show Gist options
  • Save froger-me/3734ca6862aef5cd2ebd2d7972e0c4f8 to your computer and use it in GitHub Desktop.
Save froger-me/3734ca6862aef5cd2ebd2d7972e0c4f8 to your computer and use it in GitHub Desktop.
WP Weixin - Force users to be followers even if they are not using the WeChat built-in browser.
<?php
// Place this code in your child theme's functions.php or in one of your custom plugins
// Adds an action before displaying a page
add_action( 'template_redirect', 'wp_weixin_force_follow_all_browsers', 0, 0 );
// The action executed before displaying a page
function wp_weixin_force_follow_all_browsers() {
// change `home_url( '/' )` with the URL of an existing page with your Official Account QR code of your choice,
// or add a WordPress filter "wp_weixin_force_follow_all_browsers_url" of your own to change the destination
$page_url = apply_filters( 'wp_weixin_force_follow_all_browsers_url', home_url( '/' ) );
// get the current URL
if (
isset( $_SERVER['HTTPS'] ) &&
( 'on' === $_SERVER['HTTPS'] || 1 === intval( $_SERVER['HTTPS'] ) ) ||
isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
'https' === $_SERVER['HTTP_X_FORWARDED_PROTO']
) {
$protocol = 'https://';
} else {
$protocol = 'http://';
}
$current_url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
if ( ! empty( $_SERVER['QUERY_STRING'] ) ) {
$current_url .= '?' . $_SERVER['QUERY_STRING'];
}
// get the current user
$user = wp_get_current_user();
if (
// check the page is NOT the page with your Official Account QR code
$current_url !== $page_url &&
// check WP Weixin is activated
function_exists( 'wp_weixin_is_wechat' ) &&
// check we're not in the admin backend
! is_admin() &&
(
// check:
// - if the user is not logged in OR
// - if the browser is not wechat built-in AND
// - the current user is not a follower
! is_user_logged_in() ||
(
! wp_weixin_is_wechat() &&
! wp_weixin_is_follower( $user->ID )
)
)
) {
// redirect to the page with your Official Account QR code
wp_safe_redirect( $page_url );
// stop execution, we're done!
exit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment