I am using the following code to do a query on my database from within my page template by using the term_taxonomy_id
which I retrieve from the end of the URL.
My URL looks something like this when using this template http://mysite.com/county/18
with 18 in this case being the term_taxonomy_id
My code is as follows:
<?php
/*
Template Name: County
*/
$ex = explode("/",$_SERVER['REQUEST_URI']);
//print_r($ex);
get_header();
// Global query variable
global $woo_options;
global $wp_query;
global $wpdb;
$all_terms = $wpdb->get_results("SELECT * FROM wp_term_taxonomy,wp_terms WHERE wp_term_taxonomy.parent='{$ex[2]}' AND wp_term_taxonomy.term_id=wp_terms.term_id ORDER BY wp_terms.name");
//echo "SELECT name FROM wp_terms WHERE term_id='{$ex[2]}'";
$taxName = $wpdb->get_results("SELECT name FROM wp_terms WHERE term_id='{$ex[2]}'");
foreach ( $taxName as $tx ) {
$nameTaxnaomy = $tx->name;
}
$getPostID = $wpdb->get_results("SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='{$ex[2]}'");
foreach ( $getPostID as $tx1 ) {
$post = $tx1->object_id;
}
?>
Question:
I however need to change my URL structure to use the term_name at the end of the URL and not the taxonomy_id as above.
So now my URL looks like this http://mysite.com/county/London
When I do this, the database query does not work as it is exploding the URL to get the taxonomy_id at the end (18 in my example above) and then query the DB using that string.
Actual Question: Is there a way to get the term_taxonomy_id
from the term name so I can use it in my db query?
I am thinking something like
//explode the url to get the term name
$dx = explode("/",$_SERVER['REQUEST_URI']);
//now get the id from the term name
$ex = //get the term_taxonomy_id from $dx
Any help appreciated
Cheers
Update – With some tips below I have made the string look like this. My taxonomy name is called location
//define $ex byt ge_term_by
$ex = get_term_by('slug',explode("/",$_SERVER['REQUEST_URI']),'location');
When I echo $ex
I don’t get anything so something wrong still 🙁
I think what you need is to use the get_term_by function from WordPress. You can see the full documentation of it here http://codex.wordpress.org/Function_Reference/get_term_by .
The first 3 values are required, so you would need something like
get_term_by(‘slug’,explode(“/”,$_SERVER[‘REQUEST_URI’]),’your_term_category_here’);
Hope that helps get you started!