When creating our WPBeginner Gallery Site, we needed to generate custom branded short urls automatically for each site submitted to the gallery, and then store them as a custom field as soon as the post was published. Now while we will leave the auto-generating Bit.ly shortlinks for each post for our next topic, we will cover how to add custom fields automatically on post publish in WordPress. This can be very useful for developers who are looking to push WordPress to the next level.
在创建WPBeginner Gallery网站时 ,我们需要为提交到图库的每个网站自动生成自定义品牌的短网址,然后在发布该帖子后将它们存储为自定义字段。 现在,尽管我们将为下一个主题保留每个帖子的自动生成Bit.ly短链接,但我们将介绍如何在WordPress中发布帖子时自动添加自定义字段。 对于希望将WordPress推向更高水平的开发人员而言,这可能非常有用。
First thing you need to do is open your theme’s functions.php file and paste the following code:
您需要做的第一件事是打开主题的functions.php文件,并粘贴以下代码:
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
add_post_meta($post_ID, 'field-name', 'custom value', true);
}
}
Then simply replace the field-name and custom value with your Custom Field Name, and the Value. This is a relatively simple trick, but it can be very effective when trying to use WordPress for other than blog purposes.
然后,只需将“字段名称”和“自定义值”替换为“自定义字段名称”和“值”即可。 这是一个相对简单的技巧,但是在尝试将WordPress用于博客以外的其他目的时,它可能会非常有效。
Source: WPCanyon
资料来源: WPCanyon