skip to Main Content

I am getting the woo-commerce product title of the first character using wp-query but I have to get repeating and my OUTPUT is AABBBCCCDDEEEEEFFFFFGGGGFFFFHHHHIIIKKLLLXXXY but I want only one character not repeating a character. My desired output should be like "ABCDEFGHIKLXYZ"

$category_query_args = array(‘post_type’ => ‘product’,’posts_per_page’ => -1,’post_status’ => ‘publish’,’orderby’ => ‘title’,’order’ => ‘ASC’,);
$category_query = new WP_Query($category_query_args);
while($category_query->have_posts()):$category_query->the_post();

//Product Title $title = get_the_title(); $firstChar = substr($title,0,1);echo $firstChar; endwhile; wp_reset_query();

2

Answers


  1. I’m using the example string as source, the first part is only to have an array. Just remember the last character. When it comes to the next character, only echo it if it is different to the last.

    $s = 'AABBBCCCDDEEEEEFFFFFGGGGFFFFHHHHIIIKKLLLXXXY';
    $a = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
    print_r($a);
    
    $last = '';
    foreach($a as $c) {
        if ($c != $last) {
            echo $c;
            $last = $c;
        }
    }
    
    Login or Signup to reply.
  2. If you want to get all the unique characters of a string you should use count_chars(). Documentation here

    It should be set to mode 3 to get all the unique characters.
    I used your product title in this example:

    $product_title = 'AABBBCCCDDEEEEEFFFFFGGGGFFFFHHHHIIIKKLLLXXXY';
    
    $product_title = count_chars($product_title, 3);
    
    print_r($product_title);
    

    Output looks like this:
    output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search