DESCRIPTION

I want to get the name of the slug of the last child of the post’s category.
My categories of my posts represents cities and I am assigning them 3-4 level categories as continent, country, region, and finaly most important category city as you can see here:

Example

Europe
  Italy
    Rome

I am using this working code to display a category image of the posts which speaks about some city on my index page:

<img src="https://wordpress.stackexchange.com/questions/165551/<?php echo bloginfo("url'); ?>/wp-content/uploads/cities/<?php foreach(get_the_category() as $category) {
echo $category->slug . ' ';} ?>-140x140.jpg" alt=" " />

It is fully working and it is giving me a result something like:

….. wp-content/uploads/cities/europe italy rome -140×140.jpg

I am using a folder cities to keep the city images in the “uploads” folder

wp-content/uploads/cities/

GOAL

I am interested only about the cities subcategory, but the name of the slug contains 3 categories which unfortunately are never in the correct parent order and that’s why I would like to make it more simple and I want to only get the name of the last child of those 3 assigned categories/subcategories.

How can I achieve that?

Example of my GOAL – name of the image using the third (the last) child category “representing the city”:

……wp-content/uploads/cities/rome -140×140.jpg

2 Answers
2

Create a custom taxonomy for cities, and then use get_the_terms() to display the term slug in the image URL.

ALTERNATIVE

If you’re only wanting the last slug, you can use PHP for that. Place this at the very top of the file just after get_header() :

<?php
    /* Grab the link. */
    $link = $_SERVER['PHP_SELF'];
    /* Separate the url. */
    $array = explode( "https://wordpress.stackexchange.com/", $link );
    /* Count your way backwards. */
    $last_slug = count( $array ) - 2;
    $the_city = $array[$last_slug];
?>

OR

<?php
    /* Grab the link. */
    $link = $_SERVER['REQUEST_URI'];
    /* Separate the url. */
    $array = explode( "https://wordpress.stackexchange.com/", $link );
    /* Grab the second to last element in the array. */
    $the_city = prev( $array );
?>

USAGE: Use the following for your image tag:

<img src="https://wordpress.stackexchange.com/questions/165551/<?php echo bloginfo("url'); ?>/wp-content/uploads/cities/<?php echo $the_city; ?>-140x140.jpg" alt=" " />

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *