Fix WPML integration for Cloudinary media inserted prior to WPML activation#1159
Fix WPML integration for Cloudinary media inserted prior to WPML activation#1159gabrielcld2 wants to merge 3 commits intodevelopfrom
Conversation
php/relate/class-relationship.php
Outdated
|
|
||
| // phpcs:ignore WordPress.DB | ||
| $sql = $wpdb->prepare( | ||
| "SELECT * FROM {$table_name} WHERE `post_id` = %d AND `media_context` IN ({$context_query})", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared |
There was a problem hiding this comment.
💬 suggestion: The query now searches for multiple contexts (e.g. en and default), but get_row() returns only one row. Without an ORDER BY, which row you get is up to MySQL. If a post has rows for both contexts, you want the current one (en) first and default only as a fallback.
Current code:
$sql = $wpdb->prepare(
"SELECT * FROM {$table_name} WHERE `post_id` = %d AND `media_context` IN ({$context_query})",
$this->post_id,
...$contexts
);
$data = $wpdb->get_row( $sql, ARRAY_A );Suggested fix:
$sql = $wpdb->prepare(
"SELECT * FROM {$table_name} WHERE `post_id` = %d AND `media_context` IN ({$context_query}) ORDER BY FIELD(`media_context`, %s) DESC LIMIT 1",
$this->post_id,
...$contexts,
$this->context
);
$data = $wpdb->get_row( $sql, ARRAY_A );FIELD(media_context, %s) scores 1 for an exact match on the current context and 0 for everything else. DESC puts the exact match first.
There was a problem hiding this comment.
@PatelUtkarsh thanks! I learned something today, didn't know about this ORDER BY FIELD trick 🤯I've implemented it bc33e6e.
Only slight difference in my implementation is I extracted the query parameters in an array as we cannot add another parameter after using ... operator.

The issue
When Cloudinary is enabled without WPML,
cloudinary_relationshipsentries are inserted with amedia_contextset todefault.Once WPML is activated though, new
cloudinary_relationshipsentries have theirmedia_contextset to the current language (e.g.enfor English).Furthermore, when posts are looking for the relationships data for specific images, it currently attempts to fetch them using the current language for context.
This works well in the case where WPML was activated prior to Cloudinary, however creates some issues when activation is done the other way around:
enand therefore won't find the corresponding cloudinary_relationships entries, resulting in not found assetsApproach
QA notes