{"id":307,"date":"2018-11-15T15:19:57","date_gmt":"2018-11-15T15:19:57","guid":{"rendered":"https:\/\/jmrowe.com\/blog\/?p=307"},"modified":"2022-04-27T12:38:47","modified_gmt":"2022-04-27T12:38:47","slug":"misc-notes-for-wordpress","status":"publish","type":"post","link":"https:\/\/jmrowe.com\/blog\/misc-notes-for-wordpress\/","title":{"rendered":"Misc notes for WordPress"},"content":{"rendered":"<p><strong>Proper way to add js variables from php is to use localize script.<\/strong><\/p>\n<p>An efficient way of doing it:<\/p>\n<p>First register the script at the beginning (main.js as an example).<\/p>\n<pre class=\"lang:php decode:true \"> wp_register_script('main_script', 'main.js', array('jquery'), null, true);<\/pre>\n<p>Then if any variables need to be added from php to js you create a call back for a custom filter:<\/p>\n<pre class=\"lang:php decode:true \">function localize_admin_ajax_url($array) {\r\n  $array['admin_ajax_url'] = admin_url('admin-ajax.php');\r\n  return $array;\r\n}\r\nadd_filter('localized_theme_vars', 'localize_admin_ajax_url');<\/pre>\n<p>That will add a js variable admin_ajax_url when the script is finally included. The nonce or any other data could be added as well.<\/p>\n<p>Finally, we check the filter to see if any data has been added to it and if not we do not localize the script:<\/p>\n<pre class=\"lang:php decode:true \">\/\/ Apply any filters that were added via add_filter\r\n$localized_theme_vars = apply_filters('localized_theme_vars', array());\r\n\r\nif($localized_theme_vars) { \/\/only localize if we have something to localize!\r\n    wp_localize_script('main_script', 'localized_theme_vars', $localized_theme_vars);\r\n}\r\n\r\n\/\/ After the check, we finally enqueue the script\r\n\r\nwp_enqueue_script('main_script');<\/pre>\n<p><strong>Body and Post Class<\/strong><\/p>\n<p>WordPress provides body_class() and post_class() which will provide useful classes on both &lt;body&gt; and the individual post i.e. &lt;article&gt; that will give information to target things like specific post ids etc. The functions are to be used like :<\/p>\n<pre class=\"lang:php decode:true \">\/\/ for body classes\r\n\/\/ no need for class=\"\"\r\n\r\n&lt;body &lt;?php body_class() ?&gt; &gt;\r\n&lt;\/body&gt;\r\n\r\n\/\/ for individual post classes \r\n\/\/ no need for class=\"\"\r\n\r\n&lt;article &lt;?php post_class() ?&gt; &gt;\r\n&lt;\/article&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>in_the_loop()<\/strong><\/p>\n<p>Useful for determining if the caller is within the loop. So for example, if you added an action to &#8216;loop_end&#8217; to display something after the last of the loop using a condition with in_the_loop() it will make sure the contents of the action will only execute\u00a0 if it is within the main posts loop.<\/p>\n<p><strong>Including CSS\/Javascript for a shortcode<\/strong><\/p>\n<p>As long as the styles\/scripts are registered.. they can be actually en-queued within the actual short code code so that the script\/styles will only actually load when the short code is used.<\/p>\n<p><strong>Conditionally enqueueing scripts\/styles in admin area<\/strong><\/p>\n<p>When adding an action to &#8216;admin_enqueue_scripts&#8217; to enqueue scripts, $hook is passed in to determine what page in the admin area you are on.<\/p>\n<p>To test if you are on a certain plugin menu page you can create a global variable to check against the $hook.<\/p>\n<p>Example:<\/p>\n<pre class=\"lang:php decode:true \">\/\/ First, when creating the menu page.. also assign it to a new global variable:\r\n\r\nfunction addMenuItem(){\r\n    global $main_test_plugin_menu;\r\n    $main_test_plugin_menu=add_menu_page('Test Plugin Menu Title','Test Plugin','manage_options','test_plugin_menu',__NAMESPACE__.'\\\\show_page');\r\n}\r\n\r\n\/\/ Then in the admin_enqueue_scripts function you create to add action\r\n\/\/ use the global variable to check against $hook to check if\r\n\/\/ the user is on the parent plugin for the script\/style\r\n\r\nfunction add_admin_scripts($hook)\r\n{\r\n    global $main_test_plugin_menu; \/\/ retrieve global variable \r\n    wp_register_script('main-admin-vue', PLUGIN_DIR_URL . 'js\/vue.js',['jquery'],  time(),true);\r\n    wp_register_script('main-admin-js', PLUGIN_DIR_URL . 'js\/main.js',['main-admin-vue'],time(),true);\r\n\r\n\/\/ Use global variable to check against $hookthe check, we finally enqueue the script\r\n\r\n   if($hook==$main_test_plugin_menu){\r\n    include PLUGIN_DIR.'inc\\\\template.php';\r\n    wp_enqueue_script('main-admin-js');\r\n    wp_enqueue_script('main-admin-vue');}\r\n   }\r\n}\r\n\r\nadd_action('admin_enqueue_scripts',  __NAMESPACE__.'\\\\add_admin_scripts');<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>To help with removing render-blocking resources from javascript files:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">function defer_parsing_of_js($url)\r\n{\r\n  if (is_admin()) return $url; \r\n  if (false === strpos($url, '.js')) return $url; \r\n  if (strpos($url, 'jquery.js')) return $url; \r\n  return str_replace(' src', ' defer src', $url);\r\n}\r\nadd_filter('script_loader_tag', 'defer_parsing_of_js', 10);\r\n\r\n\/*\r\n\r\nDoesn't attempt for admins\/wp admin bar\r\n\r\nCan add more lines for individual js files by name if we want to exclude from \r\ndeffer.\r\n\r\nNote the files will still load in the same order just all with deferred added.\r\n*\/\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Rewrite API and when\/how to flush_rewrite_rules<\/strong><\/p>\n<p>The simplest solution is to delete the option that WordPress sets after building the rewrite rules upon the plugins activation and deactivation hooks. This will force WordPress to rebuild the rules that you may have added.<\/p>\n<pre class=\"lang:default decode:true \">&lt;?php\r\ndefined('ABSPATH') or exit;\r\n\/**\r\n * Plugin Name: Custom Endpoint Plugin\r\n * Description: To show when and how to flush rewrite rules\r\n*\/\r\n\r\n\r\nregister_activation_hook(__FILE__, array('api_custom_endpoint', 'activation_method'));\r\nregister_deactivation_hook(__FILE__, array('api_custom_endpoint', 'deactivation_method'));\r\n\r\nclass api_custom_endpoint\r\n{\r\n  \r\n    function init()\r\n    {\r\n        add_action('init', array($this, 'add_rewrite_rules_for_api_custom_endpoint'));\r\n        add_action('template_redirect', array($this, 'check_getuserlist_template_redirect'), 0);\r\n    }\r\n\r\n\r\n    function activation_method()\r\n    {\r\n        \/\/forces WordPress to rebuild rewrite list\r\n        delete_option('rewrite_rules');\r\n    }\r\n\r\n    function deactivation_method()\r\n    {\r\n        \/\/forces WordPress to rebuild rewrite list\r\n        delete_option('rewrite_rules');\r\n    }\r\n\r\n    function add_rewrite_rules_for_api_custom_endpoint()\r\n    {\r\n        add_rewrite_endpoint('newendpoint', EP_ROOT);\r\n\r\n    }\r\n\r\n    function check_getuserlist_template_redirect()\r\n    {\r\n        global $wp_query;\r\n\r\n        \/\/ if not the root \"\/\" of the site or if request doesn't contain getUsers.. don't redirect.\r\n        if (!isset($wp_query-&gt;query_vars['newendpoint']) )\r\n            return;\r\n\r\n        \/\/ include custom template if it passes newendpoint in url check\r\n        include dirname(__FILE__) . '\/newendpointtemplate.php';\r\n        exit;\r\n    }\r\n}\r\n\r\n\r\n\/\/ running init\r\n\r\n$app = new api_custom_endpoint();\r\n$app-&gt;init();<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Change the placeholder for Add Title field on custom post type:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">function change_title_text( $title ){\r\n     $screen = get_current_screen();\r\n   \r\n     if  ( 'word' == $screen-&gt;post_type ) {\r\n          $title = 'What is the new word?';\r\n     }\r\n   \r\n     return $title;\r\n}\r\n   \r\nadd_filter( 'enter_title_here', 'change_title_text' );\r\n<\/pre>\n<p><strong>Custom Excerpt<\/strong><\/p>\n<pre class=\"lang:default decode:true \">function custom_excerpt_bn($text) { \/\/ Fakes an excerpt if needed\r\n$excerpt = get_the_content();\r\n$excerpt = strip_shortcodes($excerpt);\r\n$excerpt = strip_tags($excerpt,'&lt;p&gt;');\r\n$excerpt = substr($excerpt, 0, 150);\r\n$excerpt = substr($excerpt, 0, strripos($excerpt, \" \"));\r\n$excerpt = trim(preg_replace( '\/\\s+\/', ' ', $excerpt));\r\n$excerpt = $excerpt.' ...';\r\nreturn $excerpt;\r\n}\r\n\/* remove the default filter *\/\r\nremove_filter('get_the_excerpt', 'wp_trim_excerpt');\r\n\/* now, add your own filter *\/\r\nadd_filter('get_the_excerpt', 'custom_excerpt_bn');<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Proper way to add js variables from php is to use localize script. An efficient way of doing it: First register the script at the beginning (main.js as an example). wp_register_script(&#8216;main_script&#8217;, &#8216;main.js&#8217;, array(&#8216;jquery&#8217;), null, true); Then if any variables need to be added from php to js you create a call back for a custom [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-307","post","type-post","status-publish","format-standard","hentry","category-wordpress"],"_links":{"self":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts\/307","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/comments?post=307"}],"version-history":[{"count":16,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts\/307\/revisions"}],"predecessor-version":[{"id":732,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/posts\/307\/revisions\/732"}],"wp:attachment":[{"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/media?parent=307"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/categories?post=307"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jmrowe.com\/blog\/wp-json\/wp\/v2\/tags?post=307"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}