将插件设置保存到数据库

时间:2014-04-03 作者:Dannyw24

我不是php或wordpress的完全新手,但我想以最有效的方式解决这个问题,所以相信在这里提问会有所帮助。

我有一个插件,可以随机生成一个引号-我需要将引号保存到mysql数据库中。

我想知道保存数据的最佳方法,无论是使用设置api还是简单地将其保存到数组。

我还想实现删除报价的选项。

使用输入文本字段,我想知道如何在文本框中添加新引号,并将数据传递给包含引号的数组。

我的代码far(引号目前存储在一个数组中)

<?php

/*idea to develop further would be, add a text box that the user can input the quote in
this then gets added to the DB and passed to the $quotes array. From here the results get
output the same way*/
/*
Plugin Name: Random Quotes
Plugin URI: xxx 
Description: This Plugin randomly generates Quotes input by the user.
Version: 0.0.1
Author: xxx
Author URI: xxx
License: GPL2
*/

add_action(\'admin_menu\', \'dw_quotes_create_menu\');

function dw_quotes_create_menu() {
    //create custom top-level menu
    add_menu_page(\'Quotes Settings\', \'Quotes Styling\', \'manage_options\', __FILE__, \'dw_styling_quotes_settings\');
}

function dw_styling_quotes_settings() { ?>
    <div class="wrap">
        <?php screen_icon( \'plugins\' ); ?>
        <h2>Quotes Page</h2>
    <table class="form-table">
        <tr valign="top">
            <th scope="row">Input Quotes in the textbox</th>
                <td><input type="textarea" name="random_quote" value="" /></td>
        </tr>
    </table>
    </div>
<?php } 

// add quotes to this list
$quotes = array(
            "one" => "The weak can never forgive. Forgiveness is the attribute of the strong",
            "two" => "Be strong when you are weak, Be brave when you are scared, Be humble when you are victorious",
            "three" => "Our success is achieved by uniting our strength, not by gathering our weaknesses",
            "four" => "One of the most common causes of failure is the habit of of quitting when one is overtaken by temporary defeat",
            "five" => "The struggles make you stronger and the changes make you wise! Happiness has its own way of taking its sweet time"
            );

// uses array_rand to randomly pick a quote
$rand_quotes = array_rand( $quotes);

// pass\'s the result of $array_rand to $result_quotes
$result_quote = $quotes[$rand_quotes];

// outputs the result
//echo $result_quote;

?>

1 个回复
最合适的回答,由SO网友:Shawn H 整理而成

我将把数组作为序列化值存储到options-able中。

update_option(\'dw_quotes\', serialize($quotes));
并通过以下方式检索:

$quotes = get_option(\'dw_quotes\', null);
if ($quotes !==  null) { $quotes = unserialize($quotes); }
其他需要考虑的事项:

如果quotes选项不存在,请添加处理。

还添加了在删除插件时从选项表中删除引号的处理。请参见:http://codex.wordpress.org/Function_Reference/register_uninstall_hook

结束

相关推荐

更新wp-config.php和丢失的页面

我最近对我的wp-config.php 通过在没有正确db设置的本地版本上添加内存限制行。当我上传它时,db连接显然断了。在我更正db设置并重新上传wp-config.php, 我收到了安装页面。现在我所有的链接都断了,即使在刷新永久链接之后。但是,所有数据仍在我的数据库中。如何将所有页面重新连接到db,以便不丢失任何设置?