Last active
October 21, 2021 23:17
-
-
Save soderlind/861477f6a8511a14fa257192a4f2379e to your computer and use it in GitHub Desktop.
WordPress: In the editor, using "Insert Link", insert link to a PDF file in the media library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Soderlind\WP_Editor; | |
add_filter( 'wp_link_query', __NAMESPACE__ . '\on_wp_link_query', 10, 2 ); | |
add_filter( 'wp_link_query_args', __NAMESPACE__ . '\on_wp_link_query_args' ); | |
add_filter( 'the_permalink', __NAMESPACE__ . '\on_permalink', 10, 2 ); | |
add_filter( 'attachment_link', __NAMESPACE__ . '\on_permalink', 10, 2 ); | |
/** | |
* Modify the wp_link_query result | |
* | |
* @see on_permalink, which creates the pdf permalink | |
* | |
* @param array $results | |
* @param array $query | |
* @return array | |
*/ | |
function on_wp_link_query( array $results, array $query ) : array { | |
// If attachment is PDF, set info to 'PDF' | |
foreach ( $results as $key => $result ) { | |
if ( isset( $result['ID'], $results[ $key ]['info'] ) && 'application/pdf' == get_post_mime_type( $result['ID'] ) ) { | |
$results[ $key ]['info'] = 'PDF'; | |
} | |
} | |
// remove other media links | |
$results = array_filter( $results, function( $result ) { | |
return ( isset( $result['info'] ) && stripos( $result['info'], __( 'Media' ) ) === false ); | |
} ); | |
return $results; | |
} | |
/** | |
* Include attachments. | |
* | |
* @param array $query | |
* @return array | |
*/ | |
function on_wp_link_query_args( array $query ) : array { | |
$query['post_status'] = [ 'publish', 'inherit' ]; // 'inherit' equal include attachments. | |
return $query; | |
} | |
/** | |
* Automatically convert permalinks to PDFs to the PDF itself, not the Attachment page. | |
* | |
* @param string $permalink | |
* @param mixed $post_id | |
* @return string | |
*/ | |
function on_permalink( string $permalink, $post_id ) : string { | |
if ( is_integer( $post_id ) && 'application/pdf' == get_post_mime_type( $post_id ) ) { | |
// if the result is a PDF, link directly to the file not the attachment page. | |
$permalink = wp_get_attachment_url( $post_id ); | |
} | |
return esc_url( $permalink ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment