Skip to content

Instantly share code, notes, and snippets.

@addisonhall
Created May 23, 2025 14:53
Show Gist options
  • Select an option

  • Save addisonhall/fda92e2178e07e418b86c08c3fa221e7 to your computer and use it in GitHub Desktop.

Select an option

Save addisonhall/fda92e2178e07e418b86c08c3fa221e7 to your computer and use it in GitHub Desktop.
block.php for custom blocks where a post object field selects post for output. Custom hook name for use with GenerateBlocks elements.
<?php
/**
* ACF Block PHP for custom blocks where a post object field selects post for output.
* Custom hook name for use with GenerateBlocks elements.
*
* @link https://www.advancedcustomfields.com/resources/create-your-first-acf-block/
* @see https://youtu.be/TZsVq-jd0Ao
*/
// don't access this file directly!
if ( ! defined( 'ABSPATH' ) ) exit;
// set our values
$post_id = get_field( 'your_post_object_field' ); // ACF post object field with selected post
$post_type = 'which_post_type'; // post type name to query
$hook_name = 'custom_hook_name'; // custom hook name for GenerateBlocks Element
// if a post object was selected...
if ( $post_id ) {
// set up our options (or "arguments") for querying
$query_args = array (
'post_type' => $post_type,
'posts_per_page' => 1,
'p' => $post_id // <- this bit makes sure the specific post is pulled based on selection in block
);
// create our query using our options
$block_query = new WP_Query( $query_args );
// standard WP_Query stuff to return what we've queried
if ( $block_query->have_posts() ) {
while ( $block_query->have_posts() ) {
$block_query->the_post();
// this custom hook references our GeneratePress Element where we can build and style the output
do_action( $hook_name );
}
}
// once we're done, reset WP's post data to go back to business as usual
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment