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.
Related
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.
I have this code:
if($coupon->excluding_discounted){
if(!$product->price_after_discount){
// do something
}
}
The code worked perfectly but I thought to convert this to one if ...
dd($coupon->excluding_discounted,!$product->price_after_discount);
1
false
How to check if the value of something is 1 and another element is false to do something ...?
Update:
my full code:
$products->map(function($product) use($coupon){
if($coupon->excluding_discounted && !$product->price_after_discount){
user()->cart()->updateExistingPivot($product, [
'coupon_id' => $coupon->id,
]);
}
});
the logic of code is if the product has discount and the excluding_discounted in coupon is true do the reset of code
I tried like this but it store the coupon_id even there is a discount on product! but with if inside if worked perfectly
You can join if statements together, like so:
if ($coupon->excluding_discounted && !$product->price_after_discount) {
// do something
}
If you want to test strictly the value of a variable you can use the === operator :
if (1 === $coupon->excluding_discounted
&& false === $product->price_after_discount
) {
// do something here
}
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()
Codeigniter has a syntax for url parameter passing for functions inside the controller.
If a function for example:
function index($id){
$this->model->get_user($id);
}
Assuming that this function is called without supplying the ID namely called as
ProjectName/Controller/index
it will return an error as it expects a parameter.
Is there a way to check if a parameter exists.
No there is not a way to check if one exists per-say as that error happens before the controller has a chance to run code. ie. before the class method executes.
That said there is a simple workaround for this: You can supply a default value and check for that for example
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user($id);
}
}
This way when no parameter is supplied the ID will be null, this is fairly safe ( when using null ) because you can never supply null as part of the url path even doing this
www.mysite.com/index/null //or however the url works out in your case
Will supply null as a string, because everything in the url comes through as a string. So 'null' as a string is not in fact null it's just the word null. If that makes sense. So given that null could never be supplied and only happens if no other value is supplied.
In this case it may be worth casting the input to a int or further checking if it's an improper value.
This could be done several ways:
Casting:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user((int)$id);
//cast to int, things that are not INT or string equivalents become 0, which should not find a user as it would look for ID = 0
}
}
By Regx check:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else if( preg_match('/^[^\d]+$/', $id )){
// not an int ( contains anything other than a digit )
}else{
$this->model->get_user($id);
}
}
Cheers.
I am making a real estate related app and I've been having a hard time figuring out how to set up the query so that it would return "Only Apartments or Duplexes within selected areas" I'd like to user to be able to find multiple types of property in multiple selected quadrants of the city.
I have a database with a column "type" which is either "Apartment", "House", "Duplex", "Mobile"
In another column I have quadrant_main with values: "NW", "SW", "NE", "SE".
My code works when there is only 1 quadrant selected, but when I select multiple quadrants, I seem to get results which includes ALL the property types from the second or third or 4th quadrant, instead of only "Apartment" and "Duplex" or whatever types the user selects... Any help will be appreciated! thx in advance.
My controller function looks like this:
public function quadrants()
{
$input = \Request::all();
$currentPage = null;
$column = "price";
$order = "desc";
//
// Looks like the input is like 0 => { key: value } ...
// (an Array of key/value pairs)
$q = Listing::where('status','=','Active')->where(function($query) {
$input = \Request::all();
$currentPage = null;
$typeCount = 0;
$quadrantCount = 0;
foreach( $input as $index => $object ) {
$tempObj = json_decode($object);
$key = key((array)$tempObj);
$val = current((array)$tempObj);
if ( $key == "type" ) {
if ( $typeCount > 0 ) {
$query->orWhere('type', '=', $val );
}
else {
$query->where('type', '=', $val );
$typeCount++;
}
}
if ( $key == "quadrant_main" ) {
if ( $quadrantCount > 0 ) {
$query->orWhere('quadrant_main', '=', $val );
}
else {
$query->where('quadrant_main', '=', $val );
$quadrantCount++;
}
}
// else {
// $query->orWhere($key,$val);
// }
}
if( $currentPage ) {
//Force Current Page to Page of Val
Paginator::currentPageResolver(function() use ($currentPage) {
return $currentPage;
});
}
});
$listings = $q->paginate(10);
return $listings;
Looking at your question, its a bit confusing and not much is given to answer definitely. Probable causes of your troubles may be bad data in database, or maybe corrupted input by user.
Disclaimer: Please note that chances are my answer will not work for you at all.
In that case please provide more information and we will work things
out.
There is one thing that I think you have overlooked and thus you are getting awry results. First let me assume a few things.
I think a sample user input should look like this:
array(
0: '{type: Apartment}',
1: '{type: Duplex}',
2: '{quadrant_main: NW}',
3: '{quadrant_main: SW}',
)
What the user meant was give me any apartment or duplex which belongs in NW or SW region.
So after your loop is over, the final SQL statement should be something like this:
Oh and while we are at SQL topic, you can also log the actual
generated SQL query in laravel so you can actually see what was the
final SQL getting generated. If you can post it here, it would help a
lot. Look here.
select * from listings where status = 'Active' and (type = 'Apartment' or type = 'Duplex' and quadrant_main = 'NW' or quadrant_main = 'SW');
What this query will actually produce is this:
Select any listing which is active and:
1. Type is an apartment, or,
2. Type is a duplex, or,
3. Quadrant is SW, and,
4. Quadrant is NW
So assuming you have a database like this:
id|type|quadrant_main
=====================
1|Apartment|NW
2|Apartment|SW
3|Apartment|NE
4|Apartment|SE
5|Duplex|NW
6|Duplex|SW
7|Duplex|NE
8|Duplex|SE
9|House|NW
10|House|SW
11|House|NE
12|House|SE
You will only receive 1, and 5 in the result set. This result set is obviously wrong, plus it is depended on NW because that was the and condition.
The correct SQL query would be:
select * from listings where status = 'Active' and (type = 'Apartment' or type = 'Duplex') and (quadrant_main = 'NW' or quadrant_main = 'SW');
So structure your L5 app such that it produces this kind of SQL query. Instead of trying to cram everything in one loop, have two loops. One loop should only handle type and another loop should only handle quadrant_main. This way you will have the necessary and condition in the right places.
As a side note:
Never directly use user input. Always sanitize it first.
Its not a best practice to put all your logic in the controller. Use repository pattern. See here.
Multiple where clauses are generally applied via Criteria. Check that out in the above linked repository pattern.
You code logic is very complicated and utterly un-necessary. Instead of sending JSON objects, simply send the state of checkboxes. Don't try to generalize the function by going in loop. Instead handle all checkboxes one by one i.e. is "Apartments" selected, if yes, add that to your clause, if not, don't add.