How to set homepage based on device with Wordpress? - wordpress

I need to set a default homepage based on the visitor device (mobile/desktop), I tried the following code in plugin, but did not work.
if ( wp_is_mobile() ) {
$homepage = get_page_by_title( 'mobile' );
}else{
$homepage = get_page_by_title( 'home1' );
}
if ( $homepage ){
update_option( 'page_on_front', $homepage->ID );
update_option( 'show_on_front', 'page' );
}
it keeps loading the home1, which is selected from theme options.
Thanks,

Your current functionality wouldn't work, even if it "worked". You're attempting to set a site-wide option in the database based on the most recent visitor's device.
Using update_option() isn't in your best interest here. What you should be doing is programmatically changing the template that's loaded at run-time based on the user's device, using the template_include filter - that way you're not storing a (semi) permanent change in your database, which would get constantly overwritten countless times by any user and affect all other users.
This would end up looking something like this:
add_filter( 'template_include', 'so_52745088_homepage_template', 99 );
function so_52745088_homepage_template( $template ){
// Only execute on the front page, not pages/posts/cpts
if( is_front_page() ){
// Determine if mobile
if( wp_is_mobile() ){
// Make sure mobile homepage template is found
if( $home_template = locate_template( array( 'homepage-mobile.php' ) ) ){
return $new_template;
}
}
}
return $template;
}
If you don't have a separate page template for mobile, and it's just a regular ol' separate page, then you can look at using wp_safe_redirect() on any number of hooks, a common one being template_redirect, which would end up looking like this:
add_action( 'template_redirect', 'so_52745088_homepage_redirect' );
function so_52745088_homepage_redirect( $template ){
// Only execute on the front page, not pages/posts/cpts
if( is_front_page() ){
// Determine if mobile
if( wp_is_mobile() ){
wp_safe_redirect( 'mobile' );
exit;
}
}
}

Related

Trying to load separate headers for home, page, post, and category - only category doesn't work

Since I have different Google Ad Manager codes that need to load in the of different content types, I created separate headers for each type and put this code snippet in index.php to load them accordingly:
if ( is_front_page() ) {
get_header('home') ;
}
elseif ( !is_front_page() AND is_page() ) {
get_header('page') ;
}
elseif ( is_single() ) {
get_header('article') ;
}
elseif ( is_category() ) {
get_header('category') ;
}
else {
get_header() ;
}
All of them work great - except for the category. It isn't loading. It just loads the default header.
What am I doing wrong?
Any help is much appreciated!
The short answer would be to try and use is_archive() instead of is_category(). If that doesn't work, you may need to dump your global $wp_query variable and see what query types are being returned on that particular url.
In that same vein, you may consider using is_singular() instead of is_single(), because is_single is limited to Posts.
One more point to consider is using && instead of AND (they're synonymous other than precedence. Take a look at this answer for a bit more in-depth on it)
Lastly, if you're only loading in a separate Google Ad Manager code, I'm not sure you need to maintain x number of header files. Have you considered dropping in the script codes into your functions.php file and loading them on the wp_enqueue_scripts or wp_head hooks?
instead of maintaining separate headers like this:
if( is_front_page() ){
get_header( 'home' );
} else if( is_page() ){
get_header( 'page' );
} else if( is_singular() ){
get_header( 'article' );
} else if( is_archive() ){
get_header( 'category' );
} else {
get_header();
}
You could drop those scripts straight in based on the same is_ functions using something like this:
add_action( 'wp_head', 'load_ad_manager_scripts' );
function load_ad_manager_scripts(){
if( is_front_page() ){
echo '<script>// Home Ad Manage Code</script>';
} else if( is_page() ){
echo '<script>// Page Ad Manage Code</script>';
} else if( is_singular() ){
echo '<script>// Single Manage Code</script>';
} else if( is_archive() ){
echo '<script>// Archive Manage Code</script>';
} else {
echo '<script>// Generic Manage Code</script>';
}
}

wordpress replace text before showing it to the browser

My website is built using Elementor using GeneratePress as default theme and I want to replace output final text with some values from the database. This plugin
Real-Time Find and Replace https://wordpress.org/plugins/real-time-find-and-replace/ is doing the replace functionality perfectly and it uses action:
//Handles find and replace for public pages
add_action( 'template_redirect', 'far_template_redirect' );
to replace text using code:
function far_ob_call( $buffer ) { // $buffer contains entire page
$far_settings = get_option( 'far_plugin_settings' );
if ( is_array( $far_settings['farfind'] ) ) {
foreach ( $far_settings['farfind'] as $key => $find ) {
if( isset( $far_settings['farregex'][$key] ) ) {
$buffer = preg_replace( $find, $far_settings['farreplace'][$key], $buffer );
} else {
$buffer = str_replace( $find, $far_settings['farreplace'][$key], $buffer );
}
}
}
return $buffer;
}
I can not use the plugin directly because it repalce text with text and I need to fetch data from database, so I have to make my own plugin. But, I found this blog: https://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/ that tells me to use a filter:
add_filter( 'template_include', 'my_callback' );
instead of the above action in plugin:
add_action( 'template_redirect', 'far_template_redirect' );
But the plugin is using the action.
What to use?
The plugin description says: "Set up find and replace rules that are executed AFTER a page is generated by WordPress, but BEFORE it is sent to a user's browser." this is what I exactly want. That is to replace text after page is generated and just before the page is sent to browser, but the plugin uses action for this, and other blogs suggest to use filter?

hide wordpress posts and categories for not logged in users

Basically I handled this issue by overriding parent theme files in child theme.
i.e., by using
if( is_user_logged_in() ){
...................
wordpress loop
}
I had to do this for every template ( wherever there is wordpress loop )
Though I didn't have to do this for displaying sidebars as if there was category in widget and whenever user clicks on it to view it, it would automatically say you don't have proper privileges to view this content.
So, my question is, is there any better way to hide wordpress content ( this may be anything, like normal posts, custom post types,.. ) from just visitors.
function bt_hide_from_guestes( $content ) {
global $post;
if ( $post->post_type == 'post' ) {
if ( !is_user_logged_in() ) {
$content = 'Please login to view this post';
}
}
return $content;
}
add_filter( 'the_content', 'bt_hide_from_guestes' );
Above code didn't help
It looks like your filter function should work for you. Try setting a priority and the "accepted arg" number:
add_filter( 'the_content', 'bt_hide_from_guestes', 10, 1 );

Wordpress redirect if URL parameter is empty for each post

So there are people who access my website directly (not thru the tracking link I got with Voluum), thus they are not able to click the links and I can't see them as a part of my stats.
How can I redirect users who don't have a /?voluumdata=BASE64... URL parameter to a tracked URL, and to have a different redirect for each blog post?
I was testing and looking for a plugin / .htaccess trick for hours but nothing seemed to help.
Edit: I found a solution that I was certain is going to work but for some reason it didn't:
[insert_php]
if(empty($_GET['voluumdata']))
{
header('Location: REDIRECT_URL');
exit;
}
[/insert_php]
Also tried:
[insert_php]
if(!isset($_GET['voluumdata']))
{
header('Location: REDIRECT_URL');
exit;
}
[/insert_php]
Both just break the page loading proccess.
Unfortunately, I cannot understand what is the purpose of the code you have entered in your question. I mean that is not clear the reason you use the tags [insert_php].
A solution to your problem it can be the following.
function redirect_direct_access( ) {
// You may use the code:
//
// global $wp_query
//
// in order to determine in which pages you should run your
// redirection code. If you only check for the token existence
// then you will be faced with redirection loop. I don't explain in
// depth how to use the $wp_query as it is not part of your question
// but you always have the opportunity to check what is the contents
// of this variable using the code:
//
// echo "<pre>";
// print_r( $wp_query );
// echo "</pre>";
//
// This way you will be able to build your specific if statement
// for the page you like to test.
if (
! isset( $_GET[ 'voluumdata' ] ) ||
empty( $_GET[ 'voluumdata' ] )
) {
wp_redirect( home_url( '/page/to/redirect/' ) );
exit();
}
}
add_action( 'template_redirect', 'redirect_direct_access' );
You can find more information in the WordPress documentation related to the template_redirect hook.
Just in case anyone would face the same issue, #Merianos Nikos has given a half-answer and I mastered it into this:
function redirect_direct_access( ) {
$post_id = get_the_ID();
if (
$post_id == POST_ID &&
!isset( $_GET[ 'voluumdata' ] )
) {
wp_redirect( 'REDIRECT_URL' );
exit();
}
if (
$post_id == POST_ID &&
!isset( $_GET[ 'voluumdata' ] )
) {
wp_redirect( 'REDIRECT_URL' );
exit();
}
}
add_action( 'template_redirect', 'redirect_direct_access' );

Wordpress hook to authenticate user for pre-defined URLs

I'm building a fairly complex project that has many frontend editing pages. For example, add/edit/list custom post types, edit profile, and so on, all from the frontend.
At the moment I can of course check if user is logged in on each frontend login-walled page. However, this seems like a bad way of solving this problem as I'll have the same conditional on many pages and thus lots of repeated code.
I was thinking perhaps there is a better way where I could authenticate based on some hook (that I can't finds). I hoped I could do something like:
# create array of URLs where login is required
$needLoginArr = array(url1, url2, url3, ...)
# If current requested URL is in above array, then redirect or show different view based on whether or not user is logged in
It might not be practical in future to have conditional on each page as I plan on integrating within different plugins, so would be useful to use URL to authenticate.
I'm probably missing something here so if there's a better way please let me know.
Thanks
You could add your list of page IDs into an option:
$need_login = array(
'page1',
'page1/subpage',
'page2',
// and so forth
);
$need_login_ids = array();
foreach( $need_login as $p ) {
$pg = get_page_by_path( $p );
$need_login_ids[] = $pg->ID;
}
update_option( 'xyz_need_login', $need_login_ids );
Then, to check if your page is in the $need_login group:
add_filter( 'the_content', 'so20221037_authenticate' );
function so20221037_authenticate( $content ) {
global $post;
$need_login_ids = get_option( 'xyz_need_login' );
if( is_array( $need_login_ids ) && in_array( $post->ID, $need_login_ids ) ) {
if( is_user_logged_in() ) {
// alter the content as needs
$content = 'Stuff for logged-in users' . $content;
}
}
return $content;
}
References
get_page_by_path()
is_user_logged_in()
update_option()
get_option()

Resources