VOOZH about

URL: https://deepwiki.com/pcescato/ajc-bridge/3.2-hugo-adapter

⇱ Hugo Adapter | pcescato/ajc-bridge | DeepWiki


Loading...
Menu

Hugo Adapter

The Hugo Adapter converts WordPress posts and pages to Hugo-compatible Markdown format with YAML front matter. It implements the Adapter_Interface contract to provide Hugo-specific file path conventions, front matter generation, and content transformation.

For information about the adapter interface contract, see Adapter Interface. For Hugo-to-GitHub integration, see Sync Runner. For image optimization that works with this adapter, see Media Processor. For a comparison with Astro conventions, see Astro Adapter.


Architecture Overview

The Hugo_Adapter class serves as a strategy implementation within the plugin's adapter pattern. It is instantiated by Sync_Runner when the publishing strategy requires GitHub synchronization with Hugo as the target SSG.


Sources: adapters/class-hugo-adapter.php1-22 adapters/class-hugo-adapter.php33-38


Public Interface Methods

The Hugo_Adapter class implements four required methods from Adapter_Interface:

MethodReturn TypePurpose
convert()stringConverts WP_Post to complete Markdown with front matter
get_file_path()stringReturns Hugo-compatible repository path for post/page
get_images_dir()stringReturns Hugo images directory path for a post
get_featured_image_name()stringReturns fixed filename for featured images

Additionally, a public method get_front_matter() returns structured front matter data as an array.

Sources: adapters/class-hugo-adapter.php22-38 adapters/class-hugo-adapter.php116-129 adapters/class-hugo-adapter.php560-565 adapters/class-hugo-adapter.php577-579


File Path Conventions

Hugo uses distinct conventions for posts versus pages, and post-specific directories for images.

Content Files


The get_file_path() method implements this logic:

  • Posts: content/posts/{date}-{slug}.md format, where date is YYYY-MM-DD
  • Pages: content/{slug}.md format in the root content directory

Sources: adapters/class-hugo-adapter.php116-129

Image Files

Hugo uses post-specific image directories with fixed naming for featured images:

Image TypePath PatternExample
Featured WebPstatic/images/{post_id}/featured.webpstatic/images/42/featured.webp
Featured AVIFstatic/images/{post_id}/featured.avifstatic/images/42/featured.avif
Content WebPstatic/images/{post_id}/{basename}.webpstatic/images/42/diagram.webp
Content AVIFstatic/images/{post_id}/{basename}.avifstatic/images/42/diagram.avif

The adapter provides two methods for path generation:

  • get_images_dir(?int $post_id): Returns static/images (if no ID) or static/images/{post_id}
  • get_featured_image_name(string $basename, string $ext): Returns fixed featured.{ext} (ignores basename)

Sources: adapters/class-hugo-adapter.php560-565 adapters/class-hugo-adapter.php577-579


Conversion Pipeline

The main convert() method orchestrates content transformation through two parallel tracks that merge into the final Markdown output.


Sources: adapters/class-hugo-adapter.php33-38 adapters/class-hugo-adapter.php198-249 adapters/class-hugo-adapter.php50-103


Front Matter Generation

Hugo front matter uses YAML format with a customizable template system.

Template System

Front matter is generated from a user-configurable template stored in ajc_bridge_settings['hugo_front_matter_template']. The template system uses placeholder replacement:


Default Template:


Sources: adapters/class-hugo-adapter.php50-103

Placeholder Reference

The following placeholders are available for front matter templates:

PlaceholderData SourceExample Output
{{id}}$post->ID42
{{title}}$post->post_titleHello World
{{date}}get_the_date('c', $post)2024-01-15T14:30:00+00:00
{{author}}get_userdata($post->post_author)->display_nameJohn Doe
{{slug}}$post->post_namehello-world
{{image_avif}}Processed featured image path/images/42/featured.avif
{{image_webp}}Processed featured image path/images/42/featured.webp
{{image_original}}Original featured image URLhttps://example.com/...

