can't get Woocommerce billing phone inside input field using jquery - javascript

I have a CF7 form and need to get Woocommerce billing phone number and display it inside phone field on page load using jQuery function. I used this code in header area:
// Get billing_phone_number On Quote Form
jQuery(document).ready(function(){
jQuery('#mk-order-tel').val("<?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>");
});
But it returns raw php code ( <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?> ) instead of phone number; when I use same php code directly in php files of Woocommerce it works correctly. What should I do to run a php syntax through the jQuery?
EDIT
To escape of above issue, I tried to get data by using ajax but this method does not work too:
in functions.php :
/* Get Customer Phone Number */
function my_ajax_handler(){
global $woocommerce;
$phone = get_user_meta( get_current_user_id(), 'billing_phone', true );
?>
<script type="text/javascript">
jQuery( function($){
jQuery('#mk-order-tel').val("<?php echo json_encode($phone); ?>");
});
</script>
<?php
}
add_action( 'wp_ajax_call_my_ajax_handler', 'my_ajax_handler' );
add_action( 'wp_ajax_nopriv_call_my_ajax_handler', 'my_ajax_handler' );
function my_quote_scripts() {
wp_enqueue_script( 'my-ajax-script', get_stylesheet_directory_uri() . '/js/quote.js', array('jquery') );
wp_localize_script( 'my-ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_quote_scripts' );
in quote.js :
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'call_my_ajax_handler' }
})
What else can I do ?

This should work, you're getting an exception because of quotes
const tel = <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>;
jQuery(document).ready(function(){
jQuery('#tel').val(tel);
});
Or you can just replace single quotes to double
jQuery(document).ready(function(){
jQuery('#tel').val("<?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>");
});

Simply using this code in functions.php of child theme can fetch customer phone and display inside input text field :
/* Get Customer Phone Number On Quote Form */
function my_jquery_var() {
if ( $yourtel = get_user_meta( get_current_user_id(), 'billing_phone', true ) ) {
echo '<script type="text/javascript">
var yourTel = "' . $yourtel . '";
document.getElementById("mk-order-tel").value = yourTel;
</script>' . "\n";
}
}
add_action( 'wp_footer', 'my_jquery_var' );
Note: JavaScript should be in footer area.

Related

How to add/close a shortcode to functions.php in WordPress

How would I go about adding the following shortcode properly to functions.php in WordPress? When I add it works but it isn't closed properly and gives me an error.
<?php echo do_shortcode( '[brb_collection id="297"]' ); ?>
I am getting the following error:
"Your PHP code changes were rolled back due to an error on line 55 of file wp-content/themes/betheme-child/functions.php. Please fix and try saving again.
syntax error, unexpected '<', expecting end of file"
Here is my functions.php
<?php
// // Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
// BEGIN ENQUEUE PARENT ACTION
// AUTO GENERATED - Do not modify or remove comment markers above or below:
if ( !function_exists( 'chld_thm_cfg_locale_css' ) ):
function chld_thm_cfg_locale_css( $uri ){
if ( empty( $uri ) && is_rtl() && file_exists( get_template_directory() . '/rtl.css' ) )
$uri = get_template_directory_uri() . '/rtl.css';
return $uri;
}
endif;
add_filter( 'locale_stylesheet_uri', 'chld_thm_cfg_locale_css' );
// END ENQUEUE PARENT ACTION
/* Tillad at uploade fonts */
function wp39550_disable_real_mime_check( $data, $file, $filename, $mimes ) {
$wp_filetype = wp_check_filetype( $filename, $mimes );
$ext = $wp_filetype['ext'];
$type = $wp_filetype['type'];
$proper_filename = $data['proper_filename'];
return compact( 'ext', 'type', 'proper_filename' );
}
add_filter( 'wp_check_filetype_and_ext', 'wp39550_disable_real_mime_check', 10, 4 );
/* CF7 redirects */
add_action( 'wp_footer', 'redirect_cf7' );
function redirect_cf7() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '117' == event.detail.contactFormId ) { // Sends sumissions on form 947 to the first thank you page
location = 'https://example.com/thank-you/';
} else if ( '118' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page
location = 'https://example.com/thank-you/';
} else if ( '541' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page
location = 'https://example.com/da/tak/';
} else if ( '542' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page
location = 'https://example.com/da/tak/';
}
}, false );
</script>
<?php
}
/* Google reivew widget */
<?php echo do_shortcode( '[brb_collection id="297"]' ); ?>
You’re reopening php, while already in a php section
Just remove the php opening tag right before your last echo
Or close the previous php section before the comment
/* Google reivew widget */

Wordpress unable to save featured image

this is Nadeem I am a beginner on PHP and WordPress, I stuck on one point during custom plugin development, my problem is, I am unable to save Featured image and custom taxonomy tag and category from the frontend. In the meantime, I already Search on Google, StackOverflow, etc. too much for this error solution about this but unfortunately, this does not work and I am stuck at this point from the last 2 weeks.
This is my Plugin PHP code
/**
* The Template for displaying car archives, including the main car-data page which is a post type archive.
*
* Override this template by copying it to yourtheme/car_data/archive-car-data.php
*
* #author Shaikh Nadeem
* #package Car_Data
* #subpackage Car_Data/Templates
* #version 1.0.0
*/
class Car_Frontend_Form
{
function __construct()
{
add_shortcode( 'submit_car', array($this, 'submit_car') );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue' ) );
add_action( 'save_post_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_nopriv_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'init', array( $this, 'submit_car_data_post' ) );
}
public function submit_car() {
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
wp_nonce_field( "car-frontend-post" );
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
echo '<p>';
echo '<label for="content">Post Content</label><br />';
echo '<textarea id="content" name="content" cols="40" rows="4"></textarea>';
echo '</p>';
echo '<p><label for="feature">Feature:</label><br />';
wp_dropdown_categories( "show_option_none=Feature&tab_index=3&taxonomy=feature&name=feature&id=feature&class=feature" ) .'</p>';
echo '<p><label for="make">Make:</label><br />';
wp_dropdown_categories( "show_option_none=Make&tab_index=4&taxonomy=make&name=make&id=make&class=make" ) .'</p>';
echo '<p><label for="post_tags">Tags</label><br />';
echo ' <input type="text" value="" size="60" name="post_tags" id="post_tags" /></p>';
echo '<p><label for="post_tags">Car Image</label><br />';
echo '<input type="file" name="file" id="file"></p>';
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
echo '</form>';
echo '</div>';
return;
}
public function submit_car_data_post() {
if ( isset($_POST['title']) ) {
echo '<script>console.log("file error: '.$fileerror.'<br>");</script>';
$title = sanitize_text_field( $_POST['title'] );
$content = sanitize_text_field( $_POST['content'] );
$author_id = sanitize_text_field( $_POST['author_id'] );
$tags_input = sanitize_text_field( array($_POST['post_tags']) );
$feature = sanitize_text_field( array($_POST['feature']) );
$make = sanitize_text_field( array($_POST['make']) );
// $image = $_POST['file'];
$args = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $_POST['post_tags'],
'author' => $author_id,
'post_status' => 'publish',
'post_type' => 'car-data',
'tax_input' => array(
$feature,
$make
),
// 'post_category' => array(
// 'feature' => array($_POST['feature']),
// 'make' => array($_POST['make'])
// )
);
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'car-frontend-post') ) {
return;
}
if( is_wp_error( $posts ) ){
echo json_encode( $posts->get_error_messages() );
}
// save frontend Post
$posts = wp_insert_post( $args );
// save frontend Texonomy
wp_set_object_terms( $posts, $feature, 'feature' );
wp_set_object_terms( $posts, $make, 'make' );
// save Atachment on featured image for the current custom post
$uploaddir = wp_upload_dir();
$file = $_FILES[$image];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $_FILES['file']['tmp_name'], $uploaddir['path'] . '/' . $filename );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => preg_replace('/\.[^.]+$/', '', $filename),
'post_excerpt' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit',
'post_type' => 'attachment',
'menu_order' => $_i + 1000,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata($attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_die();
}
}
public function my_enqueue() {
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
and i use javascript for the ajax alert message when form is submit
jQuery(document).ready(function($) {
$('.cd_car').on('submit', function(event) {
event.preventDefault();
var message = document.getElementById("file").value;
var empt = document.forms["cd_car"]["title"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
$.ajax({
type: 'post',
// url : ajax_object.ajaxurl,
data : $('.cd_car').serialize(),
success : function(data){
alert(message);
console.log(data);
},
error : function(data){
alert(message);
alert('fail');
}
});
}
});
});
Also i have there one error on this line code if ( isset($_POST['title']) ) unable to use submit key on isset post only title is working here.
I believe your issue is due to sanitize_text_field( array( .. )). sanitize_text_field only accepts strings as the parameter, so I assume by sending in an Array it's actually always seeing the string "Array" - not your POST values.
To sanitize the array, could do something like:
$tags_input = array();
if ( isset($_POST['post_tags']) && !empty($_POST['post_tags']) ) {
foreach ($_POST['post_tags'] as $val)
$tags_input[] = sanitize_text_field( $val );
}
// [ .. repeat for feature & make .. ]
Or, if they're single values only (not arrays), simply remove the array wrapper.

Using ajax only saves 1 image from ACF gallery in wordpress

I'm using the ACF gallery field to let users create a gallery on front end and then I have an ajax call to save the gallery without page refresh.
If I remove the ajax save and use the default update post, all images in the gallery save correctly, but when I use my ajax save method only the last image in the gallery saves.
Here's my code:
Single post / form
<?php acf_form_head(); ?>
<?php get_header(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php $args = array(
'form_attributes' => array(
'id'=>'modalAjaxTrying'
),
'submit_value' => __("update this badboy", 'acf'),
);
acf_form( $args );
?>
<?php endwhile; endif; ?>
<?php acf_enqueue_uploader();?>
<?php get_footer(); ?>
Ajax save in JS file
jQuery('form#modalAjaxTrying :submit').click(function(event){
event.preventDefault();
var form_data = {'action' : 'acf/validate_save_post'};
jQuery('form#modalAjaxTrying :input').each(function(){
form_data[jQuery(this).attr('name')] = jQuery(this).val()
})
form_data.action = 'save_my_data';
jQuery.post(ajaxurl, form_data)
.done(function(save_data){
alert('Added successFully :');
})
})
Functions.php
add_action( 'wp_ajax_save_my_data', 'acf_form_head' );
add_action( 'wp_ajax_nopriv_save_my_data', 'acf_form_head' );
Anyone looking to get ajax save to play nice with ACF gallery here ya go.
In your functions.php
add_action('acf/submit_form', 'my_acf_submit_form', 10, 2);
function my_acf_submit_form( $form, $post_id ) {
if(is_admin())
return;
//Test if it's a AJAX request.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $form['updated_message'];
die();
}
}
add_action( 'wp_ajax_save_my_data', 'acf_form_head' );
add_action( 'wp_ajax_nopriv_save_my_data', 'acf_form_head' );
function my_acf_save_post( $post_id ) {
// get new values
$value = get_field('add_images', $post_id);
In your JS file
acf.do_action('ready', $('body'));
$('form#modalAjaxTrying').on('submit', function(e){
e.preventDefault();
});
acf.add_action('submit', function($form){
$.ajax({
url: window.location.href,
method: 'post',
data: $form.serialize(),
success: function(data) {
acf.validation.toggle($form, 'unlock');
alert(data);
}
});
});

Can't get Wordpress AJAX working

I have been following multiple tutorials on this (including Wordpress's own) and its driving me a little crazy.
I am trying to get AJAX working on the front end in Wordpress, however it is simply not doing anything, I know the function works as I have tested this independently, your input will be really appreciated on this one. Many thanks in advance.
The code in functions.php
function call_ajax()
{
//assuming this is in a theme?
wp_enqueue_script( 'ajax_car_models', get_template_directory_uri() . '/js/ajax_car_models.js', array( 'jquery' ), null, true);
//loacalize the script using the same handle it was registered / enqueued with
wp_localize_script( 'ajax_car_models', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//make a call to call_ajax at the right time
add_action( 'wp_enqueue_scripts', 'call_ajax' );
add_action( 'wp_ajax_ajax_car_models', 'ajax_car_models' );
add_action( 'wp_ajax_nopriv_ajax_car_models', 'ajax_car_models' );
function ajax_car_models() {
$args = array( 'post_type' => 'product', 'posts_per_page' => 1040 );
$loop1 = new WP_Query( $args );
$code = '';
$car_make = 26;
$all_models = array();
while ( $loop1->have_posts() ) : $loop1->the_post();
$terms_make = get_the_terms( get_the_id(), 'pa_car-make' );
foreach ( $terms_make as $make ) {
if ( $make->term_id == $car_make ) {
$the_car_model = get_the_terms( get_the_id(), 'pa_model' );
foreach ( $the_car_model as $the_model ) {
if ($all_models[$the_model->name] != 'true') {
$code .= '<br />'.$the_model->name.' ';
$all_models[$the_model->name] = 'true';
}
}
}
}
endwhile;
wp_reset_postdata();
header( 'Content-type: application/json' );
echo json_encode( $code );
die();
}
And the jQuery itself:
jQuery( document ).ready(function() {
jQuery('#car-make').change(my_js_function);
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
dataType: 'json', // add this line
data: ({action : 'ajax_car_models'}),
success: function() {
jQuery("#feedback").html(data);
}
});
}
});
If you include you javascript inline you will not be able to use localize pass it the ajax url.
You should move your javascript into a different file and then use wp_enqueue_script in order to properly use ajax.
function call_ajax()
{
//assuming this is in a theme?
wp_enqueue_script( 'ajax_car_models', get_template_directory_uri() . '/js/ajax_car_models.js', array( 'jquery' ), null, true);
//loacalize the script using the same handle it was registered / enqueued with
wp_localize_script( 'ajax_car_models', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//make a call to call_ajax at the right time
add_action( 'wp_enqueue_scripts', 'call_ajax' );
You also need to send json headers in your response function
header( 'Content-type: application/json' );
echo json_encode( $code );
exit();
In your ajax call you are not passing the data to your success callback
success: function(data){
console.log(data);
//...
}
You can use the network tab on the chrome developer tools to look at what requests are actually made and check the response they receive.
According to the PHP manual json_encode needs string data to be UTF8 encoded.
Alternatively, you can try doing this instead in your functions.php...
$return_array = array(
'val' => $code
);
echo json_encode($return_array);
Then, in your jQuery script...
jQuery("#feedback").html(data.val);
Also, try adding to your ajax request one more option...
url: my_ajax_script.ajaxurl,
dataType: 'json', // add this line
data: ({action : 'ajax_car_models'}),
Hope these help!

WordPress - Modify admin-header.php or use functions.php for inserting a jQuery script to header?

Im developing a Form with a (jQuery) onClick button so I can import results from other documents straight into WP Custom Fields.
To do this I MUST include this script to my Form:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
If I don't include this script then my Form wont work :(
And if I include this script then I can ADD NEW POST and use my Form + Button but then the EDIT POST page wont show up and I only see a WHITE SCREEN.
Finally I figured out if I insert this CODE to LINE 59 in admin-header.php:
<?php if ( is_admin() && $parent_file == 'edit.php') { ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php } ?>
Then everything will work 100% as I want :D
I thought WP already was using/including this script by default but this is NOT true as I can see. At least not for WP-Backend (Post page).
The problem is: I dont want to edit WP CORE files, so my question is how can I get the same result using functions.php instead of editing admin-header.php?
Just to show you how admin-header looks like from LINE 50 to LINE 73:
<title><?php echo $admin_title; ?></title>
<?php
wp_enqueue_style( 'colors' );
wp_enqueue_style( 'ie' );
wp_enqueue_script('utils');
$admin_body_class = preg_replace('/[^a-z0-9_-]+/i', '-', $hook_suffix);
?>
<?php if ( is_admin() && $parent_file == 'edit.php') { ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php } ?>
<script type="text/javascript">
addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>',
pagenow = '<?php echo $current_screen->id; ?>',
typenow = '<?php echo $current_screen->post_type; ?>',
adminpage = '<?php echo $admin_body_class; ?>',
thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>',
decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>',
isRtl = <?php echo (int) is_rtl(); ?>;
</script>
As you can se my CODE is on LINE 11,12 and 13 to make it work.
You can try something like this in your theme functions.php
function admin_add_script() {
wp_enqueue_script('jquery_script', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array(), null);
}
add_action('admin_head-edit.php', 'admin_add_script');
Try adding this to your functions.php:
<?php
function add_jquery_data() {
global $parent_file;
if ( isset( $_GET['action'] ) && $_GET['action'] == 'edit' && isset( $_GET['post'] ) && $parent_file == 'edit.php') {
echo "<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>";
}
}
add_filter('admin_head', 'add_jquery_data');
?>
I hope this helps.

Categories