【问题标题】:Selecting category of the new post from front-end form?从前端表单中选择新帖子的类别?
【发布时间】:2021-03-03 05:57:48
【问题描述】:

我有一个前端表单,它使用户能够创建帖子。它只发送文本类型的标题、描述和自定义字段。 但我还想在表单中添加一个类别选项,以显示当前类别的列表,并让用户为他们的新帖子选择一个或多个。 (选定的类别将分配给新帖子。)

这是一个 WordPress 网站,我使用 Avada 主题。自定义帖子类型是 Avada 的默认 Portfolio 帖子。但是笼统的答案也会非常有帮助(请对您的代码进行一些解释)。

所以,这是我的子主题中 fuctions.php 中的 php 代码:

    if(isset($_POST['title'])){

    $custom_field_address1 = $_POST['address1'];

    $my_post = array(

    'post_title' => $_POST['title'],
    'post_content' => $_POST['description'],
        
    'post_status' => 'publish', 
    'post_type' => 'companies',
    'meta_input' => array(
        'address1' => $custom_field_address1,
        )
);
    
    $post_id = wp_insert_post($my_post);

    add_post_meta( $post_id, 'address1', $custom_field_address1, false );
    echo 'New Post Saved !';
    
    die;
}

我的前端表单(我想查看 Portfolio 帖子类型的所有类别并选择我想要的):

<form method="post">
<div class="form-group">
      <label for="title">Post Title:</label>
      <input type="text" class="form-control" id="title" name="title">
</div>
    
    
<div class="form-group">
      <label for="pwd">Post Description :</label>
      <textarea class="form-control"  name="description"></textarea>
</div>
      
<div class="form-group">
      <label for="address1">Address :</label>
      <input type="text" name="address1" id="address1">
</div>

<BR>
<button type="submit" class="btn btn-default">Submit</button>
</form>

我已经阅读了很多答案,例如this,但其中大多数只是另一个人网站的代码,解释太少。所以,我需要获得更多帮助。

【问题讨论】:

  • 将这个问题表述得更像minimal, reproducible example 会使这个问题更容易解决。
  • 我做了一个完整的修改。写了一个较短的代码并在粘贴之前仔细检查了它。

标签: php wordpress forms wordpress-theming


【解决方案1】:

您可以创建一个选择。只是为了使用get_terms 或类似函数获取类别列表。

$categories = get_terms( [
    'taxonomy'   => 'category',
    'hide_empty' => false,
    'field'      => 'id=>name'
] );

?>

<select name="category">
    <?php foreach( $categories as $category_id => $category_name ) { ?>
        <option value="echo absint( $category_id ); ?>"><?php echo esc_html( $category_name ); ?></option>
    <?php } ?>
</select>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多