• Hi,

    let’s say current URL is like:

    domain.com/mytitle/yourtitle/histitle

    using get_the_TITLE(), I can only get “histitle”
    how can I get “mytitle” and “yourtitle” from the url?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi,
    It is hard to answer your question because you have not specified what you will be using “mytitle” and “yourtitle” for or where.
    You could store the post url inside a variable with the get_permalink function. You can use this inside or outside the loop: if you use it inside, it will fetch the current post’s permalink, and if you use it outside, you would have to specify a post ID parameter.

    Once you catch the URL, it would only be a matter of processing it. Here’s a way to do it, using the URL you provided as an example:

    <?php
    // Retrieve the post URL
    $post_url = 'domain.com/mytitle/yourtitle/histitle';
    //Removes "https://" and/or "https://" from the URL
    $post_url_proc = str_replace(array('https://','https://'), '', $post_url);
    // Splits the url using "/" as a separator and stores it as an array
    $post_url_proc_array = explode('/', $post_url_proc);
    // Cycles through each chunk of the url array
    foreach ($post_url_proc_array as $url_chunk) {
    // Displays each chunk
    	echo $url_chunk.'<br/>';
    }
    ?>

    That code would output the following HTML:

    domain.com<br/>mytitle</br>yourtitle<br/>histitle<br/>

    Which would look like this on your site:
    domain.com
    mytitle
    yourtitle
    histitle

    The code also removes the “https://&#8221; and/or “https://&#8221; part of the URL. In the final version, you would have to this line, which uses an example:

    $post_url = 'domain.com/mytitle/yourtitle/histitle';

    with

    $post_url = get_permalink();

    inside The Loop, or

    $post_url = get_permalink('9');

    outside The Loop, where 9 is the ID number of the post URL you are trying to fetch.

    To reference each chunk (key) of the URL separately, use $post_url_proc_array followed by the key number between brackets: $post_url_proc_array[0] contains the first chunk, $post_url_proc_array[1] the second, and so on. So, in your URL example, if you wanted to display mytitle - yourtitle, you would go:

    echo $post_url_proc_array[1].' - '.$post_url_proc_array[2];

    Thread Starter 9tontruck

    (@9tontruck)

    thx!

    Hi,

    Were you able to figure this out? If so, could you please mark this thread as resolved?

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘how can I get all levels of title?’ is closed to new replies.