If any of you are familiar with WooCommerce you may know that we have a [add_to_cart id="product_id"] shortcode to automatically add an item of given product_id to the cart.
This works fine while I give the specific ID in the html code, but I want it to be automated, for example getting the ID from a cookie.
The problem with this is that using JavaScript it is not possible to get function because it has to come from the server side but I've been mumbling for hours and getting nowhere with PHP...
What Can I do?
EDIT 1:
what I have is the following:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('test').innerHTML= '[add_to_cart id="4158"]';
})
and this does not work. Nontheless dinamically with cookies.
You don't give enough information about how you need to retrieve the product ID, but once you have it you could use do_shortcode() to automatically insert it into the shortcode:
if( isset( $_COOKIE['product_id'] ) ) {
$product_id = $_COOKIE['product_id']; // Get this from your cookie somehow
$shortcode = sprintf( '[add_to_cart id="%d"]', $product_id );
echo do_shortcode( $shortcode );
}
Solved the issue with an AJAX request to the server sending all the product information I had, it then answered with the
do_shortcode()
function and I was able to write that answer into some html element to view the button I needed.
Related
I have a specific problem that includes WordPress, Woocommerce, and c#.
My C# application allows users to access products from the Woocommerce shop. After selecting some products, the user has an option to send the order to his email, to see if everything is ok. At the bottom of the email, I want to add a "Go to cart" button.
This button should redirect the user to the cart/checkout page, with already added products. In order to do it, I need to have a specific link. I know that there is a method to add one product, but in this case, I need to direct the user to a cart full of different products and quantities. I am wondering if there is a method of doing it in javascript (the button that executes multiple links and the opens cart full of products).
Alternatively, I can create this cart earlier, when the mail is sent, and add a button that opens a specific session. However, I don't have any idea how to do it, and how to maintain this session for, for example, 3 days.
I don't know what code should be helpful here, so I don't post any. If you think that you need some of my code, write a comment and I will update the post.
I know that there is a code that you can paste into WordPress which allows you to add various products in one link, however, because of the specificity of this application (client shall not edit any WordPress files), I can't do it.
Do you have any ideas about how to resolve it?
By default woocommerce you can add one product at a time through the url:
... cart /? add-to-cart = 12
By default without changing anything in WOcommerce you will not be able through a button to add these products all at once, you will need to change the default code.
A simple solution would be to create a wordpress plugin that adds this functionality of accepting to add multiple products via url and the client just adds this wordpress plugin and it will be working.
I advise you to create a local environment to test before production.
Documentation Link: https://developer.wordpress.org/plugins/plugin-basics/
Here is a code example, you will need to create a folder inside the plugins folder and give it a name example: my_plugin first and inside it a file called my_plugin.php
Inside this file you add the following code:
<?php
/**
* Plugin Name: YOUR PLUGIN NAME
*/
function woocommerce_maybe_add_multiple_products_to_cart() {
// Make sure WC is installed, and add-to-cart qauery arg exists, and contains at least one comma.
if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['add-to-cart'] ) || false === strpos( $_REQUEST['add-to-cart'], ',' ) ) {
return;
}
// Remove WooCommerce's hook, as it's useless (doesn't handle multiple products).
remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );
$product_ids = explode( ',', $_REQUEST['add-to-cart'] );
$count = count( $product_ids );
$number = 0;
foreach ( $product_ids as $product_id ) {
if ( ++$number === $count ) {
// Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling.
$_REQUEST['add-to-cart'] = $product_id;
return WC_Form_Handler::add_to_cart_action();
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) );
$was_added_to_cart = false;
$adding_to_cart = wc_get_product( $product_id );
if ( ! $adding_to_cart ) {
continue;
}
$add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->product_type, $adding_to_cart );
/*
* Sorry.. if you want non-simple products, you're on your own.
*
* Related: WooCommerce has set the following methods as private:
* WC_Form_Handler::add_to_cart_handler_variable(),
* WC_Form_Handler::add_to_cart_handler_grouped(),
* WC_Form_Handler::add_to_cart_handler_simple()
*
* Why you gotta be like that WooCommerce?
*/
if ( 'simple' !== $add_to_cart_handler ) {
continue;
}
// For now, quantity applies to all products.. This could be changed easily enough, but I didn't need this feature.
$quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( $_REQUEST['quantity'] );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity ) ) {
wc_add_to_cart_message( array( $product_id => $quantity ), true );
}
}
}
// Fire before the WC_Form_Handler::add_to_cart_action callback.
add_action( 'wp_loaded', 'woocommerce_maybe_add_multiple_products_to_cart', 15 );
One important thing, this code is just an example and you can add products from a url like this: http://shop.com/shop/cart/?add-to-cart=3001,3282 just passing the product ids you want to update.
This code that modifies woocommerce and thus allowing various products by url, was not developed by me I took it as an example in the link below:
Adding multiple items to WooCommerce cart at once
In this link you will see several suggestions. What I did was just give a light that might help solve your problem.
Developing a plugin that will not change the source code of the client site is the best option and if something goes wrong or fails just disable everything back to normal;)
I hope I helped in some way.
I have a requirement in a wordpress website (PHP) where on select of a dropdown, two radio buttons show up and depending on the radio button selected a select dropdown will be made available.
I reached the stage where I have the radio buttons are made available. I use jQuery ON event to identify which radio button is checked and have the respective value in a javascript variable. I am trying to pass this JS variable to my php using ajax. Success attribute of ajax works fine but $_POST['name'] does not show the value. I tried to use .html() inside the success attribute of ajax but that just replaces my div element with the value of javascript variable. I need this JS variable value in my PHP code so that I can run a condition based on which I decide which dropdown I need to display on the website.
I have been trying a solution since few days but not able to find a solution. Request some guidance
Edit:
Based on the suggestion received
I tried the following changes. I see the value in my input type=hidden elements but only if I use Inspect in Chrome. However using View Source does not show me these values.. What am I missing? Can someone please give some guidance..
Ajx-script.js
$.ajax({
type : "POST",
url : myAjaxData.ajaxurl,
data : {
action : "sProdOrRegion_ajax_action",
selectedProdReg : selectedProdReg
},
success : function(data) {
$("#radioValueHidd1").val(selectedProdReg);
// $('#stakeholderParentData').load( urlValue + " " +"#stakeholderData");
//$("input[id=radioValueHidd3][value="+ selectedProdReg +"]").html();
$("input[id=radioValueHidd2]").val(selectedProdReg);
}
});
functions.php
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('my-ajax', get_template_directory_uri() . '/library/js/ajx-script.js', array('jquery') );
wp_localize_script(
'my-ajax',
'myAjaxData',
array( 'ajaxurl' => admin_url('admin-ajax.php') )
);
});
add_action( 'wp_ajax_singleIdeaProdOrRegion_ajax_action', 'callback_singleIdeaProdOrRegion' );
add_action('wp_ajax_singleIdeaProdOrRegion_ajax_action', 'callback_singleIdeaProdOrRegion');
function callback_singleIdeaProdOrRegion() {
if(isset($_POST['selectedProdReg'])) {
$selectedProdReg = $_POST['selectedProdReg'];
$selectedProdReg1 = $_POST['selectedProdReg'];
die();
}
}
single-car.php
<div id="stakeholderParentData" class="stakeholderParentData">
<div id="stakeholderData" class="stakeholderData">
<?php $selectedProdReg = $wpdb->escape($_POST['selectedProdReg']); ?>
<?php
if (isset ( $selProdReg )) {
if ($selProdReg === "custom_post_prod_company") {
Using Ajax in WordPress is usually done in the following manners:
1- You have to submit your ajax data to the admin-ajax.php. Sometimes you can use the global js variable ajaxurl, predefined by WordPress for that URL. But more reliably I'd use the output of admin_url( 'admin-ajax.php' ).
2- Your data object must contain an action value that have a unique string to represent this ajax submission. I'll use AJAX_ACTION here: data = { action: 'AJAX_ACTION', your_var: 'your_val' };
3- Receive the data by using hooks that contain the action name that you've specified:
add_action( 'wp_ajax_AJAX_ACTION', 'callback_function' );
add_action( 'wp_ajax_nopriv_AJAX_ACTION', 'callback_function' );
4- Use your callback_function to receive the data:
function callback_function() {
// $_POST['your_var'] is accessible here
}
By the way, using echo inside the callback_function would result in the response being sent to the success function.
wp_ajax_nopriv_AJAX_ACTION is for submission for visitors that do not have the WordPress account or are not logged in, while wp_ajax_AJAX_ACTION is for logged in users.
Please check: WordPress Codex
I am not sure if these will help you but I have 2 ideas. First is you might be getting the value of radio button false. Second is maybe you should write your data like this.
data: { "selRegProd" : selRegProd },
In WordPress I am trying to use Ajax to load a few posts from category X with the click of a button.
In order to know what posts/category to load from, I have added a "data-cat" attribute to the button, as such:
Category X
I then have a special-file.php setup that creates a new WP_Query to load posts from some category (whatever category ID is fed into the file).
And in Javascript I have this:
1- On '.loader' click use Ajax
2- get data-cat value
3- run special-file.php and feed it the data-cat value
4- get posts returned
5- load post HTML data in the DOM
6- End
And I started wondering if this is actually unsafe and open to easy hacks? Are there any big no-nos in my solution?
What made me wonder this was the thought that a hacker could edit the html using firebug or similar and change the data-cat value to something potentially malicious, although I don't know if feeding malicious category ID could really do any harm?
P.s special-file.php would look something like this:
$thequery = new WP_Query( array( 'cat' => $cat_id, 'post_status' => 'publish', 'posts_per_page' => 4, 'ignore_sticky_posts'=> 1 ) );
foreach post in $thequery
echo the post title
echo the featured image
end foreach
wp_reset_postdata();
So all you'd feed is the category ID and it would return 4 posts using basic WordPress functions (such as the_title(); to get the post title, etc).
Just make sure you always thoroughly sanitize the value that is posted, e.g.:
$cat = isset( $_POST['cat'] ) && $_POST['cat'] ? intval( $_POST['cat'] ) : 0;
The problem isn't exposing data-cat. What you need to be concerned with is sanitizing any request data that you get from the user. That means checking that the data-cat value is safe before plugging it into your database query.
Is it possible to add a product to cart with a new price using JavaScript? I have been working on a little script that calculates the price of the product. I would really like to write a function like this:
function addToCart(productID, productPrice) {
//add the product to cart with JavaScript
}
Any help or pointers would be deeply appreciated.
So far I have written 4 main files:
functions.js - calculates and shows the current price based on options the customer chooses (this works fine)
ajaxSubmit.js - jQuery ajax to send the variables to my PHP files (sends successfully)
post.php - file where the variables are sent
simple.php - the single product PHP file which displays the product
I have been able to send the variable from the JavaScript function to my product but I don't know how to add the product to cart.
My post.php looks like this:
EDIT: The following code works now and adds the product with the id 747
<?php
require('../../../../../../wp-load.php');
global $woocommerce;
$woocommerce->cart->add_to_cart(747);
sleep(3);
if (empty($_POST['ammount'])) {
$return['error'] = true;
$return['msg'] = 'You didnt select the amount.';
}
else {
$return['error'] = false;
$final_amount = $_POST['ammount'] * 10;
$return['msg'] = 'Youve chosen: ' . $final_amount . '.';
}
echo json_encode($return);
?>
I have found out that you can add a product into the cart using the following code in PHP:
global $woocommerce;
$woocommerce->cart->add_to_cart($product_id);
Then I tried adding these 2 lines into my post.php and it didn't work and also the form stopped working. If I add this into my simple.php (which basically displays the product) it works fine.
My question is: How can I add a product into the cart using this setup?
To add a product using AJAX I had to include the wp-load.php into my post.php file. That way I could access to the woocommerce variable and later add the product. Look above for the code fix.
I am sure there are a number of articles covering this topic, but every piece of code I try just doesn't seem to work. If this has been answered somewhere else already, I am sorry that I could not find it.
I am trying to create a live search that displays all data in my table until someone starts typing in an input field. As soon as they start typing a key, I want to run a select query on my table to narrow the results if any of the columns contain the string that is currently being typed (kind of like how google starts showing you results as you type in the search bar).
My code seems to work up until I try to use either $.get or $.post to interact with my php file that runs the MySQL search. I am kind of new to web development and have been teaching myself as I go along, but this one has stumped me for 2 days now. Here is the code I currently have (although I have tried about 20 different versions):
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.getElementById("search").onkeyup(searchScript());
function searchScript(){
var search = $("#search").val();
if(search==""){
return;
}
else{
$.get("resultspage.php",{search : search},function(result){
$("#results").html(result);
}});
}
</script>
<table id="results">
<?php
<...var assignments storing my db login data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays the results...>
?>
</table>
My PHP file
$search=$_GET['search'];
<...variables storing log in data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration WHERE CONCAT(fName,lName,storeName,numLocations,primaryPhone,secondPhone,email,products) LIKE %$search%";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays results....>
}
Any help would be much appreciated! Thank you.
Recognizing that jquery is another mountain to climb, I would still learn & use it for it's simplicity. Once the data has been retrieved from the server, use jquery to hide the values not starting with or containing the entered value (.match() below), instead of repeated calls to the server.
Not knowing the structure of your table, a framework you might try:
$( "#search" ).keyup(function() {
// Test search letter entry is working
alert( "Handler for .keyup() called." );
var s = $("#search").attr("value"); // Typed in letter
// Pass an array of table contents
// there are a couple ways you could approach the 'gathering' of table items...
$(".individual-item-class").each(function(index, element) {
if (!element.match(/s/))
$(element:parent).css("display","none");
else
$(element:parent).css("display","table-row")
}):
});
This code will not get you off the ground, but pointed in a direction.
You can learn about selectors and a few jquery functions. Used here are each(), attr() and css().