게시물의 최상위 카테고리를 얻기 위한 워드프레스 기능?
안녕하세요 저는 게시물의 최상위 카테고리를 찾으려고 합니다.WP 내장 기능을 찾으려고 했지만 실패했습니다.
예를 들면 이런 카테고리가 있습니다.
Parent
sub-1
sub-2
그리고 서브2에 게시물이 있습니다.그래서 저는 sub-2의 ID를 가지고 이 예제에서 "Parent"라는 이름의 최상위 카테고리의 ID를 찾으려고 합니다.
네, 저는 최상위 레벨의 카테고리를 얻기 위해 저만의 기능을 개발하게 되었습니다.
// function to get the top level category object
// Usage - $top_cat = get_top_category();
// echo $top_cat->slug;
function get_top_category() {
$cats = get_the_category(); // category object
$top_cat_obj = array();
foreach($cats as $cat) {
if ($cat->parent == 0) {
$top_cat_obj[] = $cat;
}
}
$top_cat_obj = $top_cat_obj[0];
return $top_cat_obj;
}
이 도움이 되는 스크립트를 보십시오.단일 게시물의 상위 수준 상위 범주 ID 가져오기
그리고 이 부분을 변경할 수 있습니다.
$catParent = $cat->cat_ID;
로.
$catParent = $cat->name;
최상위 수준 범주의 이름을 가져오려면
이 방법에 문제가 있는 사람들의 경우 저는 효율성 측면에서 최선이 아닌 간단한 해결책을 찾았습니다.게시물/제품 페이지에서 최상위 카테고리 상위를 가져오려면 다음과 같이 하십시오.
용도:
global $post;
$terms = wc_get_product_terms( $post->ID, 'product_cat', array( 'orderby' => 'parent', 'order' => 'DESC' ) );
if ( ! empty( $terms ) ) {
$main_term = $terms[0];
$root_cat_id = get_top_category($main_term->term_id);
기능:
function get_top_category ($catid) {
$cat_parent_id=0;
while ($catid!=null & $catid!=0) {
$current_term = get_term($catid);
$catid = $current_term->parent;
if($catid!=null & $catid!=0){
$cat_parent_id = $catid;
}else{
$cat_parent_id = $current_term->term_id;
}
}
return $cat_parent_id;
}
이거 먹어봐요.
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0 //this parameter is important for top level category
)
);
오늘 좋은 대답은 다음과 같습니다.
$cats = get_the_terms( false, 'category' );
$topcat = array();
foreach($cats as $cat)
{
if ($cat->parent == 0)
$topcat = $cat;
}
get_the_category는 게시물이 "sub2"에만 있는 경우 "sub1" 카테고리를 반환하지 않기 때문에 "sub2"가 "sub1"의 하위 카테고리인 경우에도 마찬가지입니다.그리고 get_cat_로 고양이 아이디를 받으실 수 있습니다.아이디...
$top_category = get_the_category_list(',');
echo $top_category;
부모님의 신분증이 필요했고 이것은 저에게 훌륭하고 간단했습니다.
$topcat = get_the_category();
echo $topcat[0]->category_parent;
언급URL : https://stackoverflow.com/questions/8823452/wordpress-function-to-get-top-level-category-of-a-post
'programing' 카테고리의 다른 글
Http의 본문.Angular2에서 DELETE 요청 (0) | 2023.09.21 |
---|---|
PowerShell의 Format-List에서 출력을 문자열로 가져오려면 어떻게 해야 합니까? (0) | 2023.09.21 |
cst디오 스트림 vs ios 스트림 스트림 스트림? (0) | 2023.09.21 |
Windows에서 Rust에서 MariaDBC Connector로의 링크가 실패함 (0) | 2023.09.21 |
SQL: null로 설정된_number로 변환할 수 없는 경우 (0) | 2023.09.21 |