Add item to administrative menu to save custom value

3

I'm trying to add an ad in the middle of the WordPress post.

<?php
    $paragraphAfter = 3; //display after the first paragraph
    $content = apply_filters('the_content', get_the_content());
    $content = explode("</p>", $content);
    for ($i = 0; $i <count($content); $i++ ) {
    if ($i == $paragraphAfter) { ?>
    <div class="googlepublisherpluginad" style="text-align: center; width: 100%; height: auto; clear: none;">

    </div>
    <?php }
    echo $content[$i] . "</p>";
    } ?>

The code works. But I tried to add an item in the admin menu ... it was added.

add_action( 'admin_menu', 'addAdminMenu' );
function addAdminMenu(){
    add_menu_page('Add Adsense', 'Adsense', 'manage_options', 'adsense-page', 'admin_pg_function', '', 3);
}

function admin_pg_function(){
    if(!current_user_can('manage_options')){
        wp_die( __( 'Você não possui premissão duficiente para acessar esta página.' ) );
    }

    ?>
    <div style="width:100%;">
    <h1>Adicionar Adsense</h1>
    <textarea>Olá</textarea>

<?php }

My problem now is to save what I type on that page, and how to retrieve it and call the single.php page?

    
asked by anonymous 28.12.2015 / 14:51

1 answer

2

It is possible to do this with "brute force" by creating a form on this options page and adding a admin_init that will observe if this form was sent and if everything is safe ( check_admin_referer ) and sanitized (standard procedure for any form) will save this in the options table ( update_option ).

But the right thing to do is to use the Settings API that is mainly responsible for the security in the processing of the form. The following example has been added by me to Codex and the only change I made here - in addition to translating the comments - was change the add_options_page of the original (add the page as a submenu of the Settings / Settings) to add_menu_page (add the page as a main menu). Tip: use add_theme_page to be one Appearance / Appearance sub-menu.

The advantage of adding as a sub-menu is that this is the type of page that we visit very little, I think it's a pollution from the main menu to add items that are rarely used.

The result is this:

And to get these options in the theme use:

$my_options = get_option( 'my_option_name' ); 
// mostra a variável, use $my_options['nome_da_opcao'] para pegar valores individuais
var_dump($my_options);

PLUGIN
If you change Theme it will keep working, then do not put it inside functions.php

<?php
/*
 * Plugin Name: Minhas Opções
 * Plugin URI: http://pt.stackoverflow.com/a/106105/201
 * Description: Adiciona menu/submenu com opções personalizadas
 * Version: 1.0
 * Author: brasofilo
*/

class MySettingsPage
{
    /**
     * Guarda o valor das nossas opções
     */
    private $options;

    /**
     * Iniciar plugin
     */
    public function __construct()
    {
        add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
        add_action( 'admin_init', array( $this, 'page_init' ) );
    }

    /**
     * Adicionar menu
     */
    public function add_plugin_page()
    {
        // This page will be under "Settings"
        add_menu_page(
            'Settings Admin', 
            'My Settings', 
            'manage_options', 
            'my-setting-admin', 
            array( $this, 'create_admin_page' )
        );
    }

    /**
     * HTML do menu
     */
    public function create_admin_page()
    {
        // Pega as opção armazenadas
        $this->options = get_option( 'my_option_name' );
        ?>
        <div class="wrap">
            <h2>My Settings</h2>           
            <form method="post" action="options.php">
            <?php
                // Imprime todos nossos settings
                settings_fields( 'my_option_group' );   
                do_settings_sections( 'my-setting-admin' );
                submit_button(); 
            ?>
            </form>
        </div>
        <?php
    }

    /**
     * Registrar e adicionar opções
     */
    public function page_init()
    {        
        register_setting(
            'my_option_group', // Option group
            'my_option_name', // Option name
            array( $this, 'sanitize' ) // Sanitize
        );

        add_settings_section(
            'setting_section_id', // ID
            'My Custom Settings', // Title
            array( $this, 'print_section_info' ), // Callback
            'my-setting-admin' // Page
        );  

        add_settings_field(
            'id_number', // ID
            'ID Number', // Title 
            array( $this, 'id_number_callback' ), // Callback
            'my-setting-admin', // Page
            'setting_section_id' // Section           
        );      

        add_settings_field(
            'title', 
            'Title', 
            array( $this, 'title_callback' ), 
            'my-setting-admin', 
            'setting_section_id'
        );      
    }

    /**
     * Sanitizar cada opção conforme necessário
     *
     * @param array $input Contém todas nossas opções como chaves da array (array keys)
     */
    public function sanitize( $input )
    {
        $new_input = array();
        if( isset( $input['id_number'] ) )
            $new_input['id_number'] = absint( $input['id_number'] );

        if( isset( $input['title'] ) )
            $new_input['title'] = sanitize_text_field( $input['title'] );

        return $new_input;
    }

    /** 
     * Imprimir o texto Section
     */
    public function print_section_info()
    {
        print 'Enter your settings below:';
    }

    /** 
     * Imprime a opção "id_number"
     */
    public function id_number_callback()
    {
        printf(
            '<input type="text" id="id_number" name="my_option_name[id_number]" value="%s" />',
            isset( $this->options['id_number'] ) ? esc_attr( $this->options['id_number']) : ''
        );
    }

    /** 
     * Imprime a opção "title"
     */
    public function title_callback()
    {
        printf(
            '<input type="text" id="title" name="my_option_name[title]" value="%s" />',
            isset( $this->options['title'] ) ? esc_attr( $this->options['title']) : ''
        );
    }
}

// Executar somente se estivermos na área administrativa (is_admin)
if( is_admin() )
    $my_settings_page = new MySettingsPage();
    
30.12.2015 / 12:40