-
Notifications
You must be signed in to change notification settings - Fork 92
gpeb-display-stars-for-rating-fields.php
: Added customizable SVG star with empty star display option for rating fields.
#1143
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
…ar with empty star display option for rating fields.
WalkthroughThe code now renders rating fields using configurable SVG-based stars instead of repeated star characters. It introduces a configuration array for star appearance, updates field values to SVG markup based on ratings, and adds a function to decode HTML-encoded SVGs for proper display. Relevant filters are updated to apply these changes. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant EntryDisplay
participant SVGRenderer
participant SVGDecoder
User->>EntryDisplay: View entry with rating field
EntryDisplay->>SVGRenderer: Render rating field as SVG stars
SVGRenderer-->>EntryDisplay: Return SVG star markup
EntryDisplay->>SVGDecoder: Decode HTML-encoded SVGs in content
SVGDecoder-->>EntryDisplay: Return decoded content
EntryDisplay-->>User: Display entry with SVG stars
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (3)
gp-entry-blocks/gpeb-display-stars-for-rating-fields.php (3)
16-16
: Optional: prefer CSS color via currentColor for simpler themingIf you’re open to CSS-driven theming, set stroke="currentColor" on the base SVG and control colors with the wrapper/container class. Keep fill/color on the variants as you do now.
-$star_svg = '<svg ... stroke="' . esc_attr( $star_color ) . '" ...> +$star_svg = '<svg ... stroke="currentColor" ...>Then set the color via CSS on .gpeb-rating, and keep the inline fill for filled vs outline variants as-is. This makes per-context color overrides trivial without regenerating the SVG string.
44-45
: Hook names look correct; update callback if you rename itIf you adopt the function prefixing, point the filters at the new name.
-add_filter('gpeb_loop_entry_content', 'decode_rating_field_svgs', 10, 3); -add_filter('gpeb_view_entry_content', 'decode_rating_field_svgs', 10, 3); +add_filter( 'gpeb_loop_entry_content', 'gpeb_decode_rating_field_svgs', 10, 3 ); +add_filter( 'gpeb_view_entry_content', 'gpeb_decode_rating_field_svgs', 10, 3 );
7-17
: General: small robustness and DX tweaks
- Consider exposing an additional config key 'total_stars' to override count($field->choices) when needed (e.g., legacy entries with mismatched choices). You can default to count($field->choices) when not provided.
- Optionally add an 'empty_star_stroke_color' to differentiate outline color from filled color.
- Add brief attribution comment for Feather icon in the header if your project requires third‑party asset attribution.
Happy to update the PR with the above changes if you want me to push a patch.
Also applies to: 23-27, 36-45
$config = [ | ||
'star_size' => '24', // Width/height of stars in pixels | ||
'star_color' => '#FFAC33', // Color of the stars | ||
'stroke_width' => '1.5', // Thickness of star outline | ||
'show_empty_stars' => false, // Whether to show empty stars | ||
]; | ||
|
||
$star_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' . $config['star_size'] . '" height="' . $config['star_size'] . '" viewBox="0 0 24 24" stroke="' . $config['star_color'] . '" stroke-width="' . $config['stroke_width'] . '" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Make star settings filterable and sanitize before output
Let integrators adjust defaults via a filter and sanitize values prior to building the SVG. This also avoids stringly-typed numbers.
Apply:
- $config = [
- 'star_size' => '24', // Width/height of stars in pixels
- 'star_color' => '#FFAC33', // Color of the stars
- 'stroke_width' => '1.5', // Thickness of star outline
- 'show_empty_stars' => false, // Whether to show empty stars
- ];
+ $config = apply_filters( 'gpeb_rating_stars_config', [
+ 'star_size' => 24, // Width/height of stars in pixels
+ 'star_color' => '#FFAC33', // Color of the stars (hex)
+ 'stroke_width' => 1.5, // Thickness of star outline
+ 'show_empty_stars' => false, // Whether to show empty stars
+ ], $entry, $form );
+
+ // Sanitize for output.
+ $star_size = max( 1, (int) $config['star_size'] );
+ $stroke_width = (float) $config['stroke_width'];
+ $star_color = sanitize_hex_color( $config['star_color'] ) ?: '#FFAC33';
And use the sanitized vars when building the SVG:
-$star_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' . $config['star_size'] . '" height="' . $config['star_size'] . '" viewBox="0 0 24 24" stroke="' . $config['star_color'] . '" stroke-width="' . $config['stroke_width'] . '" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>';
+$star_svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' . esc_attr( $star_size ) . '" height="' . esc_attr( $star_size ) . '" viewBox="0 0 24 24" stroke="' . esc_attr( $star_color ) . '" stroke-width="' . esc_attr( $stroke_width ) . '" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>';
🤖 Prompt for AI Agents
In gp-entry-blocks/gpeb-display-stars-for-rating-fields.php around lines 9 to
16, the star configuration settings are hardcoded and not filterable, and the
values are used as strings without sanitization. To fix this, wrap the $config
array in a filter to allow integrators to modify the defaults, then sanitize
each value properly (e.g., cast sizes and stroke width to integers or floats,
sanitize color as a hex color). Finally, use these sanitized variables when
constructing the SVG string instead of the original unfiltered values.
$filled_stars = str_repeat(str_replace('<svg ', '<svg fill="' . $config['star_color'] . '" class="gpeb-filled-star" ', $star_svg), $index + 1); | ||
$empty_stars = $config['show_empty_stars'] ? str_repeat(str_replace('<svg ', '<svg fill="none" class="gpeb-outline-star" ', $star_svg), 5 - ($index + 1)) : ''; | ||
|
||
$entry[$field->id] = $filled_stars . $empty_stars; | ||
break; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Don’t assume 5 stars; derive total from field choices and compute filled count from selected value; add basic a11y
Hard-coding 5 breaks for rating fields with a different number of choices. Also, relying on the choice index can be wrong if values aren’t sequential. Compute from the selected value when numeric and clamp to total choices. Add aria to improve accessibility and mark individual SVGs as decorative.
Please test with rating fields configured for 3 and 10 choices, and with non-sequential choice values, to confirm correct rendering.
- $filled_stars = str_repeat(str_replace('<svg ', '<svg fill="' . $config['star_color'] . '" class="gpeb-filled-star" ', $star_svg), $index + 1);
- $empty_stars = $config['show_empty_stars'] ? str_repeat(str_replace('<svg ', '<svg fill="none" class="gpeb-outline-star" ', $star_svg), 5 - ($index + 1)) : '';
-
- $entry[$field->id] = $filled_stars . $empty_stars;
+ // Derive counts.
+ $total_stars = is_array( $field->choices ) ? count( $field->choices ) : 5;
+ $filled_count = is_numeric( $selected_value ) ? (int) $selected_value : ( $index + 1 );
+ $filled_count = max( 0, min( $filled_count, $total_stars ) );
+ $empty_count = max( 0, $total_stars - $filled_count );
+
+ // Build star variants (each SVG marked decorative).
+ $filled_star = str_replace(
+ '<svg ',
+ '<svg aria-hidden="true" focusable="false" fill="' . esc_attr( $star_color ) . '" class="gpeb-filled-star" ',
+ $star_svg
+ );
+ $outline_star = str_replace(
+ '<svg ',
+ '<svg aria-hidden="true" focusable="false" fill="none" class="gpeb-outline-star" ',
+ $star_svg
+ );
+
+ $filled_stars = str_repeat( $filled_star, $filled_count );
+ $empty_stars = $config['show_empty_stars'] ? str_repeat( $outline_star, $empty_count ) : '';
+
+ // Wrap with an accessible label.
+ $entry[ $field->id ] = sprintf(
+ '<span class="gpeb-rating" role="img" aria-label="%1$d out of %2$d">%3$s%4$s</span>',
+ $filled_count,
+ $total_stars,
+ $filled_stars,
+ $empty_stars
+ );
🏁 Script executed:
#!/bin/bash
# Locate the display-stars file
file_path=$(fd gpeb-display-stars-for-rating-fields.php)
echo "Located file at: $file_path"
# Display the first 200 lines to inspect context around lines 23-27
sed -n '1,200p' "$file_path"
Length of output: 2499
Derive star count from field choices and improve accessibility
The current implementation in gp-entry-blocks/gpeb-display-stars-for-rating-fields.php (lines 23–27) hard-codes a 5-star total and uses the choice index to calculate filled stars. This will break when a rating field is configured with more or fewer stars—or if choice values aren’t sequential—and the SVGs lack the necessary ARIA attributes. Please update as follows:
• Compute the total number of stars from count( $field->choices ) instead of using 5.
• Calculate the filled count from the numeric selected value, then clamp it between 0 and the total.
• Build filled/outline SVG strings with aria-hidden="true" and focusable="false".
• Wrap the output in a … for basic a11y.
Example diff:
- $filled_stars = str_repeat(
- str_replace(
- '<svg ',
- '<svg fill="' . $config['star_color'] . '" class="gpeb-filled-star" ',
- $star_svg
- ),
- $index + 1
- );
- $empty_stars = $config['show_empty_stars']
- ? str_repeat(
- str_replace(
- '<svg ',
- '<svg fill="none" class="gpeb-outline-star" ',
- $star_svg
- ),
- 5 - ($index + 1)
- )
- : '';
- $entry[ $field->id ] = $filled_stars . $empty_stars;
+ // Derive counts.
+ $total_stars = is_array( $field->choices ) ? count( $field->choices ) : 5;
+ $filled_count = is_numeric( $selected_value )
+ ? (int) $selected_value
+ : ( $index + 1 );
+ $filled_count = max( 0, min( $filled_count, $total_stars ) );
+ $empty_count = $total_stars - $filled_count;
+
+ // Prepare decorative SVGs.
+ $filled_star = str_replace(
+ '<svg ',
+ '<svg aria-hidden="true" focusable="false" fill="' . esc_attr( $config['star_color'] ) . '" class="gpeb-filled-star" ',
+ $star_svg
+ );
+ $outline_star = str_replace(
+ '<svg ',
+ '<svg aria-hidden="true" focusable="false" fill="none" class="gpeb-outline-star" ',
+ $star_svg
+ );
+
+ $filled_stars = str_repeat( $filled_star, $filled_count );
+ $empty_stars = $config['show_empty_stars']
+ ? str_repeat( $outline_star, $empty_count )
+ : '';
+
+ // Wrap with accessible label.
+ $entry[ $field->id ] = sprintf(
+ '<span class="gpeb-rating" role="img" aria-label="%1$d out of %2$d">%3$s%4$s</span>',
+ $filled_count,
+ $total_stars,
+ $filled_stars,
+ $empty_stars
+ );
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
$filled_stars = str_repeat(str_replace('<svg ', '<svg fill="' . $config['star_color'] . '" class="gpeb-filled-star" ', $star_svg), $index + 1); | |
$empty_stars = $config['show_empty_stars'] ? str_repeat(str_replace('<svg ', '<svg fill="none" class="gpeb-outline-star" ', $star_svg), 5 - ($index + 1)) : ''; | |
$entry[$field->id] = $filled_stars . $empty_stars; | |
break; | |
// Derive counts. | |
$total_stars = is_array( $field->choices ) ? count( $field->choices ) : 5; | |
$filled_count = is_numeric( $selected_value ) | |
? (int) $selected_value | |
: ( $index + 1 ); | |
$filled_count = max( 0, min( $filled_count, $total_stars ) ); | |
$empty_count = $total_stars - $filled_count; | |
// Prepare decorative SVGs. | |
$filled_star = str_replace( | |
'<svg ', | |
'<svg aria-hidden="true" focusable="false" fill="' . esc_attr( $config['star_color'] ) . '" class="gpeb-filled-star" ', | |
$star_svg | |
); | |
$outline_star = str_replace( | |
'<svg ', | |
'<svg aria-hidden="true" focusable="false" fill="none" class="gpeb-outline-star" ', | |
$star_svg | |
); | |
$filled_stars = str_repeat( $filled_star, $filled_count ); | |
$empty_stars = $config['show_empty_stars'] | |
? str_repeat( $outline_star, $empty_count ) | |
: ''; | |
// Wrap with accessible label. | |
$entry[ $field->id ] = sprintf( | |
'<span class="gpeb-rating" role="img" aria-label="%1$d out of %2$d">%3$s%4$s</span>', | |
$filled_count, | |
$total_stars, | |
$filled_stars, | |
$empty_stars | |
); | |
break; |
🤖 Prompt for AI Agents
In gp-entry-blocks/gpeb-display-stars-for-rating-fields.php around lines 23 to
27, the code incorrectly assumes a fixed total of 5 stars and uses the choice
index for filled stars, which fails for variable star counts or non-sequential
values. Fix this by calculating the total stars using count($field->choices),
determine the filled stars by clamping the numeric selected value between 0 and
total stars, and generate the filled and empty star SVGs with aria-hidden="true"
and focusable="false" attributes. Finally, wrap the combined stars output in a
span with role="img" and an aria-label describing the rating (e.g., "X out of
Y") for accessibility.
function decode_rating_field_svgs($content, $entry_form, $entry) { | ||
foreach ($entry_form['fields'] as $field) { | ||
if ($field->get_input_type() === 'rating' && isset($entry[$field->id]) && strpos($entry[$field->id], '<svg') !== false) { | ||
$content = str_replace(htmlspecialchars($entry[$field->id], ENT_QUOTES), $entry[$field->id], $content); | ||
} | ||
} | ||
return $content; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use esc_html() for consistent encoding and prefix the function to avoid collisions
Align with WP helpers and reduce naming collision risk with a prefixed function name. Also guard re-declaration.
-function decode_rating_field_svgs($content, $entry_form, $entry) {
- foreach ($entry_form['fields'] as $field) {
- if ($field->get_input_type() === 'rating' && isset($entry[$field->id]) && strpos($entry[$field->id], '<svg') !== false) {
- $content = str_replace(htmlspecialchars($entry[$field->id], ENT_QUOTES), $entry[$field->id], $content);
- }
- }
- return $content;
-}
+if ( ! function_exists( 'gpeb_decode_rating_field_svgs' ) ) {
+ function gpeb_decode_rating_field_svgs( $content, $entry_form, $entry ) {
+ foreach ( $entry_form['fields'] as $field ) {
+ if ( $field->get_input_type() === 'rating' && isset( $entry[ $field->id ] ) && strpos( $entry[ $field->id ], '<svg' ) !== false ) {
+ $encoded_svg = esc_html( $entry[ $field->id ] );
+ if ( $encoded_svg !== $entry[ $field->id ] && strpos( $content, $encoded_svg ) !== false ) {
+ $content = str_replace( $encoded_svg, $entry[ $field->id ], $content );
+ }
+ }
+ }
+ return $content;
+ }
+}
🤖 Prompt for AI Agents
In gp-entry-blocks/gpeb-display-stars-for-rating-fields.php around lines 36 to
43, rename the function to include a unique prefix to avoid naming collisions
and wrap the function declaration in a conditional to prevent re-declaration.
Replace htmlspecialchars with esc_html() for consistent WordPress encoding
standards. Update all references to this function accordingly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just recommend some sanitization as suggested by coderabbit. Then, S&M!
Context
⛑️ Ticket(s): https://secure.helpscout.net/conversation/3021474440/87220?viewId=8172236
Summary
This PR addresses a feature request that would allow the user to display empty stars after the filled stars, as well as being able to change the color.
Changes:
Quick demo of the changes: https://www.loom.com/share/591fd8930a5f476aa3c381ec8606b610