前端向新帖子添加类别

时间:2019-10-10 作者:capkronos00

这是我的问题,我希望在这里找到答案。

<div class="form-group">
   <label for="genres" class="col-sm-2 control-label">genres</label>
   <div class="col-sm-10">
      <input type="text" class="form-control" id="genres" name="genres">
   </div>
</div>

// Genres value is : anime, action, adventure,

function post_creation() {
    if(isset($_POST[\'movie_nonce_field\']) && wp_verify_nonce($_POST[\'movie_nonce_field\'], \'movie_nonce\')) {
        if(strlen(trim($_POST[\'title\'])) < 1 || strlen(trim($_POST[\'overview\'])) < 1) {
            $redirect = add_query_arg(\'post\', \'failed\', home_url($_POST[\'_wp_http_referer\']));
        } else {

            $category = array( $_POST[\'genres\'] );

            $post_info = array(
                \'post_type\' => \'movies\',
                \'post_status\' => \'pending\',
                \'post_title\' => esc_attr(strip_tags($_POST[\'title\'])),
                \'post_content\' => esc_attr(strip_tags($_POST[\'overview\'])),
                \'post_category\' => $category,

            );
            $post_id = wp_insert_post($post_info);

            if($post_id) {
                update_post_meta($post_id, \'ecpt_postedby\', esc_attr(strip_tags($_POST[\'user_name\'])));
                update_post_meta($post_id, \'ecpt_posteremail\', esc_attr(strip_tags($_POST[\'user_email\'])));
                update_post_meta($post_id, \'ecpt_contactemail\', esc_attr(strip_tags($_POST[\'inquiry_email\'])));
                $redirect = add_query_arg(\'post\', \'successfull\', home_url($_POST[\'_wp_http_referer\']));
            }
        }
        wp_redirect($redirect); exit;
    }
}
add_action(\'init\', \'post_creation\');
类别未保存到帖子。

如果已经存在,我想将新帖子添加到类别中,如果不存在,我想创建新类别

1 个回复
SO网友:Antti Koskinen

看起来您正在尝试使用默认值Post 岗位类型Category 自定义帖子类型的分类法movies.

$post_info = array(
  \'post_type\'     => \'movies\', // custom post type here
  \'post_status\'   => \'pending\',
  \'post_title\'    => esc_attr(strip_tags($_POST[\'title\'])),
  \'post_content\'  => esc_attr(strip_tags($_POST[\'overview\'])),
  \'post_category\' => $category, // categories are by default only for Post post type
);
您是否已将此类代码添加到您的站点,从而允许您使用默认Category 自定义帖子类型的分类法?如果没有,请看一下如何操作,tags & categories with custom post type

如果您已为movies post类型,则应使用tax_input 在您的$post_info 大堆就像这样,

$post_info = array(
  \'post_type\'     => \'movies\',
  \'post_status\'   => \'pending\',
  \'post_title\'    => esc_attr(strip_tags($_POST[\'title\'])),
  \'post_content\'  => esc_attr(strip_tags($_POST[\'overview\'])),
  \'tax_input\'     => array(
    \'some_custom_taxonomy\' => $category
  ),
);