function nae_insert_str($text, $insert, $num){
$returnText = $text;
$text_len = mb_strlen($text, "utf-8");
$insert_len = mb_strlen($insert, "utf-8");
for($i=0; ($i+1)*$num<$text_len; $i++) {
$current_num = $num+$i*($insert_len+$num);
$returnText = preg_replace("/^.{0,$current_num}+\K/us", $insert, $returnText);
}
return $returnText;
}
function nae_get_dataset (){
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status' => 'publish'
);
$post_array = get_posts( $args );
$nodes = [];
$edges = [];
foreach ($post_array as $post) {
$category = get_the_category($post->ID);
$root_category_ID = array_pop(get_ancestors( $category[0]->cat_ID, 'category' ));
$root_category = get_category($root_category_ID);
$nodes[] = [
'id' => $post->ID,
'label' => nae_insert_str(urldecode($post->post_name), "\r\n", 20),
'group' => urldecode($root_category->slug),
'title' => ''.$post->post_title.''
];
$html = do_shortcode($post->post_content);
$dom = new DOMDocument;
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new DOMXPath($dom);
$query = "//a[
@href != ''
and not(starts-with(@href, '#'))
and normalize-space() != ''
]";
foreach ($xpath->query($query) as $node) {
$href = $xpath->evaluate('string(@href)', $node);
$linked_post_id = url_to_postid($href);
if ($linked_post_id != 0 && !in_array(['from'=>$post->ID,'to'=>$linked_post_id],$edges )){
$edges[] = [
'from' => $post->ID,
'to' => $linked_post_id
];
}
}
}
return "[".json_encode($nodes).",".json_encode($edges)."]";
}
function nae_echo_article_map(){
$dataset = nae_get_dataset ();
$body = <<
EOD;
return $body;
}
add_shortcode( 'show_article_map', 'nae_echo_article_map' );