-1

I used this code to display content from my custom fields only where post category id is 5, but all data from the custom fields show above the table in a straight line like a paragraph.

<?php
$post = $wp_query->post; if ( in_category('5') ) {
echo "<table><tr><td> ".the_field('song_title')."</td></td>
        <tr><td>
        <b>Artist: </b> ".the_field('artist')."</td></tr>
        <tr><td>
        <b >Song Title:</b> ".the_field('song_title')."</td></tr>
        <tr><td>
        <b>Song Lenght:</b> ".the_field('song_lenght')."</td></tr></table>
        ";
}  ?>
2
  • 1
    First <tr> is not closed in the first line, you close td tag twice instead of tr
    – anton
    Commented May 2, 2019 at 15:05
  • Welcome to WordPress Stack Exchange! We love to help. But code reviews are considered off-topic as they simply are too localized, whereas this Q+A site seeks to provide canonical answers that also help future readers.
    – leymannx
    Commented May 2, 2019 at 15:37

1 Answer 1

3

Welcome to this community Prezido. the_field() function has echo in it. There is no problem with in_category() function. You need to use get_field() function when you echo the values of fields.

I've updated your code. This version should work as expected.

<?php
    $post = $wp_query->post;
if ( in_category( '5' ) ) {
     echo '<table>
     <tr><td> ' . get_field( 'song_title' ) . '</td></tr>
    <tr><td><b>Artist: </b> ' . get_field( 'artist' ) . '</td></tr>
    <tr><td><b >Song Title:</b> ' . get_field( 'song_title' ) . '</td></tr>
    <tr><td><b>Song Lenght:</b> ' . get_field( 'song_lenght' ) . '</td></tr>
    </table>
    ';  }
2
  • Thanks man, I already used a seperate single.php file to achieve that. I really appreciate your time. Is there a link to a tutorial where i can learn how to create a plugin that will add custom fields to my post. not like a plugin but a code in my theme file? I have been trying to create a custom field that ads itself automatically to my post whenever i choose a specific category. Note, I do not need a plugin for this
    – Prezido
    Commented May 3, 2019 at 6:39
  • You can add an implement of javascript which can add custom fields (with hidden inputs etc) to the post when you select the certain category from WordPress category box. I don't know is there any tutorial about this, but it can be done with some research. Commented May 3, 2019 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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