Sources: adapters/class-hugo-adapter.php84-93

Structured Front Matter Method

The get_front_matter() method returns front matter as a structured array (not used for template-based output, but available for programmatic access):


Sources: adapters/class-hugo-adapter.php139-185


HTML to Markdown Conversion

The adapter uses a multi-stage conversion process with fallback mechanisms.

Conversion Strategy


Sources: adapters/class-hugo-adapter.php218-239

League HTMLToMarkdown Configuration

When available, the adapter configures the League converter with specific options:


Sources: adapters/class-hugo-adapter.php221-229

Basic Conversion Fallback

If League\HTMLToMarkdown is unavailable, the adapter uses regex-based conversion:

HTML ElementMarkdown OutputRegex Pattern
<h1> to <h6># to ######/<h([1-6])[^>]*>(.*?)<\/h\1>/is
<strong>, <b>**text**/<(strong|b)[^>]*>(.*?)<\/\1>/is
<em>, <i>*text*/<(em|i)[^>]*>(.*?)<\/\1>/is
<a href="..."><FileRef file-url="https://github.com/pcescato/ajc-bridge/blob/2980e3ea/text" undefined file-path="text">Hii</FileRef>Callback function
<img src="...">!<FileRef file-url="https://github.com/pcescato/ajc-bridge/blob/2980e3ea/alt" undefined file-path="alt">Hii</FileRef>Callback function
<li>- item/<li[^>]*>(.*?)<\/li>/is
<blockquote>> text/<blockquote[^>]*>(.*?)<\/blockquote>/is
<code>`code`/<code[^>]*>(.*?)<\/code>/is
<pre><code>```code```/<pre[^>]*><code[^>]*>(.*?)<\/code><\/pre>/is

Sources: adapters/class-hugo-adapter.php380-442


WordPress Artifact Removal

Hugo does not need WordPress-specific HTML attributes and wrapper elements. The adapter performs extensive cleanup before Markdown conversion.

Cleaning Pipeline


Elements and Attributes Removed:

CategoryRemoved ItemsReason
Gutenberg wrappers<figure>, <figcaption>, <div class="wp-block-*">Hugo doesn't use block wrappers
Alignment<div class="alignleft|alignright|aligncenter|alignnone">Markdown handles alignment differently
Image metadataclass="wp-image-{id}", srcset, sizes, width, heightProcessed images don't need WordPress attributes
Size classesclass="size-thumbnail|medium|large|full"Not relevant for static site images
Empty attributesclass=""Clean up after class removal

Sources: adapters/class-hugo-adapter.php260-292

Gutenberg Block Handling

The adapter removes Gutenberg block comment markers but preserves content:

<!-- wp:paragraph -->
<p>Content here</p>
<!-- /wp:paragraph -->

Becomes:

<p>Content here</p>

This is handled by convert_gutenberg_blocks() which strips all block comments.

Sources: adapters/class-hugo-adapter.php365-371


Image URL Replacement

When the Media Processor provides an image mapping array, the adapter replaces WordPress media URLs with Hugo-compatible static paths.

Replacement Process


Replacement Patterns:


Sources: adapters/class-hugo-adapter.php326-356


Markdown Post-Processing

After HTML-to-Markdown conversion, the adapter applies final cleanup to ensure clean output.

Post-Processing Steps

The clean_markdown_output() method performs these operations:


Specific Transformations:

InputOutputPurpose
[&hellip;][...]Normalize ellipsis entities
&nbsp; (space)Remove non-breaking space entities
text!<FileRef file-url="https://github.com/pcescato/ajc-bridge/blob/2980e3ea/img" undefined file-path="img">Hii</FileRef>text\n\n!<FileRef file-url="https://github.com/pcescato/ajc-bridge/blob/2980e3ea/img" undefined file-path="img">Hii</FileRef>Ensure images start on new line
!<FileRef file-url="https://github.com/pcescato/ajc-bridge/blob/2980e3ea/img" undefined file-path="img">Hii</FileRef>text!<FileRef file-url="https://github.com/pcescato/ajc-bridge/blob/2980e3ea/img" undefined file-path="img">Hii</FileRef>\n\n textEnsure images end with new line
\n\n\n+\n\nCollapse excessive whitespace

Sources: adapters/class-hugo-adapter.php303-316 adapters/class-hugo-adapter.php244-246


YAML Formatting Utilities

The adapter includes helper methods for generating valid YAML front matter (used by the non-template get_front_matter() method, not the template-based approach).

YAML Field Formatting


Special Characters Requiring Quotes:

The adapter quotes strings containing: : [ ] { } , & * # ? | - < > = ! % @ "` or newlines.

Sources: adapters/class-hugo-adapter.php509-530 adapters/class-hugo-adapter.php539-548


Integration with Media Processor

The Media_Processor class calls Hugo Adapter methods to determine file paths for image optimization.

Adapter Method Usage


Key Differences from Astro:

  • Hugo uses fixed filenames (featured.webp) while Astro preserves original names
  • Hugo uses post-specific directories (static/images/{post_id}/) for organization
  • Hugo's get_featured_image_name() ignores the original_basename parameter

Sources: core/class-media-processor.php441-453 core/class-media-processor.php468-472 adapters/class-hugo-adapter.php577-579


Helper Methods

Excerpt Generation


Returns post_excerpt if set, otherwise generates excerpt from content:

  • Strips all HTML tags using wp_strip_all_tags()
  • Trims to 30 words using wp_trim_words()
  • Appends '...' ellipsis

Sources: adapters/class-hugo-adapter.php452-462

Taxonomy Term Extraction


Retrieves term names for a given taxonomy (e.g., 'post_tag', 'category'):

  • Calls get_the_terms($post_id, $taxonomy)
  • Returns empty array on error or no terms
  • Plucks term names using wp_list_pluck($terms, 'name')

Sources: adapters/class-hugo-adapter.php472-480

Featured Image URL


Returns the featured image URL or null:

  • Gets thumbnail ID via get_post_thumbnail_id()
  • Retrieves URL via wp_get_attachment_url()
  • Returns null if no featured image set

Sources: adapters/class-hugo-adapter.php489-499


Error Handling

The Hugo Adapter employs graceful fallbacks throughout its processing pipeline:

OperationPrimary MethodFallbackTrigger
HTML to MarkdownLeague\HTMLToMarkdownbasic_html_to_markdown()Library not available or exception
WebP generationIntervention ImageSkip formatImagick/GD unavailable
AVIF generationIntervention Image (Imagick only)Skip formatImageMagick < 7.0.8
Author nameget_userdata($post->post_author)->display_name'Unknown'User data not found
Featured imageProcessed pathOriginal URLProcessing failed

The adapter never throws exceptions to the caller - all errors result in degraded but functional output.

Sources: adapters/class-hugo-adapter.php218-239 adapters/class-hugo-adapter.php60-61


Complete Method Reference

MethodVisibilityReturn TypePurpose
convert()publicstringMain conversion entry point
get_file_path()publicstringGenerate Hugo file path
get_front_matter()publicarrayGet structured front matter
get_images_dir()publicstringGet images directory path
get_featured_image_name()publicstringGet featured image filename
build_front_matter_from_template()privatestringBuild YAML from template
convert_content()privatestringConvert HTML to Markdown
clean_wordpress_html()privatestringRemove WordPress artifacts
clean_markdown_output()privatestringPost-process Markdown
replace_image_urls()privatestringApply image URL mappings
convert_gutenberg_blocks()privatestringRemove block comments
basic_html_to_markdown()privatestringFallback converter
get_excerpt()privatestringGenerate post excerpt
get_terms()privatearrayGet taxonomy terms
get_featured_image()private?stringGet featured image URL
format_yaml_field()privatestringFormat YAML field
escape_yaml_value()privatestringEscape YAML value

Sources: adapters/class-hugo-adapter.php1-581