markdown 自定义主题创建的Wordpress提示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 自定义主题创建的Wordpress提示相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Class autoloader
 * @param  string $class fully qualified class name
 * @return void
 */
function plugins_autoloader($class)
{
    $prefix = 'Foo\\Bar\\';
    $base_dir = __DIR__ . '/plugins/';

    $len = strlen($prefix);

    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }



    // get the relative class name
    $relative_class = strtolower( substr($class, $len) );

    // First, separate the components of the incoming file.
    $file = explode( '\\', $relative_class );
    
    $last_part_post = count($file) - 1;
    // add class prefix to the file name by wp standart
    $file[ $last_part_post ] = 'class-' . $file[ $last_part_post ];
    $file = implode(DIRECTORY_SEPARATOR, $file);
    $file = str_replace('_', '-', $file);
    $file = $base_dir . $file . '.php';

    if (file_exists($file)) {
        require_once $file;
    } else {
        print $file;
    }
    return;
}

try {
    spl_autoload_register('\\plugins_autoloader');
} catch (\Exception $e) {
    print 'Something Wrong!';
}
# Usefool links, tips and examples with custom plugin development

#### Create custom plugins
+ [Writing a Plugin](https://codex.wordpress.org/Writing_a_Plugin)
+ [How To Include CSS and JavaScript Conditionally And Only When Needed By The Posts](http://beerpla.net/2010/01/13/wordpress-plugin-development-how-to-include-css-and-javascript-conditionally-and-only-when-needed-by-the-posts/)
+ [Keeping Plugins Clean: Using Activate, Deactivate and Uninstall Hooks](https://premium.wpmudev.org/blog/activate-deactivate-uninstall-hooks/)
+ [Avatar Manager for WordPress](https://github.com/inhausmakers/avatar-manager) - репозиторий плагина как пример кастомных полей и загрузки картинки.
+ [How to add a custom user field in WordPress](https://www.cssigniter.com/how-to-add-a-custom-user-field-in-wordpress/)
+ [Best Practices](https://developer.wordpress.org/plugins/plugin-basics/best-practices/)
+ [How to Write a WordPress Plugin](https://www.devlounge.net/extras/how-to-write-a-wordpress-plugin)
+ [The Right Way to Customize a WordPress Plugin](https://iandunn.name/2014/01/10/the-right-way-to-customize-a-wordpress-plugin/)
+ [Add Page Templates to WordPress with a Plugin](https://www.wpexplorer.com/wordpress-page-templates-plugin/)
+ [How To Add Custom Rewrite Rules In WordPress](http://clivern.com/how-to-add-custom-rewrite-rules-in-wordpress/)
+ [Theme Handbook](https://developer.wordpress.org/themes/)
+ [THE BEGINNER’S GUIDE TO CREATING A THEME WITH UNDERSCORES](https://torquemag.io/2017/08/beginners-guide-to-creating-a-theme-underscores/)
+ [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/)
+ [Guttenberg - new editor, FAQ](https://wordpress.org/gutenberg/handbook/designers-developers/faq/)
+ [Как вывести количество просмотров записи на WordPress](https://izuchatel.com/kak-vyvesti-kolichestvo-prosmotrov-zapisej-na-wordpress/)
+ [WordPress Child Theme Complete Guide](https://www.wpexplorer.com/wordpress-child-theme-guide/)
+ [How to Add a Custom Author Profile Page to Your WordPress](https://www.wpbeginner.com/wp-themes/how-to-add-a-custom-author-profile-page-to-your-wordpress/)
+ [The WordPress Coding Standards](https://code.tutsplus.com/series/the-wordpress-coding-standards--cms-820)
+ [How To Redirect Default WordPress Login Into A Custom Login Page](https://www.inkthemes.com/how-to-redirecting-wordpress-default-login-into-a-custom-login-page/)
+ [Customizing the WordPress Comment Form](https://premium.wpmudev.org/blog/customizing-wordpress-comment-form/)
+ [Настройка комментариев в WordPress - функциональность и внешний вид](https://php-academy.kiev.ua/blog/customizing-comments-in-wordpress--functionality-and-appearance)
+ [How to Display Author’s Twitter and Facebook on the Profile Page](https://www.wpbeginner.com/wp-tutorials/how-to-display-authors-twitter-and-facebook-on-the-profile-page/)
+ [How to Search WordPress Users by Profile Field Value](https://www.wpexpertdeveloper.com/search-wordpress-users-by-profile-field-value/)
+ [Пример вывода похожих постов](https://misha.blog/wordpress/pohozhie-zapisi.html)
+ [Что такое WP-CLI? Руководство для новичков](https://code.tutsplus.com/ru/tutorials/what-is-wp-cli-a-beginners-guide--cms-28649)

### Custom login and register
+ [Custom login page](https://websiteguider.com/create-a-custom-login-page-for-wordpress-without-plugin/)
+ [Customizing the Login Form](https://codex.wordpress.org/Customizing_the_Login_Form) - article in codex wp.
+ [How to programatically change username (user_login)?](https://wordpress.stackexchange.com/questions/103504/how-to-programatically-change-username-user-login)

**Example custom login page**

		<?php
		/**
		 * Template Name: Sign In
		 */
		get_header();


		if($_POST)
		{

		    global $wpdb;

		//We shall SQL escape all inputs
		    $username = $wpdb->escape($_REQUEST['username']);
		    $password = $wpdb->escape($_REQUEST['password']);
		    $remember = $wpdb->escape($_REQUEST['rememberme']);

		    if($remember) $remember = "true";
		    else $remember = "false";

		    $login_data = array();
		    $login_data['user_login'] = $username;
		    $login_data['user_password'] = $password;
		    $login_data['remember'] = $remember;

		    $user_verify = wp_signon( $login_data, false );

		    if ( is_wp_error($user_verify) )
		    {
			echo '<span class="mine">Invlaid Login Details</span>';
		    } else
		    {
			echo "<script type='text/javascript'>window.location.href='". home_url() ."'</script>";
			exit();
		    }

		}
		else {
		    ?>

		    <form id="wp_login_form" action="" method="post">
			<label for="tab-1" class="tab">Sign In</label><br>

			<label class="my-username">Username</label><br>
			<input type="text" name="username" class="text" value=""><br>
			<label class="my-password">Password</label><br>

			<input type="password" name="password" class="text" value=""> <br>
			<label>
			    <input class="myremember" name="rememberme" type="checkbox" value="forever"><span
				class="hey">Remember me</span></label>
			<br><br>
			<input type="submit" id="submitbtn" name="submit" value="Login">
		    </form>
		    <?php
		}
		get_sidebar();
		get_footer();
		 ?>

+ [Disable WordPress dashboard for subscribers](https://www.stewright.me/2016/03/disable-wordpress-dashboard-subscribers/)

**Custom rewrite rules**

	function custom_rewrite_rule() {
	    add_rewrite_rule('^profile/([0-9]+)/?$', 'index.php?page_id=9&user_id=$matches[1]', 'top');
	}
	add_action('init', 'custom_rewrite_rule', 10, 0);

	function custom_rewrite_tag() {
	    add_rewrite_tag('%user_id%', '([^&]+)');
	}
	add_action('init', 'custom_rewrite_tag', 10, 0);

### PHP OOP with Wordpress
+ [Example Implementations of PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md#class-example)
+ [Class Autoloader for WordPress theme](https://gist.github.com/iCaspar/539e620a242ae55ded91)
+ [Simple Autoloader for WordPress](https://github.com/tommcfarlin/simple-autoloader-for-wordpress/)
+ [Object-Oriented Autoloading in WordPress](https://code.tutsplus.com/series/object-oriented-autoloading-in-wordpress--cms-1101) - цикл статей на сайте code.tutsplus.com.
+ [Namespaces and Autoloading in WordPress](https://tommcfarlin.com/namespaces-and-autoloading-2017/)
+ [Using namespaces and autoloading with Composer in WordPress plugins](https://medium.com/@spencerfeng/using-namespaces-and-autoloading-with-composer-in-wordpress-plugins-72ea36d82369)

### Static front page
+ [Designing a Custom Home Page for Your WordPress Website](https://www.sitepoint.com/designing-a-custom-home-page-for-your-wordpress-website/) - about Customizer and Kirki toolkit for customization wordpress theme.
+ [Creating a Static Front Page](https://codex.wordpress.org/Creating_a_Static_Front_Page) - официальное руководство.

		# Custom loop on static front page
		$paged = (get_query_var('page')) ? get_query_var('page') : 1;
		$args=array('category_name'=>'portfolio','posts_per_page'=>4,'paged'=>$paged);
		query_posts($args);
		if (have_posts()) : while (have_posts()) : the_post();
		/...
		endwhile;
		posts_nav_link();
		wp_reset_query();
		endif;

**Example custom wp_query with pagination and offset**

	$per_page     = 1;
	$offset_start = 1;
	$offset       = ( $current_page - 1 ) * $per_page + $offset_start;
	$current_page = max( get_query_var( 'page' ), 1 ); // page or paged in other case
	$args = array(
		'posts_per_page' => 1,
		'paged'          => $current_page,
		'post__not_in'   => get_option( 'sticky_posts' ), // exclude "sticky posts"
		'orderby'        => 'post_date',
		'order'          => 'DESC',
		'offset'         => $offset
	);
	$main_articles = new WP_Query( $args );

	// Manually count the number of pages, because we used a custom OFFSET (i.e.
	// other than 0), so we can't simply use $post_list->max_num_pages or even
	// $post_list->found_posts without extra work/calculation.
	$total_rows    = max( 0, $main_articles->found_posts - $offset_start );
	$total_pages   = ceil( $total_rows / $per_page );
	
	if ( $main_articles->have_posts() ):
		/* Start the Loop */
		while ( $main_articles->have_posts() ) :
			$main_articles->the_post();
			// output articles
		endwhile; 
		// output pagination
		echo paginate_links( array(
				'total'     => $total_pages,
				'current'   => $current_page,
				'type'      => 'plain',
				'end_size'  => 10,
				'mid_size'  => 1,
				'prev_next' => true,
				'prev_text' => "&lt;",
				'next_text' => "&gt;",
			) );
		wp_reset_postdata();
	endif;

**Example of custom wp_query order by meta value**

	# Display posts with ‘Product’ type ordered by ‘Price’ custom field:
	$args = array(
	    'post_type' => 'product',
	    'orderby'   => 'meta_value_num',
	    'meta_key'  => 'price',
	);
	$query = new WP_Query( $args );

### Admin dashboard customization
+ [HOW TO CUSTOMIZE THE WORDPRESS BACKEND (FOR CLIENTS AND YOURSELF)](https://torquemag.io/2016/08/customize-wordpress-backend-clients/)
+ [How to Customize Your WordPress Admin Dashboard](https://www.wpexplorer.com/customize-wordpress-admin-dashboard/)
+ [How To Create A WordPress Custom Dashboard Page](https://www.wpexplorer.com/how-to-wordpress-custom-dashboard/) - создание собственной страницы в административной панели со своими стилями, обработчиками и настройками.
+ [Administration Menus](https://codex.wordpress.org/Administration_Menus) - about custom menus and dashboard pages, funciton descriptions in codex. 
+ [A Quick and Easy Guide To Creating WordPress Admin Pages](https://premium.wpmudev.org/blog/creating-wordpress-admin-pages/)
+ [Plugin API/Action Reference](https://codex.wordpress.org/Plugin_API/Action_Reference)

**Custom Admin footer**

    function wpexplorer_remove_footer_admin () {
      echo '<span id="footer-thankyou">Built with love by <a href="http://www.wpexplorer.com/" target="_blank">WPExplorer</a></span>';
    }
    add_filter( 'admin_footer_text', 'wpexplorer_remove_footer_admin' );
 

### Thumbnails

**Get alt of the attachment image**

    $thumbnail_id = get_post_thumbnail_id( $post->ID );
	$alt = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true );

+ [How to generate thumbnails when needed only?](https://stackoverflow.com/questions/8610747/trying-to-generate-wordpress-thumbnails-programmatically)
 
### Plugins
+ [Classic Editor for WP](https://wordpress.org/plugins/classic-editor/)

### Cache
+ [W3 Total Cache](https://easyengine.io/wordpress-nginx/tutorials/single-site/w3-total-cache)
+ [9 Tips for Improving WordPress Performance](https://www.nginx.com/blog/9-tips-for-improving-wordpress-performance-with-nginx/#fastcgi)
+ [Use Redis for wordpress](https://www.digitalocean.com/community/tutorials/how-to-configure-redis-caching-to-speed-up-wordpress-on-ubuntu-14-04)
+ [Using Redis Object Cache to Speed Up Your WordPress Installation](https://scalegrid.io/blog/using-redis-object-cache-to-speed-up-your-wordpress-installation/)
+ [How to Set Up a Redis Server](https://www.digitalocean.com/community/tutorials/how-to-set-up-a-redis-server-as-a-session-handler-for-php-on-ubuntu-14-04)
+ [НАСТРОЙКА КЭШИРОВАНИЯ REDIS ДЛЯ УСКОРЕНИЯ WORDPRESS](https://www.8host.com/blog/nastrojka-keshirovaniya-redis-dlya-uskoreniya-wordpress/)

### Custom Widgets
+ [Widgets API](https://codex.wordpress.org/Widgets_API)
+ [How to Create a Custom WordPress Widget](https://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/)

		class My_Widget extends WP_Widget {
			/**
			 * Sets up the widgets name etc
			 */
			public function __construct() {
				$widget_ops = array( 
					'classname' => 'my_widget',
					'description' => 'My Widget is awesome',
				);
				parent::__construct( 'my_widget', 'My Widget', $widget_ops );
			}

			/**
			 * Outputs the content of the widget
			 *
			 * @param array $args
			 * @param array $instance
			 */
			public function widget( $args, $instance ) {
				// outputs the content of the widget
			}

			/**
			 * Outputs the options form on admin
			 *
			 * @param array $instance The widget options
			 */
			public function form( $instance ) {
				// outputs the options form on admin
			}

			/**
			 * Processing widget options on save
			 *
			 * @param array $new_instance The new options
			 * @param array $old_instance The previous options
			 *
			 * @return array
			 */
			public function update( $new_instance, $old_instance ) {
				// processes widget options to be saved
			}
		}

### Search form
+ [get_search_form](https://wp-kama.ru/function/get_search_form)

### Comments form
+ [Customizing Comments in WordPress - Functionality and Appearance](https://code.tutsplus.com/articles/customizing-comments-in-wordpress-functionality-and-appearance--wp-26128)
+ [Простейшая функция склонения слов после числительных](http://dimox.name/plural-form-of-nouns/)

**Example function search by title only**

		function __search_by_title_only( $search, \WP_Query $wp_query )
		{
		    global $wpdb;
		    if(empty($search)) {
			return $search; // skip processing - no search term in query
		    }
		    $q = $wp_query->query_vars;
		    $n = !empty($q['exact']) ? '' : '%';
		    $search = '';
		    $searchand = '';
		    foreach ((array)$q['search_terms'] as $term) {
			$term = esc_sql($wpdb->esc_like($term));
			$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
			$searchand = ' AND ';
		    }
		    if (!empty($search)) {
			$search = " AND ({$search}) ";
			if (!is_user_logged_in())
			    $search .= " AND ($wpdb->posts.post_password = '') ";
		    }
		    return $search;
		}
		add_filter('posts_search', '__search_by_title_only', 500, 2);
		
#### Like and dislike buttons 
+ [How to create WordPress like button without login/plugin](http://atiblog.com/wordpress-like-button-post-page/)

#### Create tables
+ [Creating or Updating the Table](https://codex.wordpress.org/Creating_Tables_with_Plugins#Creating_or_Updating_the_Table)
+ [Creating a Custom Table with PHP in WordPress](https://deliciousbrains.com/creating-custom-table-php-wordpress/)
+ [Creating Custom Database Tables for Your WordPress Plugins](https://premium.wpmudev.org/blog/creating-database-tables-for-plugins/)

### Upload images

**Add multipart/form-data for user profile to upload images.**

	add_action('user_edit_form_tag', 'make_form_accept_uploads');
	function make_form_accept_uploads() { echo ' enctype="multipart/form-data"'; }
	
+ [media handle upload](https://codex.wordpress.org/Function_Reference/media_handle_upload) - function for upload media files in wp.

**The code to save the attachment**

		<?php
		// Check that the nonce is valid, and the user can edit this post.
		if ( 
			isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] ) 
			&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
			&& current_user_can( 'edit_post', $_POST['post_id'] )
		) {
			// The nonce was valid and the user has the capabilities, it is safe to continue.

			// These files need to be included as dependencies when on the front end.
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
			require_once( ABSPATH . 'wp-admin/includes/media.php' );

			// Let WordPress handle the upload.
			// Remember, 'my_image_upload' is the name of our file input in our form above.
			$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );

			if ( is_wp_error( $attachment_id ) ) {
				// There was an error uploading the image.
			} else {
				// The image was uploaded successfully!
			}

		} else {

			// The security check failed, maybe show the user an error.
		}

+ [Programmatically Resize Images in WordPress](https://tommcfarlin.com/programmatically-resize-images/)
+ [PHP wp_check_filetype](https://hotexamples.com/ru/examples/-/-/wp_check_filetype/php-wp_check_filetype-function-examples.html)
+ [How to Upload a File With WordPress’ Secret Native Functions](https://premium.wpmudev.org/blog/upload-file-functions/)


### Отправка писем и подтверждение регистрации
+ [HOW TO AUTOMATICALLY SEND A WELCOME EMAIL TO NEW USER WHEN THEY SIGN UP FOR THEIR ACCOUNT IN WORDPRESS PROGRAMMATICALLY?](https://poanchen.github.io/blog/2016/10/17/how-to-automatically-send-welcome-email-to-user-when-they-sign-up-in-wp)
+ [CUSTOM WORDPRESS WELCOME EMAILS](https://viastudio.com/custom-wordpress-welcome-emails/)
+ [How to Use SMTP Server to Send WordPress Emails](https://www.wpbeginner.com/wp-tutorials/how-to-use-smtp-server-to-send-wordpress-emails/)
+ [Easy SMTP email settings for WordPress](https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/)

**Manual user Approve:**

+ [Eonet Manual User Approve](https://wordpress.org/plugins/eonet-manual-user-approve/)
+ [WP Approve User](https://wordpress.org/plugins/wp-approve-user/)

		add_action( 'user_register', 'so27450945_user_register', 10, 1 );
		function so27450945_user_register( $user_id )
		{
		    $user = get_user_by( 'id', $user_id );

		    $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );

		    $message  = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n";
		    $message .= sprintf( __( 'Username: %s'), $user->user_login ) . "\r\n\r\n";
		    $message .= sprintf( __( 'E-mail: %s'), $user->user_email ) . "\r\n";

		    @wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] New User Registration' ), $blogname ), $message);
		}

+ [Build a Custom WordPress User Flow — Part 3: Password Reset](https://code.tutsplus.com/tutorials/build-a-custom-wordpress-user-flow-part-3-password-reset--cms-23811)

`retrieve_password()` - Handles sending password retrieval email to user.

### Custom images types

**Add webp type:**

	//enable upload for webp image files.
	function webp_upload_mimes($existing_mimes) {
	    $existing_mimes['webp'] = 'image/webp';
	    return $existing_mimes;
	}
	add_filter('mime_types', 'webp_upload_mimes');

	//enable preview / thumbnail for webp image files.
	function webp_is_displayable($result, $path) {
	    if ($result === false) {
		$displayable_image_types = array( IMAGETYPE_WEBP );
		$info = @getimagesize( $path );

		if (empty($info)) {
		    $result = false;
		} elseif (!in_array($info[2], $displayable_image_types)) {
		    $result = false;
		} else {
		    $result = true;
		}
	    }

	    return $result;
	}
	add_filter('file_is_displayable_image', 'webp_is_displayable', 10, 2);
# Usefool command, tips and links for wp cli

    # Add posts with dummy content for development:
    wp post generate --count=10
    curl http://loripsum.net/api/4 | wp post generate --post_content --count=10
    
    # lists constants and globals as defined in your current wp-config.php file:
    wp config get
    # simply displays a path to the current wp-config.php file:
    wp config path
    # list db tables and their sizes:
    wp db size --tables
    # update wordpress:
    wp core update
    # plugins
    wp plugin deactivate plugin-name-example
    wp plugin delete plugin-name-example
    wp plugin update --all
    # check the status of the plugins currently on your site:
    wp plugin status
    # Reset user password:
    wp user update adminuser@example.com --user_pass=new-password-example
    # operations with db:
    wp db optimize
    wp db repair
    wp db query "SELECT * FROM wp_options"
    # comments:
    wp comment delete $(wp comment list --status=spam --format=ids)
    # media:
    wp media regenerate
    

    
    
+ [10+ WP-CLI Tricks to Manage Your WordPress Site (Updated for WP-CLI 1.2.0)](https://www.codeinwp.com/blog/wp-cli/)

以上是关于markdown 自定义主题创建的Wordpress提示的主要内容,如果未能解决你的问题,请参考以下文章

php 儿童主题的Wordpres功能

自定义包的 Composer 安装路径

使用highlightjs_markdown编辑器自定义博客园代码高亮

利用css 设计markdown 主题

分类层次结构不起作用 [Wordpress]

如何为 QtCreator 创建自定义主题