Passing Block Attribute Values to PHP Variables?

I have some PHP being pulled into my blocks via get_template_part() and I’d like to set up a block attribute that can update a variable in the PHP. Is this possible?

I’ve already tried including my PHP directly in the block and it seems like I could add attributes to the HTML elements in the PHP but for some reason the PHP loop does not work when I include the PHP directly in PG. It only executes properly if I call in the template.

I figured out a way to put the PHP into PG so I can assign actions to the non-php elements. It turns out that when you use get_template_part() you don’t need to include the global $post; but if you add the loop directly into PG then you have to add that. I also figured out how to use values for PHP if anyone ever needs to do that just assign an action to your block and use the none value for the “Use As” selector. Then in your code you can assign that value to a variable like I’ve done below:

$region_term = PG_Blocks::getAttribute( $args, 'region_slug' ); // this pulls the attribute to a variable so you can use it in your code
        $locations_region_filter_args = array(
            'tax_query' => array( 
                    'taxonomy' => 'regions', 
                    'field' => 'slug',
                    'terms' => $region_term //this will be populated by what the user selects in the WordPress Block from the admin page
            'post_parent__not_in' => array(0),
            'post_type' => 'locations',
            'post_status' => 'publish',
            'order' => 'DESC',
            'orderby' => 'menu_order'

@jonroc just wanted to ask you for the code :slight_smile: Thanks for posting the solution.

1 Like

@jonroc You are a scholar and a gentleman! I was going to work on this later this week for a project I’m wrestling with. Thanks for saving me a few hours and brain cells.


For reference, Block attributes can also be used as parameters for the Show posts action with “@block:attribute_id”:


post_type could be a dropdown attribute, categories a text field that understands cat,cat,cat and cat+cat+cat.

This works similar to WooCommerce Show products:

1 Like

Thanks for that! This is really helpful, and saved me a loooooooot of time! :wink: