Add Custom Checkout Field (user input) to Order Data and User Meta - javascript

I made this code to give user the possibility to add more user data during the checkout field
(inspired by code posted here in Stackoverflow, however I can't find the source anymore)
PHP in functions.php:
add_action('woocommerce_before_order_notes','checkout_sections');
function checkout_sections(){
echo '<div>';
echo '<h3>'. __( 'Add New Member', 'woocommerce' ).'</h3>';
echo '<div class="row" id="readroot">';
echo '<label for="fullname[]">Name and Surname</label>';
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm new_row">';
echo '<input type="text" name="fullname[]" id="newfullname" placeholder="Name and Surname" class="form-control" required>';
echo '</div>';
echo '</div>';
echo '<br>';
echo '<label for="ALIMCode[]">A.L.IM. Membership Code</label>';
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm new_row">';
echo '<input type="text" name="ALIMCode[]" id="newalimcode" placeholder="A.L.IM. Membership Code" class="form-control" required>';
echo '</div>';
echo '</div>';
echo '<br>';
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a id="moreFields" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '<br>';
echo '<div class="row" id="writeroot"></div>';
echo '<div class="btn btn-sm btn-danger waves-effect waves-light pull-right" onclick="this.parentNode.parentNode;"><br>';
}
Here's Javascript code to clone the section.
JS:
var counter = 0;
//document.getElementById('moreFields').onclick = moreFields;
window.onload = loadEventListener();
function loadEventListener() {
let addRowAnchorTags = document.getElementsByClassName('moreFields');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'row';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields, insertHere);
setTimeout(function() {loadEventListener();})
}
//window.onload = moreFields;
Here's the result during the checkout phase:
WHAT I WANT TO ACCOMPLISH
I want to add this data in my backend when I see the order (woocommerce-order-data) and in the user meta data, here's the mockup in the picture below:
WHAT I'M DOING RIGHT NOW TO STORE DATA IN THE USER META DATA
Right now, when guests are making an order, the code in functions.php will make a new user and add all the custom fields in the user meta and order data.
Here's the code I'm using:
// create account when buy
function action_woocommerce_thankyou( $order_id ) {
// Determines whether the current visitor is a logged in user.
if ( is_user_logged_in() ) return;
// Get $order object
$order = wc_get_order( $order_id );
// Get the user email from the order
$order_email = $order->billing_email;
// Check if there are any users with the billing email as user or email
$email = email_exists( $order_email );
$user = username_exists( $order_email );
// If the UID is null, then it's a guest checkout (new user)
if ( $user == false && $email == false ) {
// Random password with 12 chars
$random_password = wp_generate_password();
// Firstname
$first_name = $order->get_billing_first_name();
// Lastname
$last_name = $order->get_billing_last_name();
// Role
$role = 'customer'; //'customer'
// Company Name
$companys = $order->get_billing_company();
// payment method (luca)
$paymentuser = $order->get_payment_method_title();
// Username (luca)
$usernames = $first_name.$last_name.$companys;
// Create new user with email as username, newly created password and userrole
$user_id = wp_insert_user(
array(
'user_email' => $order_email, //$order_mail
'user_login' => $usernames,
'user_pass' => $random_password,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => $role,
)
);
// Get all WooCommerce emails Objects from WC_Emails Object instance
$emails = WC()->mailer()->get_emails();
// Send WooCommerce "Customer New Account" email notification with the password
$emails['WC_Email_Customer_New_Account']->trigger( $user_id, $random_password, true );
// (Optional) WC guest customer identification
//update_user_meta( $user_id, 'guest', 'yes' );
//codice per recuperare url file upload
//$codedocu = $order->review_order_before_submit_upload_distinta_di_pagamento;
//$urldocu = 'https://alimdigital.org/?checkout_fields_get=';
//$urldocufine = '&checkout_fields_nonce=318982cbce';
//$codefinal = $urldocu.$codedocu.$urldocufine;
//$codedocu2 = $order->review_order_before_submit_upload_documento_identita;
//$codedocu3 = $order->review_order_before_submit_upload_selfie_con_documento_identita;
//$codedocu4 = $order->review_order_before_submit_upload_visura_camerale;
//$codedocu5 = $order->review_order_before_submit_upload_proposta_di_statuto;
//$codefinales = $urldocu.$codedocu2.$urldocufine;
//$codeselfie = $urldocu.$codedocu3.$urldocufine;
//$codevisura = $urldocu.$codedocu4.$urldocufine;
//$codestatuto = $urldocu.$codedocu5.$urldocufine;
// User's billing data
update_user_meta( $user_id, 'billing_tipologia_iscritto', $order->billing_tipologia_iscritto );
update_user_meta( $user_id, 'billing_nazione_sede_alim_di_riferimento', $order->billing_nazione_sede_alim_di_riferimento );
update_user_meta( $user_id, 'billing_sede_alim_di_riferimento', $order->billing_sede_alim_di_riferimento );
update_user_meta( $user_id, 'billing_categoria_socio', $order->billing_categoria_socio);
update_user_meta( $user_id, 'billing_address_1', $order->billing_address_1 );
update_user_meta( $user_id, 'billing_address_2', $order->billing_address_2);
update_user_meta( $user_id, 'billing_city', $order->billing_city );
update_user_meta( $user_id, 'billing_company', $order->billing_company );
update_user_meta( $user_id, 'billing_codice_ateco_codice_nace', $order->billing_codice_ateco_codice_nace );
update_user_meta( $user_id, 'billing_country', $order->billing_country );
update_user_meta( $user_id, 'billing_email', $order->billing_email );
update_user_meta( $user_id, 'billing_first_name', $order->billing_first_name );
update_user_meta( $user_id, 'billing_last_name', $order->billing_last_name );
update_user_meta( $user_id, 'billing_data_di_nascita', $order->billing_data_di_nascita );
update_user_meta( $user_id, 'billing_phone', $order->billing_phone );
update_user_meta( $user_id, 'billing_postcode', $order->billing_postcode );
update_user_meta( $user_id, 'billing_state', $order->billing_state );
update_user_meta( $user_id, 'billing_tipologia_territoriale_di_sede_alim_richiesta', $order->billing_tipologia_territoriale_di_sede_alim_richiesta );
update_user_meta( $user_id, 'billing_nazione', $order->billing_nazione);
update_user_meta( $user_id, 'billing_provincia', $order->billing_provincia);
update_user_meta( $user_id, 'billing_citta', $order->billing_citta);
update_user_meta( $user_id, 'billing_indirizzo', $order->billing_indirizzo);
update_user_meta( $user_id, 'billing_cap', $order->billing_cap);
update_user_meta( $user_id, 'billing_nazione_di_rilascio', $order->billing_nazione_di_rilascio);
update_user_meta( $user_id, 'billing_ente_di_rilascio', $order->billing_ente_di_rilascio);
update_user_meta( $user_id, 'billing_numero_documento', $order->billing_numero_documento);
update_user_meta( $user_id, 'billing_data_rilascio_documento', $order->billing_data_rilascio_documento );
update_user_meta( $user_id, 'billing_data_scadenza_documento', $order->billing_data_scadenza_documento );
update_user_meta( $user_id, 'billing_nome_cognome_presidente', $order->billing_nome_cognome_presidente );
update_user_meta( $user_id, 'billing_codice_iscrizione_alim', $order->billing_codice_iscrizione_alim );
update_user_meta( $user_id, 'billing_nome_cognome_vicepresidente', $order->billing_nome_cognome_vicepresidente );
update_user_meta( $user_id, 'billing_codice_iscrizione_alim2', $order->billing_codice_iscrizione_alim2 );
update_user_meta( $user_id, 'billing_nome_cognome_segretario', $order->billing_nome_cognome_segretario );
update_user_meta( $user_id, 'billing_codice_iscrizione_alim22', $order->billing_codice_iscrizione_alim22 );
update_user_meta( $user_id, 'billing_nome_cognome_tesoriere', $order->billing_nome_cognome_tesoriere );
update_user_meta( $user_id, 'billing_codice_iscrizione_alim222', $order->billing_codice_iscrizione_alim22 );
update_user_meta( $user_id, 'billing_nome_cognome_consigliere', $order->billing_nome_cognome_consigliere );
update_user_meta( $user_id, 'billing_codice_iscrizione_alim2222', $order->billing_codice_iscrizione_alim2222 );
// Link past orders to this newly created customer
wc_update_new_customer_past_orders( $user_id );
// Auto login
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
}
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );
function filter_woocommerce_thankyou_order_received_text( $str, $order ) {
// Determines whether the current visitor is a logged in user.
if ( is_user_logged_in() ) return;
// Get the user email from the order
$order_email = $order->billing_email;
// Check if there are any users with the billing email as user or email
$email = email_exists( $order_email );
$user = username_exists( $order_email );
// If the UID is null, then it's a guest checkout (new user)
if ( $user == false && $email == false ) {
// Link
$link = get_permalink( get_option( 'woocommerce_myaccount_page_id' ) );
// Format
$format_link = 'logged in';
// Append to orginal string
$str .= sprintf( __( ' An account has been automatically created for you and you are now %s. You will receive an email about this.', 'woocommerce' ), $format_link );
}
return $str;
}
add_filter( 'woocommerce_thankyou_order_received_text', 'filter_woocommerce_thankyou_order_received_text', 10, 2 );
If I made a mistake in providing the infos, let me know! Thanks in advance

I resolved this issue!
Here's what I've done
I made all the sections I needed not visible and with Javascript I made them appear by click. Every field completed is saved in the order data.
Here's the JS (first snippet) and php (second snippet) code:
window.onload = loadEventListener();
function loadEventListener() {
let addRowAnchorTags = document.getElementsByClassName('myFunction');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener2() {
let addRowAnchorTags = document.getElementsByClassName('myFunction2');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener3() {
let addRowAnchorTags = document.getElementsByClassName('myFunction3');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener4() {
let addRowAnchorTags = document.getElementsByClassName('myFunction4');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener5() {
let addRowAnchorTags = document.getElementsByClassName('myFunction5');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener6() {
let addRowAnchorTags = document.getElementsByClassName('myFunction6');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener7() {
let addRowAnchorTags = document.getElementsByClassName('myFunction7');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener8() {
let addRowAnchorTags = document.getElementsByClassName('myFunction8');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener9() {
let addRowAnchorTags = document.getElementsByClassName('myFunction9');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function loadEventListener10() {
let addRowAnchorTags = document.getElementsByClassName('myFunction10');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function myFunction() {
var x = document.getElementById("newmember");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction2() {
var x = document.getElementById("newmember2");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction3() {
var x = document.getElementById("newmember3");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction4() {
var x = document.getElementById("newmember4");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction5() {
var x = document.getElementById("newmember5");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction6() {
var x = document.getElementById("newmember6");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction7() {
var x = document.getElementById("newmember7");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction8() {
var x = document.getElementById("newmember8");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction9() {
var x = document.getElementById("newmember9");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
function myFunction10() {
var x = document.getElementById("newmember10");
if (x.style.display === "none") {
x.style.display = "block";
} endif
}
//
add_action('woocommerce_after_order_notes', 'customise_checkout_field', 20, 1 );
function customise_checkout_field( $checkout ){
$domain = 'woocommerce';
echo '<a onclick="myFunction()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<div id="newmember" style="display:none">
<h3>' . __( 'New Member', $domain ) . '</h3>';
woocommerce_form_field( '01_new_role', array(
'type' => 'text',
'class' => array( '01_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('01_new_role') );
woocommerce_form_field( '01_new_fullname', array(
'type' => 'text',
'class' => array( '01_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('01_new_fullname') );
woocommerce_form_field( '01_new_code', array(
'type' => 'text',
'class' => array( '01_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('01_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction2()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>';
echo '</div>';
echo '</div>'; // div newmember1 finish
echo '<div id="newmember2" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '02_new_role', array(
'type' => 'text',
'class' => array( '02_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('02_new_role') );
woocommerce_form_field( '02_new_fullname', array(
'type' => 'text',
'class' => array( '02_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('02_new_fullname') );
woocommerce_form_field( '02_new_code', array(
'type' => 'text',
'class' => array( '02_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('02_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction3()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>'; // div newmember2 finish
echo '<div id="newmember3" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '03_new_role', array(
'type' => 'text',
'class' => array( '03_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('03_new_role') );
woocommerce_form_field( '03_new_fullname', array(
'type' => 'text',
'class' => array( '03_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('03_new_fullname') );
woocommerce_form_field( '03_new_code', array(
'type' => 'text',
'class' => array( '03_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('03_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction4()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>'; // div newmember3 finish
echo '<div id="newmember4" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '04_new_role', array(
'type' => 'text',
'class' => array( '04_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('04_new_role') );
woocommerce_form_field( '04_new_fullname', array(
'type' => 'text',
'class' => array( '04_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('04_new_fullname') );
woocommerce_form_field( '04_new_code', array(
'type' => 'text',
'class' => array( '04_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('04_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction5()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>'; // div newmember4 finish
echo '<div id="newmember5" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '05_new_role', array(
'type' => 'text',
'class' => array( '05_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('05_new_role') );
woocommerce_form_field( '05_new_fullname', array(
'type' => 'text',
'class' => array( '05_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('05_new_fullname') );
woocommerce_form_field( '05_new_code', array(
'type' => 'text',
'class' => array( '05_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('05_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction6()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>';
echo '</div>';
echo '</div>'; // div newmember5 finish
echo '<div id="newmember6" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '06_new_role', array(
'type' => 'text',
'class' => array( '06_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('06_new_role') );
woocommerce_form_field( '06_new_fullname', array(
'type' => 'text',
'class' => array( '06_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('06_new_fullname') );
woocommerce_form_field( '06_new_code', array(
'type' => 'text',
'class' => array( '06_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('06_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction7()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>';
echo '</div>';
echo '</div>'; // div newmember6 finish
echo '<div id="newmember7" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '07_new_role', array(
'type' => 'text',
'class' => array( '07_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('07_new_role') );
woocommerce_form_field( '07_new_fullname', array(
'type' => 'text',
'class' => array( '07_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('07_new_fullname') );
woocommerce_form_field( '07_new_code', array(
'type' => 'text',
'class' => array( '07_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('07_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction8()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>';
echo '</div>';
echo '</div>'; // div newmember7 finish
echo '<div id="newmember8" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '08_new_role', array(
'type' => 'text',
'class' => array( '08_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('08_new_role') );
woocommerce_form_field( '08_new_fullname', array(
'type' => 'text',
'class' => array( '08_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('08_new_fullname') );
woocommerce_form_field( '08_new_code', array(
'type' => 'text',
'class' => array( '08_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('08_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction9()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>';
echo '</div>';
echo '</div>'; // div newmember8 finish
echo '<div id="newmember9" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '09_new_role', array(
'type' => 'text',
'class' => array( '09_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('09_new_role') );
woocommerce_form_field( '09_new_fullname', array(
'type' => 'text',
'class' => array( '09_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('09_new_fullname') );
woocommerce_form_field( '09_new_code', array(
'type' => 'text',
'class' => array( '09_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('09_new_code') );
echo '<div class="col-lg-2">';
echo '<div class="md-form form-sm">';
echo '<a onclick="myFunction10()" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
echo '<br><br>';
echo '</div>';
echo '</div>';
echo '</div>'; // div newmember9 finish
echo '<div id="newmember10" style="display:none">
<h3>' . __( '', $domain ) . '</h3>';
woocommerce_form_field( '10_new_role', array(
'type' => 'text',
'class' => array( '10_new_role form-row-wide' ),
'label' => __( 'Role', $domain ) ,
), $checkout->get_value('10_new_role') );
woocommerce_form_field( '10_new_fullname', array(
'type' => 'text',
'class' => array( '10_new_fullname form-row-wide' ),
'label' => __( 'Name and Surname', $domain ) ,
), $checkout->get_value('10_new_fullname') );
woocommerce_form_field( '10_new_code', array(
'type' => 'text',
'class' => array( '10_new_code form-row-wide' ),
'label' => __( 'A.L.IM. Membership Code', $domain ) ,
), $checkout->get_value('10_new_code') );
echo '</div>'; // div newmember10 finish
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
endif;
}
// Save custom checkout fields in the order meta data
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_fields_in_order_meta_data', 20, 2 );
function custom_checkout_fields_in_order_meta_data( $order, $data ) {
if ( isset($_POST['01_new_role']) && ! empty($_POST['01_new_role']) )
$order->update_meta_data( '01_new_role', sanitize_text_field($_POST['01_new_role']) );
if ( isset($_POST['01_new_fullname']) && ! empty($_POST['01_new_fullname']) )
$order->update_meta_data( '01_new_fullname', sanitize_text_field($_POST['01_new_fullname']) );
if ( isset($_POST['01_new_code']) && ! empty($_POST['01_new_code']) )
$order->update_meta_data( '01_new_code', sanitize_text_field($_POST['01_new_code']) );
if ( isset($_POST['02_new_role']) && ! empty($_POST['02_new_role']) )
$order->update_meta_data( '02_new_role', sanitize_text_field($_POST['02_new_role']) );
if ( isset($_POST['02_new_fullname']) && ! empty($_POST['02_new_fullname']) )
$order->update_meta_data( '02_new_fullname', sanitize_text_field($_POST['02_new_fullname']) );
if ( isset($_POST['02_new_code']) && ! empty($_POST['02_new_code']) )
$order->update_meta_data( '02_new_code', sanitize_text_field($_POST['02_new_code']) );
if ( isset($_POST['03_new_role']) && ! empty($_POST['03_new_role']) )
$order->update_meta_data( '03_new_role', sanitize_text_field($_POST['03_new_role']) );
if ( isset($_POST['03_new_fullname']) && ! empty($_POST['03_new_fullname']) )
$order->update_meta_data( '03_new_fullname', sanitize_text_field($_POST['03_new_fullname']) );
if ( isset($_POST['03_new_code']) && ! empty($_POST['03_new_code']) )
$order->update_meta_data( '03_new_code', sanitize_text_field($_POST['03_new_code']) );
if ( isset($_POST['04_new_role']) && ! empty($_POST['04_new_role']) )
$order->update_meta_data( '04_new_role', sanitize_text_field($_POST['04_new_role']) );
if ( isset($_POST['04_new_fullname']) && ! empty($_POST['04_new_fullname']) )
$order->update_meta_data( '04_new_fullname', sanitize_text_field($_POST['04_new_fullname']) );
if ( isset($_POST['04_new_code']) && ! empty($_POST['04_new_code']) )
$order->update_meta_data( '04_new_code', sanitize_text_field($_POST['04_new_code']) );
if ( isset($_POST['05_new_role']) && ! empty($_POST['05_new_role']) )
$order->update_meta_data( '05_new_role', sanitize_text_field($_POST['05_new_role']) );
if ( isset($_POST['05_new_fullname']) && ! empty($_POST['05_new_fullname']) )
$order->update_meta_data( '05_new_fullname', sanitize_text_field($_POST['05_new_fullname']) );
if ( isset($_POST['05_new_code']) && ! empty($_POST['05_new_code']) )
$order->update_meta_data( '05_new_code', sanitize_text_field($_POST['05_new_code']) );
if ( isset($_POST['06_new_role_role']) && ! empty($_POST['06_new_role_role']) )
$order->update_meta_data( '06_new_role', sanitize_text_field($_POST['06_new_role']) );
if ( isset($_POST['06_new_fullname']) && ! empty($_POST['06_new_fullname']) )
$order->update_meta_data( '06_new_fullname', sanitize_text_field($_POST['06_new_fullname']) );
if ( isset($_POST['06_new_code']) && ! empty($_POST['06_new_code']) )
$order->update_meta_data( '06_new_code', sanitize_text_field($_POST['06_new_code']) );
if ( isset($_POST['07_new_role']) && ! empty($_POST['07_new_role']) )
$order->update_meta_data( '07_new_role', sanitize_text_field($_POST['07_new_role']) );
if ( isset($_POST['07_new_fullname']) && ! empty($_POST['07_new_fullname']) )
$order->update_meta_data( '07_new_fullname', sanitize_text_field($_POST['07_new_fullname']) );
if ( isset($_POST['07_new_code']) && ! empty($_POST['07_new_code']) )
$order->update_meta_data( '07_new_code', sanitize_text_field($_POST['07_new_code']) );
if ( isset($_POST['08_new_role']) && ! empty($_POST['08_new_role']) )
$order->update_meta_data( '08_new_role', sanitize_text_field($_POST['08_new_role']) );
if ( isset($_POST['08_new_fullname']) && ! empty($_POST['08_new_fullname']) )
$order->update_meta_data( '08_new_fullname', sanitize_text_field($_POST['08_new_fullname']) );
if ( isset($_POST['08_new_code']) && ! empty($_POST['08_new_code']) )
$order->update_meta_data( '08_new_code', sanitize_text_field($_POST['08_new_code']) );
if ( isset($_POST['09_new_role']) && ! empty($_POST['09_new_role']) )
$order->update_meta_data( '09_new_role', sanitize_text_field($_POST['09_new_role']) );
if ( isset($_POST['09_new_fullname']) && ! empty($_POST['09_new_fullname']) )
$order->update_meta_data( '09_new_fullname', sanitize_text_field($_POST['09_new_fullname']) );
if ( isset($_POST['09_new_code']) && ! empty($_POST['09_new_code']) )
$order->update_meta_data( '09_new_code', sanitize_text_field($_POST['09_new_code']) );
if ( isset($_POST['10_new_role']) && ! empty($_POST['10_new_role']) )
$order->update_meta_data( '10_new_role', sanitize_text_field($_POST['10_new_role']) );
if ( isset($_POST['10_new_fullname']) && ! empty($_POST['10_new_fullname']) )
$order->update_meta_data( '10_new_fullname', sanitize_text_field($_POST['10_new_fullname']) );
if ( isset($_POST['10_new_code']) && ! empty($_POST['10_new_code']) )
$order->update_meta_data( '10_new_code', sanitize_text_field($_POST['10_new_code']) );
}

Related

How can i show Google Adsense Ads in my Wordpress Site Homepage, in between posts Grid layout, not inside posts

How can I show "Google Ad-sense Ads" in my "WordPress" Site "Homepage", in between posts Grid layout? not inside posts. For Homepage King-composer plugin is used and want to show 'Google Ads' after specific posts only as may ads as possible. Please Help me with this. I tried many ways and used some plugins also. but nothing works.
Attaching Code file which we want to code to display Google ads.. and also attaching Homepage screenshot where I want to show ads in between the grid layout posts, not inside posts... Help me, please.
<?php
extract( shortcode_atts( array(
'ads_source' => 'by_choice',
'topads' => 'no',
'post_ids' => '',
'post_number' => '6',
'category_ids' => '',
'location_ids' => '',
'type' => '',
'orderby' => '',
'order' => '',
'style' => 'grid',
'slider' => 'no',
'visible_items' => '',
'autoplay_speed' => '',
'double_row' => '',
'items_in_row' => '4'
), $atts ) );
if( $ads_source == 'by_choice' ){
$args = array(
'post__in' => explode( ',', $post_ids ),
'orderby' => 'post__in'
);
}
else{
$args = array(
'posts_per_page' => $post_number,
'orderby' => $orderby,
'order' => $order,
);
if( $topads == 'yes' ){
$args['post__in'] = adifier_topads_ids_list();
}
if( !empty( $category_ids ) ){
$args['tax_query'] = array(
array(
'taxonomy' => 'advert-category',
'terms' => explode( ',', $category_ids )
)
);
}
if( !empty( $location_ids ) ){
$args['tax_query'] = array(
array(
'taxonomy' => 'advert-location',
'terms' => explode( ',', $location_ids )
)
);
}
}
if( !empty( $type ) ){
$args['type'] = $type;
}
$args['post_status'] = 'publish';
$adverts = new Adifier_Advert_Query( $args );
if( $adverts->have_posts() ){
if( $style == 'big_slider' ){
?>
<div class="adverts-big-slider owl-carousel">
<?php
while( $adverts->have_posts() ){
$adverts->the_post();
?>
<div class="white-block hover-shadow">
<a href="<?php the_permalink() ?>" class="advert-media">
<?php adifier_get_advert_image('adifier-single-slider') ?>
</a>
<div class="white-block-content">
<?php include( get_theme_file_path( 'includes/advert-boxes/top-meta.php' ) ) ?>
<?php include( get_theme_file_path( 'includes/advert-boxes/title.php' ) ) ?>
<?php include( get_theme_file_path( 'includes/advert-boxes/bottom-meta.php' ) ) ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
else{
$max = $double_row == 'yes' ? 2 : 1;
$counter = 0;
?>
<div class="adverts-list clearfix <?php echo $slider == 'yes' ? esc_attr( 'adverts-slider owl-carousel' ) : esc_attr( 'af-items-'.$items_in_row ) ?>" data-visibleitems="<?php echo esc_attr( $visible_items ) ?>" data-autoplay="<?php echo esc_attr( $autoplay_speed ) ?>">
<div class="af-item-wrap">
<?php
while( $adverts->have_posts() ){
$adverts->the_post();
if( $max == $counter ){
?>
</div><div class="af-item-wrap">
<?php
$counter = 0;
}
$counter++;
if( $style == 'list' ){
$limit = 80;
}
include( get_theme_file_path( 'includes/advert-boxes/'.$style.'.php' ) );
}
?>
</div>
</div>
<?php
}
?>
<?php
}
wp_reset_postdata();
?>
My Home Page image screenshot where I want to show Google ads in between Grid Layout :

How to Add Ajax Pagination On Ajax Post filter Result

I am developing a website with taxonomy filter. I have created taxonomy widget like this
Tax A
Tax B
Tax C
Tax D
And place one apply filter below that when i clicking apply filter it will filter post by Ajax request and Append Post on HTML. Now I want to show Ajax load More Button on Filter Ajax result i have added some code for load more but its fetching post from all taxonomy. I want to work the load more like this if i filter Tax A and i want to show post in Tax A taxonomy on load More.
Following are my code:
On Function.php
function misha_my_load_more_button_scripts() {
global $wp_query;
wp_register_script( 'misha_filter_scripts', get_stylesheet_directory_uri().'/custom.js', array('jquery'), '1.0.0', true );
wp_enqueue_script( 'misha_filter_scripts' );
// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'misha_filter_scripts', 'misha_loadmore_button_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
) );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_button_scripts', 1 );
//functon for ajax blog filter
add_action('wp_ajax_myfilter', 'wph_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'wph_filter_function');
function wph_filter_function(){
// $CurrentPage = get_query_var('paged');
//$paged = $_POST['paged'];
//wp_reset_postdata();
if( isset( $_POST['categoryfilter'] ) ){
$category_post = $_POST['categoryfilter'];
}
if( isset( $_POST['categoryfilter_prod'] ) ){
$category_product = $_POST['categoryfilter_prod'];
}
if( isset( $_POST['categoryfilter_resource'] ) ){
$category_resource = $_POST['categoryfilter_resource'];
}
//var_dump($category_post);
//var_dump($category_product);
//var_dump($category_resource);
$tax_query = array('relation' => 'AND');
if (isset($_POST['categoryfilter']))
{
$tax_query[] = array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category_post
);
}
if (isset($_POST['categoryfilter_prod']))
{
$tax_query[] = array(
'taxonomy' => 'cat_product',
'field' => 'id',
'terms' => $category_product
);
}
if (isset($_POST['categoryfilter_resource']))
{
$tax_query[] = array(
'taxonomy' => 'resource',
'field' => 'id',
'terms' => $category_resource
);
}
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' =>30,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $CurrentPage,
'tax_query' => $tax_query,
)
);
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
?>
<?php if( get_field('show_login_only') ): ?>
<div class="res-entry">
<div class="row">
<div class="col-md-4">
<?php
if ( has_post_thumbnail()) the_post_thumbnail('resource-blog');
?>
</div>
<div class="col-md-8 blog-details">
<a class="related-title" href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<br>
<div class="posted-date">
<?php palliance_posted_on_noslash(); ?>
</div>
<div class="post-less">
<?php echo excerpt(20); ?>
</div>
</div>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
wp_reset_postdata();
if ( $query->max_num_pages > 1 ) :
echo '<div id="misha_loadmore">More posts</div>'; // you can use <a> as well
endif;
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_loadmorebutton', 'misha_loadmore_button_ajax_handler');
add_action('wp_ajax_nopriv_loadmorebutton', 'misha_loadmore_button_ajax_handler');
function misha_loadmore_button_ajax_handler(){
$args = unserialize( stripslashes( $_POST['query']) );
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
$query = new WP_Query( $args );
global $wp_query;
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
?>
<div class="res-entry">
<div class="row">
<div class="col-md-4">
<?php
if ( has_post_thumbnail()) the_post_thumbnail('resource-blog');
?>
</div>
<div class="col-md-8 blog-details">
<a class="related-title" href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<br>
<div class="posted-date">
<?php palliance_posted_on_noslash(); ?>
</div>
<div class="post-less">
<?php echo excerpt(20); ?>
</div>
</div>
</div>
</div>
<?php
endwhile;
else :
get_template_part( 'template-parts/content', 'none' );
endif;
die;
}
Jquery Code is following
jQuery(function($){
$('#filter').on('change', 'input[type=checkbox]', function() {
setTimeout(function(){
// $(".filter-btn").click();
},1);
});
$('#clear-all-filter-1').click(function() {
$(".filter-form input[type=checkbox]").attr("checked", false);
setTimeout(function(){
$(".filter-btn").click();
},1);
});
$('#clear-all-filter-2').click(function() {
$(".filter-form input[type=checkbox]").attr("checked", false);
setTimeout(function(){
$(".filter-btn").click();
},1);
});
$('#filter').submit(function(){
var filter = $('#filter');
var response = $('#response');
$.ajax({
//url:filter.attr('action'),
url : misha_loadmore_button_params.ajaxurl,
data : $('#filter').serialize(), // form data
// dataType : 'json', // this data type allows us to receive objects from the server
type : 'POST',
beforeSend:function(xhr){
filter.find('.filter-btn').text('Processing...'); // changing the button label
//response.find('.res-entry').css("background-color", "yellow"); // changing the button label
},
success:function(data){
misha_loadmore_button_params.current_page = 1;
// set the new query parameters
misha_loadmore_button_params.posts = data.posts;
// set the new max page parameter
misha_loadmore_button_params.max_page = data.max_page;
filter.find('.filter-btn').text('Apply filter'); // changing the button label back
//$('#response').html(data); // insert data
$("#response").html('');
$("#response").append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
return false;
});
});
jQuery(document).ready( function($) {
/*
* Load More
*/
$('#misha_loadmore').click(function(){
$.ajax({
url : misha_loadmore_button_params.ajaxurl, // AJAX handler
data : {
'action': 'loadmorebutton', // the parameter for admin-ajax.php
'query': misha_loadmore_button_params.posts, // loop parameters passed by wp_localize_script()
'page' : misha_loadmore_button_params.current_page // current page
},
type : 'POST',
beforeSend : function ( xhr ) {
$('#misha_loadmore').text('Loading...'); // some type of preloader
},
success : function( data ){
if( data ) {
$('#misha_loadmore').text( 'More posts' );
$('#response').append(data); // insert new posts
misha_loadmore_button_params.current_page++;
if ( misha_loadmore_button_params.current_page == misha_loadmore_button_params.max_page )
$('#misha_loadmore').hide(); // if last page, HIDE the button
} else {
$('#misha_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
});
I think you need to use json_encode to get the current $query_var for the selected filters!
Added ob_start(); and ob_get_contents(); to pass posts to variable
Change you filter function with this and tell me if it work.
I hope it help!
//functon for ajax blog filter
add_action('wp_ajax_myfilter', 'wph_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'wph_filter_function');
function wph_filter_function(){
// $CurrentPage = get_query_var('paged');
//$paged = $_POST['paged'];
//wp_reset_postdata();
if( isset( $_POST['categoryfilter'] ) ){
$category_post = $_POST['categoryfilter'];
}
if( isset( $_POST['categoryfilter_prod'] ) ){
$category_product = $_POST['categoryfilter_prod'];
}
if( isset( $_POST['categoryfilter_resource'] ) ){
$category_resource = $_POST['categoryfilter_resource'];
}
//var_dump($category_post);
//var_dump($category_product);
//var_dump($category_resource);
$tax_query = array('relation' => 'AND');
if (isset($_POST['categoryfilter']))
{
$tax_query[] = array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category_post
);
}
if (isset($_POST['categoryfilter_prod']))
{
$tax_query[] = array(
'taxonomy' => 'cat_product',
'field' => 'id',
'terms' => $category_product
);
}
if (isset($_POST['categoryfilter_resource']))
{
$tax_query[] = array(
'taxonomy' => 'resource',
'field' => 'id',
'terms' => $category_resource
);
}
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' =>30,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $CurrentPage,
'tax_query' => $tax_query,
)
);
if( $query->have_posts() ) :
ob_start();
while( $query->have_posts() ): $query->the_post();
?>
<?php if( get_field('show_login_only') ): ?>
<div class="res-entry">
<div class="row">
<div class="col-md-4">
<?php
if ( has_post_thumbnail()) the_post_thumbnail('resource-blog');
?>
</div>
<div class="col-md-8 blog-details">
<a class="related-title" href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<br>
<div class="posted-date">
<?php palliance_posted_on_noslash(); ?>
</div>
<div class="post-less">
<?php echo excerpt(20); ?>
</div>
</div>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
wp_reset_postdata();
if ( $query->max_num_pages > 1 ) :
echo '<div id="misha_loadmore">More posts</div>'; // you can use <a> as well
endif;
$content = ob_get_contents(); // we pass the posts to variable
ob_end_clean(); // clear the buffer
else :
ob_start(); // start the buffer to capture the output of the template
get_template_part( 'template-parts/content', 'none' );
$content = ob_get_contents(); // pass the output to variable
ob_end_clean();
endif;
echo json_encode( array(
'posts' => json_encode( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'found_posts' => $wp_query->found_posts,
'content' => $content
));
die();
}

DataTables warning: table id=tableProduct - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

The same code and functionality is working properly on LOCALHOST without any error. But on my Online server i am getting above error message.
so here is my code details
in controller this is the code:
public function listproduct(){
$table = 'fc_products';
$primaryKey = 'id';
$columns = array(
array( 'db' => 'code', 'dt' => 0 ),
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'category', 'dt' => 2 ),
array( 'db' => 'description', 'dt' => 3 ),
array( 'db' => 'tax', 'dt' => 4 ),
array( 'db' => 'price', 'dt' => 5,
'formatter' => function($d, $row ) {
return $ret = number_format((float)$d, $this->setting->decimals, '.', '').' '.$this->setting->currency;
}
),
array( 'db' => 'photo', 'dt' => 6 ,
'formatter' => function( $d, $row ) {
$action ='<div class="btn-group">';
$yesiam = label('yesiam');
$areyousure = label('Areyousure');
$viewproduct = label('Viewproduct');
$edit = label('Edit');
$modifyStock = label("ModifyStock");
$viewImage = label("ViewImage");
$printBarcodes = label('printBarcodes');
$row_id = $row['id'];
$row_color = $row['color'];
$row_code = $row['code'];
if($this->user->role === "admin"){
$action .="<a class=\"btn btn-default\" href=\"javascript:void(0)\" data-toggle=\"popover\" data-placement=\"left\" data-html=\"true\" title='$areyousure' data-content=\"<a class= 'btn btn-danger' href='products/delete/{$row_id}'>$yesiam</a>\"><i class='fa fa-times'></i></a>";
}
$action .="<a class=\"btn btn-default\" href=\"javascript:void(0)\" onclick=\"Viewproduct($row_id)\"><i class=\"fa fa-file-text\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"$viewproduct\"></i></a>";
$action .="<a class=\"btn btn-default\" href=\"products/edit/$row_id\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"$edit\"><i class=\"fa fa-pencil\"></i></a>";
if($this->user->role === "admin" && $row['type'] === 0 ){
$action .= "<a class=\"btn btn-default\" href=\"javascript:void(0)\" onclick=\"modifystock($row_id)\"><i class=\"fa fa-tasks\" data-toggle=\"tooltip\" data-placement=\"top\" title='$modifyStock'></i></a>";
}
if($d){
$action .= "<a class=\"btn $row_color white open-modalimage\" data-id=\"$d\" href=\"\" data-toggle=\"modal\" data-target=\"#ImageModal\"><i class=\"fa fa-picture-o\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"$viewImage\"></i></a>";
}
$action .= "<a class=\"btn btn-default\" href=\"javascript:void(0)\" data-toggle=\"modal\" data-target=\"#barcode\" onclick=\"productBcode = $row_code\"><i class=\"fa fa-barcode\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"$printBarcodes\"></i></a>";
$action .= "</div>";
/*$action = "<div class=\"btn-group\">
<a class=\"btn btn-default\" href=\"javascript:void(0)\" data-toggle=\"popover\" data-placement=\"left\" data-html=\"true\" title=\"\" data-content=\"<a class="btn btn-danger" href="products/delete/11597">Yes, delete it!</a>\" data-original-title=\"Are you sure ?\"><i class=\"fa fa-times\"></i></a></div>";
*/
return $action;
}
),
array( 'db' => 'color', 'dt' => 7 ),
array( 'db' => 'id', 'dt' => 8 ),
array( 'db' => 'type', 'dt' => 9 ),
);
$this->load->database();
// SQL server connection information
$sql_details = array(
'user' => $this->db->username,
'pass' => $this->db->password,
'db' => $this->db->database,
'host' => $this->db->localhost
);
require( 'traits/ssp.class.php');
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
exit();
}
public function loadProducts(){
$offset = $this->input->post('offset');
$products = Product::find('all', array('limit'=>200,'offset'=>$offset));
require( 'traits/load.php');
exit();
//$this->content_view = 'pos';
}
in js script :
var tableProduct = $('#tableProduct').DataTable( {
'processing' : true,
'serverSide' : true,
'ajax' : 'index.php/products/listproduct',
//'ajax' : "<?php echo site_url('products/listproduct')?>/",
dom: 'T<"clear">lfrtip',
tableTools: {
"sSwfPath": "https://cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf",
'bProcessing' : true,
"aButtons": [
"xls",
{
"sExtends": "pdf",
"sPdfOrientation": "landscape",
"sPdfMessage": ""
},
"print"
]
},
drawCallback: function() {
$('[data-toggle="popover"]').popover();
}
});
} );

How do I add a background/highlight color to specific words in a Wordpress Chatroom plugin?

Outline-
I am running a Wordpress v4 installation and have installed a chatroom plugin: https://github.com/wp-plugins/chat-room (full code below).
I want to be able to highlight specific words that appear in chat when a user posts a message. For example, every time a user posts a message with the word "Dog" in it, it would have background colour so that it can be highlighted to everyone.
As the HTML output from the plugin is plain HTML, the best solution I have found is the following working example: https://jsfiddle.net/4ny8adpg/2/.
The Problem-
When using the script from the jsfiddle above on the page where the chatroom is placed, it seems that the script either cannot find the words or cannot replace them. I do not understand why, as the HTML that is output from the chatroom scripts is plain HTML (exactly as shown in the jsfiddle). It's also worth noting that the script will find and replace words that are written into the HTML source on the same page.
The Code-
Below is the PHP, Javascript and example HTML output for the chat-room plugin. I did not write this plugin and the original author offers very very limited support.
PHP:
Class Chatroom {
function __construct() {
register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
add_action( 'init', array( $this, 'register_post_types' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
add_filter( 'the_content', array( $this, 'the_content_filter' ) );
}
function activation_hook() {
$this->register_post_types();
flush_rewrite_rules();
}
function deactivation_hook() {
flush_rewrite_rules();
}
function register_post_types() {
$labels = array(
'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
'add_new' => _x( 'Add New', 'book', 'chatroom' ),
'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
'new_item' => __( 'New Chat Room', 'chatroom' ),
'all_items' => __( 'All Chat Rooms', 'chatroom' ),
'view_item' => __( 'View Chat Room', 'chatroom' ),
'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
'parent_item_colon' => '',
'menu_name' => __( 'Chat Rooms', 'chatroom' )
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_nav_menus' => true,
'supports' => array( 'title' )
);
register_post_type( 'chat-room', $args );
}
function enqueue_scripts() {
global $post;
if ( $post->post_type != 'chat-room' )
return;
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
}
function maybe_create_chatroom_log_file( $post_id, $post ) {
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return;
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
if ( file_exists( $log_filename ) )
return;
wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, json_encode( array() ) );
// TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
}
function define_javascript_variables() {
global $post;
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return; ?>
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
var chatroom_slug = '<?echo $post->post_name; ?>';
</script>
<?php
}
function ajax_check_updates_handler() {
$upload_dir = wp_upload_dir();
$log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
foreach ( $messages as $key => $message ) {
if ( $message->id <= $_POST['last_update_id'] )
unset( $messages[$key] );
}
$messages = array_values( $messages );
echo json_encode( $messages );
die;
}
/**
* AJAX server-side handler for sending a message.
*
* Stores the message in a recent messages file.
*
* Clears out cache of any messages older than 10 seconds.
*/
function ajax_send_message_handler() {
$current_user = wp_get_current_user();
$this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
die;
}
function save_message( $chatroom_slug, $user_id, $content ) {
$user = get_userdata( $user_id );
if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
// Set random color for each user
$red = rand( 0, 16 );
$green = 16 - $red;
$blue = rand( 0, 16 );
$user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
update_user_meta( $user_id, 'user_color', $user_text_color );
}
$content = esc_attr( $content );
// Save the message in recent messages file
$log_filename = $this->get_log_filename( $chatroom_slug );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$last_message_id = 0; // Helps determine the new message's ID
foreach ( $messages as $key => $message ) {
if ( time() - $message->time > 10 ) {
$last_message_id = $message->id;
unset( $messages[$key] );
}
else {
break;
}
}
$messages = array_values( $messages );
if ( ! empty( $messages ) )
$last_message_id = end( $messages )->id;
$new_message_id = $last_message_id + 1;
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
// Save the message in the daily log
$log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
}
function write_log_file( $log_filename, $content ) {
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, $content );
}
function get_log_filename( $chatroom_slug, $date = 'recent' ) {
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
return $log_filename;
}
function parse_messages_log_file( $log_filename ) {
$upload_dir = wp_upload_dir();
$handle = fopen( $log_filename, 'r' );
$contents = fread( $handle, filesize( $log_filename ) );
fclose( $handle );
return $contents;
}
function the_content_filter( $content ) {
global $post;
if ( $post->post_type != 'chat-room' )
return $content;
if ( ! is_user_logged_in() ) {
?>You need to be logged in to participate in the chatroom.<?php
return;
}
?>
<div class="chat-container">
</div>
<textarea class="chat-text-entry"></textarea>
<?php
return '';
}
}
$chatroom = new Chatroom();
Javascript:
var last_update_received = 0;
function chatroom_check_updates() {
jQuery.post(
ajaxurl,
{
action: 'check_updates',
chatroom_slug: chatroom_slug,
last_update_id: last_update_id
},
function (response) {
chats = jQuery.parseJSON( response );
if ( chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
}
}
);
setTimeout( "chatroom_check_updates()", 1000 );
}
function chatroom_strip_slashes(str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
jQuery(document).ready( function() {
last_update_id = 0;
chatroom_check_updates();
jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
if ( event.charCode == 13 || event.keyCode == 13 ) {
chatroom_send_message();
return false;
}
});
});
function chatroom_send_message() {
message = jQuery( 'textarea.chat-text-entry' ).val();
jQuery( 'textarea.chat-text-entry' ).val('');
jQuery.post(
ajaxurl,
{
action: 'send_message',
chatroom_slug: chatroom_slug,
message: message
},
function (response) {
}
);
}
HTML Output:
<div class="chat-container">
<div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
<div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
<div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
</div>
My question really is, am I missing something obvious? Any help towards a solution will be greatly appreciated!
EDIT: To provide better explanation.
EDIT 2: Added script output as requested
Var. Chats in chatroom_check_updates() Output:
[{"id":129,"time":1428340673,"sender":1,"contents":"What is your favourite animal?","html":"<div class=\"chat chat-message-129\"><strong style=\"color: #840;\">User 1<\/strong>: What is your favourite animal?<\/div>"},
{"id":130,"time":1428351683,"sender":2,"contents":"I vote for #dog.","html":"<div class=\"chat chat-message-130\"><strong style=\"color: #840;\">User 2<\/strong>: I vote for #dog.<\/div>"},
{"id":131,"time":1428352376,"sender":3,"contents":"I have a #cat!","html":"<div class=\"chat chat-message-131\"><strong style=\"color: #840;\">User 3<\/strong>: I have a #cat!<\/div>"}]

Highlighting words in Javascript - Why won't they stay highlighted after the page fully loads?

So this is a question following on from the awesome work #Drakes has done on this question previously: Highlighting words with Javascript, what am I missing?.
The solution is to highlight words by finding "#cat" or "#dog" and replacing them with
<span class='cat'>#CAT</span>
or
<span class='dog'>#DOG</span>
Then we can control the background colour of the span tag with CSS.
This works perfectly, however the background colour only remains for a brief moment before disappearing. Upon a closer look, it seems the span tags are applied correctly and then removed again suddenly.
Here is the actual working example for you to have a look at, plus log in details to run any tests and to view the chat.
[Removed, no longer exists]
Below is the updated code from the previous question that is currently running on the working example.
Once again, any further help is hugely appreciated. Please let me know if you require any additional information!
Javascript:
// NOTE: I needed to define these variables to make the demo work
var ajaxurl = "http://ip.jsontest.com/";
var chatroom_slug = "1";
var last_update_id = "1";
var last_update_received = 0;
function chatroom_check_updates() {
jQuery.post(
ajaxurl,
{
action: 'check_updates',
chatroom_slug: chatroom_slug,
last_update_id: last_update_id
},
function (response) {
// NOTE: the response is bad, an exception will be thrown, not NULL
chats = null;
try {
chats = jQuery.parseJSON( response );
} catch(e) {}
// NOTE: In this test, I don't know your URL, so I just commented out the bit below
if (1 || chats !== null ) {
for ( i = 0; i < chats.length; i++ ) {
if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
continue;
jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
last_update_id = chats[i].id;
jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
}
jQuery('.chat').each(function(){
var hashtag = jQuery(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
jQuery(this).html(hashtag);
});
}
}
)
.error(function(xhr, status, error){
alert(xhr.responseText);
});
// I commented this out just for testing.
setTimeout( chatroom_check_updates, 1000 );
}
function chatroom_strip_slashes(str) {
return (str + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
}
jQuery(document).ready( function() {
last_update_id = 0;
chatroom_check_updates();
jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
if ( event.charCode == 13 || event.keyCode == 13 ) {
chatroom_send_message();
return false;
}
});
});
function chatroom_send_message() {
message = jQuery( 'textarea.chat-text-entry' ).val();
jQuery( 'textarea.chat-text-entry' ).val('');
jQuery.post(
ajaxurl,
{
action: 'send_message',
chatroom_slug: chatroom_slug,
message: message
},
function (response) {
}
);
}
PHP:
<?php
/*
Plugin Name: Chat Room
Plugin URI: http://webdevstudios.com/support/wordpress-plugins/
Description: Chat Room for WordPress
Author: WebDevStudios.com
Version: 0.1.2
Author URI: http://webdevstudios.com/
License: GPLv2 or later
*/
Class Chatroom {
function __construct() {
register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
add_action( 'init', array( $this, 'register_post_types' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
add_filter( 'the_content', array( $this, 'the_content_filter' ) );
}
function activation_hook() {
$this->register_post_types();
flush_rewrite_rules();
}
function deactivation_hook() {
flush_rewrite_rules();
}
function register_post_types() {
$labels = array(
'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
'add_new' => _x( 'Add New', 'book', 'chatroom' ),
'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
'new_item' => __( 'New Chat Room', 'chatroom' ),
'all_items' => __( 'All Chat Rooms', 'chatroom' ),
'view_item' => __( 'View Chat Room', 'chatroom' ),
'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
'parent_item_colon' => '',
'menu_name' => __( 'Chat Rooms', 'chatroom' )
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_nav_menus' => true,
'supports' => array( 'title' )
);
register_post_type( 'chat-room', $args );
}
function enqueue_scripts() {
global $post;
if ( $post->post_type != 'chat-room' )
return;
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
}
function maybe_create_chatroom_log_file( $post_id, $post ) {
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return;
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
if ( file_exists( $log_filename ) )
return;
wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, json_encode( array() ) );
// TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
}
function define_javascript_variables() {
global $post;
if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
return; ?>
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
var chatroom_slug = '<?echo $post->post_name; ?>';
</script>
<?php
}
function ajax_check_updates_handler() {
$upload_dir = wp_upload_dir();
$log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
foreach ( $messages as $key => $message ) {
if ( $message->id <= $_POST['last_update_id'] )
unset( $messages[$key] );
}
$messages = array_values( $messages );
echo json_encode( $messages );
die;
}
/**
* AJAX server-side handler for sending a message.
*
* Stores the message in a recent messages file.
*
* Clears out cache of any messages older than 10 seconds.
*/
function ajax_send_message_handler() {
$current_user = wp_get_current_user();
$this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
die;
}
function save_message( $chatroom_slug, $user_id, $content ) {
$user = get_userdata( $user_id );
if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
// Set random color for each user
$red = rand( 0, 16 );
$green = 16 - $red;
$blue = rand( 0, 16 );
$user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
update_user_meta( $user_id, 'user_color', $user_text_color );
}
$content = esc_attr( $content );
// Save the message in recent messages file
$log_filename = $this->get_log_filename( $chatroom_slug );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$last_message_id = 0; // Helps determine the new message's ID
foreach ( $messages as $key => $message ) {
if ( time() - $message->time > 100 ) {
$last_message_id = $message->id;
unset( $messages[$key] );
}
else {
break;
}
}
$messages = array_values( $messages );
if ( ! empty( $messages ) )
$last_message_id = end( $messages )->id;
$new_message_id = $last_message_id + 1;
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
// Save the message in the daily log
$log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
$contents = $this->parse_messages_log_file( $log_filename );
$messages = json_decode( $contents );
$messages[] = array(
'id' => $new_message_id,
'time' => time(),
'sender' => $user_id,
'contents' => $content,
'html' => '<div class="chat chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
);
$this->write_log_file( $log_filename, json_encode( $messages ) );
}
function write_log_file( $log_filename, $content ) {
$handle = fopen( $log_filename, 'w' );
fwrite( $handle, $content );
}
function get_log_filename( $chatroom_slug, $date = 'recent' ) {
$upload_dir = wp_upload_dir();
$log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
return $log_filename;
}
function parse_messages_log_file( $log_filename ) {
$upload_dir = wp_upload_dir();
$handle = fopen( $log_filename, 'r' );
$contents = fread( $handle, filesize( $log_filename ) );
fclose( $handle );
return $contents;
}
function the_content_filter( $content ) {
global $post;
if ( $post->post_type != 'chat-room' )
return $content;
if ( ! is_user_logged_in() ) {
?>You need to be logged in to participate in the chatroom.<?php
return;
}
?>
<div class="chat-container">
</div>
<textarea class="chat-text-entry"></textarea>
<?php
return '';
}
}
$chatroom = new Chatroom();
Example HTML output:
<div class="chat-container">
<div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
<div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
<div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
</div>
Because you are replacing all the text even if there is not a match. So .text() strips the HTML and than it does not find dog or cat and just puts the text in.
var hashtag = jQuery(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
jQuery(this).html(hashtag);
since you replace #dog with #DOG it will not match since the search is not case insensitive
either make it case insensitive
/#dog/gi
or only replace the text if there is a change made.
var orgText = jQuery(this).text();
var hashtag = orgText
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
if(orgText!==hashtag) {
jQuery(this).html(hashtag);
}
Note: the way you have it currently written, you are going to blow away the User formatting since you are reading the text.

Categories

Resources