Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

jquery - How to load Wordpress Post with Ajax onclick

I have spent hours reading and trying tutorials. I cant seem to find a solution that works and I know it should be pretty easy but I struggle with AJAX. :(

I want to load Post content from a link in a div. Below is what I have. Can someone please help me with the JavaScript side? Thanks!

<ul>
    <?php query_posts('post_type=artwork&posts_per_page=-1'); ?>
    <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
    <li class="mytab">
      <span>
         <h3><?php the_title(); ?></h3>
         <a href="#"><?php the_post_thumbnail('Project'); ?></a>
      </span>
    </li>
    <?php endwhile; endif; wp_reset_query(); ?>
</ul>

<div id="loadAjaxHere"></div>

I want to load this code in div #loadAjaxHere

<div class="myArtwork">
   <h2><?php the_title(); ?></h2>
   <div class="text"><?php the_content(); ?></div>
</div>

Thank you for the help!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, I think I have solved this after a long process of trial and error.

This seems to work, but please let me know if it is not the correct way of doing this

Javascript:

jQuery.noConflict();
jQuery(document).ready(function($){
    $.ajaxSetup({cache:false});
    $("a.ajax").click(function(){
        var post_url = $(this).attr("href");
        var post_id = $(this).attr("rel");
        $("#tabs").html('<div class="loading">loading...</div>');
    $("#tabs").load(post_url);
    return false;
    });
});

The page where I want to display the post content (I am using custom post types called "artwork":

<ul class="container">
  <?php query_posts('post_type=artwork&posts_per_page=-1'); ?>
  <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
  <li class="mytab">
    <h3><?php the_title(); ?></h3>
    <a href="<?php the_permalink(); ?>" rel="<?php the_ID(); ?>" class="ajax"><?php the_post_thumbnail('Project'); ?></a>
  </li>
  <?php endwhile; endif; wp_reset_query(); ?>
</ul>

<!-- LOAD SINGLE POST CONTENT IN #TABS -->
<div id="tabs"></div>

And the single post "single-artwork.php". Note: Dont use get_header or get_footer etc:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
  <div class="tabcontent" id="tab-<?php the_ID(); ?>">
    <?php the_content(); ?>
  </div>
<?php endwhile; endif; ?>

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...