ST80
ST80

Reputation: 3903

Wordpress use query as AJAX

I have a custom field selectbox where I chose which Posts I want to be displayed. Now I want the query, where I get the selected Posts and its custom fields, to somehow be used as an AJAX-call so that I can use the data-output to build a masonry-grid. Is that possible?

here is my data/query:

$posts = get_field('choose_artist');

if( $posts ): ?>
<?php foreach( $posts as $p ): ?>
    <div class="artist">
        <a href="<?php echo get_permalink( $p->ID ); ?>">
                <div style="position: relative;">
                    <?php $image = get_field('artist_image', $p->ID); ?>
                    <div class="artist-image" style="background-image:url('<?php echo $image['url']; ?>')"></div>
                    <div class="overlay">
                        <div class="content">
                            <p><?php the_field('artist_name', $p->ID); ?></p>
                        </div>
                    </div>
                </div>
            </a>
    </div>
<?php endforeach; ?>

So, my goal is something like:

$.ajax({
 url: '/the query above',
 success: function(data){
     data is the query html
 }})

Is that even possible?

Upvotes: 0

Views: 56

Answers (1)

Adam
Adam

Reputation: 1304

ajax.php

     $content = '';
     if( $posts ) {
        foreach( $posts as $p ) {
            $image = get_field('artist_image', $p->ID);
            $content .= '<div class="artist">';
            $content .= '<a href="' . get_permalink( $p->ID ) . '">';
            $content .= '<div style="position: relative;">';
            $content .= '<div class="artist-image" style="background-image:url("' . $image['url'] . '")"></div>';
            $content .= '<div class="overlay">';
            $content .= '<div class="content">';
            $content .= '<p>' . get_the_field('artist_name', $p->ID). '</p>';
            $content .= '</div>';
            $content .= '</div>';
            $content .= '</div>';
            $content .= '</a>';
            $content .= '</div>';
        }   
     }
     echo $content;

main.js / .php (whereever you have the ajax call)

$.ajax({
 url: '/ajax.php', //Path to the ajax.php script
 success: function(data){
     console.log(data);
 }});

Check the documentation for how to catch errors, check for success etc. etc: http://api.jquery.com/jquery.ajax/

There are better ways to do the AJAX page, so refactor it and make it neater, but something similar to the above should work for you if I am understanding your needs, though you'll probably need to tweak it to get what you want.

Upvotes: 1

Related Questions