Search code examples
phpwordpressadvanced-custom-fieldscustom-wordpress-pagescustom-fields

Wordpress how to get "label" of custom fields


I have this code to get the value for custom field myCustomField which works fine:

get_post_meta( get_the_ID(), 'myCustomField', true )

This code gets the value stored in this field.

But now I need a code to dynamically get and echo the Custom field label (not the stored value) which is "My Custom Field".

This code will be fired for this action:

add_action('woocommerce_product_meta_start' , 'add_in_product_page');

Solution

  • If you've created your custom field using ACF plugin, then what you need is the field object. You could call get_field_object function in order to get the object and then find the label returned in the object, like so:

    $your_field_name = "your_custome_field_name"; 
    
    $your_field_object = get_field_object($your_field_name); // You could also pass the field key instead of field name   
    
    
    echo $your_field_object['label']; 
    echo "<br>";  
    echo $your_field_object['value'];
    echo "<br>";  
    echo $your_field_object['key'];
    echo "<br>";  
    echo $your_field_object['type'];
    echo "<br>";  
    echo $your_field_object['ID'];   
    

    You could also read more about this function on the documentation page:

    ACF get_field_object function


    UPDATE

    Translating the returned label to your local language!

    I would usually use these two filter hooks: gettext and ngettext.

    You could read more about these on the documentation page:

    WordPress gettext filter hook
    WordPress ngettext filter hook

    So the translation would be something like this:

    $awesome_label = $your_field_object['label'];
    
    add_filter('ngettext', 'your_theme_custom_translation', 20, 3);
    add_filter( 'gettext', 'your_theme_custom_translation', 20, 3 );
    
    function your_theme_custom_translation( $translated, $text, $domain ) {
      if ( ! is_admin() ) {
        if ( $awesome_label == $translated ){
          $translated = 'etiqueta impresionante'; // This is the place where you could type anything you want in your local language to replace the default english label
        }
      }
      return $translated;
    }