Ajax文章获取

2023-12-25 4次

带html结构

//
add_action('wp_ajax_load_category_posts', 'load_category_posts_callback');
add_action('wp_ajax_nopriv_load_category_posts', 'load_category_posts_callback');

function load_category_posts_callback()
{
    $cat_id = $_POST['cat_id'];
    $paged = $_POST['cat_paged'];
    $args = array(
      'post_type' => array('post'),
      'cat' => $cat_id,
      'orderby' => 'date',
      'order' => 'DESC',
      'posts_per_page' => 12,
      'paged' => $paged,
    );
    $query = new WP_Query($args);
    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post(); ?>
      <li>
        <a href="<?php the_permalink(); ?>" class="news-kld-item">
          <div class="news-kld-pic">
            <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>">
          </div>
          <div class="news-kld-content">
            <div class="news-kld-title">
              <h3 class="tf-v3"><?php the_title(); ?></h3>
              <p><?php echo wp_trim_words(get_the_excerpt(), 120); ?></p>
            </div>
          </div>
        </a>
      </li>
    <?php endwhile;
    endif;
    wp_reset_postdata();
    die();
}
<script>
	let paged = 1;
	let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
	var catId = '<?php echo $cat; ?>';

	// Ajax请求
	function postLoad(id, paged) {
		// 设置Ajax参数
		var data = {
			'action': 'load_science_posts',
			'cat_id': id,
			'cat_paged': paged
		};
		$.post(ajaxurl, data, function(response) {
			if (!response) {
				$(".loading-data a").attr("data-sign", "false")
				$(".loading-data a").html("敬请期待")
				return false;
			} else {
				$(".secview-lists ul").append(response);
			}

		});
	}

	postLoad(catId, paged);
	$(".loading-data a").on("click", function() {
		if ($(this).attr("data-sign")) {
			paged++;
			postLoad(catId, paged);
		}

	})
</script>

纯数据

add_action('wp_ajax_get_post', 'wp_ajax_get_post');
add_action('wp_ajax_nopriv_get_post', 'wp_ajax_get_post');

function wp_ajax_get_post()
{
    $post_id = $_POST['post_id']; // 通过Ajax请求传递的文章ID

    $args = array(
        'p' => $post_id, // 指定文章ID
        'post_type' => 'post', // 文章类型
        'posts_per_page' => 1, // 每页显示的文章数量
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        $query->the_post();

        $post = array(
            'title' => get_the_title(),
            'content' => get_the_content(),
            // 可按需添加其他文章信息
        );

        wp_reset_postdata();

        wp_send_json_success($post);
    } else {
        wp_send_json_error('Post not found');
    }
}
<script>
    let ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
    function getArticle(post_id) {
        $.ajax({
            url: ajaxurl, // WordPress提供的Ajax处理URL
            type: 'POST',
            data: {
                action: 'get_post', // 要执行的Ajax动作
                post_id: post_id // 传递的文章ID
            },
            success: function (response) {
                if (response.success) {
                    let post = response.data;
                    $('.wordpress-content').html('');
                    $('.wordpress-content').append(post.content);
                } else {
                    // 处理错误情况
                    console.log(response.data);
                }
            },
            error: function (xhr, status, error) {
                console.log(error);
            }
        });
    }

    $(".wordpesscode-lists ul li").eq(0).addClass("on");
    let intId = $(".wordpesscode-lists ul li").eq(0).find("a").attr("data-id");
    if (intId) {
        getArticle(intId)
    }

    $(".wordpesscode-lists ul li").on("click", function () {
        let post_id = $(this).find("a").attr("data-id");
        if (post_id) {
            $(this).addClass("on").siblings().removeClass("on")
            getArticle(post_id);
        }
    })

</script>