Tom Gonzales
Support threads created in the last 30 days: 0
Favorite Forum Topics
This user has no favorite topics.
Forum Topics Created
Status | Topic | Supporter | Voices | Posts | Freshness |
---|---|---|---|---|---|
Is it possible to use custom post fields within a WordPress shortcode?
Started by: Tom Gonzales
in: Toolset Professional Support
Problem: I would like to use the standard WordPress gallery shortcode to display a gallery that includes images from my custom fields. If no custom field images are defined, I would like to not show a gallery. Solution: Since the gallery shortcode requires a comma-separated list of image IDs, but custom fields only store individual image URLs, you must use some custom code to translate your stored image URLs into a comma-separated list of IDs: function prefix_get_img_ids($atts) { global $post; $postid = isset($atts['post_id']) ? $atts['post_id'] : $post->ID; $images[] = get_post_meta($postid, 'wpcf-pc-extra-image-1', true); $images[] = get_post_meta($postid, 'wpcf-pc-extra-image-2', true); // if you want to include more images, copy + paste here with the appropriate image field slug $ids = array(); global $wpdb; foreach($images as $img) { $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$img'"; $id = $wpdb->get_var($query); if($id) $ids[] = $id; } return implode(",",$ids); } add_shortcode("get_image_ids", "prefix_get_img_ids"); Then you can use the gallery shortcode along with your custom shortcode like so: [gallery ids="[get_image_ids post_id='12345']"] Replace '12345' with the numeric ID of the post where your custom field images are defined. Then you must register the get_image_ids function as a 3rd-party shortcode argument in Toolset > Settings > Front-end Content. If you want to hide the gallery when images are not defined, you can use a conditional. Relevant Documentation: https://toolset.com/documentation/user-guides/shortcodes-within-shortcodes/ |
2 | 9 | 7 years, 3 months ago |