Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a custom function to be accessible throughout WordPress

I have this notification function and need to call it in different places of the code. I need to put it some where which be accessed by any files inside my child theme as well as in the plugins directory.

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;
}
  • First question, Where to put it, currently it is in functions.php?
  • Second question, how to call it in different places?

Any solution and reference would be appreciated. Thank you.

like image 907
Naser Nikzad Avatar asked Jul 30 '18 04:07

Naser Nikzad


Video Answer


3 Answers

Since you've got a function with a broad scope, consider giving it a more unique name to prevent naming conflicts, such as naser_send_notitification() instead of just send_notification, or if you can - consider using a namespace or class.

Now to answer your question, functions.php is actually usually a safe bet for "broad scope" functions that need to be accessible just about anywhere. If you look at the Action Reference you'll see that after_setup_theme is fired relatively early-on, allowing your function to be accessible from that hook or later - since it will be available during this moment. However, it does come after plugins_loaded, so if you need it before then, you'll need to turn it into a plugin with a File Header or an "MU Plugin".

If you need it be accessible at effectively the earliest momement, consider putting it in a file in /wp-content/mu-plugins/ and give it a name, even something like custom-functions.php. These files are called Must-Use Plugins. Files in this directory are always loaded, and always run before anything else, so functions declared in them are accessible incredibly early. This is typically where I put code I need to make sure is theme independent, is always on and can't be deactivated.

So effectively:

1) Rename your function to something a bit more unique, like naser_send_notitification()

2) Put this code in /wp-content/mu-plugins/custom-funtions.php

3) Now you should be able to call naser_send_notification( $tokens, $message ) in any function or hook that comes after the muplugins_loaded hook (which is just about anywhere)

like image 54
Xhynk Avatar answered Oct 20 '22 22:10

Xhynk


Here is the Solution: every thing is commented on each line

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)

then Hook everywhere you need

    $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);

that's it.

like image 26
Khalil DaNish Avatar answered Oct 20 '22 22:10

Khalil DaNish


I believe wordpress shortcodes would be the best approach to handle this. Because messing with wordpress core files is not good practice and leads to several issues like code removal on upgrade etc.

There are several benefits of shortcodes and for your specific problem it would be beneficial because:

  • can be placed in parent/child themes functions.php
  • can be accessible in php code files and in dashboard editor as well

Complete Code: (just place inside 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');

Call it anywhere in theme or plugin: (like this)

  1. wordpress editor:

    [send-notification token=XXXX message="hello"]
    
  2. theme/plugin files:

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

Useful Resources:

  1. WordPress Shortcode with Parameters
  2. A tutorial on Wordpress Shortcodes
  3. Creating Shortcode with different type of parameters
like image 2
Atlas_Gondal Avatar answered Oct 20 '22 23:10

Atlas_Gondal