Can't figure out how to check multiple URL's and stop loading selected plugin. With other plugins it's all good when need to check only one page, but when it comes to multiple pages - ain't working at all.
Code:
<?php
$request_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$is_admin = strpos( $request_uri, '/wp-admin/' );
if( false === $is_admin ){
add_filter( 'option_active_plugins', function( $plugins ){
global $request_uri;
$berocket_filter_plugin = "woocommerce-ajax-filters/woocommerce-filters.php";
$c = array_search( $berocket_filter_plugin, $plugins );
if( false !== $c && in_array( strpos ($request_uri, ['/shop/','/product-category/'], true ) )){
unset( $plugins[$c] );
}
return $plugins;
} );
}
I'm trying to check is page url is exactly 'shop' page slug, or contains '/product-category/' slug, as soon as I'm trying to use this array, it's not doing his work at all.
Any suggestions are appreciated!
To be honest I'm not a wordpress expert (I hate the bloody thing) but...
The strpos function second argument needs to be a string, you're passing in an array that evaluates to 0 I believe. And the 3rd argument is an offset on the sting, since you set it to true i believe that would evaluate to 1. So... what happens is:
in_array(strpos('myurl',0,1))
strpos('myurl',0,1) = 0 // as we're looking for a '0' in 'yurl'
consider working with the url as a dictionary. Instead of keeping it as a string run a no_empty explode to get something like:
['shop' => true,
'product-category' => true]
That way instead of running an array_search or strpos for each check you can simply invoke something along the lines of:
if(!isset($request_uri['wp-admin']) {...
if (
isset($request_uri['product-category']) ||
(count($request_uri) === 1 && isset($request_uri['shop']))
) {...}
}
There is a neater way to write this but this should be simple to read and understand the logic.
Similar approach goes for the plugins array. The only difference between [$id => $value] and [$value => $id] is the fact that you need to run a search on the array and check if it's set instead of simply checking if it's set.
Related
I have 2 arrays, one of which is built dynamically and one which I use as a map.
The map array:
$social_links_map = [
'twitter' => 'twitter-icon',
'facebook' => 'facebook-icon'
];
And my dynamic array, which is just a simple list of social links:
$dynamic_social_links = [ 'twitter.com/me', 'facebook.com/me' ];
$social_links = explode( ',', $dynamic_social_links );
The $dynamic_social_links is an user input, as such, their input can be wrongly typed.
And I need to check if within my $social_links exists any of the $social_links_map keys and return the $social_links_map item accordingly:
if( !empty( $social_links ) ) {
foreach( $social_links_map as $handle => $icon ) {
foreach( $social_links as $social_link ) {
if( strpos( $social_link, $handle ) ) {
echo $handle;
}
}
}
}
This doesn't allow for "duplicate removal", nor does it look very pretty. Any ideas?
use
array_unique
to remove "duplicated data".
Try
$social_links = array_unique(explode( ',', $dynamic_social_links ));
Firstly, is it possible that you can allow the user to select from a list of your $social_links_map?
If not then the approach you are using is likely the simplest most readable way of doing this as there is no sure fire way to be able to match potentially random user input with a predefined array of options.
A couple of things to note:
As mentioned by le Mandarin, you can use array_unique to get rid of duplicates.
The other is that strpos will return 0 (which is falsey) if the search string (needle) is found at the very start of the context variable (haystack).
eg:
strpos('twitter.link/stuff', 'twitter');
will return 0 which is false Causing your if statement to fail.
instead try something like
if (false !== strpos('twitter.link/stuff', 'twitter')) {
Take note of the extra = in !==. This is necessary because you are saying "If the result is not exactly the boolean false.
I'm trying to track login dates/times for Wordpress users. I want to be able to track the last 10 times the user has logged in. To do this, I need to be able to save an array within user meta. My code below is not working and I can't figure out why. I've found multiple other questions on this site that seem to deal with similar subject matter, but their solutions seem to contradict mine. My code:
function drick_track_user_login($user_login, $user) {
$meta_key = 'drick_login_times';
$user_login_meta = get_user_meta( $user->ID, $meta_key, true);
$number_of_timestamps = count($user_login_meta);
if( ! array($user_login_meta) ) {
$user_login_meta = array();
}
if( $number_of_timestamps < 10 ) {
$user_login_meta[] = time();
} else {
array_pop($user_login_meta);
$user_login_meta[] = time();
}
update_user_meta( $user->ID, $meta_key, $user_login_meta);
}
add_action('wp_login','drick_track_user_login', 10, 2);
What I want to happen is when the wp_login action is triggered, the function checks to see how many timestamp values are in the 'drick_login_times' array. If it's over 10, to delete the last one then add in the newest time.
I've seen on multiple answers that if you don't have "true" for the third parameter in the get_user_meta function, it will create nested arrays (which I've seen happen). However, if I set that to "false" then I get a 500 Server error when logging in, and the WP_DEBUG log shows:
PHP Fatal error: Uncaught Error: [] operator not supported for strings
So I must be misunderstanding how this should work. I want the meta data to be an array, but I need the get_user_meta to be true - and the get_user_meta codex says false will return an array - which causes the nested array problem. Another answer has the conditional statement to make sure it's an array:
if( ! array($user_login_meta) ) {
$user_login_meta = array();
}
But that doesn't seem to help the server error on login. Could someone show me what is incorrect in the code, and/or point me to an answer that I missed? I appreciate the help.
You're getting error because of this line:
if( ! array($user_login_meta) ) {
Here you're just creating array with function array() without saving it's stage in some variable. So, you will never reach this line $user_login_meta = array();.
Here is working code:
function drick_track_user_login($user_login, $user)
{
$meta_key = 'drick_login_times';
$user_login_meta = get_user_meta($user->ID, $meta_key, true);
$number_of_timestamps = count($user_login_meta);
if (!is_array($user_login_meta)) {
$var[] = $user_login_meta;
}else{
$var = $user_login_meta;
}
if ($number_of_timestamps < 10) {
$var[] = time();
} else {
array_shift($var);
$var[] = time();
}
update_user_meta($user->ID, $meta_key, $var);
}
add_action('wp_login', 'drick_track_user_login', 10, 2);
We checking, if we got array with function is_array(), and if not, then creating it( will work when user first time loged in ). In other cases we'll use $var = $user_login_meta;.
Also, with array_pop() you're removing the last log of users loged in. I think, you should delete the first one with array_shift()
Just a weird PHP question about best practice.
Assuming the following function:
function get_option($val) {
return false;
}
I want to assign to a $locale variable, the value returned from this function and, if false, set to a default en_GB one.
I discovered 2 option for achieving this goal:
1st Option:
$locale = ( $locale = get_option( 'language_code' ) ) ? $locale : 'en_GB';
2nd Option:
$locale = get_option( 'language_code' ) ? get_option( 'language_code' ) : 'en_GB';
I would like to know which one is more correct and why.
Thanks
The second option is better, but even better would be to use a shorthand ternary
$locale = get_option('language_code') ?: 'en_GB';
If your function returns only locale strings or false, this is the correct solution (and it doesn't require PHP7).
However, as mentioned in the comments, it might be an idea to return default values directly from the get_option function for a more architecturally sound solution. That means the caller is not made responsible for setting the default.
Just read that you're using Wordpress and have no control over the inner workings of the function, but the advice in general still stands
Both seem a bit verbose to me, to avoid duplicated calculations, I would prefer the first one (perhaps splitted to 2 lines of code).
You can create a helper function, this one has false hardcoded, but you could even pass it as a parameter:
function use_default_false($var, $default) {
return ($var !== false) ? $var : $default;
}
Then your code becomes:
$locale = use_default_false(get_option('language_code'), 'GB');
Since PHP5.3 you can use the shorthand ternary operator ?:.
Be aware that it will check the left-hand side argument for truthy, which prevents it to be used if the valid value you're checking evaluates to false (e.g.: 0, "", "0", array()...). Because of that, I wouldn't generally recommend it, but in this case I assume the locale is a non-empty non-"0" string, so it should be fine.
$locale = get_option('language_code') ?: 'GB';
With PHP7 you can use the null coalesce operator ??.
It checks for NULL so you have to alter the default value returned by your function.
$locale = get_option('language_code') ?? 'GB';
I would prefer the second one
basically if get_option( 'language_code' ) returns true then get_option( 'language_code' ) execute else other option.
it is easier to understand, and maintainable.
for duplicate code issue use something similer to this:
you need to post some more code, but here is a better way to do it:
var var1 = null;
function get_option( somevar ){
if (var1 != null) {
return true;
} else {
var1 = do some stuff;
return true;
}
}
and then call the function like this
$locale = get_option( 'language_code' ) ? var1 : 'en_GB';
So what I wanna do is when a user pushes the submit button, a php query is run. In that php query if an "If statement" condition is fulfilled, I want to execute an operation (which in my case is a page redirection) and return false.
[EDIT] The whole query code is something like this:
add_filter( ‘mycred_add’, ‘mycred_pro_restrict_negative_balances’, 1, 3 );
function mycred_pro_restrict_negative_balances( $reply, $request, $mycred ) {
if ( $reply === false || $request[‘amount’] > 0 ) return $reply;
extract( $request );
// Users current balance
$current_balance = $mycred->get_users_balance( $user_id, $type );
// If balance is zero – decline OR If we are deducting points, make sure the amount will not take us below zero
if (( $current_balance <= 0 )||(($current_balance – abs( $amount )) < 0 )) {
$redirect_to_page = 22;
return false;
}
return $reply;
}
I wanna know if the query will work?? And if there's something wrong with it, please do mention the correction. Thanks in advance for helping / trying to help me.
In your calling function, test for a FALSE return value. If it's false, then call your redirection after processing any other actions you need to do upon this function returning FALSE.
You probably nead something like that:
if ( $current_balance <= 0 ) {
/* Redirection */
header("Location: http://www.example.com/page10.php");
exit();
}
Sending header 'Location' will tell browser to go to specified URL. That's the simplest way of redirection. You don't have to return false.
I am trying to pass a parameter to a WordPress site using a URL - for instance:
www.fioriapts.com/?ppc=1 will be the URL.
I am intending to write a function in the functions.php file but the mechanics of how to extract a parameter in WordPress is beyond me. How can it be done?
I am finding a lot of examples on how to add a parameter to a URL using the function add_query_arg() but have found nothing on how to extract a parameter.
Why not just use the WordPress get_query_var() function? WordPress Code Reference
// Test if the query exists at the URL
if ( get_query_var('ppc') ) {
// If so echo the value
echo get_query_var('ppc');
}
Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:
add_action('init','add_get_val');
function add_get_val() {
global $wp;
$wp->add_query_var('ppc');
}
Or by adding a hook to the query_vars filter:
function add_query_vars_filter( $vars ){
$vars[] = "ppc";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
When passing parameters through the URL you're able to retrieve the values as GET parameters.
Use this:
$variable = $_GET['param_name'];
//Or as you have it
$ppc = $_GET['ppc'];
It is safer to check for the variable first though:
if (isset($_GET['ppc'])) {
$ppc = $_GET['ppc'];
} else {
//Handle the case where there is no parameter
}
Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php
EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from #emc who details a WordPress function which accomplishes this goal securely.
You can try this function
/**
* Gets the request parameter.
*
* #param string $key The query parameter
* #param string $default The default value to return if not found
*
* #return string The request parameter.
*/
function get_request_parameter( $key, $default = '' ) {
// If not request set
if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
return $default;
}
// Set so process it
return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}
Here is what is happening in the function
Here three things are happening.
First we check if the request key is present or not. If not, then just return a default value.
If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.
All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/
In the call back function, use the $request parameter
$parameters = $request->get_params();
echo $parameters['ppc'];