wpseo_replace_vars()


WordPress関数wpseo_replace_vars()は、Yoast SEOプラグインで利用され、特定の変数を文字列に置き換えるために使用されます。この関数は主にSEOテンプレートやカスタムテキストの生成に役立ちます。

構文

wpseo_replace_vars( string $string, object $post );

引数の説明

  • $string (string) — 置換対象のテンプレート文字列。
  • $post (object) — 現在の投稿またはページオブジェクト。

例 1: 基本的な変数の置き換え

テンプレート文字列内の%%title%%を投稿のタイトルに置き換えます。

<?php
$string = 'この投稿のタイトルは%%title%%です。';
$post = get_post();
$result = wpseo_replace_vars( $string, $post );
echo $result;
?>

例 2: カスタムフィールドの値を使用した置き換え

カスタムフィールド%%cf_my_field%%を具体的な値に置き換えます。

<?php
$string = 'カスタムフィールドの値: %%cf_my_field%%';
$post = get_post();
update_post_meta( $post->ID, 'my_field', 'カスタムデータ' );
$result = wpseo_replace_vars( $string, $post );
echo $result;
?>

例 3: 著者名の挿入

テンプレート文字列内の%%name%%を投稿の著者名に置き換えます。

<?php
$string = 'この投稿は%%name%%が作成しました。';
$post = get_post();
$result = wpseo_replace_vars( $string, $post );
echo $result;
?>

例 4: 日付情報の置き換え

投稿の日付を%%date%%でテンプレートに挿入します。

<?php
$string = 'この投稿は%%date%%に公開されました。';
$post = get_post();
$result = wpseo_replace_vars( $string, $post );
echo $result;
?>

例 5: 複数の変数を含むテンプレート文字列

複数の変数を一度に置き換える例です。

<?php
$string = 'タイトル: %%title%% | 著者: %%name%% | 日付: %%date%%';
$post = get_post();
$result = wpseo_replace_vars( $string, $post );
echo $result;
?>

注意事項

  • カスタムフィールド変数を使用する場合、該当する値が設定されている必要があります。
  • 未定義の変数は空文字列に置き換えられます。