How-To Steps Shortcode With HowTo Schema
Adds a [howto] shortcode that wraps a numbered list of steps, keeps it on the page as normal content and outputs matching HowTo structured data.
Opens WPIDE on
Code
add_shortcode( 'howto', function ( $atts, $content = '' ) {
$atts = shortcode_atts( array( 'name' => '', 'time' => '' ), $atts, 'howto' );
$content = do_shortcode( (string) $content );
if ( ! preg_match_all( '#<li[^>]*>(.*?)</li>#is', $content, $matches ) ) {
return $content;
}
$steps = array();
foreach ( $matches[1] as $i => $step ) {
$text = trim( wp_strip_all_tags( $step ) );
if ( '' !== $text ) {
$steps[] = array( '@type' => 'HowToStep', 'position' => $i + 1, 'text' => $text );
}
}
$schema = array(
'@context' => 'https://schema.org',
'@type' => 'HowTo',
'name' => $atts['name'] ? wp_strip_all_tags( $atts['name'] ) : wp_strip_all_tags( get_the_title() ),
'step' => $steps,
);
if ( absint( $atts['time'] ) ) {
$schema['totalTime'] = 'PT' . absint( $atts['time'] ) . 'M';
}
return '<div class="howto">' . $content . '</div><script type="application/ld+json">' . wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . '</script>';
} );
Notes
Wrap a numbered list in [howto name="How to repot a plant" time="20"] ... [/howto]; Google no longer shows HowTo rich results, but other search and AI tools read the markup.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.