M
M
Maxim Demidov2019-02-06 23:16:43
WordPress
Maxim Demidov, 2019-02-06 23:16:43

How to display the number (exactly the number) of the Woocommerce product gallery image?

Hello, dear forum users! I had a task to display in the gallery of a single product alt at the image of the product in the form "Product name + Photo (x)", where x is the number of the image in the product gallery. Site on Woocommerce.
I got the name, in principle, quickly

add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
    global $post;
    if ($post->post_type == 'product') {
    $num = "Номер картинки";
    $title = $post->post_title;
        $attr['alt'] = sprintf(" %s  Фото - %s.",$title,$num);
        $attr['title'] = $title;
    }
    return $attr;
}

Everything seems to work and displays The
5c5b3e6247b24294663896.jpeg
question is - how to display instead of $num = "Picture number"; It is the number of the gallery picture (1, 2, 3, etc. depending on the number of pictures in the product gallery). Copal on
<a href="https://codex.wordpress.org/%D0%A1%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D1%87%D0%BD%D0%B8%D0%BA_%D0%BF%D0%BE_%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D1%8F%D0%BC/get_post"></a>
, but I did not find anything in the list of returned fields for the result I needed. Tell me, please, all the brains have already broken.
UPD 7.02.19
Thank you very much Anatoly Pychev!
I didn’t even think about a static function, I made huge constructions with a call to the id of the picture, etc. And everything turned out to be so simple!
The final code looks like this
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
    global $post;
    if ($post->post_type == 'product') {
    $title = $post->post_title;
    static $num = 0;
    $num++;
        $attr['alt'] = sprintf("Фото %d - %s.",$num,$title);
    }
    return $attr;
}

And everything works great. Seo rejoices, everyone dances and dances)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2019-02-07
@MaximusDem

Create a static variable inside the function and increment it by one in every call

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question