Filters plugin in WP site - php

I've added in function.php some code to create some filters in my WP site.
The script is the following:
$GLOBALS['my_query_filters'] = array(
'field_1' => 'forma',
'field_2' => 'posa',
'field_3' => 'conduttore',
'field_4' => 'isolante',
'field_5' => 'raggio_minimo_di_curvatura',
'field_6' => 'guaina',
'field_7' => 'marchiatura',
'field_8' => 'tensione_di_esercizio',
'field_9' => 'temp_max_esercizio',
'field_10' => 'temp_min_di_inst',
'field_11' => 'temp_max_corto'
);
// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) {
return;
}
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
// update meta query
$query->set('meta_query', $meta_query);
}
For the moment, this code only shows 10 empty rows but there are any checkbox or filter name.
Can you help me, please?

Related

Implementing Rawg Api wordpress not working

I try to implement the Rawg.io API to my Wordpress Functions.php File but it doesn't work, i tried my code with another API and it is working fine, i think it has something to do with the API link Page='.$current_page.'
as you can see i created an custom post type to add the games to.
i also created custom fields with the right field keys.
My Report.txt file keeps returning current page = 1
function register_game_cpt() {
register_post_type( 'game', array(
'label' => 'Games',
'public' => true,
'capability_type' => 'post',
'supports' => array('title', 'editor', 'thumbnail'),
'taxonomies' => array('recordings', 'category', 'whatever', 'post_tag'),
));
}
add_action( 'init', 'register_game_cpt' );
// if ( ! wp_next_scheduled( 'update_game_list' ) ) {
// wp_schedule_event( time(), 'weekly', 'update_game_list' );
// }
add_action( 'update_game_list', 'get_games_from_api' );
add_action( 'wp_ajax_nopriv_get_games_from_api', 'get_games_from_api' );
add_action( 'wp_ajax_get_games_from_api', 'get_games_from_api' );
function get_games_from_api() {
$file = get_stylesheet_directory() . '/report.txt';
$current_page = ( ! empty( $_POST['current_page'] ) ) ? $_POST['current_page'] : 1;
$games = [];
// Should return an array of objects
$results = wp_remote_retrieve_body(wp_remote_get('https://api.rawg.io/api/games?key=/////////////////////&page='.$current_page.'&page_size=40'));
file_put_contents($file, "Current Page: " . $current_page. "\n\n", FILE_APPEND);
// turn it into a PHP array from JSON string
$results = json_decode( $results );
// Either the API is down or something else spooky happened. Just be done.
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
$games[] = $results;
foreach( $games[0] as $game ){
$game_slug = sanitize_title( $game->name . '-' . $game->id );
$existing_game = get_page_by_path( $game_slug, 'OBJECT', 'game' );
if( $existing_game === null ){
$inserted_game = wp_insert_post( [
'post_name' => $game_slug,
'post_title' => $game_slug,
'post_type' => 'game',
'post_status' => 'publish'
] );
if( is_wp_error( $inserted_game ) || $inserted_game === 0 ) {
die('Could not insert game: ' . $game_slug);
error_log( 'Could not insert game: ' . $game_slug );
continue;
}
// add meta fields
$fillable = [
'field_62684fc72d524' => 'count',
'field_6266cb41982d3' => 'name',
'field_6266cb4c982d4' => 'publishers',
'field_6266cb54982d5' => 'genres',
'field_6266cb64012e9' => 'platforms',
'field_6266cb722ebe8' => 'dates',
'field_626850012d525' => 'results',
];
foreach( $fillable as $key => $name ) {
update_field( $key, $game->$name, $inserted_game );
}
} else {
$existing_game_id = $existing_game->ID;
$exisiting_game_timestamp = get_field('updated_at', $existing_game_id);
if( $game->updated_at >= $exisiting_game_timestamp ){
$fillable = [
'field_62684fc72d524' => 'count',
'field_6266cb41982d3' => 'name',
'field_6266cb4c982d4' => 'publishers',
'field_6266cb54982d5' => 'genres',
'field_6266cb64012e9' => 'platforms',
'field_6266cb722ebe8' => 'dates',
'field_626850012d525' => 'results',
];
foreach( $fillable as $key => $name ){
update_field( $name, $game->$name, $existing_game_id);
}
}
}
}
$current_page = $current_page + 1;
wp_remote_post( admin_url('admin-ajax.php?action=get_games_from_api'), [
'blocking' => false,
'sslverify' => false, // we are sending this to ourselves, so trust it.
'body' => [
'current_page' => $current_page
]
] );
}

Dynamically populate two Gravityform select menus

I have two select menus built with Gravityforms and I am trying to use the filters below to dynamically populate them with WooCommerce order ids and WooCommerce products. The first foreach loop works as expected. I thought I could the replicate the loop for the second select menu. The queries work as I have tried them in a non-gravityforms form.
I suspect its the variable names I'm using in the second loop?
add_filter('gform_pre_render', 'populate_rma_dropdowns');
add_filter( 'gform_pre_validation', 'populate_rma_dropdowns' );
add_filter( 'gform_admin_pre_render', 'populate_rma_dropdowns' );
add_filter( 'gform_pre_submission_filter', 'populate_rma_dropdowns' );
function populate_rma_dropdowns( $form ) {
if ( $form['title'] != "RMA" ) return $form;
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'order-list' ) === false ) {
continue;
}
$query = new WC_Order_Query( array(
'limit' => -1,
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$orders = $query->get_orders();
$choices = array(array('text' => 'Please find your order number', 'value' => 0 ));
foreach ( $orders as $order ) {
$choices[] = array( 'text' => $order, 'value' => $order, 'isSelected' => false );
}
$field['choices'] = $choices;
}
foreach ( $form['fields'] as &$field2 ) {
if ( $field2->type != 'select' || strpos( $field2->cssClass, 'product-list' ) === false ) {
continue;
}
$args2 = array( 'post_type' => 'product' ,'posts_per_page' => 100);
$products = get_posts( $args2 );
$choices2 = array(array('text' => 'Please select product', 'value' => 0 ));
foreach ( $products as $product ) {
$choices2[] = array( 'text' => $product->post_title, 'value' => $product->post_title, 'isSelected' => false );
}
$field2['choices2'] = $choices2;
}
return $form;
}
Looks like you've made a small typo in the second loop. You're setting $field2['choices2'] rather than $field2['choices']
I've fixed this: in the second foreach loop I had added a number to the &$field array element
foreach ( $form['fields'] as &$field ) {
...
}
#Marc was correct as well about his suggestion as well. Both drop downs now work as required.

Save Woocommerce cart item custom data as order item meta data displaying it on orders and emails

Regarding Woocommerce. I have custom data that I am adding to the cart. In the functions.php file, I have the following function.
// Display cart item custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_on_cart_and_checkout', 10, 2 );
function display_cart_item_custom_on_cart_and_checkout( $cart_item_data, $cart_item ){
if( isset($cart_item['custom_data']['label0']) && isset($cart_item['custom_data']['value0']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label0'],
'value' => $cart_item['custom_data']['value0'],
);
}
if( isset($cart_item['custom_data']['label']) && isset($cart_item['custom_data']['value']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label'],
'value' => $cart_item['custom_data']['value'],
);
}
if( isset($cart_item['custom_data']['label2']) && isset($cart_item['custom_data']['value2']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label2'],
'value' => $cart_item['custom_data']['value2'],
);
}
if( isset($cart_item['custom_data']['label3']) && isset($cart_item['custom_data']['value3']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label3'],
'value' => $cart_item['custom_data']['value3'],
);
}
if( isset($cart_item['custom_data']['label4']) && isset($cart_item['custom_data']['value4']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label4'],
'value' => $cart_item['custom_data']['value4'],
);
}
if( isset($cart_item['custom_data']['label5']) && isset($cart_item['custom_data']['value5']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label5'],
'value' => $cart_item['custom_data']['value5'],
);
}
if( isset($cart_item['custom_data']['label6']) && isset($cart_item['custom_data']['value6']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label6'],
'value' => $cart_item['custom_data']['value6'],
);
}
if( isset($cart_item['custom_data']['label7']) && isset($cart_item['custom_data']['value7']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label7'],
'value' => $cart_item['custom_data']['value7'],
);
}
if( isset($cart_item['custom_data']['label8']) && isset($cart_item['custom_data']['value8']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label8'],
'value' => $cart_item['custom_data']['value8'],
);
}
if( isset($cart_item['custom_data']['label9']) && isset($cart_item['custom_data']['value9']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label9'],
'value' => $cart_item['custom_data']['value9'],
);
}
if( isset($cart_item['custom_data']['label10']) && isset($cart_item['custom_data']['value10']) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label10'],
'value' => $cart_item['custom_data']['value10'],
);
}
return $cart_item_data;
}
This works and the custom data is shown in the cart. However, the custom data does not show on the order and order email. I have seen, on Stackoverflow several answers that provide solutions to this problem but I cannot make them work for my situation. The solutions that I reference are.
Save and display order item custom meta data in Woocommerce
Display and save added custom cart item data on Woocommerce Cart, Checkout and Orders
Can anybody kindly show me what "my" function should be?
Thank you.
First you can optimize and compact your function this way:
// Display cart item custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_on_cart_and_checkout', 10, 2 );
function display_cart_item_custom_on_cart_and_checkout( $cart_item_data, $cart_item ){
$keys = array('0','','2','3','4','5','6','7','8','9','10'); // Fields numbers part keys array
// Loop through Fields numbers part keys array
foreach( $keys as $key ) {
if( isset($cart_item['custom_data']['label'.$key]) && isset($cart_item['custom_data']['value'.$key]) ) {
$cart_item_data[] = array(
'name' => $cart_item['custom_data']['label'.$key],
'value' => $cart_item['custom_data']['value'.$key],
);
}
}
return $cart_item_data;
}
Then to save all your custom cart item data as custom order item meta data and display it everywhere on orders and emails, use the following:
// Save cart item custom data as order item meta data and display it everywhere in Orders and email notifications
add_action('woocommerce_checkout_create_order_line_item', 'save_as_custom_order_item_meta_data', 10, 4 );
function save_as_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {
$keys = array('0','','2','3','4','5','6','7','8','9','10'); // Fields numbers part keys array()
// Loop through Fields numbers part keys array
foreach( $keys as $key ) {
if( isset( $values['custom_data']['label'.$key] ) && isset( $values['custom_data']['value'.$key] ) ) {
$item->update_meta_data( $values['custom_data']['label'.$key], $values['custom_data']['value'.$key] );
}
}
}
Code goes in functions.php file of the active child theme (or active theme). It should works.

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

Categories