在WordPress中,如果你想要获取当前自定义分类法(Taxonomy)的一级父分类的ID,你首先需要了解WordPress是如何处理分类法(taxonomies)和术语(terms)的。分类法(taxonomies)是如“category”和“post_tag”这样的东西,而术语(terms)则是这些分类法下的具体项,如特定的分类或标签。

假设你想要获取某个自定义分类法(例如“my_custom_taxonomy”)下某个术语(term)的一级父术语的ID,你可以使用WordPress的get_ancestors函数。这个函数会返回一个术语的所有父术语的ID数组。

下面是获取上级分类法的ID

&lt;p&gt;</pre>
<pre class="prettyprint"><span class="com">// 获取该术语的所有父术语ID </span><span class="pln">
$parent_term_ids </span><span class="pun">=</span> <span class="wp_keywordlink_affiliate"><a title="View all posts in get_ancestors" href="https://www.mobantu.com/tag/get_ancestors" target="_blank" rel="noopener"><span class="pln">get_ancestors</span></a></span><span class="pun">(</span><span class="pln"> $term_id</span><span class="pun">,</span> <span class="str">'my_custom_taxonomy'</span> <span class="pun">);</span> 

<span class="com">// $parent_term_ids数组的第一个元素就是一级父术语的ID </span>
<span class="kwd">if</span> <span class="pun">(</span> <span class="pun">!</span><span class="pln">empty</span><span class="pun">(</span><span class="pln">$parent_term_ids</span><span class="pun">)</span> <span class="pun">)</span> <span class="pun">{</span><span class="pln"> 
$top_parent_id </span><span class="pun">=</span><span class="pln"> $parent_term_ids</span><span class="pun">[</span><span class="lit">0</span><span class="pun">];</span><span class="pln"> 
echo </span><span class="str">"一级父术语的ID是: "</span> <span class="pun">.</span><span class="pln"> $top_parent_id</span><span class="pun">;</span> 
<span class="pun">}</span></pre>
<pre>&lt;/p&gt; 

下面是获取顶级分类法的ID

<p></pre>
<pre class="prettyprint"><span class="pln">$parent_term_ids </span><span class="pun">=</span><span class="pln"> get_ancestors</span><span class="pun">(</span><span class="pln"> $term_id</span><span class="pun">,</span> <span class="str">'my_custom_taxonomy'</span> <span class="pun">);</span> 

<span class="com">// 如果存在父术语,那么最后一个父术语就是顶级父术语 </span>
<span class="kwd">if</span> <span class="pun">(</span> <span class="pun">!</span><span class="pln">empty</span><span class="pun">(</span><span class="pln">$parent_term_ids</span><span class="pun">)</span> <span class="pun">)</span> <span class="pun">{</span><span class="pln"> 
$top_parent_id </span><span class="pun">=</span> <span class="kwd">end</span><span class="pun">(</span><span class="pln">$parent_term_ids</span><span class="pun">);</span> <span class="com">// end()函数返回数组中的最后一个元素 </span><span class="pln">
echo </span><span class="str">"顶级父术语的ID是: "</span> <span class="pun">.</span><span class="pln"> $top_parent_id</span><span class="pun">;</span> 
<span class="pun">}</span></pre>
<pre></p> 

 

 

相关新闻

在线客服
在线客服
SHARE
TOP