Home > Back-end >  How to limit the product attbribute in custome template of woocommerce
How to limit the product attbribute in custome template of woocommerce

Time:01-12

I am able to get the attribute by selected custom attribute name like 'color','size','weight' and more in table row but i want to show only 3 rows. my working code is bellow but its showing all of them i just want to show only 3 rows

add_action( 'cw_shop_page_attribute', 'cw_shop_page_attribute', 25 );

function cw_shop_page_attribute() {
global $product;
$display_size = $product->get_attribute('display-size');
$processor = $product->get_attribute('processor-type');
$rearcamera = $product->get_attribute('primary-camera');
$frontcamera = $product->get_attribute('secondary-camera');
$storage = $product->get_attribute('internal-storage-gb');
$m_ram = $product->get_attribute('ram-gb');
$frontcamera = $product->get_attribute('secondary-camera');

if ( $display_size ) {
    echo'<tr ><td ><i ></i></td><td >Display</td>';
    echo'<td >'; printf ($display_size);
    echo'</td></tr>';
   }
if ( $processor ) {
    echo'<tr ><td ><i ></i></td><td >Processor</td>';
    echo'<td >'; printf ($processor);
    echo'</td></tr>';
   }
if ( $rearcamera ) {
    echo'<tr ><td ><i ></i></td><td >Rear Camera</td>';
    echo'<td >'; printf ($rearcamera);
    echo'</td></tr>';
   }  
if ( $frontcamera ) {
    echo'<tr ><td ><i ></i></td><td >Front Camera</td>';
    echo'<td >'; printf ($frontcamera);
    echo'</td></tr>';
   }         

how to show only 3 rows of them and hide if empty

CodePudding user response:

You could try something like this :

add_action( 'cw_shop_page_attribute', 'cw_shop_page_attribute', 25 );
function cw_shop_page_attribute() {
global $product;
$attributes = array(
    'display-size' => 'Display',
    'processor-type' => 'Processor',
    'primary-camera' => 'Rear Camera',
    'secondary-camera' => 'Front Camera',
    'internal-storage-gb' => 'Storage',
    'ram-gb' => 'RAM',
);
$counter = 0;
foreach($attributes as $attribute_name => $attribute_label) {
    $attribute_value = $product->get_attribute($attribute_name);
    if( !empty($attribute_value) && $counter < 3 ) {
        echo '<tr ><td ><i ></i></td>';
        echo '<td >' . $attribute_label . '</td>';
        echo '<td >' . $attribute_value . '</td></tr>';
        $counter  ;
    }
}
}

CodePudding user response:

get_attribute() returns a comma separated string of the values, so you can use php's explode function to loop through the values as an array and then bail after 3 results have been returned.

For example:

if ( $display_size ) {
    echo'<tr ><td ><i ></i></td><td >Display</td>';
    $display_size_array = explode( ',', $display_size );
    $count = 0;
    foreach ( $display_size_array as $attribute ) {
        if ( $count >= 3 ) {
            break;
        }
        echo'<td >' . $attribute . '</td';
        $count  ;
    }
    echo'></tr>';
}
  • Related