Hướng dẫn Redirect Attachment Pages đến The Parent Post URL

Written by admin
Posted on Tue, 06/01/2021 - 09:41

Share Everywhere

Table of contents

To redirect attachment pages to the parent post URL, there are at least 5 different solutions to choose from:

  1. Write a custom function with conditional tag using both the wp_redirect function and template_redirect function.
  2. Add 1 line of redirect code directly to your themes attachment or image.php file.
  3. Use the settings in the WordPress SEO by Yoast plugin if installed.
  4. Install the Attachment Page Redirect plugin or similar.
  5. 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 );

2. Add Redirect to image.php

  1. Create a new file using a code editor.
  2. Copy the code from the View raw link in the Gist labelled image.php
  3. 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

Attachment Page Redirect plugin

4. Attachment Page Redirect plugin

5. Genesis Attachment File With Redirect

  1. Create a new file named attachment.php using a code editor like Notepad++
  2. Copy the PHP from the view raw link in the Gist.
  3. Paste the code into the file and upload it to the root directory of your child theme
 * 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



Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
9 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
Profile picture for user admin
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”