wordpress simple Ajax

①in functions.php add below

/**
 * ajax for topics
 */
function prepare_ajax()
{
	$handle = 'js-frontend';
	$js_url = get_stylesheet_directory_uri() . '/js/sort.js';
	wp_register_script($handle, $js_url, array('jquery'));
	wp_localize_script(
		$handle,
		'js_globals',
		[
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('load-more-posts'),
		]
	);
	wp_enqueue_script($handle);
}
add_action('wp_enqueue_scripts', 'prepare_ajax', '', '', true);

②create sort.js something like this

  data = {
            'action': "get_more_post",
            'category': category,
            'nonce': js_globals.nonce
        };
        $.ajax({ // you can also use $.post here
            url: js_globals.ajax_url, // AJAX handler
            data: data,
            type: 'post',
            timeout: 10000,
            success: function (data) {
                refreshPostList(data);
                setDateHeight();
            }
        }).fail(function () {
            console.log('fail');
        });

③in functions.php add function to get data

function get_more_post()
{
	GLOBAL $post;
	$nonce = $_POST['nonce'];
	if (!wp_verify_nonce($nonce, 'load-more-posts')) {
		die('Nonce value cannot be verified.');
	}
	$ret = "";
	$category = $_POST['category'];
	$args = array(
		"post-type" => "post",
		"posts_per_page" => "5",
		"category_name" => $category
	);
	$query = new WP_Query($args);
	if ($query->have_posts()) :
		while ($query->have_posts()) :
			$query->the_post();
			$categories = get_the_category($post->id);
			foreach ($categories as $category) {
				$slug = esc_html($category->slug);
				$post_cat = '<a class="topics_list__category cat_color ' . $slug . '" href="' . esc_html(get_category_link($category->term_id)) . '">' . strtoupper($slug) . '</a>';
				break;
			};
			$ret .= '<dt class="topics_list__date js_date">' . get_the_time('Y.m.d') . '' . $post_cat . '</dt>
                     <dd class="topics_list__desc"><a class="topics_list__title topics_list__title--list" href="' . get_the_permalink() . '">' . get_the_title() . '</a></dd>';
		endwhile;
	endif;
	wp_reset_postdata();
	echo ($ret);
	// Always die in functions echoing ajax content
	die();
}
add_action('wp_ajax_get_more_post', 'get_more_post'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_get_more_post', 'get_more_post'); // wp_ajax_nopriv_{action}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です