Home>

I will ask you a simple question.
I would like to create an attachment page for wordpress images (a page linked to attachment.php) with a permalink like the one below. Is this difficult?

https://hoge.com/ Custom post type/Article ID/1 // First image posted in the article
https://hoge.com/ Custom post type/Article ID/2 // Second image posted in the article
https://hoge.com/ Custom post type/Article ID/3 // Third posted image in the article

The part around the custom post type/article ID/is not important, so don't worry about it! If it seems difficult, I will give up ...! Thank you!

  • Answer # 1

    The structure of the URL is as follows, but for your reference.

    https://hoge.com/ Custom post type/Article ID/Image ID/1 // First image posted in the article
    https://hoge.com/ Custom post type/Article ID/Image ID/2 // Second image posted in the article
    https://hoge.com/ Custom post type/Article ID/Image ID/3 // Third posted image in the article

    The "hoge" in the code below is a custom post type slug.
    Also, rather than "the xth image posted in the article", the number of "the number of images attached in the article" is included in $attach_num.

    function custom_media_link ($link, $attach_id) {
        $post_attach = get_post ($attach_id);
        $parent_post_id = $post_attach->post_parent;
        $parent_post_type = get_post_type ($parent_post_id);
        if ("hoge" == $parent_post_type) {
            $attachment_images = get_attached_media ("image", $parent_post_id);
            $attach_num = count ($attachment_images);
            return home_url ("/ hoge/$parent_post_id/$attach_id/$attach_num /");
        } else {
            return $link;
        }
    }
    add_filter ('attachment_link','custom_media_link', 10, 2);
    function add_rewrite_rules_for_custom_media_link ($rules) {
        $newrules = array ();
        $newrules ['hoge/\ d */(\ d *)/\ d * $'] ='index.php? Attachment_id = $matches [1]';
        return $newrules + $rules;
    }
    add_filter ('rewrite_rules_array','add_rewrite_rules_for_custom_media_link');
    function flush_rewite_rules_for_custom_media_link () {
        $rules = get_option ('rewrite_rules');
        if (! isset ($rules ['hoge/\ d */(\ d *)/\ d * $'])) {
            global $wp_rewrite;
            $wp_rewrite->flush_rules ();
        }
    }
    add_action ('wp_loaded','flush_rewite_rules_for_custom_media_link');