Skip to content

Instantly share code, notes, and snippets.

@timwright12
Last active May 5, 2024 21:02
Show Gist options
  • Save timwright12/d119410bacde7f3768d469949013e670 to your computer and use it in GitHub Desktop.
Save timwright12/d119410bacde7f3768d469949013e670 to your computer and use it in GitHub Desktop.
Bookmarklet to share links in WordPress
/*
* Bookmarklet is an external script for sharing content Via wordpress
* It was specifically designed for csskarma.com, but feel free to nab it.
*
* Bookmarklet content ( NOTE: change the URL path ):
*
* javascript:(function ()%7Bvar jsCode %3D document.createElement(%27script%27)%3BjsCode.setAttribute(%27src%27, %27https://csskarma.com/js/bookmarklet.js%27)%3Bdocument.body.appendChild(jsCode)%3B %7D())%3B
*
*/
( function ( w, doc ) {
// Enable strict mode
'use strict';
// Local object for method references
var Bookmarklet = {};
// Namespace
Bookmarklet.ns = 'Bookmarklet for sharing links in WordPress';
// Return the page title
Bookmarklet.getTitle = function() {
var post_title = doc.title;
if ( post_title ) {
post_title = encodeURIComponent( post_title );
} else {
post_title = '';
}
return post_title;
}; // getTitle
// Return some content for a blurb
Bookmarklet.getContent = function() {
var description = doc.head.querySelector( 'meta[name="description"]' );
var post_content;
if ( description ) {
post_content = description.content;
}
// If the content isn't there, try this:
if ( !post_content ) {
post_content = doc.querySelectorAll( 'article p' )[0].innerHTML;
}
// If it's still not there, try this:
if ( !post_content ) {
post_content = doc.querySelectorAll( '[role="main"] p' )[0].innerHTML;
}
// URL encode the content that gets returned, or blank it out so it doesn't throw and error
if ( post_content ) {
post_content = encodeURIComponent( post_content );
} else {
post_content = '';
}
return post_content;
}; // getContent()
// Return the URL to be shared
Bookmarklet.getURL = function() {
var location = window.location.href;
var post_url = encodeURIComponent( location );
return post_url;
}; // getURL()
// Initialize the bookmarklet
Bookmarklet.init = function( baseURL ) {
var title = Bookmarklet.getTitle();
var content = Bookmarklet.getContent();
var url = Bookmarklet.getURL();
w.location.href = baseURL + '/wp-admin/post-new.php?post_title=' + title + '&content=' + content + '-' + url;
};
// Start the application
Bookmarklet.init( 'https://csskarma.com/blog' );
} )( this, this.document );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment