0

I'm trying to redirect my attachment-id pages to the correct post-id page (woocommerce single page).

I got this URL with the attachment_id = 17381. How do I retrieve the products/post ID, which uses this attachment_id? I've searched for hours, and tried different approaches, but I can't find a solution.

https://www.ejstruplys.dk/no/?attachment_id=17381

I want it to be redirected to this page: https://www.ejstruplys.dk/no/produkt/block-candles-rustic-surface-3/

Doing an var_dump($post) gives me this, but I can't figure out, where this attachment_id -> product ID is located:

OBJECT = WP_Post::__set_state(array(
  'ID' => 17381,
  'post_author' => '1',
  'post_date' => '2015-08-24 19:32:00',
  'post_date_gmt' => '2015-08-24 19:32:00',
  'post_content' => '',
  'post_title' => 'Orange. Bloklys. Rustikk overflate',
  'post_excerpt' => '',
  'post_status' => 'inherit',
  'comment_status' => 'open',
  'ping_status' => 'closed',
  'post_password' => '',
  'post_name' => 'bloklys_rustik_overflade_55_dia_orange-jpg-2',
  'to_ping' => '',
  'pinged' => '',
  'post_modified' => '2015-08-24 19:32:00',
  'post_modified_gmt' => '2015-08-24 19:32:00',
  'post_content_filtered' => '',
  'post_parent' => 0,
  'guid' => 'https://www.ejstruplys.dk/wp-content/uploads/2015/08/bloklys_rustik_overflade_55_dia_orange.jpg',
  'menu_order' => 0,
  'post_type' => 'attachment',
  'post_mime_type' => 'image/jpeg',
  'comment_count' => '0',
  'filter' => 'raw',
  'post_title_ml' => '[:en]Orange. Block candles. Rustic surface[:no]Orange. Bloklys. Rustikk overflate[:sv]Orange. Blokljus. Rustik yta[:de]Orange. Stumpenkerzen. Rustikale Oberfläche[:da]Orange. Bloklys. Rustik overflade[:]',
));

How do I retrieve the post ID from the attachment ID?

Edit: I've tried this one: Get post id by attachment id?

But it just returns null.

1
  • If post_parent is 0 which is has not associated with any post. I mean the attachment is not used in any post.
    – Kvvaradha
    Dec 5, 2015 at 1:34

3 Answers 3

1

It looks like the image (for which you've done a var_dump) is not attached to any post. If an image is attached to a post - the post's ID would appear as 'post_parent', which in this case equals 0. This is often the case if you upload the image directly from withing media library ('Media Library' page in your WP admin) - you can still place such image into post content, use it as post thumbnails, in galleries etc., but this doesn't mean that the image is attached to any post.

To properly attach an image to a post you have to upload it by clicking the 'Add Media' button when creating/editing the post. This is the only way that you can be certain that the image will be labelled as post's attachment.

2
  • Thats very sad. It means I've to re-upload all my attachments? I actually used WP All Import to create my all my products, but if I've redo it all, it'll take me weeks. Are there no other smart approaches? Maybe I could loop through all products, extract their attachment ID's - and compare the attachment ID's?
    – Unicco
    Dec 5, 2015 at 7:40
  • IIRC you do not have to upload, just insert the non associated image to a post with which you want it to be associate. You can also see the association status at the media library admin table Mar 15, 2018 at 3:19
0

WordPress uses the post_parent column in the database to track which posts an attachment is linked to. You can use wp_get_post_parent_id to find an attachment's parent post. Simply pass it the attachment ID.

1
  • wp_get_post_parent_id(get_the_ID()) returns INT = 0
    – Unicco
    Dec 5, 2015 at 7:38
0

Based on the previously answers, I managed to pull this off. Thanks for the replies stating the issue was based on wrong attachments (non-existing post_parent ID's).

In case someone is struggling with the same issue, here is the solution I ended up with:

The method hooks on Wordpress' template_redirect, check if the specific page has an parent_post, and uses two different approaches towards retriving the correct Product Post ID. It works on all "~/?attachment_id" and "~/variation_product"**.

/*
* Redirect Attachment Pages
*/
add_action( 'template_redirect', 'wpse27119_template_redirect' );
function wpse27119_template_redirect() {
    global $post;

    /* Assign the specific post ID to local variable */
    $post_id = get_the_ID();

    /* If page has no attachment - no need to continue */
    if (!is_attachment() ) return false;

    if (empty($post)) $post = get_queried_object();

    /* Instantiating the product object based on currenct post ID */
    $_product = new WC_Product_Variation($post_id);

    /* Check if specific post got an post_parent ~ proper image-attachments and product_variation */
    if ($post->post_parent) {

        /* Retrieve the permalink ~ from the current product-object */
        $link = get_permalink($_product->post->ID);

        /* Redirect the user */
        wp_redirect( $link, '301' );

        exit();

    } else {

        /* Retrieve all product-pages */
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1
        );

        /* Initialize WP_Query, and retrieve all product-pages */
        $loop = new WP_Query($args);

        /* Check if array contains any posts */
        if ($loop->have_posts()): while ($loop->have_posts()): $loop->the_post();
            global $product;

            /* Iterate through all children in product */
            foreach ($product->get_children() as $child_id) {

                /* Retrieve all children of the specific product */
                $variation = $product->get_child($child_id);

                /* Check if variation is an instance of product */
                if ($variation instanceof WC_Product_Variation) {

                    /* Retrieve all image_ids from variation */
                    $variation_image_id = $variation->get_image_id();

                    /* Compare variation image id with the current post id ~ attachment id */
                    if ($variation_image_id == $post_id) {

                        /* Retrieve the correct product - using the post id */
                        $_product = new WC_Product_Variation($post_id);

                        /* Retrieve the permalink ~ from the current product-object */
                        $link = get_permalink($_product->post->ID);

                        /* Redirect the user */
                        wp_redirect($link, '301');

                        exit();

                    }


                }


            }

        endwhile; endif; wp_reset_postdata();

    }

}

I'm trying to parse the variations arguments to the redirect method. I'll update this post, if I find a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.