0

I have a custom post type in WordPress and I'm using a loop in a function so that I can call the listings using a shortcode.

I am adding to a string using .= as I have read around that this is the best way to do it.

The problem is that it isn't formatting the code in the correct format, please see code below.

$args = array( 'post_type' => 'gms_product', 'posts_per_page' => 30 );
$loop = new WP_Query( $args );

function get_the_products() {
    global $loop;
    $code = '';
    while ( $loop->have_posts() ) : $loop->the_post();
        $code .=    '<a href="#"><h3>'.the_title().'</h3></a>';
    endwhile;
    return $code;
}

The output looks like this.

post1post2 <a href="#"><h3></h3></a><a href="#"><h3></h3></a>

1 Answer 1

3

Try with get_the_title()

$code .=    '<a href="#"><h3>'.get_the_title().'</h3></a>';
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed, the difference between the_title() and get_the_title() is that the latter is used to get the title of a post outside of the loop
As a side note, although it's not a common practice, you can pass false as the third parameter of the_title so that it does not echo the title. Here, I'd use get_the_title too though.

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.