WEBOPIXEL

jQueryでWordPressの続きを読むをAjaxで読み込む

Posted: 2011.04.10 / Category: WordPress / Tag: ,

通常のブログではあまり使うことはないかもしれませんが、jQueryの練習がてらWordpressの続きを読むをAjaxで読み込んでみようと思います。

Sponsored Link

WordPressのテンプレート

動作はタイトルと概要と「続きを読む」ボタンを記事一覧に表示して、「続きを読む」ボタンを押すと、ボタンが本文に置き換わるということをやります。

まずはテンプレートファイルを普通(?)に作成します。
一覧を表示するための「index.php」と、本文を表示するための「single.php」ですね。

index.php

 
	<?php get_header(); ?>
	<div id="entry">
		<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
		<div class="section">
			<h3><?php the_title(); ?></h3>
			<?php the_excerpt(); ?>
			<div class="more"><a href="<?php the_permalink() ?>">続きを読む</a></div>
		<!-- /.section --></div>
	<?php endwhile; else: ?>
		<p><?php _e('no post'); ?></p>
		<?php endif; ?>
	<!-- /.entry --></div>
	<?php get_footer(); ?>
	

single.php

 
	<?php get_header(); ?>
	<div id="article">
		<h2><?php the_title(); ?></h2>
		<p class="date"><?php the_time('Y-m-d'); ?></p>
		<div class="content">
			<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
			<?php the_content(); ?>
			<?php endwhile; else: ?>
				<p><?php _e('no post'); ?></p>
			<?php endif; ?>
		<!-- /#content --></div>
	<!-- /#article --></div>
	<?php get_footer(); ?>
	

「index.php」では特に変わったことはないと思います。いつも通り「the_permalink()」でリンクします。
「single.php」で必要なところは「content」クラスに囲まれた部分だけなのですが、他の部分も作るっておくことでjavascriptがOFFときであったり、SEO的にもよろしいのではないのかと思います。

jQueryを書くheader.php

jQueryの部分はこうです。

header.php

 
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>jQueryでWordpressの続きを読むをAjaxで読み込む</title>
		<?php wp_enqueue_script('jquery'); ?>
		<?php wp_head(); ?>
		<?php if(is_home()): ?>
		<script type="text/javascript">
		(function($) {
			$(function() {
				$('.more a').click(function(event) {
					//aリンクの動作を停止
					event.preventDefault();
					//リンク先URLを取得
					var page = $(this).attr('href');
					$(this).parent()
						.load(page+' div.content')
						.fadeOut()
						.slideDown(200);
				});
			});
		})(jQuery);
		</script>
		<?php endif; ?>
		</head>
		<body>
	
14行目
event.preventDefault()
aタグのリンクが無効(?)になって画面遷移しなくなります。
16行目
$(this).attr(‘href’)
aタグで指定した「href(URL)」を取得します。
18行目
.load(page+’ div.content’)
ここでリンク先の「div.content」の部分だけ読み込みます。

Wordpressだからといって特別なことはないですね。
これだけでは心許ないところがありますが、とりあえずシンプルな例ということで。