<?php


function add_id_to_headers($content)
{
	$header_counts = array();
	$content = preg_replace_callback('/<h([1-6])>(.*?)<\/h[1-6]>/', function ($matches) use (&$header_counts) {
		$header_level = $matches[1];
		if (!isset($header_counts[$header_level])) {
			$header_counts[$header_level] = 0;
		}
		$header_counts[$header_level]++;
		$header_id = 'h_' . $header_level . '_' . $header_counts[$header_level];
		return '<h' . $header_level . ' id="' . esc_attr($header_id) . '">' . $matches[2] . '</h' . $header_level . '>';
	}, $content);

	return $content;
}

add_filter('the_content', 'add_id_to_headers');


function populate_dynamic_checkboxes($field)
{


	$content = get_the_content();
	$dom = new DOMDocument;
	libxml_use_internal_errors(true);
	$dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);
	libxml_clear_errors();

	$headings = [];
	$heading_tags = $dom->getElementsByTagName('*');
	$counters = [
		'h1' => 1,
		'h2' => 1,
		'h3' => 1,
		'h4' => 1,
		'h5' => 1,
		'h6' => 1,
	];
	foreach ($heading_tags as $tag) {
		if (preg_match('/^h([1-6])$/', $tag->nodeName)) {
			$id = $tag->getAttribute('id');
			$pass_id =
				$text = $tag->textContent;
			$heading_type = 'h' . $tag->nodeName[1];
			$att_value = 'h_' . $tag->nodeName[1] . '_' . $counters[$heading_type];
			if (empty($id)) {
				$id = $att_value;
			}
			$headings[$id] = $text;
			$counters[$heading_type]++;
		}
	}

	foreach ($headings as $index => $heading) {
		$field['choices'][$index] = $heading;
	}

	return $field;
}
add_filter('acf/load_field/name=toc_headings', 'populate_dynamic_checkboxes');






?>