I am trying to update multiple posts post meta at the same time. I have the following query:
<form action="" method="post">
<?php
$variations = new WP_Query();
$variations->query(array('showposts' => -1, 'post_type' => 'product_variation' )); while ($variations->have_posts()) : $variations->the_post(); ?>
<input name="regular_price[]" type="text" value="<?php echo get_post_meta(get_the_id(), "_regular_price", true); ?>" />
<input name="sale_price[]" type="text" value="<?php echo get_post_meta(get_the_id(), "_sale_price", true); ?>" />
<input name="item_id[]" type="hidden" value="<?php echo get_the_id(); ?>" />
<?php endwhile; wp_reset_query();?>
<input name="save" type="submit" />
I then have the following php to process the data:
<?php
if (isset($_POST['save'])) {
$ids = $_POST['item_id'];
$sales = $_POST['sale_price'];
foreach ($ids as $id){
update_post_meta($id,'_sale_price',$sale));
}
} ?>
For some reason the above does not save correctly. It will only save the last value, and apply this to all post meta. Is there something i am doing wrong?
I believe you need to add the id to $sale in you update_post_meta field. Like so:
<?php
if (isset($_POST['save'])) {
$ids = $_POST['item_id'];
$sales = $_POST['sale_price'];
foreach ($ids as $id){
update_post_meta($id,'_sale_price',$sale[$id]));
}
} ?>
You forgot the } for "for".
update .......;
}
}
danyo, I feel you have issue with $count. Please make sure that this variable have proper count value to update data in loop.
Related
I'm trying to update a post title using wp_update_post()
First I get the ID of the post:
global $post;
$post_to_edit = get_post($_GET['post_id']);
Then the form to update which it actually gets the title from the post to edit:
<form action="" id="primaryPostForm" method="POST">
<label for="postTitle">Title of your post</label>
<input type="text" name="postTitle" id="postTitle" class="form-control" value="<?php echo esc_html( $post_to_edit->post_title ); ?> ">
<input type="hidden" name="postId" id="postId" value="<?php echo $_GET['post_id']; ?>">
<input type="submit" name="submit_post" value="Update">
</form>
Then below on the same page I have:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['submit_post'])) {
$data = array(
'ID' => $_POST['postId'],
'post_title' => $_POST('postTitle')
);
wp_update_post( $data );
}
}
?>
But it's not updating the post title.
Your code is wrong,
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['submit_post'])) {
$data = array(
'ID' => $_POST['postId'],
'post_title' => $_POST['postTitle'] //you used wrong brackets
);
wp_update_post( $data );
}
}
?>
I've search the forum for the same situation that I have but still couldn't find the solution. It's probably a piece of cake but I can't figure it out why my $_GET[] doesn't work.
I've created a product page and when I add something to the cart I want to display a message. I've made it work with the url in the form action but then my cart counter in the header stops working properly.
If it's possible I don't want to add any extra in the url like a "?success" because then it just keeps adding ?success to the url if I add more to the cart, that works in action but not with header() ?
Here is my code for the product page:
<?php include_once '../header.php';
$message = "";
$product = New Product;
$cart_data = [];
// if the variables are set - run the following statement
if(isset($_POST["addtocart"])) {
if(isset($_COOKIE["cart"])) {
// Removes backlashes and dont replace previous item, gives every item a new row.
$cookie_data = stripslashes($_COOKIE['cart']);
$cart_data = json_decode($cookie_data, true);
}
// Returns the productid and Size in the array
$item_list = array_column($cart_data, 'ProductsId');
$size_list = array_column($cart_data, 'Size');
// Returns the value if the statement is true
if(in_array($_POST["ProductsId"], $item_list) && in_array($_POST['selectedSize'], $size_list)) {
// A foreachloop that repeats the array value of the selected key variable.
foreach($cart_data as $keys => $values) {
if($cart_data[$keys]["ProductsId"] == $_POST["ProductsId"] && $cart_data[$keys]["Size"] == $_POST["selectedSize"]) {
$cart_data[$keys]["quantity"] = $cart_data[$keys]["quantity"] + $_POST["quantity"];
}
}
}
else {
$item_array = array(
'Img' => $Img = filter_var($_POST["Img"], FILTER_SANITIZE_STRING),
'ProductName' => $ProductName = filter_var($_POST["ProductName"], FILTER_SANITIZE_STRING),
'Size' => $Size = filter_var($_POST['selectedSize'], FILTER_SANITIZE_STRING),
'ProductsId' => $ProductsId = filter_var($_POST["ProductsId"], FILTER_SANITIZE_NUMBER_INT),
'Price' => $Price = filter_var($_POST["Price"], FILTER_SANITIZE_NUMBER_INT),
'quantity' => $quantity = filter_var($_POST["quantity"], FILTER_SANITIZE_NUMBER_INT),
);
$cart_data[] = $item_array;
}
$item_data = json_encode($cart_data);
setcookie('cart', $item_data, time() +(3600),'/');
header("location: product-detail.php?product=".$_GET['product']."?success");
}
if(isset($_GET['success'])) {
$message = "Varan lades till i varukorgen";
};
var_dump($message);
?>
<main id="product-content">
<section>
<form method="post" name="cartCount" action="">
<!-- product-detail.php?product=<?php echo $_GET['product']; ?> -->
<?php if(isset($_GET['product'])) {
$product->ProductsId = $_GET['product'];
$product->ProductId = $_GET['product'];
$product->ProductsId = $_GET['product'];
} else {
$product->ProductsId = $_POST['ProductsId'];
}
$result = $product->get_product();
$test = $product->get_productvariation();
while ($row = $result->fetch()) { ?>
<div class="product-card-detail">
<div class="product-image-wrapper">
<img class="product-image" src="../<?php echo $row['Img'];?>" >
<input type ="hidden" name="Img" value="<?php echo $row['Img'] ?>">
<?php $results = $product->get_images();
$Images = $results->fetch();
if(isset($Images['Image'])) { ?>
<img class="product-image" src="../<?php echo $Images['Image'];?>">
<?php } ?>
</div>
<div class="product-details-text">
<h2 class="title"><?php echo $row['ProductName']; ?></h2>
<input type ="hidden" name="ProductName" value="<?php echo $row['ProductName'] ?>">
<span class="price"><?php echo $row['Price'];?> SEK</span>
<input type ="hidden" name="Price" value="<?php echo $row['Price'] ?>">
<span class="select-title">Storlek</span>
<select class="size" name="selectedSize">
<?php while ($sizeRow = $test->fetch()) { ?>
<option>
<?php echo $sizeRow['Size']; ?>
</option>
<?php } ?>
</select>
<input type="hidden" name="quantity" value="1" />
<input type="submit" class="addtocart-btn" name="addtocart" value="Lägg i varukorgen"/>
<div><?php echo $message ?></div>
<input type ="hidden" name="ProductsId" value="<?php echo $row['ProductsId'] ?>">
<span class="title-description">Beskrivning</span>
<p class="description"><?php echo $row['Description']; ?></p>
</div>
</div>
<?php } ?>
</form>
</section>
</main>
<?php include_once "../footer.php";?>
I've made a test page that works exactly as expected so I can only think that is has to be something about the url?
Test code:
<?php
$message ="";
if(isset($_POST['submit'])) {
header("location: index.php?success");
}
if(isset($_GET['success'])) {
$message = "hello";
}
var_dump($message);
?>
<form method="post" action="">
<input text name="name" value="">
<input type="submit" name="submit" value="submit">
<?php echo $message ?>
</form>
Glad if anyone can see why it doesn't work!
You have made a mistake:
header("location: product-detail.php?product=".$_GET['product']."?success");
See the above line and notice that you are appending param success with ?.
Make it & as:
header("location: product-detail.php?product=".$_GET['product']."&success");
no matter whichever btn i click only the last post's count changes...how do i get the corresponding count to change
<?php
// Query the custom post type to display
$args = array('post_type' => 'books');
$query = new WP_Query( $args );
while ( $query->have_posts() ) :
$query->the_post();
if ( has_post_thumbnail() ):
$postid = get_the_ID();
$oldcount=get_field('count');
$newcount=$oldcount+1;
?>
<form action="#" method="post">
<div><?php the_post_thumbnail('thumbnail'); ?><input id="<?php echo $postid;?>" type="submit" name="submit" value="Vote" /><?php echo " ".$oldcount;?></div>
</form>
<?php endif; endwhile; ?>
<?php
if (isset($_POST['submit'])) {
$ID = $_GET['id'];
echo $ID;
echo " button clicked";
update_field('field_55014a',$newcount,$ID);
}
?>
You are submitting the form via POST but trying using $_GET['id'] this does not correspond to <input id="<?php echo $postid;?>">
Change the form so that it submits the post id:
<?php
// THIS PORTION OF THE CODE MUST COME FIRST!!!!!
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$newcount = // query your database, get the vote count then add one.
update_field('field_55014a',$newcount,$id);
header('Location: '. $_SERVER['PHP_SELF']);
exit();
}
$args = array('post_type' => 'books');
$query = new WP_Query( $args );
while ( $query->have_posts() ) {
$query->the_post();
if ( has_post_thumbnail() ) {
$postid = get_the_ID();
$votecout =get_field('count');
?>
<form action="" method="POST">
<div>
<?php the_post_thumbnail('thumbnail'); ?>
<input type="hidden" value="<?php echo $postid; ?>" name="id" />
<input type="submit" name="submit" value="Vote" />
<?php echo $oldcount; ?>
</div>
</form>
<?php
} // close if
} // close while
For the below example everything works as expected when ALL the checkboxes are checked. The problem occurs when one or more (but NOT all of them) are checked.
<form action="someaction" method="post">
<?php foreach ($fields as $field) { ?>
<input type="checkbox" name="checkpid[]" value="<?php echo $field['pid']; ?>">
<input type="hidden" name="checkprice[]" value="<?php echo $field['price']; ?>">
<input type="submit" name="submit" value="Submit">
<?php } ?>
</form>
<?php if (isset($_POST['checkpid'])) { ?>
<?php
$checkpid = $_POST['checkpid'];
$checkprice = $_POST['checkprice'];
?>
<?php foreach ($checkpid as $key => $checkpid) { ?>
<?php
$eachpid[] = $checkpid.",".$checkprice[$key];
?>
<?php } ?>
<?php print_r($eachpid), ?> // the $checkpid is always as expected, but the $checkprice does not match its row.
<?php } ?>
With my little knowledge I suspect it is something wrong in the declaration of the $key, but I am overwhelmed.
this is all i can suggest.
instead of adding two input how about adding the two data in value of a checkbox input separated with |. then when submitted just explode the value and receive array 1 for id and 1 for price.
<?php
if (isset($_POST['checkp'])) {
$checkp = $_POST['checkp'];
foreach ($checkp as $check) {
$c = explode("|", $check);
$eachpid[] = $c[0].",".$c[1];
}
print_r($eachpid);
}
?>
<form action="" method="post">
<?php foreach ($fields as $field) { ?>
<input type="checkbox" name="checkp[]" value="<?php echo $field['pid']; ?>|<?php echo $field['price']; ?>">
<?php } ?>
<input type="submit" name="submit" value="Submit">
</form>
I have a shopping cart which I got from Matthew Pennell(shopping cart tutorial), in his shopping cart script I would like to implement paypal. However I encounter a problem which I cant really solve. Since in his code he is doing a foreach loop , hence my paypal "item_name_" and "amount_" have to be variable. I need to count how many array is within an array . I tried it using count($content), it does give me number of array however , the result is increasing for every other row in my cart.
I.E
1 object return 1
2 object return 2 , 2
3 object return 3, 3 ,3
I'm wondering if I've missed out on other function, or is there a way to get only 1 result even if the actual return data is 3,3,3 .
Lastly for paypal_quantity is there such variable for add to cart?
<?php
$i = 1;
function checkout() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',', $cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
?>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart"></input>
<input type="hidden" name="upload" value="1"></input>
<input type="hidden" name="business" value="my_email.com"></input>
<?php
foreach ($contents as $id => $qty) {
echo $contents;
$sql = 'SELECT * FROM books WHERE id = ' . $id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
?>
<input type="hidden" name="item_name_<?php echo count($contents); ?>" value="<?php echo $title; ?>"></input>
<input type="hidden" name="amount_<?php echo count($contents); ?>" value="<?php echo $price; ?>"></input>
<input type="hidden" name="quantity" value="<?php echo $qty; ?>"></input>
<?php
}
?>
<input type="submit" value="PayPal"></input>
</form>
That is because these lines
<input type="hidden" name="item_name_<?php echo count($contents); ?>" value="<?php echo $title; ?>"></input>
<input type="hidden" name="amount_<?php echo count($contents); ?>" value="<?php echo $price; ?>"></input>
are inside the foreach loop and so if you loop twice, echo count($contents); runs twice and you get 22.
Cant believe im so stupid. Here have to say thanks alot for your all time and help. But i manage to solve this myself real easy.
foreach ($contents as $id => $qty) {
$rowid++;
$sql = 'SELECT * FROM books WHERE id = ' . $id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
echo $rowid;
I've looked at your code and made some suggested improvements. It looked like there was a bit of duplicated work going on, hopefully you can understand what I've done to help. It looks like this will probably work well to fix your issue at a minimum.
<?php
$i = 1; // not used in the below function.
function checkout() {
global $db;
// check for isset, it is more defensive and PHP is less inclined to issue a warning.
if( isset( $_SESSION['cart'] ) && $_SESSION['cart'] ) {
$items = explode( ',', $_SESSION['cart'] );
// array_count_values is pretty cool.
// it does exactly what your first for loop did.
$contents = array_count_values( $items );
?>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart"></input>
<input type="hidden" name="upload" value="1"></input>
<input type="hidden" name="business" value="my_email.com"></input>
<?php
foreach ($contents as $id => $qty) {
// echo $contents; <!-- this should echo 'Array' continually
$sql = 'SELECT * FROM books WHERE id = ' . $id;
$result = $db->query($sql);
$row = $result->fetch();
// extract is normally not the best practice, frequently it leads to accidental replacement of
// important variables -- if `books` had a `contents` column or quantity, that would be no good.
// so I've replaced it with what I expect are the keys to the array.
?>
<?php
/*
A caution about hidden inputs. They can be modified by the client, so if you were to, say,
trust the price listed below and your client had no scruples, your client could simply set
that value to, say, $0.01. Or worse, free!
*/
/*
I've changed up your input naming convention just slightly (it is easy to fix, but hear me
out first). You've used something which will render <name-1>_1, <name-1>_2... which means
that your $_POST (If you're buying something with this form, $_POST really is your better
bet) will have $_POST[<name-1>_1], $_POST[<name-1>_2]... In order to get all of the different
products grouped properly, you'll actually need to parse the $_POST indexes... it will get
messy. It's doable, but it will be annoying.
Instead, I put the naming convention <name-1>[1], <name-2>[2]. This means that $_POST will
have an array for each of the <names>. This means that you can do this:
$quantity = "";
$ammount = "";
foreach( $_POST[ 'item_name' ] as $key => $item )
{
$quantity = $_POST[ 'quantity' ][ $key ];
$ammount = $_POST[ 'ammount' ][ $key ];
// you now have all three quickly and easily with no string parsing! Set it and forget it!
}
*/
?>
<input type="hidden" name="item_name[<?php
// before you were using count($contents) here. That would mean that everything would have
// the same name and you'd only get one value back in $_REQUEST. I think you meant ID.
echo $id;
?>]" value="<?php echo $row['title']; ?>"></input>
<input type="hidden" name="amount[<?php echo $id; ?>" value="<?php
// ammount may not be your best choice of input name for something that refers to price.
// I know that when I look at it, I expect that to refer to quantity and not to cost
// and your first job as a developer is writing code which is as obvious as possible.
// But that is more stylistic than not so feel free to disregard
echo $row['price'];
?>]"></input>
<input type="hidden" name="quantity[<?php
// I took the liberty of adding id to this input as well -- otherwise you'd only have one
// quantity
echo $id;
?>]" value="<?php echo $qty; ?>"></input>
<?php
}
?>
<input type="submit" value="PayPal"></input>
</form>
<?php
}
}
?>