Wordpress API submit post - php

I am an experienced PHP programmer, familiar with CURL and using it with cookie jar file, and also comfortable with JSON.
What I am not familiar with is WordPress 4.1.1, and my goal is simple: remotely call a WordPress site either natively or by a plugin (hopefully natively), and:
a) submit an article/post and hopefully
b) get a list of posts by user sorted by date as well (to compare).
From research so far I see you need to be logged in, and perhaps it is a 2-step process including getting a nonce and then submitting the post with the nonce. Can anyone tell me where to look under API documentation, or where to start?

You could use the XML-RPC API to do this, here is an simple example using curl which creates a new post using wp.newPost:
// initialize curl
$ch = curl_init();
// set url ie path to xmlrpc.php
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/xmlrpc.php");
// xmlrpc only supports post requests
curl_setopt($ch, CURLOPT_POST, true);
// return transfear
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// setup post data
$content = array(
'post_type' => 'post',
'post_content' => 'This is the post content',
'post_title' => 'This is the post title',
'post_status' => 'publish',
);
// parameters are blog_id, username, password and content
$params = array(1, '<user>', '<password>', $content);
$params = xmlrpc_encode_request('wp.newPost', $params);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
// execute the request
curl_exec($ch);
// shutdown curl
curl_close($ch);
To get a list of posts you may use wp.getPosts, although you cannot filter posts by author, you could loop through each post in the response and check if it should be displayed or not:
// filter used when retrieving posts
$filter = array(
'post_type' => 'post',
'post_status' => 'publish',
'number' => 50,
'offset' => 0,
'orderby' => 'post_title',
);
// fields to include in response
$fields = array(
'post_title',
'post_author',
'post_id',
'post_content',
);
$params = array(1, '<username>', '<password>', $filter, $fields);
$params = xmlrpc_encode_request('wp.getPosts', $params);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
// execute query
$response = curl_exec($ch);
// response is xml
$response = simplexml_load_string($response);
// walk over response and figure out if post should be displayed or not

I know enough about WP to know better than to use it.
But you do not need any of the stuff you are considering e.g. nonce, IXR, XML.
You write your own PHP script. I do not understand why you need a remote blog post tool when websites by their nature are remotely accessible. Like use a bookmark to your WP site.
I can see some possible uses for getting a list of posts.
Why would you need security to access posts that are there for the public to see?
Script on WP site:
header('Content-Type: text/plain; charset=utf-8');
$rows = 0;
$date = date('Y-m-d',strtotime($_GET['date'])) . '00:00:00';
$results=mysqli_query("SELECT`comment_post_ID`,`comment_date`,`comment_content`
FROM `wp_comments` WHERE `comment_date` > '$date'
ORDER BY `comment_post_ID` ASC,`comment_date` ASC);
while ($pats = mysqli_fetch_array($results, MYSQL_NUM)){
echo "$row[0]\t$row[1]\r\n";
}
echo "$rows\trows\n";
Access from Browser:
http://wp_site.com/script.php?date=m/d/y'
Script accessed from remote PHP script:
header('Content-Type: text/plain; charset=utf-8');
$data = file_get_contents('http://wp_site.com/script.php?date=m/d/y');
$fp = fopen('posts.csv');
fwrite($fp,$data);
fclose($fp);
echo $data
If you do not want to save a copy of data in file
header('Content-Type: text/plain; charset=utf-8');
echo file_get_contents('http://wp_site.com/script.php?date=m/d/y');

Related

Unable to get Healthline search results with PHP

I am trying to run a script that will search Healthline with a query string and determine if there are any search results, but I can't get the contents with the query string posting to the page. To search for something on their site, you go to https://www.healthline.com/search?q1=search+string.
Here is what I tried:
$healthline_url = 'https://www.healthline.com/search';
$search_string = 'ashwaganda';
$postdata = http_build_query(
array(
'q1' => $search_string
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$stream = stream_context_create($opts);
$theHtmlToParse = file_get_contents($healthline_url, false, $stream);
print_r($theHtmlToParse);
I also tried to just add the query string to the url and skip the stream, amongst other variations, but I'm running out of ideas. This also didn't work:
$healthline_url = 'https://www.healthline.com/search';
$search_string = 'ashwaganda';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: text/xml; charset=utf-8"
)
);
$stream = stream_context_create($opts);
$theHtmlToParse = file_get_contents($healthline_url.'&q1='.$search_string, false, $stream);
print_r($theHtmlToParse);
And suggestions?
EDIT: I changed the url in case someone wants to look at the search page. Also fixed the query string. Still doesn't work.
In response to Ken Lee, I did try the following cURL script that also just returns the page without search results:
$healthline_url = 'https://www.healthline.com/search?q1=ashwaganda';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $healthline_url);
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
Healthline does not load the search result directly. It has its search index stored in Algolia and made extra javascript calls to retrieve the result. Therefore you cannot see the search result by file_get_content.
To see the search result, you need to run a browser simulator that simulates a javascript-capable browser to properly run the site page.
For PHP developers, you may try using php-webdriver to control browers through webdriver (e.g. Selenium, Chrome + chromedriver, Firefox + geckodriver).
Update: Didn't know that the target site is Healthline. Updated the answer once I found out.

bp_core_signup_user hook not working (PHP, BuddyPress, Wordpress, & Parse.com)

I have been trying to hook into the WordPress registration action so that I can store the new user's account info on my Parse.com User database. However, since I am using BuddyPress, the WP hook user_register does not seem to work.
After doing research online, it seems like I am supposed to use the BP hook bp_core_signup_user, but that does not seem to be working, and all the info online on how it should be implemented are years old and may be outdated. Problematically, BuddyPress does not have a good Codex at all, so I am kind of stuck. I've been at this for hours, but cannot figure it out.
This is the function I created in an attempt to hook into the registration process:
<?php
// Saves the newly registered BP user account to the Parse DB.
add_action('bp_core_signup_user', 'saveNewParseUser', 10, 5);
function saveNewParseUser($userId, $userLogin, $userPass, $userEmail, $userMeta) {
//Commit new user data to an HTTP POST request to Parse.
$url = 'https://api.parse.com/1/users';
$postdata = array(
"wpUserId" => $userId,
"username" => $userLogin,
"password" => $userPass,
"email" => $userEmail,
"fullName" => $userMeta[display_name],
"firstName" => $userMeta[first_name],
"lastName" => $userMeta[last_name]
);
$appID = "a5TtlVG52JKTC************************";
$restAPIKey = "Qc86jA8dy1FpcB**************************";
$options = array();
$options[] = "Content-type: application/json";
$options[] = "X-Parse-Application-Id: $appID";
$options[] = "X-Parse-REST-API-Key: $restAPIKey";
$options[] = "X-Parse-Revocable-Session: 1";
//open connection
$ch = curl_init($url);
//sets the number of POST vars & POST data
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($postdata),
CURLOPT_HTTPHEADER => $options,
CURLOPT_RETURNTRANSFER => true
));
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
//Error check
if (curl_errno($ch)) {
echo "Error Code " . curl_errno() . ": " . curl_error($ch);
}
//Retrieve and place Parse user session token & ID into WP DB user account.
add_user_meta($userId, 'parseSessionToken', $resultArray[sessionToken]);
add_user_meta($userId, 'parseObjId', $resultArray[objectId]);
curl_close($ch);
}
What am I doing wrong? Is this not even being hooked and run as it is meant to?
I know it does not work because I check the Parse User DB after registering an account and a new row is not created, and the meta info I put into the WP account do not show there at all.
Interestingly, this DID work when I hooked into WP's user_register (with the appropriate parameter and postdata array setup) when I included an exit; call at the end of the function, which essentially prevented the registration process from going through BuddyPress' and its activation procedure, and instead went straight to registering through Wordpress directly. That also left the web page displaying the output response from the HTTP request - it was the JSON response body as expected from Parse, so I know it did in fact work. Why would it be working when avoiding BuddyPress? BuddyPress seems to be causing the problem here. (If you would like to see the code for what I had done differently for this, then I can post it.)
Thank you for any assistance.
I figured out what was wrong, and I feel like a complete idiot because it should have been obvious.
There is nothing wrong with my function - I just did not realize the custom plugin it is contained in was disabled! Apparently that happened when I renamed the PHP file, deleted the one on the server, and put the new one in, before my question became an issue.
I learned my lesson. And now I know that changing the plugin's files will deactivate the plugin as a whole.
As such, my hook to user_registration still works just fine, and it is not necessary to go through the bp_core_signup_user hook, so I have reverted to the former. For future reference for anyone wanting to know, this is my final function I used:
<?php
// Saves the newly registered WP user account to the Parse DB.
add_action('user_register', 'saveNewParseUser');
function saveNewParseUser($newUserId) {
//Retrieve the new User object from WP's DB.
$newUser = get_userdata($newUserId);
//Commit new user data to an HTTP POST request to Parse.
$url = 'https://api.parse.com/1/users';
$postdata = array(
"wpUserId" => $newUserId,
"username" => $newUser->user_login,
"password" => $newUser->user_pass,
"email" => $newUser->user_email,
"fullName" => $newUser->display_name,
"firstName" => $newUser->first_name,
"lastName" => $newUser->last_name
);
$appID = "a5TtlVG52JKTCbc*******************";
$restAPIKey = "Qc86jA8dy1F************************";
$options = array();
$options[] = "Content-type: application/json";
$options[] = "X-Parse-Application-Id: $appID";
$options[] = "X-Parse-REST-API-Key: $restAPIKey";
$options[] = "X-Parse-Revocable-Session: 1";
//open connection
$ch = curl_init($url);
//sets the number of POST vars & POST data
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($postdata),
CURLOPT_HTTPHEADER => $options,
CURLOPT_RETURNTRANSFER => true
));
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
//Error check
if (curl_errno($ch)) {
echo "Error Code " . curl_errno() . ": " . curl_error($ch);
}
//Retrieve and place Parse user session token & ID into WP DB user account.
add_user_meta($newUserId, 'parseSessionToken', $resultArray[sessionToken]);
add_user_meta($newUserId, 'parseObjId', $resultArray[objectId]);
curl_close($ch);
}

Posting to Tumblr with php & Tumblr API

I am trying to post messages automatically to my Tumblr Blog (which will run daily via Cron)
I am using the Official Tumblr PHP library here:
https://github.com/tumblr/tumblr.php
And using the Authentication method detailed here :
https://github.com/tumblr/tumblr.php/wiki/Authentication
(or parts of this, as I don't need user input!)
I have the below code
require_once('vendor/autoload.php');
// some variables that will be pretttty useful
$consumerKey = 'MY-CONSUMER-KEY';
$consumerSecret = 'MY-CONSUMER-SECRET';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$blogName = 'MY-BLOG-NAME';
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// start the old gal up
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
// get the oauth_token
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// set the token
$client->setToken($data['oauth_token'], $data['oauth_token_secret']);
// change the baseURL so that we can use the desired Methods
$client->getRequestHandler()->setBaseUrl('http://api.tumblr.com');
// build the $postData into an array
$postData = array('title' => 'test title', 'body' => 'test body');
// call the creatPost function to post the $postData
$client->createPost($blogName, $postData);
However, this gives me the following error:
Fatal error: Uncaught Tumblr\API\RequestException: [401]: Not
Authorized thrown in
/home///*/vendor/tumblr/tumblr/lib/Tumblr/API/Client.php
on line 426
I can retrieve blog posts and other data fine with (example):
echo '<pre>';
print_r( $client->getBlogPosts($blogName, $options = null) );
echo '</pre>';
So it seems it is just making a post that I cant manage.
In all honesty, I don't really understand the OAuth Authentication, so am using code that more worthy coders have kindly provided free :-)
I assume I am OK to have edited out parts of the https://github.com/tumblr/tumblr.php/wiki/Authentication as I don't need user input as this is just going to be code ran directly from my server (via Cron)
I have spent days looking around the internet for some answers (have gotten a little further), but am totally stuck on this one...
Any advice is much appreciated!
It looks like the parts that you removed in the code pertained to a portion of the OAuth process that was necessary for the desired action.
// exchange the verifier for the keys
You might try running the Authentication Example itself and removing the parts of the code that you've removed until it no longer works. This will narrow down what's causing the issue. I'm not very familiar with OAuth personally, but this looks as though it would be apart of the problem as one of the main portions you took out was surrounding the OAuth process exchanging the verifier for the OAuth keys.
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
https://howtodofor.com/how-to-delete-tumblr-account/

Post to wordpress via php

I'm trying to post on my wordpress site using php .
I used php to fetch data from a website and stored all of them in variables .
I found the code to a few auto wordpress php posters but they are kind of complex and i'm not really sure how to use/alter them.
What the simplest way to do it via php ?
My data are like :
$topic_name = "name";
$mainimage = "url/image":
$input = "hello................." ;
$category = "cars";
$tags = ("tag1","tag2","tag3"...);
Note : I just need the basic code to login to my wordpress and post some random text via php - I'm pretty sure i can figure out how to input the category , tags etc later on.
I'm trying to use this one as it seem simple but i don;t think it works for the latest version of wordpress (3.7.1 ) -
I am using xampp for hosting the site locally for now
If anyone can modify it or can share a working one , would be great .
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$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, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'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;
}
Do you really need to use XML-RPC? This is generally what you would want to do to post to a remote WordPress installation. For instance, from a completely different site, from a mobile app, etc.
It sounds like you are writing a plugin that will run within your WordPress installation. In that case you can just call wp_insert_post() directly.
A very trivial example from WordPress's wiki, which also has a complete list of parameters you can use:
// Create post object
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,39)
);
// Insert the post into the database
wp_insert_post( $my_post );

Send parameters to a URL and get output from that page

I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:
abc.php:
<?php
$id="123";
$name="blahblah";
//need to send the value to def.php & get value from that page
// echo $value=Print the "Value received" msg from def.php;
?>
def.php:
<?php
$id=$_GET['id'];
$name=$_GET['name'];
if(!is_null($id)&&!is_null($name))
{ echo "Value received";}
else{echo "Not ok";}
?>
Is there any kind heart who can help me solve the issue?
First make up your mind : do you want GET or POST parameters.
Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :
$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');
To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.
You can try without cURL (I havent tried though):
Copy pasted from : POSTing data without cURL extension
// Your POST data
$data = http_build_query(array(
'param1' => 'data1',
'param2' => 'data2'
));
// Create HTTP stream context
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
// Make POST request
$response = file_get_contents('http://example.com', false, $context);
Taken from the examples page of php.net:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com/abc.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
Edit: To send parameters
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( tch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));
use CURL or Zend_Http_Client.
<?php
$method = 'GET'; //change to 'POST' for post method
$url = 'http://localhost/browse/';
$data = array(
'manufacturer' => 'kraft',
'packaging_type' => 'bag'
);
if ($method == 'POST'){
//Make POST request
$data = http_build_query($data);
$context = stream_context_create(array(
'http' => array(
'method' => "$method",
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data)
)
);
$response = file_get_contents($url, false, $context);
}
else {
// Make GET request
$data = http_build_query($data, '', '&');
$response = file_get_contents($url."?".$data, false);
}
echo $response;
?>
get inspired by trix's answer, I decided to extend that code to cater for both GET and POST method.

Categories