0

編集:このクラスを機能させることができ、正しいコードを更新しました。値の最後に [0] を使用したくありません。このコードを改善する方法はありますか?

このクラスは、特定の投稿のすべてのカスタム キーを取得します。現在、画像の関連付けに使用しており、投稿で「related_image」、「related_image_wide」、「image_alt_text」の 3 つのキーを定義しています。

EDIT 2:私は最終的に、私が望む方法で値を取得することができました。これを見つけた人にとって、これが役立つことを願っています。コードが更新されました。

class article {
  private $alternative_text;
  private $custom_fields = array();


  public function __construct($post)
  {
    $val = array();
    $custom_field_keys = get_post_custom_keys();

    foreach ( $custom_field_keys as $key => $value ) 
    {
      // Custom_fields["a"] gets the value of the custom field "a" 
      $val = get_post_custom_values($value);
      $this->custom_fields[$value] = $val[0];
    }

    $this->alternative_text = $this->custom_fields["image_alt_text"];
  }


  public function relatedImage($type)
  {
    // Standard image to be shown with article
    if($type == 'normal')
      return $this->imageURL($this->custom_fields["related_image"]);

    // Wide image to be shown with article.
    if($type == 'wide')
      return $this->imageURL($this->custom_fields["related_image_wide"]);

    // Alternative image. Often used in article listing and not in main article
    if($type == 'alt')
      return $this->imageURL($this->custom_fields["related_image_alternative"]);      
  }

  private function imageURL($imgPath)
  {
    return '<img src="' . get_option('home') . '/wp-content/uploads' . $imgPath .'" alt="' . $this->alternative_text . '" title="' . $this->alternative_text . '" />';
  }

}

これは、テンプレート コードで行うことです。

//This is inside The Loop
$article = new article($post);
echo $article->relatedImage("normal");
4

1 に答える 1

1

実際には、これに役立つ組み込みのWordpress機能があります.

get_post_custom_values($key, $post_id)

したがって、「通常の」画像を取得したい場合は、(ループで)

echo get_post_custom_values('normal', get_the_ID())

詳細情報が必要な場合は、 Wordpress codexのリンクを参照してください。

于 2009-06-09T07:35:20.523 に答える