I'm using a plugin which retrieves the value of some radio buttons based on what values I type in the plugin dashboard.
I want to change that function with a function which retrieves the post meta of a post as the value.
This is the function for retrieving the post meta :
<?php echo get_post_meta($post->ID, 'key', true); ?>
and this is the actual code for retrieving the values:
<?php
/* Radio form */
class ECF_Radio extends ECF_Field_Type {
protected $name = 'radio';
public function form_field( $ref, $field ) {
global $ecfdb;
$name = $ecfdb->html_string( $field->name );
echo "<div class='ecf-form-field-title'>$name</div>\n";
$values = preg_split( '/, ?/', $field->values );
echo '<div class=\'ecf-form-field-input\'>';
foreach ( $values as $i => $value ) {
$checked = checked( $i, 1, false );
echo "<p><label><input type='radio' name='$ref' "
. "value='$value'$checked /> $value</p></label>\n";
}
echo '</div>';
}
public function get_description() {
return "Radio selection field";
}
}
new ECF_Radio();
?>
My question is how can I use the function for retrieving the post meta for values?
What exactly do I need to change inside the code to retrieve the post meta not the values written in a filed.
Thank you!
Related
I have tried the javascript refresh options on submit (on the <form> but none of them work. If I put the javascript refresh with the submit function, then every time it refreshes, the item gets sent to the database (do not want that).
What I have tried
onsubmit="location.reload()"
onsubmit="window.location.reload()"
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"
It currently renders an array of items with a checkbox. When I click the checkbox, the item gets sent to the database as read -- but it stays on the screen (unless I revisit the page manually in the address bar). I am developing in WordPress using PHP.
Perhaps there is a small trick we can use just to remove the array that is sent on submit out of the books_array as soon as the submit button is clicked? Or reload the books_array after submission?
Here is my code:
form function
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
foreach loop
function user_add_new() {
global $wpdb;
$value = $_POST["checkbox"][0];
$bookTOadd = $_POST["item" . $value];
$listTOadd = $_POST["listID" . $value];
$userID = $_POST["userID" . $value];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
I keep running into issues, but I am so grateful to anyone who can give a little insight on how to approach this best. Thank you for taking the time to read this!
Problem fixed by creating a WordPress action and calling/rendering it only when the form is clicked (since before the action was rendered on page load just not executed until the click, which was 1 thing causing my issue re the not refreshing the entire page after form submission). No ajax (though its great with wordpress) nor .php files (that would just be a workaround).
Removed the action="" from my form, since we'll be using wordpress to do this.
Added this line <?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?> to my form, you can see that below (this will help call my action in my WordPress file, associating it with this form)
<form method="post">
<?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?>
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
And this is my action (steps are described in the notes within the code) which makes the post when the action is called upon submit. It only submits the data after form validation. Once the data has been submitted, it then reloads the page using a built in WP function:
add_action('book_check', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST[book_send_nonce]) &&
wp_verify_nonce($_POST[book_send_nonce], 'book_send')
) {
// form validation
function validate_book_data(){
$errors = new WP_Error();
if (isset($_POST[ 'item' ]) && $_POST[ 'item' ] !== '') {
$errors->add('item_error', 'Book not selected');
}
if (isset($_POST[ 'listID' ]) && $_POST[ 'listID' ] == '') {
$errors->add('list_error', 'No valid list this belongs to.');
}
if (isset($_POST[ 'userID' ]) && $_POST[ 'userID' ] == '') {
$errors->add('user_error', 'Not signed in');
}
return $errors;
}
// If form validation passes, send the info
$pass_validation = validate_book_data($_POST);
if ( $pass_validation ) {
$value = $_POST["checkbox"][0];
$data = array(
'userID' => $_POST["userID" . $value],
'bookID' => $_POST["item" . $value],
'list' => $_POST["listID" . $value],
);
global $wpdb;
// Select the table to post the data to
$book_checked = $wpdb->prefix . 'plugin_read';
// Insert the data to the table
$wpdb->insert($book_checked, $data, '%s');
// Set page refresh
$refresh_page = wp_redirect($_SERVER['HTTP_REFERER']);
// After data is inserted, refresh the page
wp_safe_redirect( $refresh_page );
// and exit
exit();
}
}
});
Using this action solves the issue of the page not refreshing because the action is only called when the checkmark is clicked and within the action, I refresh the page only after the data has sent.
I hope this will help anyone else with the issue. Coding from 8am-2am lately really had my brain become mush so the solution took me a short bit.
So, I've been pulling my hair out over this for longer than I'd care to admit. I am trying to create a bunch of checkboxes in profile.php and user-edit.php for a plugin that is populated by an array. For starters, this works:
//<!-- "HTML" -->
function profile_fields($user) {
$user_id = $user->ID;
<input type='hidden' name="user_id" value="<?php echo $user_id ?>" />
<input type="checkbox" id="some-setting" name='some-setting'
<?php if (get_user_meta( $user->ID, 'somePref', true ) == '1'){ echo 'checked'; } ?> />
<label for="some-setting">TEST 2</label>
//PHP
function update_field_value($user_id) {
if ( isset($_POST['some-settings'], $user_id ) && $_POST['some-settings'] == 'on') {
update_user_meta( $user_id, 'somePref', '1');
} else {
update_user_meta( $user_id, 'somePref', NULL);
}
}
HOWEVER, what I have generates Undefined offset... and Trying to access array offset on value of type null... that I can't trace the origin of when using:
class Some_Class
{
//Array of user specialties to be displayed
var $userSpecialtiesList;
//Array of ids for input fields
var $userSpecialtiesIDs = array();
//Array of meta values for input fields
var $metaValues = array();
//Array of meta value names for use with accessing info
var $metaNames = array();
/**
* initialize
*
* I use this to populate the array and call add_action
*/
function initialize(){
$this->userSpecialtiesList = array(
/* some information here */
);
add_action( 'show_user_profile', array($this, 'extra_profile_fields') );
add_action( 'edit_user_profile', array($this, 'extra_profile_fields') );
add_action( 'personal_options_update', array($this, 'update_field_value') );
add_action( 'edit_user_profile_update', array($this, 'update_field_value') );
}
/**
* extra_profile_fields
* I use this to generate the input fields that the user sees
*/
function extra_profile_fields( $user ) {
$user_id = $user->ID;
//I used this for testing
//$meta_value = get_user_meta( $user->ID, 'somePref', true );
?>
<h3><?php _e("Some Title", "blank"); ?></h3>
<table class="form-table">
<!-- Some unrelated stuff here -->
<tr>
<th><h4><?php _e("Specialties"); ?></h4></th>
<td>
<fieldset>
<!-- Some more unrelated stuff here -->
<?php
$this->generateCheckboxes($user_id);?>
</fieldset>
</td>
</tr>
</table>
<?php
}
/**
* generateID
*
* Partially complete function to generate field ids and meta keys
*/
function generateID($phrase, $arrValue, $style){
//Remove illiegal characters and leave only alphanumeric
$arrValueUpdated = preg_replace('/[^a-zA-Z\d:]/', "", $arrValue);
switch($style){
//Use Dashes
case $style == "-":
case $style == "dash":
return strtolower($phrase) . "-" . strtolower($arrValueUpdated);
//Use camelCase
case $style == "camelCase":
return strtolower($phrase) . ucfirst($arrValueUpdated);
//Default is alltogether
default:
return strtolower($phrase) . strtolower($arrValueUpdated);
}
}
/**
* generateCheckboxes
*
* I use this to generate checkboxes from the array instantiated above
*/
function generateCheckboxes($userID){
foreach($this->userSpecialtiesList as $userSpecialty){
//Create unique id for input fields and add it to array for later
$inputID = $this->myGenerateID("specialty", $userSpecialty, "dash");
array_push( $this->userSpecialtiesIDs, $inputID );
//Create meta key and add it to array of meta keys for use with update_user_meta later
$metaName = $this->myGenerateID("pref", $userSpecialty, "camelCase");
array_push( $this->metaNames, $metaName );
//Create variable for meta values and add it to array for later
$meta_value = get_user_meta( $userID, $metaName, true );
array_push( $this->metaValues, $meta_value );
?>
<div class="my-checkbox-class">
<input type='hidden' name="user_id" value="<?php echo $userID ?>" />
<input type="checkbox" id="<?php echo $inputID; ?>" name='<?php echo $inputID; ?>'
<?php if ($meta_value == '1'){ echo 'checked'; } ?> />
<label for='<?php echo $inputID; ?>'><?php _e($userSpecialty); ?></label>
</div>
<?php }
function update_field_value($user_id) {
$user_id = $_POST['user_id'];
$uslIndex = 0;
foreach($this->userSpecialtiesList as $userSpecialty){
if ( isset($_POST[$this->userSpecialtiesIDs[$uslIndex]], $user_id ) && $_POST[$this->userSpecialtiesIDs[$uslIndex]] == 'on') {
update_user_meta( $user_id, $this->metaNames[$uslIndex], '1');
} else {
update_user_meta( $user_id, $this->metaNames[$uslIndex], NULL);
}
$uslIndex++;
}
}
}
function some_class_func() {
global $some_class_func;
// Instantiate only once.
if( !isset($some_class_func) ) {
$some_class_func = new Some_Class();
$some_class_func->initialize();
}
return $some_class_func;
}
// Instantiate
some_class_func();
In posting this, I obfuscated some of the variable names and removed some unnecessary bits for clarity; I also realize as I went through it that I have some artifacts from re-writing portions of it that may be part of my problem but I've chosen to leave them in.
If I get this on my own then I will post the solution for everyone; in any case though, I offer many thanks in advance for any and all answers / help!
Sometimes its easier to troubleshoot if you separate things out
$postval = isset($this->userSpecialtiesIDs[$uslIndex]) ? $this->userSpecialtiesIDs[$uslIndex] : null;
$user_id = $user_id ?? null;
$condition1 = $user_id && $postval && isset($_POST[$postval]);
$condition2 = $postval && $_POST[$postval] === 'on';
if ($condition1 && $condition2) {
// do the thing
}
and...
if ($user_id && isset($this->metaNames[$uslIndex])) update_user_meta( $user_id, $this->metaNames[$uslIndex], NULL);
Alright, so it seems like my problem was perhaps one of scope so what I did was basically just create an array elsewhere and hand it to the update function. So, I pretty much left initialize(), extra_profile_fields(), and generateID() alone and instead I made the following changes:
//Generate the input tag ID and meta key / name
// and then create the HTML for checkboxes
function generateCheckboxes($userID){
foreach($this->userSpecialtiesList as $userSpecialty){
$inputID = $this->generateID("specialty", $userSpecialty, "dash");
$metaName = $this->generateID("pref", $userSpecialty, "camelCase"); ?>
<div class="prof-checkbox">
<input type='hidden' name="user_id" value="<?php echo $userID ?>" />
<input type="checkbox" id="<?php echo $inputID; ?>" name='<?php echo $inputID; ?>'
<?php if (get_user_meta( $userID, $metaName, true ) == '1'){ echo 'checked'; } ?> />
<label for='<?php echo $inputID; ?>'><?php _e($userSpecialty); ?></label>
</div>
<?php }
}
/**
* generate_array()
* Creates, populates, and returns a multi-dimensional array holding
* the input tag's id, meta key, and text value.
*
* #return $userSpecialtiesArr Array A multi-dimensional array holding the input tag's id ("id"), meta key "meta", and text "text"
*/
function generate_array(){
$userSpecialtiesArr = array();
foreach($this->userSpecialtiesList as $userSpecialty){
$userSpecialtyPKG = array(
"text"=>$userSpecialty,
"id"=>$this->HgenerateID("specialty", $userSpecialty, "dash"),
"meta"=>$this->generateID("pref", $userSpecialty, "camelCase"),
);
array_push($userSpecialtiesArr, $userSpecialtyPKG);
}
return $userSpecialtiesArr;
}
function update_field_value($user_id) {
$user_id = $_POST['user_id'];
//Generate array to hold the neccessary information
$userSpecialtiesArr = $this->generate_array();
//Use an iterator to dynamically add the necessary unique ID and meta key.
foreach($userSpecialtiesArr as $userSpecialty) :
if ( isset($_POST[$userSpecialty['id']], $user_id ) && $_POST[$userSpecialty['id']] == 'on') {
update_user_meta( $user_id, $userSpecialty['meta'], '1');
} else {
update_user_meta( $user_id, $userSpecialty['meta'], NULL);
}
endforeach;
}
Not sure if this'll help anyone, but if not Kinglish also had a pretty great answer and hopefully both can reduce somebody out there pulling out their hair over the same thing.
I need to show a button for each value and do some function,
The following code is working for displaying the button only
but it doesn't show the result of the function after the button
$ids = [1,2,3,4,5,6];
foreach( $ids as $id ) {
$post_url = get_the_permalink($id);
echo $post_url."<input type='submit' name='doit' value='Change'><br>";
$doit = $_POST['doit'];
if(isset($_POST['doit'])){
echo get_post_field( 'post_name', $id)."<br>";
}
}
Can you try this solution?
I added an ID to the name field so when you click the button it runs only the if statement of this button.
Also make sure that the buttons are wrapped inside a form tag with a method attribute.
echo "<form method='post'>";
$ids = [1,2,3,4,5,6];
foreach( $ids as $id ) {
$post_url = "test.com";
echo "$post_url <input type='submit' name='doit_$id' value='Change'><br>";
if(isset($_POST['doit_'. $id])){
echo $id . "_RUNNING <br>";
}
}
echo "</form>";
Also $doit = $_POST['doit']; prints a NOTICE in php when it is not defined, it is better to check if $_POST['doit'] isset before assigning it to a variable.
I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.
I have a list of favorite cars which i have added to each favorite car a checkbox for letting the user to remove the favorite car from his favorite car list. The problem is that the checkbox is working in a different way: If I check any car (1st, second.. last or multiple cars) and after hit submit the car that will get removed is the last one added instead of removing the selected one. If I check multiple cars, happens same thing, removes only the last car added.
PHP
public function GetFavoriteCars() {
include("inc/membersite_config.php");
$email = $fgmembersite->UserEmail(); // this is how I take the e-mail of the
global $base_path;
$FavoriteCars = $this->QueryResult("SELECT * FROM favoritecar WHERE email='$email'");
if (count($FavoriteCars)) {
$mystring='http://';
echo '<form action="" class="deletebutton" method="post">';
echo '<input type="submit" name="deletebtn" id="deletebtn" value="Submit">';
echo '<div class="roster_slideri-login">';
foreach ($FavoriteCars as $FavoriteCar) {
$carlink = $FavoriteCar->favoritecarlink;
echo '<div class="car-info-col-login">';
echo '<input type="checkbox" name="checkbox" value="'.$carlink.'" class="checkbox-login">';
$val=strpos($FavoriteCar->favoritecarimg,$mystring);
if ($val !== false) {
if($FavoriteCar->favoritecarimg!='') {
echo '<a href="'.$base_path.'detail-page_'.$FavoriteCar->favoritecarlink.'">';
echo '<img src="'.$FavoriteCar->favoritecarimg.'" alt="'.$FavoriteCar->favoritecartitle.'" width="160" height="120" />';
echo '</a>';
echo '<div class="name">'.substr($FavoriteCar->favoritecartitle,0,20).'</div>';
echo '</div>'; //car-info-col-login
}
} else {
echo '<a href="'.$base_path.'detail-page_'.$FavoriteCar->favoritecarlink.'">';
echo '<img src="'.$base_path.'uploads/no-img.jpg" alt="'.$FavoriteCar->favoritecartitle.'" width="160" height="120" />';
echo '</a>';
echo '<div class="name">'.substr($FavoriteCar->favoritecartitle,0,20).'</div>';
echo '</div>';
}
}
echo '</form>';
if (isset($_POST["checkbox"])) {
$this->QueryResult("DELETE from favoritecar WHERE email='$email' AND favoritecarlink='$carlink'");
echo '<script type="text/javascript">alert("Car had been deleted");</script>';
}
echo '</div>'; // div roster_slideri-login
}
}
Explaning:
$email = $fgmembersite->UserEmail(); - this is how I take the e-mail of the current logged in user. It will echo "email_of_logged_in_user#domain.com"
QueryResult is a custom function that looks like this. I usually use it for SELECTING purposes but it seams that is working for deleting purposes too.
abstract class DBDetails {
protected $link = NULL;
protected function connector() {
global $DBHOSTNAME;
global $DBUSERNAME;
global $DBPASSWORD;
global $DBNAME;
$this->link = mysqli_connect($DBHOSTNAME, $DBUSERNAME, $DBPASSWORD, $DBNAME) or die("Can't connect to MySQL server on localhost");
}
protected function close() {
mysqli_close($this->link);
}
}
abstract class N2 extends DBDetails {
public function QueryResult($strQuery) {
$this->connector();
$query = mysqli_query($this->link, $strQuery);
$arr = array();
if ($query) {
while ($result = mysqli_fetch_object($query)) {
array_push($arr, $result);
}
}
$this->close();
return $arr;
}
}
Expected output
When I check the checkbox of a car, it should delete only that car. If I check the checkboxes of multiple cars, should delete the specific cars that I checked.
Please help, I am quite a noob in checkboxes. I have checked lots of questions from here, but did not find my answer.
In this line :
echo '<input type="checkbox" name="checkbox" value="'.$carlink.'" class="checkbox-login">';
--------------
When using multiple checkboxes with same name , you would need to include [] in the name :
echo '<input type="checkbox" name="checkbox[]" value="'.$carlink.'" class="checkbox-login">';
----------------
Then $_POST["checkbox"] will be an array and you can use foreach on it to get all the checked values .
if( isset( $_POST["checkbox"] ) )
{
foreach( $_POST["checkbox"] as $value )
{
/* $value contains $carlink */
echo $value; // For test purpose
/* Sanitize and use it to identify and delete the corresponding row */
}
}
( Rather than name="checkbox[]" it might be better to choose another name . )