LoginSignup
0
0

More than 5 years have passed since last update.

wp_link_pages()で得られるリンクのURLを配列形式で得る

Last updated at Posted at 2018-05-16

やりたいこと

<ol>
  <li><a href="http://hoge.com/blog/">1</a></li>
  <li><a href="http://hoge.com/blog/2/">2</a></li>
  <li><a href="http://hoge.com/blog/3/">3</a></li>
</ol>

WPで改ページのある記事に、こんな感じの一般的なページネーションを作りたい。

普通にやる

single.php
<?php
  $args = array(
    'before'           = '<ol>',
    'after'            = '</ol>',
    'link_before'      = '<li>',
    'link_after'       = '</li>',
  );

  wp_link_pages($args);
?>
出力結果
<ol>
  <a href="http://hoge.com/blog/1"><li>1</li></a>
  <a href="http://hoge.com/blog/1/2/"><li>2</li></a>
  <a href="http://hoge.com/blog/1/3/"><li>3</li></a>
</ol>

違う、そうじゃない

対策

改ページのURLを配列形式で返す自作関数を定義。

functions.php
// 改ページのURLを配列形式で返す
function wp_link_pages_uri() {
  global $page, $numpages;

  $result = array();
  for ($i = 1; $i < $numpages+1; $i++) {
        $result[] = preg_replace('/<a href="(.+)">/', '$1', _wp_link_page($i));
    }

  return $result;
}
single.php
<?php
  echo "<pre>";
  print_r(get_wp_link_pages_uri());
  echo "</pre>";

  // Array
  // (
  //     [0] => http://hoge.com/blog/
  //     [1] => http://hoge.com/blog/1/2
  //     [2] => http://hoge.com/blog/1/3
  // )
?>

あとはforeachなりで成型して完成!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0