hangar-wp-theme/functions.php

475 lines
16 KiB
PHP
Raw Permalink Normal View History

2021-02-18 14:09:56 +01:00
<?php load_theme_textdomain('hangar', TEMPLATEPATH .'/languages');
/* add support for thumbnails */
if ( function_exists( 'add_theme_support' ) )
add_theme_support( 'post-thumbnails' );
if ( function_exists( 'add_image_size' ) ) {
add_image_size( 'artists-thumb', 200, 230, true ); //200x230
add_image_size( 'obres-thumb', 136, 102, true ); //per a les galeries de les obres
}
// Path constants
define('THEMELIB', TEMPLATEPATH . '/library');
// Create widgetitzed sidebars
require_once(THEMELIB . '/widgetized-sidebars.php');
// Comments extensions
require_once(THEMELIB . '/comments-extensions.php');
// Comments extensions
require_once(THEMELIB . '/breadcrumb.php');
// Create custom posts and custom fields
require_once(THEMELIB . '/custom-posts.php');
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_more($more) {
global $post;
return '<a href="'. get_permalink($post->ID) . '"> [...]</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
// custom login screen i peu de l'admin
function custom_login() {
//echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo('template_directory').'/custom-login/custom-login.css" />';
// time stamp for caching
// https://developer.wordpress.org/reference/functions/wp_enqueue_style/#comment-2056
// wp_enqueue_style( 'myCustomStyles', get_template_directory_uri() . '/css/styleHangar.css', array(), filemtime(get_template_directory() . '/css/styleHangar.css'), false);
echo '<link rel="stylesheet" type="text/css" href="'. get_template_directory_uri() .'/custom-login/custom-login.css" />';
}
add_action('login_head', 'custom_login');
function change_wp_login_url() {
echo bloginfo('url');
}
add_filter('login_headerurl', 'change_wp_login_url');
function change_wp_login_title() {
echo 'Powered by ' . get_option('blogname');
}
add_filter('login_headertitle', 'change_wp_login_title');
function remove_footer_admin () {
echo 'Custom text | Copyright &copy; message';
}
add_filter('admin_footer_text', 'remove_footer_admin');
// THIS GIVES US SOME OPTIONS FOR STYLING THE ADMIN AREA
function custom_controls() {
echo '<style type="text/css">
label.lateral{width: 100px;}
input.lateral{width: 150px; border-color: #ddd;}
.petit {width: 20px!important;}
label.dd{float:left; width:250px;}
input.dd{width:450px;}
</style>';
}
add_action('admin_head', 'custom_controls');
/* create calendar event when saving post with dates */
function create_event( $post_id ) {
// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) )
return;
$myPost = get_post($post_id);
if (has_category(array('news', 'activitats-dels-residents'), $post_id) &&
!$update &&
$myPost->post_modified_gmt == $myPost->post_date_gmt) {
//The URL that we want to send a PUT request to.
$uid = get_the_guid( $post_id );
$url = 'https://cloud.hangar.org/remote.php/dav/calendars/hangar/hangar_activitats/neu.ics';
$headers = array('Content-Type: text/calendar', 'charset=utf-8');
$userpwd = 'hangar:AV63xlklCuOJgYTnHz5smX4chiAaDpJo';
$description = get_the_content( $post_id );
$summary = get_the_title( $post_id );
$tstart = gmdate("Ymd\THis\Z", strtotime("-2 days"));
$tend = gmdate("Ymd\THis\Z", strtotime("-2 days"));
$tstamp = gmdate("Ymd\THis\Z");
// vcalendar
$body = 'BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
DTSTAMP:$tstamp
DTSTART:$tstart
DTEND:$tend
UID:$uid
DESCRIPTION:$description
LOCATION:Hangar
SUMMARY:$summary
END:VEVENT
END:VCALENDAR';
//Initiate cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
//curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//Execute the request.
$response = curl_exec($ch);
curl_close($ch);
// send confirmation mail
$post_title = $summary;
$post_excerpt = $description;
$post_url = get_permalink( $post_id );
$subject = 'A new EVENT post has been saved';
$message = "A new post has been created on your website:\n\n";
$message .= $post_title . ": " . $post_url . "\n\n";
$message .= $post_excerpt . "\n\n";
$message .= $uid . "\n\n";
$message .= print_r($response);
// Send email to admin.
wp_mail( 'gerald@hangar.org', $subject, $message );
}
}
add_action( 'save_post', 'create_event', 10, 3 );
//per imprimir el content sense que ens tregui l'html
function get_the_content_with_formatting ($more_link_text = '(...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
$content = substr($content, 0,400);
return $content;
}
//per imprimir l'excerpt indicant un nombre de caràcters màxim
function the_excerpt_max_charlength($charlength) {
$excerpt = get_the_excerpt();
$charlength++;
if(strlen($excerpt)>$charlength) {
$subex = substr($excerpt,0,$charlength-5);
$exwords = explode(" ",$subex);
$excut = -(strlen($exwords[count($exwords)-1]));
if($excut<0) {
echo substr($subex,0,$excut);
} else {
echo $subex;
}
echo "[...]";
} else {
echo $excerpt;
}
}
//afegir estils a l'editor
/* Custom CSS styles on WYSIWYG - Start
======================================= */
if ( ! function_exists( 'myCustomTinyMCE' ) ) :
function myCustomTinyMCE($init) {
$init['theme_advanced_buttons2_add_before'] = 'styleselect'; // Adiciona os botões no incio da linha. (theme_advanced_buttons2_add adiciona-os no fim da linha)
$init['theme_advanced_styles'] = 'Centrar text=centertext,Text blau=textblau,Lletra petita=petita,Icona PDF=pdficon'; // Especifica os estilos a aplicar pela selectbox acima criada, e que já estão definidos no mycustomstyles.css, altere e/ou acrescente os seus.
return $init;
}
endif;
add_filter('tiny_mce_before_init', 'myCustomTinyMCE' );
add_filter( 'mce_css', 'tdav_css' );
// incluir o CSS no tema.
function mycustomStyles(){
// Se tiver dado ao seu ficheiros css um nome diferente do usado no exemplo, altere também aqui o nome do mesmo.
//wp_enqueue_style( 'myCustomStyles', get_bloginfo('template_url').'/css/styleHangar.css', '','','all' );
// time stamp for caching
// https://developer.wordpress.org/reference/functions/wp_enqueue_style/#comment-2056
wp_enqueue_style( 'myCustomStyles', get_template_directory_uri() . '/css/styleHangar.css', array(), filemtime(get_template_directory() . '/css/styleHangar.css'), false);
}
add_action('init', 'myCustomStyles');
/* Custom CSS styles on WYSIWYG - End
======================================= */
/**
* Tests if any of a post's assigned categories are descendants of target categories
*
* @param int|array $cats The target categories. Integer ID or array of integer IDs
* @param int|object $_post The post. Omit to test the current post in the Loop or main query
* @return bool True if at least 1 of the post's categories is a descendant of any of the target categories
* @see get_term_by() You can get a category by name or slug, then pass ID to this function
* @uses get_term_children() Passes $cats
* @uses in_category() Passes $_post (can be empty)
* @version 2.7
* @link http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category
*/
function post_is_in_descendant_category( $cats, $_post = null )
{
foreach ( (array) $cats as $cat ) {
// get_term_children() accepts integer ID only
$descendants = get_term_children( (int) $cat, 'category');
if ( $descendants && in_category( $descendants, $_post ) )
return true;
}
return false;
}
//end function testing descendent categories
function is_page_child($post, $idp)
{
//497 = artistes residents
$prova = $post->post_parent;
if ($prova == $idp) :
return true;
else :
return false;
endif;
$idp = null;
}
//per saber si una categoria té subcategories
function has_subcategories($catt)
{
$child_cats = get_term_children($catt, 'category');
$childs = count($child_cats);
if ($childs > 0 ) :
return true;
else :
return false;
endif;
}
//contruim un panell de control a l'administració per a que vegin les que estan marcades per a sortir a la home
function menu_control_home(){
add_menu_page( "Control Home","Control Home", "add_users", "control_home", "control_home", "", 6 );
}
function control_home(){
global $wpdb;
$querystr = "
SELECT wposts.post_name,wposts.ID, users.user_login, m1.meta_value as inicio, m2.meta_value as orden
FROM $wpdb->posts wposts
INNER JOIN $wpdb->postmeta m1 ON wposts.ID = m1.post_id
INNER JOIN $wpdb->postmeta m2 ON wposts.ID = m2.post_id
INNER JOIN $wpdb->users users ON wposts.post_author = users.ID
WHERE (wposts.post_type = 'post' OR wposts.post_type = 'page')
AND m1.meta_key = 'Inici'
AND m1.meta_value = '1'
AND m2.meta_key = 'Ordre_inici'
GROUP BY ID
ORDER BY inicio DESC, CAST(orden AS SIGNED) ASC
";
echo' <div id="wpbody-content">
<div class="wrap"><h2>Control Home</h2><br/></div>';
$pageposts = $wpdb->get_results($querystr, OBJECT);
if ($pageposts):
global $post;
echo "<table class=\"wp-list-table widefat fixed posts\" cellspacing=\"0\">
<thead>
<tr>
<th scope='col' width='150' class='manage-column column-slug sortable desc'>Nombre Post</th>
<th scope='col' class='manage-column column-slug sortable desc'>Id</th>
<th scope='col' class='manage-column column-slug sortable desc'>Autor Post</th>
<th scope='col' class='manage-column column-slug sortable desc'>Inicio</th>
<th scope='col' class='manage-column column-slug sortable desc'>Orden</th>
</tr>
</thead>
<tbody id=\"the-list\">";
foreach ($pageposts as $post):
$nom = $post->post_name;
$id = $post->ID;
$autor = $post->user_login;
$inici = $post->inicio;
$ordre = $post->orden;
echo "<tr>
<td><a href='post.php?post=$id&action=edit' class=\"row-tittle\">$nom</a></td>
<td>$id</td>
<td>$autor</td>
<td>$inici</td>
<td>$ordre</td>
</tr>";
endforeach;
echo "</tbody></table></div>";
endif;
}
add_action("admin_menu","menu_control_home");
// Filtre que modifica la funcio que mostra els menús, per poder seleccionar mitjançant el camp title, quines seràn links i quines no.
// title= no_link -> no es un link
// title != no_link -> es un link
// wp_includes -> nav-menu-template.php, es on es trova la clase que s'esta modificant
class my_Walker_Nav_Menu extends Walker_Nav_Menu {
/**
* @see Walker::start_el()
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param int $current_page Menu item ID.
* @param object $args
*/
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
{
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
$class_names = ' class="' . esc_attr( $class_names ) . '"';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
if(! empty( $item->attr_title ) && ($item->attr_title == 'no_link'))
{
$attributes = '';
}
else
{
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
?>
<?php
/* Code that preserves HTML formating to the automatically generated Excerpt. */
/* Also modifies the default excerpt_length and excerpt_more filters. */
/*function custom_wp_trim_excerpt($text) {
$raw_excerpt = $text;
if ( '' == $text ) {
$text = get_the_content('');
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]&gt;', $text);
//Add the allowed HTML tags separated by a comma.
$allowed_tags = '<p>,<a>,<em>,<strong>';
$text = strip_tags($text, $allowed_tags);
//Change the excerpt word count.
$excerpt_word_count = 60;
$excerpt_length = apply_filters('excerpt_length', $excerpt_word_count);
//Change the excerpt ending.
$excerpt_end = ' <a href="'. get_permalink($post->ID) . '">' . '&raquo; Continue Reading.' . '</a>';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
}*/
// https://stackoverflow.com/questions/15283948/wordpress-html-tags-strip-on-manual-excerpt
function custom_wp_trim_excerpt($text='') {
$raw_excerpt = $text;
if ( '' == $text ) {
//Retrieve the post content.
$text = get_the_content('');
//Delete all shortcode tags from the content.
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]&gt;', $text);
$allowed_tags = '<strong>,<em>,<b>,<i>,<p>,<a>'; /*** MODIFY THIS. Add the allowed HTML tags separated by a comma.***/
$twopart_tags = '<strong>,<em>,<b>,<i>,<p>,<a>'; /*** MODIFY THIS. Add the twopart HTML tags separated by a comma.***/
/* turn tag list into one big search pattern */
$search_patterns = "/" . str_replace(",","|",str_replace(">", "[^>]*>",$twopart_tags)) . '/';
$text = strip_tags($text, $allowed_tags);
$excerpt_word_count = 200; /*** MODIFY THIS. change the excerpt word count to any integer you like.***/
$excerpt_length = apply_filters('excerpt_length', $excerpt_word_count);
$excerpt_end = '[...]'; /*** MODIFY THIS. change the excerpt endind to something else.***/
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
};
/* if fragment ends in open tag, trim off */
preg_replace ("/<[^>]*$/", "", $text);
/* search for tags in excerpt */
preg_match_all ($search_patterns, $text, $matches);
/* if any tags found, check for matching pairs */
$tagstack = array ("");
$tagsfound = $matches[0];
while ( count ($tagsfound) > 0) {
$tagmatch = array_shift($tagsfound);
/* if it's a closing tag, hooray; but if it's not, then look for the closer */
if ( !strpos($tagmatch,"</") && !strpos ($tagmatch,"/>") ) {
preg_match("/\pL+/",$tagmatch, $tagwords);
$endtag = "</" . $tagwords[0] . ">";
/* if this tag was not closed, put the closing tag on the stack */
if (!in_array($endtag, $tagsfound) ) {
array_push($tagstack,$endtag);
};
};
};
/* if any unbalanced tags were found, add the closing tags */
while (count ($tagstack) > 1) {
$text = $text . array_pop($tagstack);
}
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_wp_trim_excerpt');
?>