在以前的情况下,我可以为帖子添加自定义元字段,代码如下:
function website_add_meta_box() {
add_meta_box(
\'website-website\',
__(\'Website\', \'website\'),
\'website_html\',
\'post\',
\'normal\',
\'default\'
);
}
add_action(\'add_meta_boxes\', \'website_add_meta_box\');
function website_html($post) {
wp_nonce_field(\'_website_nonce\', \'website_nonce\'); ?>
<p>Information about users website.</p>
<p>
<label for="website_website_url"><?php _e(\'Website URL\', \'website\'); ?></label><br>
<input type="text" name="website_website_url" id="website_website_url" value="<?php echo website_get_meta(\'website_website_url\'); ?>">
</p>
<p>
<label for="website_website_source_code"><?php _e(\'Website Source Code\', \'website\'); ?></label><br>
<textarea name="website_website_source_code" id="website_website_source_code" ><?php echo website_get_meta(\'website_website_source_code\'); ?></textarea>
</p><?php
}
function website_save($post_id) {
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) return;
if (!isset($_POST[\'website_nonce\']) || !wp_verify_nonce($_POST[\'website_nonce\'], \'_website_nonce\' )) return;
if (!current_user_can(\'edit_post\', $post_id)) return;
if (isset($_POST[\'website_website_url\']))
update_post_meta($post_id, \'website_website_url\', esc_attr($_POST[\'website_website_url\']));
if (isset($_POST[\'website_website_source_code\']))
update_post_meta($post_id, \'website_website_source_code\', esc_attr($_POST[\'website_website_source_code\']));
}
add_action(\'save_post\', \'website_save\');
我的问题是,如何调整此代码,使其仅适用于“网站”的自定义帖子类型?
最合适的回答,由SO网友:NightHawk 整理而成
第四个参数是$screen
, 在您的情况下设置为post
, 因此,您只需指定website
职位类型改为:
function website_add_meta_box() {
add_meta_box(
\'website-website\',
__(\'Website\', \'website\'),
\'website_html\',
\'website\',
\'normal\',
\'default\'
);
}
此处的文档:
https://developer.wordpress.org/reference/functions/add_meta_box/作为旁白save_post
挂钩适用于正在保存的任何帖子或自定义帖子类型,但如果website_website_url
和website_website_source_code
仅适用于website
post类型,您可以添加其他检查:
function website_save($post_id) {
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) return;
if (!isset($_POST[\'website_nonce\']) || !wp_verify_nonce($_POST[\'website_nonce\'], \'_website_nonce\' )) return;
if (!current_user_can(\'edit_post\', $post_id)) return;
if (get_post_type($post_id) !== \'website\') return;
if (isset($_POST[\'website_website_url\']))
update_post_meta($post_id, \'website_website_url\', esc_attr($_POST[\'website_website_url\']));
if (isset($_POST[\'website_website_source_code\']))
update_post_meta($post_id, \'website_website_source_code\', esc_attr($_POST[\'website_website_source_code\']));
}