3

I'm making a website and want to display Events. Therefore I made a Custom Post Type called 'event'.

I'm querying events to show them in a page. The Events I made also have some custom fields like : 'Location', 'Day', 'Month', 'Year' and a category.

This is my code now :

    <?php
        $args = array(
          'post_type' => 'event', 
        );

        $events = new WP_Query( $args );

        if( $events->have_posts() ) {
          while( $events->have_posts() ) {
            $events->the_post();

            ?>
              <div class='event'>
                  <div class="event-date">

                  </div>
                  <div class="event-content">
                        <div class="event-title"><?php the_title() ?></div>
                        <div class="event-info">
                            <span>Location: </span>
                            <span>Category: </span>
                        </div>
                  </div>
              </div>
            <?php
          }
        } else {
          echo 'No events!';
        }
      ?>

Which only gives me the title. How can I display the custom fields and the category ?

I am fairly new to WordPress development, used to programming in .NET.

Thx for any help!

1 Answer 1

8

Custom fields are saved in the post_meta table. In your query you got the post title and post ID, so now you have to get post meta.

Use:

<?php
get_post_meta( get_the_ID(), '_location', true );
?>

same for the rest of your custom fields only '_location' will change according to field you are getting. Read more about post meta here

8
  • I will try this function. What about using get_post_custom() ? Commented Dec 22, 2016 at 10:05
  • you can use this function as well, you have both options
    – fmeaddons
    Commented Dec 22, 2016 at 10:07
  • Thx! This both seems to work but I'm having trouble reading the exact value out of the array. Commented Dec 22, 2016 at 10:11
  • I think you have to use get_post_meta() so you can get exact value for the custom field. this will reduce your work to get value from array when you use get_post_custom().
    – fmeaddons
    Commented Dec 22, 2016 at 10:13
  • Yes, indeed. But this var_dump($day); returns me string(1) "4" and <?php $day ?> returns nothing. I am missing something here.. Sry I am still a newb. Commented Dec 22, 2016 at 10:16

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.