1

On my search page, I've added all the file from the media with this code :

    function attachment_search( $query ) {

    $args = array(
        'public'   => true,
        '_builtin' => false,
    );

    $output = 'names';
    $operator = 'and';

    $cpts = get_post_types( $args, $output, $operator );
    $cpts[] = 'attachment';
    $cpts[] = 'post';
    if ( $query->is_search ) {
        $query->set( 'post_type', $cpts );
        $query->set( 'post_status', array( 'publish', 'inherit' ) );
    }

    return $query;
}

add_filter( 'pre_get_posts', 'attachment_search' );

In the media, i've added a sample.pdf file.

The sample is showing, but is shown as a post. I want to only add the dowload link from the PDF. But how to I do this ? wp_get_attachment_url(get_the_ID()) is not working, as the post ( = the PDF ) has no attachment file ?

PS : this is my content-search.php

<?php    
$post_type = ucfirst(get_post_type());

$download = "";
//if(get_post_type() == "attachment"){
    $dowload = wp_get_attachment_url(get_the_ID());
//}
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <h2 class="entry-title m-0">
            <a href="<?=esc_url( get_permalink() ); ?>"  rel="bookmark">
                <?=the_title();?> <?= "(".$post_type.")"; ?>
                " <?php echo $download;?> " <?php the_ID(); ?>
            </a>
        </h2>
    </header><!-- .entry-header -->
</article><!-- #post-<?php the_ID(); ?> -->

The wp_get_attachment_url(get_the_ID()) is returning "" for any document for this file only... Image or PDF.

2
  • A few things I noticed just to tighten things up a bit: 1-- pre_get_posts is an action, not a filter, so use add_action( 'pre_get_posts, ...). 2-- SInce it's an action, there is nothing to return, so remove the return statement; your're already altering the query object directly anyway (which is good). 3-- Don't use PHP's echo shorthand with things that already echo the result, such as <?=the_title();?> Commented Mar 27, 2020 at 16:38
  • 1
    Hmm.. Guess chaning add_filter to add_action solved it ! Commented Mar 27, 2020 at 16:48

1 Answer 1

1

Don't know why, but doing this worked... In my search.php, no problem. In content-search.php, no result.

while (have_posts()) :
    the_post();
    $attachment = wp_get_attachment_url(get_the_ID());
    set_query_var('document', $attachment);
    get_template_part('template-parts/content', 'search');

endwhile;

EDIT

As mention @Dave Romsey, do

add_action( 'pre_get_posts', 'attachment_search' );

instead of

add_filter( 'pre_get_posts', 'attachment_search' );

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.