0

I've written a code in a WP_Query to converting a string (the_content) to an array (choices). But it seems wrong! In fact, the choices array is empty after each loop. However str string is notnull. How can i handle this array to be nutnull? Any help would be appreciated.

$first_query = new WP_Query( $args );
    while ($first_query->have_posts()) : $first_query->the_post();
        the_title();  //echo the title
        the_content();         //echo the content
                $str = the_content(); 
                $choices = explode("-",$str);
                var_dump($choices);     
    endwhile;
2

You have a couple of issues here

  • the_content() echos the content to screen. You should be using get_the_content() which returns the content. Just remember, get_the_content() is unfiltered, so if you need filtered content, use apply_filters( 'the_content', get_the_content() ) which will return filtered content.

  • Your explode() function is probably wrong as well. You are using a hyphen to explode your content into pieces of an array. If your content don't contain hyphens, your array will only have one key with the complete content as value. You would probably need to use white spaces (explode( ' ', get_the_content() );) or regular expressions or something similar to targt more than hypens or white spaces to explode the content. In one of my previous posts for custom excerpts , I have used something similar to explode my content, here is something you can try and experiment with

    preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', get_the_content(), $tokens);
    var_dump( $tokens );
    
0

Try with: $str = get_the_content();

  • 2
    How does your answer differ from mine :-) – Pieter Goosen Jul 27 '15 at 8:40
  • Right, your answer is better than mine. This is for lazy people, like me :), that skips words, reading only codes :) – Ulugov Jul 27 '15 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.