save and retrieve custom plugin options input - wordpress

I'm new to creating wordpress plugin. I want to create a plugin that display custom page option under setting options of wp-admin section and to save the value of input data and retrieve it, I have gone through the tutorial of otto press
I created a folder in wp-content/plugin/ named new-setting-plugin inside the folder is a file named new-setting-plugin.php so the entire file path is wp-content/plugin/new-setting-plugin/new-setting-plugin.php
the code of the file new-setting-plugin.php is given at the end of the table. After creating the code I went onto plugin page of wp-admin and installed the plugin, it was all fine.
Now when i press "Save setting" button it shows the message "Setting saved" but i can't see the value inside the input fields
I'm attaching my images to preview what it is appearing in my plugin page
When go to the plugin page i see the following input fields:
Now I'm entering the value to input fields:
When I clicked the "Save Setting" button i got the following message after page refreshed
Here is my code
<?php
add_action('admin_menu', 'add_page');
if ( !function_exists( 'add_page' ) ) {
//function to add page under setting options in wordpress admin section
function add_page() {
add_options_page('New Setting Page', 'New Setting', 'manage_options', 'plugin', 'plugin_options_frontpage');
}
}
function plugin_options_frontpage() {
?>
<div class="wrap">
<?php screen_icon('users'); ?><h2>New Setting Page title</h2>
<form action="options.php" method="post">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections('plugin'); ?>
<table class="form-table">
<tr valign="top">
<td colspan="2">
<input name="Submit" type="submit" class="button button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</td>
</tr>
</table>
</form>
</div>
<?php
}
add_action('admin_init', 'plugin_admin_init');
function plugin_admin_init(){
register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );
add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'plugin');
add_settings_field('plugin_text_input1', 'Input 1', 'plugin_input1', 'plugin', 'plugin_main');
add_settings_field('plugin_text_input2', 'Input 2', 'plugin_input2', 'plugin', 'plugin_main');
}
function plugin_section_text() {
echo '<p>New input setting to be saved.</p>';
}
function plugin_input1() {
$options = get_option('plugin_options');
echo "<input id='plugin_input1' class='normal-text code' name='plugin_options[text_string]' size='30' type='text' value='{$options['text_string']}' />";
}
function plugin_input2() {
$options = get_option('plugin_options');
echo "<input id='plugin_input2' class='normal-text code' name='plugin_options[text_string]' size='30' type='text' value='{$options['text_string']}' />";
}
function plugin_options_validate($input) {
$options = get_option('plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options;
}
?>
What wrong in my code, How can I correct my code and is there a way to show the value of input fields outside the field in same page in a table?

You won't see them there. You have to get_options.
For your code, if you do var_export( get_option('plugin_options') ); you'll see those saved settings/values.

check the validation criteria.
preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])
Comment the code inside validation function and test.
function plugin_options_validate($input) {
$options = get_option('plugin_options');
//$options['text_string'] = trim($input['text_string']);
//if(!preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])) {
//$options['text_string'] = '';
//}
return $options;
}

You have to change the 'name' of the inputs :
function manage_lists_cc_input1() {
$options = get_option('manage_lists_cc_options');
echo "<input id='manage_lists_cc_input1' class='normal-text code' name='manage_lists_cc_options[0]' size='30' type='text' value='{$options['text_string_0']}' />";
}
function manage_lists_cc_input2() {
$options = get_option('manage_lists_cc_options');
echo "<input id='manage_lists_cc_input2' class='normal-text code' name='manage_lists_cc_options[1]' size='30' type='text' value='{$options['text_string_1']}' />";
And just change the validate script to get the values (this is a simple example without validation ) :
function manage_lists_cc_options_validate($input) {
$options['text_string_0'] = $input[0];
$options['text_string_1'] = $input[1];
return $options;
}

Related

My custom add_meta_box is not showing up in wordpress admin panel

New to Wordpress and struggling with the meta boxes. Unable to get my piece of code to work/show, nor was I able find examples that work. Nothing just wants to show up in the admin panel and have no clue what I'm missing / doing wrong.
Until now it looks like it's not triggering the callback function or something.
What I want to do:
Show a checkbox to hide the page's title
What I see:
No checkbox is showing up on the page edit screen
My code in functions.php:
function twentyseventeenchild_hide_title() {
add_meta_box(
'no-title', // Unique id
__( 'Hide title' ), // Title
'twentyseventeenchild_hide_title_callback', // Callback
'post', // Screen (such as post type, link or comment)
'normal', // Context (normal, advanced, side)
'default' // Priority (default, core, high, low)
// Callback arguments
);
}
add_action( 'add_meta_boxes', 'twentyseventeenchild_hide_title' );
/**
* Meta box display callback.
*
* #param WP_Post $post Current post object.
*/
function twentyseventeenchild_hide_title_callback( $post ) {
$meta = get_post_meta($post->ID, '_title', true);
?>
<label><?php __('Hide title') ?></label>
<input id="no_title" type="checkbox" autocomplete="off" value="<?=esc_attr($meta)?>" name="page_title">
<?php
}
You're using checkbox incorrectly.
See input checkbox: https://www.w3schools.com/tags/att_input_type_checkbox.asp
Your method need to be like:
function twentyseventeenchild_hide_title_callback( $post ) {
$meta = get_post_meta($post->ID, '_title', true);
?>
<input id="no_title" type="checkbox" <?php ($meta === '1' ? 'selected' : ''); ?> name="page_title">
<label for="no_title"><?php _e('Hide title') ?></label>
<?php
}
_e() is for translate and echo, __() only return string and not print it.
($meta === '1' ? 'selected' : ''); is because when you save metabox value truewill be saved as string 1. With this ternary you can show as selected this metabox if value is euqals 1 (as string).

Woocommerce meta box option for shop_order admin order

I would like to add a meta box in the manual admin orders page of woocommerce.
This meta box will need to be a checkbox that if selected triggers an action
so far from what i have read it will need to start something like this
function add_meta_boxes()
{
add_meta_box(
'Meta Box', // ID, should be a string.
'woocommerce-action-trigger', // Meta Box Title.
'my_meta_box', // Your call back function, this is where your form field will go.
'shop_order', // The post type you want this to show up on, can be post, page, or custom post type.
'side', // The placement of your meta box, can be normal or side.
'default' // The priority in which this will be displayed.
);
}
Then i need a form that if admin selects will trigger an action
function triggeraction_meta_box() {
$checkboxMeta = make_action_happen();
}
<input type="checkbox" name="action" id="action" value="yes" <?php if ( isset ( $checkboxMeta['action'] ) ) checked( $checkboxMeta['action'][0], 'yes' ); ?> />make_action_happen<br />
As you can see at this point i want the checkbox to unhook something in woocommerce for this order only, so it only happens in this page for this session.
Anybody please help my coding is very very very basic.
function wporg_add_custom_box() {
$screens = ['shop_order', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Custom Meta Box Title', // Box title
'wporg_custom_box_html', // Content callback, must be of type callable
$screen // Post type
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box');
function wporg_custom_box_html($post)
{
$value = get_post_meta($post->ID, '_wporg_meta_key', true);
?>
<label for="wporg_field">Description for this field</label>
<select name="wporg_field" id="wporg_field" class="postbox">
<option value="">Select something...</option>
<option value="something" <?php selected($value, 'something'); ?>>Something</option>
<option value="else" <?php selected($value, 'else'); ?>>Else</option>
</select>
<?php
}
function wporg_save_postdata($post_id) {
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
}
}
add_action('save_post', 'wporg_save_postdata');

Create defaults to use in return in shortcode - Wordpress plugin

I'm making my first plugin to Wordpress which adds a shortcode that I can use in my header.
The plugin integrates with Wordpress option page. All admin related works fine including writing top wp_options table and/or delete/update fields.
My problem is in the custom shortcode itself (at the bottom).
What I want to achieve is, when get_option('bfcsc_logout_link') is not set in admin, a default value should be returned.
And of course, I am looking for the 'nice way', so my code looks good as well :) When the plugin works as I want to in the end, I'm thinking about taking it a step further and separate the code into init files etc, making it more professional.
Below is the full code (excluding assets):
<?php
/*
Plugin Name: Brokenfruit Custom Login Shortcode
Plugin URI: https://www.brokenfruit.dk/
Description: Adds custom login shortcode for Brokenfruit
Version: 1.0
Author: Kenn Nielsen
Author URI: https://www.brokenfruit.dk/
License: GPL
*/
// Meaning of abbreviations:
// bfclsc = brokenfruit custom login shortcode
/* Register styles and scripts */
function bfcsc_enqueue_scripts() {
global $wpdb;
$screen = get_current_screen();
if ( $screen->id != 'settings_page_brokenfruit-custom-shortcodes' )
return; // exit if incorrect screen id
wp_enqueue_style( 'brokenfruit-shortcodes-styles', plugins_url( '/css/styles.css', __FILE__ ) );
wp_enqueue_style( 'bootstrap', plugins_url( '/css/bootstrap.css', __FILE__ ) );
wp_enqueue_script('admin_js_bootstrap_hack', plugins_url( '/scripts/bootstrap-hack.js', __FILE__ ), false, '1.0.0', false);
}
add_action('admin_enqueue_scripts', 'bfcsc_enqueue_scripts' );
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'bfcsc_install');
/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'bfcsc_remove' );
function bfcsc_install() {
/* Creates new database field */
add_option('bfcsc_logout_link', '', '', 'yes');
add_option('bfcsc_login_link', '', '', 'yes');
add_option('bfcsc_account_link', '', '', 'yes');
}
function bfcsc_remove() {
/* Deletes the database field */
delete_option('bfcsc_logout_link');
delete_option('bfcsc_login_link');
delete_option('bfcsc_account_link');
}
if (is_admin() ) {
function add_bfcsc_option_page() {
add_options_page(
'Brokenfruit Custom Shortcodes', // The text to be displayed in the title tag
'Brokenfruit Custom Shortcodes', // The text to be used for the menu
'administrator', // The capability required to display this menu
'brokenfruit-custom-shortcodes', // The unique slug name to refer to this menu
'bfcsc_html_page'); // The function tooutput the page content
}
/* Call the html code */
add_action('admin_menu', 'add_bfcsc_option_page');
}
function bfcsc_html_page(){
?>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>
<div class="bootstrap-wrapper">
<div class="row top-buffer">
<div class="col-md-8">
<div><h1>Brokenfruit Custom Login Shortcode</h1></div>
<p>Til brug for shortcode:<br/><span class="shortcode-preview">[custom_login]</span></p>
<div class="top-buffer"></div>
<h5>Link til log ud:</h5><input placeholder="Eksempel: wp-login.php?action=logout" class="form-control" name="bfcsc_logout_link" type="text" id="bfcsc_logout_link" value="<?php echo get_option('bfcsc_logout_link'); ?>" /></td>
<div class="top-buffer"></div>
<h5>Link til log ind:</h5><input placeholder="Eksempel: /log-ind/" class="form-control" name="bfcsc_login_link" type="text" id="bfcsc_login_link" value="<?php echo get_option('bfcsc_login_link'); ?>" /></td>
<div class="top-buffer"></div>
<h5>Link til min konto:</h5><input placeholder="Eksempel: /min-brokenfruit/" class="form-control" name="bfcsc_account_link" type="text" id="bfcsc_account_link" value="<?php echo get_option('bfcsc_account_link'); ?>" /></td>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="bfcsc_logout_link,bfcsc_login_link,bfcsc_account_link" />
<input class="btn btn-primary top-buffer" type="submit" value="<?php _e('Save Changes') ?>" />
</div>
</div>
</div>
</form>
<?php
}
/*---------------------------------------------------*/
/* Custom login shortcode - start */
/*---------------------------------------------------*/
function mydefaults (){
if (!get_option('bfcsc_logout_link')){
$logout_link = '/log-ud/';
} else {
$logout_link = get_option('bfcsc_logout_link');
}
if (!get_option('bfcsc_login_link')){
$login_link = '/log-ind';
} else {
$login_link = get_option('bfcsc_login_link');
}
if (!get_option('bfcsc_account_link')){
$account_link = '/min-brokenfruit/';
} else {
$account_link = get_option('bfcsc_account_link');
}
}
function custom_login_shortcode ( $atts ){
if ( is_user_logged_in() ) {
return '<i class="fa icon-user"></i>Mit Brokenfruit | <i class="fa icon-logout"></i>Log ud';
} else {
return '<i class="fa icon-login"></i>Log ind';
}
}
add_shortcode( 'custom_login', 'custom_login_shortcode' );
/*---------------------------------------------------*/
/* Custom login shortcode - end */
/*---------------------------------------------------*/
?>
Thank you all in advance!
Cheers Kenn
Correct. Your variable was not available inside that method.
As to the parameters, the shortcode api is not meant to work like that. The lone parameter $atts is used to pass the variables you need from the shortcode (the part inside the bracket) as an array.
I'm not sure how you're planning to use the shortcode. But you could pass your parameters with
[custom_login login='different_login' ]
then pick them up in the shortcode in the $atts array:
function custom_login_shortcode ( $atts ){
$a = shortcode_atts( array(
'login' => '/log-ind/', // default value for login
'account' => '/min-brokenfruit/', // default value for account
), $atts );
return $a['login']; // returns 'different_login'
return $a['account'] // returns '/min-brokenfruit/'
You could also define your variables as constants (with a global scope) so they are available inside your shortcode and all your methods:
define('MY_LOGIN_LINK','/log-ind');
Then you can use if (!defined('MY_LOGIN_LINK')) to see if you have something to work with. See http://php.net/manual/en/function.define.php for more on that.
But if you only need these values in this one method, this would work in your re-written code to streamline it a little:
$login_link = get_option('bfclsc_login_link','/log-ind/');
get_option() has an optional parameter for a default value:
$no_exists_value = get_option( 'no_exists_value', 'default_value' );
var_dump( $no_exists_value ); /* outputs 'default_value' */
https://codex.wordpress.org/Function_Reference/get_option
I found a solution.
I needed to put the content of function mydefaults into the function custom_login_shortcode. I guess my variables was created in the global state and could not be used?
After all, I don't understand why I could not pass the variables into the shortcode like:
function custom_login_shortcode ( $atts, $logout_link, $login_link, $account_link ){
Below is the working shortcode function:
/*---------------------------------------------------*/
/* Custom login shortcode - start */
/*---------------------------------------------------*/
/*function mydefaults (){
if (!get_option('bfclsc_logout_link')){
$logout_link = '/log-ud/';
} else {
$logout_link = get_option('bfclsc_logout_link');
}
if (!get_option('bfclsc_login_link')){
$login_link = '/log-ind';
} else {
$login_link = get_option('bfclsc_login_link');
}
if (!get_option('bfclsc_account_link')){
$account_link = '/min-brokenfruit/';
} else {
$account_link = get_option('bfclsc_account_link');
}
}*/
function custom_login_shortcode ( $atts ){
if (!get_option('bfclsc_logout_link')){
$logout_link = wp_logout_url( home_url()); //call wordpress logout with home redirect: wp_logout_url( home_url())
} else {
$logout_link = get_option('bfclsc_logout_link');
}
if (!get_option('bfclsc_login_link')){
$login_link = '/log-ind/';
} else {
$login_link = get_option('bfclsc_login_link');
}
if (!get_option('bfclsc_account_link')){
$account_link = '/min-brokenfruit/';
} else {
$account_link = get_option('bfclsc_account_link');
}
if ( is_user_logged_in() ) {
return '<i class="fa icon-user"></i>Mit Brokenfruit | <i class="fa icon-logout"></i>Log ud';
} else {
return '<i class="fa icon-login"></i>Log ind';
}
}
add_shortcode( 'custom_login', 'custom_login_shortcode' );
/*---------------------------------------------------*/
/* Custom login shortcode - end */
/*---------------------------------------------------*/

Wordpress user profile display name - change from selectbox to textbox

Im trying to change the user profile "Display name publicly as" from a select box to a textbox. Any ideas on how this can be done? Couldnt find anything all all.
Two way to solve it. You edit the wordpress core file, which is not a good way. Or you can add an extra field on profile box using wordpress hook.
I am giving you the first way:
Go to wp-admin/user-edit.php
Open the file. Then find
<td>
<select name="display_name" id="display_name">
<?php
$public_display = array();
$public_display['display_nickname'] = $profileuser->nickname;
$public_display['display_username'] = $profileuser->user_login;
if ( !empty($profileuser->first_name) )
$public_display['display_firstname'] = $profileuser->first_name;
if ( !empty($profileuser->last_name) )
$public_display['display_lastname'] = $profileuser->last_name;
if ( !empty($profileuser->first_name) && !empty($profileuser->last_name) ) {
$public_display['display_firstlast'] = $profileuser->first_name . ' ' . $profileuser->last_name;
$public_display['display_lastfirst'] = $profileuser->last_name . ' ' . $profileuser->first_name;
}
if ( !in_array( $profileuser->display_name, $public_display ) ) // Only add this if it isn't duplicated elsewhere
$public_display = array( 'display_displayname' => $profileuser->display_name ) + $public_display;
$public_display = array_map( 'trim', $public_display );
$public_display = array_unique( $public_display );
foreach ( $public_display as $id => $item ) {
?>
<option id="<?php echo $id; ?>"<?php selected( $profileuser->display_name, $item ); ?>><?php echo $item; ?></option>
<?php
}
?>
</select>
</td>
Change it with
<th><label for="display_name"><?php _e('Display name publicly as'); ?> </label></th>
<td><input type="text" name="display_name" id="display_name" value="<?php echo esc_attr( $profileuser->display_name ); ?>" class="regular-text" /></td>
But still this is not a good solution.
I came across this same issue and used a bit of javascript to solve it. Wordpress allows you to set the display_name field to anything you want, so you can use the following script (in your theme's functions.php file) to convert the select to a text field.
function change_display_name_to_textfield() {
echo "><div>"; // don't remove '>'
?>
<script>
jQuery(function($) {
// replace display_name select with input
$('select#display_name').after( '<input type="text" name="display_name" id="display_name" value="' + $('#display_name').val() + '" class="regular-text">' ).remove();
})
</script>
<?php
echo "</div"; // don't add '>'
}
// hook into new user and edit user pages
add_action( "user_new_form_tag", "change_display_name_to_textfield" );
add_action( "user_edit_form_tag", "change_display_name_to_textfield" );
Note the weird use of opening/closing tags. This is because those particular hooks execute just before the end of the opening form tag. So you need to close the form tag, print your script, then print a final tag without closing it.
For admin user edit pages, I found one of the easiest way:
add_action( 'personal_options', 'rm_personal_options' );
function rm_personal_options($profileuser){
if( !is_admin() ) return; ?>
<script type="text/javascript">
jQuery(document).ready(function($){
//$("input#nickname").parent().parent().hide();
$("select#display_name").replaceWith(function(){
return '<input type="text" name="display_name" id="display_name" value="'+$(this).val()+'" class="regular-text" style="width:25em" />';
});
});
</script>
<?php
}
Simply paste it into the functions.php of the theme file :)

Wordpress: Page template with default fields

WordPress 3.2.1
I'm creating separate page templates, however, there are some page templates that should have default custom fields. That is, if someone created a new page of template type "Contact Us", it should by default have custom fields:
Success Message
Email To
Phone Number
etc.
Right now, the only way I can think of knocking this out is by having the admin add those custom fields to the page, and then fill them in. However, this isn't the best method for basically giving an admin a "turn-key" type of feature, i.e., they create a page with a specific template and just fill in the fields.
Thanks guys!
The following will add 1 extra meta box to your (insert-edit) page.
In it you can add custom fields to save.
It does not switch depending on the selected template.
I would recomend using javascript to show/hide fields to do this. Based on ID of the <p>
If you get the meta box working with ALL possible fields you can show I'm willing to help with the javascript to hide and show based on the template.
GL
<?php
add_action( 'add_meta_boxes', 'carrousel_build' );
function carrousel_build()
{
add_meta_box('carrousel', 'Carrousel opties', 'carrousel_options', 'page',/*show on 'pages'*/ 'normal', 'high');
}
//this will add a meta box with custom fields
function carrousel_options ($post)
{ ?>
<p>
Description
</p>
<p id="field1_container">
<label for="field1">Custom field 1</label>
<br/>
<input type="text" id="field1" name="field1" value="<?php echo get_post_meta($post->ID, 'field1', true) ?>" size="25" />
</p>
<p id="field2_container">
<label for="field2">Custom field 2</label>
<br/>
<input type="text" id="field2" name="field2" value="<?php echo get_post_meta($post->ID, 'field2', true) ?>" size="25" />
</p>
<?php }
//save the values of the meta box
add_action( 'save_post', 'post_save' );
function post_save($post_id)
{
// Check permissions
if (isset ($_POST['post_type']) && 'carrousel' == $_POST['post_type'] && !current_user_can( 'edit_page', $post_id ))
{
return;
}
if (isset($_POST['field1'])) {
$subtitle = $_POST['field1'];
update_post_meta($post_id, 'field1', $subtitle);
}
if (isset($_POST['field2']))
{
$link = $_POST['field2'];
update_post_meta($post_id, 'field2', $link);
}
}

Resources