douguo6472 2014-08-21 13:43
浏览 14
已采纳

Wordpress - 针对单个POST,而不是POST类型。 AJAX / PHP

I am trying to load the individual post information on click into the page when clicking the post title. I have managed to get my script to loop through the titles in the post array and on click load the post titles once more into a div. I want this to load the individual post information instead on click.

PHP Post Array Functions -

add_action( "wp_ajax_success_stories", "sa_get_paginated_posts" );
add_action( "wp_ajax_nopriv_success_stories", "sa_get_paginated_posts" );

function sa_get_paginated_posts(){

      $args = array(
          'posts_per_page'  => -1,
          'post_type'       => 'success-stories',
          'orderby'         => 'post_date',
          'order'           => 'DESC' 
      );

      $the_query = new WP_Query( $args );
      $queryitems = $the_query->get_posts();
      $alldata = array();

      if ($queryitems){

        foreach ($queryitems as $query_item){

          $success_story = array();

          $success_story["ID"] = $query_item->ID;
          $success_story["title"] = $query_item->post_title;

          $alldata[] = $success_story;

        }

      }

      $encoded_data = json_encode($alldata);

      echo $encoded_data;

      die();

  }



function sa_get_posts($post_amount, $post_type){

    $args = array(
        'posts_per_page'  => $post_amount,
        'post_type'       => $post_type,
        'offset'          => 0,
        'orderby'         => 'post_date',
        'order'           => 'ASC'

    );

Using this function to loop through -

      <? if ($success_stories): //success story posts ?>
            <ul class="small-block-grid-3">
                <? foreach ($success_stories as $success_story): 
                    $title = $success_story->post_title; ?>

                    <li><a data-id="<? echo $success_story->ID; ?>" class="success-extra" href="#" title=""><? echo $title; ?></a></li>

                <? endforeach; ?>
            </ul>

          <div id="success-list"></div>
          <a class="success-close" href="#" title="">CLOSE</a>

    <? endif; ?>

Javascript/ AJAX Call

  var $json_response_box = $("#success-list");

  function get_ajax_success_posts() {

    //this line gets the id attribute from the link
    var current_story = $(this).attr("data-id");
    console.log(current_story);

    jQuery.ajax({
        type: "GET",
        url: "WORDPRESSDIRECTORY/admin-ajax.php",
        cache: true,
        data: {
            action: "success_stories"
        },
        dataType: "JSON",
        success: function(data) {

            var arrayLength = data.length;

            for (var i = 0; i < arrayLength; i++) {


                var success_id = data[i].ID;
                var success_title = data[i].title;

                console.log(success_id);

                story = '<ul>';
                  story += '<li>';
                    story += success_title;
                  story += '</li>';
                story += '</ul>'; 

                $json_response_box.append(story).fadeIn(1000);

            }
        },
        error: function(errorThrown) {
            console.log("fail-posts");
        }
    });
  }

Appreciate your suggestions,

D

  • 写回答

1条回答 默认 最新

  • duanlian1960 2014-08-23 12:28
    关注

    If I understand your question correctly, you should just add another php function and AJAX call, to get the post on click, something like this (I also added nonce to add some secutiry, it's always a good idea to add that to your ajax calls)

    HTML:

    <li><a data-id="<? echo $success_story->ID; ?>" data-nonce="<?php wp_create_nonce('get_post'.$success_story->ID); ?>" class="success-extra" href="#" title=""><? echo $title; ?></a></li>
    

    PHP:

    add_action( "wp_ajax_sa_get_post", "sa_get_post" );
    add_action( "wp_ajax_nopriv_sa_get_post", "sa_get_post" );
    
    function sa_get_post(){
        if ( ! wp_verify_nonce( $nonce, 'get_post_'.$POST['id'] ) ) {
        // This nonce is not valid.
        $response['status'] = 'fail'; 
        } else {
        // The nonce was valid.
        $post = get_post($POST['id']);
        $response['status'] = 'success'; 
        $response['post'] = $post;        
        } 
        echo json_encode($response);
        exit(); // this is needed, as otherwise the AJAX returns an extra 0       
    }
    

    JS:

     $('.success-extra').on('click', function () {
         jQuery.ajax({
            type: "POST",
            url: "WORDPRESSDIRECTORY/admin-ajax.php",
            cache: false,
            data: {
                action: "sa_get_post",
                id: $(this).attr('data-id'),
                nonce: $(this).attr('data-nonce')
            },
            success: function(data) {
                var result = $.parseJSON(data);
                if (result.status != 'success') {
                   // display error messago or something
                } else {
    
                  // do whatever you want with your result.post
                }
            }
    
     })
    

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题