Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Last active January 30, 2024 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuacerbito/3fbf5d655745eb7ffc3923a9e06c2486 to your computer and use it in GitHub Desktop.
Save joshuacerbito/3fbf5d655745eb7ffc3923a9e06c2486 to your computer and use it in GitHub Desktop.
How to include PDF in Wordpress Searches
<?php
if (have_posts()) {
while (have_posts()) {
the_post();
if (get_post_mime_type() == 'application/pdf') {
// Customize how you display PDF files
echo '<a href="' . esc_url(get_permalink()) . '">' . esc_html(get_the_title()) . '</a>';
} else {
// Regular display for posts and pages
// ...
}
}
}
<?php
function include_pdf_in_search($query) {
if ($query->is_search && !is_admin()) {
$post_types = $query->get('post_type');
if (empty($post_types)) {
$post_types = ['post', 'page'];
}
if (!is_array($post_types)) {
$post_types = [$post_types];
}
if (!in_array('attachment', $post_types)) {
$post_types[] = 'attachment';
}
$query->set('post_type', $post_types);
$query->set('post_status', ['publish', 'inherit']);
$query->set('post_mime_type', 'application/pdf');
}
return $query;
}
add_action('pre_get_posts', 'include_pdf_in_search');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment