从术语名称中检索分类术语ID?

时间:2012-11-20 10:34:31

标签: php wordpress taxonomy

我使用以下代码通过使用从URL末尾检索的term_taxonomy_id在我的页面模板中对我的数据库进行查询。

使用此模板http://mysite.com/county/18时,我的网址看起来像这样,其中18是term_taxonomy_id

我的代码如下:

 <?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;
 }

 ?>

问题: 但是我需要更改我的URL结构以使用URL末尾的term_name而不是上面的taxonomy_id。

现在我的网址看起来像http://mysite.com/county/London

当我这样做时,数据库查询不起作用,因为它爆炸了URL以在最后获得taxonomy_id(在上面的示例中为18),然后使用该字符串查询数据库。

实际问题:有没有办法从术语名称中获取term_taxonomy_id,以便在数据库查询中使用它?

我在想像

//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 

任何帮助表示赞赏

干杯

更新 - 通过以下一些提示,我将字符串看起来像这样。我的分类名称称为location

//define $ex byt ge_term_by
$ex = get_term_by('slug',explode("/",$_SERVER['REQUEST_URI']),'location');

当我回复$ex时,我什么都没有得到任何错误:(

1 个答案:

答案 0 :(得分:1)

我认为你需要的是使用Wordpress的get_term_by函数。您可以在此处查看http://codex.wordpress.org/Function_Reference/get_term_by的完整文档。

前3个值是必需的,所以你需要类似的东西 get_term_by( '蛞蝓',爆炸( “/”,$ _ SERVER [ 'REQUEST_URI']), 'your_term_category_here');

希望有助于您入门!

相关问题