I need to create a plugin to save custom values to options.php.
I want to create the fields in arrays and that works.
Where I get lost is this:
The form will not actually save the settings in the WP database.
How do I create additional sections?
I know it has to do with add_settings_section(), etc. But I cannot find how to do this with arrayed inputs. Please advice. ;-)
My code so far:
<?php
// Create WordPress admin menu
function stonehenge_menu_page(){
$page_title = 'Stonehenge Options';
$menu_title = 'Stonehenge Options';
$capability = 'manage_options';
$menu_slug = 'stonehenge_slug';
$function = 'stonehenge_render_page';
$icon_url = 'dashicons-admin-plugins';
$position = 99;
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
// Call update_stonehenge function to update database
add_action( 'admin_init', 'update_stonehenge' );
}
// Create function to register plugin settings in the database
function update_stonehenge() {
register_setting( 'stonehenge-settings', 'stonehenge' );
}
function stonehenge_render_page() {
$section_1 = array(
'Field 1' => array( // $name Name of the field
'field' => 'field_1', // $field
'label' => 'Field 1', // $label Label of the field
'type' => 'text', // $type input type (text, textarea, option, etc.)
),
'Field 2' => array( // $field Name of the field
'field' => 'field_2', // $field
'label' => 'Field 2', // $label Label of the field
'type' => 'text', // $type input type (text, textarea, option, etc.)
),
'Field 3' => array( // $field Name of the field
'field' => 'field_3', // $field
'label' => 'Field 3', // $label Label of the field
'type' => 'text', // $type input type (text, textarea, option, etc.)
),
);
## START OF MAIN PAGE
echo '<h1>Stonehenge Options Fields</h1>';
?>
<form method="post" action="options.php">
<?php settings_fields( 'stonehenge-settings' ); ?>
<?php do_settings_sections( 'stonehenge-settings' ); ?>
<!-- >## SECTION 1 should start here </!-->
<br><h2>Section 1</h2>
<table>
<?php
foreach ($section_1 as $var) {
$prefix = 'stonehenge_';
$option_label = $var['label'];
$option_name = $var['field'];
$option_field = 'stonehenge_'.$var['field'];
$option_value = get_option( $option_field);
$option_input = '<input type="' .$var['type']. '"name="'.$option_field.'" id="'.$option_field.'" value="'.$option_value.'"> ';
$label_for = '<label for='.$field.'>' . $var['label'] . '</label>';
?>
<tr><th scope="row" align="left"><?php echo $option_label; ?></th>
<td><?php echo $option_input; ?></td>
<td>Database Field = <?php echo $option_field; ?></td>
</tr>
<?php } ?>
</table>
<!-- >## SECTION 2 should start here </!-->
<br><h2>Section 2</h2>
<table>
</table>
<?php submit_button(); ?>
</form>
<?php
}
SOLVED!
Turns out it was rather simple, if done correctly. :-) Now I can just add an array and all the rest is created dynamically. Whoop! Whoop!
Inputs are stored in options.php as stonehenge_section_fieldname and cal be easily called with get_option('stonehenge_section_fieldname');
Here's the code so far, if anyone is interested.
// Define common constants for stabiliy.
if (!defined("STONEHENGE_PLUGIN_VERSION")) define("STONEHENGE_PLUGIN_VERSION", "2.0.0");
if (!defined("STONEHENGE_PLUGIN_DIR_PATH")) define("STONEHENGE_PLUGIN_DIR_PATH", plugins_url('' , __FILE__));
// TO DO: Add MultiSite compatibility for network Activation.
// Current version only works if activated per blog.
// Let's load the language files.
load_plugin_textdomain('stonehenge', false, basename( dirname( __FILE__ ) ) . '/languages/' );
Class Stonehenge_Fields {
// Add additional Arrays to dynamically create more inputs. That's it!
static $stonehenge_fields = array(
'Facebook' => array(
'Page URL' => 'text',
'App ID' => 'text',
'Admin ID' => 'text',
),
/* 'Section' => array(
'Field 1' => 'text',
'Field 2' => 'textarea',
'Field 3' => 'checkbox',
),
*/
);
}
// TO DO: Add a hook to remove all option fields upon deactivation of the Plugin.
//delete_option('stonehenge_website_name');
// Call stonehenge_menu function to load Admin Menu in the Dashboard.
add_action( 'admin_menu', 'stonehenge_menu_page' );
// Let's create WordPress Admin Menu
function stonehenge_menu_page(){
$page_title = __('Stonehenge Custom Fields & Data Settings', 'stonehenge');
$menu_title = __('Stonehenge Fields', 'stonehenge');
$capability = 'manage_options';
$menu_slug = 'stonehenge';
$function = 'stonehenge_options_page';
$icon_url = 'dashicons-admin-plugins';
$position = 99;
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
}
function stonehenge_register_settings() {
// Let's create and register the Sections.
$sections = Stonehenge_Fields::$stonehenge_fields;
foreach ($sections as $section => $key) {
add_settings_section($section, $section, 'stonehenge_callback', __FILE__ );
// Let's create and register the input fields in options.php (acutal input fields are created in function stonehenge_options_page. )
foreach ($key as $name => $type) {
$prefix = 'stonehenge';
$field = str_replace(' ', '_', strtolower( $prefix.'_'.$section.'_'.$name ) );
$label = ucfirst($section.' '.$name);
$value = get_option($prefix.'_'.$section.'_'.$name);
$input = '<input type="' .$type. '"name="'.$field.'" id="'.$field.'" value="'.$value.'"> ';
$label_for = '<label for='.$field.'>' . $label . '</label>';
add_option($field, $value);
register_setting('stonehenge_options_group',$field, 'stonehenge_callback');
}
}
}
add_action( 'admin_init', 'stonehenge_register_settings' );
// Let's create the Main Page.
function stonehenge_options_page()
{
?>
<div class="wrap">
<h1><?php _e('Stonehenge Custom Fields & Data Settings', 'stonehenge'); ?></h1>
<form method="post" action="options.php">
<?php settings_fields( 'stonehenge_options_group' ); ?>
<table cellspacing="4" cellpadding"3">
<?php
//Let's create the Sections
$sections = Stonehenge_Fields::$stonehenge_fields;
foreach ($sections as $section => $key) {
$section_label = ucfirst($section);
echo ('<th scope="row" colspan="2" align="left"><br><h2>'.$section_label.' '.__('Settings','stonehenge').'</h2></th>');
// Let's create the actual Labels and input Fields
foreach ($key as $name => $type) {
$prefix = 'stonehenge';
$field = str_replace(' ', '_', strtolower( $prefix.'_'.$section.'_'.$name ) );
$label = ucfirst($section.' '.$name);
$value = get_option($field);
// TO DO: Create switch arguments for different input types, such as Checkbox, Radio, Textarea, Password, etc.
$input = '<input type="' .$type. '"name="'.$field.'" id="'.$field.'" value="'.$value.'"> ';
// Using <label for> Makes it clickable. Very handy!
$label_for = '<label for='.$field.'>' . $label . '</label>';
?><tr><th scope="row" align="left"><?php echo $label_for; ?></th><td><?php echo $input; ?></td></tr><?php
}
}?>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
// That's all Folks! :-)
?>
Related
I am new into settings api , but still can't find much about media uploader from wp.
I have followed a tutorial but I am stuck at the point where I cannot save the image src into option.
Im sorry in advance for writting this much code , I don't know how I can reproduce my problem and I wanna cover all the aspects for a good answer. I will provide a image as well for a visual view.
Thank you.
Image: https://prnt.sc/6p9gfxc51FDA
AdminClass.php
public $settings; // class that builds the fields oop;
public $callbacks; // class that handle callbacks;
public function register() {
// instantiate classes;
$this->settings = new SettingsApi();
$this->callbacks = new AdminCallbacks();
}
public function setFields(){
$args = array(
array(
'id' => 'promo_image1',
'title' => 'Promotional Image',
'callback' => array( $this->callbacks, 'ss_PromoImage' ),
'page' => SS_PLUGIN,
'section' => 'ss_options_zone',
'args' => array(
'label_for' => 'promo_image1',
'class' => 'ss_image_field'
)
)
);
$this->settings->setFields( $args );
}
SettingsApi
public $settings = array();
public $fields = array();
public function registerCustomFields(){
// add setting
foreach ( $this->settings as $setting ):
register_setting(
$setting["option_group"],
$setting["option_name"],
( isset( $setting["callback"] ) ? $setting["callback"] : '' )
);
endforeach;
// add settings field
foreach ( $this->fields as $field ):
add_settings_field(
$field["id"],
$field["title"],
( isset( $field["callback"] ) ? $field["callback"] : '' ),
$field["page"],
$field["section"],
( isset( $field["args"] ) ? $field["args"] : '' )
);
endforeach;
}
public function setFields( array $fields ){
$this->fields = $fields;
return $this;
}
CallbackClass.php
public function ss_PromoImage() {
// Set variables
// $value is always empty and I dont know why
$value = esc_attr( get_option ('promo_image1') );
$default_image = SS_PLUGIN_URL . 'assets/images/sales.png';
if ( !empty($value ) ) {
$image_attributes = wp_get_attachment_image_src( $value );
$src = $image_attributes[0];
update_option( $value , $src );
$value = $src;
} else {
$src = $default_image;
$value = '';
}
$text = __( 'Upload', '' );
// Print HTML field
echo '
<div class="upload">
<img style="max-width: 300px;" data-src="' . ( !empty($value) ? $value : $src ) . '" src="' . ( !empty($value) ? $value : $src ) . '" />
<div>
<input type="hidden" class="value_option" name="'. $value .'" value="' . $value . '" />
<button type="button" class="upload_image_button button">' . $text . '</button>
<button type="button" class="remove_image_button button">Remove</button>
</div>
</div>
';
?>
<script>
jQuery(document).ready(function($){
// The "Upload" button
$('.upload_image_button').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
wp.media.editor.send.attachment = function(props, attachment) {
$(button).parent().prev().attr('src', attachment.url);
$(button).find('.value_option').val(attachment.id);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open(button);
return false;
});
// The "Remove" button (remove the value from input type='hidden')
$('.remove_image_button').click(function() {
var src = $(this).parent().prev().attr('src', '');
});
});
</script>
<?php
}
and here is the output:
<form method="post" action="options.php">
<?php
settings_errors();
settings_fields( 'ss_options_group' );
do_settings_sections( SS_PLUGIN );
submit_button();
?>
</form>
The data can not be saved
I am trying to make settings pages for each custom post type so that I can insert specified posts to archive pages of those post types.
I made this settings page using Wordpress Settings API.
But even after I input some values and clicked the save button.
The data can not be saved on DB and no data are displayed in these forms after refreshing the page.
I also confirmed the database has not created a record of the data. 'post_type_top' should be the option_name in DB.
Here is my class file to implement this settings page.
Does anyone figure out what kind of error this has?
I am temporarily commented out some sanitization process in my code.
<?php
class CreateSettingsPage
{
private $options;
private $post_type;
private $settings = array();
public function __construct()
{
add_action('admin_menu', array($this, 'add_settings_page'));
add_action('admin_init', array($this, 'settings_page_init'));
$this->post_type = $_GET['post_type'];
$this->settings = array(
'page' => 'post-type-settings-admin',
'page_title' => __('Post Type Settings', 'tcd-w'),
'page_slug' => 'post_type_top',
'option_name' => 'post_type_top',
'option_group' => 'post_type_top_option_group',
'sections' => array(
array(
'id_prefix' => 'post_type_settings',
'section_title' => __('Add Links to Post Type Top', 'tcd-w'),
'section_info' => __('Please input category page slug and post ids which are added to the post type top page', 'tcd-w'),
'fields' => array(
array(
'field_id' => 'input_category_slug',
'field_title' => 'input_category_slug',
'type' => 'input',
),
array(
'field_id' => 'input_post_ids',
'field_title' => 'input_post_ids',
'type' => 'input',
),
),
),
),
);
}
public function add_settings_page()
{
//put a menu within all custom types if apply
$post_types = get_post_types();
foreach ($post_types as $post_type) {
//check if there are any taxonomy for this post type
$post_type_taxonomies = get_object_taxonomies($post_type);
foreach ($post_type_taxonomies as $key => $taxonomy_name) {
$taxonomy_info = get_taxonomy($taxonomy_name);
if (empty($taxonomy_info->hierarchical) || $taxonomy_info->hierarchical !== TRUE)
unset($post_type_taxonomies[$key]);
}
if (count($post_type_taxonomies) == 0)
continue;
if ($post_type == 'post') {
add_submenu_page('edit.php', $this->settings['page_title'], $this->settings['page_title'], 'manage_options', $this->settings['page_slug'] . '_' . $post_type, array($this, 'create_admin_page'));
} elseif ($post_type == 'attachment') {
add_submenu_page('upload.php', $this->settings['page_title'], $this->settings['page_title'], 'manage_options', $this->settings['page_slug'] . '_' . $post_type, array($this, 'create_admin_page'));
} else {
add_submenu_page('edit.php?post_type=' . $post_type, $this->settings['page_title'], $this->settings['page_title'], 'manage_options', $this->settings['page_slug'] . '_' . $post_type, array($this, 'create_admin_page'));
}
}
}
public function create_admin_page()
{
$this->options = get_option($this->settings['option_name']); ?>
<div class="wrap">
<h2><?php echo $this->settings['page_title']; ?></h2>
<p></p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields($this->settings['option_group']);
do_settings_sections($this->settings['page']);
submit_button();
?>
</form>
</div>
<?php }
public function settings_page_init()
{
register_setting(
$this->settings['option_group'], // option_group
$this->settings['sections']['option_name'],
array($this, 'sanitize') // sanitize_callback
);
foreach ($this->settings['sections'] as $section) {
add_settings_section(
$section['id_prefix'] . '_section', // id
$section['section_title'], // title
array($this, 'section_info'), // callback
$this->settings['page'] // page
);
foreach ($section['fields'] as $field) {
add_settings_field(
$field['field_id'] . '_' . $this->post_type, // id
$field['field_title'], // title
array($this, $field['type']), // callback
$this->settings['page'], // page
$section['id_prefix'] . '_section', // section
$field
);
}
}
}
public function sanitize($input)
{
return $input;
// $sanitary_values = array();
// if (isset($input['custom_banner_url_0'])) {
// $sanitary_values['custom_banner_url_0'] = sanitize_text_field($input['custom_banner_url_0']);
// }
// if (isset($input['custom_banner_img_src_1'])) {
// $sanitary_values['custom_banner_img_src_1'] = esc_textarea($input['custom_banner_img_src_1']);
// }
// return $sanitary_values;
}
public function section_info()
{
echo $section['section_info'];
}
public function input($field)
{
printf(
'<input class="regular-text" type="text" name="%s[%s]" id="%s" value="%s">',
$this->settings['option_name'],
$field['field_id'] . '_' . $this->post_type,
$field['field_id'] . '_' . $this->post_type,
isset($this->options[$field['field_id'] . '_' . $this->post_type]) ? esc_attr($this->options[$field['field_id'] . '_' . $this->post_type]) : ''
);
}
public function textarea($field)
{
printf(
'<textarea class="large-text" rows="5" name="%s[%s]" id="%s">%s</textarea>',
$this->settings['option_name'],
$field['field_id'],
$field['field_id'],
isset($this->options[$field['field_id']]) ? esc_attr($this->options[$field['field_id']]) : ''
);
}
}
if (is_admin()) $post_type_settings = new CreateSettingsPage();
I've developed Meta Box plugin in a Custom Post as per this playlist. (I made some custermizations to that) In here he created a custom post using the plugin and do all the metabox operation on that relevant post.
It works fine. But my requirement is to display this meta box in a page.
Here is my code.
metabox.php (plugin code)
<?php
function wpl_owt_custom_init_cpt(){
$args = array(
'public' => true,
'label' => 'Books',
'supports' => array('title' , 'editor' , 'author' , 'thumbnail' , 'excerpt' , 'comments')
);
register_post_type('book' , $args);
}
add_action('init', 'wpl_owt_custom_init_cpt');
function wpl_owt_register_metabox_cpt(){
//custom post type
add_meta_box("owt-cpt-id" , "Contact Details" , "wpl_owt_book_function" , "book" , "normal" , "high");
}
add_action("add_meta_boxes_book" , "wpl_owt_register_metabox_cpt");
/**********Callback function for metabox at custom post type book******************/
function wpl_owt_book_function( $post ) {
//echo "<p>Custom metabox for custom post type</p>";
define("_FILE_", "_FILE_");
wp_nonce_field( basename(_FILE_), "wp_owt_cpt_nonce");
echo "<label for='txtPhoneNum'>Phone</label><br>";
$phone_num = get_post_meta($post->ID, "telNo" , true);
echo "<input type ='tel' name = 'txtPhoneNum' value = '" . $phone_num . "'' placeholder = 'Phone Number' /><br><br>";
echo "<label for='txtEmail'>Email</label><br>";
$email = get_post_meta($post->ID, "email" , true);
echo "<input type ='email' name = 'txtEmail' value = '" . $email . "'' placeholder = 'Email Address' /><br><br>";
echo "<label for='txtHours'>Hours of Operation</label><br>";
$hours = get_post_meta($post->ID, "hourofOps" , true);
echo "<input type ='text' name = 'txtHours' value = '" . $hours . "'' placeholder = 'Working Hours' /><br><br>";
}
add_action("save_post" , "wpl_owt_save_metabox_data" , 10 , 2);
function wpl_owt_save_metabox_data($post_id, $post){
//verify nonce
if(!isset($_POST['wp_owt_cpt_nonce']) || !wp_verify_nonce($_POST['wp_owt_cpt_nonce'], basename(_FILE_))){
return $post_id;
}
//verify slug value
$post_slug = "book";
if($post_slug != $post->post_type){
return;
}
//save value to db filed
$pub_tel = '';
if(isset($_POST['txtPhoneNum'])){
$pub_tel = sanitize_text_field($_POST['txtPhoneNum']);
}
else{
$pub_tel = '';
}
update_post_meta($post_id, "telNo", $pub_tel);
$pub_email = '';
if(isset($_POST['txtEmail'])){
$pub_email = sanitize_text_field($_POST['txtEmail']);
}
else{
$pub_email = '';
}
update_post_meta($post_id, "email", $pub_email);
$pub_hours = '';
if(isset($_POST['txtHours'])){
$pub_hours = sanitize_text_field($_POST['txtHours']);
}
update_post_meta($post_id, "hourofOps", $pub_hours);
}
?>
Can someone give me a solution to display the metabox in a page instead of a post.
please have a look as below:
<?php
function add_custom_meta_box()
{
$screens = ['page'];
foreach ($screens as $screen) {
add_meta_box(
'meta_box_id', // Unique ID
'Custom Meta Box Title', // Box title
'callback_function', // Content callback, must be of type callable
$screen // Post type
);
}
}
add_action('add_meta_boxes', 'add_custom_meta_box');
function callback_function($post)
{
/*Do something*/
}
I hope it would help you out
Replace
function wpl_owt_custom_init_cpt(){
$args = array(
'public' => true,
'label' => 'Books',
'supports' => array('title' , 'editor' , 'author' , 'thumbnail' , 'excerpt' , 'comments')
);
register_post_type('book' , $args);
}
add_action('init', 'wpl_owt_custom_init_cpt');
with this
add_action('add_meta_boxes', 'wpl_owt_register_metabox_cpt');
function wpl_owt_register_metabox_cpt()
{
global $post;
if(!empty($post))
{
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if($pageTemplate == 'page-contact.php' )
{
add_meta_box(
'owt-cpt-id', // $id
'Contact Details', // $title
'wpl_owt_book_function', // $callback
'page', // $page
'normal', // $context
'high'); // $priority
}
}
}
and replace this
$post_slug = "book";
if($post_slug != $post->post_type){
return;
}
with this.
$post_slug = "page";
if($post_slug != $post->post_type){
return;
}
Hope this will work out.
I am having a little trouble displaying a post name in a admin column on my custom page in wordpress. I have everything working but when I call the selected item that was chosen from a drop down from a custom metabox it displays the post ID in the admin column instead of the post name.
Here is the code I am using ( to display the columns)
add_filter('manage_edit-projects_columns', 'edit_projects_columns');
function edit_projects_columns($columns) {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => __( 'Project Title' ),
'client' => __( 'Client' ),
'protype' => __( 'Project Type' ),
'featureImage' => __( 'Project Image' ),
);
return $columns;
}
To Display the selected fields
add_action('manage_projects_posts_custom_column', 'manage_projects_columns', 10, 2);
function manage_projects_columns($column, $post_id, $selected) {
global $post;
switch($column) {
/* Display Column */
case 'client' :
/* Get the post meta. */
$selected = get_post_meta($post->ID, 'a_clients', true);
if (empty($selected))
echo __('');
else
printf(__( '%s' ), $selected);
break;
/* End Display Column */
/* If displaying the 'genre' column. */
case 'protype' :
$terms = get_the_terms($post_id, 'tagwork');
if (!empty($terms)) {
$out = array();
foreach($terms as $term) {
$out[] = sprintf('%s',
esc_url(add_query_arg(array('post_type' => $post->post_type, 'tagwork' => $term->slug), 'edit.php')),
esc_html(sanitize_term_field('tagwork', $term->name, $term->term_id, 'tagwork', 'tagwork'))
);
}
echo join(', ', $out);
} else {
_e('');
}
break;
case 'featureImage' :
$column = get_the_post_thumbnail($post->ID, 'featureImage');
if (empty($contact))
echo __('');
else
printf(__('%s'), $contact);
break;
default :
break;
}
}
The selected field I am having trouble with is client
/* Display Column */
case 'client' :
/* Get the post meta. */
$selected = get_post_meta($post->ID, 'a_clients', true);
if (empty($selected))
echo __('');
else
printf(__('%s'), $selected);
break;
It is displaying the post ID instead of the post name.How would I go about fixing this?
Extra Note: The column is pulling the client information from a drop down menu on a projects page. The menu is pulling the titles from any new client I add to the client page. This way I can assign a project to a specific client.
In your example $selected is being assigned the value of the a_clients meta value, which seems to be a post_id. You need to use this post_id to fetch the WP_Post for the client and then use the post_title property to print out the proper title. You can leave out the else since it's just an empty string.
/* Display Column */
case 'client' :
/* Get the post meta. */
$client_id = get_post_meta( $post->ID, 'a_clients', true );
// Will be true if a_clients is not "" or 0
if ( !empty($client_id) ){
// Get the post for the client_id
$client = get_post($client_id);
// If we have a title, print it out, else just use the ID
printf( __( '%s' ), !empty($client->post_title)? $client->post_title : $client_id);
}
break;
I just set up a new input text option into my theme-options.php file, which is similar to the twenty eleven theme code.
Here are parts of my theme-options.php code in regards to the input, I'm looking for a way to get the input that users enter into the 'fact' text and show it on the index.php page:
function themename_theme_options_init() {
register_setting(
'themename_options', // Options group, see settings_fields() call in themename_theme_options_render_page()
'themename_theme_options', // Database option, see themename_get_theme_options()
'themename_theme_options_validate' // The sanitization callback, see themename_theme_options_validate()
);
// Register our settings field group
add_settings_section(
'general', // Unique identifier for the settings section
'', // Section title (we don't want one)
'__return_false', // Section callback (we don't want anything)
'theme_options' // Menu slug, used to uniquely identify the page; see themename_theme_options_add_page()
);
// Register our individual settings fields
add_settings_field( 'facts', __( 'Facts', 'themename' ), 'themename_settings_field_facts', 'theme_options', 'general' );
add_settings_field( 'link_color', __( 'Link Color', 'themename' ), 'themename_settings_field_link_color', 'theme_options', 'general' );
}
add_action( 'admin_init', 'themename_theme_options_init' );
Returns the default facts for Theme Name, based on color scheme:
function themename_get_default_facts( $color_scheme = null ) {
if ( null === $color_scheme ) {
$options = themename_get_theme_options();
$color_scheme = $options['color_scheme'];
}
$color_schemes = themename_color_schemes();
if ( ! isset( $color_schemes[ $color_scheme ] ) )
return false;
return $color_schemes[ $color_scheme ]['default_facts'];
}
Renders the Facts setting field.
function themename_settings_field_facts() {
$options = themename_get_theme_options();
?>
<input type="text" name="themename_theme_options[facts]" id="facts" value="<?php echo esc_attr( $options['facts'] ); ?>" />
<br />
<span><?php printf( __( 'Default facts: %s', 'themename' ), '<span id="default-facts">' . themename_get_default_facts ( $options['color_scheme'] ) . '</span>' ); ?></span>
<?php
}
Sanitize and validate form input:
function themename_theme_options_validate( $input ) {
$output = $defaults = themename_get_default_theme_options();
// Color scheme must be in our array of color scheme options
if ( isset( $input['color_scheme'] ) && array_key_exists( $input['color_scheme'], themename_color_schemes() ) )
$output['color_scheme'] = $input['color_scheme'];
// Facts must be characters.
if ( isset( $input['facts'] ) )
$output['facts'] = '' . ( ltrim( $input['facts'], '' ) );
// Our defaults for the link color may have changed, based on the color scheme.
$output['link_color'] = $defaults['link_color'] = themename_get_default_link_color( $output['color_scheme'] );
// Link color must be 3 or 6 hexadecimal characters
if ( isset( $input['link_color'] ) && preg_match( '/^#?([a-f0-9]{3}){1,2}$/i', $input['link_color'] ) )
$output['link_color'] = '#' . strtolower( ltrim( $input['link_color'], '#' ) );
return apply_filters( 'themename_theme_options_validate', $output, $input, $defaults );
}
Implements theme options into Theme Customizer:
function themename_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
$options = themename_get_theme_options();
$defaults = themename_get_default_theme_options();
$wp_customize->add_setting( 'themename_theme_options[facts]', array(
'default' => themename_get_default_facts( $options['color_scheme'] ),
'type' => 'option',
'sanitize_callback' => 'sanitize_text_field',
'capability' => 'edit_theme_options',
) );
}
add_action( 'customize_register', 'themename_customize_register' );
Thank you to anyone that can help :)
Thanks! I got it working :D
----------
<?php
/**
* Theme Options
*
* #package WordPress
*
*/
/* Write the name and the variable_name in which you want to store the data using theme options in the array $options_array */
$options_array = array(
'Facebook URL'=>'facebook_url',
);
function my_theme_options_init() {
// If we have no options in the database, let's add them now.
if ( false === my_theme_options() )
add_option( 'my_theme_options', my_default_theme_options() );
register_setting(
'my_options', // Options group, see settings_fields() call in theme_options_render_page()
'my_theme_options' // Database option, see my_theme_options()
);
global $options_array;
foreach ($options_array as $key=>$option ){
register_setting( 'my_options', $option);
}
}
add_action( 'admin_init', 'my_theme_options_init' );
function my_theme_options_add_page() {
$theme_page = add_theme_page(
'myers themeing', // Name of page
'myers themeing', // Label in menu
'edit_theme_options', // Capability required
'my_options', // Menu slug, used to uniquely identify the page
'my_theme_options_render_page' // Function that renders the options page
);
if ( ! $theme_page )
return;
}
add_action( 'admin_menu', 'my_theme_options_add_page' );
function my_default_schemes() {
$default_array = array('value' => 'Default_theme',
'label' => __( 'Default_theme', 'my' ),
'thumbnail' => get_template_directory_uri() . '/inc/images/my.png'
);
global $options_array;
foreach ($options_array as $key=>$option ){
$default_array[$option] =' ';
}
$default_scheme_options = array(
'Default_theme' => $default_array,
);
return apply_filters( 'my_default_schemes', $default_scheme_options );
}
function my_default_theme_options() {
$default_theme_options = array( 'default_scheme' => 'Default_theme' );
global $options_array;
foreach ($options_array as $key=>$option ){
$default_theme_options[$option] = my_default( $option,'Default_theme' );
}
return apply_filters( 'my_default_theme_options', $default_theme_options );
}
function my_default( $option ,$default_scheme = null ) {
if ( null === $default_scheme ) {
$options = my_theme_options();
$default_scheme = $options['default_scheme'];
}
$default_schemes = my_default_schemes();
if ( ! isset( $default_schemes[ $default_scheme ] ) )
return false;
return $default_schemes[ $default_scheme ][$option];
}
function my_theme_options() {
return get_option( 'my_theme_options', my_default_theme_options() );
}
function my_theme_options_render_page() {
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2><?php printf( __( '%s Theme Options', 'my' ), get_current_theme() ); ?></h2>
<?php settings_errors(); ?>
<hr>
<div id="theme_option_main">
<h2>myers themeing</h2>
<form method="post" enctype="multipart/form-data" action="options.php">
<?php
settings_fields( 'my_options' );
$options = my_theme_options();
$default_options = my_default_theme_options();
global $options_array;
foreach ($options_array as $key=>$option ){
do_settings_sections($option);
}
?>
<table class="form-table">
<tr>
<th scope="row"><?php _e( "(Use ' http:// ' for Hyperlinks)", 'my' ); ?></th>
<td>
<fieldset>
</fieldset>
</td>
</tr>
<?php
foreach ($options_array as $key=>$option ){
?>
<tr>
<th scope="row"><?php _e( $key, 'my' ); ?></th>
<td>
<fieldset>
<legend class="screen-reader-text"><span><?php _e( $key, 'my' ); ?></span></legend>
<input type="text" name="<?php echo $option ?>" id="<?php echo $option ?>" class="large-text" value="<?php echo get_option($option); ?>"></input>
</fieldset>
</td>
</tr>
<?php } ?>
</table>
<?php submit_button(); ?>
</form>
</div>
</div>
<?php
}
?>
copy the code and create a new theme options file. Add the name and the variable_name in the options array in the file and you are good to go.
Don't forget to link this file in your functions.php
To link it just add the following code in your functions.php
require( dirname( __FILE__ ) . '/inc/your_file_name.php' );