Support » Developing with WordPress » Using pre_get_posts on a specific core/query block

  • I’m trying to apply the pre_get_posts to a specific core/query block, in order to programatically modify the number of posts displayed when a custom attribute is set. If I use the render_block hook, the block is already pre-rendered and so modifying the query using pre_get_posts has no effect. Is there any way to achieve this?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    To use “pre_get_posts” you’ll need to somehow differentiate the targeted query from all other queries. There are a series of is_*() query object methods that can be used to help do so, but they are often too broad. Sometimes you can distinguish the targeted query by some distinct query var or value. Dump out $query->query_vars from within the callback to see if there’s anything useful.

    Another way to ensure you only alter the targeted query is to add the callback in other code just before it’s needed. The callback can then remove itself from the call stack to avoid influencing other queries that may occur later.

    Of course the best way to alter a query is to provide the desired args when the query is instantiated. You’d need access to the code that does so, which isn’t always an option.

    Thread Starter Mark Howells-Mead

    (@markhowellsmead)

    Thank you for your suggestions. The block can appear be used anywhere in the content or in the full-site editor, so the is_* functions can’t help. The query vars don’t contain anything I can use and I can’t access the block attributes at a point suitable to add a custom query_var based on the block attribute.

    The solution I need is definitely using add_filter and then remove_filter at the appropriate point immediately before and after the query. After a couple of hours of going through the core code, I can’t find the point at which WP_Query is executed for the core/query block. I’ve tried all the filters in the WP_Block class, to no avail.

    Thread Starter Mark Howells-Mead

    (@markhowellsmead)

    I’ve spoken with colleagues and found that it’s currently impossible to modify the query args in this case. The following trac ticket addresses it. https://core.trac.wordpress.org/ticket/54850

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.