Post to wordpress via php - 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 );

Related

Schedule php wordpress script to run in background

I hope I am not expecting too much. Any help would be extremely useful for me, because I am stuck for days now.
I created a relatively simple wordpress plugin in php.
What is the plugin supposed to do ?
-The plugin is supposed to communicate with external api and import product data in json file.
Import is started by pressing "start import" button that is created by pluin in the wordpress menu - import products.
Example request:
curl -X GET
-H 'X-Api-Key: [api-key]'
https://example.com/products/[PRODUCT ID]
[PRODUCT ID] is supposed to range from 1 to 10000
Plugin receives json file with product feed for every single request - every single [PRODUCT ID]
Plugin creates a woocommerce product and attaches imported information.
Does the plugin work ?
Yes and no, It imports first 100 products (in about 1min) correctly and then it just stops, sometimes resulting in error related to the request taking too much time to finish.
I know that the plugin doesn't work because the import script is executed in the browser and gets timed out.
I also know that I should do this process in the background, split it into batches and queue execution. The thing is I tried many ways to do so but failed miserably.
I have composer and action scheduler installed.
Unfortunately everytime I try to split this into batches, use action scheduler It just doesn't work or imports first product and stops.
I know that I'm dealing with large amount of products, I don't have error handling, checking if imported product exists etc, but I really have to run this import once
so there is no need to make this plugin very refined. This has to run, import products and I can get rid of it.
I do have wp debug on, so my attepmts on using action scheduler didn't create any errors or fatal errors, but it just didn't work properly.
I have 1500MB Ram available, this is shared hosting server, I/O 1MB, 60 available processes, 88000/600000 Inodes used, 5/200GB disc space used.
I increased php maxExecutionTime to 3000, memorylimit 1536M, maxInputTime 3000, but that didn't change anything.
I'm attaching my working code below. This is the version without my poor attemts on using action scheduler, splitting it into batches and running it in the backgroud.
I feel like this is going to be easier to read.
This code below runs in the web browser and works, but gets timed out.
I will be extremely grateful for any help with running it in the background.
Is it possible to just run this script from SSH linux terminal so it doesn't get timed out ?
`
<?php
/**
* Plugin Name: Product Importer
* Description: Imports products from an external API
* Version: 1.0
* Author: me
* Author URI: http://www.example.com
*/
// Include the Autoscheduler library
require_once '/home/user/vendor/woocommerce/action-scheduler/action-scheduler.php';
add_action('admin_menu', 'add_import_button');
function add_import_button() {
add_menu_page('Import Products', 'Import Products', 'manage_options', 'import_products', 'import_products_page');
}
function import_products_page() {
echo '<h1>Import Products</h1>';
echo '<form method="post">';
echo '<input type="submit" name="start_import" value="Start Import">';
echo '</form>';
if (isset($_POST['start_import'])) {
import_function();
}
}
function import_function() {
$product_id = 1;
while($product_id < 10000){
$product_id++;
$api_key = 'my-api-key';
$headers = array(
'X-Api-Key: ' . $api_key,
);
$url = 'https://example.com/products/';
$product_url = $url . $product_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $product_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$product_data = json_decode($response, true);
// post array etc
// Set other product data as required.
}
}
}
`
One of the ways to solve this issue is using recursion where the code can run in the background. Take a look at the example below
require_once '/home/user/vendor/woocommerce/action-scheduler/action-scheduler.php';
add_action('admin_menu', 'add_import_button');
function add_import_button() {
add_menu_page('Import Products', 'Import Products', 'manage_options', 'import_products', 'import_products_page');
}
function import_products_page() {
echo '<h1>Import Products</h1>';
echo '<form method="post">';
echo '<input type="hidden" name="product_id" value="1">'; // optional
echo '<input type="submit" name="start_import" value="Start Import">';
echo '</form>';
if (isset($_POST['start_import'])) {
import_function();
}
}
// AJAX function
add_action( 'wp_ajax_nopriv_import_function', 'import_function' );
add_action( 'wp_ajax_import_function', 'import_function' );
function import_function() {
$product_id = ( ! empty( $_POST['product_id'] ) ) ? $_POST['product_id'] : 1;
$url = 'https://example.com/products/';
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
'X-Api-Key' => 'apikey12345'
)
);
// this call the function and return the body
$results = wp_remote_retrieve_body(wp_remote_get($url . $product_id, $args));
// convert to array
$results = json_decode( $results );
// Stop the code execution on this conditions
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
// Do your product creation here...
$product_id++; // increase $product_id
wp_remote_post( admin_url('admin-ajax.php?action=import_function'), [
'blocking' => false, // needed for the script to continue running on the background
'sslverify' => false, // needed if working on localhost.
'body' => [
'product_id' => $product_id
]
] );
}
OK, I managed to get it to work. I assume that it's dumb way to do this, but since it works it's fine for me. The only thing that is problematic now is the fact that the code for image import that I used previously (when code ran in browser) now makes the plugin stuck. Without it it works great and fast. Here is my current code:
<?php
/**
* Plugin Name: Product Importer
* Description: Imports products from an external API
* Version: 3.0
* Author: me
* Author URI: http://www.example.com
*/
register_activation_hook( __FILE__, 'schedule_import' ); //plugin starts when activated, fine for me
function schedule_import() {
wp_schedule_single_event( time(), 'import_products' );
}
add_action( 'import_products', 'import_function' );
function import_function() {
$batch_size = 50; //when split into batches it worked faster than one products after another, so ok
$batch_delay = 60; //give it some time to finish batch, to avoid problems
$last_imported_product_id = get_option( 'last_imported_product_id', 1 ); //need it for incrementation and rescheduling
$api_key = 'apikey123456789';
$headers = array(
'X-Api-Key: ' . $api_key,
);
$url = 'https://example.com/products/';
for ( $i = 0; $i < $batch_size; $i++ ) {
$product_id = $last_imported_product_id + $i;
$product_url = $url . $product_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $product_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$product_data = json_decode($response, true);
$post = array(
'post_title' => $product_data['name'],
'post_content' => $product_data['description'],
'post_status' => 'publish',
'post_type' => 'product',
'meta_input' => array(
'_virtual' => 'yes',
'_regular_price' => $product_data['price'],
),
);
$post_id = wp_insert_post($post);
update_post_meta($post_id, '_sku', $product_data['Id']);
wp_set_object_terms($post_id, 'external', 'product_type');
$external_url = 'https://example.external.url';
update_post_meta( $post_id, '_product_url', $external_url );
update_option( 'last_imported_product_id', $product_id + 1 ); //incrementation of product_id for rescheduling
wp_schedule_single_event( time() + $batch_delay, 'import_products' ); //rescheduling
}
}
This above works well. However when I add my old code for image imports it imports nothing or 1 product (without image lol) and becomes stuck. After a minute it imports the same product over and over again. Old code for image import:
// Get the product images
$images = $product_data['images']['screenshots'];
$image_ids = [];
foreach ($images as $image) {
// Download the image
$image_url = $image['url'];
$response = wp_remote_get($image_url);
if (is_array($response)) {
$image_data = $response['body'];
$filename = basename($image_url);
$file_array = array(
'name' => $filename,
'tmp_name' => download_url($image_url),
);
// Insert the image into the media library
$attach_id = media_handle_sideload($file_array, $post_id);
if (!is_wp_error($attach_id)) {
array_push($image_ids, $attach_id);
}
}
// Set the product image gallery
update_post_meta($post_id, '_product_image_gallery', implode(',', $image_ids));
// Set the product featured image
update_post_meta($post_id, '_thumbnail_id', $image_ids[0]);
And no, I don't put it after rescheduling, but after $post array.
Honestly no idea why it would crash, tried smaller batches, longer wait between batches etc. I assume the code for images import is just very poorly written. Any solutions for this problem are going to be very appreciated ! :)
PS: I am totally fine with importing the first image available (there is around 6) and setting it up as thumbnail for product. I can give up on the gallery since It's going to slow down the process anyway.
EDIT: here is the fragment of json file received from api. (for better context of importing images):
"images":{
"screenshots":[
{
"url":"https://example.jpg",
"thumbnail":"https://example.jpg"
},
{
"url":"https://example.jpg",
"thumbnail":"https://example.jpg"
},
{
"url":"https://example.jpg",
"thumbnail":"https://example.jpg"
etc....

Scrape business listing content from google search

I am developing a simple PHP app which takes
business name,
business address
and business phone from user and then checks if that business is listed in Google or not and
Also compares the business name, address and phone returned by Google against the search terms.
The result I want to display whether the information found in Google is accurate or whether something is different or missing. Something similar as this site does
What I have tried:
I have tried to scrape page with phpQuery library but it does not include that part(which is circled in image below).
$buss_name = $_GET['business_name'];
$link = "https://www.google.com/search?q=" . urlencode($buss_name) . "&rct=j";
$resp_html = file_get_contents($link, false);
$resp_html = phpQuery::newDocumentHTML($resp_html);
echo $resp_html;
echo pq("div.kno-ecr-pt.kno-fb-ctx._hdf",$resp_html)->text();
Reason is that it is loaded via some sort of AJAX call.
I also tried this web service by google
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=don%20jayne%20&%20assoc
But this also do not include that part I require.
Long story short >>>
Please tell me is there any API or whatever is available which checks for a business listed on Google or not?
probably you wont need this anymore but I will reply your post just for future reference.
One of the ways to check if a business is on google or not, is to check the google places api (documentation). You can preform a search and then check the results for the business you are looking for. Something like this:
$params = array(
'query' => 'mindseo',
'key' => "XXXXXXXXXXXXXXXXXXX");
$service_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
//do the request
$placesSearch = request( $service_url, $params );
//print the result
print_r($placesSearch);
//loop the results
if ( count( $placesSearch['results'] ) >= 1 ) {
$params = array(
'placeid' => $placesSearch['results'][0]['place_id'],
'key' => "AIzaSyAc73-uGCLLIuN3Bb2idOwRbLBzoaTmPHI");
$service_url = 'https://maps.googleapis.com/maps/api/place/details/json';
$placeData = request( $service_url, $params );
//echo the place data
echo '//Place ID#'.$params['placeid'].' DATA -----------------------';
print_r($placeData);
}
//function to make the request
function request( $googleApiUrl, $params) {
$dataOut = array();
$url = $googleApiUrl . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$dataOut = json_decode(curl_exec($ch), true);
curl_close($ch);
return $dataOut;
}

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

Wordpress API submit post

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

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/

Categories