Search code examples
phpwordpresspdfwhile-loopcustom-post-type

Wordpress get pdf attached link to post


I'm working late on this for tomorrow so could use the community to help. I have a loop in a plugin that outputs the custom post type and I want to get the attached pdf file associated with the post. I've managed to get the post and most of the pdf attachment working, apart from it's only pulling in the first pdf file and showing it on all the links. I need it to pull the link for the pdf on each of the posts. I'm almost there but I can't seem to get it.

Code is:

global $post;

    $custom  = get_post_custom($post->ID);


    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 10;

    $args = array( 'post_type' => 'trends', 'orderby' => 'title', 'order' => 'asc', 'posts_per_page' => $paged );

    $success = new WP_Query( $args );

    if( $success->have_posts() ) :

    $output  = '';
    $output .= '<table class="custom-table-trend">';
    $output .= '<tr><th>File Name</th><th>Date added</th><th>Download</th></tr>';


        while( $success->have_posts() ) : $success->the_post();

        $query_pdf_args = array(
            'post_type' => 'attachment',
            'post_mime_type' =>'application/pdf',
            'post_status' => 'inherit',
            'numberposts' => 1,
            'posts_per_page' => -1,
            'post_parent'   => $custom
            );

            $query_pdf = new WP_Query( $query_pdf_args );

        foreach ( $query_pdf->posts as $file) {

                    $string = '<td><a href='. $file->guid .'>Download</a></td>';
            }


                $output .= '<tr>';
                $output .= '<td>'. get_the_title() .'</td>';
                $output .= '<td>' . get_the_date() . '</td>';
                $output .= sprintf( $string );
                $output .= '<tr>';



        endwhile;

        $output .= '</tr></table>';

    endif;

        return  $output;

Solution

  • Inside your loop you need to specify the parent id to get the pdfs.your are passing $custom in it which you have initialized outside of the loop try below

    $query_pdf_args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'application/pdf',
        'post_status' => 'inherit',
        'numberposts' => 1,
        'posts_per_page' => -1,
        'post_parent'   => get_the_ID()
    );
    

    get_the_ID Retrieve the numeric ID of the current post. This tag must be within The Loop