Integrating Wordpress and MODx
Wednesday, September 30th, 2009So at last I join the ever-growing world of blogging. Being a developer of modx sites I considered whether to use the various snippets available for building a blog in MODx, having done this before. However its always good to experiment so instead I opted to link a WordPress blog with my own existing MODx site.
I have recently linked SMF to MODx for the Mountain Rescue England and Wales website, and so adapted the code I used there.
I use the code (below) in an include file which is then included in each of the theme files that represents a WordPress page. Alternatively and to be on the safe side, use ‘require_once’ in every php file that needs data from MODx.
You will see from looking at the code that I have set things so that as far as the MODx API is concerned we are on the document/resource with id 31, which is the MODx weblink to this blog. As such, menu snippets such as Wayfinder will correctly identify docid 31 as being the page we are on. In addition I run the getDocumentObject method so that the template variables used by this document/resource are available.
Lastly I provide a function to parse a MODx chunk as this is what I mainly want it to do (for the header and the navigation in the top right corner).
<?php
// MODx integration
// -------------------------------------------------------------------------------
// ----- CONFIG -----
define('MODX_SITE_BASE_URL', '/');
define('MODX_MANAGER_PATH', '/home/timspe/public_html/TimSpencerWeb_modx/manager');
define('MODX_DOCUMENT_IDENTIFIER', 31); // The MODx document we are going to pretend to be
// ------------------
// Some defines used by the modx API
define('MODX_API_MODE', true); // Tells MODx index.php to not run $modx->executeParser
define('MODX_SITE_URL', (!isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) == 'off' ? 'http://' : 'https://').$_SERVER['SERVER_NAME'].MODX_SITE_BASE_URL);
// Run the MODx config and get site settings
require(MODX_MANAGER_PATH.'/../index.php');
$modx->getSettings();
// Set the docid (most sensibly to the MODx weblink to here) and get the MODx document object
$modx->documentObject = $modx->getDocumentObject('id', MODX_DOCUMENT_IDENTIFIER);
$modx->documentIdentifier = MODX_DOCUMENT_IDENTIFIER;
// Set the base URL for any MODx snippets
$modx->config['base_url'] = MODX_SITE_BASE_URL;
// Get AND parse a modx chunk. Cannot cope with nested snippets within the chunk.
function modx_chunk($chunk_name)
{
global $modx;
return $modx->rewriteURLs(str_replace('[~', MODX_SITE_URL.'[~', // Ensure that the link goes to the MODx site and not e.g. /blog/pagename
$modx->parseDocumentSource(str_replace('[!', '[[', str_replace('!]', ']]', $modx->getChunk($chunk_name))))));
}
?>