in_array function not working when using variable? - php

In my below code I am trying to check whether the $query['skill'] value is contained in $c_skills. However it keeps failing. When I use the actual string that I am looking for, e.g. "test" then it functions as intended. My only thought is perhaps $query['skill'] doesn't return as a string, but I can't do a var_dump to find out since I am using wordpress and I am changing code to effect ajax query.
global $user_ID;
$query = $_REQUEST['query'];
if (isset($_REQUEST['query']['skill'])) {
if (isset($query['skill']) && $query['skill'] != '') {
global $wp_query, $ae_post_factory, $post, $current_user;
$post_object = $ae_post_factory->get(PROFILE);
$profile_id = get_user_meta( $user_ID, 'user_profile_id', true);
$profile = array('id' => 0, 'ID' => 0);
if($profile_id) {
$profile_post = get_post( $profile_id );
if($profile_post && !is_wp_error( $profile_post )){
$profile = $post_object->convert($profile_post);
}
}
$current_skills = get_the_terms( $profile, 'skill' );
if (!empty($current_skills)) {
$c_skills = array();
foreach ($current_skills as $key => $value) {
$c_skills[] = $value->name;
};
if(in_array( $query['skill'], $c_skills )) {
$query_args['tax_query'] = array(
'skill' => array(
'taxonomy' => 'skill',
'terms' => 'test',
'field' => 'slug'
)
);
}
}

I think your problem come from $query_args['tax_query'].
For me, the Key (skill) has nothing to do here.
Try to make it simple with
$query_args['tax_query'] = array(
array(
'taxonomy' => 'skill',
'terms' => 'test',
'field' => 'slug'
)
);
The place you use for skill between the two array is intended to be use for relation if you want to query more than one taxonomy.
Hope it works after this.

Related

WooCommerce; Query products by attribute term, do not include parent product in query if variation which uses the term is disabled

Scenario:
Variable product has attribute color, term is 'yellow'
Variation with yellow term is disabled
Customer filters product by color 'yellow'
Parent product is displayed even if variation which uses the color 'yellow' is not enabled
Note: Query should contain simple and variation product types.
The query is being called by ajax function, I'm not sure how to use filters if its possible.
The query:
add_action('wp_ajax_getProducts', 'getProducts');
add_action('wp_ajax_nopriv_getProducts', 'getProducts');
function getProducts(){
$input = [
'currentTerm' => $_POST['currentTerm'],
'searchTerms' => $_POST['searchTerms'],
'page' => $_POST['page'],
'color' => $_POST['color'],
'sortBy' => $_POST['sortBy'],
'sortDirection' => $_POST['sortDirection'],
'beltWidth' => $_POST['beltWidth'],
];
// args init
$args = array(
'post_type' => 'product',
'posts_per_page' => 12,
'post_status' => 'publish',
'lang' => pll_current_language()
);
$args['meta_query'] = array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock'
),
);
$args['tax_query'] = array(
'relation' => 'AND',
);
// 0. Search
if( isset() ) {
$sargs = array(
's' => $input['searchquery'],
);
$args = array_merge($sargs, $args);
}
// 1. Terms
if( isset($input['currentTerm']) ) {
$cat_tax = array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $input['currentTerm'],
);
array_push($args['tax_query'], $cat_tax);
}
// 2. Page
if( isset($input['page']) ) {
$args['paged'] = $input['page'];
}
// 3. color
if( isset($input['color']) && $input['color'] != 'clear') {
$color_tax = array(
'taxonomy' => 'pa_color',
'field' => 'slug',
'terms' => $input['color'],
'operator' => 'IN'
);
array_push($args['tax_query'], $color_tax);
}
// 4. sort
if ( isset($input['sortBy']) ) {
if ( $input['sortBy'] == 'price' ) {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = '_price';
} elseif ( $input['sortBy'] == 'name' ) {
$args['orderby'] = 'title';
} else {
$args['orderby'] = 'date';
}
}
if ( isset($input['sortDirection'])) {
if ( $_POST['sortDirection'] == 'asc') {
$args['order'] = 'asc';
} else {
$args['order'] = 'desc';
}
}
// query
$wp_query = new WP_Query( $args );
...
echo json_encode($products);
...
}
The query works fine, and I've found the way to clear results, by filtering the results; but it returns uneven number of products per page, which is not very user friendly.
The solution is to do something like code below within the query arguments, not inside the results loop.
if( isset($input['color']) && $input['color'] != 'clear') {
if ($product['terms']) {
foreach($product['terms'] as $item) {
if ((string) $item['slug'] == $input['color']) {
array_push($products, $product);
}
}
}
}

php wordpress processing inside the hook and synchronizing the value to the variable outside the hook

what I want is that I have a special taxonomy and get_terms does not work without it being loaded, naturally the only way I can get it is to hook up to "init". But when this is the case, I will have to repeat this. I do not want this.
As you can see in the code below, I am doing the operation in init and trying to transfer it to "$ new_array". How can I do it?
protected function get_reactions()
{
$new_array = array();
add_action( 'init', function() use ( &$new_array ) {
$reactions = get_terms( array(
'taxonomy' => 'bp_reaction',
'hide_empty' => false
));
foreach ( $reactions as $value ) {
$priority = get_option( 'taxonomy_'.$value->term_id.'_priority' );
$image = get_option( 'taxonomy_'.$value->term_id.'_image' );
$new_array[$priority] = (object) array(
'id' => $value->term_id,
'priority' => $priority,
'slug' => $value->slug,
'name' => $value->name,
'image' => $image
);
}
}, 9 );
// Sort from largest to small
krsort( $new_array );
return $new_array;
}

wp remote get and advanced custom fields returning hundreds of duplicates

I found a tutorial explaining how to use wp_remote_get() and post results to WP custom post types using Advanced Custom Fields Plugin.
My problem is that when I run this from the admin dashboard as explained, I get hundreds of duplicate entries for the same product! I assume because I'm looping through pages as explained in the tutorial, but the API endpoint I'm using is not paginated, as is the one in the tutorial. I'm trying to figure out how to stop the loop from running when the newly created post already exists. Here is my code
<?php
add_action('wp_ajax_nopriv_get_products_from_api', 'get_products_from_api');
add_action('wp_ajax_get_products_from_api', 'get_products_from_api');
function get_products_from_api() {
$current_page = ( ! empty($_POST['current_page']) ) ? $_POST['current_page'] : 1;
$myproducts =[];
$results = wp_remote_retrieve_body( wp_remote_get('https://link/to/api/endpoint/'));
$results = json_decode($results);
if ( ! is_array( $results ) || empty ( $results ) ) {
return false;
}
$myproducts[] = $results;
foreach( $myproducts[0] as $myproduct ) {
$myproducts_slug = $myproduct->name;
$existing_product = get_page_by_path($myproducts_slug, 'OBJECT', 'myproduct');
if($existing_product === null ) {
$inserted_product = wp_insert_post([
'post_name' => $myproducts_slug,
'post_title' => $myproducts_slug,
'post_type' => 'myproducts',
'post_status' => 'publish'
]);
if (is_wp_error($inserted_product) ) {
continue;
}
//ADVANCED CUSTOM FIELDS INTEGRATION
$fillable = [
'field_5dc862b619530' => 'name',
'field_5dc862ec19531' => 'style',
'field_5dc863269b298' => 'description',
'field_5dc8633738fad' => 'rating',
];
foreach( $fillable as $key => $name ) {
update_field( $key, $myproducts->$name, $inserted_product );
}
}
}
$current_page = $current_page +1;
wp_remote_post(admin_url('admin-ajax.php?action=get_products_from_api'), [
'blocking' => false,
'sslverify' => false,
'body' => [
'current_page' => $current_page
]
]);
}
What am I doing wrong, what am I missing? The script runs with no errors, but it just keeps going and going and making many copies of same post.
So, I figured out what was going on here. Due to the recursive nature of the admin-ajax call, there is no need to keep running that through pages that don't exist. While it's still necessary to run the script from wp-admin, it doesn't need to be hard coded in.
New code looks like this:
<?php
add_action('wp_ajax_nopriv_get_products_from_api', 'get_products_from_api');
add_action('wp_ajax_get_products_from_api', 'get_products_from_api');
function get_products_from_api() {
$current_page = ( ! empty($_POST['current_page']) ) ? $_POST['current_page'] : 1;
$myproducts =[];
$results = wp_remote_retrieve_body( wp_remote_get('https://link/to/api/endpoint/'));
$results = json_decode($results);
$myproducts[] = $results;
foreach( $myproducts[0] as $myproduct ) {
$myproducts_slug = $myproduct->name;
$existing_product = get_page_by_path($myproducts_slug, 'OBJECT', 'myproduct');
if($existing_product === null ) {
$inserted_product = wp_insert_post([
'post_name' => $myproducts_slug,
'post_title' => $myproducts_slug,
'post_type' => 'myproducts',
'post_status' => 'publish'
]);
if (is_wp_error($inserted_product) ) {
continue;
}
//ADVANCED CUSTOM FIELDS INTEGRATION
$fillable = [
'field_5dc862b619530' => 'name',
'field_5dc862ec19531' => 'style',
'field_5dc863269b298' => 'description',
'field_5dc8633738fad' => 'rating',
];
foreach( $fillable as $key => $name ) {
update_field( $key, $myproducts->$name, $inserted_product );
}
}
}
Hopefully this will help someone else that runs into the same issue I did.
Check the DIFF

OOP PHP method doesn't work when invoked within another method

I'm creating a PHP class for a Wordpress site. The following method works fine, but when I try to abstract it a bit by passing an argument and calling it within another method (see code further down below), it doesn't work anymore.
public function user_has_submitted_in_dog_category() {
$args = array(
'post_type' => 'submissions',
'author' => get_current_user_id(),
'tax_query' => array(
array(
'taxonomy' => 'submissions_categories',
'field' => 'slug',
'terms' => 'dog'
)
)
);
$user_posts = get_posts( $args );
if( count( $user_posts ) )
return true;
}
This is not working:
public function user_has_submitted_in_dog_category() {
$this->user_has_submitted_in_animal_category( 'dog' );
}
public function user_has_submitted_in_animal_category( $category ) {
$args = array(
'post_type' => 'submissions',
'author' => get_current_user_id(),
'tax_query' => array(
array(
'taxonomy' => 'submissions_categories',
'field' => 'slug',
'terms' => $category
)
)
);
$user_posts = get_posts( $args );
if( count( $user_posts ) )
return true;
}
By not working, I mean that user_has_submitted_in_dog_category() is not returning true. I call it in a template file as follows:
<?php if( $submission->user_has_submitted_in_dog_category() ) : ?>
<div class="msg">You have already submitted.</div>
<?php else : ?>
<div class="msg">You have not submitted yet.</div>
<?php endif; ?>
The block of code prints You have not submitted yet, but I do have posts in my custom taxonomy dog.
You need to return from your first (dog) method.
public function user_has_submitted_in_dog_category() {
return $this->user_has_submitted_in_animal_category( 'dog' );
}
Wordpress might be calling the method statically. You might be best off doing that yourself as the method doesn't seem to need an object instance to work:
public function user_has_submitted_in_dog_category() {
MyClass::user_has_submitted_in_animal_category( 'dog' );
}

Get Custom Posts and put into option array - wordpress plugin

Trying to write a piece of code to expand a theme that I am using in Wordpress.
Basically, I want to get all custom post types and put it into an array for a select - the issue I am having is that I need to add the option values in the array and I cannot put a foreach loop in the array so not sure how to do this.
In the code below you will see the code:
'options' => array(),
This is where the custom posts need to be in the format:
'PostID' => esc_html__( 'Post Name', 'builder' ),
Here is my code:
function get_fields() {
$fields = array(
'get_post_names' => array(
'label' => esc_html__( 'Url Opens', 'builder' ),
'type' => 'select',
'option_category' => 'configuration',
'options' => array(),
'toggle_slug' => 'post_names',
'description' => esc_html__( 'Here you can choose whether or not your link opens in a new window', 'et_builder' ),
),
);
global $wpdb;
$custom_post_type = 'custom_post_name';
$results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
if ( ! $results )
return;
foreach( $results as $index => $post ) {
$fields['options'][] = array (
$post['ID'] => esc_html__( $post['post_title'], 'builder' ),
);
}
return $fields;
}
Any help would be much appreciated.
Thanks
Hopefully this may work
function generate_post_select($select_id, $post_type, $selected = 0) {
$post_type_object = get_post_type_object($post_type);
$label = $post_type_object->label;
$posts = get_posts(array('post_type'=> $post_type, 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
foreach ($posts as $post) {
echo $post->post_title;
}
}
$select_id is used as the name and id of the select, $post_type is the type you want to be made into the select and $selected is the post id you want selected in the select box.
Found a solution if anyone wants to know.
Changed the 'option' to be the following and removed the code from global $wpdb; down.
'options' => array_reduce( get_posts( 'post_type=custom_post&posts_per_page=-1' ), function( $result, $item ) {
$result[$item->ID] = $item->post_title;
return $result;
}),

Categories