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
  • Note that injecting <script> tags this way is frowned upon in WordPress. It's better to use wp_enqueue_script() to add the script; you can use wp_localize_script() to pass data from PHP to the script if you need to. – Pat J Commented Sep 25, 2024 at 13:35
Add a comment  | 

1 Answer 1

Reset to default 1

In 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