Quantcast
Channel: otapps
Viewing all articles
Browse latest Browse all 196

WordPressで、はてなブログやはてなダイアリーの脚注記法(?)っぽいのを実現する方法。

$
0
0

※タイトル変更しました。「脚注記法」ですね。
はてなブログや、はてなダイアリーには、脚注機能みたいなのがあります。

たとえば、はてなブログで…。

あいうえお((二重の丸括弧で括った部分は脚注になるよん♪))

とか入力して投稿すると…。
二重の丸括弧(?)でくくった部分は、脚注として*Nなリンクに置き換えられ、記事の文末にその脚注が表示されます。

こんな感じ。
hatena2

最近、はてなブログProを試してみている私のお気に入りがこの脚注記法。
というわけで、それをWordPressで実現する方法を考えてみました。

add_filter('the_content', 'notes_replace');
function notes_replace($content) {
    global $post;
    $text = '';
    $notes = array();
    $post_id = $post->ID;
    $post_permalink=get_permalink($post_id);
    $note_pattern = '/\(\((.+?)\)\)/';
    $id_attr_format = 'post-%d-note%d';
    $link_format = '<a href=%s#%s>*%d</a>';
    $text_format = '<p id="%s">*%d:%s</p>';
    preg_match_all($note_pattern, $content, $notes);
    foreach ($notes[0] as $key => $target) {
        $num = $key + 1;
        $id_attr = sprintf($id_attr_format, $post_id, $num);
        $link = sprintf($link_format, $post_permalink,$id_attr, $num);
        $text .= sprintf($text_format, $id_attr, $num, $notes[1][$key]);
        $content = str_replace($target, $link, $content);
    }
   return is_single()?$content.$text:$content;
}


ローカルの環境にWordPressをインストールしてなかったので、何か色々とやっつけな感じですが上記のソースをfunctions.php に貼り付けて、記事中で脚注としたいものを二重の丸括弧でくくって、((ここに脚注を入力)) みたいな感じで書いてやる事で、動作します。


Viewing all articles
Browse latest Browse all 196

Trending Articles