PHP / WP连接 - 字符串最终分为两部分
问题描述:
$args = array( 'post_type' => 'object', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo "<div class=\"item\"><a href=\"" . the_permalink() . "\">" . the_title() . "</a></div>";
endwhile;
This loop I have in WP is not echoing
<div class="item"><a href="#mylink">The name of my link</a></div>
but instead
#mylink The Name of my link
<div class="item"><a href=""></a></div>
Am I missing something trivial?
答
I would do it this way (code below), which will show something only if:
- There is at least one published post of type
object
new WP_Query( array(
'post_type' => 'object',
'posts_per_page' => 10,
) );
while ( have_posts() ) :
the_post();
printf(
'<div class="item"><a href="%s">%s</a></div>'
, get_permalink()
, get_the_title()
);
endwhile;
wp_reset_query();
Notes:
- I don't store the WP_Query object since it will not be used
- I use
printf()
for better readibility -
I don't forget to add
wp_reset_query();
which is necessary in most cases
答
Try echoing like this
echo '<div class="item"><a href="'.$mylink.'">'.$myTitle.'</a></div>';