Skip to content

Instantly share code, notes, and snippets.

@propertyhive
Created October 21, 2025 09:38
Show Gist options
  • Save propertyhive/a173e38ab3de97ec12a8035005d508ed to your computer and use it in GitHub Desktop.
Save propertyhive/a173e38ab3de97ec12a8035005d508ed to your computer and use it in GitHub Desktop.
add_shortcode( 'office_logo', function( $atts = [], $content = '' ) {
// Allow optional overrides
$atts = shortcode_atts(
[
'post_id' => 0, // property post ID (optional override)
'size' => 'full', // image size: thumbnail, medium, large, full
],
$atts,
'office_logo'
);
// Resolve the property post ID
$post_id = absint( $atts['post_id'] );
if ( ! $post_id ) {
// Try to get from global $post context or queried object
$post_id = get_the_ID();
if ( ! $post_id ) {
$post_id = get_queried_object_id();
}
}
if ( ! $post_id ) {
return ''; // No context to work with
}
// 1) From the property post, get the linked Office ID
$office_id = get_post_meta( $post_id, '_office_id', true );
$office_id = $office_id ? absint( $office_id ) : 0;
if ( ! $office_id ) {
return '';
}
// 2) From the Office post, get the _logo meta (attachment ID)
$logo_id = get_post_meta( $office_id, '_logo', true );
$logo_id = $logo_id ? absint( $logo_id ) : 0;
if ( ! $logo_id ) {
return '';
}
// Prefer WordPress' helper to output a full <img> tag (with alt/srcset)
$img_html = wp_get_attachment_image(
$logo_id,
$atts['size'],
false,
[
'loading' => 'lazy',
'decoding' => 'async',
]
);
// Fallback: build a plain <img> if helper didn't return anything
if ( ! $img_html ) {
$src = wp_get_attachment_image_url( $logo_id, $atts['size'] );
if ( ! $src ) {
return '';
}
$alt = get_post_meta( $logo_id, '_wp_attachment_image_alt', true );
$img_html = sprintf(
'<img src="%s" alt="%s" loading="lazy" decoding="async" />',
esc_url( $src ),
esc_attr( $alt )
);
}
return $img_html;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment