从 API 响应添加内容到新的图片上传

问题描述 投票:0回答:1

我正在尝试使用 Astica API 来获取新上传附件的内容。虽然我在 WordPress 外部使用 API 没有问题,但我似乎无法在 WordPress 内部使用它。

意向:

  1. 上传新附件图片时触发功能
  2. 发送 $image_url 到 API
  3. 从响应中提取“标题 > 文本”
  4. 将文本添加到 post_content 字段。

Astica 文档

功能:

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

在 WordPress 内部和外部进行测试,也尝试使用 rest API,但没有成功。还尝试用 jQuery 加载它并且没有冲突。似乎无法弄清楚。

javascript php wordpress response
1个回答
0
投票

wp_add_inline_script
是注入JavaScript代码,而
wp_update_post
是一个PHP函数。您不能在要由用户执行的 JavaScript 代码中调用 PHP 函数。

© www.soinside.com 2019 - 2024. All rights reserved.