Skip to content

Instantly share code, notes, and snippets.

@sybrew
Last active February 21, 2024 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sybrew/94d779044a0a8b9bb31fd90c7d74c8ea to your computer and use it in GitHub Desktop.
Save sybrew/94d779044a0a8b9bb31fd90c7d74c8ea to your computer and use it in GitHub Desktop.
Example snippet to prepend image arrays from ACF generators for The SEO Framework.
<?php
// Do not include this PHP opening tag if PHP is already opened...
// Ref: https://theseoframework.com/docs/using-filters/
// Ref: https://wordpress.org/support/topic/featured-image-as-ogimage/
add_filter( 'the_seo_framework_image_generation_params', 'my_tsf_custom_image_generation_args', 10, 2 );
/**
* Adjusts image generation parameters.
*
* @link https://theseoframework.com/docs/api/filters/#append-image-generators-for-social-images
* @param array $params : [
* string size: The image size to use.
* boolean multi: Whether to allow multiple images to be returned.
* array cbs: The callbacks to parse. Ideally be generators, so we can halt remotely.
* array fallback: The callbacks to parse. Ideally be generators, so we can halt remotely.
* ];
* @param array|null $args The query arguments. Contains 'id' and 'taxonomy'.
* Is null when query is autodetermined.
* @return array $params
*/
function my_tsf_custom_image_generation_args( $params = [], $args = null ) {
if ( null === $args ) {
// In the loop.
if ( is_singular() ) {
$params['cbs'] = array_merge(
[ 'custom' => 'my_custom_tsf_acf_singular_image_generator' ], // prepend to regular callbacks.
$params['cbs'],
);
}
} else {
if ( 'single' === The_SEO_Framework\get_query_type_from_args( $args ) ) {
$params['cbs'] = array_merge(
[ 'custom' => 'my_custom_tsf_acf_singular_image_generator' ], // prepend to regular callbacks.
$params['cbs'],
);
}
}
return $params;
}
/**
* Generates an image URL and ID from an ACF array field.
*
* @generator
*
* @param array|null $args The query arguments. Accepts 'id' and 'taxonomy'.
* Leave null to autodetermine query.
* @param string $size The size of the image to get.
* @yield array : {
* string url: The image URL location,
* int id: The image ID,
* }
*/
function my_custom_tsf_acf_singular_image_generator( $args = null, $size = 'full' ) {
if ( ! function_exists( 'get_field' ) ) return;
$image = get_field( 'post-image', $args['id'] ?? tsf()->query()->get_the_real_id() );
if ( ! empty( $image['url'] ) ) {
yield [
'url' => $image['url'],
'id' => $image['id'] ?? 0, // Optional. Used for alt-tag and dimension fetching.
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment