Skip to content

Instantly share code, notes, and snippets.

@jasalt
Created August 15, 2025 15:23
Show Gist options
  • Save jasalt/dc3d9b7704da431e184096595e0637ea to your computer and use it in GitHub Desktop.
Save jasalt/dc3d9b7704da431e184096595e0637ea to your computer and use it in GitHub Desktop.
Block binding example for twig-templating block
<?php
// Example for https://github.com/jasalt/twig-templating-block (2025-08-15 714be3a)
// Example template
// <div class="favourited-videos {{ editor_classes }}">
// {% if videos %}
// {% for video in videos %}
// {{ include_template_part('cpt-video-card', video.id) }}
// {% endfor %}
// {% else %}
// <p>No videos to found</p>
// {% endif %}
// </div>
add_action('init', function(){
register_block_bindings_source(
'my-plugin/favourited-videos',
[
'label' => __('Favourited Videos', 'my-plugin'),
'get_value_callback' => 'get_favourited_videos_binding_value',
]
);
});
/**
* Get favourited videos for the current user
* Accepts block binding argument: 'limit': int
* e.g {"limit": 3}
*
* @param array $source_args The source arguments.
* @param WP_Block $block_instance The block instance.
* @return Timber\Post[] An array of Timber Post objects of user's favourited videos.
*/
function get_favourited_videos_binding_value($source_args, $block_instance) {
if (!is_user_logged_in()) {
return;
}
$limit = !empty($source_args['limit']) ? intval($source_args['limit']) : 9999;
$user_id = get_current_user_id();
$user_video_data = get_user_meta($user_id, 'user_video_data', true);
if (!is_array($user_video_data) || empty($user_video_data)) {
return;
}
// Filter for videos that have 'completed_at'
$favourited_videos = array_filter($user_video_data, function($video_data) {
return isset($video_data['favourited_at']);
});
if (empty($favourited_videos)) {
return [];
}
// Sort by 'completed_at' descending
uasort($favourited_videos, function($a, $b) {
return strtotime($b['favourited_at']) - strtotime($a['favourited_at']);
});
// Get the last N completed videos based on limit
$favourited_videos = array_slice($favourited_videos, 0, $limit, true);
// Get post IDs
$video_ids = array_keys($favourited_videos);
if (empty($video_ids)) {
return [];
}
// Get Timber posts for each video
$video_posts = array_map(function($video_id) {
return Timber::get_post($video_id);
}, $video_ids);
return $video_posts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment