I was coding my very first plugin in order to share the posts on Facebook and Instagram, and I was writing the plugin options page.
I get always the error "Options page not found".
I thought that register_setting in the callback function could make the trick, but it didn't.
What am I doing wrong?
Here my code:
<?php
class Socialize {
public function __construct() {
// Hook into the admin menu
add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) );
add_action( 'admin_init', array( $this, 'setup_sections' ) );
add_action( 'admin_init', array( $this, 'setup_fields' ) );
}
public function setup_fields() {
add_settings_field( 'facebook_account', 'Facebook Username', array( $this, 'fb_account_callback' ), 'smashing_fields', 'facebook_section' );
add_settings_field( 'facebook_password', 'Facebook Password', array( $this, 'fb_pwd_callback' ), 'smashing_fields', 'facebook_section' );
add_settings_field( 'instagram_account', 'Instagram Username', array( $this, 'insta_account_callback' ), 'smashing_fields', 'instagram_section' );
add_settings_field( 'instagram_password', 'Instagram Password', array( $this, 'insta_pwd_callback' ), 'smashing_fields', 'instagram_section' );
}
public function setup_sections() {
add_settings_section( 'facebook_section', 'Facebook Account', array( $this, 'section_callback' ), 'smashing_fields' );
add_settings_section( 'instagram_section', 'Instagram Account', array( $this, 'section_callback' ), 'smashing_fields' );
}
public function fb_account_callback( $arguments ) {
echo '<input name="fb_account" id="fb_account" type="text" value="' . get_option( 'facebook_account' ) . '" />';
register_setting( 'smashing_fields', 'facebook_account' );
}
public function fb_pwd_callback( $arguments ) {
echo '<input name="fb_pwd" id="fb_pwd" type="password" value="' . get_option( 'facebook_password' ) . '" />';
register_setting( 'smashing_fields', 'facebook_password' );
}
public function insta_account_callback( $arguments ) {
echo '<input name="insta_account" id="insta_account" type="text" value="' . get_option( 'instagram_account' ) . '" />';
register_setting( 'smashing_fields', 'instagram_account' );
}
public function insta_pwd_callback( $arguments ) {
echo '<input name="insta_pwd" id="insta_pwd" type="password" value="' . get_option( 'instagram_password' ) . '" />';
register_setting( 'smashing_fields', 'instagram_password' );
}
public function section_callback( $arguments ) {
switch ( $arguments['id'] ) {
case 'facebook_section':
echo 'This is the Facebook section';
break;
case 'instagram_section':
echo 'This is the Instagram section';
break;
}
}
public function create_plugin_settings_page() {
// Add the menu item and page
$page_title = 'Free Socialize';
$menu_title = 'Free Socialize';
$capability = 'manage_options';
$slug = 'smashing_fields';
$callback = array( $this, 'plugin_settings_page_content' );
$icon = 'dashicons-admin-plugins';
$position = 100;
add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position );
}
public function plugin_settings_page_content() { ?>
<div class="wrap">
<h2>Free Socialize Settings Page</h2>
<form method="post" action="options.php">
<?php
settings_fields( 'smashing_fields' );
do_settings_sections( 'smashing_fields' );
submit_button();
?>
</form>
</div> <?php
}
}
new Socialize();
?>
I can't comment to gain clarification so apologies if I've misunderstood but would you not need to use add_plugins_page() in this instance?
<?php
add_plugins_page( $page_title, $menu_title, $capability, $menu_slug, $function);
?>
Docs: https://codex.wordpress.org/Function_Reference/add_plugins_page
Hope that helps and I've understood :)
Related
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'm trying to set max limit.When there are any 2 button pressed there must be a action (the other buttons get disabled).
This is code of the post reaction in wordpress.
I tried first something like at this link
.http://jsfiddle.net/r6KYu/ But I could not.How can I counting the clicks and set max click limit ?
(function($) {
$(document).ready(function() {
$('#zuzu_viral_reactions li').click(function() {
var unreact = ($(this).hasClass("clicked") ? true : false);
var id = $(this).parent().data("postId") || $(this).parent().data("post-id");
var url = zvr_data.ajax_url;
var reaction = $(this).data().reaction;
$.post(url, { postid: id, action: 'zvr_react', reaction: reaction, unreact: unreact }, function(data) {
console.log("Ajax: " + data);
});
$(this).toggleClass("clicked");
var howMany = parseInt($(this).find('span').text());
if (howMany > 0) {
if ($(this).hasClass("clicked")) {
howMany += 1;
} else {
howMany -= 1;
}
} else {
howMany = 1;
}
$(this).find('span').text(howMany);
});
});
})(jQuery);
document.addEventListener("touchstart", function() {}, true);
if ('createTouch' in document) {
try {
var ignore = /:hover/;
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
for (var j = sheet.cssRules.length - 1; j >= 0; j--) {
var rule = sheet.cssRules[j];
if (rule.type === CSSRule.STYLE_RULE && ignore.test(rule.selectorText)) {
sheet.deleteRule(j);
}
}
}
} catch (e) {}
}
Also php file here.
<?php
/*
Plugin Name: Zuzu Viral Reactions
Plugin URI: http://tiguandesign.com/
Description: Simple WordPress reactions plugin for viral stories.
Author: Tiguan
Author URI: http://tiguandesign.com/
Licence: GPLv2
Version: 1.0
Stable Tag: 1.0
*/
class Zuzu_Viral_React {
// $reactions = array( 'like','love', 'win', 'cute', 'lol', 'omg', 'wtf', 'fail' );
function __construct() {
$this->defaults = array(
'like' => "Like",
'love' => "LOVE",
'win' => "Win",
'cute' => "Cute",
'lol' => "LOL",
'omg' => "OMG",
'wtf' => "WTF",
'fail' => "Fail",
'boxtitle' => "Your Reaction"
);
add_action('the_content', array($this,'addContent'));
add_action('the_excerpt', array($this, 'zvrdisablePlugin'));
add_action('admin_menu', array($this, 'addMenu'));
add_action( 'admin_init', array($this, 'registerSettings'));
add_action( 'wp_ajax_zvr_react', array($this,'react'));
add_action( 'wp_ajax_nopriv_zvr_react', array($this,'react' ));
add_action('wp_enqueue_scripts', array($this,'addStylesAndScripts'));
add_action( 'load-post.php', array($this, 'initMetaBox'));
add_action( 'load-post-new.php', array($this, 'initMetaBox'));
add_shortcode( 'zvr_reactions', array($this, 'shortCode') );
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), array($this, 'addSettingsLink' ));
}
function addSettingsLink ( $links ) {
$link = array('Settings');
return array_merge( $links, $link );
}
function initMetaBox() {
add_action( 'add_meta_boxes', array($this, 'addMetaBox'));
add_action( 'save_post', array($this, 'savePostMeta'), 10, 2 );
}
function savePostMeta($post_id, $post) {
if ( !isset( $_POST['zvr_enable_meta_nonce'] ) || !wp_verify_nonce( $_POST['zvr_enable_meta_nonce'], basename( __FILE__ ) ) )
return $post_id;
$post_type = get_post_type_object( $post->post_type );
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
$meta_value = ( isset( $_POST['zvr_enable'] ) ? sanitize_html_class( $_POST['zvr_enable'] ) : '' );
if (empty($meta_value)) {
$meta_value = "off";
}
update_post_meta( $post_id, 'zvr_enable', $meta_value );
}
function addMetaBox() {
add_meta_box('zvr-enable-on-post', 'Zuzu Viral Reactions', array($this, 'renderMetaBox'), 'post', 'normal', 'default');
}
function renderMetaBox() {
$options = get_option( 'zvr_settings' );
$enable = isset($options['zvr_auto_enable']) ? $options['zvr_auto_enable']: 'on';
$post_id = get_the_ID();
$meta_enable = get_post_meta( $post_id, 'zvr_enable', true );
if (!empty($meta_enable)) {
$enable = $meta_enable;
}
wp_nonce_field( basename( __FILE__ ), 'zvr_enable_meta_nonce' );
?>
<label><input type="checkbox" name="zvr_enable" id="zvr-enable" <?php checked($enable, 'on')?>>Enable reactions on this post</label>
<?php
}
function addMenu() {
add_options_page('Zuzu Reaction Settings', 'Zuzu Reaction', 'manage_options', 'zvr_options', array($this, 'renderOptionsPage'));
}
function registerSettings() {
register_setting('zvr_options', 'zvr_settings');
add_settings_section( 'zvr_enable', '', array($this, 'renderEnableGuide'), 'zvr_options' );
add_settings_field( 'zvr_options-auto-enable-on', 'Show buttons on posts', array($this, 'renderRadio'), 'zvr_options', 'zvr_enable', array('value' => 'on'));
add_settings_field( 'zvr_options-auto-enable-off', "Don't show buttons on posts", array($this, 'renderRadio'), 'zvr_options', 'zvr_enable', array('value' => 'off'));
add_settings_section( 'zvr_content', '', array($this, 'renderContent'), 'zvr_options' );
add_settings_section( 'zvr_share_translations', 'Reaction box title', array($this, 'renderReactionTranslations'), 'zvr_options');
add_settings_field( 'zvr_options-boxtitle', 'Your Reaction', array($this, 'renderField'), 'zvr_options', 'zvr_share_translations', array('label' => 'boxtitle'));
add_settings_section( 'zvr_translations', 'Reactions Text', array($this, 'renderReactionTranslations'), 'zvr_options' );
add_settings_field( 'zvr_options-like', 'Like', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'like'));
add_settings_field( 'zvr_options-love', 'Love', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'love'));
add_settings_field( 'zvr_options-win', 'Win', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'win'));
add_settings_field( 'zvr_options-cute', 'Cute', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'cute'));
add_settings_field( 'zvr_options-lol', 'LOL', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'lol'));
add_settings_field( 'zvr_options-omg', 'OMG', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'omg'));
add_settings_field( 'zvr_options-wtf', 'WTF', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'wtf'));
add_settings_field( 'zvr_options-fail', 'Fail', array($this, 'renderField'), 'zvr_options', 'zvr_translations', array('label' => 'fail'));
}
function shortCode() {
$options = get_option('zvr_settings');
return $this->renderPlugin($options);
}
function renderField($args) {
$label = $args['label'];
$options = get_option('zvr_settings');
$value = isset($options['zvr_'.$label]) ? $options['zvr_'.$label]: $this->defaults[$label];
echo "<input type='text' name='zvr_settings[zvr_$label]' value='".esc_attr($value)."'>";
}
function renderContent() {
?>
<div style="border-top: 1px solid #bbb; width: 100%; padding: 30px 0; margin: 30px 0; border-bottom: 1px solid #bbb;">
<h3>Adding reactions manually (short code)</h3>
<ol>
<li>You can use shortcode <code>[zvr_reactions]</code> within post or page text.</li>
<li>You can add <code>if (function_exists('zvr_reactions')) { zvr_reactions() }</code> into your templates.</li>
</ol>
</div>
<?php
}
function zvrdisablePlugin($excerpt) {
$pattern = '/zvr.*/i';
return preg_replace($pattern, '', $excerpt);
}
function renderRadio($args) {
$options = get_option( 'zvr_settings' );
$value = $args['value'];
$set_value = isset($options['zvr_auto_enable']) ? $options['zvr_auto_enable']: 'on';
?>
<input type='radio' name='zvr_settings[zvr_auto_enable]' <?php checked( $set_value, $value ); ?> value='<?php echo $value ?>'>
<?php
}
function renderReactionTranslations() {
echo "";
}
function renderEnableGuide() {
?>
<?php
}
function renderOptionsPage() {
?>
<form action='options.php' method='post'>
<p><h1>Zuzu Viral Reaction Settings</h1></p><br />
<p>Select the default setting for Zuzu Viral Reaction visibility. You can override this setting for each post in the post editor.</p>
<?php
settings_fields( 'zvr_options' );
do_settings_sections( 'zvr_options' );
?>
<?php submit_button(); ?>
</form>
<?php
}
function addContent($content) {
$options = get_option('zvr_settings');
$show_on_every_post = isset($options['zvr_auto_enable']) ? $options['zvr_auto_enable'] : 'on';
$post_id = get_the_ID();
$enabled = get_post_meta( $post_id, 'zvr_enable', true );
if (!is_page() && ($enabled=="on" || (empty($enabled) && $show_on_every_post=='on'))) {
$plugin = $this->renderPlugin($options);
$content .= $plugin;
}
return $content;
}
function renderPlugin($options) {
$post_id = get_the_ID();
$post_url = get_permalink($post_id);
$label_like =isset($options['zvr_like']) ? $options['zvr_like']: $this->defaults['like'];
$label_love =isset($options['zvr_love']) ? $options['zvr_love']: $this->defaults['love'];
$label_win =isset($options['zvr_win']) ? $options['zvr_win']: $this->defaults['win'];
$label_cute =isset($options['zvr_cute']) ? $options['zvr_cute']: $this->defaults['cute'];
$label_lol =isset($options['zvr_lol']) ? $options['zvr_lol']: $this->defaults['lol'];
$label_omg =isset($options['zvr_omg']) ? $options['zvr_omg']: $this->defaults['omg'];
$label_wtf =isset($options['zvr_wtf']) ? $options['zvr_wtf']: $this->defaults['wtf'];
$label_fail =isset($options['zvr_fail']) ? $options['zvr_fail']: $this->defaults['fail'];
$label_boxtitle =isset($options['zvr_boxtitle']) ? $options['zvr_boxtitle']: $this->defaults['boxtitle'];
ob_start() ?>
<div id="zuzu_viral_reactions">
<span style="display:none">zvr</span>
<div class="zvr-reaction-title"><?php echo $label_boxtitle ?></div>
<ul data-post-id="<?php echo $post_id ?>">
<li class="animated" data-reaction="like" <?php echo $this->getClass("like", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f44d.svg' ?>" /><em><?php echo $label_like ?></em><span><?php echo $this->getAmount("like",$post_id) ?></span></li>
<li class="animated" data-reaction="love" <?php echo $this->getClass("love", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f60d.svg' ?>" /><em><?php echo $label_love ?></em><span><?php echo $this->getAmount("love",$post_id) ?></span></li>
<li class="animated" data-reaction="win" <?php echo $this->getClass("win", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f61c.svg' ?>" /><em><?php echo $label_win ?></em><span><?php echo $this->getAmount("win",$post_id) ?></span></li>
<li class="animated" data-reaction="cute" <?php echo $this->getClass("cute", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f917.svg' ?>" /><em><?php echo $label_cute ?></em><span><?php echo $this->getAmount("cute",$post_id) ?></span></li>
<li class="animated" data-reaction="lol" <?php echo $this->getClass("lol", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f632.svg' ?>" /><em><?php echo $label_lol ?></em><span><?php echo $this->getAmount("lol",$post_id) ?></span></li>
<li class="animated" data-reaction="omg" <?php echo $this->getClass("omg", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f631.svg' ?>" /><em><?php echo $label_omg ?></em><span><?php echo $this->getAmount("omg",$post_id) ?></span></li>
<li class="animated" data-reaction="wtf" <?php echo $this->getClass("wtf", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f914.svg' ?>" /><em><?php echo $label_wtf ?></em><span><?php echo $this->getAmount("wtf",$post_id) ?></span></li>
<li class="animated" data-reaction="fail" <?php echo $this->getClass("fail", $post_id) ?> ><img class="animated" src="<?php echo trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/img/1f915.svg' ?>" /><em><?php echo $label_fail ?></em><span><?php echo $this->getAmount("fail",$post_id) ?></span></li>
</ul>
<div style="clear: both;"></div>
</div>
<?php
$plugin = ob_get_contents();
ob_clean();
return $plugin;
}
function getClass($reaction, $post_id) {
$clicked = isset($_COOKIE["zvr_reacted_".$reaction."_".$post_id]);
return ($clicked ? 'class="clicked"':'');
}
function getAmount($reaction, $post_id) {
$meta_key = "zvr_reaction_".$reaction;
$amount = get_post_meta($post_id, $meta_key, true) ? get_post_meta($post_id, $meta_key, true) : 0;
return $amount;
}
function react() {
if (isset($_POST["postid"])) {
$post_id = $_POST["postid"];
$reaction = $_POST["reaction"];
$unreact = $_POST["unreact"];
}
$amount = $this->getAmount($reaction, $post_id);
if (isset($unreact) && $unreact === "true") {
unset($_COOKIE['zvr_reacted_'.$reaction.'_'.$post_id]);
setcookie('zvr_reacted_'.$reaction.'_'.$post_id, '', time() - 3600, "/");
$amount = (int) $amount - 1;
if ($amount >=0) {
echo "Amount: ".$amount." ";
update_post_meta($post_id, "zvr_reaction_".$reaction, $amount);
}
}
else {
setcookie('zvr_reacted_'.$reaction.'_'.$post_id, $reaction, time() + (86400 * 30), "/");
$amount = (int) $amount + 1;
if ($amount >=0) {
echo "Amount: ".$amount." ";
update_post_meta($post_id, "zvr_reaction_".$reaction, $amount);
}
}
return;
}
function addStylesAndScripts() {
wp_enqueue_style( 'zvr-font', 'https://fonts.googleapis.com/css?family=Open+Sans' );
wp_enqueue_style( 'zvr-style', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/css/zvr-styles.css', array(), "1.0.3" );
wp_enqueue_script( 'zvr-script', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/js/zvr-script.js', array( 'jquery' ), "1.0.3" );
$localize = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'zvr-script', 'zvr_data', $localize );
}
}
function zvr_reactions() {
// Call from templates
// if (function_exists('zvr_reactions')) { zvr_reactions() }
$zvr = new Zuzu_Viral_React();
$options = get_option('zvr_settings');
echo $zvr->renderPlugin($options);
}
new Zuzu_Viral_React();
you can solve this by jquery and get max length event by the following code
<label for="name">Input 1: maxlength=10</label>
<input type="text" maxlength="10" id="input-1" value="Allen"/>
$("#input-1").maxlength();
// get maxlength and other event
$("input").bind("update.maxlength", function(event, element, lastLength, length, maxLength, left){
console.log(event, element, lastLength, length, maxLength, left);
});
I have this following code to give a textarea to a front end user to use it as notes on a page to write things to remember. But this code saves only one sticky note that can be edited whenever the user wants. My questions is if there is a way to save the content somewhere and have a new one every time submit is pressed. or a add new sticky button.
require_once( plugin_dir_path( __FILE__ ) . 'wp-ajax.php' );
class notepad_stikey extends WP_Ajax {
var $user;
var $username;
function __construct() {
parent::__construct();
add_action('init', array( &$this, 'setup') );
}
function setup() {
$this->user = get_current_user_id();
$this->username = get_userdata( $this->user )->user_login;
$this->notes = get_user_meta( $this->user, 'notepad_stikey', true );
$this->ph = ' '; //placeholder
if (empty( $this->notes )) {
$this->notes = $this->ph;
}
add_action('wp_enqueue_scripts', array( &$this, 'scripts') );
}
function scripts() {
wp_enqueue_script( 'notepad_stikey', plugins_url( 'notepad_stikey.js', __FILE__ ), array( 'jquery' ) );
wp_localize_script( 'notepad_stikey', 'notepad_stikey', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function an_change_notepad_stikey() {
$notes = trim( $_POST['notes'] );
//if notes is empty, delete
if ( empty($notes) ) {
if ( delete_user_meta( $this->user, 'notepad_stikey' ) )
die( 'notes deleted' );
}
//notes are the same, notes = placeholder, or resaving empty notes
if ( $notes == $this->notes || $notes == $this->ph || ( empty($notes) && $this->notes == $this->ph) )
die();
//update
if ( update_user_meta( $this->user, 'notepad_stikey', $notes ) )
die( 'updated' );
//hopefully, we don't get this far. if we do, something is wrong
die( 'uh oh. notes could not be saved' );
}
}
global $notepad_stikey;
$notepad_stikey = new notepad_stikey();
add_action( 'widgets_init', 'notepad_stikey_load' );
function notepad_stikey_load() {
register_widget( 'notepad_stikey_Widget' );
}
class notepad_stikey_Widget extends WP_Widget {
function notepad_stikey_Widget() {
$widget_ops = array('classname' => 'notepad_stikey', 'description' => __( 'notepad_stikey. Only one instance please. Else this will break.', 'notepad_stikey' ) );
$control_ops = array( 'id_base' => 'notepad_stikey' );
parent::WP_Widget( 'notepad_stikey', __( 'notepad_stikey', 'notepad_stikey' ), $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args, EXTR_SKIP );
echo $before_widget;
global $notepad_stikey;
$username = $notepad_stikey->username;
$notes = $notepad_stikey->notes;
//overwrite title
$instance['title'] = 'Notepad for '. $username;
echo $instance['hide_title'] ? '' : $before_title . $instance['title'] . $after_title;
echo "<div id='notepad_stikey' class='$username' style='border: 1px solid #eee; padding: 10px 15px;min-height: 100px;'>";
echo $notes;
echo '</div><span style="float:left;color:#008;" id="notepad_stikey_response"></span><small style="float:right;">click box above to edit</small>';
echo $after_widget;
} //end widget()
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = esc_attr( $new_instance['title'] );
$instance['hide_title'] = (bool) $new_instance['hide_title'] ? 1 : 0;
return $instance;
} //end update()
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'hide_title' => 0 ) );
extract( $instance );
?>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('hide_title'); ?>" name="<?php echo $this->get_field_name('hide_title'); ?>"<?php checked( $hide_title ); ?> />
<label for="<?php echo $this->get_field_id('hide_title'); ?>"><?php _e('Hide Title?', 'notepad_stikey' );?></label>
</p>
<?php
} //end form()
}
if (!class_exists('WP_Ajax')) {
class WP_Ajax {
function __construct( $ajax_prefix = 'a', $nopriv_prefix = 'n' ) {
$regex = "/^($ajax_prefix)?($nopriv_prefix)?_|^($nopriv_prefix)? ($ajax_prefix)?_/";
$methods = get_class_methods( $this );
foreach ( $methods as $method ) {
if ( preg_match( $regex, $method, $matches ) ) {
if ( count( $matches ) > 1 ) {
$action = preg_replace( $regex, '', $method );
if ( count( $matches ) == 3 ) {
add_action( "wp_ajax_$action", array( $this, $method ) );
add_action( "wp_ajax_nopriv_$action", array( $this, $method ) );
} else {
if ( $matches[1] == $ajax_prefix ) {
add_action( "wp_ajax_$action", array( $this, $method ) );
} else {
add_action( "wp_ajax_nopriv_$action", array( $this, $method ) );
}
}
}
}
}
}
}
}
jQuery(document).ready(function($) {
$('#notepad_stikey').click(function(e) {
tag = e.target.tagName;
if ( tag != 'TEXTAREA' && tag != 'INPUT' ) {
contents = $(this).html();
$(this).html( '<textarea rows="5" cols="50" style="display:block;width:98%;height:100px;">' + contents + '</textarea><input type="submit" class="save" style="position:relative;z-index:99" />' );
}
});
$('#notepad_stikey input.save').live( 'click', function() {
new_contents = $(this).siblings('textarea').val();
$('#notepad_stikey').html( new_contents );
change_notepad_stikey( new_contents );
return false;
});
function change_notepad_stikey( notes ) {
$('#notepad_stikey_response').text( '...' );
$.post(notepad_stikey.ajaxurl,
{
'action' : 'change_notepad_stikey',
'notes' : notes
}, function(response) {
//if (response != '') {
//alert( response );
$('#notepad_stikey_response').text( response );
//}
}, 'text' );
}
});
I rewrite the WordPress example to create a meta box, using functions as variables:
$myplugin_add_meta_box = function() {
add_meta_box('myplugin_sectionid', 'Testing', $myplugin_meta_box_callback, 'page' );
};
add_action( 'add_meta_boxes', $myplugin_add_meta_box );
$myplugin_meta_box_callback = function( $post ) {
wp_nonce_field( 'myplugin_save_meta_box_data', 'myplugin_meta_box_nonce' );
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
echo '<label for="myplugin_new_field">';
_e( 'Description for this field', 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
};
But this error appear:
Warning: call_user_func() expects parameter 1 to be a valid callback,
no array or string given in
/var/www/public/wp-admin/includes/template.php on line 1037
I believe the error has something to do with the use of function as a variable.
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
function myplugin_add_meta_box() {
add_meta_box('myplugin_sectionid', 'Testing', 'myplugin_meta_box_callback', 'page' );
}
function myplugin_meta_box_callback ( $post ) {
wp_nonce_field( 'myplugin_save_meta_box_data', 'myplugin_meta_box_nonce' );
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
echo '<label for="myplugin_new_field">';
_e( 'Description for this field', 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
};
Declare myplugin_meta_box_callback as a function, not as a variable.
Found the solution:
add_meta_box('myplugin_sectionid', 'Testing', __NAMESPACE__ . '\\myplugin_meta_box_callback', 'page' );
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' );