Get reach estimate with PHP API - facebook-php-sdk

I spent hours trying to get reach estimate using PHP SDK. The problem I am having is simply not knowing how to use function "getReachEstimate(.., ..)" It is not explained anywhere in a way that I would be able to understand.
If someone could give me a code example of using this function would be great, or any other way of geting reach estimate using PHP.

The same GET request through the SDK
$response = $api->call(
"/".$ad_account_id."/reachestimate",
RequestInterface::METHOD_GET,
array(
'targeting_spec' => json_encode($targeting),
'currency' => 'USD'
)
);
return $response->getContent();
Where $ad_account_id looks like act_XXXXXXX

I have searched for documentation on the exact function and there is no documentation on that function anywhere although I was able to find the actual function in the SDK. I ended up writing a curl call. I am using the targeting specs for a campaign to query it. Here is the call.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.4/$ad_account_id/reachestimate" .
'?access_token=' . $accessToken . '&' .
'targeting_spec=' . urlencode(json_encode($targeting)) . '&' .
'currency=' . 'USD'
);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

Related

How to save "text" from Twitter JSON data to a ACF field?

I need help with my code. What it's suppose to do is a user enter the full URL from twitter into a text field ('https://twitter.com/openbayou/status/1487977976033685506') and when the post is saved, it breaks down the url by using explode and then gets data from a tweet via Twitter API v2.
My code:
$tweet_url_raw = get_field('twitter_url');
$parts = explode('/', $tweet_url_raw);
$url = 'https://api.twitter.com/2/tweets/' . $parts[5] . '?expansions=author_id&tweet.fields=created_at&user.fields=username,verified';
$authorization = 'Authorization: Bearer ' . get_field_object('twitter_bearer_token', 'option')['value'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
$tweet_data = json_encode($result);
$tweet_data2 = json_decode($tweet_data);
The code above does get the data:
{"data":{"text":"SEC Super Bowl!!","created_at":"2022-01-31T02:36:09.000Z","author_id":"1471331","id":"1487977976033685506"},"includes":{"users":[{"name":"OpenBayou","verified":false,"id":"1471331","username":"openbayou"}]}}
The problem I'm having is when I'm trying to get individual data from the output. I'm trying to update a text field called tweet with the text from text. I've tried to use update_field('tweet', $tweet_data2->data, $post_id); and it was blank. When I use update_field('tweet2', $tweet_data2["data"], $post_id); all it saves is {
Any idea what I'm doing wrong?
You are almost there.
Since you omitted the associative parameter for json_decode, it defaults to false so you get an object, not an array. You then need to reference it as such:
$tweet_data2 = json_decode($tweet_data);
echo 'Tweet text: ' . $tweet_data2->data->text;
If you prefer to work with arrays, simply pass true to json_decode:
$tweet_data2 = json_decode($tweet_data, true);
echo 'Tweet text: ' . $tweet_data2['data']['text'];
More info on json_decode can be found at the PHP Manual site:
https://www.php.net/manual/en/function.json-decode.php

Sending Order Details From WooCommerce To External System Over API

I am trying to send woocommerce order to netsuite via an external api I have written. I am nw to woocommerce and do not fully get how to add this functionality.
I have added the following code to the functions.php file in public_html/wp-content/themes/reverie-master/
add_action( 'woocommerce_payment_complete'', 'wdm_send_order_to_ext');
function wdm_send_order_to_ext( $order_id ){
// get order object and order details
$order = new WC_Order( $order_id );
$email = $order->billing_email;
$phone = $order->billing_phone;
//Create the data object
$orderData = array(
'customer_email' => $email,
'customer_phone' => $phone
);
$apiData = array(
'caller' => 'woocommerce',
'json' => $orderData,
'key' => 'MY_SECRET_KEY'
);
$jsonData =json_encode($orderData);
$url = "";
$api_mode = 'sandbox';
if($api_mode == 'sandbox'){
// sandbox URL example
$url = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=XXX&deploy=X&compid=XXXXXXX_SB1&h=XXXXXXXXXXXXXXXX";
}
else{
// production URL example
$url = "";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
// the handle response
if (strpos($response,'ERROR') !== false) {
print_r($response);
} else {
// success
}
}
I have tested the brunt of this code, just the parts that do not concern woocommerce in a different site and I can see the data showing up in NetSuite. However, when I go through my store and place an order, and take payment, I do not see the data come into NetSuite. Do I have this code in the right location? Is there something I am missing?
Update
I installed the plugin Code Snippets and added the code there instead. Set it to Run snippet everywhere. Still no luck.
Looks like you have a double quote on the first link
change
add_action( 'woocommerce_payment_complete'', 'wdm_send_order_to_ext');
to
add_action( 'woocommerce_payment_complete', 'wdm_send_order_to_ext');
Rather than use curl - you can always use the build in WordPress wp_remote_post() function
Also make sure you have WP_DEBUG set to true in wp-config.php while testing.

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.
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)
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.
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)
wordpress editor:
[send-notification token=XXXX message="hello"]
theme/plugin files:
<?php echo do_shortcode('[send-notification token=XXXX message="hello"]'); ?>
Useful Resources:
WordPress Shortcode with Parameters
A tutorial on Wordpress Shortcodes
Creating Shortcode with different type of parameters
According to this question :
step 1: write your function into a class inside your plugin
step 2: create an object of that class into your theme
step 3: access your function by that object.
// 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();

How to get title of all pages with WP Rest API

I need to get only title of all Pages of my wordpress site with WP Handbook API. I use this function in php to get all pages, but I need only the title. How do I do to manipolate the result data?
function getHomePage($link){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $link . '/wp-json/wp/v2/pages');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$pagine = curl_exec($ch);
curl_close($ch);
echo $pagine;
}
In reality I need to get the content of only homepage. How do I do that?
Sorry for my bad english, but I'm Italian.

how to call instagram api in wordpress plugin

I want to call instagram api in callback function but when i try to do it an error occured. "Headers alreay sent". I have registered my application on instagram developer. This is very basic thing but i'm new with api.
function insta_plugin_menu(){
add_menu_page( 'insta', 'Insta', 'manage_options', 'insta_slug', 'insta_callback_function','dashicons-admin-users',3 );
}
add_action('admin_menu','insta_plugin_menu');
function insta_callback_function(){
wp_redirect("https://api.instagram.com/oauth/authorize/?client_id=af450e026f99441abf0d4dab66daf84c&redirect_uri=http://wsiserver.website/shahbaz/wordpress/wp-admin/admin.php?page=insta_slug&response_type=code");
}
If you want to call instagram API then wp_redirect() is probably not the best way to do. That function is used to redirect not for calling any api.
You are getting the error may be because of various reasons.
You have to use wp_redirect() before get_header() Then it will not show header error.
you're sending data to the browser before calling wp_redirect()
But ; You should try
function insta_plugin_menu(){
add_menu_page( 'insta', 'Insta', 'manage_options', 'insta_slug', 'insta_callback_function','dashicons-admin-users',3 );
}
add_action('admin_menu','insta_plugin_menu');
function insta_callback_function(){
$url="https://api.instagram.com/oauth/authorize/?client_id=af450e026f99441abf0d4dab66daf84c&redirect_uri=http://wsiserver.website/shahbaz/wordpress/wp-admin/admin.php?page=insta_slug&response_type=code";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
curl_error($ch);
curl_close($ch);
$result = json_decode($result);
}

Resources