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.
pre_get_posts
is an action, not a filter, so useadd_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();?>