如何向wordpress添加自定义字段面板(WordPress自定义文章模板)

Wordpress1年前 (2023)发布 SUYEONE
665 0 0

WordPress中添加自定义字段面板,可以极大地方便你管理和输入常用字段,无需每次都从下拉菜单中选择。以下是一个简单的教程,教你如何实现这一功能,让你像添加文章标签那样直接在面板上填写内容。

首先,你需要定义自定义字段。在下面的代码示例中,我们创建了两个字段:`_description_value` 和 `_keywords_value`。你可以根据需要添加更多字段到数组中。每个字段的名称(例如`_description`)后面加上`_value`是为了避免与其他代码冲突,`std`代表默认值,`title`是用户界面中显示的标题。

“`php
$new_meta_boxes = array(
‘description’ => array(
‘name’ => ‘_description_value’,
‘std’ => ‘在此填写默认页面描述’,
‘title’ => ‘页面描述:’,
),
‘keywords’ => array(
‘name’ => ‘_keywords_value’,
‘std’ => ‘在这里填写默认的网页关键字’,
‘title’ => ‘关键词:’,
),
);
“`

接下来,创建自定义字段的输入框。这段代码会在文章编辑页面生成输入框:

“`php
function new_meta_box() {
global $post, $new_meta_boxes;
foreach ($new_meta_boxes as $meta_box) {
$meta_box_value = get_post_meta($post->ID, $meta_box[‘name’] . ‘_value’, true);
if ($meta_box_value == ”) $meta_box_value = $meta_box[‘std’];
echo ‘

‘ . $meta_box[‘title’] . ‘

‘;
echo ‘
‘;
}
echo ”;
}
“`

然后,使用WordPress内置的`add_meta_box`函数创建自定义字段模块:

“`php
function create_meta_box() {
if (function_exists(‘add_meta_box’)) {
add_meta_box(‘new_meta_box’, ‘自定义模块’, ‘new_meta_box’, ‘post’, ‘normal’, ‘high’);
}
}
“`

在保存文章数据前,确保保存自定义字段的信息:

“`php
function save_postData($post_id) {
global $new_meta_boxes;
if (!wp_Verify_nonce($_POST[‘ludou_metaboxes_nonce’], plugin_basename(__FILE__))) return;
if (!current_user_can(‘eDiT_posts’, $post_id)) return;
foreach ($new_meta_boxes as $meta_box) {
$data = $_POST[$meta_box[‘name’] . ‘_value’];
if ($data == ”) delete_post_meta($post_id, $meta_box[‘name’] . ‘_value’, get_post_meta($post_id, $meta_box[‘name’] . ‘_value’, true));
else update_post_meta($post_id, $meta_box[‘name’] . ‘_value’, $data);
}
}
“`

最后,将这些函数绑定到适当的动作上,使它们在适当的时候运行:

“`php
add_Action(‘admin_menu’, ‘create_meta_box’);
add_action(‘save_post’, ‘save_postdata’);
“`

现在,你可以在文章编辑页面看到自定义的字段面板,并且在保存文章时,自定义字段的数据也会被保存。在主题中,你可以通过`get_post_meta`函数获取这些字段的值并使用,例如在`header.php`中显示元描述和关键词

“`php
if (is_single()) {
$description = get_post_meta($post->ID, ‘_description_value’, true);
$keywords = get_post_meta($post->ID, ‘_keywords_value’, true);
$description = trim(strip_tags($description));
$keywords = trim(strip_tags($keywords));
echo ”;
echo ”;
}
“`

通过这种方式,你可以创建一个直观且方便的自定义字段面板,提高你的工作效率。

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!