本文主要是介绍为wordpress特定分类目录下的内容添加自定义字段,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在WordPress中,您可以使用自定义字段(Custom Fields)或称为元数据(Meta Data)来为特定分类目录下的内容添加额外的信息。自定义字段可以附加到文章、页面、用户和其他对象上。以下是一个逐步指南,介绍如何为特定分类目录下的内容添加自定义字段,并在内容录入时显示这些字段。
步骤 1: 添加自定义字段
首先,您需要在WordPress后台创建一个自定义字段。这可以通过在主题函数文件(functions.php)中添加代码来实现。
打开您的WordPress主题文件夹,并找到functions.php文件。
在functions.php文件中添加以下代码,以创建一个名为my_custom_field的自定义字段,并将其与特定分类关联:
// 添加自定义字段
function add_custom_field_to_category() {register_meta('post', 'my_custom_field', array('type' => 'text','single' => true,'show_in_rest' => true,'label' => '我的自定义字段','description' => '这是一个自定义字段示例。',));
}
add_action('init', 'add_custom_field_to_category');// 将自定义字段与特定分类关联
function load_custom_field_for_category($term) {$term_id = $term->term_id;$category_name = $term->name;// 假设您的分类名称是 "特定分类"if ($category_name === '特定分类') {add_meta_box('my_custom_field_box','我的自定义字段','display_custom_field_box','post','normal','high');}
}
add_action('load-post.php', 'load_custom_field_for_category');
add_action('load-post-new.php', 'load_custom_field_for_category');// 显示自定义字段的输入框
function display_custom_field_box() {global $post;echo '<input type="text" id="my_custom_field" name="my_custom_field" value="' . get_post_meta($post->ID, 'my_custom_field', true) . '" size="30" style="width:97%;" />';
}
请注意,上述代码中的特定分类应替换为您想要添加自定义字段的实际分类名称。
步骤 2: 保存自定义字段的值
接下来,您需要在WordPress保存文章时保存自定义字段的值。这可以通过添加以下代码到functions.php文件来实现:
// 保存自定义字段的值
function save_custom_field_value($post_id) {if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {return;}if (!current_user_can('edit_post', $post_id)) {return;}if (isset($_POST['my_custom_field'])) {update_post_meta($post_id, 'my_custom_field', $_POST['my_custom_field']);} else {delete_post_meta($post_id, 'my_custom_field');}
}
add_action('save_post', 'save_custom_field_value');
步骤 3: 在内容录入时显示自定义字段
最后,您可以在文章编辑页面和内容页面显示自定义字段。这可以通过编辑WordPress的模板文件来实现。
打开您的WordPress主题文件夹,并找到single.php或content.php文件(取决于您的主题结构)。
在适当的位置添加以下代码,以显示自定义字段的值:
<?php if (get_post_meta($post->ID, 'my_custom_field', true)) : ?><p>我的自定义字段: <?php echo get_post_meta($post->ID, 'my_custom_field', true); ?></p>
<?php endif; ?>
这段代码会检查当前文章是否有my_custom_field自定义字段,并在有值的情况下显示它。
完成
现在,当您在WordPress后台为特定分类下的文章添加或编辑内容时,应该会看到一个名为“我的自定义字段”的新输入框。您可以在这个输入框中输入自定义字段的值,这些值会在保存文章后保存,并在文章页面上显示。
原文
https://www.wowsoho.com/news/6203.html
这篇关于为wordpress特定分类目录下的内容添加自定义字段的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!