onclicking button only the last post changes - php

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

Related

Why the selected dropdown value is not getting shown?

I am building a function on my WordPress plugin where it displays a dropdown of all the available pages. When I click on Save Changes, the value gets saved perfectly in the DB. It updates the value perfectly too. But, the selected value is not being shown in the dropdown. When Save Changes is clicked the value gets saved, but the dropdown again resets to "Choose one". It doesn't get to display the selected option. Am I doing something wrong here? Any guidance is appreciated.
<form method=post>
<div class="header-right">
<?php
$posts = get_pages(
array(
'post_status' => 'publish',
)
);
?>
<select name="page_for_logged_in" id="page_for_logged_in">
<option selected="selected">Choose one</option>
<?php
foreach ( $posts as $page ) {
?>
<option value="<?php echo esc_attr( $page->post_name ); ?>" <?php selected(get_option('page_for_logged_in'), 'page')?>><?php echo esc_html( $page->post_title ); ?></option>
<?php
}
?>
</select>
<?php
if(empty($_POST['page_for_logged_in'])) {
} else {
$myvalue=$_POST['page_for_logged_in'];
update_option('page_for_logged_in', $myvalue, $autoload = 'no');
}
?>
<?php submit_button(); ?>
</p>
</br>
</br>
</form>
Okay, so I figured out the working solution to my issue. Pasted below; Might be helpful for someone.
<form method=post>
<div class="header-right">
<?php
$posts = get_pages(
array(
'post_status' => 'publish',
)
);
?>
<?php
if(empty($_POST['page_for_logged_in'])) {
} else {
$myvalue=$_POST['page_for_logged_in'];
update_option('page_for_logged_in', $myvalue, $autoload = 'yes');
}
?>
<select name="page_for_logged_in" id="page_for_logged_in">
<option value="" disabled selected>Choose one</option>
<?php
foreach ( $posts as $page ) {
?>
<option value="<?php echo esc_attr( $page->post_title ); ?>" <?php echo ( get_option('page_for_logged_in') == $page->post_title ? 'selected' : '' ); ?>><?php echo esc_html( $page->post_title ); ?></option>
<?php
}
?>
</select>
<?php submit_button(); ?>
</p>
</br>
</br>
</form>

Can´t show message after form submit with header("location:")

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");

Fill input with array

In my jquery code I have:
$("#show").append("<img src=" +attachment.url+" alt="+attachment.alt+" title="+attachment.title+" description="+attachment.caption+" class='img-responsive img-thumbnail'/><input type='hidden' name='my_image_URL[]' value="+attachment.url+"></span>");
My jquery code adds fields for news selected images and fills inputs names my_image_URL[].
In PHP:
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
}
I trying to add $urls array in the hidden input.
And after, if its works ok:
<?php
if ($urls != '' ) {
foreach ($urls as $url) {
?>
<img src="<?php echo $url;?>" class="img-responsive img-thumbnail " />
<input name="my_image_URL[]" value="<?php echo $url;?>"/>
</div>
<?php
};
}
?>
But this part of code not fill the input:
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
}
---------- UPDATE --------
options.php
register_setting(
'tema-setting-group',//string $option_group
'imagens_home' //string $option_name
//calback $sanitize_calback
);
---
add_settings_field(
'home-imagens-top',//string $id
'Imagens',//String $title
'tema_home_imgs',//string $calback
'opcoes_do_tema',//string $page
'tema-home-options'//string $section
//string $args
);
//calback
function tema_home_imgs(){
$urlsImagens = esc_attr( get_option( 'imagens_home' ) ); // RETURN DB DATA
include( get_template_directory() . '/inc/templates/selecao_imagens.php');
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input name="imagens_home" value="'.$json_encode($urls).'" style="width:300px"/>';
}
}
selecao_imagens.php
<input id="my_upl_button" type="button" value="Escolher Imagens" /><br/>
<div class="row">
<div id="exibe" class="sortable">
<?php
$urls = json_decode($urlsImagens, true);
if ($urls != '' ) {
foreach ($urls as $url) {
?>
<img src="<?php echo $url;?>" class="img-responsive img-thumbnail " />
<input name="my_image_URL[]" value="<?php echo $url;?>"/>
<?php
};
}
?>
</div>
</div>
theme_options.php
<?php settings_errors();?>
<form method="post" action="options.php">
<?php settings_fields ('tema-setting-group'); ?>
<?php do_settings_sections (
'opcoes_do_tema'//string $page
); ?>
<?php submit_button ();
?>
</form>
-------- UPDATE 2 -------
I tried:
echo '<input name="imagens_home" value="' . htmlspecialchars(json_encode($urls)) . '" />';
but it is not yet filling in the input.
I also tried only:
If (isset ($ _POST ['my_image_URL'])) {
Print_r ($ _ POST ['my_image_URL']);
}
But after the submit does not appear anything on the screen, in the form correctly saves all other inputs except what I am trying to save the array, if I put some manual information goes ok. But I do not understand why it is not capturing the my_image_URL [] names of each image input. The action in form is like this:
<Form method = “post” action = “options.php”>
I’m using the Settings API
Thanks
I trying to add $urls array in the hidden input.
If I understand, you're trying to store an array value in a hidden input, so you can retrieve it later. Problem is, this doesn't work...
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
...because when you echo a PHP array all you get is the string Array, not the actual array contents.
You could turn the array into a json string though:
echo '<input type="hidden" name="imagens_home" value="'.$json_encode($urls).'"/>';
Now your hidden input has a regular string. Later, when the form is POSTed, you could retrieve it:
$urls = json_decode($_POST['imagens_home'], true)

wordpress update multiple posts post meta

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.

Trying to send a hidden input value to next page

I am trying to tweak Wordpress Jigoshop according to my customer's needs and I got a bit stuck. What I need is: when a product variation is selected, some additional options appear in the form of radio buttons which customers must chose. I've managed to get everything working, but what I need now is to send the selected radio button to the cart, checkout and so on when the submit button is clicked.
I am trying to use their product customization function to do this and their function is:
if (!function_exists('jigoshop_product_customize_panel')) {
function jigoshop_product_customize_panel() {
global $_product;
if ( isset( $_POST['Submit'] ) && $_POST['Submit'] == 'Save Personalization' ) {
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom_products[$_POST['customized_id']] = trim( wptexturize( $_POST['jigoshop_customized_product'] ));
jigoshop_session::instance()->customized_products = $custom_products;
}
if ( get_post_meta( $_product->ID , 'customizable', true ) == 'yes' ) :
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom = isset( $custom_products[$_product->ID] ) ? $custom_products[$_product->ID] : '';
$custom_length = get_post_meta( $_product->ID , 'customized_length', true );
$length_str = $custom_length == '' ? '' : sprintf( __( 'You may enter a maximum of %s characters.', 'jigoshop' ), $custom_length );
echo '<div class="panel" id="tab-customize">';
echo '<p>' . apply_filters('jigoshop_product_customize_heading', __('Enter your personal information as you want it to appear on the product.<br />'.$length_str, 'jigoshop')) . '</p>';
?>
<form action="" method="post">
<input type="hidden" name="customized_id" value="<?php echo esc_attr( $_product->ID ); ?>" />
<?php
if ( $custom_length == '' ) :
?>
<textarea
id="jigoshop_customized_product"
name="jigoshop_customized_product"
cols="60"
rows="4"><?php echo esc_textarea( $custom ); ?>
</textarea>
<?php else : ?>
<input
type="text"
id="jigoshop_customized_product"
name="jigoshop_customized_product"
size="<?php echo $custom_length; ?>"
maxlength="<?php echo $custom_length; ?>"
value="<?php echo esc_attr( $custom ); ?>" />
<?php endif; ?>
<p class="submit"><input name="Submit" type="submit" class="button-alt add_personalization" value="<?php _e( "Save Personalization", 'jigoshop' ); ?>" /></p>
</form>
<?php
echo '</div>';
endif;
}
}
I tried modifying their function to suit my needs and this is what I've come up with (where get_cod is the id and name of the hidden input and "Adauga in cos" is the value of my submit button):
if (!function_exists('salveaza_cod_material')) {
function salveaza_cod_material() {
global $_product;
if ( isset( $_POST['submit']) && $_POST('submit') == 'Adauga in cos') {
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom_products[$_POST['customized_id']] = trim( wptexturize( $_POST['get_cod'] ));
jigoshop_session::instance()->customized_products = $custom_products;
}
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom = isset( $custom_products[$_product->ID] ) ? $custom_products[$_product->ID] : '';
}}
However the value isn't sent to the next page. Can anybody please help? Cheers!
Here's an update containing more of the code:
<form action="<?php echo esc_url( $_product->add_to_cart_url() ); ?>" class="variations_form cart" method="post">
<fieldset class="variations">
<?php foreach ( $attributes as $name => $options ): ?>
<?php $sanitized_name = sanitize_title( $name ); ?>
<div>
<span class="select_label"><?php echo jigoshop_product::attribute_label('pa_'.$name); ?></span>
<select id="<?php echo esc_attr( $sanitized_name ); ?>" name="tax_<?php echo $sanitized_name; ?>">
<option value=""><?php echo __('Choose an option ', 'jigoshop') ?>…</option>
<?php foreach ( $options as $value ) : ?>
<?php if ( taxonomy_exists( 'pa_'.$sanitized_name )) : ?>
<?php $term = get_term_by( 'slug', $value, 'pa_'.$sanitized_name ); ?>
<option value="<?php echo esc_attr( $term->slug ); ?>"><?php echo $term->name; ?> </option>
<?php else : ?>
<option value="<?php echo esc_attr( sanitize_title( $value ) ); ?>"><?php echo $value; ?></option>
<?php endif;?>
<?php endforeach; ?>
</select>
</div>
<?php endforeach;?>
</fieldset>
<div id="piele-neagra" class="colors" style="display:none">
<ul class="materiale">
<li><input type="radio" name="piele-neagra" value="L73">
<p><img class="alignnone size-full wp-image-155" title="L73" src="http://www.scaune-directoriale.ro/wp-content/uploads/materiale/piele-neagra/L73.gif" alt="L73" width="72" height="72" /></p>
</li>
</ul>
</div>
<div id="stofa-mf" class="colors" style="display:none">
<ul class="materiale">
<li><input type="radio" name="tapiterie" value="MF01" />
...
<div id="stofa-rg" class="colors" style="display:none"> Stofa RG</div>
<div class="clear"></div>
<span id="cod_material"><?php echo esc_attr( $custom ); ?></span>
<span><?php echo trim( wptexturize( $_POST['get_cod'] )); ?></span>
<div class="single_variation"></div>
<?php do_action('jigoshop_before_add_to_cart_form_button'); ?>
<div class="variations_button" style="display:none;">
<input type="hidden" name="variation_id" value="" />
<input type="hidden" name="customized_id" value="<?php echo esc_attr( $_product->ID ); ?>" />
<input type="hidden" id="get_cod" name="get_cod" value="" />
<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
<div class="quantity"><input name="quantity" value="1" size="4" title="Qty" class="input-text qty text" maxlength="12" /></div>
<input type="submit" id="submit_cart" class="button-alt" value="<?php esc_html_e('Add to cart', 'jigoshop'); ?>" />
</div>
<?php do_action('salveaza_cod_material'); ?>
<?php do_action('jigoshop_add_to_cart_form'); ?>
</form>
And this is the section of the cart that receives the value:
if ( !empty( $values['variation_id'] )) {
$product_id = $values['variation_id'];
} else {
$product_id = $values['product_id'];
}
$custom_products = (array) jigoshop_session::instance()->customized_products;
$custom = isset( $custom_products[$product_id] ) ? $custom_products[$product_id] : '';
if ( ! empty( $custom_products[$product_id] ) ) :
?>
<dl class="customization">
<dt class="customized_product_label"><?php echo apply_filters('jigoshop_customized_product_label', __('Personal: ','jigoshop') ); ?></dt>
<dd class="customized_product"><?php echo esc_textarea( $custom ); ?></dd>
</dl>
<? php
endif;
?>
It's just a typo: in if ( isset( $_POST['submit']) && $_POST('submit') == 'Adauga in cos'), replace $_POST('submit')by $_POST['submit']

Categories