Support » Developing with WordPress » How to display Custom Meta Field Key and Value when using array

  • xii

    (@thehiicompanyca)


    What would syntax look like when aiming to echo $variable with array containing multiple $var# = get_post_meta( get_the_ID(), ‘var#’, true). Currently I am able to echo array $var#, however after much research and testing if get_post_custom_keys(), get_post_meta(), and other similar functions I am confused about how to display $var# key.

    Below is code snippet of what is currently producing partially intended results.

    if ( have_posts() ) :
    
    while ( have_posts() ) :
    	the_post();
    	$special_category_slug = get_post_special_category_slug();
    
    $cpmf = array(    
            $var1 = get_post_meta( get_the_ID(), 'var1', true),
            $var2 = get_post_meta( get_the_ID(), 'var2', true),
            );
    
       if( ! empty( $cpmf ) ) {
        		echo '<h3>VAR1:</h3>' . $var1;
        		echo '<h3>VAR2:</h3>' . $var2;
          }
    

    echo is accurately displaying $var# custom meta field value, how can the custom meta field key be displayed only when there is a value associated with key?

    • This topic was modified 2 weeks, 6 days ago by xii.
Viewing 10 replies - 1 through 10 (of 10 total)
  • Dion

    (@diondesigns)

    Based on the code you provided, the $cpmf array makes no sense, and this would accomplish what you want:

    	$var1 = get_post_meta(get_the_ID(), 'var1', true),
    	$var2 = get_post_meta(get_the_ID(), 'var2', true),
    
    	if( !empty($var1) ) {
    		echo "<h3>VAR1:</h3>$var1";
    	}
    	if( !empty($var2) ) {
    		echo "<h3>VAR2:</h3>$var2";
    	}

    If the $cpmf array is needed in code you did not provide, then adjust the above accordingly.

    Thread Starter xii

    (@thehiicompanyca)

    Hi @diondesigns,

    Your response works, how can this be achieved without multiple if statements (ex. $var1, $var2, etc.)? bc there will be an increasing amount of custom variables with custom meta field values.

    In original code snippet, $var_name is displayed even if $var_value is empty… how to display $var_name, only if $var_value has data retrievable, otherwise both fields should not be displayed?

    
    $cpmf = array(    
            $var1_name = get_post_meta( get_the_ID(), 'var1_value', true),
            $var2_name = get_post_meta( get_the_ID(), 'var2_value', true),
            );
    

    Clarification
    I thought code snippet of $cpmf array is declaration of $var1 (custom meta field name) and $var1(custom meta field value) was pulling $var1 value via get_post_meta(….var1, true) within while loop. I’ve adjusted the code snippet in an effort to distinguish name and value.

    $var1_name has $var1_value, which is input data from wp custom meta value fields.

    How do I achieve custom meta ‘name’ field display only when custom meta ‘value’ field has data entered/ available for display, otherwise ‘name’ and ‘value’ should not be displayed if either are empty?

    Edit Below
    Edit

    
    $cpmf = array(    
                    "testKey1" => get_post_meta( get_the_ID(), 'testValue1', true),
                    "$testKey2" => get_post_meta( get_the_ID(), 'testValue2', true),
                    $testKey3 => get_post_meta( get_the_ID(), 'testValue3', true),
                } 
    
    foreach( $cpmf as $cpmfKey => $cpmfValue ){
                    echo "$cpmfKey = $cpmfValue<br>";
    
    

    Results from testing:
    “testkey1” displays literal and get_post_meta, however custom meta name field is not dynamically generated.

    if I try to call “$testKey2” as typed in custom meta name field input with $variable declaration, only get_post_meta() displays field value and not name (aka $testKey2).

    And if I try to call $testKey3, neither name or value of custom meta field is displayed, which I presume is because no quotes. Sorry for the long verbose description of my “troubleshooting”. How do I dynamically generate the custom meta “name” field?

    • This reply was modified 2 weeks, 4 days ago by xii.
    • This reply was modified 2 weeks, 4 days ago by xii. Reason: add on of "troubleshooting"
    • This reply was modified 2 weeks, 4 days ago by xii.
    • This reply was modified 2 weeks, 4 days ago by xii. Reason: typo
    Dion

    (@diondesigns)

    You’re on the right track. The following should do what you want:

    	$cpmf = array(
    		'var1' => get_post_meta(get_the_ID(), 'var1', true),
    		'var2' => get_post_meta(get_the_ID(), 'var2', true),
    	);
    
    	foreach($cpmf as $key => $val) {
    		${$key} = $val;
    		if( !empty($val) ) {
    			echo "<h3>{$key}:</h3>$val";
    		}
    	}

    The ${$key} = $val; line will create variables $var1 and $var2.

    Dion

    (@diondesigns)

    The above can be further condensed because the $post variable is created by the “loop”. The code below is much perferred because it avoids calling get_post_meta(), which saves a potentially large number of DB queries.

    	$cpmf = array('var1', 'var2');
    
    	foreach($cpmf as $key) {
    		${$key} = $val = $post->$key;
    		if( !empty($val) ) {
    			echo "<h3>{$key}:</h3>$val";
    		}
    	}
    Thread Starter xii

    (@thehiicompanyca)

    Hi @diondesigns,

    ${key} = $val; code that created variables from $var# worked exceptionally well. Thank you for bestowing your wisdom and patience upon me. This may seem a really simple question in lieu of above achievement.

    How do I encapsulate every and all instances of key/value pairs within the foreach loop? I’ve isolated each single instance within html tags, however am having some glitches on how to enclose all key/value pairs within $cpmf loop.

    What am I missing?

    foreach( $cpmf as $cpmfKey => $cpmfValue ){
      ${$cpmfKey} = $cpmfValue;
        if( ! empty( $cpmfValue) ) {
          echo "<div class='cpmf'><h3>{$cpmfKey}:</h3>$cpmfValue</div>";
          }
        }
    

    Other attempts to apply html tags to enclose all of $cpmf include ul/ li, div(with inline-block), and for giggles tried to enclose the foreach loop with html tag, which gave an error.

    I am aiming to enclose and control this foreach loop as a block element, how would this be achievable, given above loop?

    Dion

    (@diondesigns)

    I think the following code within the foreach() loop would do what you want. Adjust it as required.

    ${$cpmfKey} = $cpmfValue;
    echo '<div class="cpmf">';
    if( !empty($cpmfValue) ) {
    	echo "<h3>{$cpmfKey}:</h3>$cpmfValue<br />";
    }
    else {
    	echo "<h3>{$cpmfKey}:</h3>(No Value)<br />";
    }
    echo '</div>';
    Thread Starter xii

    (@thehiicompanyca)

    Hey @diondesigns,

    Code snippet above does enclose each key/value pair within the foreach loop in html tags, however it populates wrappers for key/value pairs that have no data available (which we resolved earlier in this thread).

    I was able to achieve what you suggested as detailed in below snippet:

    
    foreach( $cpmf as $cpmfKey => $cpmfValue ){
      ${$cpmfKey} = $cpmfValue;
        if( ! empty( $cpmfValue) ) {
          echo "<div class='cpmf'><h3>{$cpmfKey}:</h3>$cpmfValue</div>";
        }
      }
    

    How do I achieve below with ‘cpmfWrapper’, so that it encloses all iterations of foreach loop with one wrapper, excluding key/value pairs that have no data available to display, given the if( !empty ($cpmf) ) statement?

    How do I achieve this => <div class=”cpmfWrapper”> encloses all <div class=”cpmf”> :

    
    <div class="cpmfWrapper">
     <div class='cpmf'><h3>cpmfKey1:</h3>cpmfValue1<br /></div>
     <div class='cpmf'><h3>cpmfKey2:</h3>cpmfValue2<br /></div>
     <div class='cpmf'><h3>cpmfKey3:</h3>cpmfValue3<br /></div> <!-- if no value, key/value pair omitted -->
     <div class='cpmf'><h3>cpmfKey4:</h3>cpmfValue4<br /></div> <!-- empty key/value pair handled by -->
     <div class='cpmf'><h3>cpmfKey5:</h3>cpmfValue5<br /></div> <!-- if (! empty () ) statement  -->
    </div>
    
    • This reply was modified 2 weeks ago by xii. Reason: Clarification of html tag placement
    Thread Starter xii

    (@thehiicompanyca)

    Hi @diondesigns,

    Stumbled upon this to resolve html tags <div class="cpmfWrapper"> desired for wrapping <div class="cpmf"> not sure how I brain farted on this.

    Is there a more elegant way of executing this operation?

    
    echo '<div class="cpmfWrapper">'; 
      foreach( $cpmf as $cpmfKey => $cpmfValue ){
        ${$cpmfKey} = $cpmfValue;
          if( ! empty( $cpmfValue) ){
            echo "<div class='cpmf'><h3>{$cpmfKey}:</h3>$cpmfValue</div>";
        }
      }
    echo '</div>';
    

    Updating post for future reference.

    Little Package

    (@littlepackage)

    Hi @thehiicompanyca

    I’m done here seeing as you have duplicate threads on the same topic.

    https://wordpress.org/support/topic/how-to-dynamically-generate-custom-meta-name/#post-15622312

    Please respect that we are not here to provide you with free PHP coding, or to teach you how to code, and go to jobs.wordpress.net or codeable.io… and pay a professional for help.

    Moderator bcworkz

    (@bcworkz)

    This topic is closed as duplicate. Anyone wishing to continue may do so in the topic linked in the above reply.

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘How to display Custom Meta Field Key and Value when using array’ is closed to new replies.