【问题标题】:Wordpress: how to create posts programatically and check for duplications beforeWordpress:如何以编程方式创建帖子并在之前检查重复项
【发布时间】:2020-11-21 16:45:20
【问题描述】:

我有一个从 API 获取一些数据的脚本,我需要将这些数据(帖子数组)作为帖子插入 WordPress。

所以我需要做的是:

  1. 签入每个帖子(如果存在或不存在)以避免post_name 配音 或slugtitle(如果可能)
  2. 我已经在名为newspaper 的帖子中注册了一个自定义分类法 我需要插入title 的报纸。
  3. 我还用帖子注册了自定义字段,键是 fifu_img_urlfifu_img_alt_cmb_link 所以我需要一种方法来为每个帖子的这些键插入数据

这将是一个rest API post请求,我已经完成了API部分并通过post请求接收数据,剩下的就是按照我上面的描述处理数据。

【问题讨论】:

    标签: php mysql wordpress wordpress-theming


    【解决方案1】:

    我通过以下方式做到了这一点

    $is_post_exists = post_exists($post->title);
    
    if ($is_post_exists === 0) {
        $post_id = wp_insert_post(array(
            'post_title'    => $post->title,
            'post_date'     => $post->date,
            'post_content'  => $post->excerpt,
            'post_author'   => 1,
            'post_status'   => 'publish',
            'meta_input'    => array(
                'fifu_image_url'   => $post->image,
                'fifu_image_alt'   => $post->title,
                '_cmb_link'        =>  $post->link,
            )
        ));
    
        $termObj = get_term_by('name', $post->newspaper->title, 'newspaper');
    
        set_post_format($post_id, $post->type);
    
        if ($termObj) {
            wp_set_object_terms($post_id, array($termObj->term_id), 'newspaper');
        } else {
            $new_newspaper = wp_insert_term($post->newspaper->title, 'newspaper');
    
            wp_set_object_terms($post_id, array($new_newspaper['term_id']), 'newspaper');
        }
    
        if ($post_id) {
            $added_posts[] = $post_id;
        }
    } else {
        $not_added_posts[] = $post->id;
    }
    

    【讨论】:

    • 我无法使用 fifu_image_url 获取特色图片。你能帮忙吗?
    • fifu_image_url 是我注册的自定义字段,不是特色图片,要以任何方式获取特色图片,您必须使用get_the_post_thumbnail()
    • 我需要在每个帖子的参数中设置一个 fifu_image_url。我正在使用 PHP 使用 XMLRPC 发布帖子,但帖子没有附带特色图像我已经在自定义字段中定义 fifu_image_url 为以及他们定义的文档,但没有出现特色图片。
    • 查看代码:$content = array( 'terms' => array('category' => array( $YourCategoryID ) ), 'post_type' => 'post', 'post_name' => $slug, //for slug 'post_status' => 'draft', 'post_title' => $title, 'post_content' => $body, 'ping_status' => 'closed', 'comment_status' => 'closed', 'meta_input' => array( 'fifu_image_url' => $img_url, 'fifu_image_alt' => $title, )
    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 2018-04-19
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多