Skip to content

Instantly share code, notes, and snippets.

@bewho
Created February 7, 2018 11:31
Show Gist options
  • Save bewho/8afa1fb09159c1264a84e8ecdd78b3ad to your computer and use it in GitHub Desktop.
Save bewho/8afa1fb09159c1264a84e8ecdd78b3ad to your computer and use it in GitHub Desktop.
M11 functions
<?php
/*
Plugin Name: M11 Theme Features
Plugin URI: https://speedword.press
Description: Das Plugin muss sich im Ordner wp-content/mu-plugins/ befinden. Ebenfalls muss in der wp-config autoupdaten aktiviert sein.
Author: Daniel Bieli
Author URI: https://speedword.press
License: GPL2
*/
/* =======================================================================
01 - BASE64
======================================================================== */
class base64_encode_images{ function parse($content = ''){ return preg_replace_callback( '|<img(.*)src=["\'](.*?)["\'](.*)/>|i', create_function( '$matches', 'return "<img$matches[1]src=\'".(base64_encode_images::fetchurl($matches[2]))."\'$matches[3]/>";' ), $content ); } public function fetchurl($url = null, $ttl = 86400){ if($url){ $option_name = 'base64_encode_images_'.md5($url); $data = get_option($option_name); if(isset($data['cached_at']) && (time() - $data['cached_at'] <= $ttl)){}else{ $ch = curl_init(); $options = array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 10 ); curl_setopt_array($ch, $options); $data['chunk'] = @base64_encode(curl_exec($ch)); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $data['mime'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if($http_code === 200){ $data['cached_at'] = time(); update_option($option_name, $data); } } } return 'data:'.$data['mime'].';base64,'.$data['chunk']; } }
add_filter('the_content', array('base64_encode_images','parse'));
add_filter('post_thumbnail_html', array('base64_encode_images','parse'));
/* =======================================================================
02 - SITEMAP
======================================================================== */
function ah_create_sitemap() {
$sitemap_posts = get_posts(array(
'numberposts' => -1,
'orderby' => 'modified',
'post_type' => array('post','page'), // Deine Custom Post Types hier einfügen (z.B. Portfolio)
'order' => 'DESC'
));
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach($sitemap_posts as $post) {
setup_postdata($post);
$postdate = explode(" ", $post->post_modified);
$sitemap .= '<url>'.
'<loc>'. get_permalink($post->ID) .'</loc>'.
'<lastmod>'. $postdate[0] .'</lastmod>'.
'<changefreq>monthly</changefreq>'.
'</url>';
}
$sitemap .= '</urlset>';
$fp = fopen(ABSPATH . "sitemap.xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}
add_action('publish_post', 'ah_create_sitemap');
add_action('publish_page', 'ah_create_sitemap');
/* =======================================================================
04 - RELATIVE LINKS
======================================================================== */
function make_href_root_relative($input) { return preg_replace('!http(s)?://' . $_SERVER['SERVER_NAME'] . '/!', '/', $input); } function root_relative_permalinks($input) { return make_href_root_relative($input); }
add_filter( 'day_link', 'root_relative_permalinks');
add_filter( 'year_link', 'root_relative_permalinks');
add_filter( 'term_link', 'root_relative_permalinks');
add_filter( 'month_link', 'root_relative_permalinks');
add_filter( 'search_link', 'root_relative_permalinks');
add_filter( 'the_content', 'root_relative_permalinks');
add_filter( 'the_permalink', 'root_relative_permalinks');
add_filter( 'get_shortlink', 'root_relative_permalinks');
add_filter( 'post_type_link', 'root_relative_permalinks');
add_filter( 'attachment_link', 'root_relative_permalinks');
add_filter( 'get_pagenum_link', 'root_relative_permalinks');
add_filter( 'wp_get_attachment_url', 'root_relative_permalinks');
add_filter( 'post_type_archive_link', 'root_relative_permalinks');
add_filter( 'get_comments_pagenum_link', 'root_relative_permalinks');
/* =======================================================================
05 - REMOVE ADMIN DASHBOARD WIDGETS
======================================================================== */
function ah_remove_dashboard_widgets() {
global $wp_meta_boxes;
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}
add_action('wp_dashboard_setup', 'ah_remove_dashboard_widgets' );
/* =======================================================================
06 - REMOVE QUERY STRINGS
======================================================================== */
function evolution_remove_wp_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
add_filter( 'style_loader_src', 'evolution_remove_wp_ver_css_js', 9999 );
add_filter( 'script_loader_src', 'evolution_remove_wp_ver_css_js', 9999 );
/* =======================================================================
07 - Syntax Highlighten
======================================================================== */
function add_prism() {
if ( is_single() ) { ?>
<link rel="stylesheet" href="/wp-content/themes/M11/prism.css">
<script type="text/javascript" src="/wp-content/themes/M11/prism.js"></script>
<?php }
}
add_action('wp_footer', 'add_prism');
/* =======================================================================
08 - HTML Minify
======================================================================== */
class WP_HTML_Compression {
protected $compress_css = true;
protected $compress_js = true;
protected $info_comment = true;
protected $remove_comments = true;
protected $html;
public function __construct($html) {
if (!empty($html)) {
$this->parseHTML($html);
}
}
public function __toString() {
return $this->html;
}
protected function bottomComment($raw, $compressed) {
$raw = strlen($raw);
$compressed = strlen($compressed);
$savings = ($raw-$compressed) / $raw * 100;
$savings = round($savings, 2);
return '<!-- HTML Minify | Größe reduziert um '.$savings.'% | Von '.$raw.' Bytes, auf '.$compressed.' Bytes -->';
}
protected function minifyHTML($html) {
$pattern = '/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si';
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
$overriding = false;
$raw_tag = false;
$html = '';
foreach ($matches as $token) {
$tag = (isset($token['tag'])) ? strtolower($token['tag']) : null;
$content = $token[0];
if (is_null($tag)) {
if ( !empty($token['script']) ) {
$strip = $this->compress_js;
}
else if ( !empty($token['style']) ) {
$strip = $this->compress_css;
}
else if ($content == '<!--wp-html-compression no compression-->') {
$overriding = !$overriding;
continue;
}
else if ($this->remove_comments) {
if (!$overriding && $raw_tag != 'textarea') {
$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
}
}
}
else {
if ($tag == 'pre' || $tag == 'textarea') {
$raw_tag = $tag;
}
else if ($tag == '/pre' || $tag == '/textarea') {
$raw_tag = false;
}
else {
if ($raw_tag || $overriding) {
$strip = false;
}
else {
$strip = true;
$content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content);
$content = str_replace(' />', '/>', $content);
}
}
}
if ($strip) {
$content = $this->removeWhiteSpace($content);
}
$html .= $content;
}
return $html;
}
public function parseHTML($html) {
$this->html = $this->minifyHTML($html);
if ($this->info_comment) {
$this->html .= "\n" . $this->bottomComment($html, $this->html);
}
}
protected function removeWhiteSpace($str) {
$str = str_replace("\t", ' ', $str);
$str = str_replace("\n", '', $str);
$str = str_replace("\r", '', $str);
while (stristr($str, ' ')) {
$str = str_replace(' ', ' ', $str);
}
return $str;
}
}
function wp_html_compression_finish($html) {
return new WP_HTML_Compression($html);
}
function wp_html_compression_start() {
ob_start('wp_html_compression_finish');
}
add_action('get_header', 'wp_html_compression_start');
/* =======================================================================
16 - SHARE BUTTONS
======================================================================== */
function tb_share_buttons() {
?>
<div class="share-container">
<div class="share-buttons">
<center><a style="background: #5DB5DE; font-weight: bold; color: #fff; padding: 5px 15px 5px 15px;" title="Bei Twitter empfehlen" href="https://twitter.com/intent/tweet?source=webclient&text=<?php echo rawurlencode(strip_tags(get_the_title())) ?> <?php echo urlencode(get_permalink($post->ID)); ?>" target="blank" rel="nofollow"><span>Twitter</span></a>
<a style="background: #3D62B3; font-weight: bold; color: #fff; padding: 5px 15px 5px 15px;" title="Bei Facebook empfehlen" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode(get_permalink($post->ID)); ?>&t=<?php echo rawurlencode(strip_tags(get_the_title())) ?>" target="blank" rel="nofollow"><span>Facebook</span></a>
<a style="background: #D34836; font-weight: bold; color: #fff; padding: 5px 15px 5px 15px;" title="Bei Google+ empfehlen" href="https://plusone.google.com/_/+1/confirm?hl=de&url=<?php echo urlencode(get_permalink($post->ID)); ?>&title=<?php echo rawurlencode(strip_tags(get_the_title())) ?>" target="blank" rel="nofollow"><span>Google+</span></a></center>
</div>
</div>
<?php }
/* =======================================================================
09 - SCREENSHOTS
======================================================================== */
function tb_screenshots($atts, $content = NULL) {
extract(shortcode_atts(array(
"snap" => 'http://s.wordpress.com/mshots/v1/',
"url" => 'https://project.speedword.press',
"alt" => 'screenshot',
"w" => '720', // die Breite des Screenshots
"h" => '500' // die Höhe des Screenshots
), $atts));
$img = '';
return $img;
}
add_shortcode("screen", "tb_screenshots");
/* =============================================================================
10 - ALLE VIDEOS RESPONSIVE MACHEN
============================================================================= */
function noupe_wrap_oembed( $html ){
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); // Strip width and height #1
return'<div class="embed-youtube">'.$html.'</div>'; // Wrap in div element and return #3 and #4
}
add_filter( 'embed_oembed_html','noupe_wrap_oembed',10,1);
/* =============================================================================
11 - EMBED GIST
============================================================================= */
class mattonomics_gist {
public function __construct() {
add_action('wp', array(__CLASS__, 'add_css')); // check if we have a gist
}
public static function add_css() {
global $post;
if (self::has_gist($post))
add_action('wp_head', array(__CLASS__, 'css_output')); // if we have a gist, add the css to the head
}
public static function has_gist($post = false) {
if (! empty($post) && is_object($post) && property_exists($post, 'post_content') && preg_match('/\[gist.+\]/', $post->post_content))
return true;
return false;
}
public static function css_output() {
echo "\n\n\t\t\n"
. "\t\t\n";
}
public static function gist($a) {
if (! preg_match('/^https:\/\/gist\.github\.com\/([0-9]+)$/', $a['src'], $m)) // $m[1] is the identifier
return false;
$g = wp_remote_get("http://gist.github.com/{$m[1]}.json");
if (! is_wp_error($g))
$code = json_decode($g['body']);
return $code->div;
}
}
add_shortcode('gist', array('mattonomics_gist', 'gist'));
new mattonomics_gist;
/* =============================================================================
12 - POSTLIST SHORTCOLDE
============================================================================= */
function recent_posts_shortcode($atts, $content = NULL)
{
$atts = shortcode_atts(
[
'orderby' => 'date',
'posts_per_page' => '50'
], $atts, 'recent-posts' );
$query = new WP_Query( $atts );
$output = '<ul class="recent-posts">';
while($query->have_posts()) : $query->the_post();
$output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a> - <small>' . get_the_date() . '</small></li>';
endwhile;
wp_reset_query();
return $output . '</ul>';
}
add_shortcode('recent-posts', 'recent_posts_shortcode');
/* =============================================================================
13 - RSS FEED LIST SHORTCOLDE
============================================================================= */
function tb_categories_with_feed() {
$args = array(
'orderby' => 'name',
'feed' => 'RSS',
'echo' => false,
'title_li' => '',
);
$string .= '<ul>';
$string .= wp_list_categories($args);
$string .= '</ul>';
return $string;
}
// add shortcode
add_shortcode('categories-feed', 'tb_categories_with_feed');
// Add filter to execute shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
/* =============================================================================
14 - CUSTOM LOGIN
============================================================================= */
function speedwp_replace_login_logo() { ?>
<style type="text/css">
#login h1 a, .login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/site-login-logo.png);
padding-bottom: 30px;
}</style>
<?php }
add_action( 'login_enqueue_scripts', 'speedwp_replace_login_logo' );
function speedwp_replace_login_url() {
return home_url();
}
add_filter( 'login_headerurl', 'speedwp_replace_login_url' );
function speedwp_replace_login_url_title() {
return 'SpeedWord.Press - Performence Webdesign';
}
add_filter( 'login_headertitle', 'speedwp_replace_login_url_title' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment