Refresh shipping rates on city select field - wordpress

I am trying to update/refresh the shipping rates on city change, so far I have managed to do so only by refreshing the page manually.
add_action( 'woocommerce_package_rates', 'check_minimum_and_city', 10, 2 );
function check_minimum_and_city($rates, $package){
$selected_city = WC()->checkout->get_value('billing_city');
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
if(WC()->session->get( 'chosen_shipping_methods' )[0] == 'local_pickup:13'){
$minimum = 0;
}else{
$minimum_thirty = 100;
$minimum_fifty = 150;
$minimum_sixty = 200;
if(in_array($selected_city, $price_thirty)){
unset( $rates['flat_rate:18']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_thirty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_thirty )
)
);
}
}elseif(in_array($selected_city, $price_fifty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_fifty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_fifty )
)
);
}
}elseif(in_array($selected_city, $price_sixty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:18']);
if(WC()->cart->subtotal < $minimum_sixty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_sixty )
)
);
}
}
return $rates;
}
}
When I select a city field (dropdown custom list) I get the shipping cost I have made through the woocommerce settings but when I change it it does not update the rates.
add_filter( 'woocommerce_checkout_fields', 'city_dropdown_field' );
function city_dropdown_field( $fields ) {
$city_args = wp_parse_args( array(
'type' => 'select',
'options' => array(
'' => '',
'yavne' => 'יבנה',
'kfar-nagid' => 'כפר הנגיד',
'galiya' => 'גאליה',
'ben-zakai' => 'בן זכאי',
'beit-gamliel' => 'בית גמליאל',
'bnaya' => 'בניה',
'einot' => 'עינות',
'kfar-aviv' => 'כפר אביב',
'gan-shlomo' => 'גן שלמה',
'beit-oved' => 'בית עובד',
'aseret' => 'עשרת',
'givat-brener' => 'גבעת ברנר',
'irus' => 'אירוס',
'misgav-dov' => 'משגב דב',
'givton' => 'גיבתון',
'kerem-yavne' => 'כרם יבנה',
'beit-raban' => 'בית רבן',
'rehovot' => 'רחובות',
'beit-elezri' => 'בית אלעזרי',
'beit-hanan' => 'בית חנן',
'kvuzat-yavne' => 'קבוצת יבנה',
'kfar-bilu' => 'כפר בילו',
'bnei-darom' => 'בני דרום',
'nir-galim' => 'ניר גלים',
'kiryat-ekron' => 'קרית עקרון',
'gedera' => 'גדרה',
'nes-tziona' => 'נס ציונה',
'kanot' => 'כנות',
'netayim' => 'נטעים',
'gan-darom' => 'גן דרום',
'givatayim' => 'גבעתיים',
'ramat-gan' => 'רמת גן',
'tel-aviv-yafo' => 'תל אביב - יפו',
'bnei-brak' => 'בני ברק',
'ramat-hasharon' => 'רמת השרון',
'herzliya' => 'הרצליה',
'kfar-shmariyahu' => 'כפר שמריהו',
'rishpon' => 'רישפון',
'raanana' => 'רעננה',
'kfar-saba' => 'כפר סבא',
'bat-yam' => 'בת ים',
'hulon' => 'חולון',
'azur' => 'אזור',
'savion' => 'סביון',
'ganei-tikva' => 'גני תקווה',
'or-yehuda' => 'אור יהודה',
'kiryat-ono' => 'קרית אונו',
'yehud' => 'יהוד',
'petah-tikva' => 'פתח תקווה',
'rishon-letzion' => 'ראשון לציון',
'mishmar-hashiva' => 'משמר השבעה',
'gan-sorek' => 'גן שורק',
'beit-dagan' => 'בית דגן',
'ganot' => 'גנות',
'beit-hanan-irus' => 'בית חנן אירוס',
'hemed' => 'חמד',
'tsafria' => 'צפריה',
'beer-yaakov' => 'באר יעקב',
'netser-sireni' => 'נצר סירני',
'nir-tzvi' => 'ניר צבי',
'ramla' => 'רמלה',
'matsliax' => 'מצליח',
'clear' => true
),
), $fields['shipping']['shipping_city'] );
$fields['shipping']['shipping_city'] = $city_args;
$fields['billing']['billing_city'] = $city_args;
return $fields;
}
Tried using this jQuery but nothing does the work
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery( function($){
// Shipping fias code change & input events
$(document.body).on( 'change', 'select[name=billing_city]', function() {
console.log($(this).val());
});
});
</script>
<?php
endif;
}
Help is appreciated. :-)

I have Managed to resolve the issue and here is my solution, the answer was in corrected AJAX call and changing from multiple shipping rates to one and changing the rate by code.
add_action('woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
WC()->cart->calculate_shipping();
}
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery(document).on('change', 'select[name=billing_city]', function(){
var requested_city = jQuery(this).val();
ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl
var data = {
'action': 'get_and_set_shipping_rate',
'city': requested_city
};
jQuery.ajax({
type: "POST",
url: ajaxurl, // this will point to admin-ajax.php
data: data,
async: false,
success: function (response) {
console.log(response);
setTimeout(function (){
jQuery('.shipping_method:checked').trigger('change');
});
}
});
});
</script>
<?php
endif;
}
function get_and_set_shipping_rate(){
$shipping_city = $_POST['city'];
$shipping_cost = get_shipping_cost_by_city($shipping_city);
setcookie('shipping_city_cost', $shipping_cost, time() + (86400 * 30), '/');
$_COOKIE['shipping_city_cost'] = $shipping_cost;
echo $shipping_cost;
wp_die();
}
add_action( 'wp_ajax_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
add_action( 'wp_ajax_nopriv_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
function get_shipping_cost_by_city( $city ) {
$cost = 30;
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
// SET HERE the default cost (when "calculated cost" is not yet defined)
if(in_array($city, $price_thirty)){
$cost = 30;
}elseif(in_array($city, $price_fifty)){
$cost = 50;
}elseif(in_array($city, $price_sixty)){
$cost = 60;
}
return $cost;
}
add_filter('woocommerce_package_rates', 'update_shipping_costs_based_on_cart_session_custom_data', 10, 2);
function update_shipping_costs_based_on_cart_session_custom_data( $rates, $package ){
$selected_city = WC()->checkout->get_value('billing_city');
$calculated_cost = get_shipping_cost_by_city($selected_city);
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// SET HERE the default cost (when "calculated cost" is not yet defined)
$cost = '30';
// Iterating though Shipping Methods
foreach ( $rates as $rate_key => $rate_values ) {
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
// For "Flat rate" Shipping" Method only
if ( 'flat_rate' === $method_id ) {
if( ! empty( $calculated_cost ) ) {
$cost = $calculated_cost;
}
// Set the rate cost
$rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost, 2);
WC()->session->set( 'shipping_calculated_cost', $rates[$rate_id]->cost );
// Taxes rate cost (if enabled)
foreach ($rates[$rate_id]->taxes as $key => $tax){
if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
$taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost, 2 );
$has_taxes = true;
} else {
$has_taxes = false;
}
}
if( $has_taxes )
$rates[$rate_id]->taxes = $taxes;
}
}
return $rates;
}

Related

How can I add a check and not send an auto-reply to certain comments if the user fills in a custom field?

I'm using custom fields in the comment form "Did you like this book?" and "yes" and "no" values. I want to send 2 different auto-replies to a comment, if the user selects "yes" then the response is "Thank you for your kind recognition, customer's satisfaction is always our goal." and if "no" then the auto answer is "We'll strive to do better." I would appreciate any of your help...
//And this is how I send an auto reply to a comment
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $commentdata ){
$comment_parent = (int) $commentdata['comment_parent'];
// If a new comment is a reply to another comment, don't do anything
if ( $comment_parent !== 0 ) {
return;
}
//How do I add a response if the comment contains the value of the [likebook ] meta field???
if( !empty( $_POST['likebook'] ) {
return;
}
$commentdata = [
'comment_post_ID' => $commentdata['comment_post_ID'],
'comment_author' => 'admin',
'comment_author_email' => 'admin#example.com',
'comment_author_url' => 'http://example.com',
'comment_content' => 'Thank you for your kind recognition, customer satisfaction is always our goal.',
'comment_type' => 'comment',
'comment_parent' => $comment_ID,
'user_ID' => 1,
];
wp_new_comment( $commentdata );
}
try these,
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $comment ) {
if ( $comment['comment_parent'] !== 0 ) {
return;
}
if ( ! empty( $_POST['like'] ) ) {
if ( $_POST['like'] == 'dog' ) {
$msg = 'We are glad that you liked it!';
} else {
$msg = 'We will try to make this product better!';
}
$admins = get_super_admins();
$current_user = get_user_by( 'login', $admins[0] );
$data = array(
'comment_post_ID' => $comment['comment_post_ID'],
'comment_content' => $msg,
'comment_parent' => $comment_ID,
'user_id' => $current_user->ID,
'comment_author' => $current_user->user_login,
'comment_author_email' => $current_user->user_email,
'comment_author_url' => $current_user->user_url
);
$comment_id = wp_insert_comment( $data );
if ( is_wp_error( $comment_id ) ) {
throw new Exception( $comment_id );
}
}
}

Woocommerce, recognize "cash on delivery" not valid addresses

I'm trying to create a function.
My need is follow:
I have a cash on delivery payment method.
Sometime it happens that the shipping comes back because the address is wrong or not real.
Then I put this order in SPAM status.
I want that when I have a COD order, to check in all SPAM orders if address is present, if yes put the order in SPAM review status, so I can check it personally with client.
This is my code:
I put a check address button on "on hold" orders, that will check the addresses:
// 1. Create 2 new order statuses: SPAM and SPAM REVIEW
function create_new_order_statuses() {
register_post_status( 'wc-spam', array(
'label' => 'SPAM',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true
) );
register_post_status( 'wc-spam-review', array(
'label' => 'SPAM REVIEW',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true
) );
}
add_action( 'init', 'create_new_order_statuses' );
// 2. Register them in woocommerce
function add_spam_order_statuses_to_select( $order_statuses ) {
$order_statuses['wc-spam'] = 'SPAM';
$order_statuses['wc-spam-review'] = 'SPAM REVIEW';
return $order_statuses;
}
add_filter( 'wc_order_statuses', 'add_spam_order_statuses_to_select' );
add_action( 'woocommerce_admin_order_data_after_order_details', 'check_address_button_on_order_page' );
function check_address_button_on_order_page( $order ) {
if ( $order->get_status() === 'on-hold' ) {
$address = $order->get_address( 'shipping' );
echo '<button class="button check-address-button">Check Address</button>';
?>
<script>
jQuery('.check-address-button').click( function() {
var data = {
'action': 'check_address',
'address': <?php echo json_encode( $address ); ?>
};
jQuery.post(ajaxurl, data, function(response) {
if(response.found) {
alert('Match found, order status changed to "SPAM REVIEW"');
} else {
alert('No match found');
}
});
});
</script>
<?php
}
}
add_action( 'wp_ajax_check_address', 'check_address' );
function check_address() {
$address = json_decode( $_POST['address'] );
$spam_orders = wc_get_orders( array(
'status' => 'spam',
) );
foreach ( $spam_orders as $spam_order ) {
if ( $address == $spam_order->get_address( 'shipping' ) ) {
$order_id = $_POST['order_id'];
$order = wc_get_order( $order_id );
$order->update_status( 'spam-review' );
echo json_encode( array( 'found' => true ) );
wp_die();
}
}
echo json_encode( array( 'found' => false ) );
wp_die();
}
Of course doesn't work... any suggestion?

Add a checkbox as WooCommerce admin product option that disables payment gateways

I'm trying to unset COD payment gateway based on a custom product type based on the value from the checkbox, added as WooCommerce admin product option.
But it seems the code doesn't do anything with product type: doarcard.
If I set it to simple then it will work:
//new product type
add_filter("product_type_options", function ($product_type_options) {
$product_type_options['doarcard'] = array(
'id' => '_doarcard',
'wrapper_class' => 'show_if_simple show_if_variable',
'label' => __( 'Doar Card', 'woodmart' ),
'description' => __( 'Activare doar plata cu card sau transfer bancar', 'woodmart' ),
'default' => 'no');
return $product_type_options;
});
add_action("save_post_product", function ($post_ID, $product, $update) {
update_post_meta(
$product->ID
, "_doarcard"
, isset($_POST["_doarcard"]) ? "yes" : "no");
}, 10, 3);
//disable cod for doarcard
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {
if( is_admin() )
return $available_gateways;
$prod_doarcard = false;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = wc_get_product($cart_item['product_id']);
// Get the product types in cart (example)
if($product->is_type('doarcard')) $prod_doarcard = true;
}
if($prod_doarcard)
unset($available_gateways['cod']); // unset 'cod'
return $available_gateways;
}
Any advice?
A custom product type has nothing to do with your question. The value of the checkbox is a boolean with value yes or no
and based on that you can then unset the $payment_gateways
So use:
// Add a checkbox as WooCommerce admin product option
function filter_product_type_options( $product_type_options ) {
$product_type_options['doarcard'] = array(
'id' => '_doarcard',
'wrapper_class' => 'show_if_simple show_if_variable',
'label' => __( 'Doar Card', 'woocommerce' ),
'description' => __( 'Activare doar plata cu card sau transfer bancar', 'woocommerce' ),
'default' => 'no',
);
return $product_type_options;
}
add_filter( 'product_type_options', 'filter_product_type_options', 10, 1 );
// Save checkbox
function action_woocommerce_admin_process_product_object( $product ) {
$product->update_meta_data( '_doarcard', isset( $_POST['_doarcard'] ) ? 'yes' : 'no' );
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );
// Payment gateways
function filter_woocommerce_available_payment_gateways( $payment_gateways ) {
// Not on admin
if ( is_admin() ) return $payment_gateways;
// Initialize
$prod_doarcard = false;
// WC Cart
if ( WC()->cart ) {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Get meta
$doarcard = $cart_item['data']->get_meta( '_doarcard', true );
// Equal to yes = checked
if ( $doarcard == 'yes' ) {
$prod_doarcard = true;
// Product present with the right condition, so break the loop
break;
}
}
// True
if ( $prod_doarcard ) {
// Cod
if ( isset( $payment_gateways['cod'] ) ) {
unset( $payment_gateways['cod'] );
}
}
}
return $payment_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'filter_woocommerce_available_payment_gateways', 10, 1 );
you should use unset inside foreach loop like this:
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = wc_get_product($cart_item['product_id']);
// Get the product types in cart (example)
if($product->is_type('doarcard')){
unset($available_gateways['cod']); // unset 'cod'
}
}

ACF. How to update repeater field with files?

