Как получить альтернативную таблицу стилей для загрузки в wp_head при сохранении / сбросе страницы параметров темы? - PullRequest
0 голосов
/ 28 мая 2011

Я надеялся, что смогу получить некоторую помощь о том, как загрузить две разные встроенные таблицы стилей в тег head (ловушка действия wp_head), в зависимости от того, нажмет ли пользователь кнопку сохранения или сброса на странице параметров темы.

При настройке сейчас сохраняются только параметры, указанные в массиве в начале (параметры, введенные пользователем), но не альтернативная таблица стилей.Прямо сейчас у меня есть функции-заполнители, называемые test1 () и test2 () вместо реальных таблиц стилей, которые будут загружены в wp_head.Ниже приведен код, который у меня есть.Части, которые закомментированы ниже тестовых функций, - вот что я пытался заставить эту функциональность работать.

<?php // add the admin options page
$themename = "Cool Orange";
$shortname = "co";
$options = array (
array ( "name" => "Main Settings",
    "type" => "title" ),

array ( "type" => "open" ),

array ( "name" => "Upload logo to the Media Library:",
    "id" => $shortname."_logo_label",
    "std" => "",
    "type" => "label" ),

array ( "name" => "Logo location:",
    "desc" => "In this section, you can replace the standard blog title heading with a custom logo. The logo cannot be wider than 960 pixels.",
    "id" => $shortname."_logo_url",
    "std" => "",
    "type" => "text" ),

array ( "name" => "Logo width:",
    "desc" => "Enter logo width in pixels, for example <strong>800px</strong>",
    "id" => $shortname."_logo_width",
    "std" => "",
    "type" => "text" ),

array ( "name" => "Logo height:",
    "desc" => "Enter logo height in pixels, for example <strong>90px</strong>",
    "id" => $shortname."_logo_height",
    "std" => "",
    "type" => "text" ),

array( "type" => "close" )

);

function mytheme_add_admin() {
    global $themename, $shortname, $options;

    if ( $_GET['page'] == basename(__FILE__) ) {
        if ( 'save' == $_REQUEST['action'] ) {
            foreach($options as $value) {
                update_option( $value['id'], $_REQUEST[ $value['id'] ] ); }
            foreach ($options as $value) {
        if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ]  ); } else { delete_option( $value['id'] ); } }
        header("Location: themes.php?page=functions.php&saved=true");
        die;
        } else if( 'reset' == $_REQUEST['action'] ) {
            foreach ($options as $value) {
                delete_option( $value['id'] ); }
            header("Location: themes.php?page=functions.php&reset=true");
            die;
        }
    }
    add_theme_page($themename." Options", "".$themename." Options", 'edit_themes', basename(__FILE__), 'mytheme_admin');
}

function mytheme_admin() {
    global $themename, $shortname, $options;

    if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
    if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>'; ?>
<div class="wrap">
<h2><?php echo $themename; ?> Theme Options</h2>

<form method="post">
    <h3>How to upload a logo to replace the heading</h3>
    <div style="background-color: #FFFFFF; border: 1px solid #BBBBBB; padding: 30px;">
    <ul style="list-style: disc;">
    <li>Upload the image from your computer to the Media Library using the <strong>Upload image</strong> button below</li>
    <li>Go to the <strong>Media</strong> button at the left to acces the Media Library. Look for the file you just uploaded. It should be the file at the top of the list.</li>
    <li>Once you mouseover the image, click <strong>Edit</strong></li>
    <li>in the Edit Media dialog, highlight (Ctrl a) the url in the <strong>File URL</strong> textbox</li>
    <li>Note the width and height of the image</li>
    <li><strong>Copy</strong> (ctrl c) the url and return to this page by clicking <strong>Appearance</strong>, then <strong>Cool Orange Theme Options</strong></li>
    <li><strong>Paste</strong> (ctrl v) the url into the <strong>Logo location</strong> box below</li>
    <li><strong>Paste</strong> (ctrl v) the width and height of the image into the <strong>Logo width</strong> and <strong>Logo height</strong> boxes below</li>
    </ul>
    </div>
<?php foreach($options as $value) {
//Next is the code which tells WordPress how to display the ‘type’ of option used (title, open, close, text, textarea, checkbox etc.)

switch ( $value['type'] ) {
    case "open":
    ?>
    <div style="width: 100%;">
    <?php break;
    case "title":
    ?>
    <h3><?php echo $value['name']; ?></h3>
    <?php break;
    case "label":
    ?>
    <p><?php echo $value['name']; ?></p>
    <p><label for="upload_image">
    <input id="upload_image_button" type="button" value="Upload image" /></p>
    <?php break;
    case "text":
    ?>
    <p><strong><?php echo $value['name']; ?></strong></p>
    <input style="width:400px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" /><br />
    <div style="font-size: 11px;"><?php echo $value['desc']; ?></div>
    <?php break;
    case "close":
    ?>
    </div><br />
    <?php break;
    }
} ?>
<p class="submit">
<input name="save" class="button-primary" type="submit" value="Save changes" />
<input type="hidden" name="action" value="save" />
</p>
</form>
<form method="post">
<p class="submit">
<input name="reset" class="button-primary" type="submit" value="Reset" />
<input type="hidden" name="action" value="reset" />
</p>
</form>

</div> 
<?php 
}

add_action('admin_menu', 'mytheme_add_admin'); 

//Scripts to load WP's Media Library panel
//http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/

function my_admin_scripts() {
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    wp_register_script('my-upload', trailingslashit( get_stylesheet_directory_uri()).'scripts/invoke_uploader.js', array('jquery','media-upload','thickbox'));
    wp_enqueue_script('my-upload');
}

function my_admin_styles() {
    wp_enqueue_style('thickbox');
}

if (isset($_GET['page']) && $_GET['page'] == 'functions.php') {
    add_action('admin_print_scripts', 'my_admin_scripts');
    add_action('admin_print_styles', 'my_admin_styles');
}

//test functions
function test1() { 
echo '<!-- logo stylesheet -->';
}

function test2() {
echo '<!-- reset stylesheet -->';
}

//if ( $_REQUEST['saved'] ) {
//      add_action('wp_head', 'test1');
//} elseif ( $_REQUEST['reset'] ) {
//      add_action('wp_head', 'test2');
//}

?>

Я также открыт для альтернативных способов сделать это.

1 Ответ

0 голосов
/ 30 мая 2011

Похоже, что после двух дней проб и ошибок я нашел решение, или, скорее, обходной путь для этой проблемы.Я следовал учебному пособию о том, как переключать таблицы стилей со страницы настроек темы.Учебное пособие называется Добавление переключателя стилей в тему WordPress .В этом уроке автор переключает внешние таблицы стилей из выпадающего меню выбора.В своем коде я поменял внешние таблицы стилей на встроенные таблицы стилей.В случае моего вопроса выше, это были бы функции test1 и test2.

Пример кода:

Добавить новый массив сверху

array ( "name" => "Restore CSS",
    "desc" => "Restore the original heading text",
    "id" => $shortname."_restore_css",
    "type" => "select",
    "options" => array ("select an option", "test2"),
    "std" => "Logo CSS" ),

Затем добавьте новую функцию, в данном случае с именем css_switcher

function css_switcher() { //opens css_switcher function

global $options;
foreach ($options as $value) {
    if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); }
}

?>
<!-- logo stylesheet goes outside of switch statement -->
<?php switch ($co_restore_css) {//opens switch statement
case "select an option": //nothing goes between this closing php tag and
                         // next opening php tag, to make select an option do nothing 
?>
<?php break;
case "Restore CSS": ?>
<!-- restore stylesheet goes inside of switch statement -->
<?php break; 
}//closes switch statement

}//closes css_switcher_function

add_action('wp_head', 'css_switcher');
?>

Это сработало для меня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...