I am running my wordpress on localhost, My code retrieves photos from urls and using file_put_contents add them to the current directory, but I need it to add them to /wordpress/wp-content/uploads where wordpress save the manually uploaded files.
$Address = "www.xxx.com/" . $file;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$url = curl_exec($ch);
curl_close($ch);
$location = "/wordpress/wp-content/uploads/2013/a.jpg";
file_put_contents($location, file_get_contents($url));
if(! function_exists('wp_upload_dir'))
{
define('WP_USE_THEMES',false);
require 'wordpress/wp-load.php';
}
$upload_dir = wp_upload_dir();
echo $upload_dir['path'];
echo $upload_dir['url'];
echo $upload_dir['subdir'];
http://codex.wordpress.org/Function_Reference/wp_upload_bits
// the curl thing from question...results in `$url`
$upload = wp_upload_bits('a.jpg', null, file_get_contents($url));
echo $upload['file'], $upload['url'], $upload['error'];
I think I understand the problem.
This or any equivalent statement should be at the top of the file to load WP:
require_once("path/to/wp-load.php");
The path/to/ is relative and depends on the position of your file. If, for example, your file is located in a folder at wordpress/here, the path should be something like "../wp-load.php", but that's something you have to figure out.
Try displaying errors so you know what's going on, with a code like this one:
ini_set( 'display_errors', TRUE );
error_reporting( E_ALL );
Then, add this code:
$UploadDir = wp_upload_dir();
$UploadURL = $UploadDir['baseurl'];
$location = $UploadURL . "/2013/a.jpg";
Remove:
$location = "/wordpress/wp-content/uploads/2013/a.jpg"; and all code from:
if(! function_exists('wp_upload_dir')) {
down to the last line.
Insert echo statements in the appropriate places to see the results.
Related
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.
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();
I wants to add posts in Wordpress site using xml-rpc and curl OR any alternate method without logging in WP admin. Is this possible?
I got the answer and Following code is working for me.
function wpPostXMLRPC ($title,$body,$rpcurl,$username,$password,$category='Uncategorized',$keywords='',$encoding='UTF-8') {
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array (
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0,
'mt_allow_pings'=>0,
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array(
$category
)
);
$params = array(
0,
$username,
$password,
$content,
true
);
$request = xmlrpc_encode_request('metaWeblog.newPost', $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
$title = 'post-title';
$body = 'POST BODY WILL GOES HERE';
$rpcurl = 'http://example.com/xmlrpc.php';
$username = 'xxx';
$password = 'xxx';
$category = 'test';
$chk = wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8');
if($chk) {
echo $chk;
} else {
echo 'failed';
}
There is a built-in feature in Wordpress that allow you to publish an article via e-mail. Never tested it though, but it may suit your needs.
You can configure it in your site's admin, under settings > writing (URL is like http://yourwordpresssite.com/wp-admin/options-writing.php).
However, if you need an API, you'll find useful things in Wordpress Codex pages related to XML-RPC support and wp.newPost.
For a code sample, you can have a look at this snippet, which seems a good basis to me.
I am running wordpress on localhost, I can successfully save files into upload directory of wordpress using the following code, but wordpress does not show them in its media library, although it shows just those that I upload using its upload feature.
require("/Applications/MAMP/htdocs/wordpress/wp-load.php");
$Addr = "http://www.xxx.com" . $Addr;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, $Addr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
ini_set( 'display_errors', TRUE );
error_reporting( E_ALL );
$upload_dir = wp_upload_dir();
$location= $upload_dir['basedir']. "/" . "a.jpg";
file_put_contents($location, $output);
echo 'Photo is uploaded';
When I go to following address I can see the photos there.
http://localhost:8888/wordpress/wp-content/uploads/
I even copied a file manually but it does not show that one as well but when I upload the same file using wordpress itself the file will be shown.
Seems a permission problem, try set 644 with chmod:
file_put_contents($location, $output);
chmod($location, 0644); // <--- new code
I'm using curl to fill a form. After completion of the post the other script which handles the form is redirecting to another URL. I want to get this redirect URL into a variable.
Easy way to find the redirected url (if you don't want to know in advance)
$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
You would use
curl_setopt($CURL, CURLOPT_HEADER, TRUE);
And parse the headers for the location header
Here I get the resource http headers then I parse the headers out into an array $retVal. I got the code for parsing the headers from here (http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/) You could also use http://php.net/manual/en/function.http-parse-headers.php if you have (PECL pecl_http >= 0.10.0)
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
// Getting binary data
$header = curl_exec($ch);
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
//here is the header info parsed out
echo '<pre>';
print_r($retVal);
echo '</pre>';
//here is the redirect
if (isset($retVal['Location'])){
echo $retVal['Location'];
} else {
//keep in mind that if it is a direct link to the image the location header will be missing
echo $_GET[$urlKey];
}
curl_close($ch);
You may want to set the CURLOPT_FOLLOWLOCATION to true.
Or set the CURLOPT_HEADER to true and then use regexp to get the Location header.