也想出现在这里?联系我们

非插件扩展wordpress分类,增加分类关键词自定义字段

2023.11.10 wordpress教程
  • 文章介绍
  • 升级版本
  • 评价&建议

要在WordPress中扩展分类以添加自定义字段,您可以通过编写自定义插件或在主题的functions.php文件中添加代码来实现。以下是一个示例,演示如何为分类添加自定义关键词字段:

  1. 创建一个自定义插件(如果您已经有一个插件,可以在其中添加以下代码)。

  2. 在插件的主文件中添加以下代码:

<?php
/
Plugin Name: Custom Category Keywords
Description: Adds custom keyword field to categories.
/

// 添加自定义字段
function custom_category_keywords_field() {
    ?>
    <div class="formfield">
        <label for="customcategorykeywords">自定义关键词</label>
        <input type="text" name="customcategorykeywords" id="customcategorykeywords" value="">
    </div>
    <?php
}
add_action('category_add_form_fields', 'custom_category_keywords_field', 10, 2);

// 保存自定义字段值
function save_custom_category_keywords($term_id) {
    if (isset($_POST['customcategorykeywords'])) {
        $custom_keywords = sanitize_text_field($_POST['customcategorykeywords']);
        update_term_meta($term_id, 'customcategorykeywords', $custom_keywords);
    }
}
add_action('created_category', 'save_custom_category_keywords', 10, 2);

// 编辑页面上显示自定义字段
function edit_custom_category_keywords_field($term) {
    $custom_keywords = get_term_meta($term>term_id, 'customcategorykeywords', true);
    ?>
    <tr class="formfield">
        <th scope="row" valign="top"><label for="customcategorykeywords">自定义关键词</label></th>
        <td>
            <input type="text" name="customcategorykeywords" id="customcategorykeywords" value="<?php echo esc_attr($custom_keywords); ?>">
        </td>
    </tr>
    <?php
}
add_action('category_edit_form_fields', 'edit_custom_category_keywords_field', 10, 2);

// 更新自定义字段值
function update_custom_category_keywords_field($term_id) {
    if (isset($_POST['customcategorykeywords'])) {
        $custom_keywords = sanitize_text_field($_POST['customcategorykeywords']);
        update_term_meta($term_id, 'customcategorykeywords', $custom_keywords);
    }
}
add_action('edited_category', 'update_custom_category_keywords_field', 10, 2);
?>
  1. 激活插件。

现在,当您编辑或添加新的WordPress分类时,将会显示一个名为“自定义关键词”的自定义字段。您可以在这里输入您想要的关键词,并通过get_term_meta()函数来检索和使用这些关键词。

有用0
  • 2023.11.10初次和大家见面了!

等待您对该主题的建议

发表评论

还能输入240个字

Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

我要入群
也想出现在这里?联系我们
wordpress加速

我来推荐一个更牛逼的给你看看?

  • 猛戳我吧