Using Forms and Get/Post in Wordpress - php

I have a page called wc-info.php which is loaded using this function on a page called plugin_admin.php
public function iris_info()
{
include('partials/wc-info.php');
}
public function get_gtin_woo_db($GTIN_Val)) {
// get the gtin number
$key = 'sku';
$getTheMeta = get_post_meta($GTIN_Val, $key, TRUE);
if ($getTheMeta != '') {
$gtinSuccess = 'Yes';
} else {
$gtinSuccess = 'No';
}
return $gtinSuccess;
}
The partial looks like this:
<div class="welcome-panel-column">
<form action="POST">
<input type="text" action="" name="gtin_search">
<input type="submit" action="" name="gtin_submit">
</form>
</div
The problem is how do I pass the POST values to the plugin_admin.php page in wordpress? When submit is clicked, I need the page to be reloaded, and have POST passed to the function.

Try this,
function custom_function() {
if ( isset( $_POST['gtin_search'] ) ) {
// Update to the function which you are going to use
get_gtin_woo_db($POST['gtin_search']);
} // end if
}
add_action( 'init', 'custom_function' );
I hope this will help.

Related

Custom Post Type Meta Box not saving

I have created a CPT called 'encyclopedia' in WordPress. I am then creating a couple of Meta Fields inside that, just some simple Text Fields, but they are not saving at the moment and I cannot figure out why. Can someone help?
/*
=========================================================================
Custom Meta Fields - English version
=========================================================================
*/
function custom_meta_box_markup()
{
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<label for="english_version">Description</label>
<input name="english_version" type="text" value="<?php echo get_post_meta($object->ID, "english_version", true); ?>">
</div>
<?php }
function add_custom_meta_box()
{
add_meta_box("english_version", "English Version", "custom_meta_box_markup", "encyclopedia", "advanced", "high", null);
//add_meta_box("german-version", "German Version", "custom_meta_box_markup", "encyclopedia", "advanced", "high", null);
}
add_action("add_meta_boxes", "add_custom_meta_box");
function save_custom_meta_box($post_id, $post, $update)
{
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__))){
return $post_id;
}
if(!current_user_can("edit_post", $post_id)){
return $post_id;
}
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE){
return $post_id;
}
$slug = "post";
if($slug != $post->post_type){
return $post_id;
}
$meta_box_text_value = "";
if(isset($_POST["english_version"]))
{
$meta_box_text_value = $_POST["english_version"];
}
update_post_meta($post_id, "english_version", $meta_box_text_value);
}
add_action("save_post_encyclopedia", "save_custom_meta_box", 10, 3);
The relevant code is above and I currently have it stored in the functions.php file of my child theme.
Thanks
As per my comment on your question, after fixing the post slug, you still have something wrong on the code.
On your meta box output function custom_meta_box_markup, you are using get_post_meta($object->ID, "english_version", true) without defining $object.
I have tested your code and your data is being saved in DB. But as $object->ID is returning nothing, it's not showing anything on the input textfield. custom_meta_box_markup receives a $post object, which you have missed. Update your code like this:
function custom_meta_box_markup($post) {
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<label for="english_version">Description</label>
<input name="english_version" type="text" value="<?php echo get_post_meta($post->ID, "english_version", true); ?>">
</div>
<?php }

How to call function from one function in WordPress plugin?

How can I call specific function in plugin in admin page.
I am submitting a form in WordPress plugin. On submitting I want to check validity of key which is entered in the form. I have a function which checkes the validity of the key. I want to call that function from the function of the form.
I have tried few things but it gives me error of
Using $this when not in object context
Here is my code
class WP_Cms_Plugin{
function __construct() {
add_action( 'admin_menu', array( $this, 'cms_options_panel' ));
}
function cms_options_panel() {
add_menu_page('CMS', 'Cms', 'manage_options', 'cms-dashboard', array(__CLASS__,'cms_setting_form'), 'dashicons-building');
}
function cms_setting_form()
{
if(isset($_POST['btn_submit']))
{
$secret_key = $_POST['project_secret_key'];
if($secret_key=='' || empty($secret_key))
{
$error['project_secret_key'] = 'Please enter Secret Key.';
}
if(empty($error)){
call to cms_check_key();
echo "Key validated successfully";
}
else
{
echo "Please use proper Key";
}
}
?>
<form method="post">
<div>Secret Key</div>
<input type="text" name="project_secret_key" value="<?php echo esc_attr( get_option('cms_secret_key') ); ?>" required/>
<?php submit_button('Submit','primary','btn_submit'); ?>
</form>
<?php
}
function cms_check_key($secret_key)
{
code to check validity
}
}
$cmsservice = new WP_Cms_Plugin();
The issue is your callable specifies using the WP_Cms_Plugin class and not an instance of it (object).
Either change your cms_options_panel function to:
add_menu_page('CMS', 'Cms', 'manage_options', 'cms-dashboard', array($this,'cms_setting_form'), 'dashicons-building');
(replace __CLASS__ with $this)
Or try a static function
static function cms_check_key($secret_key)
and then call WP_Cms_Plugin::cms_check_key($secret_key) from the form.
PHP Static Keyword

Learning OOP in PHP. Is this the correct way to do this?

I've just started learning to do oop and I just wanted to put the most basic set of code together to make sure I'm understanding things correctly. I wanted to capture a form entry in the $_POST variable and pass it to an object to have it output something back to the browser. No SQL, no Security measures, just proof of understanding.
Here is the form:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
And here is the class:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
This is working without error right now but it doesn't seem like I should have to enter the $_POST in the echo statement on the form page and in the object on the class page. Is this correct? Should I instead be collecting that in the $entry property. It's working, but I don't think the execution is correct. Thanks in advance!
Your right you don't need to enter the $_POST variable into that function, you could change it to this and it would work without entering the post:
public function processName() {
return "You entered " . $this->entry . ".";
}
Because right now processName function doesn't do anything with the class's public $entry variable, it just echoes out what you put in when you call the function.
What you likely want to do instead is:
Change public $entry; to protected $entry;
Then:
public function getEntry() {
return $this->entry;
}
Then in your html, after constructing the class, you can just put this to get the $entry variable:
echo $name->getEntry();
Coming from Symfony framework background. You could do something right this:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>

PHP MVC passing form values to controller and model

I'm trying to send POST values to the controller and then pass it to the model in PHP but I'm not sure how to go about doing this.
This part of the controller is to see if the user requests for a view like ?action=game. This works.
But I'm trying to modify it to allow $_POST to be sent to it and then to the model.
function __construct()
{
if(isset($_GET['action']) && $_GET['action']!="" )
{
$url_view = str_replace("action/","",$_GET['action']);
if(file_exists("views/" . $url_view . ".php" ))
{
$viewname = $url_view;
$this->get_view($viewname . ".php");
}
else
{
$this->get_view('error.php');
}
}
else
{
$this->get_view('home.php');
}
}
Here's what I got. In the registration form page, the action of the form is ?process=register but it doesn't work.
if(isset($_POST['process']) == 'register)
{
$this->get_view('register.php')
}
Get_view function determines what model to bind with the view
function get_view($view_name)
{
$method_name = str_replace(".php","",$view_name);
if(method_exists($this->model,$method_name))
{
$data = $this->model->$method_name();
} else {
$data = $this->model->no_model();
}
$this->load->view($view_name,$data);
}
Since the action of your form is ?process=register, then process is still in the $_GET superglobal. What you can do to make it use post is add a hidden input field containing process.
With this:
<form method="post" action="script.php?process=register">
The form is POST'ed to script.php?process=register so you have $_GET['process'], not $_POST['process'].
Try this instead:
<form method="post" action="script.php">
<input type="hidden" name="process" action="register" />
To have $_POST['process']. Alternatively, you could keep the "process" in the GET and switch your if statement to check $_GET instead of $_POST.

Using $_POST += array() for default values

I'm finishing up a small contact form and had a question about providing default values for $_POST. The reason I'm asking about default values is because within my form I have fields like this:
<input type="text" name="fullname" value="<?php echo $_POST['fullname']; ?>" />
Clearly I would like to retain the submitted value if I do not permit the data to clear. This raises errors when the page is first loaded, since there is no value for $_POST['fullname'].
To my question: is there anything I should be concerend about providing default values to the $_POST array like I'm doing in the next code-sample:
$_POST += array(
'fullname' = '',
);
If $_POST['fullname'] already exists, it will be retained - if it doesn't, it will be created within the array. This way, upon loading the form, blank values will be presented in the input fields.
Don't worry, all
I sanitize my data
Thank you for the help
Even if you are doing so, put that data in your container, do not modify superglobals. Create class that'll contain your data - then you'll have the interface do sanitize, manipulate and get it te proper way. Import data from $_POST and then validate, if all necessary values are in.
As for code:
<?php
class PostData
{
private $data;
public function __construct(array $data)
{
$this->data = is_array($data)
? $data
: array();
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function get($key, $default, $escaping)
{
if(isset($this->data[$key]))
{
switch($escaping)
{
case 'htmlspecialchars':
{
return htmlspecialchars($this->data[$key]);
break;
}
case 'mysql_real_escape_string':
{
return mysql_real_escape_string($this->data[$key]);
break;
}
// and so on, your invention goes here
default:
{
return $this->data[$key];
}
}
}
else
{
return $default;
}
}
}
$postData = new PostData($_POST);
Create function:
function displayValue($field) {
if(isset($_POST[$field])) {
echo 'value="' . htmlentities($_POST[$field]) . '"';
}
}
And then use like:
<input type="text" name="fullname" <?php displayValue('fullname'); ?> />
You can also do it like this:
<?php echo empty($_POST['fullname']) ? null : $_POST['fullname']; ?>

Categories