Retrieve custom variable

时间:2016-09-12 作者:otinane

我创建了一个简单的插件来更改车身背景颜色。但我无法检索存储颜色的变量。

<?php
/*
Plugin Name: My Plugin
Version: 1.0
License: GPL2
*/
/** Step 2 (from text above). */
add_action( \'admin_menu\', \'my_plugin_menu\' );
add_action(\'wp_head\',\'hook_css\');
// $opt_val = $opt_name = $data_field_name = null;

/** Step 1. */
function my_plugin_menu() {
add_management_page( \'My Plugin Options\', \'My Plugin\', \'manage_options\',      \'my-unique-identifier\', \'my_plugin_options\' );
}
/*Step 3. */
function my_plugin_options($opt_val) {
global $opt_val, $opt_name;

//must check that the user has the required capability
if (!current_user_can(\'manage_options\'))
{
  wp_die( __(\'You do not have sufficient permissions to access this page.\')   );
}

// variables for the field and option names
$opt_name = \'mt_favorite_color\';
$hidden_field_name = \'mt_submit_hidden\';
$data_field_name = \'mt_favorite_color\';

// Read in existing option value from database
$opt_val = get_option( $opt_name );

// See if the user has posted us some information
// If they did, this hidden field will be set to \'Y\'
if( isset($_POST[ $hidden_field_name ]) && $_POST[ $hidden_field_name ] == \'Y\' ) {
    // Read their posted value
    $opt_val = $_POST[ $data_field_name ];

    // Save the posted value in the database
    update_option( $opt_name, $opt_val );

    // Put a "settings saved" message on the screen

 ?>
 <div class="updated"><p><strong><?php _e(\'Settings saved.\', \'menu-test\' );   ?></strong></p></div>
 <?php

}

// Now display the settings editing screen

echo \'<div class="wrap">\';

// header

echo "<h2>" . __( \'Menu Test Plugin Settings\', \'menu-test\' ) . "</h2>";

// settings form

?>
<form name="form1" method="post" action="">
<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">

<p><?php _e("Favorite Color:", \'menu-test\' ); ?>
<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo     $opt_val; ?>" size="20">
</p><hr />

<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php    esc_attr_e(\'Save Changes\') ?>" />
</p>

</form>
</div>

<?php;
}
function hook_css() {
global $opt_val;
echo "style> body { background-color :" . $opt_val ."!important; }  </style>";
}

1 个回复
SO网友:david.binda

问题是$opt_val 仅当my_plugin_options 函数被调用。只有在用户查看“我的插件选项”屏幕时,才会调用该函数。

你得打电话get_option( \'mt_favorite_color\' ); 内部hook_css 作用(请注意hook_css 函数没有前缀。所有自定义函数、全局变量、选项等都应该加前缀)。

此外,您共享的代码没有在用户输入上清除值,也没有在输出上转义主题。确保阅读Validating Sanitizing and Escaping User Data part of the codex. 和使用sanitize_text_field 将值保存到数据库之前,以及esc_attr 当输出值以使插件更安全时。

相关推荐

Class variables in shortcodes

不知道我做错了什么,但我有以下代码:class the_shortcode { //Define Class Variables private $var; public function __construct() { add_shortcode( \'the_single\', array( $this, \'shortcode_2\' )); }&#