【问题标题】:Wordpress wp_insert_post is creating new Taxonomy term when creating new custom postWordpress wp_insert_post 在创建新的自定义帖子时正在创建新的分类术语
【发布时间】:2021-01-29 23:03:34
【问题描述】:

在我的 WordPress v5.5.1 中,我使用公共前端表单来创建自定义帖子类型。我使用以下代码将表单数据保存为自定义帖子:

function save_function() {
   // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => array(
            'my_custom_taxonomy' => array(filter_input(INPUT_POST, 'subject')) // subject is a HTML select which captures option value contains term_id which is generated using get_terms.
        )
    );

    wp_insert_post($public_post);
}

不是'tax_input' 将此帖子标记到现有的custom_taxonomy 术语,而是创建一个以term_id 作为术语名称的重复术语。

【问题讨论】:

  • 检查税务条款是否已经存在,如果不存在,则在插入之前创建它 - 然后您可以获得新创建的 term_taxonomy_id,并在插入中使用它。 - 如果它已经存在,则获取它的 term_taxonomy_id,并将其用于插入。
  • 在 SE 发布之前我已经尝试过了,我遇到的代码问题既不是创建重复的术语,也不是将 custom_post 分配给术语。我已经使用term_idterm_taxonomy_id 进行了测试。

标签: php wordpress


【解决方案1】:

您好,请试试这个功能

   function save_function()
{

    $subject_term = 'subject';
    $my_subject_term = term_exists($subject_term, 'my_custom_taxonomy');   // check if term in website or no
    // Create Term if it doesn't exist
    if (!$my_subject_term) {
        $my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
    }
    $custom_tax = array(
        'my_custom_taxonomy' => array(
            $my_subject_term['term_taxonomy_id'],
        )
    );

    // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => $custom_tax
    );

    $post_id = wp_insert_post($public_post);

    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多