반응형
ajax를 사용하여 wordPress menu를 통해 div의 카테고리별 최신 게시물 로드
맨 위에 카테고리 이름의 가로 목록이 있는 index.php를 원합니다. 그리고 카테고리 이름을 클릭하면 새로 고침 없이 특정 div 컨테이너의 index 페이지에 최신 10개의 게시물이 표시됩니다.워드프레스에서도 가능한가요?
감사해요.
내 코드로 업데이트하기:
카테고리 메뉴의 경우:
<?php $categories = get_categories(); ?>
<ul id="category-menu">
<?php foreach ( $categories as $cat ) { ?>
<li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></li>
<?php } ?>
ajax를 통해 게시물이 로드되는 html div 플레이스 홀더:
<div id="main-container">
<div id="loading-animation" style="display: none;"><img src="<?php bloginfo('url'); ?>/images/loading.gif"></div>
<div id="category-listing"></div>
jQuery 함수:
<script>
function cat_ajax_get(catID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
jQuery("#loading-animation").show();
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter", cat: catID },
success: function(response) {
jQuery("#category-listing").html(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
PHP 함수:
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
$cat_id = $_POST[ 'cat' ];
$args = array (
'cat' => $cat_id,
'posts_per_page' => 10,
'order' => 'DESC'
);
$posts = get_posts( $args );
ob_start ();
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<div>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>/h1>
</div>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
카테고리를 클릭하면 표시되지 않지만 모두 선택하고 소스 코드를 보면 결과가 나타납니다.
loading without data..도와줄 사람?
이 경우에는 개체 버퍼 또는 post_attributes() 함수를 무시할 필요가 없습니다.
function prefix_load_cat_posts () {
$cat_id = $_POST[ 'cat' ];
$args = array (
'cat' => $cat_id,
'posts_per_page' => 10,
'order' => 'DESC'
);
$posts = get_posts( $args );
if($posts) {
foreach ($posts as $post) { ?>
<div>
<h1><a href="<?php echo get_the_permalink($post->ID); ?>"><?php echo get_the_title($post->ID); ?></a></h1>
</div>
<?php }
}
die();
}
언급URL : https://stackoverflow.com/questions/42186225/load-the-latest-posts-by-category-in-a-div-via-wordpress-menu-using-ajax
반응형
'sourcecode' 카테고리의 다른 글
모든 테이블에 기본 키가 있어야 합니까? (0) | 2023.10.11 |
---|---|
Oracle 별칭 이해 - 두 번째 쿼리로 래핑하지 않는 한 쿼리에서 별칭이 인식되지 않는 이유는 무엇입니까? (0) | 2023.10.06 |
점선(점선 아님!) 선 그리기, 2017년 IBDesignable (0) | 2023.10.06 |
보이드로 변환하거나 그 반대로 변환하는 것은 무엇을 의미합니까? (0) | 2023.10.06 |
컴파일러 최적화 bitwise not operation (0) | 2023.10.06 |