简体   繁体   中英

Get only selected child category from the parent category

first of i am no a developer i got of my friend ,i can get all the child category of category id "1292" with but its working fine, but i want to display only some of category i select from the category "1292"

<?php
$term_id = 1292;
$taxonomy_name = 'product_cat';
$term_children = get_term_children( $term_id, $taxonomy_name );
foreach ( $term_children as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
$category_thumbnail = get_woocommerce_term_meta($term->term_id,     'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
echo '<div class="col-md-2 col-sm-12">

<div class="ado-prdct-cat">
    <div class="ado-prdct-cat-wrpr">
      <a href="' . get_term_link( $child, $taxonomy_name ) . '">  <img   src="'.$image.'">
    </div>

    <div class="ado-prdct-cat-ttl-wrpr">
    ' . $term->name . '</a>
    </div>
</div>
</div>';
}
?>

category id 1292 has 15 child category and i want some of them to display on page by id from the parent id 1292, if any one know the best way for the same

Where does the selection happen, are you fine with hard coding the IDs to use / skip in your code?

You have the child's term id in $child, just add

if(in_array($child, array(123, 456))) continue;

before

$term = get_term_by( 'id', $child, $taxonomy_name );

to skip over the categories 123 and 456, or use !in_array to only show those and skip the others. You can use a variable instead of array(123, 456) , of course.

Edit: turning this into a shortcode is pretty easy as well:

add_shortcode( "mycategoryprinter" , function($attributes) {
    $skipids = array();
    if(array_key_exists("skipids", $attributes)) {
        $skipids = preg_split("/\s*,\s*/", $attributes["skipids"]);
    }
    $term_id = $attributes["termid];
    $taxonomy_name = $attributes["taxonomy];

    // code goes here, change echo to return

});

Which you can then use with something like

[mycategoryprinter termid="1292" taxonomy="product_cat" skipids="123, 456"][/mycategoryprinter]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM