在Ajax启动模式时显示WP内容

时间:2017-01-23 09:10:44

标签: jquery ajax wordpress

我试图搞清楚我的模态文件是如何显示我的WP内容的,如果我尝试其他的东西,它最终会导致500(内部服务器错误),尽管我已经发现了内部服务器错误的情况。这是我的模态代码。

<?php include '/wp-blog-header.php'; ?>

<?php $postname = new WP_Query([ 'post_type' => 'causes', 'posts_per_page' => 1, 'p' => $_POST['key'] ]); ?>
<?php while ( $postname->have_posts() ) : $postname->the_post(); ?>
<div class="uk-modal-dialog">
  <a class="uk-modal-close uk-close"></a>
  <div class="fetched-data">
    this is modal popup
    <?php echo $post->post_name; ?>
  </div>
</div>
<?php endwhile; wp_reset_postdata(); ?>

虽然如果我以纯文本形式进行,但它会显示模态。 这是我的Ajax脚本。

$(document).ready(function(){
  $('.open-modal').on('click', function(){
    var postID = $(this).attr('data-content');

    var modal = UIkit.modal(".uk-modal", {center: true, bgclose: false});
    if ( modal.isActive() ) {
      modal.hide();
    } else {
      modal.show();

      $.ajax({
        type: "POST",
        cache: false,
        dataType: "json",
        url: "wp-content/themes/mytheme/inc/structures/modal/modal-donate.php",
        data: { key : postID },
        success: function(data) {
          $('.uk-modal').html(data);
        }           
      });
    }
  });
});

注意

我将模态文件更新为:

<?php 
  require '../../../../../../wp-load.php';
  require '../../../../../../wp-blog-header.php';

  echo $postKey = $_POST['key'];
  global $post;
  $args = array( 'post_type' => 'causes', 'posts_per_page' => 1, 'p' => $postKey );
  $posts = get_posts( $args );
?>

<?php foreach ($posts as $post) : setup_postdata( $post ); ?>
<div class="uk-modal-dialog">
  <a class="uk-modal-close uk-close"></a>
  <div class="fetched-data">
    <p>this is modal popup</p>
    <?php the_title(); ?>
  </div>
</div>
<?php endforeach; ?>

虽然Ajax错误一直显示在我的模态中。

2 个答案:

答案 0 :(得分:1)

您需要在页面顶部包含“wp-load.php”文件才能首先执行WordPress功能。

include("../../../wp-load.php");

要调用“modal-donate.php”文件,如果在PHP文件中设置脚本,可以设置类似的代码,

$.ajax({
        type: "POST",
        cache: false,
        dataType: "json",
        url: <?php echo get_template_directory_uri(); ?>"/inc/structures/modal/modal-donate.php",
        data: { key : postID },
        success: function(data) {
          $('.uk-modal').html(data);
        }           
      });

答案 1 :(得分:0)

我发现dataType: "json"是导致我的错误的原因,所以在我再次回读jQuery Ajax文档之后,我发现我的案例问题只是回到了&#34; html&#34;仅限类型。所以这是我问题的完整解决方案。

$(document).ready(function(){
  $('.open-modal').on('click', function(){
    var postID = $(this).attr('data-content');

    var modal = UIkit.modal(".uk-modal", {center: true, bgclose: false});
    if ( modal.isActive() ) {
      modal.hide();
    } else {
      modal.show();

      $.ajax({
        type: "POST",
        cache: false,
        dataType: "html",
        url: "wp-content/themes/mytheme/inc/structures/modal/modal-donate.php",
        data: { key : postID },
        success: function(data) {
          $('.uk-modal').html(data);
        }           
      });
    }
  });
});