サポート » 使い方全般 » カスタムフィールドの値の有無での条件分岐

  • 解決済 bigi879

    (@bigi879)


    よろしくお願いいたします。

    カスタムフィールドを使い、以下のようなソースを書いていますがうまく行きません。

    ・カスタムフィールドの「description」に記述があればそれを使い、なければデフォルトの文章を表示させます。

    <?php //meta descriptionの設定
    $custom_fields = get_post_custom();
    $description = $custom_fields['description'];
    if ($description != null) { ?>
    <meta name="description" content="<?php echo get_post_meta($post->ID,'description',true); ?>" />
    <?php }
    else { ?>
    <meta name="description" content="<?php bloginfo('description'); ?>" />
    <?php }
    ?>

    カスタムフィールドの値がなくても、なぜかカスタムフィールドの方を表示しようとしてしまいます。

    プラグインで、Advanced Custom Fieldsを使っています。
    これが何か悪さをしているのでしょうか?

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • $description != null で判定されていますが、空の値が入っているのではないでしょうか?
    下記のようにするとどうでしょう?

    <?php //meta descriptionの設定
     $description = get_post_meta( $post->ID, 'description', true );
    if ( !empty( $description ) ) : ?>
    <meta name="description" content="<?php echo esc_attr( $description ); ?>" />
    <?php else: ?>
    <meta name="description" content="<?php bloginfo( 'description' ); ?>" />
    <?php endif; ?>
    トピック投稿者 bigi879

    (@bigi879)

    inc2734様

    素晴らしいです!
    バッチリうまくいきました。
    早急にご指示いただきありがとうございました!
    また今後ともよろしくお願いいたします。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「カスタムフィールドの値の有無での条件分岐」には新たに返信することはできません。