Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryWordPress Widgets & Other WP Software

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Custom Message for Website Pages

With this little tool, you can update a specific section of any web page on your website — whenever you feel like it. What you type into the Custom Message for Website Pages software dashboard immediately shows up on your site, wherever you have indicated it shall do so.

It works for both Wordpress websites and non-Wordpress websites.

The dashboard has the copy-and-paste line of code to paste into web pages. It comes with special Wordpress instructions in case yours is a Wordpress site.

The custom message might be your contact information, an ad, a frequently updated quote — whatever can be published with HTML.

For occasional messages, like holiday messages or special announcements, the custom message can be deleted from the software dashboard during the periods when there is nothing to say.

And another thing: when your page loads, the custom content is fetched and published asynchronously. In other words, the custom message will not hold up the main page load. Instead, the message will be inserted into the page as it becomes available.

To present a custom message, just type it into the dashboard.

Optionally, you may use HTML markup. You may also use inline CSS.

However, no JavaScript can be used in the custom message because the message itself is being pulled in with JavaScript. And no PHP code because PHP runs before JavaScript.

Got Clients?

If you have clients who want to update certain sections of their website on their own whim, yet are intimidated with Wordpress or whatever CMS you are using, Custom Message for Website Pages may be a solution.

Your client types their content into a text box. When done, they tap a button. Their content update is immediate.

It is type-and-tap easy.

Screenshot

Here is an editable screenshot of a section of the dashboard.

Type custom message here. HTML markup may be used.

Change the custom message anytime you want for an instant update.

Same-Domain Only

To accomplish the asynchronous custom message publication, Ajax is used.

Unless special coding is inserted into the PHP software, the special message can be published only on web pages at the same domain as the PHP software.

The Source Code

It's a one-file installation. In the file, there are two customization spots. Notes follow the source code.

<?php
/*
   Custom Message for Website Pages
   Version 1.0
   February 11, 2020

   Will Bontrager Software LLC
   https://www.willmaster.com/
*/

/* Two Customizations */
// 
// Place 1:
// Specify the directory location where message data is to be stored. 
//   The directory needs to be writable.

$DataDirectoryLocation = "/CMWPdata";

// Place 2:
// Specify a password for accessing the Custom Mesages dashbaord.

$CMWPdashboardPassword = "UpdatePassword";

/* End Customization */
/**********************************************************/

