Skip to content

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

SebastianWiz
Copy link
Contributor

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:

  • Replaced the emoji star with a single SVG star. The SVG is from Feather, an open-source icon library.
  • Added Customization options that allows the user to:
    • Enable the display of empty stars
    • Customize the stars appearance (size, color and stroke width)

Quick demo of the changes: https://www.loom.com/share/591fd8930a5f476aa3c381ec8606b610

…ar with empty star display option for rating fields.
Copy link

coderabbitai bot commented Aug 8, 2025

Walkthrough

The 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

Cohort / File(s) Change Summary
SVG Star Rendering & Decoding for Rating Fields
gp-entry-blocks/gpeb-display-stars-for-rating-fields.php
Replaces character-based stars with configurable SVG-based stars for rating fields, adds a decoding function for SVGs, and hooks both features into entry content filters.

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
Loading

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch seb/add/87220-empty-stars-rating-display

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented Aug 8, 2025

Warnings
⚠️ When ready, don't forget to request reviews on this pull request from your fellow wizards.

Generated by 🚫 dangerJS against 876439f

Copy link

@coderabbitai coderabbitai bot left a 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 theming

If 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 it

If 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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6e5edf and 876439f.

📒 Files selected for processing (1)
  • gp-entry-blocks/gpeb-display-stars-for-rating-fields.php (1 hunks)

Comment on lines +9 to +16
$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>';
Copy link

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.

Comment on lines +23 to +27
$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;
Copy link

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.

Suggested change
$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.

Comment on lines +36 to +43
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;
}
Copy link

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.

Copy link
Contributor

@saifsultanc saifsultanc left a 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants