我正在尝试从omdb web服务获取电影信息,它工作得很好,但当我想使用wp\\u insert\\u post创建新帖子时,它不起作用。此脚本的作用是,用户输入电影ID并以AJAX的形式接收信息,并向用户显示一个链接以编辑帖子,但帖子ID值为0。
function omdb_Flex_movie(){
add_menu_page(
\'Fetch info\',
\'fetch info\',
\'edit_posts\',
\'test-script\',
\'menu_callback\',
\'dashicons-format-video\',
1);
}
add_action(\'admin_menu\',\'omdb_Flex_movie\');
function fetch_info(){
if (current_user_can(\'edit_posts\')) {
if (isset($_POST[\'id_movie\'])) {
$id_movie = $_POST["id_movie"];
if (($id_movie != NULL)) {
$get_json_movie = file_get_contents("http://www.omdbapi.com/?apikey=ba9e1d33&i=$id_movie");
$result = json_decode($get_json_movie, TRUE);
$imdb = $result[\'imdbID\'];
$genrefarsi = $result[\'Genre\'];
$my_post = array(
\'post_title\' => \'test title\',
\'post_status\' => \'pending\',
\'post_type\' => \'post\'
);
global $wpdb;
$consulta = "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = \'id_imdb\' AND meta_value = \'{$imdb}\' ";
$verificar = $wpdb->get_results($consulta, OBJECT);
if ($verificar) {
echo \'<strong>This Post Already Exist</strong> \';
} else {
$post_id = wp_insert_post($my_post);
echo \'<a target="_blank" href="\' . esc_url(home_url()) . \'/wp-admin/post.php?post=\' . $post_id . \'&action=edit"><span class="draft_ready">Click This Link</span></a><span class="import_completed">Success</span>\';
}
wp_set_object_terms($post_id, $genrefarsi, \'category\');
}
}
}
die();
}
add_action(\'wp_ajax_fetch_info\', \'fetch_info\');
function menu_callback(){
?>
<!--Tabs Container-->
<div class="tabs-container">
<ul class="tabs">
<li data-tab="film" class="active">movie</li>
<li data-tab="serial" class="">series</li>
</ul>
</div>
<!--Body Container-->
<div class="omdb-container active" id="film">
<div class="form">
<div class="inputs">
<input type="text" name="id_movie" placeholder="ID imdb">
<?php wp_nonce_field(\'send-movies\', \'send-movies-nonce\'); ?>
</div>
<div class="bottom">
<button type="button" id="sendAjax">Fetch info</button>
<p>
<small>exp :</small>
http://www.imdb.com/title/<strong>tt2386490</strong>
</p>
</div>
</div>
<div class="loading"><img src="<?php echo DT_DIR_URI ;?>/inc/omdb/img/loading.svg"></div>
<div class="result"></div>
</div>
}
最合适的回答,由SO网友:Pratikb.Simform 整理而成
我想原因是你没有添加帖子标题和帖子id
$my_post = array(
\'post_id\' => 1,
\'post_status\' => \'pending\',
\'post_type\' => \'post\'
);
理想情况下,如果应该
$my_post = array(
\'post_title\' => wp_strip_all_tags( $_POST[\'post_title\'] ),
\'post_content\' => $_POST[\'post_content\'],
\'post_status\' => \'publish\',
\'post_author\' => 1,
\'post_category\' => array( 8,39 ),
\'post_type\' => \'post\'
);