Support Forum
Support › MB Relationships › Memory issues and unbound queries - "Query posts for field options"
We have issue where at times the Connect To metabox is running out of memory. It's unbound query that we cannot ship to production with our current hosting provider. Happy to help work on a solution.
Here is the function:
/**
* Query posts for field options.
*
* @param array $field Field settings.
* @return array Field options array.
*/
public static function query( $field ) {
$args = wp_parse_args(
$field['query_args'],
array(
'post_type' => $field['post_type'],
'post_status' => 'publish',
'posts_per_page' => -1,
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
)
);
// Get from cache to prevent same queries.
$cache_key = md5( serialize( $args ) );
$options = wp_cache_get( $cache_key, 'meta-box-post-field' );
if ( false !== $options ) {
return $options;
}
$query = new WP_Query( $args );
$options = array();
foreach ( $query->posts as $post ) {
$options[ $post->ID ] = array_merge(
array(
'value' => $post->ID,
'label' => $post->post_title,
'parent' => $post->post_parent,
),
(array) $post
);
}
// Cache the query.
wp_cache_set( $cache_key, $options, 'meta-box-post-field' );
return $options;
}
Hi Vinny,
Do you have a lot of posts? Can you try increase the memory limit?
https://wordpress.org/support/article/editing-wp-config-php/#increasing-memory-allocated-to-php
We have a lot of posts. We use WordPress for our newsroom so we have 10s of thousands of posts and reach millions of visitors reach month.
Our hosting and development partner, Humanmade, has really strict standards for code review. And, asking for increased memory isn't really an option especially if it's because of a query they don't permit.
We greatly appreciate the response.
We are already at a 192M limit and even increasing it to 512M doesn't solve our problem with the current implementation.
Can the above function get optimized?
There is no way for us to figure out all the use cases for this core function, but does MB really need to store all post fields?
The metabox plugin for relationships is only using the custom values setting for value
, label
, and parent
.
Hi Vinny,
The query function makes sure you can get all posts to connect to/from. If you don't need to do that, you can optimize the query by using the query_args
parameter for the from
or to
side to avoid the 'posts_per_page' => -1
.
See this docs for details:
https://docs.metabox.io/extensions/mb-relationships/#syntax
There is no way for us to figure out all the use cases for this core function, but does MB really need to store all post fields?
As you see, we're using WP_Query
and it doesn't have any option to return some fields. Besides, we need all post fields in case developers want to filter what field to display.