The Page Links To plugin is a great tool for setting the post permalink to an external URL. This way, when the post shows up in archive pages and search results, clicking it goes to that external URL.
You might want to use this feature in a custom metabox with your other metdata, rather than using a separate metabox.
In the code below, the first function removes the Page Links To metabox. The second creates a new metabox using CMB2 containing the URL field. The third function sets the “open in new window” checkbox to true on all posts. If you want this to be optional, remove this third function and add a field to your metabox with a key of _links_to_target
.
<?php | |
/** | |
* Remove "Page Links To" metabox | |
* | |
*/ | |
function be_remove_page_links_to() { | |
remove_meta_box( 'page-links-to', 'post', 'advanced' ); | |
} | |
add_action( 'do_meta_boxes', 'be_remove_page_links_to', 21 ); | |
/** | |
* Link Post Metabox | |
* | |
*/ | |
function be_link_post_metabox() { | |
// Register metabox | |
$metabox = new_cmb2_box( array( | |
'id' => 'be_link_post_metabox', | |
'title' => 'Post Link', | |
'object_types' => array( 'post' ), | |
'context' => 'normal', | |
'priority' => 'high', | |
'show_names' => true, | |
) ); | |
// Link field | |
$metabox->add_field( array( | |
'name' => 'Link', | |
'id' => '_links_to', | |
'type' => 'text', | |
) ); | |
} | |
add_action( 'cmb2_init', 'be_link_post_metabox', 9 ); | |
/** | |
* All links in new window | |
* | |
*/ | |
function be_links_in_new_window( $meta_value, $post_id, $meta_key, $single ) { | |
if( '_links_to_target' == $meta_key ) | |
$meta_value = true; | |
return $meta_value; | |
} | |
add_filter( 'get_post_metadata', 'be_links_in_new_window', 10, 4 ); |