usa o editor de temas / plugins do Wordpress no meu plugin

4

Existe uma maneira de usar o editor do wordpress theme / plugin dentro do meu plugin para dar ao usuário a capacidade de editar o arquivo css do meu plugin?

Estou construindo um plugin que dá ao usuário a opção de adicionar CSS. Primeiro eu ia usar apenas uma textarea, mas depois pensei que seria bonito se eu pudesse usar o editor do Wordpress que irá abrir o meu arquivo style.css. Eu poderia colocar apenas um link para enlace mas seria ótimo se eu pudesse integrá-lo no meu plugin.

Atenciosamente

    
por chifliiiii 05.12.2011 / 20:32

2 respostas

0

Para começar, você pode usar o seguinte código. Por segurança, você também pode adicionar alguma verificação do nonce e até mesmo usar as configurações da API. Aqui plugin-test é o nome da sua pasta de plugins.

$file = stripslashes('plugin-test/style.css');
$plugin_files = get_plugin_files($file);
$file = validate_file_to_edit($file, $plugin_files);
$real_file = WP_PLUGIN_DIR . '/' . $file;

if( isset($_POST['plugin_test_settings']['newcontent']) ) {
    $newcontent = stripslashes($_POST['plugin_test_settings']['newcontent']);
    if ( is_writeable($real_file) ) {
            $f = fopen($real_file, 'w+');
            fwrite($f, $newcontent);
            fclose($f);
    }
}

$content = file_get_contents( $real_file );

$content = esc_textarea( $content ); ?>
<table class="form-table">
    <tbody>
        <tr valign="top">
            <td>
                <textarea cols="70" rows="25" name="plugin_test_settings[newcontent]" id="newcontent" tabindex="1"><?php echo $content ?></textarea>
            </td>
        </tr>
    </tbody>
</table>
    
por Joshua Abenazer 08.12.2011 / 05:12
1

Se você está procurando por uma solução mais complexa, eu escrevi o plugin WP Custom File Editor baseado no código do tema da Tese enlace

<?php
/*
Plugin Name: WP Custom File Editor
Plugin URI: http://www.webikon.eu/
Description: Simple file editor
Version: 0.1
Author: Ján Bočínec
Author URI: http://johnnypea.wp.sk/
License: GPLv2 or later
*/

/* This code is based on code from Thesis theme http://diythemes.com/ */

// You can define your custom folder where are located files you would like to be editable. Default is current folder.
if (!defined('WPCFE_CUSTOM_FOLDER'))
    define('WPCFE_CUSTOM_FOLDER', __DIR__);

/**
 * You can define your own array of file paths.
 * If this is set, only these files are loaded into the editor
 */
// global $custom_files_array;
// $custom_files_array = array('custom.css', 'hello.php');

// register the admin menu
add_action('admin_menu', 'wpcfe_add_menu');
// save the changes
add_action('admin_post_wpcfe_file_editor', array('wpcfe_custom_editor', 'save_file'));

// Add admin menu
function wpcfe_add_menu() {
    add_options_page(__('WP Custom File Editor', 'wpcfe'), __('WP Custom File Editor', 'wpcfe'), 'edit_themes', 'wpcfe-file-editor', array('wpcfe_custom_editor', 'options_page'));
}

/**
 * Outputs the Custom File Editor
 */
class wpcfe_custom_editor {

    function wpcfe_custom_editor($custom_files_array='') {
        $this->custom_files = $custom_files_array;
    }

    function get_custom_files() {
        $files = array();
        if ( $this->custom_files )
            return $files = $this->custom_files;
        if ( !is_dir (WPCFE_CUSTOM_FOLDER) )
            return $files;
        $directory = opendir(WPCFE_CUSTOM_FOLDER); // Open the directory
        $exts = array('.php', '.css', '.js', '.txt', '.inc', '.htaccess', '.html', '.htm'); // What type of files do we want?

        while ($file = readdir($directory)) { // Read the files
            if ($file != '.' && $file != '..' && (strpos($file, 'layout') === false)) { // Only list files within the _current_ directory
                $extension = substr($file, strrpos($file, '.')); // Get the extension of the file

                if ($extension && in_array($extension, $exts)) // Verify extension of the file; we can't edit images!
                    $files[] = $file; // Add the file to the array
            }
        }

        closedir($directory); // Close the directory
        return $files; // Return the array of editable files
    }

    function is_custom_writable($file, $files) {
        if (!in_array($file, $files) && is_dir (WPCFE_CUSTOM_FOLDER))
            $error = "<p><strong>" . __('Attention!', 'wpcfe') . '</strong> ' . __('For security reasons, the file you are attempting to edit cannot be modified via this screen.', 'wpcfe') . '</p>';
        elseif (!file_exists(WPCFE_CUSTOM_FOLDER)) // The custom/ directory does not exist
            $error = "<p><strong>" . __('Attention!', 'wpcfe') . '</strong> ' . __('Your <code>'.WPCFE_CUSTOM_FOLDER.'/</code> directory does not appear to exist.', 'wpcfe') . '</p>';
        elseif (!is_file(WPCFE_CUSTOM_FOLDER . '/' . $file)) // The selected file does not exist
            $error = "<p><strong>" . __('Attention!', 'wpcfe') . '</strong> ' . __('The file you are attempting does not appear to exist.', 'wpcfe') . '</p>';
        elseif (!is_writable(WPCFE_CUSTOM_FOLDER . '/' . $file)) // The selected file is not writable
            $error = "<p><strong>" . __('Attention!', 'wpcfe') . '</strong> ' . sprintf(__('Your <code>/'.WPCFE_CUSTOM_FOLDER.'/%s</code> file is not writable by the server, and in order to modify the file via the admin panel, WP File Editor needs to be able to write to this file. All you have to do is set this file&#8217;s permissions to 666, and you&#8217;ll be good to go.', 'wpcfe'), $file) . '</p>';

        if ($error) { // Return the error + markup, if required
            $error = "<div class=\"warning\">\n\t$error\n</div>\n";
            return $error;
        }

        return false;
    }

    function save_file() {
        if (!current_user_can('edit_theme_options'))
            wp_die(__('Easy there, homey. You don&#8217;t have admin privileges to access theme options.', 'wpcfe'));

        $custom_editor = new wpcfe_custom_editor;

        if (isset($_POST['custom_file_submit'])) {
            check_admin_referer('wpcfe-custom-file', '_wpnonce-wpcfe-custom-file');
            $contents = stripslashes($_POST['newcontent']); // Get new custom content
            $file = $_POST['file']; // Which file?
            $allowed_files = $custom_editor->get_custom_files(); // Get list of allowed files

            if (!in_array($file, $allowed_files)) // Is the file allowed? If not, get outta here!
                wp_die(__('You have attempted to modify an ineligible file. Only files within the <code>/'.WPCFE_CUSTOM_FOLDER.'</code> folder may be modified via this interface. Thank you.', 'wpcfe'));

            $file_open = fopen(WPCFE_CUSTOM_FOLDER . '/' . $file, 'w+'); // Open the file

            if ($file_open !== false) // If possible, write new custom file
                fwrite($file_open, $contents);

            fclose($file_open); // Close the file
            $updated = '&updated=true'; // Display updated message
        }
        elseif (isset($_POST['custom_file_jump'])) {
            check_admin_referer('wpcfe-custom-file-jump', '_wpnonce-wpcfe-custom-file-jump');
            $file = $_POST['custom_files'];
            $updated = '';
        }

        wp_redirect(admin_url("admin.php?page=wpcfe-file-editor$updated&file=$file"));
    }

    function options_page() {
        global $wpcfe_site, $custom_files_array;

        $custom_editor = new wpcfe_custom_editor($custom_files_array);
?>

<div id="wpcfe_options" class="wrap<?php if (get_bloginfo('text_direction') == 'rtl') { echo ' rtl'; } ?>">

<?php

    wpcfe_options_status_check();

    // Determine which file we're editing. Default to something harmless, like custom.css.
    $file = ($_GET['file']) ? $_GET['file'] : 'custom.css';
    $files = $custom_editor->get_custom_files();
    $extension = substr($file, strrpos($file, '.'));

    // Determine if the custom file exists and is writable. Otherwise, this page is useless.
    $error = $custom_editor->is_custom_writable($file, $files);

    if ($error)
        echo $error;
    else {
        // Get contents of custom.css
        if (filesize(WPCFE_CUSTOM_FOLDER . '/' . $file) > 0) {
            $content = fopen(WPCFE_CUSTOM_FOLDER . '/' . $file, 'r');
            $content = fread($content, filesize(WPCFE_CUSTOM_FOLDER . '/' . $file));
            $content = htmlspecialchars($content);
        }
        else
            $content = '';
    }
?>
    <div class="one_col">
        <form method="post" id="file-jump" name="file-jump" action="<?php echo admin_url('admin-post.php?action=wpcfe_file_editor'); ?>">
            <h3><?php printf(__('Currently editing: <code>%s</code>', 'wpcfe'), "$file"); ?></h3>
            <p>
                <select id="custom_files" name="custom_files">
                    <option value="<?php echo $file; ?>"><?php echo $file; ?></option>
<?php
        foreach ($files as $f) // An option for each available file
            if ($f != $file) echo "\t\t\t\t\t<option value=\"$f\">$f</option>\n";
?>
                </select>
                <?php wp_nonce_field('wpcfe-custom-file-jump', '_wpnonce-wpcfe-custom-file-jump'); ?>
                <input type="submit" id="custom_file_jump" class="button" name="custom_file_jump" value="<?php _e('Edit selected file', 'wpcfe'); ?>" />
            </p>
<?php
        if ($extension == '.php')
            echo "\t\t\t<p class=\"alert\">" . __('<strong>Note:</strong> If you make a mistake in your code while modifying a <acronym title="PHP: Hypertext Preprocessor">PHP</acronym> file, saving this page <em>may</em> result your site becoming temporarily unusable. Prior to editing such files, be sure to have access to the file via <acronym title="File Transfer Protocol">FTP</acronym> or other means so that you can correct the error.', 'wpcfe') . "</p>\n";
?>
        </form>
        <form class="file_editor" method="post" id="template" name="template" action="<?php echo admin_url('admin-post.php?action=wpcfe_file_editor'); ?>">
            <input type="hidden" id="file" name="file" value="<?php echo $file; ?>" />
            <p><textarea id="newcontent" name="newcontent" rows="25" cols="50" class="large-text"><?php echo $content; ?></textarea></p>
            <p>
                <?php wp_nonce_field('wpcfe-custom-file', '_wpnonce-wpcfe-custom-file'); ?>
                <input type="submit" class="button-primary" id="submit" name="custom_file_submit" value="<?php _e('Save changes', 'wpcfe'); ?>" />
            </p>
        </form>
    </div>

</div>
<?php
    }
}

// Update message after saving the changes
function wpcfe_options_status_check($depth = 1) {
    $indent = str_repeat("\t", $depth);

    if ($_GET['updated']) {
        echo "$indent<div id=\"updated\" class=\"updated fade\">\n";
        echo "$indent\t<p>" . __('Options updated!', 'wpcfe') . ' <a href="' . get_bloginfo('url') . '/">' . __('Check out your site &rarr;', 'wpcfe') . "</a></p>\n";
        echo "$indent</div>\n";
    }

}
    
por Ján Bočínec 09.12.2011 / 00:45