ajax使用wp_query

时间:2017-12-06 13:01:31

标签: ajax wordpress

我是使用Ajax的初学者,我尝试使用ajax将帖子加载到我正在处理的网站的灯箱上。这个想法是当他们点击存档页面中的帖子时,它会打开一个帖子灯箱,而不是转到新页面。

我的代码如下:

在Functions.php中

add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
function enqueue_scripts() {
    //other scripts
    wp_localize_script( 'ajax-postload', 'ajaxpostload', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
}
add_action( 'wp_ajax_nopriv_ajax_postload', 'my_ajax_postload' );
add_action( 'wp_ajax_ajax_postload', 'my_ajax_postload' );

function my_ajax_postload() {

    $postid = $_POST['postid'];
    $args = array(
        'p' => $postid
    );


    $posts = new WP_Query( $args ); 

    if( ! $posts->have_posts() ) { 
        ?>
        <div class="image-info">
            <p>There has been an issue loading this image, please try again.</p>
        </div>
        <?php
    }
    else {
        while ( $posts->have_posts() ) { 
            $posts->the_post();
            ?>
            <div class="image-info">
                <h3>Image Name: </h3>
                <h4><?php the_title(); ?></h4>
                <h3>Image Description:</h3>
                <div class="description">
                    <?php the_content(); ?>
                </div>
            </div>
            <div class="lightbox-image">
                <?php the_post_thumbnail(); ?>
            </div>
            <?php
        }
    }

    die();
} 

在Javascript文件中:

(function($) {
    function find_post_ID( element ) {
        var link = $(element).parents('.post-link');
        return $(link).find('.post-id').attr('id').replace('lightbox-',"")
    }
    if (window.innerWidth > 767) {
    $(document).on( 'click', '.post-link', function( event ) {
        event.preventDefault();

        $wp_postid = find_post_ID( event.target );

        $.ajax({
            url: ajaxpostload.ajaxurl,
            type: 'post',
            data: {
                action: 'ajax_postload',
                postid: $wp_postid,
                query_vars: ajaxpostload.query_vars
            },
            beforeSend: function() {
                $('.lightbox .image-info').remove();
                $('.lightbox').append( '<div class="image-info" id="loader"><h3>Loading Image...</h3></div>' );
                $('.lightbox').css( 'display' , 'block');
            },
            success: function( html ) {
                $('.lightbox #loader').remove();
                $('.lightbox').append( html );
            }
        })
    });
    }
})(jQuery);

我的问题是,每当我点击一个帖子,灯箱打开,但显示无帖子错误信息,我是否遗漏了一些简单的事情或者我搞砸了ajax电话?

1 个答案:

答案 0 :(得分:0)

您应该将'any'参数作为post_type传递给post,如下所示

 $postid = $_POST['postid'];    
  $args = array(
        'p' => $postid,
        'post_type' => 'any'
    );

如果没有ajax,你只能尝试使用'p'(一个参数)来发帖,不会返回任何帖子。 所以试试并检查你的结果。

相关问题