X

Obtenir la valeur d’un champ personnalisé avec un code court

Snippets by IsItWP

Voulez-vous obtenir les valeurs des champs personnalisés en utilisant un shortcode ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour obtenir la valeur d’un champ personnalisé avec un shortcode dans WordPress.

Instructions:

Tout ce que vous avez à faire est d’ajouter ce code dans le fichier functions.php de votre thème ou dans un plugin spécifique à votre site:

add_shortcode('field', 'shortcode_field');

function shortcode_field($atts){
     extract(shortcode_atts(array(
                  'post_id' => NULL,
               ), $atts));
  if(!isset($atts[0])) return;
       $field = esc_attr($atts[0]);
       global $post;
       $post_id = (NULL === $post_id) ? $post->ID : $post_id;
       return get_post_meta($post_id, $field, true);
}
 [field "my_key"]
 [field "my_key" post_id=1]

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez consulter notre guide sur la façon d’ajouter correctement des extraits de code dans WordPress, afin de ne pas endommager accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 10 meilleurs plugins WordPress de témoignages pour ajouter de la preuve sociale et comment créer un formulaire de contact sur WordPress.

Commentaires   laisser une réponse

  1. Mine just output the word Array?

  2. Hello, excellent snippet 🙂

    Is it possible to show an error message when the custom file does not exist?

    It is hard to spot errors when there is no output at all.

    Best regards
    Rudi

  3. Any idea how to output a custom field as a link?
    I tried this: test but it’s not working. Thanks.

  4. Hello,

    It is working well for custom fields of the plugins, thank you! But how to render standard fields like “Title” or “Exerpt”?

  5. thank you so very much. nice work

    1. Hey Kasra, you’re welcome. Don’t forget to follow us on Facebook and Twitter. 🙂

  6. How to global custom field value as it is not fired in meta description by rankmath.

  7. This article help me so much. A lots of thanks from Vietnam.

  8. Thanks, Worked like charm 🙂

  9. thanks a lot. this is work perfectly

    1. Glad it helped, Nail 🙂

  10. Mamma mia – works perfectly fine! Thanks a lot! 🙂

  11. Thank you for this amazing snippet, works like a charm ?

    1. Glad it worked for you

  12. Hey
    I can not make it work. Do I need to edit the short code and replace words : my_key with the name of my custom field?
    And do I have to change something in the code that you put in functions.php or paste it as it is? Thanks a lot

  13. Great snippet, thank you. It works great on my woocommerce product pages, but not on cart and checkout. Any advice how to fix this would be really appreciated!

    1. No idea? 🙁

  14. Andreas Kyriakidis novembre 1, 2016 à 6:41 am

    Hi! Thank your for the code.

    Is it possible to customize the snippet in order to have a [field “my_key” page_id=1] shortcode too?

  15. Hi Marco if I was to guess you are using the wrong custom field name. some plugins will use an underscore before the custom field name e.g. _description. this is done to hide the fields on the admin side.

    you can use this snippet within your theme to display a listing of all custom fields. This will display an admin notice within the post edit screen in the admin and list everything. You can just remove this snippet when you have the correct custom field name.

    http://wpsnipp.com/index.php/functions-php/show-absolutely-custom-fields-post/

    1. No, “description” is the field name, imported by the plugin “CultureObject”
      i enter a new “testfield” with text “textfield for post” in the post editor screen.
      The “description” doesn’t show up, the “textfield for post” text is visible.
      I looked in de database and both fields show up. Except for the text/content they are identical.
      Why does a custom field imported by CulturObject behave differently from a manually created custom field.
      Is the difference that the fields i fill in manually (and do show up) are in regular posts and the custom fields imported by CultureObject are in Custom Posts ? (that don’t show up)

  16. Jarod Emerson Thornton août 5, 2015 à 11:56 am

    This is awesome. Thank you so much!

  17. Doesn’t output anything within a Grid Element text block, in a Post Grid (Visual Composer)

  18. Thanks! Was searching on google last 2 days!!!

  19. Thanks for that article, it really help me a lot 🙂

  20. Thanks for that article, it really help me a lot 🙂

  21. 30 Extremely Useful Wordpress Code Snippets & Hacks | Web Design Habits octobre 14, 2011 à 6:33 am
  22. When trying to put custom field content within another shortcode, depending on how the other shortcode is setup, could you do away with the double-quotes?
    For example:
    [my_field_name]
    instead of
    [field "my_field_name"]

    That way a shortcode like this could work (right?):
    [contact-form to="[my_field_name]"]
    Because if a shortcode with quotes is within a shortcode with quotes, the quote/bracket stuff at the end gets it confused (i.e. doesn’t work).

    I don’t see any double-quotes in your function/snippet, so I wasn’t sure.

    Thanks bunches!

    1. I tried [field]my_field_name[/field] and it didn’t work.

      1. I’m posting details on nested shortcode tomorrow take a look it will give you a better idea of how it needs to work with embedded shortcode

    2. No you can’t do that it would no longer function. What is it that you are trying to do with the nested shortcodes? nesting shortcode is not going to work either it will just break.

  23. Kevin, I think this is EXACTLY what I’ve been hoping to find. Thank you for it.I want to be certain how to use it. When would you use the 2nd one instead of the 1st one? :
    [field “my_key”][field “my_key” post_id=1]

    Thank you.

    1. Well if you add the shortcode to a post you can use  [field “my_key”] my_key is the name of the custom field. The other method [field “my_key” post_id=1] will let you define the post ID to get a specific posts custom field value.

      1. Could you have HTML code in a custom field that “outputs”? For example:

        Today is the greatest day in the world.
        Blah
        [field “list_of_images”]
        The images above are grand, aren’t they?
        Blah
        [field “html_block1”]
        Blah
        [field “html_block2”]
        Thanks for reading my blog.

        And, just to be clear, if you don’t add a “post_id=”, it’ll just pull the custom field for the post/page you’re already on–the current post, right?

        1. 1. With no ID yes it will just pull the current posts custom field.
          2. I can’t see why not should work fine you should be able to anything in the field and it will display.

        2. I guess what I’m asking is if it renders custom field content as if it were entered in the Visual Editor or as if it was entered in the HTML Editor.

        3. No it will render HTML just fine.

  24. Adding this code in function.php disable my website. What was I doing wrong?

    Shovan Sargunam
    from http://tamilbabyname.org team

    1. Are you getting any errors?

      1. A ) is missing in line 6, before return;

        Works fine besides that 🙂

        1. Cool thanks, updated the snippet,

  25. Tweets that mention Wordpress Get custom field value with shortcode – wpsnipp.com Wordpress code snippets for your blog -- Topsy.com janvier 20, 2011 à 6:14 pm

    […] This post was mentioned on Twitter by wp_freak, WPSNIPP. WPSNIPP said: #wordpress Get custom field value with shortcode http://bit.ly/fWRRa3 #blog please RT 🙂 […]

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !