我的建议是提取代码的查询部分:
function get_brands() {
$loop_brands = array();
wp_nonce_field( plugin_basename( __FILE__ ), \'brands-nonce-field\' );
$args = array(
\'post_type\' => \'page\',
\'post_parent\' => 7,
\'orderby\' => \'title\',
\'order\' => \'ASC\'
);
$query_brands = new WP_Query($args);
return $query_brands;
}
然后像这样使用:
function brands_save_meta_box( $post_id ) {
$loop_brands = get_brands();
$loop_brands = wp_list_pluck($loop_brands->posts,\'post_name\');
foreach ( $loop_brands as $brand ) {
if ( brands_user_can_save( $post_id, $brand ) ) {
if ( isset( $_POST[ $brand ] ) ) {
update_post_meta( $post_id, $brand, $_POST[ $brand ]);
} else {
delete_post_meta( $post_id, $brand);
}
}
}
}
这将是第一步。除非我犯了错误,否则代码应该像以前一样工作,但不必担心
global
.
然后,如果愿意,您可以转向更复杂的解决方案,该解决方案涉及一些“缓存”:
function brands_query() {
$loop_brands = array();
wp_nonce_field( plugin_basename( __FILE__ ), \'brands-nonce-field\' );
$args = array(
\'post_type\' => \'page\',
\'post_parent\' => 7,
\'orderby\' => \'title\',
\'order\' => \'ASC\'
);
$query_brands = new WP_Query($args);
return $query_brands;
}
function get_brands() {
$brands = get_option(\'loop_brands\');
if (empty($brands)) {
$brands = brands_query();
update_option(\'loop_brands\',$brands);
}
return $brands;
}
如果我读对了,你真的只需要刷新一下
loop_brands
在页面上保存。类似这样:
function save_brands($post_id) {
$brands = brands_query();
update_option(\'loop_brands\',$brands);
}
add_action(\'save_post_page\',\'save_brands\');