Deactivate WordPress Plugin if URL is - php

I have installed SMS Validator so everyone who register to my site must enter there phone number to sign-up
Now I have created a new function (link) to add a different type user role if users sign-up by visit this link:
http://example.com/wp-login.php?action=register&role=vip_member
I want to turn OFF SMS Validator ONLY for this URL link.
Is it possible to do it somehow?
Success so far using mathielo code:
// Activate SMSGlobal
function activate_plugin_conditional() {
if ( !is_plugin_active('sms-validator-SMSG/sms-validator.php') ) {
activate_plugins('sms-validator-SMSG/sms-validator.php');
}
}
// Deactivate SMSGlobal
function deactivate_plugin_conditional() {
if ( is_plugin_active('sms-validator-SMSG/sms-validator.php') ) {
deactivate_plugins('sms-validator-SMSG/sms-validator.php');
}
}
// Now you in fact deactivate the plugin if the current URL matches your desired URL
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=vip_member') !== FALSE){
// Calls the disable function at WP's init
add_action( 'init', 'deactivate_plugin_conditional' );
}
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=seller') !== FALSE){
// Calls the enable function at WP's init
add_action( 'init', 'activate_plugin_conditional' );
}
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=provider') !== FALSE){
// Calls the enable function at WP's init
add_action( 'init', 'activate_plugin_conditional' );
}
So far this code helps me to activate and deactivate this plugin in this 3 selected URLs.
But I want this plugin to be activated if is deactivated in this links: /wp-login.php and /wp-login.php?action=register
But if I set it to activate on URL: /wp-login.php then it will not be deactivated on URL: /wp-login.php?action=register&role=vip_member where I need it to be deactivated.

You could match the current URL using $_SERVER["REQUEST_URI"] and then disable the plugin in functions.php:
// Just creating the function that will deactivate the plugin
function deactivate_plugin_conditional() {
if ( is_plugin_active('plugin-folder/plugin-name.php') ) {
deactivate_plugins('plugin-folder/plugin-name.php');
}
}
// Now you in fact deactivate the plugin if the current URL matches your desired URL
if(strpos($_SERVER["REQUEST_URI"], 'my-disable-url') !== FALSE){
// Calls the disable function at WP's init
add_action( 'init', 'deactivate_plugin_conditional' );
}
Note: Be aware that php's strpos() may return 0 if the needle matches the given string at position zero, so the condiional !== is needed.
Got my references from here and implemented the URL check. Check out the current value of $_SERVER["REQUEST_URI"] at your desired URL for a perfect match.
Answering the second part of your question:
You could improve your code removing the last 2 ifs and complementing the first one with an else, like so:
// Now you in fact deactivate the plugin if the current URL matches your desired URL
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=vip_member') !== FALSE){
// Calls the disable function at WP's init
add_action( 'init', 'deactivate_plugin_conditional' );
}
// Otherwise, for any other URLs the plugin is activated if it's currently disabled.
else{
add_action( 'init', 'activate_plugin_conditional' );
}
Now for every URL that is not the one you wish to deactivate the plugin, your code will enable the plugin if it is currently inactive.

Related

Prevent direct access to a page in WordPress

I need some help. I am trying to prevent direct access to a page that my customers get redirected to after checkout. I want the page to be accessible only after checkout.
I have found this topic: https://wordpress.stackexchange.com/questions/290234/prevent-block-direct-access-to-a-thank-you-page
I placed the following code snippet to my functions.php:
add_action('template_redirect', function() {
// ID of the redirect page
if (!is_page(2072)) {
return;
}
// URL of checkout page
if (wp_get_referer() === 'https://www.exampledomain.com/checkout/') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
} );
This works fine if the customer pays through Stripe. However, it does not work if the customer chooses to pay through PayPal because PayPal redirects the customer to their website to make the payment.
Can something be done here to fix this issue?
You could do it the other way around. Only accept an array of predefined urls. For example here we have defined an array with github and stackoverflow as referees. If the referring url isn't one of those two, then we kill the process. With wp_die() we can display a custom message and a backlink, and with header() we can redirect automatically after 3 seconds.
add_action( 'wp', function() {
if( is_page( '3975' ) && ! is_admin() ) { // restrict page ID '2072' if it's on the front end and if user doesn't have the permissions
$base = [ // allowed referees
'https://github.com/', // referee 1
'https://stackoverflow.com/', // referee 1 ... and so on
];
if( ! in_array( $_SERVER['HTTP_REFERER'], $base ) ) { // if not in referees
header( 'Refresh: 3; ' . esc_url( home_url() ) ); // redirect in 3 seconds
wp_die( 'Something went wrong.', NULL, $args = array( 'back_link' => true, ) ); // kills WordPress execution and displays an HTML page with an error message
exit; // terminate the current script
};
};
} );
I've had a look at a bunch of things. wp_get_referer() can't be used that way as it's specific to Wordpress
Retrieve referer from _wp_http_referer or HTTP referer. If it’s the same as the current request URL, will return false.
I'm using $_SERVER['HTTP_REFERER'] instead # https://stackoverflow.com/a/16374737/3645650. Which does the job I thaught wp_get_referer() would do.

WordPress Plugin settings page(options_page) redirecting to DB Upgrade page

I have been building a plugin for WordPress for a client, however I seem to be having a strange problem. I have added an options page but it's not working correctly.
When I go to the Wordpress menu I can see my options page. It has the correct options page options-general.php?page=Beacon_Registation_WP, however when I click on the menu item that page redirects me to upgrade.php?_wp_http_referer=%2Fwp-admin%2Foptions-general.php%3Fpage%3DBeacon_Registation_WP
Am unsure why this is happening.
The code im using as the entry point for the plugin:
<?php
/**
* Plugin Name: ** OMITED **
* Plugin URI: ** OMITED **
* Description: This plugin enabled the wordpress site to register new users to the beaconapp
* Version: 1.0
* Author: Martin Barker - ** OMITED **
* Author URI: ** OMITED **
* License: Propriatry Software (do not distribute)
*/
class BeaconRegistation
{
// handler for registing the wp-admin menu
public function addMenuItem()
{
add_options_page( 'Configure Server', 'BeaconApp Registation', 'manage_options', 'Beacon_Registation_WP', array($this, "wp_admin") );
}
// display the wp_admin page for this plugin
public function wp_admin()
{
ob_start();
if ( !current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
$this->sdr = get_option("sdr", "martindev.** OMITED **");
if($_POST['sdr'] !== $this->sdr){
update_option("sdr", $_POST['sdr']);
$this->sdr = get_option("sdr", "martindev.** OMITED **");
}
// include the view for switch environment
include("admin.php");
return ob_get_clean();
}
// displays the shortcode 'ba_business_form'
public function showBusinessForm($atts, $content = "")
{
ob_start();
if($_POST['form_mode'] == "business"){
// form has been posted
}else{
include("business.html");
}
return ob_get_clean();
}
// displays the short code 'ba_agency_form'
public function showAgencyForm($atts, $content = "")
{
ob_start();
if($_POST['form_mode'] == "agency"){
// form has been posted
}else{
include("agency.html");
}
return ob_get_clean();
}
public function init()
{
// add the admin menu call
add_action( 'admin_menu', array($this, "addMenuItem"));
// add the short code for the business form
add_shortcode("ba_business_form", array($this, "showBusinessForm"));
// add the short code for the agency form
add_shortcode("ba_agency_form", array($this, "showAgencyForm"));
}
}
(new BeaconRegistation())->init();
Just to confirm the 2 shortcodes are working correctly so the only problem is the options_page
So after some hacking of the Wordpress admin panel, we managed to dig this down to the include("admin.php") I'm unsure how but WordPress seems to interfere and prevent this process from working.
so the include relative paths seem to work as it does with the include("business.html"); and include("agency.html"); however the "admin.php" one just seems to not occur it's like another admin.php get's included unsure how or why this happens.
so to fix i resolved the absolute path and included via that include(realpath(dirname(__FILE__))."/admin.php");

WordPress separate php file

I created a new page in my admin panel.
On this page, for example function is_admin() works fine.
if ( ! is_admin() ) {
echo "You are viewing the theme";
} else {
echo "You are viewing the WordPress Administration Panels";
}
From this page i send post data to xxx.php file.
And! In this xxx.php file functions such as is_admin doens't work.
How can i let wordpress to understand, that this xxx.php file is the part of him? So i can use functions on this page?
I am using
"include wp-load.php"
but it doesn't help me.
You can add him in the theme folder & include in functions.php:
// functions.php of your current theme
include __DIR__.'/custom.php';
I just checked the source code on Github.
function is_admin() appears in this file https://github.com/WordPress/WordPress/blob/6fda2e67b0fe3872cbf5f82b58b98f2a4c96d8f8/wp-includes/load.php#L710-L717
So, require_once 'wp-includes/load.php; should sort you out.
The fact that you're sending POST data (request, i assume) to another php file makes me think that it's a completely different HTTP request, therefore you won't be able to use wp functions in the target php file, unless you include wp-load.ph in that file.
See this: https://wordpress.stackexchange.com/questions/69184/how-to-load-wordpress-on-non-wp-page
add_action('admin_menu', function(){
add_menu_page( 'Subscribe', 'Subscribe', 'manage_options', 'subsc-options', 'sub_setting', '', 4 );
} );
add_action( 'current_screen', function( $current_screen ){ // hook is admin panel only
if ( stripos($current_screen->base, 'subsc-options')==true ) {
include __DIR__.'/custom.php';
}
});
<form method="post">
<input type="hidden" name="my_save_settings" >
..............
</form>
/********* CUSTOM.PHP **************/
if ( isset($_POST['my_save_settings']) ) {
// save form fields
}

WordPress map custom url to a function

I am trying to add a custom URL structure to a WordPress based website.
for example:
example.com/machines //list all machines in a table
example.com/machines?some=params //list filtered machines in a table
example.com/machines/1 //show single machine
The data will come from an external api i have already developed, via curl.
I cannot import the data into a custom post type as it is normalized over many tables, the business logic is complicated and the api is used by other devices anyway.
I have looked at the docs for add_rewrite_rule, but the second parameter has me stumped:
$redirect
(string) (required) The URL you would like to actually fetch
Well I don't have a url to fetch, I want to run a function, that will act as a simple router - take the url parts, call the external api and return a template with the correct data.
Calling the API will be simple, but how i actually route the url to the function, and how I then load a template (utilizing existing WordPress header.php and footer.php) has me stumped.
After much googling and reading a few good resources, I have found the solution.
Step 1: Use add_rewrite_endpoint to create a base url that will be mapped to a query variable:
add_action( 'init', function(){
add_rewrite_endpoint( 'machines', EP_ROOT );
} );
Step 2: Visit the permalinks settings page and click "Save Changes" to flush the rewrite rules.
Step 3: Hook into the action 'template_redirect' to actually do something when the url is hit:
add_action( 'template_redirect', function() {
if ( $machinesUrl = get_query_var( 'machines' ) ) {
// var_dump($machinesUrl, $_GET);
// $machinesURl contains the url part after example.com/machines
// e.g. if url is example.com/machines/some/thing/else
// then $machinesUrl == 'some/thing/else'
// and params can be retrieved via $_GET
// after parsing url and calling api, it's just a matter of loading a template:
locate_template( 'singe-machine.php', TRUE, TRUE );
// then stop processing
die();
}
});
Step 4: The only other thing to do is handle a hit to a url with no further parts to it e.g. example.com/machines.
It turns out that at some point within WordPress's guts, the empty string gets evaluated to false and thus skipped, so the final step is to hook into the filter 'request' and set a default value:
add_filter( 'request', function( $vars = [] ) {
if ( isset( $vars['machines'] ) && empty( $vars['machines'] ) ) {
$vars['machines'] = 'default';
}
return $vars;
});
This can easily be improved by wrapping it all in a class(es).
The url parsing and template loading logic can be passed to a basic router, even a rudimentary MVC setup, loading routes from a file etc, but the above is the starting point.
A simplier solution is to just create a new template redirect.
So assuming you loading example.com/custom-url
/**
* Process the requests that comes to custom url.
*/
function process_request() {
// Check if we're on the correct url
global $wp;
$current_slug = add_query_arg( array(), $wp->request );
if($current_slug !== 'custom-url') {
return false;
}
// Check if it's a valid request.
$nonce = filter_input(INPUT_GET, '_wpnonce', FILTER_SANITIZE_STRING);
if ( ! wp_verify_nonce( $nonce, 'NONCE_KEY')) {
die( __( 'Security check', 'textdomain' ) );
}
// Do your stuff here
//
die('Process completed' );
}
add_action( 'template_redirect', 'process_request', 0);

WordPress Cookie Redirect - Home Page to Blog Page

I'm using WordPress and I want the user to go to the Home Page on their first visit, but on every other visit after that I would like them to be redirected to the Blog.
Home Page:
www.website.com
Blog:
www.website.com/blog
I'm guessing the best way to do this is to set a cookie?
I have no idea on what PHP files to edit or anything...
In your theme functions.php ( or plugin )
function o99_set_newvisitor_cookie() {
if ( !is_admin() && !isset($_COOKIE['sitename_newvisitor'])) {
setcookie('sitename_newvisitor', 1, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);
}
}
add_action( 'init', 'o99_set_newvisitor_cookie');
After that
if (isset($_COOKIE['sitename_newvisitor'])) {
echo 'Welcome back!'; // or redirect using wp_redirect( 'some_url/' ); exit;
}
else {
echo 'Hello new visitor!'; // or redirect using wp_redirect( home_url() ); exit;
}
This should do the job .
Wordpress itself had a function called wp_setcookie() but it was deprecated and replaced by wp_set_auth_cookie() which is only for user auth I believe . Not sure why, but maybe because of cookies laws that were introduced ( and that also you need to take into account )
Anyhow, see also the normal PHP setcookie() docs and the wp_redierct() function in codex.

Categories