Skip to content

Instantly share code, notes, and snippets.

@ChaseWPDEV
Last active February 12, 2020 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChaseWPDEV/78afcdc4ca7997ddfed13c3e915d96cc to your computer and use it in GitHub Desktop.
Save ChaseWPDEV/78afcdc4ca7997ddfed13c3e915d96cc to your computer and use it in GitHub Desktop.
Link files to post_content and watch for easy IDE editing
/* Requires the following npm packages:
grunt
mysql
grunt-contrib-watch
*/
module.exports=function(grunt){
let mysql=require('mysql');
let connection;
grunt.initConfig({
'wp-content-sync':{
host: 'localhost',
user: dbUser,
password: dbUserPassword,
database: 'local_wordpress',
prefix: 'wp_'
}
})
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('wp-content-upload', 'upload portion of sync', function(){
var done=this.async();
let config=grunt.config.get('wp-content-upload');
let content=grunt.file.read(config.filename);
let sql="UPDATE ?? SET ??=? WHERE ??=?";
let updates=[
`${config.prefix}posts`,
'post_content',
content,
'ID',
config.postID
];
sql=mysql.format(sql, updates);
connection.query(sql, function(error, results, fields){
if (error) done(error);
done(results);
});
});
grunt.registerTask('wp-content-sync', 'syncs raw wp-content from the database for editing', function(postID, filename){
let dB=grunt.config.get('wp-content-sync');
//connect to mysql
connection=mysql.createConnection(dB);
connection.connect();
let prefix=dB.prefix;
//let grunt know this is an async task
let file=this.async();
//pull post
connection.query('SELECT `post_content` AS content FROM '+prefix+'posts WHERE `ID`='+postID, function(error, results, fields){
if (error) file(error);
let content=results[0].content;
//write file
grunt.file.write(filename, content);
grunt.file.write(filename+'.bak', content);
//create task to upload changes to database
file(filename);
});
grunt.config.set('wp-content-upload',{
filename: filename,
postID: postID,
prefix:prefix
});
//config the watch task
grunt.config.set('watch', {
files: filename,
tasks:['wp-content-upload'],
options:{
spawn:false
}
});
grunt.task.run(['watch']);
});
};
@ChaseWPDEV
Copy link
Author

The task is run as:

grunt wp-content-sync:1234:post.html

Where 1234 is the post ID and post.html is the file that is sync'd automatically with the database (as long as watch continues to run)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment