1if (!class_exists('RandomizePostPublishPHP')) {
2 // Randomize a Post Publish Date in the Classic Editor [SnipSnip.pro] - https://snipsnip.pro/s/333
3 class RandomizePostPublishPHP {
4 public function __construct() {
5 if (is_admin() && current_user_can('manage_options')) {
6 add_action('admin_footer', array($this, 'add_script_randomize_date_to_page'), 999);
7 }
8 }
9
10 public function add_script_randomize_date_to_page() {
11 // TODO: enable on the Block Editor (way more work!) -- for now, just exit if this is Block Editor
12 if (function_exists('get_current_screen')) {
13 $current_screen = get_current_screen();
14 if (method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor()) {
15 return;
16 }
17 }
18 ?>
19
20<script type="text/javascript">
21(function($) {
22
23 /**
24 * Randomize a Post Publish Date in the Classic Editor [SnipSnip.pro] - https://snipsnip.pro/s/333
25 * @author brandonjp.com
26 *
27 * This script adds a randomize button and month buttons to the WordPress post editor.
28 * Clicking the randomize button selects a random date within the selected range of months
29 * and sets it as the post's publish date.
30 *
31 * Usage:
32 * 1. Include jQuery library in your page.
33 * 2. Add this code within a <script> tag or in an external JavaScript file.
34 * 3. Customize the configuration options as needed.
35 *
36 * Configuration options:
37 * - wpDateEditLink: The selector for the WordPress date edit link.
38 * - randLinkID: The ID for the randomize button.
39 * - randCtrlID: The ID for the container element of the randomize buttons.
40 * - prependRandBtnsTo: The selector for the element to prepend the randomize buttons to.
41 * - btnIDPrefix: The prefix for the IDs of the month buttons.
42 * - monthsToButtonize: An array of integers representing the range of months to buttonize.
43 * - randomWithinText: The text to display before the month buttons.
44 * - monthsText: The text to display after the month buttons.
45 * - styles: The CSS styles to apply to the randomize buttons container element.
46 *
47 * How it works:
48 * - The script initializes by adding the randomize button and month buttons to the editor.
49 * - Clicking the randomize button triggers a random date selection within the range of months.
50 * - The selected date is set as the publish date of the post.
51 */
52 class RandomizePostPublishJS {
53 constructor(config) {
54 this.config = config;
55 this.stylesheet = null;
56 this.initialize();
57 }
58
59 initialize() {
60 if (window.jQuery) {
61 this.addRandomizeButton();
62 this.addRandomizeForm();
63 this.listenForRandomDateButtonClicks();
64 this.listenForRandomizeLinkClick();
65 this.createAndAppendStyleSheet();
66 console.log('Snippet: Randomize a Post Publish Date in the Classic Editor [SnipSnip.pro] - https://snipsnip.pro/s/333');
67 }
68 }
69
70 addRandomizeButton() {
71 const $editLink = $(this.config.wpDateEditLink);
72 const $randLink = $(`
73 <a id="${this.config.randLinkID}" href="#${this.config.randLinkID}" class="rand-timestamp hide-if-no-js" role="button" style="margin-left: 3px;" title="Randomize the date">
74 <span aria-hidden="true">Randomize</span>
75 <span class="screen-reader-text">Use a random date and time</span>
76 </a>
77 `);
78 $editLink.after($randLink);
79 }
80
81 addRandomizeForm() {
82 const $randBtnWrap = $(`<div id="${this.config.randCtrlID}" title="Randomize the date"></div>`);
83 this.config.monthsToButtonize.forEach((num) => {
84 $randBtnWrap.append(`
85 <button type="button" id="${this.config.btnIDPrefix}${num}" data-months="${num}" title="Randomize within ${num} months">
86 ${num}
87 </button>
88 `);
89 });
90 $randBtnWrap.prepend(`<span>${this.config.randomWithinText}</span>`);
91 $randBtnWrap.append(`<span>${this.config.monthsText}</span>`);
92 const $timestampDiv = $(this.config.prependRandBtnsTo);
93 $timestampDiv.prepend($randBtnWrap);
94 }
95
96 getDatePlusMonths(date, months) {
97 const dateCopy = new Date(date);
98 dateCopy.setMonth(dateCopy.getMonth() + months);
99 return dateCopy;
100 }
101
102 randomDate(start, end) {
103 return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
104 }
105
106 setWPPostToNewDate(date) {
107 if (typeof date.getMonth === 'function') {
108 const newDay = date.getDate().toString().padStart(2, '0');
109 const newMonth = (date.getMonth() + 1).toString().padStart(2, '0');
110 const newYear = date.getFullYear();
111 const newDateObj = {
112 aa: newYear,
113 mm: newMonth,
114 jj: newDay,
115 };
116 $.each(newDateObj, (k, v) => {
117 $('#' + k).attr('value', v).val(v).trigger('change');
118 });
119 }
120 }
121
122 setRandomDate(event) {
123 event.preventDefault();
124 const todayDate = new Date();
125 const monthsToAdd = $(event.target).data('months');
126 const oldestDate = this.getDatePlusMonths(todayDate, monthsToAdd);
127 const newDate = this.randomDate(todayDate, oldestDate);
128 this.setWPPostToNewDate(newDate);
129 }
130
131 listenForRandomDateButtonClicks() {
132 $(`#${this.config.randCtrlID} > button`).each((ii, ll) => {
133 $(ll).on('click', this.setRandomDate.bind(this));
134 });
135 }
136
137 listenForRandomizeLinkClick() {
138 $('a#' + this.config.randLinkID).on('click', (e) => {
139 e.preventDefault();
140 $(this.config.wpDateEditLink).trigger('click');
141 const randomMonths = this.config.monthsToButtonize[Math.floor(Math.random() * this.config.monthsToButtonize.length)];
142 $(`button#${this.config.btnIDPrefix}${randomMonths}`).trigger('click');
143 });
144 }
145
146 createAndAppendStyleSheet() {
147 const styles = this.formatStyles(this.config.styles);
148 const styleSheet = $('<style>').prop('type', 'text/css').html(`#${this.config.randCtrlID} { ${styles} }`);
149 $('head').append(styleSheet);
150 }
151
152 formatStyles(styles) {
153 const stylePairs = styles.split(';').map(pair => pair.trim()).filter(pair => pair !== '');
154 const formattedStyles = stylePairs.map(pair => {
155 const [key, value] = pair.split(':').map(item => item.trim());
156 return `${key}:${value};`;
157 });
158 return formattedStyles.join('');
159 }
160 }
161
162 $(document).ready(() => {
163 const config = {
164 wpDateEditLink: '#submitdiv a.edit-timestamp',
165 randLinkID: 'rand_timestamp',
166 randCtrlID: 'rand-controls',
167 prependRandBtnsTo: 'fieldset#timestampdiv',
168 btnIDPrefix: 'rand-btn-',
169 monthsToButtonize: [-12, -6, -2, 6, 12],
170 randomWithinText: 'Within',
171 monthsText: 'Mos',
172 styles: `
173 display: flex;
174 justify-content: space-evenly;
175 margin-bottom: 0.3rem;
176 `
177 };
178
179 new RandomizePostPublishJS(config);
180 });
181})(jQuery);
182
183</script>
184
185<?php
186 }
187 }
188
189 new RandomizePostPublishPHP();
190}