Suporte » Plugins » [Plugin] Funções adicionais ao functions.php

  • Resolvido kraudio

    (@kraudio)


    Bom dia a todos, sempre que tenho um novo projeto e preciso de alguma função extra, vou la e começo a editar o functions.php e ir colocando o que preciso(que se torna um pouco incomodo, já que nem sempre tenho os códigos todos juntos). Hoje li um artigo Ayudawordpress que gostei muito.

    Bom, qual é minha idéia colocando este post aqui? compartilhar e atribuir mais funções ao plugin.

    Sem mais conversa, segue o plugin(mantive os créditos do autor).

    <?php
    /*
    Plugin Name: Funciones
    Plugin URI: http://ayudawordpress.com/
    Description: Plugin para liberar de funciones el fichero <code>functions.php</code> y activarlo a placer (o no) .
    Version: 1.0
    Author: Fernando Tellado
    Author URI: http://tellado.es
    License: GPLv2 o posterior
    */
    
    // Logo personalizado en login
    
    add_action("login_head", "my_login_head");
    function my_login_head() {
    	echo "
    	<style>
    	body.login #login h1 a {
    		background: url('".get_bloginfo('template_url')."/images/awloginlogo.png') no-repeat scroll center top transparent;
    		height: 135px;
    		width: 135px;
    	}
    	</style>
    	";
    }
    
    // personalizar url logo acceso
    add_action( 'login_headerurl', 'my_custom_login_url' );
    function my_custom_login_url() {
    return 'http://ayudawordpress.com';
    }
    
    //Cambiar texto alt del logo de login
    add_action("login_headertitle","my_custom_login_title");
    function my_custom_login_title()
    {
    return 'Otro sitio creado por Fernando Tellado';
    }
    
    // Añadir campos sociales a los perfiles y elimina (unset) los inútiles
    function add_redessociales_contactmethod( $contactmethods ) {
      // Añade Twitter
      $contactmethods['twitter'] = 'Twitter';
      // Añade Facebook
      $contactmethods['facebook'] = 'Facebook';
      // Quita Yahoo, IM, AIM y Jabber
      unset($contactmethods['yim']);
      unset($contactmethods['aim']);
      unset($contactmethods['jabber']);
      return $contactmethods;
    }
    add_filter('user_contactmethods','add_redessociales_contactmethod',10,1);
    
    // Añadir nuevos tipos de archivo para subir
     add_filter ( 'upload_mimes' , 'masMimes' ) ;
     function masMimes ( $mimes )
     {
    	 $mimes = array_merge ( $mimes , array (
    		 'pages|numbers|key' => 'application/octet-stream'
    	 ) ) ;
    
    	 return $mimes ;
     } 
    
    // Cambiar texto de pie de página en el escritorio
    function remove_footer_admin () {
        echo "Este sitio está administrado por mi mismo y mi mecanismo";
    } 
    
    add_filter('admin_footer_text', 'remove_footer_admin'); 
    
    //quitar menus de admin
    //function quitar_menus () {
    //global $menu;
    //		$restricted = array( __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
    //		end ($menu);
    //		while (prev($menu)){
    //			$value = explode(' ',$menu[key($menu)][0]);
    //			if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
    //		}
    //}
    //add_action('admin_menu', 'quitar_menus');
    
    // añade enlaces/menús a la barra de admin
    function mytheme_admin_bar_render() {
    	global $wp_admin_bar;
    	if ( !is_super_admin() || !is_admin_bar_showing() )
            return;
    	$wp_admin_bar->add_menu( array(
    		'parent' => 'comments', // usa 'false' para que sea un menú superior o sino indica el ID del menú superior
    		'id' => 'false', // ID del enlace, por defecto debe ser un valor de título
    		'title' => __('Disqus'), // título del enlace
    		'href' => admin_url( 'edit-comments.php?page=disqus') // hombre del archivo al que enlaza, en mi caso disqus
    	));
    }
    add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );
    
    //permalinks canónicos
    function set_canonical() {
      if ( is_single() ) {
    	global $wp_query;
    	echo '<link rel="canonical" href="'.get_permalink($wp_query->post->ID).'"/>';
      }
    }
    add_action('wp_head', 'set_canonical');
    
    //soporte de Twitter oEmbed
    add_filter('oembed_providers','twitter_oembed');
    function twitter_oembed($a) {
    	$a['#http(s)?://(www\.)?twitter.com/.+?/status(es)?/.*#i'] = array( 'http://api.twitter.com/1/statuses/oembed.{format}', true);
    	return $a;
    }
    
    //distinto color segun estado de entrada
    function posts_status_color() {
    ?>
      <style>
      .status-draft { background: #FCE3F2 !important; }
      .status-pending { background: #87C5D6 !important; }
      .status-publish { /* por defecto */ }
      .status-future { background: #C6EBF5 !important; }
      .status-private { background: #F2D46F; }
      </style>
    <?php
    }
    add_action('admin_footer','posts_status_color');
Visualizando 15 respostas - 1 até 15 (de um total de 16)
  • Criador do tópico kraudio

    (@kraudio)

    Mover o Bar do Admin para o rodapé

    function stick_admin_bar_to_bottom_css() {
            echo "
            <style type='text/css'>
            html {
                    padding-bottom: 28px !important;
            }
    
            body {
                    margin-top: -28px;
            }
    
            #wpadminbar {
                    top: auto !important;
                    bottom: 0;
            }
    
            #wpadminbar .quicklinks .menupop ul {
                    bottom: 28px;
            }
            </style>
            ";
    }
    
    add_action('admin_head', 'stick_admin_bar_to_bottom_css');
    add_action('wp_head', 'stick_admin_bar_to_bottom_css');

    Fonte: wpbeginner

    Criador do tópico kraudio

    (@kraudio)

    Esconder a mensagem de atualização WordPress

    add_action('admin_menu','wphidenag');
    function wphidenag() {
    remove_action( 'admin_notices', 'update_nag', 3 );
    }

    Fonte: wpbeginner

    Criador do tópico kraudio

    (@kraudio)

    Resumo com apenas 100 palavras

    function minWord($content)
    {
    	global $post;
    	$content = $post->post_excerpt;
    	if (str_word_count($content) < 100 ) //set this to the minimum number of words
    	wp_die( __('Error: your post is below the minimum word count. It needs to be longer than 100 words.') );
    }
    add_action('publish_post', 'minWord');

    Fonte: wpbeginner

    Criador do tópico kraudio

    (@kraudio)

    Enable TinyMCE editor for post the_excerpt

    function tinymce_excerpt_js(){ ?>
    <script type="text/javascript">
    	jQuery(document).ready( tinymce_excerpt );
                function tinymce_excerpt() {
    		jQuery("#excerpt").addClass("mceEditor");
    		tinyMCE.execCommand("mceAddControl", false, "excerpt");
    	    }
    </script>
    <?php }
    add_action( 'admin_head-post.php', 'tinymce_excerpt_js');
    add_action( 'admin_head-post-new.php', 'tinymce_excerpt_js');
    function tinymce_css(){ ?>
    <style type='text/css'>
    	    #postexcerpt .inside{margin:0;padding:0;background:#fff;}
    	    #postexcerpt .inside p{padding:0px 0px 5px 10px;}
    	    #postexcerpt #excerpteditorcontainer { border-style: solid; padding: 0; }
    </style>
    <?php }
    add_action( 'admin_head-post.php', 'tinymce_css');
    add_action( 'admin_head-post-new.php', 'tinymce_css');

    Fonte: wpsnipp

    Criador do tópico kraudio

    (@kraudio)

    Adicionar filtro ao custom fields

    add_filter( 'parse_query', 'ba_admin_posts_filter' );
    add_action( 'restrict_manage_posts', 'ba_admin_posts_filter_restrict_manage_posts' );
    function ba_admin_posts_filter( $query )
    {
        global $pagenow;
        if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && $_GET['ADMIN_FILTER_FIELD_NAME'] != '') {
            $query->query_vars['meta_key'] = $_GET['ADMIN_FILTER_FIELD_NAME'];
        if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '')
            $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
        }
    }
    function ba_admin_posts_filter_restrict_manage_posts()
    {
        global $wpdb;
        $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
        $fields = $wpdb->get_results($sql, ARRAY_N);
    ?>
    <select name="ADMIN_FILTER_FIELD_NAME">
    <option value=""><?php _e('Filter By Custom Fields', 'baapf'); ?></option>
    <?php
        $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
        $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
        foreach ($fields as $field) {
            if (substr($field[0],0,1) != "_"){
            printf
                (
                    '<option value="%s"%s>%s</option>',
                    $field[0],
                    $field[0] == $current? ' selected="selected"':'',
                    $field[0]
                );
            }
        }
    ?>
    </select> <?php _e('Value:', 'baapf'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
    <?php
    }

    fonte: wpsnipp

    Criador do tópico kraudio

    (@kraudio)

    Restringir uploads por tipo de arquivo

    add_filter('upload_mimes','restrict_mime');
    function restrict_mime($mimes) {
    $mimes = array(
                    'jpg|jpeg|jpe' => 'image/jpeg',
                    'gif' => 'image/gif',
    );
    return $mimes;
    }

    fonte: wpsnipp

    Criador do tópico kraudio

    (@kraudio)

    Como remover links da barra de administração(topo) do Wp

    function remove_admin_bar_links() {
        global $wp_admin_bar;
        $wp_admin_bar->remove_menu('wp-logo');          // Remove the WordPress logo
        $wp_admin_bar->remove_menu('about');            // Remove the about WordPress link
        $wp_admin_bar->remove_menu('wporg');            // Remove the WordPress.org link
        $wp_admin_bar->remove_menu('documentation');    // Remove the WordPress documentation link
        $wp_admin_bar->remove_menu('support-forums');   // Remove the support forums link
        $wp_admin_bar->remove_menu('feedback');         // Remove the feedback link
        $wp_admin_bar->remove_menu('site-name');        // Remove the site name menu
        $wp_admin_bar->remove_menu('view-site');        // Remove the view site link
        $wp_admin_bar->remove_menu('updates');          // Remove the updates link
        $wp_admin_bar->remove_menu('comments');         // Remove the comments link
        $wp_admin_bar->remove_menu('new-content');      // Remove the content link
        $wp_admin_bar->remove_menu('w3tc');             // If you use w3 total cache remove the performance link
        $wp_admin_bar->remove_menu('my-account');       // Remove the user details tab
    }
    add_action( 'wp_before_admin_bar_render', 'remove_admin_bar_links' );

    Fonte: paulund

    Criador do tópico kraudio

    (@kraudio)

    Alterando nome dos itens do menu administrativo

    function change_post_menu_label() {
        global $menu;
        global $submenu;
        $menu[5][0] = 'Notícias';
        $submenu['edit.php'][5][0] = 'Notícias';
        $submenu['edit.php'][10][0] = 'Nova Notícia';
        $submenu['edit.php'][15][0] = 'Categoria'; // Change name for categories
        $submenu['edit.php'][16][0] = 'Tags'; // Change name for tags
        echo '';
    }
    
    function change_post_object_label() {
            global $wp_post_types;
            $labels = &$wp_post_types['post']->labels;
            $labels->name = 'Contacts';
            $labels->singular_name = 'Contact';
            $labels->add_new = 'Add Contact';
            $labels->add_new_item = 'Add Contact';
            $labels->edit_item = 'Edit Contacts';
            $labels->new_item = 'Contact';
            $labels->view_item = 'View Contact';
            $labels->search_items = 'Search Contacts';
            $labels->not_found = 'No Contacts found';
            $labels->not_found_in_trash = 'No Contacts found in Trash';
        }
        add_action( 'init', 'change_post_object_label' );
        add_action( 'admin_menu', 'change_post_menu_label' );
    Criador do tópico kraudio

    (@kraudio)

    Criador do tópico kraudio

    (@kraudio)

    Recente posts

    function my_recent_post()
     {
          global $post;
    
          $html = "";
    
          $my_query = new WP_Query( array(
               'post_type' => 'post',
               'posts_per_page' => 1
          ));
    
          if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
    
               $html .= "<h2>" . get_the_title() . "</h2>";
               $html .= "<p>" . get_the_excerpt() . "</p>";
               $html .= "<a href=\"" . get_permalink() . "\" class=\"button\">Read more</a>";
    
          endwhile; endif;
    
          return $html;
     }
     add_shortcode( 'recent', 'my_recent_post' );

    Shortcode: [recent]

    Fonte

    Criador do tópico kraudio

    (@kraudio)

    Restringir o upload de arquivos

    <?php
    /**
     * Plugin Name: Restrict mime types
     * Plugin URI:  http://wpengineer.com/?p=2369
     * Description: Restrict list of allowed mime types and file extensions.
     * Version:     1.0.0
     * License:     GPLv3
     * Author:      Frank Bültge
     * Author URI:  http://bueltge.de/
     */
     // This file is not called from WordPress. We don't like that.
    ! defined( 'ABSPATH' ) and exit;
    // If the function exists this file is called as upload_mimes.
    // We don't do anything then.
    if ( ! function_exists( 'fb_restrict_mime_types' ) ) {
    	add_filter( 'upload_mimes', 'fb_restrict_mime_types' );
    	/**
    	 * Retrun allowed mime types
    	 *
    	 * @see     function get_allowed_mime_types in wp-includes/functions.php
    	 * @param   array Array of mime types
    	 * @return  array Array of mime types keyed by the file extension regex corresponding to those types.
    	 */
    	function fb_restrict_mime_types( $mime_types ) {
    		$mime_types = array(
    			'pdf' => 'application/pdf',
    			'doc|docx' => 'application/msword',
    		);
    		return $mime_types;
    	}
    }
    // If the function exists this file is called as post-upload-ui.
    // We don't do anything then.
    if ( ! function_exists( 'fb_restrict_mime_types_hint' ) ) {
    	// add to wp
    	add_action( 'post-upload-ui', 'fb_restrict_mime_types_hint' );
    	/**
    	 * Get an Hint about the allowed mime types
    	 *
    	 * @return  void
    	 */
    	function fb_restrict_mime_types_hint() {
    		echo '<br />';
    		_e( 'Accepted MIME types: PDF, DOC/DOCX' );
    	}
    }

    Fonte: wpengineer.com

    Criador do tópico kraudio

    (@kraudio)

    Permissão assinante nos arquivos de midia

    <?php
    /*
    Plugin Name: Restrict Midia
    Version: 0.1
    */
    //Manage Your Media Only
    function mymo_parse_query_useronly( $wp_query ) {
        if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !
    == false ) {
            if ( !current_user_can( 'level_5' ) ) {
                global $current_user;
                $wp_query->set( 'author', $current_user->id );
            }
        }
    } 
    
    add_filter('parse_query', 'mymo_parse_query_useronly' );
    ?>

    Fonte: groups.google.com

    Criador do tópico kraudio

    (@kraudio)

    Substitua reticências por um permalink

    function replace_excerpt($content) {
           return str_replace('[...]',
                   '... <div class="more-link"><a href="'. get_permalink() .'">Continue Reading</a></div>',
                   $content
           );
    }
    add_filter('the_excerpt', 'replace_excerpt');

    Fonte: wprecipes.com

    Nota: Por favor, se o código for muito extenso, crie uma conta gratuita no pastebin.com e crie tópicos somente com o link para lá.

    Criador do tópico kraudio

    (@kraudio)

    Encurtar titulos

    No functions.php:

    function short_title($after = '', $length) {
    	$mytitle = get_the_title();
    	if ( strlen($mytitle) > $length ) {
    	$mytitle = substr($mytitle,0,$length);
    	echo $mytitle . $after;
    	} else {
    	echo $mytitle;
    	}
    }

    Em seu template:
    <?php short_title('...', 40); ?>

Visualizando 15 respostas - 1 até 15 (de um total de 16)
  • O tópico ‘[Plugin] Funções adicionais ao functions.php’ está fechado para novas respostas.