保存分类法条款


16

我有一个有趣的问题,希望有人可以快速回答。

我已经创建了自己的元框,该框基于“我的METABOX代码”(下面的列表)正确显示了我创建的“ event_types”分类法中所有术语的下拉列表。

我遇到问题的地方是,从下拉列表中选择其他术语并更新帖子后,便能够保存/更新与该帖子相关的术语。

在修改了各种代码位之后,我能够弄清楚,通过手动将term_ID号(用逗号分隔)输入到数组区域中,可以得到想要的结果。

例如,如果保存帖子,则函数将调用此代码

wp_set_post_terms( $post_id, array(5,7), 'event_types', FALSE);

然后我的帖子将更新,并将term_ID 5和7与其关联,如您所见,我正在传递数组。问题是,这是硬编码到我的functions.php文件中的,而不是基于用户选择的下拉值的(注意:我实际上只是试图传递一个ID,但是我做了两个测试,如下所述)。

我还能够弄清楚,如果我将以下代码添加到我的metabox文件中,则可以回显已分配术语ID的列表,但最后一项带有逗号。

<?php $event_types = wp_get_object_terms($post->ID, 'event_types'); 
foreach ($event_types as $event_type) { echo $event_type->term_id . ','; } ?>

所以...看来我的问题已经解决了85%。我剩下的15%的问题仍然是:

  1. 我需要在我的functions.php文件代码中添加什么(在下面列出),以便在我创建/更新帖子时,将从分类法下拉列表中选择的新值传递到数组中?

  2. 尽管在此示例中,我希望确保仅将SINGLE分类法与帖子相关联,但是在其他情况下,我想创建一个复选框列表,该列表要求我将多个值传递给数组。这样,我需要更改什么,以便将以逗号分隔的术语ID列表传递到数组中?如果您的答案涉及使用上面列出的部分或部分示例代码,在这些代码中回显ID,那么如何确保最后打印的ID末尾没有逗号?(是否有其他/更好的方法?我看到了可能与添加过滤器有关的提示,但不确定如何做到这一点...)

提前非常感谢你们-以下是我当前在每个文件中使用的代码。

我的函数中的代码.PHP文件

function save_event_taxonomy_terms($meta, $post_id) {
        $event_types = wp_get_object_terms($post->ID, 'event_types'); 
        wp_set_post_terms( $post_id, array($names), 'event_types', FALSE);
    }

我的METABOX代码

<select name='post_event_types' id='post_event-types'>
// DISPLAY TERMS AS DROP DOWN OPTIONS
    <?php 
    $names = wp_get_object_terms($post->ID, 'event_types'); 
    $event_types = get_terms('event_types', 'hide_empty=0'); 
    ?>
    <option class='event_type-option' value='' <?php if (!count($names)) echo "selected";?>>Not Assigned</option>
    <?php foreach ($event_types as $event_type) {
        if (!is_wp_error($names) && !empty($names) && !strcmp($event_type->slug, $names[0]->slug)) 
        echo "<option class='event_type-option' value='" . $event_type->slug . "' selected>" . $event_type->name . "</option>\n"; 
        else
        echo "<option class='event_type-option' value='" . $event_type->slug . "'>" . $event_type->name . "</option>\n"; 
    }
    ?>
</select>

Answers:


6

我认为在Dimas可以协助我之后,我会发布答案。

利用他的WPAlchemey类,我添加了一个save_action var,它看起来像这样(请注意,我将分类法用于“类别”,您当然可以将其更改为任何自定义分类法):

'save_action'   => 'save_taxonomy_terms',

然后,我为此添加以下功能:

function save_taxonomy_terms($meta, $post_id) {
wp_set_post_terms($post_id, array($meta['my_terms']), 'category', FALSE);
}

显示分类法下拉列表的my metabox代码如下所示:

<label>Event Category:</label>
    <?php $terms = get_terms('category', 'hide_empty=0'); ?>
    <?php $mb->the_field('my_terms'); ?>
    <select name="<?php $mb->the_name(); ?>">
    <option value='' <?php if (!count($terms)) echo "selected";?>>Not Assigned</option>
    <?php foreach ($terms as $term): ?>
    <option value="<?php echo $term->term_id; ?>"<?php $mb->the_select_state($term->term_id); ?><?php echo '>' . $term->name; ?></option>
    <?php endforeach; ?>
    </select>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.