<?php
if (!class_exists('RandomizePostPublishPHP')) {
// Randomize a Post Publish Date in the Classic Editor [SnipSnip.pro] - https://snipsnip.pro/s/333
class RandomizePostPublishPHP {
public function __construct() {
if (is_admin() && current_user_can('manage_options')) {
add_action('admin_footer', array($this, 'add_script_randomize_date_to_page'), 999);
}
}
public function add_script_randomize_date_to_page() {
// TODO: enable on the Block Editor (way more work!) -- for now, just exit if this is Block Editor
if (function_exists('get_current_screen')) {
$current_screen = get_current_screen();
if (method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor()) {
return;
}
}
?>
<script type="text/javascript">
(function($) {
/**
* Randomize a Post Publish Date in the Classic Editor [SnipSnip.pro] - https://snipsnip.pro/s/333
* @author brandonjp.com
*
* This script adds a randomize button and month buttons to the WordPress post editor.
* Clicking the randomize button selects a random date within the selected range of months
* and sets it as the post's publish date.
*
* Usage:
* 1. Include jQuery library in your page.
* 2. Add this code within a <script> tag or in an external JavaScript file.
* 3. Customize the configuration options as needed.
*
* Configuration options:
* - wpDateEditLink: The selector for the WordPress date edit link.
* - randLinkID: The ID for the randomize button.
* - randCtrlID: The ID for the container element of the randomize buttons.
* - prependRandBtnsTo: The selector for the element to prepend the randomize buttons to.
* - btnIDPrefix: The prefix for the IDs of the month buttons.
* - monthsToButtonize: An array of integers representing the range of months to buttonize.
* - randomWithinText: The text to display before the month buttons.
* - monthsText: The text to display after the month buttons.
* - styles: The CSS styles to apply to the randomize buttons container element.
*
* How it works:
* - The script initializes by adding the randomize button and month buttons to the editor.
* - Clicking the randomize button triggers a random date selection within the range of months.
* - The selected date is set as the publish date of the post.
*/
class RandomizePostPublishJS {
constructor(config) {
this.config = config;
this.stylesheet = null;
this.initialize();
}
initialize() {
if (window.jQuery) {
this.addRandomizeButton();
this.addRandomizeForm();
this.listenForRandomDateButtonClicks();
this.listenForRandomizeLinkClick();
this.createAndAppendStyleSheet();
console.log('Snippet: Randomize a Post Publish Date in the Classic Editor [SnipSnip.pro] - https://snipsnip.pro/s/333');
}
}
addRandomizeButton() {
const $editLink = $(this.config.wpDateEditLink);
const $randLink = $(`
<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">
<span aria-hidden="true">Randomize</span>
<span class="screen-reader-text">Use a random date and time</span>
</a>
`);
$editLink.after($randLink);
}
addRandomizeForm() {
const $randBtnWrap = $(`<div id="${this.config.randCtrlID}" title="Randomize the date"></div>`);
this.config.monthsToButtonize.forEach((num) => {
$randBtnWrap.append(`
<button type="button" id="${this.config.btnIDPrefix}${num}" data-months="${num}" title="Randomize within ${num} months">
${num}
</button>
`);
});
$randBtnWrap.prepend(`<span>${this.config.randomWithinText}</span>`);
$randBtnWrap.append(`<span>${this.config.monthsText}</span>`);
const $timestampDiv = $(this.config.prependRandBtnsTo);
$timestampDiv.prepend($randBtnWrap);
}
getDatePlusMonths(date, months) {
const dateCopy = new Date(date);
dateCopy.setMonth(dateCopy.getMonth() + months);
return dateCopy;
}
randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
setWPPostToNewDate(date) {
if (typeof date.getMonth === 'function') {
const newDay = date.getDate().toString().padStart(2, '0');
const newMonth = (date.getMonth() + 1).toString().padStart(2, '0');
const newYear = date.getFullYear();
const newDateObj = {
aa: newYear,
mm: newMonth,
jj: newDay,
};
$.each(newDateObj, (k, v) => {
$('#' + k).attr('value', v).val(v).trigger('change');
});
}
}
setRandomDate(event) {
event.preventDefault();
const todayDate = new Date();
const monthsToAdd = $(event.target).data('months');
const oldestDate = this.getDatePlusMonths(todayDate, monthsToAdd);
const newDate = this.randomDate(todayDate, oldestDate);
this.setWPPostToNewDate(newDate);
}
listenForRandomDateButtonClicks() {
$(`#${this.config.randCtrlID} > button`).each((ii, ll) => {
$(ll).on('click', this.setRandomDate.bind(this));
});
}
listenForRandomizeLinkClick() {
$('a#' + this.config.randLinkID).on('click', (e) => {
e.preventDefault();
$(this.config.wpDateEditLink).trigger('click');
const randomMonths = this.config.monthsToButtonize[Math.floor(Math.random() * this.config.monthsToButtonize.length)];
$(`button#${this.config.btnIDPrefix}${randomMonths}`).trigger('click');
});
}
createAndAppendStyleSheet() {
const styles = this.formatStyles(this.config.styles);
const styleSheet = $('<style>').prop('type', 'text/css').html(`#${this.config.randCtrlID} { ${styles} }`);
$('head').append(styleSheet);
}
formatStyles(styles) {
const stylePairs = styles.split(';').map(pair => pair.trim()).filter(pair => pair !== '');
const formattedStyles = stylePairs.map(pair => {
const [key, value] = pair.split(':').map(item => item.trim());
return `${key}:${value};`;
});
return formattedStyles.join('');
}
}
$(document).ready(() => {
const config = {
wpDateEditLink: '#submitdiv a.edit-timestamp',
randLinkID: 'rand_timestamp',
randCtrlID: 'rand-controls',
prependRandBtnsTo: 'fieldset#timestampdiv',
btnIDPrefix: 'rand-btn-',
monthsToButtonize: [-12, -6, -2, 6, 12],
randomWithinText: 'Within',
monthsText: 'Mos',
styles: `
display: flex;
justify-content: space-evenly;
margin-bottom: 0.3rem;
`
};
new RandomizePostPublishJS(config);
});
})(jQuery);
</script>
<?php
}
}
new RandomizePostPublishPHP();
}
Leave a Reply