Add item to administrative menu to save custom value

Asked

Viewed 339 times

3

I’m trying to add an ad in the middle of posting Wordpress.

<?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 on the page single.php?

1 answer

2


You can do this with "brute force" by creating a form on this options page and adding a admin_init that will observe if this form has been sent and if everything is secure (check_admin_referer) and sanitized (standard procedure for any form) will record this in the options table (update_option).

But it is indicated to use the Settings API which is mainly responsible for security in the processing of the form. The following example was added by me to Codex and the only change I made here -besides translating the comments- was to change the add_options_page from the original (add page as sub-menu of Settings/Settings) to add_menu_page (add the page as a main menu).
Tip: use add_theme_page to be an Appearance/Appearance sub-menu.

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

The result is this:
menu wordpress personalizado

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 Change Theme wants this to continue working, then nay we put inside functions.php

<?php
/*
 * Plugin Name: Minhas Opções
 * Plugin URI: /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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.