wp_remote_post() body empty - json

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

Related

How to use ACF into JSON via ajax in Wordpress

I'm trying to use the Advanced Custom Field (ACF) plugin to return JSON via ajax in WordPress.
The below code correctly returns the JSON data of the posts but is not giving me the ACF data inside each post.
How can I get that ACF data into JSON?
PHP File
add_shortcode("owt-ajax-shortcode", "owt_wpl_run_shortcode");
function owt_wpl_run_shortcode() {
ob_start();
include_once plugin_dir_path(__FILE__) . 'views/owt-ajax-page-view.php';
$template = ob_get_contents();
ob_end_clean();
echo $template;
}
add_action("wp_enqueue_scripts", "owt_include_scripts");
function owt_include_scripts() {
wp_enqueue_script("jquery");
}
add_action("wp_ajax_owt_ajax_lib", "owt_lib_ajax_handler_fn");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_lib_ajax_handler_fn");
function owt_lib_ajax_handler_fn() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$all_posts = get_posts(array(
"post_type" => "post",
"post_status" => "publish",
'posts_per_page' => 20,
'order' => 'DESC',
'orderby' => 'date',
'cat' => 66
));
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $all_posts );
die;
}
}
wp_die();
}
JavaScript
<button id="btn-get-all-posts">Click to get All Posts</button>
<script>
jQuery(function () {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery("#btn-get-all-posts").on("click", function () {
var postdata = "action=owt_ajax_lib&param=get_all_posts";
jQuery.post(ajaxurl, postdata, function (response) {
console.log(response);
});
});
});
</script>
instead of use get_posts try your own query with WP_Query
here is an example code, please let me know if it works correctly(I didn't test it yet)
function owt_lib_ajax_handler_fn()
{
$param = isset($_REQUEST[ 'param' ]) ? trim($_REQUEST[ 'param' ]) : "";
if ( ! empty($param) ){
if ( $param == "get_all_posts" ){
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 66 ],
];
$all_posts = new WP_Query($args);
$json_response = [];
if ( $all_posts->have_posts() ){
while ( $all_posts->have_posts() ) {
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields(get_the_ID()),
],
];
}
wp_send_json($json_response, 200);
wp_die();
}
else {
wp_send_json($json_response, 404);
wp_die();
}
}
}
wp_die();
}
please have a look as below:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => array('red', 'orange'),
'compare' => 'IN',
),
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
),
));
Please use below function:
add_action("wp_ajax_owt_ajax_lib", "owt_ajax_lib");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_ajax_lib");
function owt_ajax_lib() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 33 ],
];
$all_posts = new WP_Query($args);
$json_response = array();
if ( $all_posts->have_posts() ):
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields( get_the_ID() ),
],
];
endwhile;
endif;
echo json_encode($json_response);
die;
}
}
die;
}

JSON WP REST API getting featured image by Taxonomy Terms

I'm trying to get a featured-image from my custom taxonomy-*projects* term-*elfla*.
I managed to get a image from the posts with this code what i found here but I don't understand how to do it with taxonomy terms.
At this point I do not understand how to get the featured image source and whether the 'GET' request url is correct.
JS:
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://localhost/test/wordpress/wp-json/wp/v2/posts/?filter=projects&filter=elfla&_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
portfolioPostsBtn.remove();
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
});
}
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < postsData.length; i++) {
ourHTMLString += '<img src="'+postsData[i].featured_image_thumbnail_url+ '" alt="img">';
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}
Functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$thumbnail_id = get_term_meta( $post->ID , 'thumbnlai' false );
$thumbnail = wp_get_attachment_image_src( $thumbnail_id );
$_data['featured_image_thumbnail_url'] = $thumbnail[0];
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Use this function.
**function custom_api_get_all_posts() {
register_rest_route( 'custom/v1', '/all-posts', array(
'methods' => 'GET',
'callback' => 'custom_api_get_all_posts_callback'
)); }
function custom_api_get_all_posts_callback( $request ) {
// Initialize the array that will receive the posts' data.
$posts_data = array();
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param( 'page' );
$paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1;
// Get the posts using the 'post' and 'news' post types
$posts = get_posts( array(
'paged' => $paged,
'post__not_in' => get_option( 'sticky_posts' ),
'posts_per_page' => 1000,
'post_type' => array('post') // This is the line that allows to fetch multiple post types.
)
);
// Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
foreach( $posts as $post ) {
$id = $post->ID;
$post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
'type' => $post->post_type,
'title' => $post->post_title,
"content" => apply_filters('the_content', $post->post_content),
'featured_img_src' => $post_thumbnail
);
}
return $posts_data; }
use this link http://yourdomin.com/wp-json/custom/v1/all-posts.
I think it will work for you

WP query retrieve the src of the attached image

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

Save an object in wordpress database

it is possibe to save an object in prefix_options in wordpress database like this one:
$arr_params = array( 'cat' => $display_category, 'product' => $single_post_ID );
Thanks
edit:
after make some changes, the code can't add an new array in exsisting array in the database:
$item= array(
'name' => $name ,
'prename' => $prename
);
print_r($item);
$options = get_option( 'options' );
if (empty($options['items'])) {
$options['items']=array();
add_option( 'options', $options );
$options = get_option( 'options' );
$options['items'] = array_push($options['items'], "$item");
update_option( 'options', $options );
}
else{
$options = get_option( 'options' );
$options['items'] = array_push($options['items'], "$item");
update_option( 'options', $options );
}
yes you can,
$arr_params = array( 'cat' => $display_category, 'product' => $single_post_ID );
if( get_option("_arr_params") === false ) {
add_option("_arr_params", $arr_params);
}
else {
// holds : array( 'cat' => $display_category, 'product' => $single_post_ID );
$my_param = get_option("_arr_params");
}
According to Edit Part: array_push() on works to add one or more elements not the array, you can use array_merge() in place of it, or second option is i already used in below codes.
$options['wphyper_orders'][] = $order_detail;
helpful link : get_option()

Issue on Adding Taxonomy to Custom Post Type Using Function

Using WordPress 3.7.1 and PHP 5.4.12, I am trying to add Custom Post Type and Taxonomy to my Theme, so far the custom post type method works but the Taxonomy is not adding to the Admin Dashboard.
Here is the code I have:
<?php
function add_post_type($name, $args = array()) {
add_action('init', function() use($name, $args) {
$upper = ucwords($name);
$name = strtolower(str_replace(' ','_',$name));
$args = array_merge(
array(
'public'=> true,
'label' => "All $upper" . 's',
'labels' => array('add_new_item' => "Add New $upper"),
'support' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments')
),
$args
);
register_post_type('$name', $args);
});
}
function add_taxonomy($name, $post_type, $args = array()) {
$name = strtolower($name);
add_action('init', function() use($name, $post_type, $args) {
$args = array_merge(
array(
'label' => ucwords($name),
),
$args
);
register_taxonomy($name, $post_type, $args);
});
}
add_post_type('book', array(
'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments')
));
add_taxonomy('fun', 'book');
?>
Can you please let me know what part I am doing wrong?
The $name variable is not parsed, put it between double quotes:
register_post_type( "$name", $args );
edit
add_action( 'init', 'so19966809_init' );
function so19966809_init()
{
register_post_type( 'book', array(
'public'=> true,
'label' => 'All Books',
'labels' => array( 'add_new_item' => 'Add New Book' ),
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
'taxonomies' => array( 'fun' )
) );
register_taxonomy( 'fun', 'book', array(
'label' => 'Fun',
) );
}