PHP - If an array contains part of a string - php

I have the following PHP code:-
<?php
if( have_rows('postcode_checker', 'option') ):
while ( have_rows('postcode_checker', 'option') ) : the_row(); ?>
<?php
$postcodes .= get_sub_field('postcodes');
$postcode_url = get_sub_field('page');
?>
<?php endwhile;
else : endif;
$postcode_array = $postcodes; // This collects postcodes, i.e. LE67, LE5 etc...
$postcode_array = explode(',', $postcode_array);
$postcode_array = str_replace(' ', '', $postcode_array);
$postcode_search = $_POST['postcode']; // This will be a single postcode i.e. LE67
if (in_array($postcode_search, $postcode_array)) {
echo 'yes';
} else {
echo 'no';
}
?>
So the code above is working fine if I want to look up say LE67 and it finds LE67 in the array and returns 'yes'. Now if I search LE675AN for example it will return no even though it needs to be returning yes as it is within the postcode area.
Any idea's on how I can achieve this?

Related

Very simple geo targeting for WordPress

I need to do some very basic geo-targeting for a WordPress site.
Something like:
<?php if ( visitor is from usa ): ?>
<?php get_footer('us'); ?>
<?php else: ?>
<?php get_footer('other-countries'); ?>
<?php endif; ?>
Till now I used the GEO service provided by ip-api.com.
My code looks like this:
<?php $ip = $_SERVER['REMOTE_ADDR'];
$query = #unserialize(file_get_contents('http://ip-api.com/php/' . $ip));
$geo = $query['countryCode'];
if( $query['countryCode'] == 'US') : ?>
DO THIS
<?php else: ?>
DO THAT
<?php endif ?>
The problem is that the php unserialize is now deprecated and extremely slow. Ip-api suggest to use JSON instead. But I am a total newbie and I don't know how to achieve the same results with JSON. Can someone please help me?
I know there are various plug-ins out there, but I think they are overkill for the very simple geo targeting I need.
PS: I just learn that I should use the code
$.getJSON( '//ip-api.com/json?callback=?', function( data ) {
console.log( JSON.stringify( data, null, 2 ) );
});
But still I need help to put together the final complete code.
Try this:
<?php
$ip = ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) ?
$_SERVER['REMOTE_ADDR'] : '';
$country_code = '';
if ( $ip ) {
// 'fields' are comma-separated list of fields to include in the response.
// No spaces between the fields. See http://ip-api.com/docs/api:returned_values#field_generator
$url = 'http://ip-api.com/json/' . $ip . '?fields=countryCode,status,message';
$res_body = wp_remote_retrieve_body( wp_safe_remote_get( $url ) );
$geo = json_decode( $res_body );
$country_code = isset( $geo->countryCode ) ? $geo->countryCode : '';
}
if ( 'US' === $country_code ) : ?>
DO THE THIS
<?php else : ?>
DO THE THAT
<?php endif; ?>
PS: I just learn that I should use the code
Yes, that's an example of doing it with jQuery.

How to combine two if statements in PHP for WP

I need to run a function (show a modal) if a page DOES have a particular field value AND is not a certain page. It also needs to work if the page DOES NOT HAVE THE FIELD VALUE and it is not the certain page. They work individually like this:
//if page has field value:
<?php
$values = get_field( 'recast_video' );
if ( ($values) ) {
get_template_part('template-parts/popIn', 'none');
}
?>
//if it is this page, do not show:
<?php
if ( (!is_page('trading-education-webinars') ) ){
get_template_part('template-parts/popIn', 'none');
}
?>
How do I combine the two so that it shows (get_template_part) if the field has the value and is not the specified page
//this fails
<?php
$values = get_field( 'recast_video' );
if ( ($values) || (!is_page('trading-education-webinars') ) ){
get_template_part('template-parts/popIn', 'none');
}
?>
First thing to do is look for the common condition. No matter what, you don't want it to be a certain page, right? So first check that it's not that page:
$result = (!is_page('trading-education-webinars')) ? : ;
It also needs to work if the page DOES NOT HAVE THE FIELD VALUE and it
is not the certain page.
Then why check for the field value at all? No need, as long as it's not the page we checked for.
$result = (!is_page('trading-education-webinars')) ? get_template_part('template-parts/popIn', 'none') : return false;
You can change return false; to whatever you want to happen if the page IS 'trading-education-webinars'
EDIT: Clarifying the conditional:
Page X never gets served "content" (modal)
If NOT page X and has $values, show content
If NOT page X and NOT has $values, show some other content
$values = get_field( 'recast_video' );
$x = get_template_part('template-parts/popIn', 'none');
$y = 'some other content';
$return = (!is_page('trading-education-webinars')) ? (($values) ? $x; : $y ) : return false );
Use the && (AND) operator:
<?php
$values = get_field( 'recast_video' );
if ( ($values && !is_page('trading-education-webinars')) || (!$values && is_page('trading-education-webinars')) ){
get_template_part('template-parts/popIn', 'none');
}
?>
|| operator is true when at least one or both statements are true

unset item from array and update wp option

I have a series of checkboxes, each of which triggers an ajax action in WordPress. It sends an id number and the state of the checkbox to my php function. The function checks two wp_options. If the checkbox is checked, it looks for the id number in one option's array and if it's not in the array, it adds it. It also looks for the id number in the second option's array and if it is in the array, it's supposed to unset it. If the checkbox is unchecked, it does the opposite.
It's successfully adding items to the first option's array, but I can't get it to unset the item from the second option's array. It returns "error" every time. Here's the function, minus the nonce info:
function my_required_fields(){
$field = $_POST['field'];
$checked = $_POST['checked'];
$required_fields = get_option('ghsc_required_fields') ? unserialize(get_option('ghsc_required_fields')) : array();
$optional_fields = get_option('ghsc_optional_fields') ? unserialize(get_option('ghsc_optional_fields')) : array();
if($checked === 'yes'):
if(!in_array($field, $required_fields)): $required_fields[] = $field; endif;
if(in_array($field, $optional_fields)): unset($optional_fields[$field]); endif;
elseif($checked === 'no'):
if(!in_array($field, $optional_fields)): $optional_fields[] = $field; endif;
if(in_array($field, $required_fields)): unset($required_fields[$field]); $required_fields = array_values($required_fields); endif;
endif;
$update_required = update_option('ghsc_required_fields', serialize($required_fields));
$update_optional = update_option('ghsc_optional_fields', serialize($optional_fields));
$response = ($update_required && $update_optional) ? 'success' : 'error';
$response = json_encode($response); header( "Content-Type: application/json" ); echo $response; exit;
}
Any idea what I'm doing wrong?
I worked it out. Needed to use array_keys (or an alternative) to unset the key, rather than the value, and also needed to check to see if the value of the option had changed, because if it hadn't it would return false. See below:
function my_required_fields(){
$field = $_POST['field'];
$checked = $_POST['checked'];
$required_fields = get_option('ghsc_required_fields') ? unserialize(get_option('ghsc_required_fields')) : array();
$optional_fields = get_option('ghsc_optional_fields') ? unserialize(get_option('ghsc_optional_fields')) : array();
if($checked === 'yes'):
if(!in_array($field, $required_fields)): $required_fields[] = $field; endif;
if(in_array($field, $optional_fields)): foreach(array_keys($optional_fields, $field, true) as $key) unset($optional_fields[$key]); endif;
elseif($checked === 'no'):
if(!in_array($field, $optional_fields)): $optional_fields[] = $field; endif;
if(in_array($field, $required_fields)): foreach(array_keys($required_fields, $field, true) as $key) unset($required_fields[$key]); endif;
endif;
$update_required = (get_option('ghsc_required_fields') === serialize($required_fields) ? 1 : update_option('ghsc_required_fields', serialize($required_fields)));
$update_optional = (get_option('ghsc_optional_fields') === serialize($optional_fields) ? 1 : update_option('ghsc_optional_fields', serialize($optional_fields)));
$response = ($update_required && $update_optional) ? 'success' : 'error';
$response = json_encode($response); header( "Content-Type: application/json" ); echo $response; exit;
}

