【问题标题】:Front end only version of Init hook?仅前端版本的初始化钩子?
【发布时间】:2012-08-22 07:11:03
【问题描述】:

我正在尝试在我的主题中构建一个功能,该功能依赖于在发送标头之前执行的操作。所以我很自然地像这样挂入了 Init 钩子:

add_action('init', 'my_function');

但问题是我只希望 my_function 在用户不查看管理部分或登录页面时运行。

那么我可以使用什么钩子,它只是前端,但在发送标头之前运行。 Looking at the API reference,似乎没有,显然条件在运行时的早期不起作用。

所以除了搜索 /wp-admin/ 和 /wp-login/ 的 URL(这对我来说似乎很笨拙)之外,我无法弄清楚。

【问题讨论】:

    标签: wordpress conditional-statements


    【解决方案1】:

    我只针对前端(不是管理员)的解决方案也是检查引用者,因为有一些 ajax 调用直接指向非 /wp-admin url 序列,而 is_admin() 不固定。看来他正在看这条网址。

    // Skip for admin
    if ( is_admin() || ( $_SERVER['HTTP_REFERER'] && strpos( $_SERVER['HTTP_REFERER'], 'wp-admin' ) !== false ) ) {
        return;
    }
    

    【讨论】:

      【解决方案2】:

      这里有一些不错的解决方案,希望大家喜欢。

      function my_func(){
       if ( !is_admin())
       {
      
       // add code here for show only in front-end or create another function outside this block and call that function here.
       }
       else
       {
       // add code here for show only in admin or create another function outside this block and call that function here.
      }}add_action ('init', 'my_func');
      

      就是这样,使用并看到魔法。

      【讨论】:

      • is_admin() 对于 Ajax 请求也返回 true。例如,如果您在前端进行无限滚动,那么 is_admin() 将返回 true。
      【解决方案3】:

      if(!is_admin()){} 中封装你的动作的钩子和函数

      像这样:

      if(!is_admin()) {
        //Style
        add_action('init', 'style');
      
        function style()
        {
            wp_enqueue_style('style', THEMEROOT . '/css/your.css');
        }
      }
      

      【讨论】:

        【解决方案4】:

        这就是我的做法。使用 wp 操作挂钩已经足够晚了,可以提供对查询和条件的访问,但仍然发生在设置模板之前。

        <?php
        function my_function() {
            if ( ! is_admin() && ! is_login_page() ) {
                // Enqueue scripts, do theme magic, etc.
            }
        }
        
        add_action( 'wp', 'my_function' );
        
        function is_login_page() {
            return in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'));
        }
        

        编辑:我误解了标题的意思(我在想wp_head...最近主题编码太多了!)。我现在假设您正在尝试击败 send_headers 行动:

        function my_function() {
            if ( 'index.php' == $GLOBALS['pagenow'] ) {
                // Pre-header processing on the front-end
            }
        }
        
        add_action( 'wp_loaded', 'my_function' );
        

        它不是超级优雅,但至少它是简洁的。还有it seems likely it will continue to work,这总是好消息。

        【讨论】:

        • WP 在标头发送后被调用,所以它不适用于我想要做的事情。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 2020-09-24
        • 2020-06-07
        • 2020-04-24
        • 1970-01-01
        相关资源
        最近更新 更多