I am trying to update my repeater field from front end-with files. In case with one field file - it works. But when I'm trying to fill repeater with files it doesn't work.
// JS. Ajaxly sending files
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
$('.js-new-msg-send').click(function (e) {
e.preventDefault();
var form = document.forms.namedItem("new_theme");
var formData = new FormData(form);
formData.append('user_id', '<?php echo $userID; ?>');
formData.append('action', 'msg_to_acf');
var xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl, true);
xhr.send(formData);
})
I found function to handle files uploading to acf field and modified it to handle multiple files from $_FILES variable:
// FOR MULTIPLE FILES
if ( !empty($_FILES[$f]['name']) && is_array($_FILES[$f]['name']) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$file_list = array();
foreach ($_FILES[$f]['name'] as $key => $value) {
$temp_file = array(
'name' => $_FILES[$f]['name'][$key],
'type' => $_FILES[$f]['type'][$key],
'tmp_name' => $_FILES[$f]['tmp_name'][$key],
'error' => $_FILES[$f]['error'][$key],
'size' => $_FILES[$f]['size'][$key]
);
wp_update_attachment_metadata( $pid, $temp_file );
$file = wp_handle_upload( $temp_file , array('test_form' => FALSE, 'action' => 'editpost') );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($temp_file['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
$final_temp_arr = array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
array_push($file_list, $final_temp_arr);
}
}
return $file_list;
}
In final, I using this function to get an array of information with attach-id variable that I inserting to repeater.
$att = my_update_attachment( 'msg-file-list' , $post_id );
$files_final_list = array();
foreach ($att as $key => $val) {
array_push($files_final_list, $val['attach_id']);
}
$value_arr = array(
array(
"msg-author" => $user_name,
"msg-date" => $date,
"msg-read-check" => true,
"msg-cont" => $msg_cont,
'msg-file-list' => $files_final_list
)
);
update_field( 'test_file_list' , $files_final_list , $post_id );
I guess that mistake is in last part , where I trying to upload files to repeater. Can someone show me what I'am doing wrong? Thanks for helping.

Not displayed in the article list until you click "Update" on the dashboard

I am challenging Ajax implementation when replying by "BBPress".
However, reply posted in this manner is displayed in the dashboard, but it is not displayed in the loop of the replies list.
This will be displayed in the loop of the replies list only when you click "Update" on the dashboard.
I want to know the code that displays correctly in the loop.
This is my code:
my-reply.js
"use strict";
(function($){
$(document).on("click","#bbp_reply_submit", function() {
// get
var inputForum = '56'; //There is only one forum.
var inputTopic = $('#bbp_topic_id').val();
var inputTitle = $('#bbp-reply-form-info').text();
var inputContent = $('#bbp_reply_input').val();
var inputParent = $('#bbp_reply_to').val();
var inputIp = $('#my_reply_ip').val();
// Ajax
$.ajax({
url: MY_AJAX.api,
type: 'POST',
data: {
// action name
action: MY_AJAX.action,
// nonce
nonce: MY_AJAX.nonce,
// submit data
submitForum: inputForum,
submitTopic: inputTopic,
submitTitle: inputTitle,
submitContent: inputContent,
submitParent: inputParent,
submitIp: inputIp,
}
})
// scusess
.done(function( response ) {
alert('success'); // Actually, I will display reply instead of alerts.
})
// error
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('error');
});
});
})(jQuery);
functions.php
// nonce
function my_enqueue_scripts() {
$handle = 'my-script';
$jsFile = 'path/to/myscript.js';
wp_register_script($handle, $jsFile, ['jquery']);
$acrion = 'my-ajax-action';
wp_localize_script($handle, 'MY_AJAX', [
'api' => admin_url( 'admin-ajax.php' ),
'action' => $acrion,
'nonce' => wp_create_nonce( $acrion ),
]);
wp_enqueue_script($handle);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
// post reply
function my_ajax_event() {
$action = 'my-ajax-action';
if( check_ajax_referer($action, 'nonce', false) ) {
$submitForum = esc_html( $_POST['submitForum'] );
$submitTopic = esc_html( $_POST['submitTopic'] );
$submitTitle = esc_html( $_POST['submitTitle'] );
$submitContent = esc_html( $_POST['submitContent'] );
$submitParent = esc_html( $_POST['submitParent'] );
$submitIp = esc_html( $_POST['submitIp'] );
$submitTopicslug = esc_html( $_POST['submitTopicslug'] );
$page = get_post( $submitTopic );
$slug = $page->post_name;
$date = 'Y-m-d H:i:s';
$my_post = array(
'post_title' => (string)wp_strip_all_tags($_POST['submitTitle']),
'post_content' => (string)$_POST['submitContent'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'reply',
'meta_input' => array(
'_bbp_forum_id' => $_POST['submitForum'],
'_bbp_topic_id' => $_POST['submitTopic'],
'_bbp_reply_to' => $_POST['submitParent'],
'_bbp_author_ip' => $_POST['submitIp'],
'_edit_last' => get_current_user_id(),
'_bbp_topic_sort_desc' => 'dft',
'_bbp_sort_desc' => 'dft',
'_bbp_topic_sort_show_lead_topic' => 'dft',
'_bbp_topic_sort_show_lead_topic_forum' => 'dft',
'_wp_old_slug' => $slug,
'_bbp_last_active_time' => $date,
'_bbp_reply_count' => '',
'_bbp_engagement' => '',
'_bbp_reply_count_hidden' => '',
'_bbp_voice_count' => '',
)
);
wp_insert_post( $my_post );
} else {
status_header( '403' );
}
die();
}
add_action( 'wp_ajax_my-ajax-action', 'my_ajax_event' );
add_action( 'wp_ajax_nopriv_my-ajax-action', 'my_ajax_event' );

Resources