【问题标题】:Need a custom function to be accessible throughout WordPress需要一个可在整个 WordPress 中访问的自定义函数
【发布时间】:2019-01-06 06:50:04
【问题描述】:

我有这个通知功能,需要在代码的不同地方调用。我需要把它放在我的子主题以及插件目录中的任何文件都可以访问的地方。

function send_notification($tokens, $message)
{
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array(
         'registration_ids' => $tokens,
         'data' => $message
        );
    $headers = array(
        'Authorization:key = My_Token',
        'Content-Type: application/json'
        );

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
   $result = curl_exec($ch);           
   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
   }
   curl_close($ch);

   return $result;
}
  • 第一个问题,放在哪里,目前在functions.php中?
  • 第二个问题,不同地方怎么称呼?

任何解决方案和参考将不胜感激。谢谢。

【问题讨论】:

    标签: wordpress function notifications call


    【解决方案1】:

    由于您有一个范围广泛的函数,请考虑给它一个更独特的名称以防止命名冲突,例如 naser_send_notitification() 而不仅仅是 send_notification,或者如果可以 - 考虑使用 namespaceclass

    现在回答您的问题,functions.php 实际上对于需要在任何地方都可以访问的“广泛范围”功能通常是一个安全的选择。如果您查看Action Reference,您会看到after_setup_theme 相对较早地被触发,从而允许您的函数可以从该钩子或更晚的时间访问——因为它在此时可用。但是,它确实出现在plugins_loaded 之后,因此如果您在此之前需要它,则需要将其转换为带有File Header 或“MU 插件”的插件。

    如果您需要在最早的时候有效地访问它,请考虑将其放入 /wp-content/mu-plugins/ 的文件中并为其命名,甚至可以使用 custom-functions.php 之类的名称。这些文件称为Must-Use Plugins。此目录中的文件总是被加载,并且总是在其他任何东西之前运行,因此在其中声明的函数可以非常早地访问。这通常是我放置代码的地方,我需要确保独立于主题、始终开启且无法停用。

    如此有效:

    1) 将您的函数重命名为更独特的名称,例如 naser_send_notitification()

    2) 将此代码放入/wp-content/mu-plugins/custom-funtions.php

    3) 现在您应该可以在 muplugins_loaded 挂钩之后的任何函数或挂钩中调用 naser_send_notification( $tokens, $message )(几乎在任何地方)

    【讨论】:

      【解决方案2】:

      解决方法如下: 每一行都有注释

      function do_something( $a = "", $b = "" ) { // create your function
          echo '<code>';
              print_r( $a ); // `print_r` the array data inside the 1st argument
          echo '</code>';
      
          echo '<br />'.$b; // echo linebreak and value of 2nd argument
      }
      
      add_action( 'danish', 'do_something', 10, 2 ); 
      // create your own action with params('action name', 'callback funtion', priority, num_of params)
      

      然后钩住你需要的任何地方

          $a = array(
          'eye patch'  => 'yes',
          'parrot'     => true,
          'wooden leg' => 1
      );
      $b = __( 'And Hook said: "I ate ice cream with Peter Pan."', 'textdomain' ); 
      
      // Executes the action hook named 'danish'
      
      do_action('danish', $a, $b);
      

      就是这样。

      【讨论】:

        【解决方案3】:

        我相信wordpress shortcodes 将是处理此问题的最佳方法。因为弄乱 wordpress 核心文件并不是一个好的做法,并且会导致一些问题,例如升级时删除代码等。

        短代码有几个好处,对于您的具体问题,这将是有益的,因为:

        • 可以放在父/子主题functions.php
        • 可以在 php 代码文件和仪表板编辑器中访问

        完整代码:(只需放入functions.php

        function send_notification( $atts )
        {
        
          extract(shortcode_atts(array(
            "tokens" => '',
            "message" => ''
          ), $atts));
        
          $url = 'https://fcm.googleapis.com/fcm/send';
          $fields = array(
            'registration_ids' => $tokens,
            'data' => $message
          );
          $headers = array(
            'Authorization:key = My_Token',
            'Content-Type: application/json'
          );
        
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
          $result = curl_exec($ch);
          if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
          }
          curl_close($ch);
        
          return $result;
        
        }
        
        add_shortcode('send-notification', 'send_notification');
        

        在主题或插件的任何地方调用它:(像这样)

        1. wordpress 编辑器:

          [send-notification token=XXXX message="hello"]
          
        2. 主题/插件文件:

          <?php echo do_shortcode('[send-notification token=XXXX message="hello"]'); ?>
          

        有用的资源:

        1. WordPress Shortcode with Parameters
        2. Wordpress 简码上的tutorial
        3. Creating Shortcode 不同类型的参数

        【讨论】:

          【解决方案4】:

          根据this question :
          第 1 步:将函数写入插件内的类
          第 2 步:在您的主题中创建该类的对象
          第 3 步:通过该对象访问您的函数。

          // inside your plugin 
          class foo {
                public function send_notification() {
                      return "whatever you want";
             }
          }
          
          // inside your themes functions.php
          $foo_object = new foo();
          
          // use the object to access your function:
          $foo_object->send_notification();
          

          【讨论】:

            猜你喜欢
            • 2014-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-28
            • 2019-04-21
            相关资源
            最近更新 更多