ワードプレスのget_edit_post_linkフィルタの使用方法・解説

概要

get_edit_post_linkフィルタは、投稿記事の編集用リンクを取得する際に使用されます。このフィルタを利用することで、デフォルトの編集リンクを変更したり、特定の条件に基づいて異なるリンクを表示することが可能になります。以下は、このフィルタがよく使われる機能の例です。

  1. 投稿の編集画面へのカスタムリンクを作成する。
  2. 投稿の編集リンクにカスタムパラメータを追加する。
  3. 管理者のみに編集リンクを表示する。
  4. 特定の投稿タイプに対してのみ編集リンクを修正する。
  5. 自動的に編集リンクを生成するウィジェットを作成する。
  6. 一覧表示でのリンクの出力形式をカスタマイズする。
  7. ユーザーの権限に基づいて編集リンクを変更する。
  8. 特定の条件に基づいて編集リンクを削除する。

このフィルタの構文は以下の通りです。

apply_filters( 'get_edit_post_link', string $link, int $post_id, string $context = '' );

パラメータ

  • $link: 編集リンクのURL。
  • $post_id: 編集する投稿のID。
  • $context: 編集リンクのコンテキスト (例: ‘display’, ‘raw’)。

戻り値

  • 編集リンクを変更した結果のURL。

関連する関数

関数の詳細は こちら から確認できます。

使用可能なバージョン

このフィルタは、WordPress 2.5以降で使用可能です。

コアファイルのパス

wp-includes/post.php

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1

add_filter( 'get_edit_post_link', 'custom_edit_post_link', 10, 3 );
function custom_edit_post_link( $link, $post_id, $context ) {
    return str_replace( 'wp-admin/', 'my-custom-admin/', $link );
}

このサンプルは、デフォルトの編集リンクのURLをカスタム管理パスに置き換えます。

サンプルコード2

add_filter( 'get_edit_post_link', 'add_custom_query_param', 10, 3 );
function add_custom_query_param( $link, $post_id, $context ) {
    return add_query_arg( 'custom_param', 'value', $link );
}

このサンプルは、編集リンクにカスタムクエリパラメータを追加します。

サンプルコード3

add_filter( 'get_edit_post_link', 'restrict_edit_link_for_authors', 10, 3 );
function restrict_edit_link_for_authors( $link, $post_id, $context ) {
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return '';
    }
    return $link;
}

このサンプルは、投稿の編集権限がないユーザーに対して編集リンクを非表示にします。

サンプルコード4

add_filter( 'get_edit_post_link', 'customize_link_for_post_type', 10, 3 );
function customize_link_for_post_type( $link, $post_id, $context ) {
    $post_type = get_post_type( $post_id );
    if ( $post_type == 'my_custom_post_type' ) {
        return str_replace( 'wp-admin/', 'my-custom-admin/', $link );
    }
    return $link;
}

このサンプルは、特定の投稿タイプに対して編集リンクを変更します。

サンプルコード5

add_filter( 'get_edit_post_link', 'remove_edit_link_conditionally', 10, 3 );
function remove_edit_link_conditionally( $link, $post_id, $context ) {
    if ( get_post_status( $post_id ) == 'private' && ! current_user_can( 'edit_private_posts' ) ) {
        return '';
    }
    return $link;
}

このサンプルは、プライベートな投稿に対して適切な権限を持たないユーザーに編集リンクを非表示にします。

この関数について質問する


上の計算式の答えを入力してください