类中的条件标记

时间:2014-04-19 作者:Pieter Goosen

我现在在一个类中组合了几个函数。这样做的原因是所有这些函数都朝着一个目标前进,而在这些函数之间使用全局变量更合适。该类由三个主要部分组成,第一部分添加我的元框,第二部分添加创建边栏的选项页面,第三部分实际注册边栏。

我现在的问题是,第一节和第二节只需要在管理端运行。我知道如何在正常功能上实现这一点。我的问题是如何在课堂上做到这一点。我知道您可以将整个类包装在is_admin() 标记,但这在这里不起作用,因为我的边栏不会显示在前端。

我如何才能在is_admin() 标签这是我的课

class PieterGoosen_Custom_Sidebars {
    private $sdwas;

    public function __construct() {

        add_action( \'add_meta_boxes\', array( $this, \'add_cspp\' ) );
        add_action( \'save_post\', array( $this, \'save_cspp\' ) );
        add_action( \'admin_init\', array( $this, \'init\' ) );
        add_action( \'admin_menu\', array( $this, \'add_page\' ) );
        add_action( \'widgets_init\', array( $this, \'sidebars_register\' ) );

    }

    /*----------------------------------------------------------------------------------
     *
     *      Create and add meta box to page edit screen
     *
     *---------------------------------------------------------------------------------*/

    public function add_cspp() {

        //Meta box in page screen
        add_meta_box( 
            \'custom_sidebar_per_page\', 
            __( \'Sidebar options\', \'pietergoosen\' ), 
            array( $this, \'cspp_link\' ),
            \'page\', 
            \'side\', 
            \'high\'
        );

        // Meta box in post screen
        add_meta_box( 
            \'custom_sidebar_per_page\', 
            __( \'Sidebar options\', \'pietergoosen\' ), 
            array( $this, \'cspp_link\' ),
            \'post\', 
            \'side\', 
            \'high\'
        );
    }

    public function cspp_link( $post ) {

        wp_nonce_field( \'cspp_meta_nonce\', \'cspp_nonce\' );

        $custom = get_post_custom($post->ID);

        if(isset($custom[\'_custom_sidebar_per_page\']))
            $val = $custom[\'_custom_sidebar_per_page\'][0];
        else
            $val = "default";

        // The actual fields for data entry
        $output = \'<p><label for="pietergoosen_new_field">\'.__( \'Choose a sidebar to display\', \'pietergoosen\' ).\'</label></p>\';
        $output .= \'<select name="custom_sidebar_per_page">\';

        // Add a default option
        $output .= \'<option\';
        if($val == "default")
            $output .= \' selected="selected"\';
        $output .= \' value="default">\'.__( \'No Specified Sidebar\', \'pietergoosen\' ).\'</option>\';

        // Fill the select element with all registered sidebars
        if(!empty($this->sdwas))
            foreach($this->sdwas as $sid => $sdwa) {  
                $output .= \'<option\';  
                if($sdwa == $val)  
                    $output .= \' selected="selected"\';  
                $output .= \' value="\'.$sdwa.\'">\'.$sdwa.\'</option>\';  
            }  

        $output .= \'</select>\';  

        echo $output;  
    } 

    public function save_cspp($post_id){

        // Check if our nonce is set.
        $nonce = filter_input(INPUT_POST, \'cspp_nonce\', FILTER_SANITIZE_STRING);

        // Verify that the nonce is valid.
        if ( empty($nonce) || ! wp_verify_nonce( $nonce, \'cspp_meta_nonce\' ) )
            return $post_id;

        // If this is an autosave, our form has not been submitted, so we don\'t want to do anything.
        if ( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE ) 
        return $post_id;

        // Check the user\'s permissions for pages.
        if ( !current_user_can( \'edit_page\', $post_id ) )
            return;

        // Check the user\'s permissions for posts.
        if ( !current_user_can( \'edit_post\', $post_id ) )
            return; 

        /* OK, its safe for us to save the data now. */
        $custom = filter_input(INPUT_POST, \'custom_sidebar_per_page\', FILTER_SANITIZE_STRING);

        if(!empty( $_POST[\'custom_sidebar_per_page\'] )) {
            update_post_meta($post_id, \'_custom_sidebar_per_page\', $custom);
        }else{
            delete_post_meta( $post_id, \'_custom_sidebar_per_page\');
        }
    }

    /*----------------------------------------------------------------------------------
     *
     *      Register and add a options screen under the "Appearance" menu screen.
     *          Sidebars are created/deleted here.
     *
     *---------------------------------------------------------------------------------*/

    public function init() {

        register_setting( 
            \'set_fields\', 
            \'cspp_get_option\', 
            array( $this, \'sanitation\' )
        );

        add_settings_section( 
            \'general\',  
            __( \'Custom sidebars per page\', \'pietergoosen\' ), 
            \'__return_false\', 
            \'theme_options\' 
        );

        add_settings_field( 
            \'custom_sidebar_per_page\', 
            __( \'Custom sidebars\', \'pietergoosen\' ), 
            array( $this, \'settings_field\' ), 
            \'theme_options\', 
            \'general\' 
        );

    }

    public function add_page() {
        add_theme_page(
            __( \'Custom Sidebars\', \'pietergoosen\' ),     
            __( \'Custom Sidebars\', \'pietergoosen\' ),     
            \'edit_theme_options\',                       
            \'theme_options\',                             
            array( $this, \'render_page\' )                
        );
    }

    public function render_page() {
        if (! current_user_can(\'edit_theme_options\') ) 
            return;
         ?>
        <div class="wrap">
            <h2><?php _e( \'Custom Sidebars Per Page Options\', \'pietergoosen\' ); ?></h2>  
            <p>
                <?php 
                _e( \'Create or remove custom sidebars that can be individually used on posts and pages\', \'pietergoosen\' )
                ?>
            </p>
            <form method="post" action="options.php">
            <?php
                // This prints out all hidden setting fields
                settings_fields( \'set_fields\' ); 
                do_settings_sections( \'theme_options\' );
                submit_button(); 
            ?>
            </form>
        </div>
        <?php
    }

    public function sanitation( $input ) {

        $output = array();

        if ( isset( $input[\'_custom_sidebar_per_page\'] ) ) {
        $output[\'_custom_sidebar_per_page\'] = $input[\'_custom_sidebar_per_page\'];
        }   
        return $output;
    }

    public function settings_field() {

        $option1 = get_option( \'cspp_get_option\' );

        // A bit of jQuery to handle interactions (add / remove sidebars)
        $val1 = \'<script type="text/javascript">\';
        $val1 .= \'
                    var $ = jQuery;
                    $(document).ready(function(){
                        $(".sidebar_management").on("click", ".delete", function(){
                            $(this).parent().remove();
                        });

                        $("#add_sidebar").click(function(){
                            $(".sidebar_management ul").append("<li>"+$("#new_sidebar_name").val()+" <a href=\\\'#\\\' class=\\\'delete\\\'>\'.__(\'Delete\', \'pietergoosen\').\'</a> <input type=\\\'hidden\\\' name=\\\'cspp_get_option[_custom_sidebar_per_page][]\\\' value=\\\'"+$("#new_sidebar_name").val()+"\\\' /></li>");
                            $("#new_sidebar_name").val("");
                        })

                    })
        \';

        $val1 .= \'</script>\';

        $val1 .= \'<div class="sidebar_management">\';

        $val1 .= \'<p><input type="text" id="new_sidebar_name" /></p><p><input class="button-primary" type="button" id="add_sidebar" value="\'.__(\'Add\', \'pietergoosen\').\'" /></p>\';

        $val1 .= \'<ul>\';

        // Display all custom sidebars
        if(isset($option1[\'_custom_sidebar_per_page\']) ? esc_attr($option1[\'_custom_sidebar_per_page\']) : \'\') {
            $csppval = $option1[\'_custom_sidebar_per_page\'];
            $i = 0;

            foreach($csppval as $sdwa) {
                $val1 .= \'<li>\'.$sdwa.\' <a href="#" class="delete">\'.__( \'Delete\', \'pietergoosen\' ).\'</a><input type="hidden" name="cspp_get_option[_custom_sidebar_per_page][]" value="\'.$sdwa.\'" /></li>\';
                $i++;
            }
        }

        $val1 .= \'</ul>\';

        $val1 .= \'</div>\';

        echo $val1;
    }

    /*----------------------------------------------------------------------------------
     *
     *      Register the custom sidebars if a value is entered in save in the options
     *          screens. Also create a sidebar ID from this value
     *
     *---------------------------------------------------------------------------------*/

    public function sidebars_register() {

        $option2 = get_option( \'cspp_get_option\' );
            if( isset($option2[\'_custom_sidebar_per_page\']))
                $this->sdwas = $option2[\'_custom_sidebar_per_page\'];

        if( isset($this->sdwas) && sizeof($this->sdwas) > 0) {  
            foreach($this->sdwas as $sid => $sdwa) {

                register_sidebar(
                    array (
                        \'name\'          => $sdwa,
                        \'id\'            => sanitize_title($sdwa),
                        \'description\'   => __( \'Page specific sidebars that can be chosen per page\', \'pietergoosen\' ),
                        \'before_widget\' => \'<aside id="%1$s" class="widget %2$s">\',
                        \'after_widget\'  => \'</aside>\',
                        \'before_title\'  => \'<h1 class="widget-title">\',
                        \'after_title\'   => \'</h1>\',
                    )
                );
            }
        }
    }
}

$pgsidebar = new PieterGoosen_Custom_Sidebars();

EDIT

正如@isNaN所建议的,我已经试过了。

public function __construct() {
    if (is_admin()) {
        add_action( \'add_meta_boxes\', array( $this, \'add_cspp\' ) );
        add_action( \'save_post\', array( $this, \'save_cspp\' ) );
        add_action( \'admin_init\', array( $this, \'init\' ) );
        add_action( \'admin_menu\', array( $this, \'add_page\' ) );
    } 
        add_action( \'widgets_init\', array( $this, \'sidebars_register\' ) );
    }
我不确定这是不是正确的方法。所有函数仍使用此方法执行。只是钩子没有执行,因为它们在条件标记中。我真的认为应该有一种方法可以在is_admin() 条件标记,而不仅仅是操作挂钩

2 个回复
最合适的回答,由SO网友:fuxia 整理而成

你真正的问题是上帝阶级。您将渲染、卫生、验证、保存和获取数据以及注册放在一个类中。Separate your tasks 使其成为OOP,并让main类成为一个非常简单的前端控制器,它只处理初始注册。

这是一个粗略的开始,说明了我将如何做到这一点:

// validate nonces
interface PG_Nonce_Validator_Interface {
    public function is_valid();
    public function get_name();
    public function get_action();
}
class PG_Nonce_Validator implements PG_Nonce_Validator_Interface {
    public function __construct( $base_string ) {}
    public function is_valid() {}
    public function get_name() {}
    public function get_action() {}
}

// validate request for the action \'save_post\'
interface PG_Request_Validator_Interface {
    public function is_valid();
}
class PG_Save_Post_Validator implements PG_Request_Validator_Interface {
    public function __construct( PG_Nonce_Validator_Interface $nonce_validator ) {}
    public function is_valid() {}
}

// sanitation
interface PG_Sanitize_Data_Interface {
    public function sanitize( $data );
}
class PG_Sanitize_Data implements PG_Sanitize_Data_Interface {
    public function sanitize( $data ) {}
}

// data access
interface PG_Data_Interface {
    public function save( $data );
    public function get();
}
class PG_Option_Data implements PG_Data_Interface {
    public function __construct( $option_name ) {}
    public function save( $data ) {}
    public function get() {}
}

interface PG_View_Interface {
    public function render();
}

interface PG_Event {
    public function trigger( $name, $data = NULL );
}

class PG_Settings_Page implements PG_View_Interface {

    public function __construct() {

    }

    public function render() {}
}


class PG_Custom_Sidebars {

    private $option_name = \'cspp_get_option\';

    // we do not run methods automatically in a constructor
    public function setup() {

        if ( is_admin() )
            $this->register_admin_actions();

        add_action( \'widgets_init\', array( $this, \'register_sidebars\' ) );
    }

    public function register_sidebars() {}

    private function register_admin_actions() {

        $nonce             = new PG_Nonce_Validator( \'pg_nonce\' );
        $request_validator = new PG_Save_Post_Validator( $nonce );
        // and so on …
    }
}

$pg_custom_sidebars = new PG_Custom_Sidebars;
$pg_custom_sidebars->setup();
您可以在多语言出版社中找到类似类的示例:

  • Nonce_Validator 那个doesn’t delete user data in a multisite.
  • Save_Post_Request_Validator 使用Nonce\\u验证器
  • Post_Data handler, 可能对于您的用例来说太复杂了,而且没有我想要的那么干净。:)
  • Metabox controller (仍然做得太多)

    视图类永远不应该知道什么时候必须显示什么内容(标题、描述、提交按钮)。它甚至不应该知道数据来自哪里。

    也许您想稍后将数据存储在用户元字段中,而不是存储在选项中?只需为PG_Data_Interface 在你的控制器中调用它,而不接触任何其他类。

SO网友:isNaN

您可以在构造函数中添加is\\u admin()函数来分隔逻辑。

/* php */
public function __construct() {
    if (is_admin()) {
        /* add actions for admins here */
        add_action( \'init\', array( $this, \'do_admin_stuff\' ) );
    } else {
        /* add actions for front-end here */
        add_action( \'init\', array( $this, \'do_front_end_stuff\' ) ); 
    }
}

结束

相关推荐

Loops in category description

我希望您能帮助我找到如何做我需要的事情:我有一些帖子,例如:文章标题:香蕉文章标题:橙色文章标题:Lemon文章标题:草莓所有这些文章都需要像这样的面包屑:首页>水果>\\35;标题#在“水果”类别页面中,我想创建如下内容:黄色水果(以及所有关于黄色水果的文章列表)橙色水果(以及所有关于橙色水果的文章列表)红色水果(以及所有关于红色水果的文章列表)要做到这一点,我认为在类别描述中,我应该手动编写标题(黄色水果、橙色水果、红色水果),并且在每个标题下,我应该放置一个循环,以放置所有具有特定标签的