Here’s how I solved this type of thing, although it’s assuredly roundabout.
FYI: Transform rules are the correct way to go, but the docs are paleolithic. Wait a bit until the platform/docs/priorities stabilize. In theory, transforms allow you to replace *any* markup with *any* instant articles element.
Try using this filter in your functions.php to add a subtitle to the instant article.
add_filter('instant_articles_transformed_element', 'my_subtitle'], 10, 1);
//the filter is provided by the fb-instant-articles plugin
//it passes in the instant_article object, which you can modify
//before it finishes rendering the feed.
function my_subtitle($article) {
global $post;
$my_subtitle = get_the_excerpt(); //replace this with whatever
//the instant article has a Header element, which has a subtitle property.
//Get it and add a subtitle
$subtitle = $article->getHeader()->withSubTitle($my_subtitle);
//return the modified instant article back into the render flow
return $article;
//verify that your /feed/instant-articles contains <h2>'s in each feed item <content> elements.
}
voravor the “]” after ‘my_subtitle’ in the add_filter function is extraneous (shouldn’t be there), right?
terriz: Yes you are right!
voravor: Beautiful, thank you so much! 🙂
@terriz Yes, sorry about that. Here’s a corrected version:
add_filter('instant_articles_transformed_element', 'my_subtitle', 10, 1);
//the filter is provided by the fb-instant-articles plugin
//it passes in the instant_article object, which you can modify
//before it finishes rendering the feed.
function my_subtitle($article) {
global $post;
$my_subtitle = get_the_excerpt(); //replace this with whatever
//the instant article has a Header element, which has a subtitle property.
//Get it and add a subtitle
$subtitle = $article->getHeader()->withSubTitle($my_subtitle);
//return the modified instant article back into the render flow
return $article;
//verify that your /feed/instant-articles contains <h2>'s in each feed item <content> elements.
}
Thank you – this was very helpful!
Another solution is to use the specific hook ‘instant_articles_subtitle’:
This code is to set the subtitle from the excerpt:
add_filter('instant_articles_subtitle', 'my_subtitle', 10, 2);
function my_subtitle($subtitle, $instant_articles_post) {
$my_post = get_post($instant_articles_post->get_the_id());
$my_subtitle = $my_post->post_excerpt;
return $my_subtitle;
}
This is to set it from the first occurrence of the h2 tag in the post content:
add_filter('instant_articles_subtitle', 'my_subtitle', 10, 2);
function my_subtitle($subtitle, $instant_articles_post) {
$my_post = get_post($instant_articles_post->get_the_id());
preg_match('#<h2[^>]*>(.*?)</h2>#i', $my_post->post_content, $match);
$my_subtitle = $match[1];
return $my_subtitle;
}