如何加载WordPress的帖子与阿贾克斯的onclick(How to load Wordpres

2019-07-21 14:25发布

我花了几个小时读书,并努力教程。 我似乎无法找到有效的解决方案,我知道这应该是很容易的,但我用AJAX斗争。 :(

我要发表的内容从一个div链路负载。 下面是我。 有人可以帮我与JavaScript的一面呢? 谢谢!

<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>

我想在div来加载此代码#loadAjaxHere

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

感谢您的帮助!!

Answer 1:

好吧,我想我已经尝试和错误的一个漫长的过程后,解决了这个。

这似乎是工作,但请让我知道如果不这样做的正确方法

使用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;
    });
});

在这里我想显示帖子内容(我使用自定义文章类型称为“艺术品”的页面:

<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>

而单后“单artwork.php”。 注意:不要使用get_header或get_footer等:

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

谢谢!



Answer 2:

我想补充,如果你只是想在一个职位,你可以ammend的一部分加载

$("#tabs").load(post_url);

$("#tabs").load(post_url + ".tabcontent" );

这将只是一切都加载在div.tabcontent



Answer 3:

巴里的答案是对能够通过添加CSS选择器表达式的URL的末尾来加载部分页面正确。 然而,将需要的URL和像这样的选择之间的空间:

$("#tabs").load(post_url + " .tabcontent" );

否则,传递给串.load()http://example.com.tabscontent 。 但它应该是http://example.com .tabscontent

另外,对明智一个字,使用这种方法将停止加载jQuery和执行内部的任何代码<script>标记。 然而,仅仅使用.load(post_url); 没有选择器将成功地加载并在执行代码<script>标记。

了解更多有关在这里 。



文章来源: How to load Wordpress Post with Ajax onclick