0
votes

I created a simple load more ajax button for a wordpress theme, using jquery and php. i'm able to load more posts, but im trying to set the div's background image to the posts thumbnail in my functions.php file using echo, however im not sure how? i tried creating the variable and passing it in the url, but it did not work. Heres my code:

add_action( 'wp_ajax_load_more', 'load_more' );

function load_more() {
    // load more posts
    $paged = $_POST['page']+1;
    $ppp = $_POST['ppp'];

    $query = new WP_Query( array(
        'post_type' => 'project',
        'status' => 'publish',
        'order' => 'ASC',
        'posts_per_page' => $ppp,
        'paged' => $paged
    ) );

    if($query->have_posts()):
        while($query->have_posts()): $query->the_post();

            $thumbnail = the_post_thumbnail_url();

            echo '<div class="col-lg-4 col-md-6">';
                echo '<div class="project">';
                    echo '<div class="project-content">';
                        echo '<div class="project-img" style="background:url( THUMBNAIL HERE )">';

                        echo '</div>';
                    echo '</div>';
                echo '</div>';
            echo '</div>';
        endwhile;
    endif;

    wp_reset_postdata();

    die();

```}
2
How do u retrieve the image url ie is it a function, a variable a session/cookie or a constant? - Tito
retrieving it via the $query loop, i set it to the $thumbnail variable and if i echo it out i can see the image url (localhost/websites/site_canada/wp-content/uploads/2019/06/…) ... i just cant seem to set it to the background of the project-img div using 'echo' - juicy j
Does ` echo "<div class='project-img' style='background:url($thumbnail )'>"; ` work - Tito

2 Answers

2
votes

If you want to set a variable equal to a post's thumbnail I think that you need to use the get function:

get_the_post_thumbnail_url()

You could then echo the variable name as the background image:

echo '<div class="project-img" style="background:url(' . $thumbnail . ')">';
0
votes
 echo "<div class='project-img' style='background:url($thumbnail )'>";