<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'content_id':'內容 ID',
'content_category':'內容分類',
'content_author': '內容作者(多個以逗號分隔)',
'content_tags':'內容標籤(多個以逗號分隔)'
});
</script>
function add_datalayer_for_single_posts() {
if (!is_single()) return;
$post_id = get_the_ID();
$categories = wp_get_post_categories($post_id, ['fields' => 'names']);
$categories = (count($categories) > 0)? $categories : '';
$tags = wp_get_post_tags($post_id, ['fields' => 'names']);
$tags = implode(',', $tags);
$author = get_the_author();
?>
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
content_id: <?= json_encode($post_id) ?>,
content_title: <?= json_encode(get_the_title()) ?>,
content_category: <?= json_encode($categories) ?>,
content_tags: <?= json_encode($tags) ?>,
content_author: <?= json_encode($author) ?>
});
</script>
<?php
}
add_action('wp_head', 'add_datalayer_for_single_posts');
請先用 「預覽」 功能測試,確認 「Tags Fired」 是否有觸發成功