0

How would I include a foreach function inside a variable. The code should explain what I mean.

$list = get_posts('post_type=services&numberposts=-1');
    foreach ($list as $post) :
        $title = $post->post_title; 


    $return = '<li>
                    <a href="#main_content_inner" onClick="slide(this); return false" rel="catalogue_sevices_page">'.$title.'</a>
                </li>';
                endforeach;

That is not quite correct. I am trying to make it so that $return displays all the posts from the type services in the format

  • So effectively I am after::

    $list = get_posts('post_type=services&numberposts=-1');
        foreach ($list as $post) :
            $title = $post->post_title; 
    

    And therefore the output from $return should look something like this

    <li><a href="#content1" onClick="slide(this); return false" rel="catalogue_sevices_page">Title 1</a></li>
    <li><a href="#content2" onClick="slide(this); return false" rel="catalogue_sevices_page">Title 2</a></li>
    <li><a href="#content3" onClick="slide(this); return false" rel="catalogue_sevices_page">Title 3</a></li>
    

    Any ideas,

    2 Answers 2

    4

    you have to use concatenation to store data in a variable with in foreach loop

     $return .= '<li>....
    

    and then return the $return variable before foreach end

     return $return;
    endforeach;
    
    Sign up to request clarification or add additional context in comments.

    Comments

    3

    Simply append with the .= operator.

    $return = '';
    $list = get_posts('post_type=services&numberposts=-1');
    foreach ($list as $post) {
        $title = $post->post_title; 
        $return .= '<li>
                    <a href="#main_content_inner" onClick="slide(this); return false" rel="catalogue_sevices_page">'.$title.'</a>
                </li>';
    }
    return $return;
    

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.