Question

I have the following code and need to show THREE things from my custom post type called fact-sheet.

  1. The Title
  2. The summary (fact_sheet_summary)
  3. A file upload URL (fact_sheet_pdf_link)

I can get the first two to work but no idea how to do the third. Basically my output should be...

The Title The Summary paragraph Click here to download as PDF

Any ideas how I can query to list all of these post type results? Is there a better way to do this rather than what I have below? The main problem is, I can't get the URL of the uploaded file.

<?php

$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
));

if($posts)
{


foreach($posts as $post)
{
    echo '<span class="fact-sheet-title">' . get_the_title($post->ID) . '</span><br />';
    echo '<p><span class="fact-sheet-summary">' . the_field('fact_sheet_summary') . '</span></p>';
}
}

?>
Was it helpful?

Solution

I think It's better to use query_posts() as you can use The Loop default structure.

As for the custom fields (Using ACF Plugin), you're using the_field(), which automatically echoes the retrieved field value. You can use, in other hand, the get_field() function, which just returns the value of the field.

You could do something like this:

// Query all posts from 'fact-sheet' post_type
query_posts(array(
    'numberposts' => -1,
    'post_type' => 'fact-sheet',
    'order' => 'ASC',
    // Getting all posts, limitless
    'posts_per_page' => -1,
));

// Loop throught them
while(have_posts()){
    the_post();

    echo '<span class="fact-sheet-title">' . get_the_title() . '</span><br />';
    echo '<p><span class="fact-sheet-summary">' . get_field('fact_sheet_summary') . '</span></p>';
    // Echos the link to PDF Download
    echo '<p><a href="'. get_field('fact_sheet_pdf_link') .'" target="_blank">Click here to download as PDF</a></p>';

}

// Once you're done, you reset the Default WP Query
wp_reset_query();

In case you might need further explanation about wp_reset_query(), check this out.

OTHER TIPS

Can you try this? It's slightly modified from the manual of the WP Codex (not much)

<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();    

 $args = array(
   'post_type' => 'attachment',
   'post_mime_type' => array('application/pdf'),
   'numberposts' => -1,
   'post_status' => null,
   'post_parent' => $post->ID
  );

  $attachments = get_posts( $args );
     if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
           echo '<li>';
           the_attachment_link( $attachment->ID, true );
           echo '<p>';
           echo apply_filters( 'the_title', $attachment->post_title );
           echo '</p></li>';
          }
     }

 endwhile; endif; ?>
</ul>

If it works, maybe it's better to modify a working sample to your needs - by adding your custom fields. Just my thoughts :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top