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.

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

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)