I'm assigning IDs to each heading on my Wordpress site. It works fine for pages where I don't use ACF with the following code snippet in functions.php
function auto_id_headings( $content ) {
$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
if ( ! stripos( $matches[0], 'id=' ) ) :
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
endif;
return $matches[0];
}, $content );
return $content;
}
add_filter( 'the_content', 'auto_id_headings' );
However, this won't pick up headings inside ACFs so I came up with the following solution, which I also added to functions.php
function auto_id_headings_acf( $value, $post_id, $field ) {
$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
if ( ! stripos( $matches[0], 'id=' ) ) :
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
endif;
return $matches[0];
}, $value );
return $value;
}
add_filter( 'acf/format_value/type=wysiwyg', 'auto_id_headings_acf', 10, 3);
It doesn't work though. :/
Any idea what I can do to make it work? Your help would be greatly appreciated!
I'm assigning IDs to each heading on my Wordpress site. It works fine for pages where I don't use ACF with the following code snippet in functions.php
function auto_id_headings( $content ) {
$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
if ( ! stripos( $matches[0], 'id=' ) ) :
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
endif;
return $matches[0];
}, $content );
return $content;
}
add_filter( 'the_content', 'auto_id_headings' );
However, this won't pick up headings inside ACFs so I came up with the following solution, which I also added to functions.php
function auto_id_headings_acf( $value, $post_id, $field ) {
$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
if ( ! stripos( $matches[0], 'id=' ) ) :
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
endif;
return $matches[0];
}, $value );
return $value;
}
add_filter( 'acf/format_value/type=wysiwyg', 'auto_id_headings_acf', 10, 3);
It doesn't work though. :/
Any idea what I can do to make it work? Your help would be greatly appreciated!
How are you printing the contents of the ACF field in your site code?
Assuming that you have self-coded theme files, instead of using the_field()
to print the field content, you should echo get_field()
passed through the 'the_content'
filter,
eg: echo apply_filters( 'the_content', get_field( 'my_field_name' ) );
and it will apply the modifications from your first snippet.