カテゴリー: WordPress

  • カスタム分類ってデフォルトだと、
    [plain]
    http://example.com/カスタム分類名/項目
    [/plain]

    ってなってるんですが、これを
    [plain]
    http://example.com/カスタム投稿名/カスタム分類名/項目
    [/plain]

    にしたい時があると思います。そんな時のハックです。

    2011-12-28追記:Custom Post Type Permalinksにこの機能は実装しています。是非そちらをお使い下さい。

    [php]
    add_action( ‘generate_rewrite_rules’, ‘my_rewrite’ );
    function my_rewrite( $wp_rewrite ){
    $taxonomies = get_taxonomies();
    $taxonomies = array_slice($taxonomies,4,count($taxonomies)-1);
    foreach ( $taxonomies as $taxonomy ) :

    $post_types = get_taxonomy($taxonomy)->object_type;

    foreach ($post_types as $post_type){
    $new_rules[$post_type.’/’.$taxonomy.’/(.+?)/?$’] = ‘index.php?taxonomy=’.$taxonomy.’&term=’.$wp_rewrite->preg_index(1);
    }

    $wp_rewrite->rules = array_merge($new_rules, $wp_rewrite->rules);

    endforeach;
    }

    add_filter( ‘term_link’, ‘my_term_link’ ,10,3);
    function my_term_link( $termlink, $term, $taxonomy){
    $t=get_taxonomy($taxonomy);
    $wp_home = get_option("home");

    $post_type = $t->object_type[0];
    if(!isset($t->object_type[1])) {
    $termlink = str_replace($wp_home,$wp_home."/".$post_type,$termlink);
    }

    return $termlink;
    }

    [/php]

    上記のコードをfunctions.phpに書きこんでください。

    デフォルトだと、http://example.com/カスタム投稿名/カスタム分類名/項目でアクセスしても、Not Foundになってしまうので、my_rewrite()で、リライトルールを追加します。
    そして、下のmy_term_linkの方で、get_term_link等で出力されるURLを書き換えます。

    この時、複数の投稿タイプに関連付けられているものは書き換えないようにしています。タグとかはそういう運用があるかと思います。
    そういう運用をしない場合は
    [php]
    if(!isset($t->object_type[1]))
    [/php]
    を外しても大丈夫です。

    [php]
    $terms = get_terms(‘カスタム分類’);
    foreach ($terms as $term) { ?>
    <li><a href="<?=get_term_link($term->slug, ‘カスタム分類’);?>"><?=$term->name;?></a></li>
    <?php
    }?>

    [/php]

    で、カスタム分類の一覧がリンク付きで出ると思いますので、試してみてください。

  • WordPress3.0から追加されたget_themplate_partという関数がありまして。

    [php]
    get_template_part( $slug, $name );
    [/php]

    機能としては、get_headerなどの拡張版です。
    “{slug}-{name}.php” をインクルードします。”{slug}-{name}.php” がない場合、”{slug}.php” をインクルードします。

    小テーマ等が増えて複雑怪奇になってきたときに

    [php]
    get_template_part( "css");
    [/php]

    等と書いておくと、css.phpをインクルードします。
    また、includeやrequireなどと違い、そのcss.phpの中でもwordpressの関数が動作します。

    twentytenでは、
    [php]
    get_template_part( "loop","archive");
    [/php]

    のような使い方をして、記事の表示の部分をloop.phpに統一しています。メンテンナンス性が上がりますね。

  • カスタム投稿のパーマリンクはデフォルトだと

    /カスタム投稿名/投稿タイトル

    になってて、これが結構使いづらいんですよ。日本語タイトルだとURLまで日本語になってしまったり。

    また、月別アーカイブとかが無かったりで色々と面倒。なので、functions.phpで色々カスタマイズします。

    2011-12-28追記:プラグインにしました。今後はこちらをお使い下さい。Custom Post Type Permalinks

    [php]
    class set_custom_rewrite {
    var $post_type;

    function set_custom_rewrite($post_type){
    $this->post_type = $post_type;

    add_action(‘init’, array(&$this,’set_rewrite’));
    add_action(‘init’, array(&$this,’add_rule’));
    add_filter(‘post_type_link’, array(&$this,’set_permalink’), 1, 3);
    }
    //Rewrite Ruleの追加
    function add_rule(){
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/feed/(feed|rdf|rss|rss2|atom)/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&feed=$matches[4]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/(feed|rdf|rss|rss2|atom)/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&feed=$matches[4]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/page/?([0-9]{1,})/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&paged=$matches[4]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/feed/(feed|rdf|rss|rss2|atom)/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&feed=$matches[3]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/(feed|rdf|rss|rss2|atom)/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&feed=$matches[3]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/page/?([0-9]{1,})/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&paged=$matches[3]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/([0-9]{1,2})/?$’,’index.php?year=$matches[1]&monthnum=$matches[2]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/feed/(feed|rdf|rss|rss2|atom)/?$’,’index.php?year=$matches[1]&feed=$matches[2]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/(feed|rdf|rss|rss2|atom)/?$’,’index.php?year=$matches[1]&feed=$matches[2]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/page/?([0-9]{1,})/?$’,’index.php?year=$matches[1]&paged=$matches[2]&post_type=’.$this->post_type);
    add_rewrite_rule($this->post_type.’/([0-9]{4})/?$’,’index.php?year=$matches[1]&post_type=’.$this->post_type);

    }

    function set_rewrite() {
    global $wp_rewrite;

    $queryarg = ‘post_type=’.$this->post_type.’&p=’;
    $wp_rewrite->add_rewrite_tag(‘%’.$this->post_type.’_id%’, ‘([^/]+)’,$queryarg);
    $wp_rewrite->add_permastruct($this->post_type, ‘/’.$this->post_type.’/%year%/%monthnum%/%day%/%’.$this->post_type.’_id%/’, false);
    }

    function set_permalink($post_link, $id = 0) {
    global $wp_rewrite;

    $post = &get_post($id);
    if ( is_wp_error( $post ) )
    return $post;

    $newlink = $wp_rewrite->get_extra_permastruct($this->post_type);
    $newlink = str_replace("%".$this->post_type."%", $post->post_type, $newlink);
    $newlink = str_replace("%".$this->post_type."_id%", $post->ID, $newlink);

    $post_date = strtotime($post->post_date);
    $post_year = date("Y",$post_date);
    $post_monthnum = date("m",$post_date);
    $post_day = date("d",$post_date);

    $newlink = str_replace("%year%",$post_year, $newlink);
    $newlink = str_replace("%monthnum%",$post_monthnum, $newlink);
    $newlink = str_replace("%day%",$post_day, $newlink);

    $newlink = home_url(user_trailingslashit($newlink));
    return $newlink;
    }

    }

    $set_blog_permalink = new set_custom_rewrite("カスタム投稿名");

    [/php]

    こいつをfunctions.phpに書くと、
    /カスタム投稿名/年/月/日/投稿id
    に個別記事のURLが変更されます。

    また、add_ruleのところで
    カスタム投稿の月別アーカイブなどのURLを追加しています。これで
    /カスタム投稿名/年/月
    などで、月別アーカイブ等が表示されるようになります。

    ついでに
    http://ja.forums.wordpress.org/topic/6080
    を参考に
    [php]

    global $my_archives_post_type;
    add_filter( ‘getarchives_where’, ‘my_getarchives_where’, 10, 2 );
    function my_getarchives_where( $where, $r ) {
    global $my_archives_post_type;
    if ( isset($r[‘post_type’]) ) {
    $my_archives_post_type = $r[‘post_type’];
    $where = str_replace( ‘\’post\”, ‘\” . $r[‘post_type’] . ‘\”, $where );
    } else {
    $my_archives_post_type = ”;
    }
    return $where;
    }
    add_filter( ‘get_archives_link’, ‘my_get_archives_link’ );
    function my_get_archives_link( $link_html ) {
    global $my_archives_post_type;
    if ( ” != $my_archives_post_type )
    $my_archives_post_type;
    $blog_url = get_bloginfo("url");

    $link_html = str_replace($blog_url,$blog_url.’/’.$my_archives_post_type,$link_html);

    return $link_html;
    }

    [/php]

    を記述しておくと、
    [php]
    wp_get_archives(‘type=monthly&post_type=カスタム投稿名’);
    [/php]

    でカスタム投稿の月別アーカイブ一覧が表示されます。

    ここまでするならDrupalとかで作った方が楽なんじゃないかとかは言わない約束です。

    参考
    http://ja.forums.wordpress.org/topic/6080
    http://www.phpfreaks.com/forums/index.php?PHPSESSID=ad52a9sjjre4bh7fue8uf5c4g4&topic=328834.0

  • サイトの高速化を図るためにGoogleにホスティングされているjqueryを使いたいとき、WordPressのデフォルトのjQueryが邪魔で仕方ないことが結構ありまして。。。
    そんな時functions.phpで少しのコードを書くだけでどうにでもなります。

    [php]
    //Replace jQuery
    function rep_jQuery(){
    if (!is_admin()) {
    wp_deregister_script(‘jquery’);
    wp_enqueue_script(‘jquery’,’http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js’);

    wp_deregister_script(‘jquery-ui-core’);
    wp_enqueue_script(‘jquery-ui-core’,’http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js’);
    }
    }

    add_action(‘init’,’rep_jQuery’);
    [/php]

    管理画面でも使いたい場合はif文を外してもらえば全てに適応されます。

    この例だと、jquery1.5系と、jQuery UIの1.8系の最新版が読み込まれます。
    その他細かい仕様等はGoogleさんに聞いてみてください、
    http://code.google.com/apis/libraries/devguide.html

  • 素敵なブログって、記事の最初にアイキャッチャーの画像があったりするんですよね。
    というわけで、投稿サムネイルを活用して、それをやってみたい。。。

    しかし、デフォルトだと、150×150の画像になってしまう。。。
    自分が使いたいのは、横長の画像なんです。

    って困っていたら、こんな関数発見。

    [php]
    set_post_thumbnail_size(WIDTH,HEIGHT, true );
    [/php]

    をfunctions.phpに書いておくと、投稿サムネイルの画像のサイズのデフォルトがここで指定された値になって、このサイズの画像がアップロード時に作成されるようです。

    追記

    また、set_post_thumbnail_sizeで指定したサイズの投稿サムネイルは

    [php]
    the_thumbnail(‘post-thumbnail’);
    [/php]
    で表示することができます。

    これでまたアルファブロガーに一歩近づきましたね!

  • jQuery hashchange eventを使ったWordPressテーマを作成してみました。

    デモサイトはコチラ

    一応HashLogなんていうそのまんまな名前です。
    Ver0.1というアルファバージョンです。一応CSS周りはIE7までOKのはずです。
    WordPress3以上対応です。

    制作の元ネタにでもして頂けたらと思います。

    ダウンロードはこちらからどうぞ。
    hashlog

    これだけではちょっとあれなのでJS周りのソースを張っておきます。

    [php]
    <script type="text/javascript" src="<?php bloginfo( ‘stylesheet_directory’ ); ?>/js/jquery.ba-hashchange.min.js"></script>
    <script type="text/javascript" src="<?php bloginfo( ‘stylesheet_directory’ ); ?>/js/jquery.easing.1.3.js"></script>

    <script type="text/javascript">
    var blogUrl = "<?php bloginfo( ‘url’ ); ?>";
    </script>

    <script type="text/javascript">

    //ハッシュ付にリダイレクトさせる。
    if ( location.href != blogUrl+"/") {
    var index = location.href.indexOf(blogUrl+"/#",0);
    if(index < 0){
    var goHash = location.href.replace(blogUrl, ”);
    location.href =blogUrl+ ‘#’ + goHash;
    }
    }

    jQuery(function($){

    //hrefをハッシュ付に変更
    function changeHref(){
    $("#contentsArea a,#siteId a,#widgetArea a").each(function(){
    var setHref = $(this).attr("href").replace(blogUrl, ‘#’);
    if(setHref.match(/^\//)){
    setHref = "#"+setHref;
    }

    $(this).attr({href:setHref});
    });
    }
    changeHref();

    //Ajaxで変更する部分
    var contentsArea = $("#contentsArea");
    contentsArea.css({height:0,opacity:0,marginBottom:0});

    var nowHash = "";
    $(window).hashchange(function() {
    var setHash = location.hash.replace(‘#’, ”);
    //for Front Page
    if(!setHash){
    setHash = "/?p=0";
    }
    //ページ内リンク(コメントの返信は除く)
    if(setHash.indexOf("#",0)>-1 && setHash.indexOf("respond",0)<0){
    var sel = setHash.match(/(#.+)$/);
    var target = $(sel[1]).offset().top;
    $(‘html,body’).delay(100).animate({ scrollTop: target }, 200,"easeOutQuart");

    }else{

    //コンテンツの削除
    contentsArea.animate({height:0,opacity:0,marginBottom:0},200,function(){
    //ロード
    $(this).hide().load(setHash+" #contents",function(){
    //表示
    $(this).delay(200).show().animate({height:$(this).find("#contents").height(),opacity:"1",marginBottom:"36px"},200,"easeOutQuart",function(){
    changeHref();
    //コメントの返信だった場合の処理
    if(setHash.indexOf("respond",0)>-1){
    var respondOffset = $("#respond").offset().top;
    $(‘html,body’).delay(100).animate({ scrollTop: respondOffset }, 200,"easeOutQuart");

    }

    });
    });
    });
    }
    nowHash = setHash;

    });

    //検索フォーム
    $("form").submit(function(){
    var s = $("#s").val();
    location.href = ‘/#/?s=’+s;
    return false;

    });

    $(window).hashchange();

    });
    </script>

    [/php]

    という感じでWordPressとの連携をとっています。トップページの記事はパラメーターにp=0を入れて表示しています。page_idやp等に存在しない値を放り込むとトップページの内容を表示することを利用しています。
    空白だといまいちうまくいきませんでしたので、こんなおかしなことをやっています。

    indexOfとmatchとか色々混在していて見づらいソースですが、そこはご愛敬ということで、ご勘弁下さい。徐々に直していこうと思いますので。

  • そういえば結構前の話ですが、Googleが検索順位に表示速度を反映するという発表がありました。

    またAmazonでは0.1秒表示速度が遅くなると1%売り上げが減るとか。

    そんな中、WordPressはSEO的には優れているのですが、毎回動的生成を行うために、表示速度の面で他のCMSと比較するとやや、遅いと言われています。

    そんなわけで今回はWordPressで作ったサイトを高速化することについて。

    (さらに…)

  • WordPressテーマの作り方その4。今回はfunctions.phpについてです。

    functions.phpとはテーマ内で使用する関数や設定等が記述されるファイルです。
    functions.phpはテーマが設定されている間、常時読み込まれているファイルです。管理画面を見ているときでもしっかり読み込まれています。ですので、複数のテンプレートファイルで同じコードを関数化、ないしクラス化して使い回すことができます。

    つまりは、
    [php]
    function hello(){
    echo "Hello World!!";
    }
    [/php]

    等という関数をfunctions.phpで定義しておくと、どのテンプレートファイルからも呼び出して使うことができる、ということです。WordPressのプラグインも基本的には同じような仕組みで動いていますので、プラグインでできることは大抵functions.phpに記述することが可能です。ただ、余り大がかりだと管理運用で面倒が発生すると思われるので、そういう場合はプラグイン化する方が良い気がします。

    また、ウィジェットエリアの定義、各種機能の有効化もこのファイルに記述することでなされています。
    とりあえず、よく使う物を書き並べていきます。

    (さらに…)

  • 前回は、テンプレートを部品分けすることをやりました。
    今回は1回目でさらっと書いた、テンプレート階層について、もう少し掘り下げていこうと思います。

    (さらに…)

  • カスタム分類のラベルが、wp_titleから出力されてしまうのを避けたかったのですが、プラグインなどを見つけられなかったので自作します。
    wp-include内のgeneral-template.php からwp_titleのソースを失敬して、必要なところだけを書き換えてfilterにかけているだけですが・・・・・。

    (さらに…)

  • 職場で新しく入った人にWordPress信者になって頂こうという布教活動の一環で、WordPressのテーマの作り方をまとめていきたいと思います。
    デフォルトでついてくるテーマtwentytenとか、色々配布テーマがありますよね。ただ、多機能だったりして、ブログテーマとしてはいいんだけど、WordPressのテーマを理解する上ではハードルが高い気がします。
    というわけで、ここではゼロから作ることをテーマにして、まとめていこうかなと思います。

    (さらに…)