0

On my demo website i would like to show some custom fields on posts of specific custom post type. And if possible only when they have a filled in value. Demo site: http://www.jsfaber.nl/gibson-eb-2014-120th-anniversary/

What i have so far in single.php is:

<p>
Auteur: <?php echo get_post_meta( $post->ID, 'dublin_core_author', true); ?><br>
Contributor: <?php echo get_post_meta( $post->ID, 'dublin_core_contributor', true); ?><br>
</p>

but this is now shown on alle the posts in the website instead of only on guitar related posts. Can someone please help me?

1

Take a look at the WP's template hierarchy. When a page is requested WordPress searches for the file to load in a specific order. You can create a template specific to your custom post type. You would copy the file called single.php and name the copy single-{post_type}.php where "post_type" is the name of your CPT. This file would then load instead of single.php every time a single custom post type page was requested.

As for only displaying the field, you could check if it has a value in an if() statement. When you validate the feild's value when the post is saved you can check if the user set anything, if they did not then you should set it to something falsy like an empty string.

Then the check in the template file would look something like this:

<?php
    $meta_author = get_post_meta( $post->ID, 'dublin_core_author', true);
    $meta_contributor = get_post_meta( $post->ID, 'dublin_core_contributor', true);
    if ($meta_author != '' && $meta_contributor != '') :
        echo '<p>
              Auteur: ' . $meta_author . '<br>
              Contributor: ' . $meta_contributor . '<br>
              </p>';
    endif;
    ?>

<!--Other template html-->
  • Thanks, you pointed me in the right direction. The specific template for the custom post type succeeded. With your If code both lines of meta tekst would not be shown if one value would not be filled, but with a little twist i got that to work too. Thanks! – JSF Jul 3 '17 at 21:12
  • '<?php $meta_author = get_post_meta( $post->ID, 'dublin_core_author', true); $meta_contributor = get_post_meta( $post->ID, 'dublin_core_contributor', true); if ($meta_author != '') : echo ' Auteur: ' . $meta_author . '<br> '; endif; if ($meta_contributor != '') : echo ' Contributor: ' . $meta_contributor . '<br> '; endif; ?>' – JSF Jul 3 '17 at 21:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.