foreach statement echo once if nested foreach is empty?

OK I have a foreach statement searching for a keyword across 3 multisite blogs in wordpress like so:
<?php
foreach ( $blogs as $blog ):
switch_to_blog($blog['blog_id']);
$search = new WP_Query($query_string);
if ($search->found_posts>0) {
foreach ( $search->posts as $post ) {
echo "POST CONTEN";
}
}elseif ($search->found_posts===0) {
# code...
$notfound = true;
}
endforeach;
if ($notfound) {
# code...
echo "POST NOT FOUND";
}
This works fine if there are no posts using the keyword across all thre blogs it echos the POST NOT FOUND but if there is a post on blog 1 but not on blog 2 or 3 it still echos POST NOT FOUND why?
Chris
//********UPDATE***********************************/
<?php
$searchfor = get_search_query(); // Get the search query for display in a headline
$query_string=esc_attr($query_string); // Escaping search queries to eliminate potential MySQL-injections
$blogs = get_blog_list( 0,'all' );
$notfound = true;
foreach ( $blogs as $blog ):
switch_to_blog($blog['blog_id']);
$search = new WP_Query($query_string);
if ($search->found_posts>0) {
$notfound = false;
}
if($notfound){
?>
<div class="post">
<h2><?php _e('Ingen resultater'); ?></h2>
<p><?php _e('Beklager, vi fant ingen innlegg som samsvarer med ditt søk: ' . get_search_query()); ?></p>
</div>
<?php
}else{
foreach ( $search->posts as $post ) {
echo "content";
}
}
endforeach;
?>
Your logic is backwards. You should start with a "nothing found" condition, and change it to false when something is found:
$not_found = true;
while ...
if ($search->found_posts != 0) {
$not_found = false;
}
}
if ($not_found) {
echo 'nothing found'; // $not_found is true
} else {
echo 'found something'; // $not_found is false
}
Sorry about the formatting. Just copied your code here. Do the opposite of what your doing, look at the variable $found here.
<?php
$found = false;
foreach ( $blogs as $blog ):
switch_to_blog($blog['blog_id']);
$search = new WP_Query($query_string);
if ($search->found_posts>0) {
foreach ( $search->posts as $post ) {
echo "POST CONTEN";
}
$found = true;
}elseif ($search->found_posts===0) {
# code...
}
endforeach;
if ($found == false) {
# code...
echo "POST NOT FOUND";
}

Check session is set, codeigniter

I have a upload script which post upload lets the user edit the content title for a period of time. It sets the following in the ci_sessions user_data column in the db:
array (
'user_data' => '',
'edit' =>
array (
'image_id' => 'HF',
'session_id' => '783c15b057bcd9c19d3fd82f367ee55d',
),
)
The problem is my session CHECK code can't find the session:
<?php if ($this->session->userdata('edit') !== FALSE) : ?>
<?php echo '<!-- session found -->'; ?>
<?php $session_info = $this->session->userdata('edit'); ?>
<?php $ids_array = explode(",", $session_info['image_id']); ?>
<?php foreach ($ids_array as $id): ?>
<?php
if ($id == $alpha_id
&&
$session_info['session_id'] == $this->session->userdata('session_id')) :
?>
The echo on line 2 of that block never gets outputted.
Can anyone see what I'm doing wrong? thanks
heres my controller http://pastebin.com/aXeRn1VN
Try this
<?php if( $this->session->userdata('edit') ) : ?>
instead of
<?php if ($this->session->userdata('edit') !== FALSE) : ?>

Categories