1

I have a custom WordPress post array that looks like this:

Array ( 
[1] => Array ( 
    [sno] => 1 
    [post] => WP_Post Object ( 
        [ID] => 1452 
        [post_author] => 12 
        [post_date] => 2017-06-04 18:09:47 
        [post_date_gmt] => 2017-06-05 01:09:47 
        [post_content] => Content here 
        [post_title] => Title here 
        [post_excerpt] => 
        [post_status] => publish 
        [comment_status] => open 
        [ping_status] => closed 
        [post_password] => 
        [post_name] => title-here 
        [to_ping] => 
        [pinged] => 
        [post_modified] => 2017-07-14 09:35:35 
        [post_modified_gmt] => 2017-07-14 16:35:35 
        [post_content_filtered] => 
        [post_parent] => 0 
        [guid] => https://urlhere.com&p=1452 
        [menu_order] => 0 
        [post_type] => sfwd-lessons 
        [post_mime_type] => 
        [comment_count] => 0 
        [filter] => raw 
    ) 
    [permalink] => https://urlhere.com/ 
    [sub_title] => 
    [status] => notcompleted 
    [sample] => is_not_sample 
    [lesson_access_from] => 
    )
)   

I am trying to loop through the posts in this array with this logic. If 'status' equals 'completed' output title and link of post. I think a basic foreach loop should work, but it doesn't seem to be working. The array is created like this:

$lessons = learndash_get_course_lessons_list( $course_id );

My foreach loop looks like:

foreach ($lessons as $key => $lesson) {
  echo $lesson["post_title"];
}

This doesn't return anything though. What do I need to do to loop through the array data?

  • modify your loop as follows: foreach ($lessons as $lesson) { echo $lesson['post_title']; } – Den Isahac Jul 17 '17 at 19:07
  • @DenIsahac I had that in a previous iteration. It doesn't output anything. Is it because there are two levels of the array? Do I need nested foreach loops? – Andrew Jul 17 '17 at 19:11
  • Yep, try it with another foreach nested – Cesar Henrique Damascena Jul 17 '17 at 19:21
  • What you're doing in your foreach loop is accessing the $lesson as value contained in the $key array. – Den Isahac Jul 17 '17 at 19:21
2

Based on what you said about a post being completed, you can check if its status is completed and if it is, then point to the title:

foreach ( $lessons as $lesson ){
    if( $lesson['status'] == 'completed' ){
        echo $lesson['post']->post_title;
    }
}
  • This should be the correct solution based on the provided array of data. – Den Isahac Jul 17 '17 at 19:24
  • 1
    Yes, that worked great. I just wan't using the right syntax. Thanks for your help! – Andrew Jul 17 '17 at 19:38
  • My pleasure Andrew. It was because you treated an object like an array :) @Andrew – Jack Johansson Jul 17 '17 at 19:43

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.