WordPress.org

Ready to get started?Download WordPress

Forums

need help to urlencode the_title and the_category? (6 posts)

  1. gembel
    Member
    Posted 3 years ago #

    Hello,

    I need help to urlencode the_title and the_category,

    for the_category, example:
    <?php the_category(); ?> output will be My Category Name Here
    what i need for the output is My+Category+Name+Here

    same case for the_title, example:
    <?php the_title(); ?> output will be My Post Title Here
    what i need for the output is My+Post+Title+Here

    I hope you guys understand what i mean, Thanks!

  2. stvwlf
    Member
    Posted 3 years ago #

    instead of the_category and the_title, use

    $my_cat = get_the_category();
    and
    $my_title = get_the_title();

    They store the output to variables instead of echoing it.

    Then you can use regular PHP urlencode on the variables.

  3. gembel
    Member
    Posted 3 years ago #

    Hi stvwlf, thanks for your reply, can you give me an example final code for the output i needed? Thanks again

  4. stvwlf
    Member
    Posted 3 years ago #

    <?php echo urlencode( get_the_title() ); ?>

    the_category is different - if a post is in multiple categories it returns a list of all of them. To display the first one in the list encoded:

    <?php
    $category = get_the_category();
    echo urlencode($category[0]->cat_name);
    ?>

    displaying all of them requires a loop

    <?php
    foreach((get_the_category()) as $category) {
        echo urlencode($category->cat_name);
    }
    ?>
  5. gembel
    Member
    Posted 3 years ago #

    Thanks stvwlf, its work! how about the_title? i found this code on google
    <?php echo urlencode(the_title('','', false)) ?>
    this code works, but doo you have better code for urlencode the_title? Thank you so much!

  6. stvwlf
    Member
    Posted 3 years ago #

    The very first line in my previous answer is the code for the title

    <?php echo urlencode( get_the_title() ); ?>`

Topic Closed

This topic has been closed to new replies.

About this Topic