Search code examples
phpwordpresstinymceadvanced-custom-fieldswysiwyg

WP Advanced Custom Fields: WYSIWYG Insert link to media


I hope I can explain this properly... and unfortunately I don't have code to show, but I've researched all over and can't find any anything to help. For reference, I'm also using the ACF plugin for WordPress. I have the WYSIWYG set to 'Visual Only' and 'Simple' in ACF.

Essentially, I'm trying to customize the WordPress WYSIWYG menu, in particular the 'Insert/Edit link' button actions. Currently when you click on that button in the WYSIWYG editor, it first shows a mini editor like such:

enter image description here

And when you click on the gear icon 'Link Options' it brings up more options like so:

enter image description here

But the only links in the list are Pages (or posts, but this site doesn't have any posts).

What I'd like to do is also include links to media documents in the list. Something like this must be possible, but I can't for the life of me figure out where to edit this. I imagine it must be some part of TinyMCE but I can't be sure. Has anyone dealt with this?

EDIT: See my comment which includes edits to the accepted answer to see the final product.


Solution

  • Add these to your theme's 'functions.php'.

    // Query for attachments
    add_filter( 'wp_link_query_args', 'my_modify_link_query_args' );
    function my_modify_link_query_args( $query ) {
        $query['post_status'] = array('publish','inherit');
        return $query;
    }
    
    // Link to media file URL instead of attachment page
    add_filter( 'wp_link_query', 'my_modify_link_query_results' );  
    function my_modify_link_query_results( $results, $query ) {
        foreach ( $results as &$result ) {
            if ( 'Media' === $result['info'] ) {
                $result['permalink'] = wp_get_attachment_url( $result['ID'] );
            }
        }
        return $results;
    }