Wp_insert_post:如果post_type中不存在id,则插入带有wp_insert_post的帖子:peliculas

时间:2015-04-15 19:39:49

标签: wordpress wpdb

我需要帮助。 我想用这个args插入帖子:

$new_post = array(
        'post_title'    => $title,
        'post_content'  => $sinopsis,
        'import_id'     =>  $id,
        'post_status'   => 'publish',
        'post_type'     => 'peliculas'
);

但首先我必须在数据库中搜索我设置的import_id是否存在,如果存在Id,我必须用0更新自定义字段状态,如果id不是存在我必须插入帖子:

$query = "SELECT ID FROM $wpdb->posts WHERE post_type='peliculas' AND ID = '" . $id . "'";
$db=$wpdb->get_var($query);

$content = get_posts($db);
if ($content){
    update_post_meta( $content, 'status',0,1);
} else{
    $new_post = array(
        'post_title'    => $title,
        'post_content'  => $sinopsis,
        'import_id'     =>  $id,
        'post_status'   => 'publish',
        'post_type'     => 'peliculas'
    );
    $post_id = wp_insert_post($new_post);
    add_post_meta($post_id, 'titulo', $pelicula->TituloOriginal);
    add_post_meta($post_id, 'director', $pelicula->Director);
    add_post_meta($post_id, 'actores', $pelicula->Actores);
    add_post_meta($post_id, 'genero', $pelicula->Genero);
    add_post_meta($post_id, 'clasificacion', $pelicula->Clasificacion);
    add_post_meta($post_id, 'duracion', $pelicula->Duracion);
    add_post_meta($post_id, 'status', 1);
    add_post_meta($post_id, 'imagen', $pelicula->Cartel);

}

1 个答案:

答案 0 :(得分:0)

我在这里看到一些问题:

  1. get_posts会返回一系列帖子,但当您尝试更新元字段时,您会将其视为返回帖子ID:update_post_meta( $content, 'status',0,1);
  2. 如果您已经知道帖子ID,则无需手动查询数据库以检查其是否存在,只需致电get_post($id)
  3. -

    $post = get_post($id);
    if ($post && $post->post_type == 'peliculas') {
        update_post_meta( $post->ID, 'status', 0, 1);
    } else {
        //...
    }