钩子文档

ajax_query_attachments_args

💡 云策文档标注

概述

ajax_query_attachments_args 是一个 WordPress 过滤器,用于在 Ajax 调用中修改查询附件时传递给 WP_Query 的参数。它主要应用于媒体库模态窗口中的附件查询。

关键要点

  • 过滤器名称:ajax_query_attachments_args,用于过滤在 Ajax 调用中查询附件的参数数组。
  • 使用场景:在文章编辑屏幕的媒体库模态窗口中,控制附件的显示和查询条件。
  • 基本用法:通过 add_filter 添加回调函数,函数必须接收并返回查询数组,否则可能导致查询为空。
  • 参数说明:$query 是一个数组,可以修改、添加或删除现有参数,例如设置作者 ID 来限制附件显示。
  • 版本历史:从 WordPress 3.7.0 版本引入。

代码示例

add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );

function show_current_user_attachments( $query = array() ) {
    $user_id = get_current_user_id();
    if( $user_id ) {
        $query['author'] = $user_id;
    }
    return $query;
}

注意事项

  • 回调函数必须返回修改后的查询数组,否则查询将为空,不显示任何附件。
  • 函数名应唯一,避免与其他已声明的函数名冲突。
  • $query 是数组类型,允许灵活修改参数,如添加新键值对或移除现有项。

📄 原文内容

Filters the arguments passed to WP_Query during an Ajax call for querying attachments.

Description

See also

Parameters

$queryarray
An array of query variables.

More Information

The ajax_query_attachments_args filter is used to filter the query that fetches the attachments displayed in the media library modal on the post edit screen.

The filter is used like this

add_filter( 'ajax_query_attachments_args', 'filter_function_name', 10, 1 )

Where filter_function_name() is the function WordPress should call when the query is being modified. Note that the filter function must return the query array after it is finished processing, or the query will be empty and no attachments will be shown.

filter_function_name() should be a unique function name. It cannot match any other function name already declared.

Source

$query             = apply_filters( 'ajax_query_attachments_args', $query );

Changelog

Version Description
3.7.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    (From Codex)
    Only Show Current User’s Attachments

    add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );
    
    function show_current_user_attachments( $query = array() ) {
        $user_id = get_current_user_id();
        if( $user_id ) {
            $query['author'] = $user_id;
        }
        return $query;
    }

    Note that $query is an array – this means that you can modify (or remove) existing arguments as well as add new ones.

  2. Skip to note 4 content

    Only Show Current User’s Attachments

    add_filter( 'ajax_query_attachments_args', 'wpdocs_show_current_user_attachments' );
    
    function wpdocs_show_current_user_attachments( $query = array() ) {
        $user_id = get_current_user_id();
    
        if ( $user_id ) {
            $query['author'] = $user_id;
        }
    
        return $query;
    }

    Note that $query is an array – this means that you can modify (or remove) existing arguments as well as add new ones.