函数文档

get_options()

💡 云策文档标注

概述

get_options() 函数用于批量检索多个选项值,通过 wp_prime_option_caches() 优化数据库查询,最多仅需一次查询。

关键要点

  • 参数:接受一个字符串数组 $options,包含要检索的选项名称。
  • 返回值:返回一个键值对数组,键为选项名,值为对应的选项值。
  • 内部机制:先调用 wp_prime_option_caches() 预加载选项到缓存,再循环使用 get_option() 获取每个选项。
  • 引入版本:WordPress 6.4.0 中首次引入。

代码示例

$options = get_options( array(
    'siteurl', 
    'blogname', 
    'blogdescription', 
    'posts_per_page', 
    'admin_email'
) );
// print all options keys
print_r( $options );

// print single option key
echo esc_html( $options['admin_email'] );

📄 原文内容

Retrieves multiple options.

Description

Options are loaded as necessary first in order to use a single database query at most.

Parameters

$optionsstring[]required
An array of option names to retrieve.

Return

array An array of key-value pairs for the requested options.

Source

function get_options( $options ) {
	wp_prime_option_caches( $options );

	$result = array();
	foreach ( $options as $option ) {
		$result[ $option ] = get_option( $option );
	}

	return $result;
}

Changelog

Version Description
6.4.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can retrieves multiple options using option keys, like below:

    $options = get_options( array(
        'siteurl', 
        'blogname', 
        'blogdescription', 
        'posts_per_page', 
        'admin_email'
    ) 
    );
    // print all options keys
    print_r( $options );
    
    // print single option key
    echo esc_html( $options['admin_email'] );