Lotus@ 2018-08-24 14:17 采纳率: 100%
浏览 34

WordPress使用查询作为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?

  • 写回答

1条回答 默认 最新

  • ℡Wang Yan 2018-08-24 15:00
    关注

    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.

    评论

报告相同问题?