Ready to get started?Download WordPress


how to get_post_meta and if else statement (4 posts)

  1. Gram3000
    Posted 2 years ago #


    I'm using this function

    function get_custom_field_data($key, $echo = false) {
    		global $post;
    		$value = get_post_meta($post->ID, $key, true);
    		if($echo == false) {
    			return $value;
    		} else {
    			echo $value;

    to simplify echo*ing* out a custom field. What I think is happening the function is always true and so my else statement never fires.

    <?php if(function_exists('get_custom_field_data')) {
          get_custom_field_data('video', true);
     }  else {
          echo the_post_thumbnail('100%-thumb');
     }  ?>

    I'm lost. How can I make this work?

    Many thanks Graeme

  2. Digital Raindrops
    Posted 2 years ago #

    Would it no be as easy just to test the metadata, instead of using a function?

    By looking at the call it is already inside the loop, so this would be quicker and less code than using another function!

    if( get_post_meta( the_ID(), 'video', true ) ) {
    	echo get_post_meta( the_ID(), 'video', true );
    } else {
        if( has_post_thumbnail() ) the_post_thumbnail('100%-thumb');



  3. alchymyth
    Forum Moderator
    Posted 2 years ago #

    if(function_exists('get_custom_field_data')) is of course always true as long the function's code is either in a plugin or in functions.php of your theme.

    possibly try to check if the 'video' custom field exists for the post:

    <?php if( get_custom_field_data('video') ) {
          get_custom_field_data('video', true);
     }  else {
     }  ?>
  4. Gram3000
    Posted 2 years ago #

    Thanks YOU!

    I thought that the if statement was always true. Due to my lack in knowledge I didn't realize I could call the field label (if that's it name) with the function. I'm learning, which is good.

    @David I had been using the function to cut down on repeat code with lots custom field types. I started using a plugin to handle custom fields to clean up the back end. Now the only field left is video. I could drop the function completely.

    Thanks you very much gentle men!

Topic Closed

This topic has been closed to new replies.

About this Topic