Advertisement
terorama

Wordpress Snippets 8

Dec 13th, 2013
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 33.47 KB | None | 0 0
  1. <?php
  2. var $public_query_vars = array(
  3.           'm', 'p', 'posts',
  4.           'w', 'cat',
  5.           'withcomments', 'withoutcomments',
  6.           's', 'search', 'exact',          
  7.           'sentence', 'calendar', 'page',
  8.           'paged',
  9.           'more',
  10.           'tb', 'pb',
  11.           'author', 'order', 'orderby',
  12.           'year', 'monthnum', 'day',
  13.           'hour','minute', 'second',
  14.           'name', 'category_name',
  15.           'tag', 'feed',
  16.           'author_name', 'static',
  17.           'pagename', 'page_id', 'error',
  18.           'comments_popup',
  19.           'attachment', 'attachment_id',
  20.           'subpost', 'subpost_id',
  21.           'preview', 'robots',
  22.           'taxonomy', 'term', 'cpage',          
  23.           'post_type');
  24. //--------------------------------------------------------------------
  25. ?>
  26.  
  27. http://dmkim1979.ru/?p=37                   //  single post
  28. http://dmkim1979.ru/?page_id=40             //  single page
  29. http://dmkim1979.ru/?paged=4                //  page 4 of 10 in archive
  30.  
  31. http://dmkim1979.ru/?m=201310               //  10-2013 archive
  32. http://dmkim1979.ru/?monthnum=10            //  month 10 archive
  33. http://dmkim1979.ru/?year=2013              //  year archive
  34. http://dmkim1979.ru/?day=12                 //  daily archive (current year and month)
  35.  
  36. http://dmkim1979.ru/?cat=3                  //  category archive
  37. http://dmkim1979.ru/?tag=tag4               //  tag archive
  38. http://dmkim1979.ru/?rating=rating4         //  custom taxonomy archive
  39. http://dmkim1979.ru/?post_type=tickets      //  custom post type archive
  40. http://dmkim1979.ru/?author=1               //  author archive by id
  41. http://dmkim1979.ru/?author_name=admin      //  author archive by name
  42. http://dmkim1979.ru/?s=uuu                  //  search archive
  43. http://dmkim1979.ru/?error=404              //  page not found
  44. http://dmkim1979.ru/?feed=rss2              //  output feed
  45.  
  46. //--------------------------------------------------------------------
  47.  
  48.  'posts', 'w', 'withcomments', 'withoutcomments', 'search', 'exact',          
  49.  'sentence', 'calendar', 'page', 'more', 'tb', 'pb',
  50.  'order', 'orderby',
  51.  'hour','minute', 'second',
  52.  'name', 'category_name',      
  53.  'static',
  54.  'pagename',
  55.  'comments_popup',
  56.  'attachment', 'attachment_id',
  57.  'subpost', 'subpost_id',
  58.  'preview', 'robots',
  59.  'taxonomy', 'term', 'cpage'
  60. //--------------------------------------------------------------------
  61.  
  62. <?php
  63. //-------------------------------------------------------------------
  64. //                      print rewrite rules
  65. //-------------------------------------------------------------------
  66. ?>
  67. <div><code>  
  68. <?php  
  69. global $wp_rewrite;  
  70. print_r($wp_rewrite->rules);  
  71. ?>  
  72. </code></div>  
  73.  
  74. <?php
  75. //-------------------------------------------------------------------
  76. //                 add custom rewrite rules
  77. //-------------------------------------------------------------------
  78.  
  79. add_action( 'init', 'add_author_rules' );
  80.  
  81. //----------------------------------------  
  82. function add_author_rules() {  
  83. //----------------------------------------
  84.     add_rewrite_rule(  
  85.         "writer/([^/]+)/?",  
  86.         "index.php?author_name=$matches[1]",  
  87.         "top");  
  88.      
  89.     add_rewrite_rule(  
  90.     "writer/([^/]+)/page/?([0-9]{1,})/?",  
  91.     "index.php?author_name=$matches[1]&paged=$matches[2]",  
  92.     "top");  
  93.      
  94.     add_rewrite_rule(  
  95.     "writer/([^/]+)/(feed|rdf|rss|rss2|atom)/?",  
  96.     "index.php?author_name=$matches[1]&feed=$matches[2]",  
  97.     "top");  
  98.          
  99.     add_rewrite_rule(  
  100.     "writer/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?",  
  101.     "index.php?author_name=$matches[1]&feed=$matches[2]",  
  102.     "top");  
  103. }  
  104.  
  105. //----------------------------------------
  106. function generate_author_rewrite_rules() {
  107. //----------------------------------------  
  108.  
  109.   global $wp_rewrite;  
  110.  
  111.   $new_rules = array(  
  112.     "writer/([^/]+)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1)  
  113.   );  
  114.  
  115.   $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;  
  116. }  
  117. //----------------------------------------
  118. function generate_author_rewrite_rules() {
  119. //----------------------------------------
  120.   global $wp_rewrite;  
  121.   $new_rules = array(  
  122.     "writer/([^/]+)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1),
  123.  
  124.     "writer/([^/]+)/page/?([0-9]{1,})/?" => "index.php?author_name=".$wp_rewrite->preg_index(1).
  125.     "&paged=".$wp_rewrite->preg_index(2),
  126.  
  127.     "writer/([^/]+)/(feed|rdf|rss|rss2|atom)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1).
  128.     "&feed=".$wp_rewrite->preg_index(2),
  129.  
  130.     "writer/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?" => "index.php?author_name=".
  131.     $wp_rewrite->preg_index(1)."&feed=".$wp_rewrite->preg_index(2)  
  132.   );  
  133.  
  134.   $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;  
  135. }  
  136. ?>
  137.  
  138. <?php
  139. //-------------------------------------------------------------------
  140. //                generate custom  mod-rewrite rules
  141. //-------------------------------------------------------------------
  142.  
  143. add_action('generate_rewrite_rules',
  144.                                     'themes_dir_add_rewrites');  
  145.  
  146. //----------------------------------------  
  147. function themes_dir_add_rewrites() {  
  148. //----------------------------------------
  149.   $theme_name = next(explode('/themes/', get_stylesheet_directory()));  
  150.  
  151.   global $wp_rewrite;  
  152.  
  153.   $new_non_wp_rules = array(  
  154.  
  155.     'css/(.*)'       => 'wp-content/themes/'. $theme_name . '/css/$1',  
  156.     'js/(.*)'        => 'wp-content/themes/'. $theme_name . '/js/$1',
  157.  
  158.     'images/wordpress-urls-rewrite/(.*)'    =>
  159.             'wp-content/themes/'. $theme_name . '/images/wordpress-urls-rewrite/$1',  
  160.   );  
  161.   $wp_rewrite->non_wp_rules += $new_non_wp_rules;  
  162. }  
  163. ?>
  164.  
  165. <?php
  166. //-------------------------------------------------------------------
  167. //        add custom post type to taxonomy archive
  168. //-------------------------------------------------------------------
  169.  
  170. //    Inside archive template:
  171.  
  172. $taxonomies_to_match = array('the_room','the_system','the_style');
  173.  
  174. if(is_tax($taxonomies_to_match)) {
  175.   global $wp_query;
  176.   query_posts(array_merge($wp_query->query_vars,array('post_type' => 'the_case_study'));
  177. }
  178.  
  179. //   Action Hook Method:
  180.  
  181. //----------------------------------------
  182. add_action('pre_get_posts','my_post_filter');
  183. //----------------------------------------
  184. function my_post_filter($query) {
  185. //----------------------------------------
  186.   $taxonomies_to_match = array('the_room','the_system','the_style');
  187.   if(is_tax($taxonomies_to_match)) {
  188.     $query->set('post_type','the_post_type_you_want');
  189.   }
  190. }
  191. ?>
  192.  
  193. <?php
  194. //-------------------------------------------------------------------
  195. //             add custom rewrite rules
  196. //-------------------------------------------------------------------
  197. add_action( 'init', 'wpse_100386_rewrites' );
  198.  
  199. //----------------------------------------
  200. function wpse_100386_rewrites() {
  201. //----------------------------------------
  202.     add_rewrite_rule( 'case-studies/room/([^/]+)/?',
  203.                       'index.php?the_room=$matches[1]&post_type=the_case_study', 'top' );
  204.  
  205.     add_rewrite_rule( 'videos/room/([^/]+)/?',
  206.                       'index.php?the_room=$matches[1]&post_type=the_video', 'top' );
  207. }
  208. ?>
  209.  
  210. <?php
  211. //-------------------------------------------------------------------
  212. //                      add cutom taxonomy
  213. //-------------------------------------------------------------------
  214.  # -*- coding: utf-8 -*-
  215. /*
  216. Plugin Name: Custom Taxonomy Quote Author
  217. Plugin URI:  https://gist.github.com/996608
  218. Description: Creates a custom taxonomy <code>Quote Author</code> with an URI <code>/qa/author-name/</code>
  219. Version:     1.0
  220. Required:    3.1
  221. Author:      Thomas Scholz
  222. Author URI:  http://toscho.de
  223. License:     GPL
  224. */
  225. ! defined( 'ABSPATH' ) and exit;
  226. //----------------------------------------
  227. add_action( 'after_setup_theme', 'register_quote_author' );
  228.  
  229. //----------------------------------------
  230. register_activation_hook(   __FILE__, 'qua_flush' );
  231. register_deactivation_hook( __FILE__, 'qua_flush' );
  232. //----------------------------------------
  233. /**
  234.  * Registers the taxonomy 'Quote Author'.
  235.  *
  236.  * To list the authors with links in your theme use
  237.  * @link http://codex.wordpress.org/Function_Reference/get_the_term_list
  238.  * <code>print get_the_term_list( get_the_ID(), 'quoteauthor' );</code>
  239.  *
  240.  * @link http://codex.wordpress.org/Function_Reference/register_taxonomy
  241.  * @return void
  242.  */
  243. //----------------------------------------
  244. function register_quote_author()
  245. {
  246.     register_taxonomy(
  247.         // Internal name
  248.         'quoteauthor'
  249.         // Post types the taxonomy applies to.
  250.         // The attachment field is not very nice, just a simple input field.
  251.         // You may tweak that.
  252.     ,   array ( 'post', 'attachment' )
  253.         // Visible labels
  254.     ,   array (
  255.         'labels'            => array (
  256.             'name'                       => 'Quote Authors'
  257.         ,   'menu_name'                  => 'Quote Authors'
  258.         ,   'singular_name'              => 'Quote Author'
  259.         ,   'search_items'               => 'Search Quote Authors'
  260.         ,   'popular_items'              => 'Popular Quote Authors'
  261.         ,   'all_items'                  => 'All Quote Authors'
  262.         ,   'edit_item'                  => 'Edit Quote Author'
  263.         ,   'update_item'                => 'Update Quote Author'
  264.         ,   'add_new_item'               => 'Add Quote Author'
  265.         ,   'new_item_name'              => 'New name for Quote Author'
  266.         ,   'separate_items_with_commas' => 'Separate Quote Authors by comma'
  267.         ,   'add_or_remove_items'        => 'Add or remove Quote Authors'
  268.         ,   'choose_from_most_used'      => 'Choose from most quoted authors'
  269.         )
  270.         // Most important parameter. :)
  271.     ,   'public'            => TRUE
  272.         // Available in custom menus.
  273.     ,   'show_in_nav_menus' => TRUE
  274.         // Standard box.
  275.     ,   'show_ui'           => TRUE
  276.         // Clickable list of popular authors.
  277.     ,   'show_tagcloud'     => TRUE
  278.         // URI
  279.     ,   'rewrite'           => array (
  280.             'slug' => 'qa'
  281.         )
  282.         // If you want to use WP_Query.
  283.     ,   'query_var'         => 'qa'
  284.     )
  285.     );
  286. }
  287. //----------------------------------------
  288. /**
  289.  * Tells WordPress to rebuild the rewrite rules to include our custom URIS.
  290.  *
  291.  * @return void
  292.  */
  293. //----------------------------------------
  294. function qua_flush()
  295. //----------------------------------------
  296. {
  297.     // The current instance of the class WP_Rewrite.
  298.     global $wp_rewrite;
  299.     $wp_rewrite->flush_rules();
  300. }
  301. ?>
  302.  
  303. <?php
  304. //-------------------------------------------------------------------
  305. //        generate rewrite rules for custom post type
  306. //-------------------------------------------------------------------
  307.  
  308. /**
  309.  * Custom post type date archives
  310.  */
  311.  
  312. /**
  313.  * Custom post type specific rewrite rules
  314.  * @return wp_rewrite             Rewrite rules handled by Wordpress
  315.  */
  316. //----------------------------------------
  317. function cpt_rewrite_rules($wp_rewrite) {
  318. //----------------------------------------
  319.  
  320.     $rules = cpt_generate_date_archives('news', $wp_rewrite);
  321.     $wp_rewrite->rules = $rules + $wp_rewrite->rules;
  322.     return $wp_rewrite;
  323. }
  324. //----------------------------------------
  325. add_action('generate_rewrite_rules', 'cpt_rewrite_rules');
  326.  
  327. /**
  328.  * Generate date archive rewrite rules for a given custom post type
  329.  * @param  string $cpt        slug of the custom post type
  330.  * @return rules              returns a set of rewrite rules for Wordpress to handle
  331.  */
  332. //------------------------------------------------
  333. function cpt_generate_date_archives($cpt, $wp_rewrite) {
  334. //------------------------------------------------
  335.     $rules = array();
  336.  
  337.     $post_type = get_post_type_object($cpt);
  338.     $slug_archive = $post_type->has_archive;
  339.     if ($slug_archive === false) return $rules;
  340.     if ($slug_archive === true) {
  341.         $slug_archive = $post_type->name;
  342.     }
  343.  
  344.     $dates = array(
  345.         array(
  346.             'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
  347.             'vars' => array('year', 'monthnum', 'day')),
  348.         array(
  349.             'rule' => "([0-9]{4})/([0-9]{1,2})",
  350.             'vars' => array('year', 'monthnum')),
  351.         array(
  352.             'rule' => "([0-9]{4})",
  353.             'vars' => array('year'))
  354.         );
  355.  
  356.     foreach ($dates as $data) {
  357.         $query = 'index.php?post_type='.$cpt;
  358.         $rule = $slug_archive.'/'.$data['rule'];
  359.  
  360.         $i = 1;
  361.         foreach ($data['vars'] as $var) {
  362.             $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
  363.             $i++;
  364.         }
  365.  
  366.         $rules[$rule."/?$"] = $query;
  367.         $rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
  368.         $rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
  369.         $rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
  370.     }
  371.     return $rules;
  372. }
  373.  
  374. ?>
  375.  
  376. <?php
  377. //-------------------------------------------------------------------
  378. //        Get a montlhy archive list for a custom post type
  379. //-------------------------------------------------------------------
  380. /**
  381.  * Get a montlhy archive list for a custom post type
  382.  * @param  string  $cpt  Slug of the custom post type
  383.  * @param  boolean $echo Whether to echo the output
  384.  * @return array         Return the output as an array to be parsed on the template level
  385.  */
  386. //------------------------------------------------
  387. function get_cpt_archives( $cpt, $echo = false )
  388. //------------------------------------------------
  389. {
  390.     global $wpdb;
  391.     $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts
  392.                  WHERE
  393.                    post_type = %s AND
  394.                    post_status = 'publish'
  395.  
  396.                        GROUP BY YEAR(wp_posts.post_date),
  397.                        MONTH(wp_posts.post_date)
  398.  
  399.                             ORDER BY wp_posts.post_date DESC", $cpt);
  400.  
  401.     $results = $wpdb->get_results($sql);
  402.  
  403.     if ( $results )
  404.     {
  405.         $archive = array();
  406.         foreach ($results as $r)
  407.         {
  408.             $year = date('Y', strtotime( $r->post_date ) );
  409.             $month = date('F', strtotime( $r->post_date ) );
  410.             $month_num = date('m', strtotime( $r->post_date ) );
  411.             $link = get_bloginfo('siteurl') . '/' . $cpt . '/' . $year . '/' . $month_num;
  412.             $this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
  413.             array_push( $archive, $this_archive );
  414.         }
  415.  
  416.         if( !$echo )
  417.             return $archive;
  418.         foreach( $archive as $a )
  419.         {
  420.             echo '<li><a href="' . $a['link'] . '">' . $a['month'] . ' ' . $a['year'] . '</a></li>';
  421.         }
  422.     }
  423.     return false;
  424. }
  425. ?>
  426.  
  427. To use this function just supply the slug of the custom post type, ie: get_cpt_archives( 'news' ).
  428. This will return an array of unique Year/Dates/Links, ie:
  429.  
  430. Array
  431. (
  432.     [0] => Array
  433.         (
  434.             [month] => February
  435.             [year] => 2013
  436.             [link] => http://yoursite.com/news/2013/02
  437.         )
  438.  
  439.     [1] => Array
  440.         (
  441.             [month] => January
  442.             [year] => 2013
  443.             [link] => http://yoursite.com/news/2013/01
  444.         )
  445.  
  446. )
  447.  
  448. <?php
  449. //-------------------------------------------------------------------
  450. //            add custom rewrite rules via tag
  451. //-------------------------------------------------------------------
  452.  
  453. function add_places_rewrite_tags() {
  454. //------------------------------------
  455.     add_rewrite_tag('%action%','([^&]+)');
  456. }
  457. //------------------------------------
  458. add_action( 'init', 'add_places_rewrite_tags' );
  459.  
  460. //  First add the rewrite tag action (action=xxxx)
  461.  
  462. //------------------------------------
  463. function add_places_rewrite_rules() {
  464. //------------------------------------
  465.     add_rewrite_rule('^area/([^/]*)/places/?',
  466.                      'index.php?post_type=area&name=$matches[1]&action=places','top');
  467.  
  468.     add_rewrite_rule('^area/([^/]*)/([^/]*)/places/?',
  469.                      'index.php?post_type=area&name=$matches[2]&action=places','top');
  470. }
  471.  
  472. add_action( 'init', 'add_places_rewrite_rules' );
  473. ?>
  474.  
  475. <?php
  476. //-------------------------------------------------------------------
  477. //               add custom variables to query
  478. //-------------------------------------------------------------------
  479.  
  480. // Either directly (in your init hook):
  481.  
  482. $wp->add_query_var( 'var1' );
  483. $wp->add_query_var( 'var2' );
  484.  
  485. // Or via a filter:
  486. //------------------------------------
  487. add_filter( 'query_vars', 'wpse12965_query_vars' );
  488. //------------------------------------
  489. function wpse12965_query_vars( $query_vars )
  490. //------------------------------------
  491. {
  492.     $query_vars[] = 'var1';
  493.     $query_vars[] = 'var2';
  494.     return $query_vars;
  495. }
  496.  
  497. //------------------------------------
  498. add_action( 'init', 'wpse12065_init' );
  499. //------------------------------------
  500. function wpse12065_init()
  501. //------------------------------------
  502. {
  503.     add_rewrite_rule(
  504.         'carpage(/([^/]+))?(/([^/]+))?/?',
  505.         'index.php?pagename=carpage&var1=$matches[2]&var2=$matches[4]',
  506.         'top'
  507.     );
  508. }
  509. ?>
  510. <?php
  511. //-------------------------------------------------------------------
  512. //             use WPEditor on front-end
  513. //-------------------------------------------------------------------
  514. /**
  515.  * Пример вызова текстового редактора.
  516.  */
  517. $settings = array(
  518.   'media_buttons'=>false,     // Убрать кнопки загрузки мультимедийных данных.
  519.   'textarea_name'=>'comment', // Имя поля конечно же comment -
  520.                               // для корректной передачи информации системному обрабочику.
  521.   'quicktags'=>true,          // Редактор со списком HTML тегов показать.
  522.   'tinymce'=>false,           // Визуальный редактор TinyMCE скрыть.
  523.   'textarea_rows'=>5          // Строк в textarea пусть будет пять.
  524. );
  525. wp_editor('', 'comment', $settings);
  526. ?>
  527.  
  528. <?php
  529. //------------------------------------
  530. // Пример набора кнопок для TinyMCE
  531. //------------------------------------
  532. $tinymce_settings = array(
  533.   'theme_advanced_buttons1'=>'link,|,bold,italic,underline,strikethrough,
  534.                              separator,blockquote,separator,bullist,numlist'
  535. );
  536.  //------------------------------------
  537. // Пример набора кнопок для Quick-редактора.
  538. //------------------------------------
  539. $quicktags_settings = array(
  540.   'buttons'=>'b,i,ul,ol,li,link,close'
  541. );
  542. ?>
  543.  
  544. <?php
  545. //------------------------------------
  546. $tinymce_settings = array(
  547.   'theme_advanced_buttons1' => 'link,|,bold,italic,underline,
  548.                                strikethrough,separator,blockquote,
  549.                                separator,bullist,numlist'
  550. );
  551.  
  552. $settings = array(
  553.   'media_buttons'=>false,
  554.   'textarea_name'=>'comment',
  555.   'quicktags'=>false,.
  556.   'tinymce'=>$tinymce_settings, // Передаем TinyMCE произвольный набор кнопок массивом.
  557.   'textarea_rows'=>5
  558. );
  559. wp_editor('', 'comment', $settings);
  560. ?>
  561.  
  562. <?php
  563. //-------------------------------------------------------------------
  564. //                use TinyMCE in comment form
  565. //-------------------------------------------------------------------
  566.  
  567. add_filter( 'comment_form_defaults', 'tinymce_comment_4265340' );
  568.  
  569. //------------------------------------
  570. function tinymce_comment_4265340 ( $args ) {
  571. //------------------------------------
  572.     ob_start();
  573.     wp_editor( '', 'comment', array('tinymce') );
  574.     $args['comment_field'] = ob_get_clean();
  575.     return $args;
  576. }
  577. ?>
  578.  
  579. <?php
  580. //-------------------------------------------------------------------
  581. //               use TinyMCE in comment form
  582. //-------------------------------------------------------------------
  583.  
  584. add_action( 'comment_form_after', 'tinyMCE_comment_form' );
  585. //------------------------------------
  586. function tinyMCE_comment_form() {
  587. ?>
  588.     <script type="text/javascript" src="<?php echo includes_url( 'js/tinymce/tiny_mce.js' ); ?>">
  589.     </script>;
  590.     <script type="text/javascript">
  591.         tinyMCE.init({
  592.             theme : "advanced",
  593.             mode: "specific_textareas",
  594.             language: "",
  595.             skin: "default",
  596.             theme_advanced_buttons1: 'bold, italic, underline, blockquote,
  597.                                       strikethrough, bullist, numlist,
  598.                                       undo, redo, link, unlink',
  599.             theme_advanced_buttons2: '',
  600.             theme_advanced_buttons3: '',
  601.             theme_advanced_buttons4: '',
  602.             elements: 'comment',
  603.             theme_advanced_toolbar_location : "top",
  604.         });
  605.     </script>
  606. <?php
  607. }
  608. ?>
  609.  
  610.  
  611. theme_advanced_buttons1: 'bold, italic, underline, blockquote,
  612.                           strikethrough, bullist, numlist, undo,
  613.                           redo, link, unlink',
  614.  
  615. theme_advanced_buttons1: 'bold, italic, underline, blockquote,
  616.                           strikethrough, bullist, numlist,
  617.                           undo, redo',
  618.  
  619. #respond table {
  620.     margin: 0;
  621.     padding: 0;
  622. }
  623. #respond table td {
  624.     padding: 0;
  625.     margin: 0;
  626. }
  627.  
  628. <?php
  629. //-------------------------------------------------------------------
  630. //               use TinyMCE in comment form
  631. //-------------------------------------------------------------------
  632.  
  633. add_filter( 'comment_form_defaults',
  634.                            'custom_comment_form_defaults' );
  635.  
  636. //-------------------------------------------------
  637. function custom_comment_form_defaults( $args ) {
  638. //-------------------------------------------------
  639.  
  640.     if ( is_user_logged_in() ) {
  641.         $mce_plugins = 'inlinepopups, fullscreen, wordpress, wplink, wpdialogs';
  642.     } else {
  643.         $mce_plugins = 'fullscreen, wordpress';
  644.     }
  645.     ob_start();
  646.  
  647.     wp_editor( '', 'comment', array(
  648.         'media_buttons' => true,
  649.         'teeny' => true,
  650.         'textarea_rows' => '7',
  651.         'tinymce' => array( 'plugins' => $mce_plugins )
  652.     ) );
  653.  
  654.     $args['comment_field'] = ob_get_clean();
  655.  
  656.     return $args;
  657. }
  658. //-------------------------------------------------
  659. add_action( 'wp_enqueue_scripts',
  660.                       '__THEME_PREFIX__scripts' );
  661.  
  662. //-------------------------------------------------
  663. function __THEME_PREFIX__scripts() {
  664.     wp_enqueue_script('jquery');
  665. }
  666. //-------------------------------------------------
  667. add_filter( 'comment_reply_link',
  668.                    '__THEME_PREFIX__comment_reply_link' );
  669. //-------------------------------------------------
  670. function __THEME_PREFIX__comment_reply_link($link) {
  671.     return str_replace( 'onclick=', 'data-onclick=', $link );
  672. }
  673. //-------------------------------------------------
  674. add_action( 'wp_head',
  675.                       '__THEME_PREFIX__wp_head' );
  676. //-------------------------------------------------
  677. function __THEME_PREFIX__wp_head() {
  678. //-------------------------------------------------
  679. ?>
  680. <script type="text/javascript">
  681.     jQuery(function($){
  682.         $('.comment-reply-link').click(function(e){
  683.             e.preventDefault();
  684.             var args = $(this).data('onclick');
  685.             args = args.replace(/.*\(|\)/gi, '').replace(/\"|\s+/g, '');
  686.             args = args.split(',');
  687.             tinymce.EditorManager.execCommand('mceRemoveControl', true, 'comment');
  688.             addComment.moveForm.apply( addComment, args );
  689.             tinymce.EditorManager.execCommand('mceAddControl', true, 'comment');
  690.         });
  691.     });
  692. </script>
  693. <?php
  694. }
  695.  
  696. //-------------------------------------------------------------------
  697. //                        tz-todoapp.php
  698. //-------------------------------------------------------------------
  699.  
  700. /*
  701. Plugin Name: Todo App
  702. Plugin URI: http://tutorialzine.com
  703. Description: This is a demo plugin for a Tutorialzine tutorial
  704. Version: 1.0
  705. Author: Martin Angelov
  706. Author URI: http://tutorialzine.com
  707. License: GPL2
  708. */
  709.  
  710. define('TZ_TODO_FILE', __FILE__);
  711. define('TZ_TODO_PATH', plugin_dir_path(__FILE__));
  712.  
  713. require TZ_TODO_PATH.'includes/tzTodo.php';
  714.  
  715. new tzTodo();
  716.  
  717. //-------------------------------------------------------
  718. //                includes/tzTodo.php
  719. //-------------------------------------------------------
  720. class tzTodo {
  721.  
  722.     public function __construct(){
  723.  
  724.         add_action( 'init', array($this,'init'));
  725.    
  726.         add_action('wp_ajax_nopriv_tz_ajax', array($this,'ajax'));
  727.         add_action('wp_ajax_tz_ajax', array($this,'ajax'));
  728.  
  729.         add_filter( "manage_tz_todo_posts_columns", array($this, 'change_columns'));
  730.  
  731.         // The two last optional arguments to this function are the
  732.         // priority (10) and number of arguments that the function expects (2):
  733.  
  734.         add_action( "manage_posts_custom_column", array($this, "custom_columns") , 10, 2 );
  735.     }
  736.     //-----------------------------------------
  737.     public function init(){
  738.     //-----------------------------------------
  739.         if( preg_match('/\/todo\/?$/',$_SERVER['REQUEST_URI'])){
  740.             $base_url = plugins_url( 'app/' , TZ_TODO_FILE);
  741.             require TZ_TODO_PATH.'/app/index.php';
  742.             exit;
  743.         }
  744.         $this->add_post_type();
  745.     }
  746.  
  747.     //-----------------------------------------
  748.     public function ajax(){
  749.     //-----------------------------------------
  750.         $id = -1;
  751.         $data = '';
  752.         $verb = '';
  753.  
  754.         $response = array();
  755.  
  756.         if(isset($_POST['verb'])){
  757.             $verb = $_POST['verb'];
  758.         }
  759.  
  760.         if(isset($_POST['id'])){
  761.             $id = (int)$_POST['id'];
  762.         }
  763.  
  764.         if(isset($_POST['data'])){
  765.             $data = wp_strip_all_tags($_POST['data']);
  766.         }
  767.  
  768.         $post = null;
  769.  
  770.         if($id != -1){
  771.             $post = get_post($id);
  772.  
  773.             if($post && $post->post_type != 'tz_todo'){
  774.                 exit;
  775.             }
  776.         }
  777.  
  778.         switch($verb){
  779.             //---------------------
  780.             case 'save':
  781.             //---------------------
  782.                 $todo_item = array(
  783.                     'post_title' => $data,
  784.                     'post_content' => '',
  785.                     'post_status' => 'publish',
  786.                     'post_type' => 'tz_todo',
  787.                 );
  788.  
  789.                 if($post){
  790.  
  791.                     // Adding an id to the array will cause
  792.                     // the post with that id to be edited
  793.                     // instead of a new entry to be created.
  794.  
  795.                     $todo_item['ID'] = $post->ID;
  796.                 }
  797.  
  798.                 $response['id'] = wp_insert_post($todo_item);
  799.             break;
  800.             //---------------------
  801.             case 'check':
  802.             //---------------------
  803.                 if($post){
  804.                     update_post_meta($post->ID, 'status', 'Completed');
  805.                 }
  806.             break;
  807.  
  808.             //---------------------
  809.             case 'uncheck':
  810.             //---------------------
  811.                 if($post){
  812.                     delete_post_meta($post->ID, 'status');
  813.                 }
  814.             break;
  815.  
  816.             //---------------------
  817.             case 'delete':
  818.             //---------------------
  819.                 if($post){
  820.                     wp_delete_post($post->ID);
  821.                 }
  822.             break;
  823.         }
  824.  
  825.         header("Content-type: application/json");
  826.         die(json_encode($response));
  827.  
  828.     }
  829.  
  830.     //-------------------------------------------------
  831.     private function add_post_type(){
  832.     //-------------------------------------------------
  833.  
  834.         register_post_type( 'tz_todo',
  835.             array(
  836.                 'labels' => array(
  837.                     'name' => __( 'Todo items' ),
  838.                     'singular_name' => __( 'Todo item' )
  839.                 ),
  840.                 'public' => true,
  841.                 'supports' => array('title')
  842.             )
  843.         );
  844.     }
  845.  
  846.     //-------------------------------------------------
  847.     public function change_columns($cols){
  848.     //-------------------------------------------------
  849.  
  850.         $cols = array(
  851.             'cb'       => '<input type="checkbox" />',
  852.             'title'      => __( 'Task' ),
  853.             'status' => __( 'Status' ),
  854.             'date'     => __( 'Date' ),
  855.         );
  856.  
  857.         return $cols;
  858.     }
  859.  
  860.     //-------------------------------------------------
  861.     public function custom_columns( $column, $post_id ) {
  862.     //-------------------------------------------------
  863.         switch ( $column ) {
  864.  
  865.             case "status":
  866.                 $status = get_post_meta( $post_id, 'status', true);
  867.  
  868.                 if($status != 'Completed'){
  869.                     $status = 'Not completed';
  870.                 }
  871.                 echo $status;
  872.                 break;
  873.         }
  874.     }
  875.  
  876. }
  877.  
  878. //-------------------------------------------------------
  879. //                /app/index.php
  880. //-------------------------------------------------------
  881. ?>
  882.  
  883. <!DOCTYPE html>
  884. <html>
  885.     <head>
  886.         <meta charset="utf-8" />
  887.         <title>Todo App Powered By WordPress | Tutorialzine Demo</title>
  888.  
  889.         <!-- This is important! It fixes the paths of the css and js files -->
  890.         <base href="<?php echo $base_url ?>"></base>
  891.  
  892.         <!-- The stylesheets -->
  893.         <link rel="stylesheet" href="assets/css/styles.css" />
  894.  
  895.         <script>
  896.  
  897.             // This is the URL where we need to make our AJAX calls.
  898.             // We are making it available to JavaScript as a global variable.
  899.  
  900.             var ajaxurl = '<?php echo admin_url('admin-ajax.php')?>';
  901.         </script>
  902.     </head>
  903.  
  904.     <body>
  905.  
  906.         <div id="todo">
  907.             <h2>Todo List <a href="#" class="add"
  908.                 title="Add new todo item!">✚</a></h2>
  909.             <ul>
  910.                 <?php
  911.  
  912.                     $query = new WP_Query(
  913.                         array( 'post_type'=>'tz_todo', 'order'=>'ASC')
  914.                     );
  915.  
  916.                     // The Loop
  917.                     while ( $query->have_posts() ) :
  918.                         $query->the_post();
  919.                         $done = get_post_meta(get_the_id(), 'status', true) ==
  920.                             'Completed';
  921.                     ?>
  922.  
  923.                         <li data-id="<?php the_id()?>"
  924.                             class="<?php echo ($done ? 'done' : '')?>">
  925.                             <input type="checkbox"
  926.                                 <?php echo ($done ? 'checked="true"' : '')?> />
  927.                             <input type="text"
  928.                                 value="<?php htmlspecialchars(the_title())?>"
  929.                                 placeholder="Write your todo here" />
  930.                             <a href="#" class="delete" title="Delete">✖</a>
  931.                         </li>
  932.  
  933.                     <?php endwhile; ?>
  934.             </ul>
  935.         </div>
  936.  
  937.         <!-- JavaScript includes.  -->
  938.         <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
  939.         <script src="assets/js/script.js"></script>
  940.  
  941.     </body>
  942. </html>
  943.  
  944. //-----------------------------------------------------------------
  945. //                 /app/assets/js/script.js
  946. //-----------------------------------------------------------------
  947. $(function(){
  948.  
  949.     var saveTimer;
  950.     var todoHolder = $('#todo');
  951.  
  952.     //--------------------------------------------
  953.     todoHolder.on('input','li input[type=text]', function(e){
  954.     //--------------------------------------------
  955.         var todo = $(this),
  956.             li = todo.closest('li');
  957.  
  958.         clearTimeout(saveTimer);
  959.  
  960.         saveTimer = setTimeout(function(){
  961.  
  962.             ajaxAction('save', li.data('id'), todo.val()).done(function(r){
  963.  
  964.                 if(r.id != li.data('id')){    
  965.                     li.data('id', r.id);
  966.                 }
  967.             });
  968.  
  969.         }, 1000);
  970.  
  971.     });
  972.  
  973.     //--------------------------------------------
  974.     todoHolder.on('change', 'li input[type=checkbox]',function(e){
  975.     //--------------------------------------------
  976.  
  977.         var checkbox = $(this),
  978.             li = checkbox.closest('li');
  979.  
  980.         li.toggleClass('done',checkbox.is(':checked'));
  981.  
  982.         if(checkbox.is(':checked')){
  983.             ajaxAction('check', li.data('id'));
  984.         }
  985.         else{
  986.             ajaxAction('uncheck', li.data('id'));
  987.         }
  988.  
  989.     });
  990.  
  991.     //--------------------------------------------
  992.     todoHolder.on('click', 'li .delete',function(e){
  993.     //--------------------------------------------
  994.  
  995.         e.preventDefault();
  996.  
  997.         var li = $(this).closest('li');
  998.  
  999.         li.fadeOut(function(){
  1000.             li.remove();
  1001.         });
  1002.  
  1003.         if(li.data('id') != 0){
  1004.             ajaxAction('delete', li.data('id'));
  1005.         }
  1006.  
  1007.     });
  1008.  
  1009.     //--------------------------------------------
  1010.     todoHolder.on('click','a.add', function(e){
  1011.     //--------------------------------------------
  1012.         e.preventDefault();
  1013.  
  1014.         var item = $('<li data-id="0">'+
  1015.             '<input type="checkbox" />
  1016.              <input type="text" val="" placeholder="Write your todo here" />'+
  1017.             '<a href="#" class="delete">✖</a>'+
  1018.             '</li>');
  1019.  
  1020.         todoHolder.find('ul').append(item);
  1021.     });
  1022.  
  1023.     //---------------------------------------------
  1024.     function ajaxAction(verb, id, data){
  1025.     //---------------------------------------------
  1026.  
  1027.         return $.post(ajaxurl, {
  1028.             'action': 'tz_ajax',
  1029.             'verb':verb,
  1030.             'id': id,
  1031.             'data': data
  1032.         }, 'json');
  1033.  
  1034.     }
  1035. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement