Skip to content

Smart Links: Add ITM parameters to planted Smart Links#3211

Merged
vaurdan merged 10 commits intoadd/traffic-boostfrom
add/smart-links-itm-params
Mar 20, 2025
Merged

Smart Links: Add ITM parameters to planted Smart Links#3211
vaurdan merged 10 commits intoadd/traffic-boostfrom
add/smart-links-itm-params

Conversation

@vaurdan
Copy link
Contributor

@vaurdan vaurdan commented Mar 19, 2025

Description

This PR adds ITM parameters to any planted smart link, either through Smart Linking or Traffic Boost. This adds a ITM parameter with the parsely-pch campaign, smart-link source, and with the Smart Link UID as the term.

ITM parameter was used instead of UTM parameters, as per the Parse.ly documentation, ITM are more suited for internal traffic than UTM parameters.

Motivation and context

Track Smart Links clicks in order to calculate and assert their effectiveness.

How has this been tested?

Tested locally, and validated that existing tests, after some minor changes, are passing.

Summary by CodeRabbit

  • New Features

    • Enhanced smart linking now integrates campaign tracking by appending ITM parameters for more accurate attribution.
    • Link handling has been refined to clearly separate the original URL from its tracking-enhanced version, resulting in more consistent link resolution.
    • API responses now include richer metadata, such as post titles and types, for improved content linking clarity.
  • Bug Fixes

    • Updated filtering of self-referencing links ensures unwanted duplicates are effectively excluded.

@vaurdan vaurdan added Component: PHP Feature: PCI Ticket/PR related to Content Intelligence Feature: Engagement Boost Ticket/PR related to Engagement Boost labels Mar 19, 2025
@vaurdan vaurdan added this to the 3.18.0 milestone Mar 19, 2025
@vaurdan vaurdan self-assigned this Mar 19, 2025
@vaurdan vaurdan requested a review from a team as a code owner March 19, 2025 11:43
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

📝 Walkthrough

Walkthrough

This pull request refactors smart link handling across PHP and TypeScript files. In the models, it replaces legacy URL-to-post ID logic with a direct call to a utility method and simplifies the handling of link attributes. The smart link class now uses a structured href property with both raw and ITM values. Additionally, new utility methods for appending ITM parameters are introduced along with corresponding updates to front‑end components, REST API endpoints, and integration tests to validate the new structure.

Changes

File(s) Change Summary
src/Models/class-inbound-smart-link.php, src/Models/class-smart-link.php Refactored source post ID retrieval by replacing legacy URL functions with Utils::get_post_id_by_url. Introduced new method get_link_href, updated update_uid, and modified to_array structure to use a { raw, itm } href format.
src/Utils/class-utils.php Added PHPStan type ItmParams and method append_itm_params; refactored get_post_id_by_url to include fallback slug lookup and caching.
src/content-helper/common/utils/functions.ts Added functions addITMParamsToURL and removeITMParamsFromURL for managing ITM parameters in URLs.
src/content-helper/editor-sidebar/smart-linking/... (component.tsx, provider.ts, review-modal/component-modal.tsx, utils.ts) Updated smart link processing in the editor sidebar: modified href to an object containing raw and itm, adjusted filtering and telemetry tracking, and integrated ITM parameter functions.
src/rest-api/content-helper/class-endpoint-smart-linking.php, src/rest-api/stats/class-endpoint-posts.php Enhanced API responses by including post type object and title; updated href validation to check for an array structure; added URL validation callback in posts endpoint.
tests/Integration/RestAPI/ContentHelper/EndpointSmartLinkingTest.php Updated test assertions to verify the new href structure with raw and itm keys and to ensure the proper inclusion of ITM parameters.

Sequence Diagram(s)

sequenceDiagram
    participant Panel as EditorSidebar
    participant Provider as SmartLinkingProvider
    participant SmartLink as Smart_Link Object
    participant Utils as Utils

    Panel->>Provider: Request smart links processing
    Provider->>SmartLink: Retrieve smart link data
    SmartLink->>Utils: Invoke get_link_href(skip_utm_params)
    Utils-->>SmartLink: Return URL with appended ITM parameters
    SmartLink-->>Provider: Return href object { raw, itm }
    Provider-->>Panel: Provide processed smart links
Loading

Possibly related PRs

Suggested labels

Changelog: Added

Suggested reviewers

  • acicovic
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

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
Contributor

@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: 0

🔭 Outside diff range comments (2)
src/content-helper/editor-sidebar/smart-linking/component.tsx (2)

377-383: 🛠️ Refactor suggestion

Update console warning to match the new href structure.

The condition now correctly uses link.href.raw to check for self-referencing links, which aligns with the new SmartLink structure. However, the console warning message on line 379 still uses ${ link.href } directly, which might now output [object Object] instead of the actual URL.

if ( link.href.raw.includes( strippedPermalink ) ) {
    // eslint-disable-next-line no-console
-   console.warn( `PCH Smart Linking: Skipping self-reference link: ${ link.href }` );
+   console.warn( `PCH Smart Linking: Skipping self-reference link: ${ link.href.raw }` );
    return false;
}

386-405: ⚠️ Potential issue

Update href equality check to use the new structure.

The code needs to be updated to use the new href structure when checking for duplicate links on line 388. Currently, it's attempting to directly compare sl.href === link.href, but since href is now an object, this will always result in a false comparison.

links = links.filter( ( link ) => {
    return ! smartLinks.some( ( sl ) => {
-       if ( sl.href === link.href ) {
+       if ( sl.href.raw === link.href.raw ) {
            // eslint-disable-next-line no-console
-           console.warn( `PCH Smart Linking: Skipping duplicate link: ${ link.href }` );
+           console.warn( `PCH Smart Linking: Skipping duplicate link: ${ link.href.raw }` );
            return true;
        }
        if ( sl.text === link.text ) {
            // If the offset is the same, we want to keep the link, so it can replace the old smart link.
            if ( sl.offset === link.offset ) {
                // TODO: Flag smart link as updated.
                return false;
            }
            // eslint-disable-next-line no-console
            console.warn( `PCH Smart Linking: Skipping duplicate link text: ${ link.text }` );
            return true;
        }
        return false;
    } );
} );
🧹 Nitpick comments (1)
src/rest-api/stats/class-endpoint-posts.php (1)

218-234: Well-implemented URL validation function.

The new validate_urls method properly validates that each element in the array is a valid URL using PHP's filter_var function with the FILTER_VALIDATE_URL filter. It returns appropriate error messages when validation fails, following WordPress coding standards.

Consider adding a check for empty strings as well, as filter_var might validate them as valid URLs in some circumstances.

public function validate_urls( array $urls ) {
    foreach ( $urls as $url ) {
-       if ( false === filter_var( $url, FILTER_VALIDATE_URL ) ) {
+       if ( empty( $url ) || false === filter_var( $url, FILTER_VALIDATE_URL ) ) {
            return new WP_Error( 'invalid_param', __( 'The parameter must be a list of URLs.', 'wp-parsely' ) );
        }
    }

    return true;
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 715d9db and 1409372.

⛔ Files ignored due to path filters (6)
  • build/blocks/recommendations/edit.asset.php is excluded by !build/**
  • build/blocks/recommendations/edit.js is excluded by !build/**
  • build/blocks/recommendations/view.asset.php is excluded by !build/**
  • build/blocks/recommendations/view.js is excluded by !build/**
  • build/content-helper/editor-sidebar.asset.php is excluded by !build/**
  • build/content-helper/editor-sidebar.js is excluded by !build/**
📒 Files selected for processing (14)
  • src/Models/class-inbound-smart-link.php (5 hunks)
  • src/Models/class-smart-link.php (3 hunks)
  • src/Utils/class-utils.php (2 hunks)
  • src/blocks/recommendations/components/parsely-recommendations-list.tsx (1 hunks)
  • src/content-helper/common/utils/functions.ts (1 hunks)
  • src/content-helper/editor-sidebar/smart-linking/component.tsx (1 hunks)
  • src/content-helper/editor-sidebar/smart-linking/provider.ts (5 hunks)
  • src/content-helper/editor-sidebar/smart-linking/review-modal/component-modal.tsx (6 hunks)
  • src/content-helper/editor-sidebar/smart-linking/review-modal/component-suggestion.tsx (4 hunks)
  • src/content-helper/editor-sidebar/smart-linking/store.ts (1 hunks)
  • src/content-helper/editor-sidebar/smart-linking/utils.ts (5 hunks)
  • src/rest-api/content-helper/class-endpoint-smart-linking.php (2 hunks)
  • src/rest-api/stats/class-endpoint-posts.php (2 hunks)
  • tests/Integration/RestAPI/ContentHelper/EndpointSmartLinkingTest.php (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/content-helper/editor-sidebar/smart-linking/store.ts
  • src/content-helper/editor-sidebar/smart-linking/component.tsx
  • src/blocks/recommendations/components/parsely-recommendations-list.tsx
  • src/content-helper/common/utils/functions.ts
  • src/content-helper/editor-sidebar/smart-linking/review-modal/component-suggestion.tsx
  • src/content-helper/editor-sidebar/smart-linking/review-modal/component-modal.tsx
  • src/content-helper/editor-sidebar/smart-linking/utils.ts
  • src/content-helper/editor-sidebar/smart-linking/provider.ts
`**/*.{html,php}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the HTML and PHP code to ensure it is well-structured and adheres ...

**/*.{html,php}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the HTML and PHP code to ensure it is well-structured and adheres to best practices.
  • Ensure the code follows WordPress coding standards and is well-documented.
  • Confirm the code is secure and free from vulnerabilities.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Verify code compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/rest-api/stats/class-endpoint-posts.php
  • tests/Integration/RestAPI/ContentHelper/EndpointSmartLinkingTest.php
  • src/rest-api/content-helper/class-endpoint-smart-linking.php
  • src/Utils/class-utils.php
  • src/Models/class-inbound-smart-link.php
  • src/Models/class-smart-link.php
🧬 Code Definitions (5)
src/Models/class-inbound-smart-link.php (2)
src/Utils/class-utils.php (2) (2)
  • Utils (34-498)
  • get_post_id_by_url (428-468)
src/Models/class-smart-link.php (2) (2)
  • set_source_post_id (561-586)
  • get_link_href (445-458)
src/content-helper/editor-sidebar/smart-linking/review-modal/component-suggestion.tsx (1)
src/content-helper/editor-sidebar/smart-linking/provider.ts (1) (1)
  • SmartLink (25-45)
src/content-helper/editor-sidebar/smart-linking/review-modal/component-modal.tsx (1)
src/content-helper/editor-sidebar/smart-linking/provider.ts (1) (1)
  • SmartLink (25-45)
src/content-helper/editor-sidebar/smart-linking/utils.ts (1)
src/content-helper/common/utils/functions.ts (2) (2)
  • removeITMParamsFromURL (103-111)
  • addITMParamsToURL (69-92)
src/Models/class-smart-link.php (1)
src/Utils/class-utils.php (2) (2)
  • Utils (34-498)
  • append_itm_params (479-497)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: E2E against WordPress latest
🔇 Additional comments (49)
src/content-helper/editor-sidebar/smart-linking/store.ts (1)

11-11: Import reorganization looks good.

The import statement for DEFAULT_MAX_LINKS has been correctly reorganized in this file.

src/blocks/recommendations/components/parsely-recommendations-list.tsx (1)

21-25: Enhanced key uniqueness for React list items.

The addition of the index parameter to the map function and including it in the key prop enhances the uniqueness of each list item key. This follows React best practices for efficiently rendering lists and prevents potential key duplication issues.

src/rest-api/stats/class-endpoint-posts.php (1)

181-181: Good addition of URL validation.

Adding the validate_callback for the URLs parameter enhances input validation and security.

src/rest-api/content-helper/class-endpoint-smart-linking.php (5)

517-519: Good improvement in retrieving post type information.

This change enhances the code by retrieving the singular name of the post type using get_post_type_object instead of just returning the post type slug. This provides a more user-friendly representation in the response.


524-524: Good addition of post title to response data.

Adding the post title to the response provides valuable context for the post, making the API more useful for consumers.


526-526: Good use of post type singular name.

Using the post type's singular name rather than the raw post type makes the response more user-friendly and consistent with WordPress conventions.


571-577: Proper validation for the new href structure.

The validation has been correctly updated to check for the new href format where it's an array with a 'raw' property. This aligns with the PR objective of supporting ITM parameters for Smart Links.


583-583: Updated href assignment to use the new structure.

The code correctly uses params['href']['raw'] when updating an existing smart link, maintaining consistency with the new href structure.

tests/Integration/RestAPI/ContentHelper/EndpointSmartLinkingTest.php (4)

268-270: Test data updated to match new href structure.

The test data has been properly updated to reflect the new href structure that includes a 'raw' property, ensuring the tests align with the implementation.


310-316: Good test assertions for ITM parameters.

The added assertions properly verify that the response includes both 'raw' and 'itm' properties in the href, and checks that the ITM parameters contain the expected values. This validates the core functionality introduced in this PR.


378-389: Test data updated consistently across multiple test cases.

The test data for multiple smart links has been consistently updated to use the new href structure, ensuring all test cases validate the same behavior.


442-448: Comprehensive validation of ITM parameter structure.

The assertions validate both the structure of the href object and the specific ITM parameters added to each smart link. This ensures the implementation is working as expected across multiple links.

src/content-helper/common/utils/functions.ts (2)

54-92: Well-implemented function for adding ITM parameters.

The addITMParamsToURL function is well-structured and properly documented with JSDoc comments. It correctly handles the addition of ITM parameters to a URL, with appropriate conditional checks for optional parameters.

The implementation uses the URL object for proper URL manipulation, which is more robust than string concatenation.


94-111: Good implementation of ITM parameter removal.

The removeITMParamsFromURL function provides a clean way to remove ITM parameters from URLs. This is useful for maintaining the original URL separately from the tracking parameters, enhancing the flexibility of the Smart Links system.

The function is well-documented with proper JSDoc comments including the @since tag.

src/Utils/class-utils.php (3)

26-32: Good type definition for ITM parameters.

The PHPStan type definition for ItmParams is well-structured and clearly defines the required and optional parameters, which helps with type safety and documentation.


442-467: Enhanced post ID retrieval from URL.

The enhanced get_post_id_by_url method now attempts to derive the post ID from the URL slug when standard methods fail, making it more robust. This improvement will help in cases where the standard url_to_postid function doesn't work due to custom permalink structures or other edge cases.


470-497: Well-implemented function for appending ITM parameters.

The append_itm_params method provides a clean way to append ITM parameters to URLs in PHP, complementing the TypeScript implementation. The function correctly maps the input parameters to the ITM query parameters and uses WordPress's add_query_arg function for proper URL manipulation.

The method is well-documented with proper PHPDoc comments including parameter types and return value.

src/Models/class-inbound-smart-link.php (5)

15-15: Added Utils namespace import for better code organization.

This import is used to access the get_post_id_by_url method, which centralizes URL-to-post resolution logic.


488-492: Improved code reusability with Utils::get_post_id_by_url.

This change simplifies the URL-to-post ID resolution by leveraging the centralized utility method, improving maintainability and ensuring consistent behavior across the codebase.


574-575: Enhanced link validation with ITM parameter support.

The link validation now correctly checks if the link's href contains the Smart Link's href with ITM parameters by using the get_link_href() method, ensuring consistent link matching.


728-729: Standardized href handling using get_link_href method.

Replaced direct href assignment with the get_link_href() method, ensuring consistent ITM parameter application across the codebase.


744-745: Consistent href formatting with get_link_href method.

Using get_link_href() method for the smart link anchor element ensures ITM parameters are consistently applied when creating new links.

src/Models/class-smart-link.php (5)

428-435: Reintroduced update_uid method for managing smart link identifiers.

The update_uid method provides a clean way to regenerate the UID for a smart link, ensuring proper identification when link properties change.


437-458: Added get_link_href method for standardized ITM parameter handling.

This new method provides a centralized way to generate smart link URLs with or without ITM parameters:

  • It returns the raw href when ITM parameters should be skipped
  • Otherwise, it appends standard ITM parameters (campaign, source, and term) using Utils::append_itm_params
  • Properly documented with since tag

This implementation ensures consistent tracking parameter application across all smart links.


684-691: Enhanced href structure in to_array method for improved tracking.

The href is now returned as a structured object with:

  • 'raw' property for the original URL
  • 'itm' property containing the URL with ITM parameters

This change provides both the clean URL and the tracking-enabled URL to clients, offering more flexibility in how the links are used.


728-729: Updated deserialize method to support the new href structure.

The method now correctly handles the structured href object by accessing the 'raw' property, maintaining backward compatibility with the updated data structure.


736-737: Updated href setting in deserialize method for consistency.

Ensures that when deserializing a smart link, the 'raw' property of the href object is used consistently when updating an existing smart link.

src/content-helper/editor-sidebar/smart-linking/provider.ts (5)

23-23: Updated JSDoc to document new SmartLink properties.

The comment now correctly indicates the addition of wp_post_meta and post_stats properties in version 3.18.0.


25-45: Enhanced SmartLink type with structured href and additional metadata.

The SmartLink type has been improved with:

  1. A structured href object containing both raw and ITM-enhanced URLs
  2. Optional WordPress post metadata for better content display
  3. Optional post statistics for performance insights

These changes provide richer data for UI components and enable smarter link presentation.


167-246: Added fetchSmartLinksExtraData method for enhanced link enrichment.

This method improves code organization by:

  1. Extracting the data enrichment logic into a dedicated function
  2. Fetching both post metadata and performance statistics for each link
  3. Correctly handling the new href structure when making API requests
  4. Providing proper error handling and fallbacks

The implementation properly structures the extra data into the standardized format expected by consumers.


248-277: Refactored generateSmartLinks to leverage the new data enrichment method.

The method now:

  1. Fetches basic smart link data from the API
  2. Passes the results to fetchSmartLinksExtraData for enrichment
  3. Returns the fully enriched data

This separation of concerns improves maintainability and keeps the code DRY.


374-387: Enhanced getSmartLinks method to return enriched outbound links.

The method now processes outbound links through fetchSmartLinksExtraData to provide consistent data enrichment across all API methods, ensuring a uniform data structure for consumers.

src/content-helper/editor-sidebar/smart-linking/utils.ts (6)

12-12: Updated imports to include ITM parameter utility functions.

Added imports for addITMParamsToURL and removeITMParamsFromURL from the common utils, enabling consistent ITM parameter handling across the codebase.


436-439: Implemented structured href object with raw and ITM-enhanced URLs.

The href is now stored as an object with two properties:

  • 'raw': The URL with ITM parameters removed
  • 'itm': The URL with Smart Link ITM parameters added

This provides flexibility for clients to use either version based on their requirements.


598-601: Updated link matching to handle the new href structure.

Modified the link detection logic to check if the link's href includes the raw URL rather than requiring an exact match, making the validation more robust when handling URLs with different query parameters.


613-613: Updated href attribute to use ITM-enhanced URL.

When restoring a missing smart link, the code now correctly sets the href attribute to the ITM-enhanced URL, ensuring proper tracking parameters are included.


749-751: Updated getAllSmartLinksURLs to use raw URLs.

Modified the function to return the raw URLs without ITM parameters, providing clean URLs for API requests and comparisons.


753-769: Added addSmartLinkITMParamsToURL for consistent parameter application.

This new utility function encapsulates the logic for adding standard ITM parameters to a Smart Link URL:

  • Sets campaign to "parsely-pch"
  • Sets source to "smart-link"
  • Uses the smart link UID as the term parameter

Having this in a dedicated function ensures consistent parameter application across the codebase.

src/content-helper/editor-sidebar/smart-linking/review-modal/component-modal.tsx (6)

16-16: Good refactoring of the import statement

The import now only includes SmartLink from the provider, which aligns with the consolidated type structure. This is a cleaner approach.


86-86: Type simplification for selectedLink is appropriate

The state initialization now uses just SmartLink type instead of a union type, matching the consolidated link type structure in the provider.


112-112: Smart Link href structure updated correctly

The code now correctly uses linkSuggestion.href.itm for the anchor href, which includes the ITM parameters as specified in the PR objectives. This allows for better tracking of smart link clicks.


296-297: Telemetry tracking properly updated to use raw URL

Good adjustment of the telemetry tracking to use selectedLink.href.raw instead of the decorated URL with ITM parameters. This ensures analytics collect the actual destination URL.


344-345: Telemetry tracking properly updated to use raw URL

Good adjustment of the telemetry tracking to use selectedLink.href.raw instead of the decorated URL with ITM parameters. This ensures analytics collect the actual destination URL.


372-373: Telemetry tracking properly updated to use raw URL

Good adjustment of the telemetry tracking to use selectedLink.href.raw instead of the decorated URL with ITM parameters. This ensures analytics collect the actual destination URL.

src/content-helper/editor-sidebar/smart-linking/review-modal/component-suggestion.tsx (5)

37-37: Import statement updated appropriately

Added InboundSmartLink to the imports which is needed for type checking later in the file while maintaining the SmartLink import for the updated component props.


109-112: JSDoc updated correctly with version information

The JSDoc comment has been appropriately updated to indicate the addition of the post type to the link details with the correct @since tag, following WordPress coding standards.


113-122: Improved error handling with optional chaining

Good use of optional chaining (?.) to safely access potentially undefined properties on the link object. This prevents runtime errors and improves code robustness.

The function now correctly accepts the consolidated SmartLink type rather than the more specific OutboundSmartLink type.


160-178: Enhanced conditional rendering for post stats

The component now properly checks if link.post_stats exists before attempting to render the stats section. Each individual stat is also conditionally rendered, improving the robustness of the component.


190-190: Props type updated for consistency

The ReviewSuggestionProps type now correctly uses the consolidated SmartLink type instead of the specific OutboundSmartLink type, maintaining consistency with the rest of the codebase.

Copy link
Collaborator

@acicovic acicovic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this.

I've left some nitpicking comments, but the PR is good to merge.

@acicovic acicovic changed the title Smart Links: Add ITM parameters to any planted Smart Link. Smart Links: Add ITM parameters to planted Smart Links Mar 20, 2025
vaurdan and others added 4 commits March 20, 2025 11:38
Co-authored-by: Alex Cicovic <23142906+acicovic@users.noreply.github.com>
# Conflicts:
#	build/content-helper/editor-sidebar.asset.php
#	build/content-helper/editor-sidebar.js
Copy link
Contributor

@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: 0

🧹 Nitpick comments (2)
src/content-helper/common/utils/functions.ts (2)

54-93: Well-structured function with good parameter handling.

The addITMParamsToURL function is well-implemented with proper JSDoc documentation, including the required @SInCE tag. The function correctly handles both required and optional parameters with appropriate type definitions. The code structure follows WordPress coding standards with proper spacing and indentation.

Consider adding basic URL validation and error handling to make the function more robust against invalid inputs, which could throw exceptions when creating the URL object.

export function addITMParamsToURL( url: string, itmParams: {
	campaign: string;
	source?: string;
	medium?: string;
	content?: string;
	term?: string;
} ): string {
+	try {
		const urlObj = new URL( url );
		urlObj.searchParams.set( 'itm_campaign', itmParams.campaign );

		if ( itmParams.source ) {
			urlObj.searchParams.set( 'itm_source', itmParams.source );
		}
		if ( itmParams.medium ) {
			urlObj.searchParams.set( 'itm_medium', itmParams.medium );
		}
		if ( itmParams.content ) {
			urlObj.searchParams.set( 'itm_content', itmParams.content );
		}
		if ( itmParams.term ) {
			urlObj.searchParams.set( 'itm_term', itmParams.term );
		}

		return urlObj.toString();
+	} catch ( error ) {
+		console.error( 'Invalid URL provided to addITMParamsToURL:', url );
+		return url; // Return the original URL if it's invalid
+	}
}

95-113: Well-structured function for removing ITM parameters.

The removeITMParamsFromURL function has proper JSDoc documentation with the required @SInCE tag and follows WordPress coding standards. Similar to the addITMParamsToURL function, consider adding error handling for invalid URLs.

export function removeITMParamsFromURL( url: string ): string {
+	try {
		const urlObj = new URL( url );
		urlObj.searchParams.delete( 'itm_campaign' );
		urlObj.searchParams.delete( 'itm_source' );
		urlObj.searchParams.delete( 'itm_medium' );
		urlObj.searchParams.delete( 'itm_content' );
		urlObj.searchParams.delete( 'itm_term' );

		return urlObj.toString();
+	} catch ( error ) {
+		console.error( 'Invalid URL provided to removeITMParamsFromURL:', url );
+		return url; // Return the original URL if it's invalid
+	}
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1409372 and 96cf355.

📒 Files selected for processing (4)
  • src/content-helper/common/utils/functions.ts (1 hunks)
  • src/content-helper/editor-sidebar/smart-linking/provider.ts (4 hunks)
  • src/rest-api/stats/class-endpoint-posts.php (2 hunks)
  • tests/Integration/RestAPI/ContentHelper/EndpointSmartLinkingTest.php (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/rest-api/stats/class-endpoint-posts.php
  • tests/Integration/RestAPI/ContentHelper/EndpointSmartLinkingTest.php
  • src/content-helper/editor-sidebar/smart-linking/provider.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/content-helper/common/utils/functions.ts
🔇 Additional comments (2)
src/content-helper/common/utils/functions.ts (2)

92-92: Properly implemented empty line before return statement.

The empty line before the return statement improves readability, as suggested in a previous review.


112-112: Properly implemented empty line before return statement.

The empty line before the return statement improves readability, as suggested in a previous review.

@vaurdan vaurdan merged commit 199141e into add/traffic-boost Mar 20, 2025
39 checks passed
@vaurdan vaurdan deleted the add/smart-links-itm-params branch March 20, 2025 12:21
github-actions bot added a commit that referenced this pull request Mar 21, 2025
…ms Smart Links: Add ITM parameters to planted Smart Links" (199141e)
@acicovic acicovic removed this from the 3.18.0 milestone Apr 9, 2025
@acicovic acicovic added this to the 3.19.0 milestone Apr 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Feature: Engagement Boost Ticket/PR related to Engagement Boost Feature: PCI Ticket/PR related to Content Intelligence

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants