I’m trying to use the Astica API to get content for my new attachment uploads. While I have no problem using the API outside WordPress, I can’t seem to get it working inside WordPress.
Intend:
- Trigger function when a new attachment image is uploaded
- Send $image_url to the API
- Extract "caption > text" from the response
- Add the text to the post_content field.
The function:
function cwpai_add_content_to_new_attachment( $attachment_id ) {
// Get the attachment post object
$attachment = get_post( $attachment_id );
$image_url = wp_get_attachment_url( $attachment_id );
// Make sure the attachment is an image
if ( 'image' === substr( $attachment->post_mime_type, 0, 5 ) ) {
// Get the current content of the attachment
$content = $attachment->post_content;
// Add image URL to the caption
$new_content = $content ? "{$content}<br>{$image_url}" : $image_url;
// Update the attachment post with the new content
//Add Astica API script
wp_enqueue_script( 'asticaAPI', 'https://www.astica.org/endpoint/ml/javascript/2023-04-10/astica.core.js' );
//Add custom script
wp_add_inline_script( 'asticaAPI', '
function your_astica_CallBack(data) {
if(typeof data.error != "undefined") { alert(data.error); }
console.log(data); //view all data
//Update the attachment post with the Astica response
wp_update_post( array(
"ID" => '.$attachment_id.',
"post_content" => json_encode(data)
) );
}
asticaAPI_start("KEY");
asticaVision(
"2.0_full", //modelVersion: 1.0_full, 2.0_full
"'.$image_url.'", //Input Image
"description, tags,", //or "all"
your_astica_CallBack, //Your Custom Callback function
);
' );
}
}
add_action( 'add_attachment', 'cwpai_add_content_to_new_attachment' )
Testing inside and outside WordPress, tried with rest API as-well without no luck. Also tried to load it with jQuery and no conflict. Can’t seem to figure it out.
2
Answers
wp_add_inline_script
is to inject JavaScript code where aswp_update_post
is a PHP function. You can’t call PHP function inside the JavaScript code to be executed by the user.There are a few issues with the code that may be causing the problem. First, you need to include the Astica API script in the head section of your HTML, rather than using
wp_enqueue_script()
andwp_add_inline_script()
. You can do this by adding the following code to your theme’sheader.php
file:Next, you need to modify the
your_astica_CallBack
function to extract the caption text from the response and update the post content. Assuming the response is in JSON format and contains acaption
field, you can modify the function as follows:Finally, you need to update the
wp_update_post()
function to only update the post content field and remove thejson_encode()
function, since the caption text is already a string:With these changes, the function should work as intended and add the Astica-generated caption text to the post content field of the attachment post.