Hướng dẫn Redirect Attachment Pages đến The Parent Post URL
1st Jun 2021To redirect attachment pages to the parent post URL, there are at least 5 different solutions to choose from:
- Write a custom function with conditional tag using both the wp_redirect function and template_redirect function.
- Add 1 line of redirect code directly to your themes attachment or image.php file.
- Use the settings in the WordPress SEO by Yoast plugin if installed.
- Install the Attachment Page Redirect plugin or similar.
- Genesis Users: Create a new attachment.php or image.php file which includes the redirect to post parent URL code and upload it to your child themes root directory.
1. Custom Function With Redirect
Simply copy this PHP code from the view raw link in the Gist and paste it at the end of your child themes functions.php file.
add_action( 'template_redirect', 'wpsites_attachment_redirect' ); function wpsites_attachment_redirect(){ global $post; if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) : wp_redirect( get_permalink( $post->post_parent ), 301 ); exit(); wp_reset_postdata(); endif; }
2. Add Redirect to image.php
- Create a new file using a code editor.
- Copy the code from the View raw link in the Gist labelled image.php
- Paste the code into the file and upload it to your child themes root directory.
<?php wp_redirect( get_permalink( $post->post_parent ), 301 ); exit; ?>
Tested on the Twenty Fourteen default theme for WordPress.
3. WordPress SEO Permalink Settings
4. Attachment Page Redirect plugin
5. Genesis Attachment File With Redirect
- Create a new file named attachment.php using a code editor like Notepad++
- Copy the PHP from the view raw link in the Gist.
- Paste the code into the file and upload it to the root directory of your child theme
<?php /** * This file creates a custom attachment redirect page for any Genesis child theme. * @author Brad Dalton * @example http://wpsites.net/wordpress-tips/5-ways-to-redirect-attachment-pages-to-the-parent-post-url/ * @copyright 2014 WP Sites */ wp_redirect(get_permalink($post->post_parent)); genesis();
Add new comment