‘preview_post_link’ is a WordPress filter that allows you to modify the URL used for a post preview.
Usage
To use this filter, you need to add a custom function to your theme’s functions.php file or a custom plugin. Then, hook your function to the preview_post_link filter using the add_filter() function.
Here’s a basic code example:
function my_custom_preview_link( $preview_link, $post ) {
// Your custom code goes here
return $preview_link;
}
add_filter( 'preview_post_link', 'my_custom_preview_link', 10, 2 );
Parameters
- $preview_link (string): URL used for the post preview.
- $post (WP_Post): Post object.
Examples
Add a query parameter to the preview URL
function add_query_param_to_preview_link( $preview_link, $post ) {
$preview_link = add_query_arg( 'my_param', 'value', $preview_link );
return $preview_link;
}
add_filter( 'preview_post_link', 'add_query_param_to_preview_link', 10, 2 );
This code adds a query parameter my_param with the value value to the post preview URL.
Change preview URL to a custom domain
function change_preview_domain( $preview_link, $post ) {
$preview_link = str_replace( 'example.com', 'preview.example.com', $preview_link );
return $preview_link;
}
add_filter( 'preview_post_link', 'change_preview_domain', 10, 2 );
This code replaces the domain in the post preview URL with a custom domain (preview.example.com).
Append post ID to the preview URL
function append_post_id_to_preview_link( $preview_link, $post ) {
$preview_link .= '-' . $post->ID;
return $preview_link;
}
add_filter( 'preview_post_link', 'append_post_id_to_preview_link', 10, 2 );
This code appends the post ID to the post preview URL.
Add a custom path to the preview URL
function add_custom_path_to_preview_link( $preview_link, $post ) {
$preview_link .= '/custom-path/';
return $preview_link;
}
add_filter( 'preview_post_link', 'add_custom_path_to_preview_link', 10, 2 );
This code adds a custom path /custom-path/ to the post preview URL.
Change preview URL based on post type
function change_preview_link_based_on_post_type( $preview_link, $post ) {
if ( 'custom_post_type' === $post->post_type ) {
$preview_link = 'https://example.com/custom-preview-url/';
}
return $preview_link;
}
add_filter( 'preview_post_link', 'change_preview_link_based_on_post_type', 10, 2 );
This code changes the post preview URL to a custom URL (https://example.com/custom-preview-url/) if the post type is custom_post_type.