在安装时触发默认值wordpress插件

时间:2013-02-04 19:56:09

标签: wordpress wordpress-plugin

我花了很多时间来解决这个问题。如何在安装插件时自动填充字段上的默认值或插入到数据库中。

我尝试了以下这些代码,但没有任何作用:

register_activation_hook(__FILE__, 'just_a_handler');
function just_a_handler($plugin_options) {
$defaults = array(
      'youtube_keyword' => 'keyword here',
      'youtube_author' => 'author here',
      'youtube_content' => 'by_keyword',
      'youtube_width' => '500',
      'youtube_height' => '350',
      'youtube_number_of_videos' => '5',
      'youtube_preview' => '',
    );
    $plugin_options = wp_parse_args(get_option('youtube_plugin_options'), $defaults);
}

和这一个:

register_activation_hook(__FILE__, 'just_a_handler');
    function just_a_handler() {
     add_option("youtube_keyword", 'keyword here', '', 'yes');
    add_option("youtube_author", 'author here', '', 'yes');
}

1 个答案:

答案 0 :(得分:0)

要使用某些默认值自动填充选项,您可以执行以下操作。根据您执行此代码的时间,我认为在填充默认数据之前检查该选项是否已存在是个好主意。另请注意,如果要存储数组,则需要在将数据添加到数据库之前对其进行序列化。数据库只能存储数字,文本和日期。序列化采用一个数组并将其转换为序列化字符串。

function init_options() {
    $retrieved_options = array();
    $defaults = array(
      'youtube_keyword' => 'keyword here',
      'youtube_author' => 'author here',
      'youtube_content' => 'by_keyword',
      'youtube_width' => '500',
      'youtube_height' => '350',
      'youtube_number_of_videos' => '5',
      'youtube_preview' => '',
    );

    // Check to see if the option exists
    $retrieved_options = maybe_unserialize( get_option( 'youtube_plugin_options' ) );

    if ( $retrieved_options == '' ) {
        // There are no options set
        add_option( 'youtube_plugin_options', serialize( $defaults ) );
    } elseif ( count( $retrieved_options ) == 0 ) {
        // All options are blank
        update_option( 'youtube_plugin_options', serialize( $defaults ) );
    }
}

register_activation_hook( __FILE__, 'init_options' );