mb_internal_encoding('UTF-8');
$Global = array();
$Global['Errors'] = array();
$Global['Messages'] = array();
$Global['current-content'] = array();
$Global['dashpw'] = trim($CMWPdashboardPassword);
$Global['dashpw-encrypted'] = md5($Global['dashpw']);
$Global['CookieName'] = 'CustomMessage4WebsiteDashboard';
$Global['LoggedIn'] = isset($_COOKIE[$Global['CookieName']]) ? true : false;
$Global['self'] = ((isset($_SERVER['HTTPS']) and $_SERVER['HTTPS']=='on')?'https://':'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$Global['data-dir'] = (strpos($DataDirectoryLocation,'.')===0) ? $DataDirectoryLocation : ($_SERVER['DOCUMENT_ROOT'].(preg_replace('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',(preg_replace('!^https?://[^*/]+!i','',(preg_replace('!/*$!','',trim($DataDirectoryLocation))))))));
$Global['data-file'] = 'cmwp_data{{N}}.txt';
$Global['data-indice'] = 0;

$Global['f'] = false;
#$Global['f'] = time().'ME.txt';
if($Global['f']){file_put_contents($Global['f'],__LINE__.":\n".print_r($Global,true)."\n\n",FILE_APPEND); }
if($Global['f']){file_put_contents($Global['f'],__LINE__.":\n".print_r($_GET,true)."\n\n",FILE_APPEND); }
if($Global['f']){file_put_contents($Global['f'],__LINE__.":\n".print_r($_POST,true)."\n\n",FILE_APPEND); }

if( count($_GET) ) { foreach( $_GET as $k => $v ) { $_GET[$k] = stripslashes($v); } }
if( count($_POST) ) { foreach( $_POST as $k => $v ) { $_POST[$k] = stripslashes($v); } }
if( isset($_GET['publish']) ) { PublishControl(); }
elseif( isset($_POST['ContentNow']) and $_POST['ContentNow'] == 'yes' ) { PublishContent(); }
elseif( isset($_POST['login']) ) { LogIn(); }
elseif( isset($_GET['logout']) ) { LogOut(); }
elseif( isset($_POST['UpdateContentNow']) and isset($_POST['message_content']) ) { UpdateContent(); }

function ReloadDashboard()
{
   global $Global;
   if( headers_sent() ) { echo "<script>location.href='{$Global['self']}'</script>"; }
   else { header("Location: {$Global['self']}"); }
   exit;
} # function ReloadDashboard()

function LogIn()
{
   global $Global;
   $_POST['pw'] = trim($_POST['pw']);
   if( empty($_POST['pw']) )
   {
      $Global['Errors'][] = 'A password must be provided.';
      return;
   }
   if( $_POST['pw'] != $Global['dashpw'])
   {
      $Global['Errors'][] = 'Incorrect password.';
      return;
   }
   setcookie($Global['CookieName'],time());
   $Global['LoggedIn'] = true;
} # function LogIn()

function LogOut()
{
   global $Global;
   setcookie($Global['CookieName'],'0',time()-2);
   $Global['LoggedIn'] = false;
   ReloadDashboard();
} # function LogOut()

function PublishControl()
{
   global $Global;
   echo header("Content-type: text/javascript");
   $Global['data-indice'] = preg_match('/\d/',$_GET['publish']) ? preg_replace('/\D/','',$_GET['publish']) : '0';
   echo <<<THEJS
function Xsdf_ewir345dsksdfewewewee()
{
  var http = new XMLHttpRequest();
  if(! http) { return; }
  var params = new Array();
  params.push( "ContentNow=yes" );
  params.push( "indice=" + encodeURIComponent("{$Global['data-indice']}") );
  http.onreadystatechange = function()
  { 
    if(http.readyState == 4 && http.status == 200) { document.getElementById("{$_GET['id']}").innerHTML = http.responseText; }
  }
  http.open("POST","{$Global['self']}",true);
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.send(params.join("&"));
}
Xsdf_ewir345dsksdfewewewee();
THEJS;
   exit;
} # function PublishControl()

function PublishContent()
{
   global $Global;
   $Global['data-indice'] = preg_match('/\d/',$_POST['indice']) ? preg_replace('/\D/','',$_POST['indice']) : '0';
   $filename = "{$Global['data-dir']}/" . str_replace('{{N}}',$Global['data-indice'],$Global['data-file']);
   GetContent();
   $Global['current-content'][$Global['data-indice']] = str_replace("\r",'',trim($Global['current-content'][$Global['data-indice']]));
   $Global['current-content'][$Global['data-indice']] = '<p>'.preg_replace('/\n\n+/','</p><p>',$Global['current-content'][$Global['data-indice']]).'</p>';
   $Global['current-content'][$Global['data-indice']] = str_replace("\n",'<br>',$Global['current-content'][$Global['data-indice']]);
   echo $Global['current-content'][$Global['data-indice']];
   exit;
} # function PublishContent()

function GetContent()
{
   global $Global;
   $filename = "{$Global['data-dir']}/" . str_replace('{{N}}',$Global['data-indice'],$Global['data-file']);
   $Global['current-content'][$Global['data-indice']] = file_exists($filename) ? file_get_contents($filename) : '';
   return $Global['current-content'][$Global['data-indice']];
} # function GetContent()

function UpdateContent()
{
   global $Global;
   $Global['data-indice'] = (isset($_POST['indice']) and preg_match('/\d/',$_POST['indice'])) ? preg_replace('/\D/','',$_POST['indice']) : '0';
   $filename = "{$Global['data-dir']}/" . str_replace('{{N}}',$Global['data-indice'],$Global['data-file']);
   if( ! file_exists($Global['data-dir']) ) { mkdir($Global['data-dir'],0755); }
   file_put_contents( $filename, $_POST['message_content'] );
} # function UpdateContent()

?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Message for Website Pages</title>
<style type="text/css">
* { box-sizing:border-box; font-family:sans-serif; }
html, body { font-size:100%; }
p { line-height:140%; }
td, pre { line-height:120%; }
pre, code { font-size:120%; font-family:monospace; }
.smallcaps { font-variant:small-caps; }
ul > :first-child, ol > :first-child, ul > :last-child, ol > :last-child { margin:0; }
div > :last-child { margin-bottom:0; }
div > :first-child { margin-top:0; }
.center { text-align:center; margin-left:auto; margin-right:auto; }
.nowrap { white-space:nowrap; }
.bold { font-weight:bold; }
.italic { font-style:italic; }
.underline { text-decoration:underline; }
h1, h2, h3, h4, h5 { margin-top:0; margin-bottom:.5em; }
h1 { font-size:180%; color:#666; }
a { text-decoration:none; color:#1c5292; font-weight:bold; }
a, img { border:none; outline:none; }
.nowrap { white-space:nowrap; }
input, textarea { width:100%; font-size:1em; }
textarea { height:1.5in; }
input[type="password"], textarea { border:1px solid #ccc; border-radius:3px; padding:5px; }
#content { max-width:500px; margin:55px auto; position:relative; }
</style>
</head>
<body><div id="content">
<form method="post" enctype="multipart/form-data" accept-charset="utf-8" action="<?php echo($_SERVER['PHP_SELF']); ?>">
<div style="position:absolute; left:0; top:-55px;">
<a href="https://www.willmaster.com/"><img src="https://www.willmaster.com/images/wmlogo_icon.gif" style="width:50px; height:50px;" alt="Willmaster logo"></a>
</div>

<h1>Custom&nbsp;Message for Website&nbsp;Pages</h1>
<?php if($Global['LoggedIn']): ?>
<div style="margin:2em 0; text-align:center;">
<div id="wp-instructions-link" style="display:inline-block; padding-right:1em;"><a href="javascript:OpenInstructions()">Custom&nbsp;Message&nbsp;Publishing</a></div>
<div style="display:inline-block; padding-right:1em;"><a href="<?php echo($_SERVER['PHP_SELF']) ?>?logout=1">Log&nbsp;Out</a></div>
</div>
<div id="wp-instructions" style="position:relative; display:none; border:2px dashed #ccc; margin-top:1em; margin-bottom:1em; padding:.5em;">
<div style="position:absolute; right:0; top:0;"><a href="javascript:CloseInstructions()">(Dismiss)</a></div>
<p class="bold" style="margin-top:.25em;">Custom Message Publishing</p>
<p>
To insert custom content into your non&#x2011;WordPress web pages or your WordPress posts, pages, or text widgets, use this line of HTML and JavaScript code:
</p>
<textarea style="height:3em; white-space:nowrap;" wrap="off" nowrap>&lt;div id="cmwp"&gt;&lt;script type="text/javascript" src="<?php echo($Global['self']); ?>?publish&amp;id=cmwp" async&gt;&lt;/script&gt;&lt;/div&gt;</textarea>
<p>
If you change the <code>div</code> tag's <code>id</code> value, make a corresponding change in the <code>script</code> tag's <code>src</code> value.
</p>
<p class="bold" style="margin-bottom:0;">WordPress info:</p>
<p style="margin-bottom:.25em; margin-top:0;">
If you use the Gutenberg feature for editing, paste the HTML/JavaScript code into an "HTML" block. If you use the previously traditional method with "Visual" and "Text" tabs, use the "Text" tab.
</p>
<div style="position:absolute; right:0; bottom:0;"><a href="javascript:CloseInstructions()">(Dismiss)</a></div>
</div>
<script>
function OpenInstructions()
{
   document.getElementById('wp-instructions').style.display='block';
   document.getElementById('wp-instructions-link').style.display='none';
}
function CloseInstructions()
{
   document.getElementById('wp-instructions').style.display='none';
   document.getElementById('wp-instructions-link').style.display='inline-block';
}
</script>
<?php endif; ?>

<!-- style="margin-top:2em;"-->
<div id="message-area">
<?php if( count($Global['Errors']) ): ?>
<div style="border:3px double red; border-radius:9px; color:red; background-color:yellow; font-weight:bold; padding:0 15px; margin-top:2em;">
<p>
<?php echo implode('</p><p>',$Global['Errors']); ?>
</p>
</div>
<?php endif; ?>
</div><!-- id="message-area" -->

<?php if( $Global['LoggedIn'] ): ?>
<p style="margin-bottom:.2em;" class="bold">
Type custom message here. HTML markup may be used.
</p>
<textarea name="message_content"><?php echo(GetContent()) ?></textarea>
<p>
<input type="submit" name="UpdateContentNow" value="Update Custom Message">
</p>
<?php else: ?>
<h3 style="margin-top:2em;">Log In With Password</h3>
<p>
<input type="password" id="pw" name="pw" value="" class="input width">
<p>
<input type="submit" name="login" value="Log In">
</p>
<?php endif; ?>
<p style="position:relative; top:50px; display:table; border-top:1px solid #ccc; padding-top:.15em;">
Copyright 2020 <a href="https://www.willmaster.com/">Will Bontrager Software LLC</a>
</p>
</div>
</body>
</html>

Notes —

In the source code are two lines to customize.

  1. $DataDirectoryLocation = "/CMWPdata";
    

    Replace /CMWPdata with the directory location where the message data file is to be stored.

    The directory needs to be writable. The software will try to create the directory for you if it isn't already present. On some systems, you may need to create the directory manually and, perhaps, give it 777 permissions.

  2. $CMWPdashboardPassword = "UpdatePassword";
    

    Replace UpdatePassword with a password for this dashboard.

When the file has been updated, save it as cmwp.php or other *.php file name. Upload it to your server and make a note of its URL.

To use the dashboard, type its URL into your browser and log in.

The dashboard contains the text box for your custom message. It also contains the code to paste into web pages where the custom message is to be published.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC