How to use WordPress REST API to post article? I can edit post using the following PHP code, i'm using the Basic Authentication.
require( dirname(__FILE__) . '/wp-load.php' );
$headers = array (
'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);
// Edit post
$url = rest_url( 'wp/v2/posts/1' );
$data = array(
'title' => 'Test API Edit'
);
$response = wp_remote_post( $url, array (
'method' => 'POST',
'headers' => $headers,
'body' => $data
) );
print_r($response);
But I can not post new article
<?php
require( dirname(__FILE__) . '/wp-load.php' );
$headers = array (
'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);
// post new article
$url = rest_url( 'wp/v2/create_post/' );
$data = array(
'title' => 'Post from API',
'content' => 'test contents'
);
$response = wp_remote_post( $url, array (
'method' => 'POST',
'headers' => $headers,
'body' => $data
) );
print_r($response);
The return is always No route was found matching the URL and request method
Any suggestions?
It looks like you are using the wrong endpoint for POSTing to the REST API. As mentioned here the endpoint for creating new posts is:
/wp/v2/posts
Hope this solves your problem!
Related
I am trying to build a plugin that sends webhooks to an external site from client sites so I can keep a record of everything that happens from when a user signs in, to when someone installs a new plugin or updates or adds new pages etc.
The problem is I am receiving NULL values through the $api array, and can't seem to figure it out.
This is my last attempt and making this work:
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$installed_plugins = get_plugins();
$installed_plugins = array_keys( $installed_plugins );
$new_plugin = false;
$new_plugin_name = '';
$new_plugin_version = '';
foreach ( $installed_plugins as $installed_plugin ) {
if ( ! in_array( $installed_plugin, $package ) ) {
$new_plugin = $installed_plugin;
break;
}
}
if ( $new_plugin ) {
$new_plugin_data = get_plugins( '/' . $new_plugin );
$new_plugin_name = $new_plugin_data[ $new_plugin ]['Name'];
$new_plugin_version = $new_plugin_data[ $new_plugin ]['Version'];
}
$body = array(
'plugin_name' => $new_plugin_name,
'plugin_version' => $new_plugin_version
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
The JSON that is being received is:
{
"plugin_name": null,
"plugin_version": null
}
The Warnings I'm getting are this:
PHP Warning: Undefined array key "advanced-custom-fields-pro/acf.php" in C:\xampp\htdocs\site\wp-content\plugins\webhook-sender\plugin-update.php on line 25
PHP Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\site\wp-content\plugins\webhook-sender\plugin-update.php on line 25
Previous Versions of the code that also failed:
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$body = array(
'plugin_name' => $api['name'],
'plugin_version' => $api['version']
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
I thought by accessing $api array directly might work, but still getting NULL values on the return.
and...
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$body = array(
'plugin_name' => $api->name,
'plugin_version' => $api->version
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
function diwp_services_custom_post_type()
{
$labels = array(
'name' => 'Services',
'singular_name' => 'Service',
'add_new' => 'Add Service',
'add_new_item' => 'Enter Service Details',
'all_items' => 'All Services',
'featured_image' => 'Add Service Image',
'set_featured_image' => 'Set Service Image',
'remove_featured_image' => 'Remove Service Image'
);
// Set Options for this custom post type;
$args = array(
'public' => true,
'label' => 'Services',
'labels' => $labels,
'description' => 'Services is a collection of services and their info',
'menu_icon' => 'dashicons-hammer',
'supports' => array('title', 'editor', 'thumbnail'),
'capability_type' => 'page',
);
register_post_type('services', $args);
}
add_action('init', 'diwp_services_custom_post_type');
// >> Create Shortcode to Display Services Post Types
function diwp_create_shortcode_services_post_type()
{
$args = array(
'post_type' => 'services',
'posts_per_page' => '10',
'publish_status' => 'published',
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
$result .= '<div class="card">';
$result .= '<div class="card-block block-1">';
$result .= ' <h3 class="card-title">' . get_the_title() . '</div>';
$result .= ' <p class="card-text">' . get_the_content() . '</div>';
$result .= '</div>';
$result .= '</div>';
endwhile;
wp_reset_postdata();
endif;
return $result;
}
add_shortcode('services-list', 'diwp_create_shortcode_services_post_type');
// shortcode code ends here
I visited below link and implemented same as that but find no results
DIVEIN WP
Here is the screenshot as I am working on localhost
Any help regarding this will be appreciatable.
Thanks
First, you must fetch permalink from Setting >> permalink, and click Save changes
Seconds, Now you must add do_shortcode on the position you need to show all post from custom post type like :
echo do_shortcode('[services-list]');
I test your code in my end and work good https://abukotsh.me/wp/services/test-service/
Scroll down and you see test services
When doing
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
The response is
)]}'
["uvresp","03AJpayVHarkP_b40i5...stuff...VOrIy6m3ws",1,120]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The )]}' breaks things. I have no idea where that is coming from.
$g_recaptcha_response looks fine to me (what I am sending to google to verify).
The function to verify recaptcha
function verify_recaptcha ($g_recaptcha_response, $remote_address) {
# Verify captcha
$post_data = http_build_query(
array(
'secret' => 'secret',
'response' => $g_recaptcha_response,
'remoteip' => $remote_address
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
return $result->success;
}
Thanks.
Ok my bad. The above code works, I had a problem further downstream (query was trying to use a column that did not exist).
I'm encoding in JSON a bunch of data from a WP Query:
$args = array(
'posts_per_page' => 20,
'post_type' => 'post',
'category' => 6,
'meta_key' => 'custom_total_hits',
'tag' => 'indie-pop',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array(
'after' => date('Y-m-d', strtotime('-40 days'))
)
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
$output[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'count' => $post->custom_total_hits,
'soundcloud_url' => $post->soundcloud_song,
'soundcloud_id' => $post->soundcloud_ids,
'link' => get_permalink($post),
);
}
echo json_encode($output);
I would like to display in my JSON a key corrisponding to the src of the medium size of the attached image. If I use 'images' => get_attached_media('image', $post->ID) it retrives an array of multiple data which I can not access since I don't know the ID of the attached image when I process the data of my JSON. How can I do to retrieve a first level key - value where the value is the src of the attached image?
get_post_thumbnail_id : Get post thumbnail ID
wp_get_attachment_url : Get attachment URL by attachment id
'images' => parse_url( wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) ) );
Would you please try above code?
Try this solution:
$images = array();
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
foreach (get_intermediate_image_sizes() as $size) {
$images[$size] = wp_get_attachment_image_src($post_thumbnail_id, $size);
}
//end
'images' => $images // type_of_size => image_url
I need your help with Google notifications sending which works correctly but with empty messages, title, message etc. are missing...
Any ideas ?
Here is picture how it looks like:
define( 'API_ACCESS_KEY', 'AIzaSyBBh4ddPa96rQQNxqiq_qQj7sq1JdsNQUQ' );
//$registrationIds = array( $_GET['id'] );
$user_device_key = 'eVuuhJNB3vs:APA91bGyf2iAcDEHMVe8MmYzUmNAVl08tfP4wHQFi0sIMhtlZ9PwljdEfZ8JhtfJ_O0rhXTvdJEiVbeRJaUfWn2qvHG6Gw7OjV2jSCmkUd1HK93dyocyC26_48xb0srxa5imUpqXSxMk';
$payload_info = create_payload_json("I know how to send push notifications!");
// API access key from Google API's Console
define('API_ACCESS_KEY', 'AIzaSyAjcvboyovxihsZBtrs2FmVkFbLs-bNk1k');
// prep the bundle
$msg = array
(
'message' => json_decode($payload_info)->aps->alert,
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => array($user_device_key),
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
echo $fields;
$result = curl_exec($ch);
curl_close($ch);
return $result > 0;
function create_payload_json($message) {
//Badge icon to show at users ios app icon after receiving notification
$badge = "0";
$sound = 'default';
$payload = array();
$payload['aps'] = array('alert' => $message, 'badge' => intval($badge),'sound' => $sound);
return json_encode($payload);
}