如何通过在ajax wordpress中使用post id来发帖?

时间:2018-03-15 09:09:19

标签: javascript php jquery ajax wordpress

我没有wordpress ajax的经验。我想通过在ajax中使用post id来获取我的自定义帖子类型帖子,但我不知道如何编写函数。 这是我在functions.php中使用的代码

add_action('wp_ajax_data_fetch', 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch', 'data_fetch');
function data_fetch(){
    if (isset($_POST["post_id"]) && isset($_POST["post_id"]) != '') {       
      $post_id = $_POST["post_id"];


        $args = array( 'post_type' => 'sponsors');
        $the_query = new WP_Query( $post_id ); 
        if ( $the_query->have_posts() ) :
            while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                        <?php the_title(); ?>
                    </div>  
                </div>

            <?php endwhile;
        endif;

    }

}

这是我的ajax代码

    <a href="<?php echo get_the_ID(); ?>" data-id="<?php echo $post->ID; ?>" id="click_me" >Fetch Data</a>
    jQuery( document ).on( 'click', '#click_me', function() {
    var post_id = jQuery(this).data('id');
    jQuery.ajax({
        url : 'http://localhost/verturesort/wp-admin/admin-ajax.php',
        type : 'post',
        data : {
            action : 'data_fetch',
            'post_id' : post_id
        },
        success : function( response ) {
            jQuery('#datainsert').append( response );
        }
    });

    return false;
});

0 个答案:

没有答案