Shwan Namiq
Shwan Namiq

Reputation: 631

Store tags slugs and names from get_the_tags function in the new array

I created new array named $YPE_slugs_names to store tags slug and tags name from get_the_tags(); function within it, In which tags slug set to $YPE_slugs_names keys and tags name set to $YPE_slugs_names values. I tried this code below but don't work with me (I used this code within loop because don't need post ID)

<?php
    $YPE_slugs_names = array();
    $YPE_tags = get_the_tags();
    if ($YPE_tags) {
        foreach($YPE_tags as $YPE_tag) {
            $YPE_slugs_names[] = $YPE_tag->slug[$YPE_tag->name];
        }
    }
?>

Upvotes: 0

Views: 1031

Answers (1)

Erik van de Ven
Erik van de Ven

Reputation: 4975

You should probably want this, if I understand your question correctly.

<?php
    $YPE_slugs_names = array();
    $YPE_tags = get_the_tags();
    if ($YPE_tags) {
        foreach($YPE_tags as $YPE_tag) {
            $YPE_slugs_names[$YPE_tag->slug] = $YPE_tag->name;
        }
    }
?>

According to https://developer.wordpress.org/reference/functions/get_the_tags/, get_the_tags() returns something like this:

/*
This above prints the tag objects for post ID #24 (if post has any tags):
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 108
            [name] => tag-1
            [slug] => tag-1
            [term_group] => 0
            [term_taxonomy_id] => 109
            [taxonomy] => post_tag
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [object_id] => 24
        )

    [1] => WP_Term Object
        (
            [term_id] => 109
            [name] => tag-2
            [slug] => tag-2
            [term_group] => 0
            [term_taxonomy_id] => 110
            [taxonomy] => post_tag
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [object_id] => 24
        )

)
*/

So my code will generate an array like this (name as value, slug as key):

Array
    (
        [tag-1] => tag-1,
        [tag-2] => tag-2
    )

Upvotes: 2

Related Questions