简体   繁体   中英

WordPress : can't include custom post type loop (using ACF's “the_field”) inside a PHP echo line

I'm learning how to create new custom post types with WordPress + Custom Post Types UI + Advanced Custom Fields, and I'm having a weird problem. Basically I want to be able to add a custom HTML "data-target" attribute (to open modals with Bootstrap) directly from my Wordpress dashboard.

Here is the code :

<div class="slider slider--columns" data-arrows="true" data-paging="true">
<ul class="slides">

<?php 

$args = array(
'post_type' => 'MY_POST_TYPE',
'posts_per_page' => -1 
);

$MYPOSTTYPE = new WP_Query ($args);
if ($MYPOSTTYPE->have_posts() ):
    while ($MYPOSTTYPE->have_posts() ): $MYPOSTTYPE->the_post();

echo '<li class="col-sm-4 col-xs-6" data-toggle="modal" data-target="'.the_field('datatarget_gds').'">';
echo '<div id="MY_ID" style="background-image: url(BGIMAGE.png) !important;"><img style="visibility: hidden;" alt="Image" src="dummyimage.png"></div>';
echo '</li>';


endwhile; endif;
wp_reset_postdata();

?>

</ul>
</div>

But when starting the web page, the values that should appear inside the "data-target" attribute appear just before the opening of the <li> tag, in perfect order by the way. Why ?
Oh and as you can see I'm using Flickity here, starting in the first Div, but I doubt that's the fault.

Thanks !

Okay, well, problem solved. I simply realized the solution was to put that HTML code out of the PHP.

So here is the concrete code :

<div class="slider slider--columns" data-arrows="true" data-paging="true">
<ul class="slides">

<?php 

$args = array(
'post_type' => 'MY_POST_TYPE',
'posts_per_page' => -1 
);

$MYPOSTTYPE = new WP_Query ($args);
if ($MYPOSTTYPE->have_posts() ):
    while ($MYPOSTTYPE->have_posts() ): $MYPOSTTYPE->the_post();

?>

<li class="col-sm-4 col-xs-6" data-toggle="modal" data-target="<?php the_field('datatarget_gds') ?>">
<div id="MY_ID" style="background-image: url(BGIMAGE.png) !important;"><img style="visibility: hidden;" alt="Image" src="dummyimage.png"></div>
</li>

<?php

endwhile; endif;
wp_reset_postdata();

?>

But still, I imagine this may be complicated if for some reason you need to use some PHP echo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM