admin管理员组文章数量:1122832
I need a Data Layer in my WordPress header.php. It's already running by author like this:
<?php $author_id = get_post_field('post_author', get_queried_object_id()); if (get_the_author_meta('display_name', $author_id) === 'AUTHOR1') { echo '<script> var dataLayer = []; dataLayer.push({'author': 'ALIAS_AUTHOR_1'}); </script>'; } ?>
Now the tricky part: The data layer should disappear 30 days after publish date (not modified date). I really searched the whole web but I did not find any way to let a function stop by Date published plus X days. Any thoughts about that?
I need a Data Layer in my WordPress header.php. It's already running by author like this:
<?php $author_id = get_post_field('post_author', get_queried_object_id()); if (get_the_author_meta('display_name', $author_id) === 'AUTHOR1') { echo '<script> var dataLayer = []; dataLayer.push({'author': 'ALIAS_AUTHOR_1'}); </script>'; } ?>
Now the tricky part: The data layer should disappear 30 days after publish date (not modified date). I really searched the whole web but I did not find any way to let a function stop by Date published plus X days. Any thoughts about that?
Share Improve this question asked Sep 24, 2024 at 21:43 JobJob 31 bronze badge 1 |1 Answer
Reset to default 1In this code we are getting the Publish Date using get_the_date()
to retrieve the publish date of the current post. and then calculating the difference by comparing the publish date with the current date.
After this we conditionally output the script. The condition is if the publish date is within the last 30 days, output the data layer script.
You can achieve your desired results with the help of given code.
<?php
// This is to get the author ID of the current post.
$author_id = get_post_field( 'post_author', get_queried_object_id() );
// This is to get the publish date of the current post.
$publish_date = get_the_date( 'Y-m-d', get_queried_object_id() );
$current_date = date('Y-m-d');
// This is to calculate the difference in days between the publish date and the current date.
$date_diff = ( strtotime( $current_date ) - strtotime( $publish_date ) ) / ( 60 * 60 * 24 );
if ( get_the_author_meta( 'display_name', $author_id ) === 'AUTHOR1' && $date_diff <= 30 ) {
echo '<script> var dataLayer = []; dataLayer.push({"author": "ALIAS_AUTHOR_1"}); </script>';
}
?>
本文标签: How to build an expiring function in Wordpress
版权声明:本文标题:How to build an expiring function in Wordpress? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736288711a1928151.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
<script>
tags this way is frowned upon in WordPress. It's better to usewp_enqueue_script()
to add the script; you can usewp_localize_script()
to pass data from PHP to the script if you need to. – Pat J Commented Sep 25, 2024 at 13:35