Skip to content
Blocks Code

PHP

PHP output method gives you full access to WordPress functions and PHP features while rendering your block content.

PHP code editor in block builder

Basic Usage

Access block controls through the $attributes array:

Simple Example
<?php if ($attributes['show_title']) : ?>
    <h2><?php echo esc_html($attributes['title']); ?></h2>
<?php endif; ?>

Common Examples

Working with Images

Image Control
<?php
if (isset($attributes['image']['url'])) :
    $image_url = esc_url($attributes['image']['url']);
    $image_alt = esc_attr($attributes['image']['alt']);
    ?>
    <img src="<?php echo $image_url; ?>"
         alt="<?php echo $image_alt; ?>"
         class="featured-image">
<?php endif; ?>

Repeater Fields

Repeater Control
<?php if (isset($attributes['items']) && is_array($attributes['items'])) : ?>
    <ul class="items-list">
        <?php foreach ($attributes['items'] as $item) : ?>
            <li class="item">
                <?php echo esc_html($item['title']); ?>
                <p><?php echo wp_kses_post($item['description']); ?></p>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

Using WordPress Functions

WordPress Integration
<?php
// Get related posts
$related = get_posts([
    'category__in' => wp_get_post_categories(get_the_ID()),
    'numberposts'  => $attributes['posts_count'],
    'post__not_in' => [get_the_ID()]
]);
 
if ($related) : ?>
    <div class="related-posts">
        <h3><?php esc_html_e('Related Posts', 'your-textdomain'); ?></h3>
        <ul>
            <?php foreach ($related as $post) : ?>
                <li>
                    <a href="<?php echo esc_url(get_permalink($post->ID)); ?>">
                        <?php echo esc_html($post->post_title); ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

Always use proper escaping functions:

  • esc_html() for text content
  • esc_attr() for HTML attributes
  • esc_url() for URLs
  • wp_kses_post() for HTML content

Was this article helpful?