Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Så här lägger du till Custom Fields automatiskt när du publicerar ett post i WordPress

Behöver du automatiskt skapa customize-fält när du publicerar dina posts i WordPress?

Det här är ett enkelt trick som utvecklare kan använda när de lägger till utvalda funktioner på sin website WordPress.

I den här artikeln visar vi dig hur du lägger till customize-fält automatiskt när du publicerar post i WordPress.

How to Add Custom Fields Automatically on Post Publish in WordPress

Varför lägga till Custom Fields automatiskt?

MedCustomize-fält kan du lägga till ytterligare information i dina posts. Denna information kan visas på din website, hållas privat eller användas av teman och tillägg för att utöka funktionaliteten på din WordPress website.

Det finns många sätt att använda customize-fält. Du hittar en lista med användbara idéer i vår guide med tips, tricks och hacks för customize-fält.

Ibland vill du att ett customze-fält ska skapas automatiskt när du publicerar ett post. Detta gäller särskilt när du lägger till funktionalitet i WordPress så att du kan använda det som mer än en enkel blogg.

Vi använde den här metoden när vi skapade en website för ett gallery. Vi ville lagra korta URL:er för varje objekt som skickades in till galleriet. Så vi skapade automatiskt ett custom field för att lagra den korta URL:en när varje post publicerades.

Detta trick kan vara mycket användbart för utvecklare som vill ta WordPress till nästa nivå.

Lägga till Customize-fält automatiskt vid publicering av post

Den här metoden innebär att du lägger till ett custom code snippet i ditt temas functions.php-fil. Vi rekommenderar inte att oerfarna användare editerar dina theme-filer, eftersom även ett litet misstag kan förstöra din website.

Istället visar vi dig hur du använder WPCode-tillägget i den här tutorialen.

WPCode

WPCode gör det enkelt att add to code snippets i WordPress utan att behöva editera functions.php-filen i ditt theme. Du kan också hantera alla dina code snippets från en central vy.

Om det här är första gången du lägger till kod i WordPress bör du kontrollera vår guide om hur du copy and paste code snippets i WordPress för mer details.

För att komma igång måste du installera och aktivera det gratis pluginet WPCode. Om du behöver hjälp kan du läsa vår tutorial om hur du installerar ett plugin för WordPress.

Note: Den gratis versionen av WPCode har allt du behöver för att add custom code i WordPress. För mer avancerade funktioner som gillar tidsinställda snippets, Conversion Pixels, och mer, kan du uppgradera till WPCode Pro.

När pluginet har aktiverats kommer ett nytt menu item med namnet ”Code Snippets” att addas till din WordPress admin bar. Klicka på det och tryck sedan på knappen ”Add New” på nästa vy.

Click the Add New Button to Add Your First Custom Code Snippet in WPCode

Härifrån navigerar du till alternativet ”Add Your Custom Code (New Snippet)” och klickar på knappen ”Use snippet” under den.

Add your new custom code snippet in WPCode

Därefter måste du ge snippet en titel och sedan kopiera följande kod och klistra in den i rutan ”Code Preview”.

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);
    }
}

Du måste ersätta ”field-name” och ”custom value” med det faktiska namn och värde som du vill använda för det anpassade fältet.

Glöm inte att välja ”PHP Snippet” som code type i dropdown-menyn till höger.

Paste code snippet in WPCode code box

Därefter rullar du ner till ”Insertion” section. Här måste du låta metoden ”Auto Insert” vara vald.

Pick the insertion method for your custom code snippet

Med metoden Auto Insert kommer snippet automatiskt att infogas och exekveras på rätt location.

När du är klar måste du toggle omkopplaren från ”Inaktiverad” till ”Aktiv” och sedan clicka på knappen ”Save Snippet”.

Save and activate your custom code snippet

När snippet är aktiverat skapas det anpassade fältet när du publicerar ett post.

Vi hoppas att denna tutorial hjälpte dig att lära dig hur du lägger till custom fields automatiskt vid publicering av post i WordPress. Du kanske också vill lära dig hur du väljer det bästa webbhotellet för WordPress eller kontrollera vår lista över WordPress tillägg som du måste ha för att utveckla din website.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

17 kommentarerLämna ett svar

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. nayan says

    I want to add category Id for the post in the post_meta table. How can be the function function add_custom_field_automatically($post_ID) be twicked to accomodate that?

    Thanks

  3. chris says

    Instead of adding the custom field at the time of creating the post, how do I display a custom field by default on the admin page?

    • Editorial Staff says

      If you notice, the code above doesn’t have anything related to the custom post types. It only adds to Post and Page ”content type”. So you would have to specify the hook for your custom post type.

      Administratör

      • puanthanh says

        Thanks for the reply. Can you help me out on this code.
        add_action(’publish_page’, ’add_custom_field_automatically’);
        add_action(’publish_post’, ’add_custom_field_automatically’);
        add_action( ’save_post’, ’add_custom_field_automatically’ );

        function add_custom_field_automatically($post_ID) {
        global $post;
        if(!wp_is_post_revision($post_ID)) {
        global $wpdb;
        $user_id = $wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = $post_ID");
        $themename = $wpdb->get_var("SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = ’themeperauthor’ AND user_id = $user_id");
        add_post_meta($post_ID, ’themeperauthor’, $themename, true);
        }
        }
        When the user meta field is changed, I want to automatically delete the custom field value and update with the new one

  4. brian says

    I’ve been working on adding some hidden custom fields on post publish/update (by preceding the field name with ”_”) but for some reason I have to update the post twice before the wp_postmeta entries are written to the database.

    I’ve tried messing with the priority and experimenting with other action hooks (draft_to_publish, edit_post, etc) but it doesn’t seem to make a difference.

    Any ideas?

  5. Piet says

    will this work too for custom post types?
    sth like add_action(’publish_custom-post-typ-name’, ’add_custom_field_automatically’);

    • Otto says

      Yes, it will.

      One downside to this technique that people should be aware of is that if somebody edits a published post, this hook WILL get fired again on the edit. Therefore, you need to check for the meta before adding it, or to update it, or to do whatever makes the most sense for your use-case.

      If you only want to get your code fired off on the initial publish only, then you can use the transition_post_status hook. This hook works like this:


      add_action('transition_post_status','example',10,3);
      function example($new, $old, $post) {
      // $new is the new post status ('publish')
      // $old is the old post status ('draft')
      // $post is the complete Post Object (so use $post->ID for the ID, etc)
      }

      Then, in here you can do a check for something like this:

      if ($new == 'publish' && $old != 'publish')

      To have your code only used when the post status actually transitions to publish from whatever it was before. This hook is fired at the same time as the {$status}_{$post-type} hooks are, so the operation of them is basically the same.

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.