Smart App Download Link
Turns an address such as /app/ into one link for posters and QR codes: iPhone visitors go to the App Store, Android visitors to Google Play and everyone else to a page you choose.
Opens WPIDE on
Code
// The short address to share, for example on posters, QR codes and email signatures.
$wpide_app_link_path = '/app/';
// Store pages of your app. Leave a value empty to skip that platform.
$wpide_app_link_ios = ''; // e.g. https://apps.apple.com/app/id0000000000
$wpide_app_link_android = ''; // e.g. https://play.google.com/store/apps/details?id=com.example.app
// Where everyone else goes (desktop browsers); empty = let WordPress show the page at that address.
$wpide_app_link_other = '';
add_action( 'template_redirect', function () use ( $wpide_app_link_path, $wpide_app_link_ios, $wpide_app_link_android, $wpide_app_link_other ) {
if ( '' === $wpide_app_link_ios && '' === $wpide_app_link_android ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
$want = (string) wp_parse_url( home_url( $wpide_app_link_path ), PHP_URL_PATH );
if ( '' === $path || strtolower( untrailingslashit( $path ) ) !== strtolower( untrailingslashit( $want ) ) ) {
return;
}
$agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
$target = $wpide_app_link_other;
if ( preg_match( '/iPhone|iPad|iPod/i', $agent ) && '' !== $wpide_app_link_ios ) {
$target = $wpide_app_link_ios;
} elseif ( false !== stripos( $agent, 'Android' ) && '' !== $wpide_app_link_android ) {
$target = $wpide_app_link_android;
}
if ( '' === $target ) {
return;
}
nocache_headers();
header( 'Vary: User-Agent', false );
wp_redirect( esc_url_raw( $target ), 302 ); // phpcs:ignore WordPress.Security.SafeRedirect -- store links set by the site owner.
exit;
}, 1 );
Notes
Off until you add your store links; without a desktop address, desktop visitors see the page at that address, if any.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.