I am trying to Post WordPress post URLs to My Twitter. I have created twitter CONSUMER KEY, CONSUMER SECRET KEY, Access Token, Access Token Secret (FREE plan).
Maybe getting connection error from client side (Twitter side).
My code:
require_once plugin_dir_path(__FILE__) . '/vendor/autoload.php';
use Abraham\\TwitterOAuth\\TwitterOAuth;
// I have a button, On its click this function is called to Post Hello world message to Twitter.
/* if (isset($_POST['start_auto_tweet'])) {
TweetPost();
}
*/
function TweetPost() {
define('CONSUMER_KEY', 'xxxxxxxxxxxxxxxxxxxx');
define('CONSUMER_SECRET', 'xxxxxxxxxxxxxxxxxxxx');
define('ACCESS_TOKEN', 'xxxxxxxxxxxxxxxxxxxx');
define('ACCESS_TOKEN_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxx');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$content = $connection->get("account/verify_credentials");
if ($connection->getLastHttpCode() == 200) {
echo '\nRequest successful. getLastHttpCode Content equal to 200: ';
} else {
echo 'Error in getLastHttpCode';
}
$tweet = $connection->post('statuses/update', array('status' => 'Hi'));
if ($tweet) {
echo 'Success: Your message Hi has been posted to Twitter.';
} else {
echo "\nError: Could not post the Hi message to Twitter. $tweet\n";
}
}
I am receiving:
"Error in getLastHttpCode" and "Error: Could not post the Hi message to Twitter" .
Please someone help me to fix this, I have used https://twitteroauth.com/ (Composer via CMD to import TwitterOAuth library in plugin folder).
It should Post "Hi" message to my twitter profile. later, I want to post WordPress Post URLs automatically via WordPress cron.
For starters you are checking if $tweet exists and then trying to echo it if it doesn't. It is hard to troubleshoot when your error output is just your string you put there. I would recommend trying to get more information both about your request and the response to figure out where the problem begins. You could try and use the
error_log()function to write these out for you to examine. Maybe something like :And also for the response
now see if there is anything useful in your php/error.log or wherever you have that configured, should be able to find it in your php.ini for error_log.
It might also be useful to first try and figure out how to form the request so it is accepted in something like Postman, maybe will help you troubleshoot and get better error messages.