How to call function from one function in WordPress plugin? - php

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

Related

Validate WordPress Custom Post Type fields

I'm developing a plugin, in which the administrator has the ability to add and remove ZIP codes on the backend. I found that the best way to do this is by creating a custom post type named zip_code with only a title being supported, as that functionality is already built-in to WordPress.
I'm having trouble with validating the title, as it must be a valid ZIP code to avoid errors on the front end.
I've added the following action hooks:
// Action hook to intercept WordPress' default post saving function and redirect to ours
add_action('save_post', 'zip_code_save');
$validator = new Validator();
// Called after the redirect
add_action('admin_head-post.php', array($validator, 'add_plugin_notice'));
zip_code_save function:
public function zip_code_save() {
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (isset($_POST['post_type']) && $_POST['post_type'] == 'zip_code') {
$validator = new Validator();
if (!$validator->validate(get_the_title($post->ID))) {
$validator->update_option(1);
return false;
} else {
update_post_meta(
$post->ID,
'zip_code', get_the_title($post->ID));
}
}
}
And finally this is my Validator class:
class Validator {
//This for your your admin_notices hook
function show_error() {
echo '<div class="error">
<p>The ZIP Code entered is not valid. <b>Note</b>: only US ZIP codes are accepted.</p>
</div>';
}
//update option when admin_notices is needed or not
function update_option($val) {
update_option('display_my_admin_message', $val);
}
// Function to use for your admin notice
function add_plugin_notice() {
if (get_option('display_my_admin_message') == 1) {
// Check whether to display the message
add_action('admin_notices', array(&$this, 'show_error'));
// Turn off the message
update_option('display_my_admin_message', 0);
}
}
function validate($input) {
$zip = (isset($input) && !empty($input)) ? sanitize_text_field($input) : '';
if ( !preg_match( '/(^\d{5}$)|(^\d{5}-\d{4}$)/', $zip ) ) {
return false;
} else {
return true;
}
}
}
The above code successfully outputs an error message if the entered ZIP is not valid, however regardless of the error, it does publish the post. Is there a way to block the publishing of the post if the title is not valid?
Also, is there a way to prevent WordPress from creating drafts automatically? Since there is so little data, it's really irrelevant here, and more a hassle.

Using Forms and Get/Post in Wordpress

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.

add_settings_field not functioning with validation - returns string

The plugin admin panel works fine until I attempt to validate the settings;
register_setting('jo_plugin_options', 'jo_plugin_options', array($this, 'jo_validate_settings'));
add_settings_section('jo_main_section', 'Data Table Settings', array($this, 'jo_main_section_cb'), __FILE__); // id, title, section, callback, page
add_settings_field('jo_col_1_name', 'Column 1 Name: ', array($this, 'jo_col_1_name_setting'), __FILE__, 'jo_main_section');
add_settings_field('jo_col_2_name', 'Column 2 Name: ', array($this, 'jo_col_2_name_setting'), __FILE__, 'jo_main_section');
add_settings_field('jo_col_3_name', 'Column 3 Name: ', array($this, 'jo_col_3_name_setting'), __FILE__, 'jo_main_section');
add_settings_field('jo_file_upload', 'Upload File: ', array($this, 'jo_file_upload_setting'), __FILE__, 'jo_main_section');
So if I remove the // array($this, 'jo_validate_settings') // from the register_setting line my text boxes function fine. But when I add that validation code, it breaks them and returns this error;
*Warning: Illegal string offset 'jo_col_1_name' in /Applications/MAMP/htdocs/wp-content/plugins/plugin-rough.php on line 82*
The boxes are here:
public function jo_col_1_name_setting() {
echo "<input id='jo_col_1_name' name='jo_plugin_options[jo_col_1_name]' type='text' value='{$this->options['jo_col_1_name']}' />"; }
public function jo_col_2_name_setting() {
echo "<input name='jo_plugin_options[jo_col_2_name]' type='text' value='{$this->options['jo_col_2_name']}' />"; }
public function jo_col_3_name_setting() {
echo "<input name='jo_plugin_options[jo_col_3_name]' type='text' value='{$this->options['jo_col_3_name']}' />"; }
I did some reading online and found something semi relevant, someone saying that the keys were the same and I needed to change $this to &$this for it to function. I tried it and nothing happened, same errors.
Any ideas?
Additionally: Is it necessary to use add_settings_field for each additional field I want to add? Seems like I will be adding a very large amount of these.
var_dump shows me this:
string(31) "{$this->options[jo_col_1_name]}"
Try something like this:
if (!isset($youroptions['somename'])){
$youroptions['somename'] = '';
}
//or like this
if (!isset($youroptions['somename'])){
$youroptions['somename']= 'blank';//You can try to use
} //$youroptions['somename']= 'undefined';
Full working example (added inside "Settings" backend) :
<?php
add_action('admin_menu','create_theme_options_page');
function create_theme_options_page(){
add_options_page('Theme Options','Theme Options','administrator',__FILE__,'build_options_page');
}
function build_options_page(){
?>
<div id="theme-options-wrap">
<div style="float:left;margin-top:19px;position:absolute;" class="icon32" id="icon-tools"><br/></div>
<h2>My options page</h2>
<form method="post" action="options.php">
<?php settings_fields('plugin_options');?>
<?php do_settings_sections(__FILE__); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save changes');?>"/>
</p>
</form>
</div>
<?php
}
add_action('admin_init','register_and_build_fields');
function register_and_build_fields(){
register_setting('plugin_options','plugin_options','validate_setting');
add_settings_section('main_section','<br/><br/>Main Settings','section_cb',__FILE__);
add_settings_field('banner_headings','Banner Heading:','banner_heading_settings',__FILE__,'main_section');
}
//Banner Heading
function banner_heading_settings(){
$options = get_option('plugin_options');
if(isset( $options['banner_headings'])) {
$options = $options['banner_headings'];
} else {
$options='';
}
echo '<input type="text" name="plugin_options[banner_headings]" value="'.$options.'" />';
}
//Return our options back
function validate_setting($plugin_options){
return $plugin_options;
}
function section_cb(){
}
?>

How to save custom meta box's data?

I'm trying to learn something about WordPress plug-in development. Here is my first attemp to write something. This should create an input field on "page" pages to store a custom value.
This is the code I written, but something doesn't work. I can't save my data.
<?php
/*
Plugin Name: nw_Page_Gallery
*/
class nw_Page_Gallery {
public function __construct(){
$this->add_meta_boxes();
}
public function add_meta_boxes(){
add_action("add_meta_boxes", array($this, "add_meta_box_images"));
}
public function add_meta_box_images(){
add_meta_box("nw_page_image", "Sfondo pagina", array($this, "add_image_box"), "page");
}
public function add_image_box($post){
$back_url = get_post_meta($post->ID, 'nw_page_image', true);
echo "Il valore รจ".$back_url;
?>
<label>Lenght:</label>
<input type="text" class="widefat" name="nw_page_image" id="nw_page_image" value="<?php echo $back_url; ?>" />
<?php
add_action("save_post", function($id){
if(isset($_POST['nw_page_image'])){
update_post_meta(
$id,
'nw_page_image',
strip_tags($_POST['nw_page_image'])
);
}
});
}
}
add_action("admin_init", function(){
$PG = new nw_Page_Gallery();
});
Can someone tells me what is wrong?
You are doing your add_action("save_post", in the last place it should be...
That belongs to the __construct, or as you're doing:
public function add_meta_boxes(){
add_action("add_meta_boxes", array($this, "add_meta_box_images"));
add_action("save_post", function($id){
if(isset($_POST['nw_page_image'])){
update_post_meta(
$id,
'nw_page_image',
strip_tags($_POST['nw_page_image'])
);
}
});
}
Note that you are hooking into save_post without checking for a bunch of things (if it is revision, if doing autosave) and more problematic, without security checks: wp_nonce_field.
You can find plenty of good examples at WordPress Answers, check this search query.

PHP Concrete 5 Pass Variables to Add.php

I'm creating a new block and I want to pass a defined variable to the block instance on add.
In my controller, I have the following:
// declare the var
public $hasMap = 0;
public function add() {
$this->set('hasMap', $this->generateMapNumber());
}
The generateMapNumber() function looks like this:
public function generateMapNumber() {
return intval(mt_rand(1,time()));
}
In my add.php form I have a hidden field:
<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->hasMap?>" />
When I create a new block, hasMap is always 0 and the hidden input value is always 0 too. Any suggestions? Thank you!
--- EDIT ---
From the concrete5 documentation:
// This...
$controller->set($key, $value)
// ... takes a string $key and a mixed $value, and makes a variable of that name
// available from within a block's view, add or edit template. This is
// typically used within the add(), edit() or view() function
Calling $this->set('name', $value) in a block controller sets a variable of that name with the given value in the appropriate add/edit/view file -- you don't need to get it from within the controller object. So just call <?php echo $hasMap; ?> in your add.php file, instead of $myObj->hasMap.
It will not be the same value, because the function will give diferrent values every timy it is called.
So here's the solution. In the controller...
public $hasMap = 0;
// no need for this:
// public function add() { }
public function generateMapNumber() {
if (intval($this->hasMap)>0) {
return $this->hasMap;
} else {
return intval(mt_rand(1,time()));
}
}
And then in the add.php file...
<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->generateMapNumber()?>" />
It works perfectly. On add, a new number is generated and on edit, the existing number is drawn from the hasMap field in the db.
Thanks for all the input. Hope that helps someone else!

Categories