为主题选项(部分)创建一个ajax处理的保存操作


create a ajax handled save action for theme options (sections)

我想创建一个主题选项页面,其中包含部分。这些部分应该一个接一个地保存,也应该全部保存在一起。

WordPress的默认功能,无论我把它放在哪里,都会一次保存所有内容。这对决赛来说很好;全部保存";按钮,但不适用于每个单独的

我的目标:

  1. 每个部分都可以一次保存,也许很快就会在中突出显示保存时颜色略有不同
  2. 页面不应该重新加载,这就是为什么AJAX被推荐在这里:https://wordpress.org/support/topic/save-options-sections-one-by-one

我的代码(的一部分)也可以在那里看到。我不确定是否应该在这里粘贴主题部分的全部代码(数组和所有其他部分)。

我不想要现成的代码。我知道这不是StackOverflow的范围,但也许有人可以给我一个很酷的例子,我是PHP初学者,想象一下AJAX(

我感谢每一个人给我指明了正确的方向,甚至是指导?

我认为这也可以帮助社区

我在这里分享我的主题函数的代码。注意:我没有包括主题选项CSS和JavaScript表单

<?php
// Define Variables
$themename = "MinimaX3";
$shortname = "mx3";
$version = "1.0.0";
// Create theme options in arrays, with options for sections and open/close them
global $options;
$options = array(
//Type + Name of array = section General
array( 
    "name" => "General",
    "type" => "section"),
//Open section
array( 
    "type" => "open"),
//Options in General section
//Header Text
array( 
    "name" => "Header Text",
    "desc" => "Your Header Text. If empty, the Blog Name will be displayed",
    "id"   => $shortname."_headertext",
    "type" => "text",
    "std"  => ""),
//Wether to show Blog Name or not
array( 
    "name" => "Show the Blog name",
    "desc" => "If you leave the Hedaer text empty, you canstill deicde if you want the Bloga nem displayed or not",
    "id"   => $shortname."_blogname",
    "type" => "checkbox",
    "std"  => ""),
//Close General section
array( 
    "type" => "close"),
//Type + Name of next array = section Social Networks
array( 
    "name" => "Social Networks",
    "type" => "section"),
//Open section
array(
    "type" => "open"),
//Options in Social Networks section
//Twitter ID
array( 
    "name" => "Twitter ID",
    "desc" => "Your Twitter user name, please. It will be shown in the navigation bar. Leaving it blank will keep the Twitter icon supressed.",
    "id"   => $shortname."_twitterid",
    "type" => "text",
    "std"  => ""),
//Facebook URL
array( 
    "name" => "Facebook Page",
    "desc" => "Link to your Facebook page, <strong>with http://</strong>. It will be shown in the navigation bar. Leaving it blank will keep the Facebook icon suppressed.",
    "id"   => $shortname."_facebookid",
    "type" => "text",
    "std"  => ""),
//Close Social Networks section
array(
    "type" => "close"),
//Type + Name of next array
array( 
    "name" => "Footer",
    "type" => "section"),
//Open Footer section
array( 
    "type" => "open"),
//Options in Footer section
//Right Footer Area
array( 
    "name" => "Right Footer Text",
    "desc" => "Paste your text, copyright statements, etc., here.",
    "id"   => $shortname."_right_footer_text",
    "type" => "textarea",
    "std"  => ""),
//Left Footer Area
array( 
    "name" => "Left Footer Text",
    "desc" => "Paste your text, copyright statements, etc., here.",
    "id"   => $shortname."_left_footer_text",
    "type" => "textarea",
    "std"  => ""),
//Close Footer Area section
array( 
    "type" => "close"),
//Type + Name of next array
array( 
    "name" => "Google Analytics",
    "type" => "section"),
//Open Google Analytics section
array( 
    "type" => "open"),
//Options in Google Anaslytics section
//Googel Analytics
array( 
    "name" => "Analytics/Tracking Code",
    "desc" => "You can paste your Google Analytics or other website tracking code in this box. This will be automatically added to the footer.",
    "id"   => $shortname."_analytics_code",
    "type" => "textarea",
    "std"  => ""),
//Close Google Anayltics section
array( 
    "type" => "close"),
//Type + Name of next array
array( 
    "name" => "Custom CSS",
    "type" => "section"),
//Open Custom CSS section
array( "type" => "open"),
//Options in Custom CSS section
//Custom CSS
array( 
    "name" => "Custom CSS",
    "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of.",
    "id"   => $shortname."_custom_css",
    "std"  => "",
    "type" => "textarea"),
//Close Custom CSS section
array( 
    "type" => "close"),
//Type + name of next array
array( 
    "name" => "Custom Header and Footer Code",
    "type" => "section"),
//Open Custom Header and Fotter Code section
array( 
    "type" => "open"),
//Options in Custom Header and Footer Code
//Custom Header Code
array( 
    "name" => "Custom Header Code",
    "desc" => "All code you enter here will be added to your Hedaer.php file",
    "id"   => $shortname."_custom_header_code",
    "std"  => "",
    "type" => "textarea"),
//Custom Footer Code
array( 
    "name" => "Custom Footer Code",
    "desc" => "All code you enter here will be added to your Footer.php file",
    "id"   => $shortname."_custom_footer_code",
    "std"  => "",
    "type" => "textarea"),
//Close Custom Header and Footer Code section
array( "type" => "close"),
);
//How to save, wehn to save, URL definition
function mx3_add_admin() {
global $themename, $shortname, $options;
if ( isset ( $_GET['page'] ) && ( $_GET['page'] == basename(__FILE__) ) ) {
    if ( isset ($_REQUEST['action']) && ( 'save' == $_REQUEST['action'] ) ){
        foreach ( $options as $value ) {
            if ( array_key_exists('id', $value) ) {
                if ( isset( $_REQUEST[ $value['id'] ] ) ) {
                    update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
                }
                else {
                    delete_option( $value['id'] );
                }
            }
        }
    header("Location: admin.php?page=".basename(__FILE__)."&saved=true");
    }
    else if ( isset ($_REQUEST['action']) && ( 'reset' == $_REQUEST['action'] ) ) {
        foreach ($options as $value) {
            if ( array_key_exists('id', $value) ) {
                delete_option( $value['id'] );
            }
        }
    header("Location: admin.php?page=".basename(__FILE__)."&reset=true");
    }
}
add_theme_page($themename, $themename, 'administrator', basename(__FILE__), 'mx3_admin');
add_theme_page(basename(__FILE__), $themename . ' Options', 'Theme Options', 'administrator',  basename(__FILE__),'mx3_admin'); // Default
}
function mx3_add_init() {
$file_dir=get_template_directory_uri('template_directory');
wp_enqueue_style("mx3Css", $file_dir."/functions/theme-options.css", false, "1.0", "all");
wp_enqueue_script("mx3Script", $file_dir."/functions/theme-options.js", false, "1.0");
}
//Echos upon suuccesful save/reset operation + cases for rendering previous arrays
function mx3_admin() {
global $themename, $shortname, $version, $options;
$i=0;
if ( isset ($_REQUEST['saved']) && ($_REQUEST['saved'] ) )echo '<div id="message" class="updated fade"><p><strong>'.$themename.' Options saved.</strong></p></div>';
if ( isset ($_REQUEST['reset']) && ($_REQUEST['reset'] ) ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' Options reset.</strong></p></div>';
?>
<div class="wrap ">
<div class="options_wrap">
    <h2 class="Options-title"><?php echo $themename; ?> Options</h2>
    <form method="post">
<?php foreach ($options as $value) {
switch ( $value['type'] ) {
case "section":
?>
<div class="section_wrap">
<h3 class="section_title"><?php echo $value['name']; ?></h3>
    <div class="section_body">
<?php
break;
case 'text':
?>
<div class="options_input options_text">
    <span class="labels"><label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label></span>
    <input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" style="width: 100%;" type="<?php echo $value['type']; ?>" value="<?php if            ( get_option( $value['id'] ) != "") { echo stripslashes(get_option( $value['id'])  ); } else { echo $value['std']; } ?>" />
    <br>
    <div class="options_desc"><?php echo $value['desc']; ?></div>
</div>
<?php
break;
case 'textarea':
?>
<div class="options_input options_textarea">
    <span class="labels"><label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label></span>
    <textarea name="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" cols="" rows="">
        <?php if ( get_option( $value['id'] ) != "") { echo stripslashes(get_option( $value['id']) ); } else { echo $value['std']; } ?>
    </textarea>
    <br>
    <div class="options_desc"><?php echo $value['desc']; ?></div>
</div>
<?php
break;
case 'select':
?>
<div class="options_input options_select">
    <span class="labels"><label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label></span>
    <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
    <?php foreach ($value['options'] as $option) { 
        ?>
        <option <?php if (get_option( $value['id'] ) == $option) { echo 'selected="selected"'; } ?>><?php echo $option; ?></option>
    <?php 
    } 
    ?>
    </select>
    <br>
    <div class="options_desc"><?php echo $value['desc']; ?></div>
</div>
<?php
break;
case "checkbox":
?>
<div class="options_input options_checkbox">
    <label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
    <br>
    <?php if(get_option($value['id'])){ $checked = "checked='"checked'""; }else{ $checked = "";} ?>
    <input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />
    <br>
    <div class="options_desc"><?php echo $value['desc']; ?></div>
    <br>
</div>
<?php
break;
case "close":
$i++;
?>
    <input name="save<?php echo $i; ?>" type="hidden" />
    <?php submit_button() ?>
    </div><!--#section_body-->
</div><!--#section_wrap-->
<?php 
break;
}
}
?>
    <input type="hidden" name="action" value="save" />
    <?php submit_button( 'Save All Options' ) ?>
    </form>
    <form method="post">
        <input type="hidden" name="action" value="reset" />
        <div class="warning">
        <?php echo _e('Warning! Next Step Resets ALL options!', 'minmax3'); ?>
        </div>
        <?php submit_button( 'Reset All Options' ); ?>
    </form>
    <br/>
</div><!--#options-wrap-->
</div><!--#wrap-->
<?php
}
add_action('admin_init', 'mx3_add_init');
add_action('admin_menu' , 'mx3_add_admin');
//Enqueue Custom CSS Front-End
function display_custom_css() {
$custom_css = get_option( 'mx3_custom_css' );
echo '<style> '.$custom_css.' </style>';
}
add_filter('wp_head', 'display_custom_css');
?>

编辑:

我可以通过在<form method="post">:的</form>标签后添加这个来使它发挥作用(保存而不重新加载页面)

<div id="saveResult"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#myOptionsForm').submit(function() { 
  jQuery(this).ajaxSubmit({
     success: function(){
        jQuery('#saveResult').html("<div id='saveMessage'    class='successModal'></div>");
        jQuery('#saveMessage').append("<p><?php echo    htmlentities(__('Settings Saved Successfully','wp'),ENT_QUOTES); ?>   </p>").show();
     }, 
     timeout: 5000
  }); 
  setTimeout("jQuery('#saveMessage').hide('slow');", 5000);
  return false; 
  });
  });
  </script>

并相应地更改表单(添加类):

<form method="post" id="myOptionsForm">

我也添加了一些CSS。

(这一切都来自这里的教程:http://www.wpoptimus.com/434/save-plugin-theme-setting-options-ajax-wordpress/)

到目前为止,一切都很好。

我现在正在挣扎的是:

  • 目前的情况产生了";弹出";保存操作的消息,并带有成功消息。很酷,但是:
  • 我想";突出显示";当保存设置时,单个主题选项部分(下拉框)的myBody(div)会以不同的颜色显示
  • 我知道我必须寻址这些主体的div,并且可能设置一个if/else语句,以调用;突出显示";CSS,仅当保存选项时

我知道我必须在新的中添加这个if/else语句

"div id="saveResult"></div>

对吧?

也许这里有人比我更快地尝试和失败,并能为我指明正确的方向?

:D

如果我理解得对,你需要两个下拉菜单来显示这两个部分的主题,然后你需要通过ajax发布这两个值,然后在php代码中,你可以将主题值保存到数据库中。这样你就可以在用户打开网站时读取这些值。我不明白,问题就在眼前。

要突出显示几秒钟,可以使用jquerys添加类,如下所示:

$("#sucessId").addClass("solve");
setTimeout(function (){         
    $("#sucessId").removeClass("solve");
}, 500);

然后,Id为successId的div会让类求解半秒钟,所以你只需要一个CSS文件,它会像橙色边框一样给出类的求解。

好的,现在我浪费了很多时间来完成您的解决方案。希望现在一切顺利:

<html>
    <head>
        <title>Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
        <style type="text/css">
            .solve {
                border: 1px solid #000000;
            }
        </style>
    </head>
    <body>
        <form onsubmit="saveTheme();">
            Sectiontheme 1:
            <select id="section1">
                <option value="dark"> Dark Theme </option>
                <option value="light"> Light Theme
            </select>
            </select>
            Sectiontheme 2:
            <select id="section2">
                <option value="dark"> Dark Theme </option>
                <option value="light"> Light Theme </option>
            </select>
            <input type="submit" value="Save">
        </form>
        <div id="sucessId1" style="width: 200px; height: 200px;">
        </div>
        <div id="sucessId2" style="width: 200px; height: 200px;">
        </div>
        <script type="text/javascript">
            var sectionCounter = 0;
            function saveTheme() {
                theme = document.getElementById("section" + (sectionCounter + 1)).value;
                $.ajax({
                    url : "save.php",
                    type : 'POST',
                    data : {
                        "theme" : theme,
                    },
                    error : function(xhr, status, error) {
                        alert(xhr.toSource());
                    },
                    success : function() {
                        $("#sucessId" + (sectionCounter + 1)).addClass("solve");
                        setTimeout(function() {
                            $("#sucessId" + (sectionCounter + 1)).removeClass("solve");
                        }, 500);
                        sectionCounter = 1 - sectionCounter
                        if (sectionCounter == 1) {
                            saveTheme();
                        }
                    }
                });
                return false;
            }
        </script>
    </body>
</html>