Bibek
Bibek

Reputation: 61

How to get value in url from php in wordpress?

I want to get the value of url from php in wordpress. url: https://www.domain.com/category/cricket/

I want to get cricket value from url i tried by

<?php $value=$_GET['cat']; ?>

Above code worked fine when i set url to defult (https://www.domain.com/?cat=17) in wordpress but didn't worked when it is set to "pretty permalinks" (https://www.domain.com/category/cricket/).

How can i get the value of url in wordpress from php when it set to "pretty permalinks" (https://www.domain.com/category/cricket/)

Thank you in advance. :)

Upvotes: 0

Views: 136

Answers (2)

Heidar
Heidar

Reputation: 689

This is what you need to do:

<?php
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID; //the category id
$cat_name = $cat->name; //the category name
$cat_slug = $cat->slug; //the category slug
?>

Upvotes: 0

rnevius
rnevius

Reputation: 27092

You can use get_query_var() to get the category ID, and then get_category() to get the category object:

if ( is_category() ) {
    $category = get_category( get_query_var('cat'), false );
    echo $category->slug;
}

Alternatively, you can use get_queried_object() to get the current category:

$category = $wp_query->get_queried_object();
echo $category->slug;

Upvotes: 1

Related Questions