qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
299,582
<p>I am trying to add a new menu item to an already existing nav menu in my theme, I am using some part of this answer <a href="https://wordpress.stackexchange.com/questions/15455/how-to-hard-code-custom-menu-items">How to Hard Code Custom menu items</a></p> <p>I am directly using this code in my plugin</p> <pre><code>wp_update_nav_menu_item(2, 0, array( 'menu-item-title' =&gt; __('Home'), 'menu-item-classes' =&gt; 'home', 'menu-item-url' =&gt; home_url( '/' ), 'menu-item-status' =&gt; 'publish')); </code></pre> <p>But it gives me following error</p> <blockquote> <p>Your PHP code changes were rolled back due to an error on line 357 of file C:\xampp\htdocs\wordpress\wp-includes\link-template.php. Please fix and try saving again</p> <p>Call to a member function get_page_permastruct() on null</p> </blockquote>
[ { "answer_id": 299572, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Never manipulate the DB directly, instead write some small wordpress plugin to do it. The amount of gotchas when trying to change a serialized data \"by hand\" is ridiculous and the risk do not justify the small amount of time it seems like it will save you.</p>\n" }, { "answer_id": 299576, "author": "nicolai", "author_id": 140965, "author_profile": "https://wordpress.stackexchange.com/users/140965", "pm_score": 1, "selected": false, "text": "<p>I misplaced a single quote. This query worked for me and solved my problem.</p>\n\n<p>update <code>wp_postmeta</code> set <code>meta_value</code>= concat( 'a:1:{s:3:\"url\";s:28:\"', <code>meta_value</code>, '\";}' ) where <code>meta_key</code> = '_woofv_video_embed'</p>\n" } ]
2018/04/02
[ "https://wordpress.stackexchange.com/questions/299582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114573/" ]
I am trying to add a new menu item to an already existing nav menu in my theme, I am using some part of this answer [How to Hard Code Custom menu items](https://wordpress.stackexchange.com/questions/15455/how-to-hard-code-custom-menu-items) I am directly using this code in my plugin ``` wp_update_nav_menu_item(2, 0, array( 'menu-item-title' => __('Home'), 'menu-item-classes' => 'home', 'menu-item-url' => home_url( '/' ), 'menu-item-status' => 'publish')); ``` But it gives me following error > > Your PHP code changes were rolled back due to an error on line 357 of file C:\xampp\htdocs\wordpress\wp-includes\link-template.php. Please fix and try saving again > > > Call to a member function get\_page\_permastruct() on null > > >
I misplaced a single quote. This query worked for me and solved my problem. update `wp_postmeta` set `meta_value`= concat( 'a:1:{s:3:"url";s:28:"', `meta_value`, '";}' ) where `meta_key` = '\_woofv\_video\_embed'
299,591
<p>I am developing a plugin. Among other things its backend settings will allow admins to update a site data file from a 3rd party data provider, or to switch on/off a wp-cron job to do this automatically.</p> <p>In this (simplified) code <strong>I <em>assume</em> my wp-cron job will only be run if someone logs in to the WP Dashboard?</strong> (not what I really want)</p> <pre><code>if (is_admin()) { include 'my_update_script.php'; include 'settings_form_stuff.php'; // schedules/deschedules xyz_job etc } </code></pre> <p>and in "my_update_script.php":</p> <pre><code>function xyz_2weekly( $schedules ) { $schedules['xyz_2weekly'] = array( 'interval' =&gt; 3*604800, 'display' =&gt; __('Two Weeks') ); return $schedules; } add_filter( 'cron_schedules', 'xyz_2weekly'); add_action( $xyz_job, 'xyz_update_files' ); function (xyz_update_files) { $xyz_update = new xyz_upd_class(); $xyz_update-&gt;do_update(TRUE); // true identifies it as automated and emails admin on failure unset($xyz_update); } class xyz_upd_class { // etc </code></pre> <p>Inefficiencies add up, and I want to avoid overhead of unnecessary includes on the front end (the plugin is for both PHP 5 &amp; 7).</p> <p>I am aware that to prevent delay in response to the visitor the front end request spawns a background request to fire a separate wp-cron "process" but I <em>assume</em> (I couldn't find any info) this process isn't set to run in "wp-admin/is-admin scope" and so won't execute the add_action.</p> <p><strong>Is there an efficient alteration I can make so</strong> the update script (with add_action) is not included on front end requests but is still available to wp-cron when fired from front-end?</p> <p><strong>Edit:</strong> Clinton's answer indicates that my is_admin include would be "out of scope" when "wp-cron process" is spawned by front-end request. </p> <p>I was hoping for answers similar to this <code>if ( is_admin() || wp_next_scheduled($xyz_job) ) include ...</code> (one I thought of but ruled out, as most sites will have scheduled the job; and I suspect schedule won't be in memory so this would just result in an additional "slow" server read). </p> <p>In absence of alternatives, I have decided to just incorporate the code without checking if admin so I am accepting Clinton's answer.</p>
[ { "answer_id": 299600, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 2, "selected": true, "text": "<p>I had to read this a few times to understand it and I am not sure if my interpretation is correct. Anyhow here is my interpretation (apologies if I have gotten this wrong)...</p>\n\n<p>You have a CRON job that is intended to update files of some sort. This CRON job will run when someone visits the site whether admin or not at your specified frequency. The CRON job can be switched off by an administrator from the plugin settings. You do not want to include any unnecessary includes.</p>\n\n<p>I would split this into 2 separate parts first the settings part where I would set a on/off flag as follows:</p>\n\n<p>define the flag as an option setting and set it to on (1) when the plugin is activated:</p>\n\n<pre><code>register_activation_hook(__FILE__, function(){\n add_option('xyz_cron_status', 1);\n}\n</code></pre>\n\n<p>The value of this option will be changed through a form accessed through the plugin settings menu in the usual Wordpress Plugin way.</p>\n\n<p>Next define your CRON job in the plugin setup code (not surrounded by is_admin() function) as follows:</p>\n\n<pre><code>xyz_cron_option = get_option('xyz_cron_status');\nif ( xyz_cron_option ){\n add_filter('cron_schedules', 'xyz_2weekly');\n add_action('wp', 'xyz_cron_settings');\n add_action('xyz_cron_hook', 'xyz_update_files');\n}\n</code></pre>\n\n<p>where xyz_cron_settings is as follows:</p>\n\n<pre><code>/**\n * Create a hook called xyz_cron_hook for this plugin and set the time\n * interval for the hook to fire through CRON\n */\nfunction xyz_cron_settings() {\n //verify event has not already been scheduled\n if ( !wp_next_scheduled( 'xyz_cron_hook' ) ) {\n wp_schedule_event( time(), 'xyz_2weekly', 'xyz_cron_hook' );\n }\n}\n</code></pre>\n\n<p>the other functions are as shown in your code:</p>\n\n<pre><code>function xyz_2weekly( $schedules ) {\n ...\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function xyz_update_files() {\n ...\n}\n</code></pre>\n\n<p>I hope that this helps.</p>\n" }, { "answer_id": 350885, "author": "Marcos Silva", "author_id": 177088, "author_profile": "https://wordpress.stackexchange.com/users/177088", "pm_score": 3, "selected": false, "text": "<p>I know it's late, but for other people searching:</p>\n\n<pre><code>if (is_admin () || wp_doing_cron ()) {\n your code ...\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_doing_cron/\" rel=\"noreferrer\">about wp_doing_cron</a></p>\n" } ]
2018/04/02
[ "https://wordpress.stackexchange.com/questions/299591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128374/" ]
I am developing a plugin. Among other things its backend settings will allow admins to update a site data file from a 3rd party data provider, or to switch on/off a wp-cron job to do this automatically. In this (simplified) code **I *assume* my wp-cron job will only be run if someone logs in to the WP Dashboard?** (not what I really want) ``` if (is_admin()) { include 'my_update_script.php'; include 'settings_form_stuff.php'; // schedules/deschedules xyz_job etc } ``` and in "my\_update\_script.php": ``` function xyz_2weekly( $schedules ) { $schedules['xyz_2weekly'] = array( 'interval' => 3*604800, 'display' => __('Two Weeks') ); return $schedules; } add_filter( 'cron_schedules', 'xyz_2weekly'); add_action( $xyz_job, 'xyz_update_files' ); function (xyz_update_files) { $xyz_update = new xyz_upd_class(); $xyz_update->do_update(TRUE); // true identifies it as automated and emails admin on failure unset($xyz_update); } class xyz_upd_class { // etc ``` Inefficiencies add up, and I want to avoid overhead of unnecessary includes on the front end (the plugin is for both PHP 5 & 7). I am aware that to prevent delay in response to the visitor the front end request spawns a background request to fire a separate wp-cron "process" but I *assume* (I couldn't find any info) this process isn't set to run in "wp-admin/is-admin scope" and so won't execute the add\_action. **Is there an efficient alteration I can make so** the update script (with add\_action) is not included on front end requests but is still available to wp-cron when fired from front-end? **Edit:** Clinton's answer indicates that my is\_admin include would be "out of scope" when "wp-cron process" is spawned by front-end request. I was hoping for answers similar to this `if ( is_admin() || wp_next_scheduled($xyz_job) ) include ...` (one I thought of but ruled out, as most sites will have scheduled the job; and I suspect schedule won't be in memory so this would just result in an additional "slow" server read). In absence of alternatives, I have decided to just incorporate the code without checking if admin so I am accepting Clinton's answer.
I had to read this a few times to understand it and I am not sure if my interpretation is correct. Anyhow here is my interpretation (apologies if I have gotten this wrong)... You have a CRON job that is intended to update files of some sort. This CRON job will run when someone visits the site whether admin or not at your specified frequency. The CRON job can be switched off by an administrator from the plugin settings. You do not want to include any unnecessary includes. I would split this into 2 separate parts first the settings part where I would set a on/off flag as follows: define the flag as an option setting and set it to on (1) when the plugin is activated: ``` register_activation_hook(__FILE__, function(){ add_option('xyz_cron_status', 1); } ``` The value of this option will be changed through a form accessed through the plugin settings menu in the usual Wordpress Plugin way. Next define your CRON job in the plugin setup code (not surrounded by is\_admin() function) as follows: ``` xyz_cron_option = get_option('xyz_cron_status'); if ( xyz_cron_option ){ add_filter('cron_schedules', 'xyz_2weekly'); add_action('wp', 'xyz_cron_settings'); add_action('xyz_cron_hook', 'xyz_update_files'); } ``` where xyz\_cron\_settings is as follows: ``` /** * Create a hook called xyz_cron_hook for this plugin and set the time * interval for the hook to fire through CRON */ function xyz_cron_settings() { //verify event has not already been scheduled if ( !wp_next_scheduled( 'xyz_cron_hook' ) ) { wp_schedule_event( time(), 'xyz_2weekly', 'xyz_cron_hook' ); } } ``` the other functions are as shown in your code: ``` function xyz_2weekly( $schedules ) { ... } ``` and ``` function xyz_update_files() { ... } ``` I hope that this helps.
299,617
<p>I have created a custom button for TinyMCE and I would like it to use the Twitter icon from dashicons. I am hoping to be able to do this just through the Javascript with no additional CSS. Is this possible? </p> <p>Here is my current(non-working) attempt:</p> <pre><code>(function () { tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) { editor.addButton('mce_tweet_button', { title: 'Insert tweet', icon: 'dashicons dashicons-twitter', onclick: function() { ... } }); }); })(); </code></pre>
[ { "answer_id": 299635, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I am hoping to be able to do this just through the Javascript with no\n additional CSS. Is this possible?</p>\n</blockquote>\n\n<p>I assume you only want to stay within <code>tinymce.PluginManager.add( ... )</code>.</p>\n\n<p>Here's a JS workaround with:</p>\n\n<pre><code>jQuery( '.is-dashicon' ).css( 'font-family', 'dashicons' );\n</code></pre>\n\n<p>within a <a href=\"https://www.tinymce.com/docs/api/tinymce.ui/tinymce.ui.flowlayout/#postrender\" rel=\"nofollow noreferrer\"><em>onPostRender</em></a> event callback:</p>\n\n<pre><code>(function () {\n tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) {\n editor.addButton('mce_tweet_button', {\n title: 'Insert tweet',\n icon: 'insert-tweet is-dashicon dashicons dashicons-twitter',\n onPostRender: function () {\n jQuery( '.is-dashicon' ).css( 'font-family', 'dashicons' );\n },\n onclick: function() {\n ...\n }\n });\n });\n})();\n</code></pre>\n\n<p>that will generate the tag:</p>\n\n<pre><code>&lt;i class=\"mce-ico mce-i-insert-tweet \n is-dashicon dashicons dashicons-twitter\" style=\"font-family: dashicons;\"&gt;&lt;/i&gt;\n</code></pre>\n\n<p>Example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VA2em.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VA2em.jpg\" alt=\"twitter\"></a></p>\n" }, { "answer_id": 303838, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Here's your easy solution (hopefully this will help other people too):</p>\n\n<p>1) add a custom class for icon, in this example \"myicons\"</p>\n\n<pre><code>(function () {\n tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) {\n editor.addButton('mce_tweet_button', {\n title: 'Insert tweet',\n icon: 'myicons dashicons-twitter',\n onclick: function() {\n ...\n }\n });\n });\n})();\n</code></pre>\n\n<p>2) Enqueue your admin stylesheet file</p>\n\n<pre><code>function load_custom_wp_admin_style() {\n wp_enqueue_style( 'custom_wp_admin_css', 'URL/TO/custom_admin_style.css' );\n}\nadd_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );\n</code></pre>\n\n<p>3) Then in your <strong>custom_admin_style.css</strong> file add this:</p>\n\n<pre><code>/**\n * TinyMCE add support for dashicons\n */\ni.mce-i-myicon {\n font: 400 20px/1 dashicons;\n padding: 0;\n vertical-align: top;\n speak: none;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n margin-left: -2px;\n padding-right: 2px\n}\n</code></pre>\n" }, { "answer_id": 409648, "author": "RafaSashi", "author_id": 37412, "author_profile": "https://wordpress.stackexchange.com/users/37412", "pm_score": 1, "selected": false, "text": "<p>Using the OP code when setting icon to <code>'dashicons dashicons-twitter'</code> the editor renders the button with the following classes <code>'mce-ico mce-i-dashicons dashicons-twitter'</code></p>\n<p>Therefore without using jQuery what works for me is:</p>\n<pre><code>(function () {\n tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) {\n editor.addButton('mce_tweet_button', {\n title: 'Insert tweet',\n icon: 'dashicons dashicons-twitter',\n onPostRender: function () {\n \n elements = document.getElementsByClassName(&quot;mce-i-dashicons&quot;);\n \n for(i=0; i&lt;elements.length; i++) {\n \n elements[i].style.fontFamily = &quot;dashicons&quot;;\n }\n }\n onclick: function() {\n ...\n }\n });\n });\n})();\n</code></pre>\n" } ]
2018/04/02
[ "https://wordpress.stackexchange.com/questions/299617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13286/" ]
I have created a custom button for TinyMCE and I would like it to use the Twitter icon from dashicons. I am hoping to be able to do this just through the Javascript with no additional CSS. Is this possible? Here is my current(non-working) attempt: ``` (function () { tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) { editor.addButton('mce_tweet_button', { title: 'Insert tweet', icon: 'dashicons dashicons-twitter', onclick: function() { ... } }); }); })(); ```
Here's your easy solution (hopefully this will help other people too): 1) add a custom class for icon, in this example "myicons" ``` (function () { tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) { editor.addButton('mce_tweet_button', { title: 'Insert tweet', icon: 'myicons dashicons-twitter', onclick: function() { ... } }); }); })(); ``` 2) Enqueue your admin stylesheet file ``` function load_custom_wp_admin_style() { wp_enqueue_style( 'custom_wp_admin_css', 'URL/TO/custom_admin_style.css' ); } add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' ); ``` 3) Then in your **custom\_admin\_style.css** file add this: ``` /** * TinyMCE add support for dashicons */ i.mce-i-myicon { font: 400 20px/1 dashicons; padding: 0; vertical-align: top; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; margin-left: -2px; padding-right: 2px } ```
299,664
<p>I try to add an existing user to a blog with the function <code>add_user_to_blog($blog_id, $user_id, $role)</code>. The code I use gives me: </p> <blockquote> <p>Catchable fatal error: Object of class WP_Error could not be converted to string in C:\wamp64\www\wordpress\wp-includes\ms-functions.php on line 206.</p> </blockquote> <p>What do I need to do to make this work?</p> <p>This is my code:</p> <pre><code>$domain = ""; $path = "localhost/wordpress/wp_4"; $title = "WP_4"; $user_id = 1; $network_id = get_main_network_id(); $role = 'editor'; $new_blog_id = wpmu_create_blog($domain, $path, $title, $user_id, $network_id); add_user_to_blog($new_blog_id, $network_id, $role); </code></pre>
[ { "answer_id": 299635, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I am hoping to be able to do this just through the Javascript with no\n additional CSS. Is this possible?</p>\n</blockquote>\n\n<p>I assume you only want to stay within <code>tinymce.PluginManager.add( ... )</code>.</p>\n\n<p>Here's a JS workaround with:</p>\n\n<pre><code>jQuery( '.is-dashicon' ).css( 'font-family', 'dashicons' );\n</code></pre>\n\n<p>within a <a href=\"https://www.tinymce.com/docs/api/tinymce.ui/tinymce.ui.flowlayout/#postrender\" rel=\"nofollow noreferrer\"><em>onPostRender</em></a> event callback:</p>\n\n<pre><code>(function () {\n tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) {\n editor.addButton('mce_tweet_button', {\n title: 'Insert tweet',\n icon: 'insert-tweet is-dashicon dashicons dashicons-twitter',\n onPostRender: function () {\n jQuery( '.is-dashicon' ).css( 'font-family', 'dashicons' );\n },\n onclick: function() {\n ...\n }\n });\n });\n})();\n</code></pre>\n\n<p>that will generate the tag:</p>\n\n<pre><code>&lt;i class=\"mce-ico mce-i-insert-tweet \n is-dashicon dashicons dashicons-twitter\" style=\"font-family: dashicons;\"&gt;&lt;/i&gt;\n</code></pre>\n\n<p>Example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VA2em.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VA2em.jpg\" alt=\"twitter\"></a></p>\n" }, { "answer_id": 303838, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Here's your easy solution (hopefully this will help other people too):</p>\n\n<p>1) add a custom class for icon, in this example \"myicons\"</p>\n\n<pre><code>(function () {\n tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) {\n editor.addButton('mce_tweet_button', {\n title: 'Insert tweet',\n icon: 'myicons dashicons-twitter',\n onclick: function() {\n ...\n }\n });\n });\n})();\n</code></pre>\n\n<p>2) Enqueue your admin stylesheet file</p>\n\n<pre><code>function load_custom_wp_admin_style() {\n wp_enqueue_style( 'custom_wp_admin_css', 'URL/TO/custom_admin_style.css' );\n}\nadd_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );\n</code></pre>\n\n<p>3) Then in your <strong>custom_admin_style.css</strong> file add this:</p>\n\n<pre><code>/**\n * TinyMCE add support for dashicons\n */\ni.mce-i-myicon {\n font: 400 20px/1 dashicons;\n padding: 0;\n vertical-align: top;\n speak: none;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n margin-left: -2px;\n padding-right: 2px\n}\n</code></pre>\n" }, { "answer_id": 409648, "author": "RafaSashi", "author_id": 37412, "author_profile": "https://wordpress.stackexchange.com/users/37412", "pm_score": 1, "selected": false, "text": "<p>Using the OP code when setting icon to <code>'dashicons dashicons-twitter'</code> the editor renders the button with the following classes <code>'mce-ico mce-i-dashicons dashicons-twitter'</code></p>\n<p>Therefore without using jQuery what works for me is:</p>\n<pre><code>(function () {\n tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) {\n editor.addButton('mce_tweet_button', {\n title: 'Insert tweet',\n icon: 'dashicons dashicons-twitter',\n onPostRender: function () {\n \n elements = document.getElementsByClassName(&quot;mce-i-dashicons&quot;);\n \n for(i=0; i&lt;elements.length; i++) {\n \n elements[i].style.fontFamily = &quot;dashicons&quot;;\n }\n }\n onclick: function() {\n ...\n }\n });\n });\n})();\n</code></pre>\n" } ]
2018/04/03
[ "https://wordpress.stackexchange.com/questions/299664", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141040/" ]
I try to add an existing user to a blog with the function `add_user_to_blog($blog_id, $user_id, $role)`. The code I use gives me: > > Catchable fatal error: Object of class WP\_Error could not be converted > to string in C:\wamp64\www\wordpress\wp-includes\ms-functions.php on > line 206. > > > What do I need to do to make this work? This is my code: ``` $domain = ""; $path = "localhost/wordpress/wp_4"; $title = "WP_4"; $user_id = 1; $network_id = get_main_network_id(); $role = 'editor'; $new_blog_id = wpmu_create_blog($domain, $path, $title, $user_id, $network_id); add_user_to_blog($new_blog_id, $network_id, $role); ```
Here's your easy solution (hopefully this will help other people too): 1) add a custom class for icon, in this example "myicons" ``` (function () { tinymce.PluginManager.add('twitter_button_plugin', function (editor, url) { editor.addButton('mce_tweet_button', { title: 'Insert tweet', icon: 'myicons dashicons-twitter', onclick: function() { ... } }); }); })(); ``` 2) Enqueue your admin stylesheet file ``` function load_custom_wp_admin_style() { wp_enqueue_style( 'custom_wp_admin_css', 'URL/TO/custom_admin_style.css' ); } add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' ); ``` 3) Then in your **custom\_admin\_style.css** file add this: ``` /** * TinyMCE add support for dashicons */ i.mce-i-myicon { font: 400 20px/1 dashicons; padding: 0; vertical-align: top; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; margin-left: -2px; padding-right: 2px } ```
299,701
<p>There is an author_link hook which is very useful for posts and bios; however, I don't see a hook for comment author link. Does one exist?</p>
[ { "answer_id": 299704, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 0, "selected": false, "text": "<p>Are you looking for <code>get_comment_author_url</code> ?</p>\n" }, { "answer_id": 299714, "author": "Mohammad Tajul Islam", "author_id": 87355, "author_profile": "https://wordpress.stackexchange.com/users/87355", "pm_score": 2, "selected": false, "text": "<p>There is a filter hook like author_link hook. </p>\n\n<pre><code>get_comment_author_link()\n</code></pre>\n\n<p>Details info about the above filter hook.<br/>\n<a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author_link/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/get_comment_author_link/</a></p>\n\n<p>There are a lot of built-in functions at wordpress.</p>\n\n<pre><code>&lt;?php comment_author_url_link('linktext', 'before', 'after'); ?&gt; \n</code></pre>\n\n<p>Let's have a look the functions related to comments.<br />\n<a href=\"https://codex.wordpress.org/Function_Reference/comment_author_url_link\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/comment_author_url_link</a></p>\n\n<p>I hope you will find the solution. </p>\n" }, { "answer_id": 299722, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>The other two answers probably answer your question, but here's a way look at WordPress source code to be able to determine for yourself whether a certain hook exists for your purposes.</p>\n\n<p>You ask whether there is a hook for the comment author link. So let's look at the source for that function: <a href=\"https://developer.wordpress.org/reference/functions/comment_author_link/\" rel=\"nofollow noreferrer\"><code>comment_author_link()</code></a>.</p>\n\n<p>We see that there's not really much to that function. It just echos the output of <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link()</code></a>. So let's look at that function.</p>\n\n<p>It does some stuff and then returns the filtered results of <a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link</code></a>. So you could use that filter to modify the output of <code>comment_author_link()</code>.</p>\n\n<pre><code>add_filter( 'get_comment_author_link', function( $return, $author, $comment_id ){\n if( 'example' === $author ) {\n $return = '&lt;a href=\"https://example.com/\"&gt;Example&lt;/a&gt;';\n }\n return $return;\n}, 10, 3 );\n</code></pre>\n\n<p>But I have a feeling that you want to modify the URL of the comment author. If that's the case, we see that <code>get_comment_author_link()</code> calls <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_url/\" rel=\"nofollow noreferrer\"><code>get_comment_author_url()</code></a> to determine the author.</p>\n\n<p>And in that function we see that it returns the filtered results of <a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author_url/\" rel=\"nofollow noreferrer\"><code>get_comment_author_url</code></a>.</p>\n\n<p>So if you want to change the URL of the comment author link, you could do something like:</p>\n\n<pre><code>add_filter( 'get_comment_author_url', function( $url, $id, $comment ){\n if( 'example' === $comment-&gt;comment_author ) {\n $url = 'https://example.com/';\n }\n return $url;\n}, 10, 3 );\n</code></pre>\n" } ]
2018/04/03
[ "https://wordpress.stackexchange.com/questions/299701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47326/" ]
There is an author\_link hook which is very useful for posts and bios; however, I don't see a hook for comment author link. Does one exist?
The other two answers probably answer your question, but here's a way look at WordPress source code to be able to determine for yourself whether a certain hook exists for your purposes. You ask whether there is a hook for the comment author link. So let's look at the source for that function: [`comment_author_link()`](https://developer.wordpress.org/reference/functions/comment_author_link/). We see that there's not really much to that function. It just echos the output of [`get_comment_author_link()`](https://developer.wordpress.org/reference/functions/get_comment_author_link/). So let's look at that function. It does some stuff and then returns the filtered results of [`get_comment_author_link`](https://developer.wordpress.org/reference/hooks/get_comment_author_link/). So you could use that filter to modify the output of `comment_author_link()`. ``` add_filter( 'get_comment_author_link', function( $return, $author, $comment_id ){ if( 'example' === $author ) { $return = '<a href="https://example.com/">Example</a>'; } return $return; }, 10, 3 ); ``` But I have a feeling that you want to modify the URL of the comment author. If that's the case, we see that `get_comment_author_link()` calls [`get_comment_author_url()`](https://developer.wordpress.org/reference/functions/get_comment_author_url/) to determine the author. And in that function we see that it returns the filtered results of [`get_comment_author_url`](https://developer.wordpress.org/reference/hooks/get_comment_author_url/). So if you want to change the URL of the comment author link, you could do something like: ``` add_filter( 'get_comment_author_url', function( $url, $id, $comment ){ if( 'example' === $comment->comment_author ) { $url = 'https://example.com/'; } return $url; }, 10, 3 ); ```
299,751
<p>I have some code that works to display the children of a single page. I'm using this to display the children of a page in my footer. </p> <pre><code>$args = [ 'post_type'=&gt;'page', //this is the custom post type 'child_of'=&gt; '1452', ]; // we get an array of posts objects $posts = get_posts($args); // start our string $str = '&lt;ul&gt;'; // then we create an option for each post foreach($posts as $key=&gt;$post){ $str .= '&lt;li&gt;&lt;a href=" '.get_permalink($post).' "&gt;'.$post-&gt;post_title.'&lt;/a&gt; &lt;/li&gt;'; } $str .= '&lt;/ul&gt;'; echo $str; } </code></pre> <p>But I want to display the children of several pages - and when I try to use several instances of the code, of course, it displays only the first ID. </p> <p>I've tried changing this into a function - but I can't get it to work. This is probably a very stupid question, but I'm a small-time PHP hack.</p> <hr> <p>EDIT: I've just seen that it is not only pulling children from the page ID I have specified, it's pulling a few from everywhere. Very strange. </p>
[ { "answer_id": 299704, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 0, "selected": false, "text": "<p>Are you looking for <code>get_comment_author_url</code> ?</p>\n" }, { "answer_id": 299714, "author": "Mohammad Tajul Islam", "author_id": 87355, "author_profile": "https://wordpress.stackexchange.com/users/87355", "pm_score": 2, "selected": false, "text": "<p>There is a filter hook like author_link hook. </p>\n\n<pre><code>get_comment_author_link()\n</code></pre>\n\n<p>Details info about the above filter hook.<br/>\n<a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author_link/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/get_comment_author_link/</a></p>\n\n<p>There are a lot of built-in functions at wordpress.</p>\n\n<pre><code>&lt;?php comment_author_url_link('linktext', 'before', 'after'); ?&gt; \n</code></pre>\n\n<p>Let's have a look the functions related to comments.<br />\n<a href=\"https://codex.wordpress.org/Function_Reference/comment_author_url_link\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/comment_author_url_link</a></p>\n\n<p>I hope you will find the solution. </p>\n" }, { "answer_id": 299722, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>The other two answers probably answer your question, but here's a way look at WordPress source code to be able to determine for yourself whether a certain hook exists for your purposes.</p>\n\n<p>You ask whether there is a hook for the comment author link. So let's look at the source for that function: <a href=\"https://developer.wordpress.org/reference/functions/comment_author_link/\" rel=\"nofollow noreferrer\"><code>comment_author_link()</code></a>.</p>\n\n<p>We see that there's not really much to that function. It just echos the output of <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link()</code></a>. So let's look at that function.</p>\n\n<p>It does some stuff and then returns the filtered results of <a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author_link/\" rel=\"nofollow noreferrer\"><code>get_comment_author_link</code></a>. So you could use that filter to modify the output of <code>comment_author_link()</code>.</p>\n\n<pre><code>add_filter( 'get_comment_author_link', function( $return, $author, $comment_id ){\n if( 'example' === $author ) {\n $return = '&lt;a href=\"https://example.com/\"&gt;Example&lt;/a&gt;';\n }\n return $return;\n}, 10, 3 );\n</code></pre>\n\n<p>But I have a feeling that you want to modify the URL of the comment author. If that's the case, we see that <code>get_comment_author_link()</code> calls <a href=\"https://developer.wordpress.org/reference/functions/get_comment_author_url/\" rel=\"nofollow noreferrer\"><code>get_comment_author_url()</code></a> to determine the author.</p>\n\n<p>And in that function we see that it returns the filtered results of <a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author_url/\" rel=\"nofollow noreferrer\"><code>get_comment_author_url</code></a>.</p>\n\n<p>So if you want to change the URL of the comment author link, you could do something like:</p>\n\n<pre><code>add_filter( 'get_comment_author_url', function( $url, $id, $comment ){\n if( 'example' === $comment-&gt;comment_author ) {\n $url = 'https://example.com/';\n }\n return $url;\n}, 10, 3 );\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141089/" ]
I have some code that works to display the children of a single page. I'm using this to display the children of a page in my footer. ``` $args = [ 'post_type'=>'page', //this is the custom post type 'child_of'=> '1452', ]; // we get an array of posts objects $posts = get_posts($args); // start our string $str = '<ul>'; // then we create an option for each post foreach($posts as $key=>$post){ $str .= '<li><a href=" '.get_permalink($post).' ">'.$post->post_title.'</a> </li>'; } $str .= '</ul>'; echo $str; } ``` But I want to display the children of several pages - and when I try to use several instances of the code, of course, it displays only the first ID. I've tried changing this into a function - but I can't get it to work. This is probably a very stupid question, but I'm a small-time PHP hack. --- EDIT: I've just seen that it is not only pulling children from the page ID I have specified, it's pulling a few from everywhere. Very strange.
The other two answers probably answer your question, but here's a way look at WordPress source code to be able to determine for yourself whether a certain hook exists for your purposes. You ask whether there is a hook for the comment author link. So let's look at the source for that function: [`comment_author_link()`](https://developer.wordpress.org/reference/functions/comment_author_link/). We see that there's not really much to that function. It just echos the output of [`get_comment_author_link()`](https://developer.wordpress.org/reference/functions/get_comment_author_link/). So let's look at that function. It does some stuff and then returns the filtered results of [`get_comment_author_link`](https://developer.wordpress.org/reference/hooks/get_comment_author_link/). So you could use that filter to modify the output of `comment_author_link()`. ``` add_filter( 'get_comment_author_link', function( $return, $author, $comment_id ){ if( 'example' === $author ) { $return = '<a href="https://example.com/">Example</a>'; } return $return; }, 10, 3 ); ``` But I have a feeling that you want to modify the URL of the comment author. If that's the case, we see that `get_comment_author_link()` calls [`get_comment_author_url()`](https://developer.wordpress.org/reference/functions/get_comment_author_url/) to determine the author. And in that function we see that it returns the filtered results of [`get_comment_author_url`](https://developer.wordpress.org/reference/hooks/get_comment_author_url/). So if you want to change the URL of the comment author link, you could do something like: ``` add_filter( 'get_comment_author_url', function( $url, $id, $comment ){ if( 'example' === $comment->comment_author ) { $url = 'https://example.com/'; } return $url; }, 10, 3 ); ```
299,753
<p>I want to check if a term object is in an get_terms array, but i really can't figure out how to do it.</p> <pre><code>$subcat_terms = get_terms([ 'taxonomy' =&gt; 'product_cat' ]); </code></pre> <p>$subcat_terms generates an array like this:</p> <pre><code>array (size=3) 0 =&gt; object(WP_Term)[10551] public 'term_id' =&gt; int 16 public 'name' =&gt; string 'Hardware' (length=8) public 'slug' =&gt; string 'hardware' (length=8) public 'term_group' =&gt; int 0 public 'term_taxonomy_id' =&gt; int 16 public 'taxonomy' =&gt; string 'product_cat' (length=11) public 'description' =&gt; string '' (length=0) public 'parent' =&gt; int 0 public 'count' =&gt; int 4 public 'filter' =&gt; string 'raw' (length=3) public 'meta_value' =&gt; string '0' (length=1) </code></pre> <p>I tried to check with the php function in_array, but as it has objects, i don't know how to do this, i would like to check by the term object number or if possible by the term slug. I'll be grateful if someone helps me.</p>
[ { "answer_id": 299755, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>A simple <code>foreach</code> loop can be used to check if a certain <code>slug</code> (or <code>term_id</code> or any other property) is in the results returned by <code>get_terms()</code>.</p>\n\n<p>In the following example, <code>$special_term_slugs</code> holds the slugs we'd like to search for. I used an array here so that we can search for multiple slugs, though it's just fine to use only a single slug.</p>\n\n<p>We get all of the terms for the desired taxonomy, <code>product_cat</code>, in this case.</p>\n\n<p>If results are returned, we iterate through them checking to see if the current term object matches one of the slugs defined in our <code>$special_term_slugs</code> array. </p>\n\n<pre><code>// Array of term slugs to check for. Customize as needed.\n$special_term_slugs = [\n 'hardware',\n];\n\n// Attempt to get the terms.\n$subcat_terms = get_terms( [\n 'taxonomy' =&gt; 'product_cat'\n] );\n\n// If we get results, search for our special term slugs.\nif ( is_array( $subcat_terms ) ) {\n foreach ( $subcat_terms as $subcat_term ) {\n if ( in_array( $subcat_term-&gt;slug, $special_term_slugs ) ) {\n // Special term was found. Do something...\n\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 299757, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 4, "selected": true, "text": "<p>WordPress has the <code>wp_list_pluck</code> function, which can be helpful here. We can make an array of just term IDs from the array of objects like:</p>\n\n<pre><code>$term_ids = wp_list_pluck( $subcat_terms, 'term_id' );\n</code></pre>\n\n<p>Then we can check <code>in_array</code>:</p>\n\n<pre><code>$this_id = 42;\nif( in_array( $this_id, $term_ids ) ){ // do something }\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111513/" ]
I want to check if a term object is in an get\_terms array, but i really can't figure out how to do it. ``` $subcat_terms = get_terms([ 'taxonomy' => 'product_cat' ]); ``` $subcat\_terms generates an array like this: ``` array (size=3) 0 => object(WP_Term)[10551] public 'term_id' => int 16 public 'name' => string 'Hardware' (length=8) public 'slug' => string 'hardware' (length=8) public 'term_group' => int 0 public 'term_taxonomy_id' => int 16 public 'taxonomy' => string 'product_cat' (length=11) public 'description' => string '' (length=0) public 'parent' => int 0 public 'count' => int 4 public 'filter' => string 'raw' (length=3) public 'meta_value' => string '0' (length=1) ``` I tried to check with the php function in\_array, but as it has objects, i don't know how to do this, i would like to check by the term object number or if possible by the term slug. I'll be grateful if someone helps me.
WordPress has the `wp_list_pluck` function, which can be helpful here. We can make an array of just term IDs from the array of objects like: ``` $term_ids = wp_list_pluck( $subcat_terms, 'term_id' ); ``` Then we can check `in_array`: ``` $this_id = 42; if( in_array( $this_id, $term_ids ) ){ // do something } ```
299,783
<p>I want to add a widget to my wordpress site, but i can't see it in the back-end of wordpress. I know that i am doing something wrong. The template doesent have a header.php and a footer.php</p> <p>I did put the widget in the functions.php but then i want the header.php. In the header.php i want the widget to appear on the header ofcource. </p>
[ { "answer_id": 299755, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>A simple <code>foreach</code> loop can be used to check if a certain <code>slug</code> (or <code>term_id</code> or any other property) is in the results returned by <code>get_terms()</code>.</p>\n\n<p>In the following example, <code>$special_term_slugs</code> holds the slugs we'd like to search for. I used an array here so that we can search for multiple slugs, though it's just fine to use only a single slug.</p>\n\n<p>We get all of the terms for the desired taxonomy, <code>product_cat</code>, in this case.</p>\n\n<p>If results are returned, we iterate through them checking to see if the current term object matches one of the slugs defined in our <code>$special_term_slugs</code> array. </p>\n\n<pre><code>// Array of term slugs to check for. Customize as needed.\n$special_term_slugs = [\n 'hardware',\n];\n\n// Attempt to get the terms.\n$subcat_terms = get_terms( [\n 'taxonomy' =&gt; 'product_cat'\n] );\n\n// If we get results, search for our special term slugs.\nif ( is_array( $subcat_terms ) ) {\n foreach ( $subcat_terms as $subcat_term ) {\n if ( in_array( $subcat_term-&gt;slug, $special_term_slugs ) ) {\n // Special term was found. Do something...\n\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 299757, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 4, "selected": true, "text": "<p>WordPress has the <code>wp_list_pluck</code> function, which can be helpful here. We can make an array of just term IDs from the array of objects like:</p>\n\n<pre><code>$term_ids = wp_list_pluck( $subcat_terms, 'term_id' );\n</code></pre>\n\n<p>Then we can check <code>in_array</code>:</p>\n\n<pre><code>$this_id = 42;\nif( in_array( $this_id, $term_ids ) ){ // do something }\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299783", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140728/" ]
I want to add a widget to my wordpress site, but i can't see it in the back-end of wordpress. I know that i am doing something wrong. The template doesent have a header.php and a footer.php I did put the widget in the functions.php but then i want the header.php. In the header.php i want the widget to appear on the header ofcource.
WordPress has the `wp_list_pluck` function, which can be helpful here. We can make an array of just term IDs from the array of objects like: ``` $term_ids = wp_list_pluck( $subcat_terms, 'term_id' ); ``` Then we can check `in_array`: ``` $this_id = 42; if( in_array( $this_id, $term_ids ) ){ // do something } ```
299,817
<p>For starters, I'm not a programmer but I'm good at cut and paste. :) I want to create a drop down list that displays each post and I've done that by putting this in my functions.php child theme file using this code: </p> <pre><code>function wpb_recentposts_dropdown() { $string .= '&lt;select id="rpdropdown"&gt; &lt;option value="" selected&gt;Select a Post&lt;option&gt;'; $args = array( 'numberposts' =&gt; '5', 'post_status' =&gt; 'publish' ); $recent_posts = wp_get_recent_posts($args); foreach( $recent_posts as $recent ){ $string .= '&lt;option value="' . get_permalink($recent["ID"]) . '"&gt;' . $recent["post_title"].'&lt;/option&gt; '; } $string .= '&lt;/select&gt; &lt;script type="text/javascript"&gt; var urlmenu = document.getElementById( "rpdropdown" ); urlmenu.onchange = function() { window.open( this.options[ this.selectedIndex ].value, "_self" ); }; &lt;/script&gt;'; return $string; } add_shortcode('rp_dropdown', 'wpb_recentposts_dropdown'); add_filter('widget_text','do_shortcode'); </code></pre> <p>And I use the short code [rp_dropdown] in my widget and it works. The problem is it displays posts from every category. I need for it to display a specific category and I also would like it to be alphabetical. Can someone please tell me how to make this happen in layman's terms? Thank you!</p>
[ { "answer_id": 299813, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I want similar design for mainsite.com/support. Should I have to create a new theme for this site?</p>\n</blockquote>\n\n<p>If you can reuse the existing theme great, if you can create a child theme great, <strong>it's up to you and there is no correct answer here</strong></p>\n\n<blockquote>\n <p>Right now, I used the same theme but front-page.php is taking over homepage of this subsite but I want mainsite.com/support show blog posts.</p>\n</blockquote>\n\n<p>Have you considered not using a subsite and having a blogs page named <code>support</code>? Or copying the theme and not using <code>front-page.php</code>?</p>\n\n<blockquote>\n <p>Another issue is, I don't want woocommerce and some other plugins for this subsite. I realize that only way to disable plugin on subsite is adding some code in functions.php, which means I need to make seperate theme for subsite ?</p>\n</blockquote>\n\n<p>This suggests you've not setup the site at all, that's not how multisites work. To disable a plugin on a site you go to plugins and click disable. Multisites are no different.</p>\n\n<p>If on the other hand you've put WooCommerce inside your theme, and not in a plugin, then that is a major grave mistake. Remove WooCommerce and install it as a plugin as it's supposed to be installed. Themes are for templates and visuals, you should not embed plugins inside them</p>\n" }, { "answer_id": 299815, "author": "Nigel", "author_id": 66151, "author_profile": "https://wordpress.stackexchange.com/users/66151", "pm_score": 1, "selected": false, "text": "<p>I was stuck at this for hours. But apparently solution is more easier than I had expected.</p>\n\n<p>I don't have to create new theme for the subsite.</p>\n\n<p>To make subsite homepage show blog posts instead of custom <code>front-page.php</code>, I went to Settings > Reading and selected static page and set posts page to \"Blog\" and left homepage with nothing selected.</p>\n\n<p>To enable plugin management for individual sites, I went to Network Settings and checked \"Enable administrations menus\".</p>\n\n<p>Now I can manage plugin for the subsite without have to add any specific codes to <code>functions.php</code>.</p>\n\n<p>Since Woocommerce is going to be disabled in the subsite, only change I had to make is to update sections of code in the theme that is relying on woocommerce functions ( such as title section in <code>header.php</code> ) to check if Woocommerce is active. </p>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299817", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116037/" ]
For starters, I'm not a programmer but I'm good at cut and paste. :) I want to create a drop down list that displays each post and I've done that by putting this in my functions.php child theme file using this code: ``` function wpb_recentposts_dropdown() { $string .= '<select id="rpdropdown"> <option value="" selected>Select a Post<option>'; $args = array( 'numberposts' => '5', 'post_status' => 'publish' ); $recent_posts = wp_get_recent_posts($args); foreach( $recent_posts as $recent ){ $string .= '<option value="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</option> '; } $string .= '</select> <script type="text/javascript"> var urlmenu = document.getElementById( "rpdropdown" ); urlmenu.onchange = function() { window.open( this.options[ this.selectedIndex ].value, "_self" ); }; </script>'; return $string; } add_shortcode('rp_dropdown', 'wpb_recentposts_dropdown'); add_filter('widget_text','do_shortcode'); ``` And I use the short code [rp\_dropdown] in my widget and it works. The problem is it displays posts from every category. I need for it to display a specific category and I also would like it to be alphabetical. Can someone please tell me how to make this happen in layman's terms? Thank you!
I was stuck at this for hours. But apparently solution is more easier than I had expected. I don't have to create new theme for the subsite. To make subsite homepage show blog posts instead of custom `front-page.php`, I went to Settings > Reading and selected static page and set posts page to "Blog" and left homepage with nothing selected. To enable plugin management for individual sites, I went to Network Settings and checked "Enable administrations menus". Now I can manage plugin for the subsite without have to add any specific codes to `functions.php`. Since Woocommerce is going to be disabled in the subsite, only change I had to make is to update sections of code in the theme that is relying on woocommerce functions ( such as title section in `header.php` ) to check if Woocommerce is active.
299,820
<p>I have this code in a page of my custom theme:</p> <pre><code>$args = array( 'public' =&gt; true, '_builtin' =&gt; false ); $output = 'names'; // names or objects, note names is the default $operator = 'and'; // 'and' or 'or' $post_types = get_post_types( $args, $output, $operator ); </code></pre> <p>This code if loaded in a wp-admin page.</p> <p>The problem is that I want to load all types of post, I tried changing the built in but it does not work. I want to get the default post of wordpress and the custom post type as woocomerce products. Does someone help me? Thank you!</p>
[ { "answer_id": 299822, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>First of all, you don't need to create variables just to pass them as arguments when calling a function.</p>\n\n<p>And getting back to your problem... You pass 'AND' as last argument, so the conditions will be joined with 'AND' - so you will get only post types that are public AND _builtin.</p>\n\n<p>If you want to get all public OR _builtin post types, then you should use OR operator:</p>\n\n<pre><code>$post_types = get_post_types( array('public' =&gt; true, '_builtin' =&gt; true), 'names', 'or' ); \n</code></pre>\n\n<p>But if you want to get all registered post types (not all of them have to be public), then this code will help (you don't wont any conditions in there):</p>\n\n<pre><code>$post_types = get_post_types( array(), 'names' ); \n</code></pre>\n" }, { "answer_id": 299825, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>Custom post types can only be registered on the <code>init</code> hook. So if you're trying to get the post types before the <code>init</code> hook, you will only ever get the built-in ones.</p>\n\n<p>To get custom post types, you need to use a hook after <code>init</code>, or later on <code>init</code> than the custom post types were registered.</p>\n\n<pre><code>function wpse_func() {\n $args = array(\n 'public' =&gt; true,\n '_builtin' =&gt; false,\n ];\n $post_types = get_post_types( $args );\n}\nadd_action( 'init', 'wpse_func', PHP_INT_MAX );\n//* Or\nadd_action( 'wp_loaded', 'wpse_func' );\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299820", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111714/" ]
I have this code in a page of my custom theme: ``` $args = array( 'public' => true, '_builtin' => false ); $output = 'names'; // names or objects, note names is the default $operator = 'and'; // 'and' or 'or' $post_types = get_post_types( $args, $output, $operator ); ``` This code if loaded in a wp-admin page. The problem is that I want to load all types of post, I tried changing the built in but it does not work. I want to get the default post of wordpress and the custom post type as woocomerce products. Does someone help me? Thank you!
Custom post types can only be registered on the `init` hook. So if you're trying to get the post types before the `init` hook, you will only ever get the built-in ones. To get custom post types, you need to use a hook after `init`, or later on `init` than the custom post types were registered. ``` function wpse_func() { $args = array( 'public' => true, '_builtin' => false, ]; $post_types = get_post_types( $args ); } add_action( 'init', 'wpse_func', PHP_INT_MAX ); //* Or add_action( 'wp_loaded', 'wpse_func' ); ```
299,824
<p>[LAST UPDATE]</p> <p>Using get_nav_menu_locations() I'm able to find all menu locations provided by theme and relative menu assigned.</p> <p>I'm already able to see if a specific menu contains an item related to a page.</p> <p>Now the problem is to extract a valid menu item from an istance of WP_Post.</p> <p>Tried this</p> <pre><code> $item = array( "menu-item-title" =&gt; $page-&gt;post_title, "menu-item-object" =&gt; "page", "menu-item-type" =&gt; "post_type", "menu-item-object_id" =&gt; $page-&gt;ID, "menu-item-parent_id" =&gt; "0", "menu-item-db_id" =&gt; "0", "menu-item-url" =&gt; get_permalink( $page-&gt;ID ) ); wp_update_nav_menu_item($idmenu, 0, $item); </code></pre> <p>But the new item causes some error and has no reference to page:</p> <p><a href="https://i.stack.imgur.com/UOiEm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UOiEm.png" alt="enter image description here"></a></p> <p>===================</p> <p>I'm trying to add a page to main menu (frontend). </p> <p>Here is what I tried:</p> <pre><code>public function paginaAMenu($page){ $menu_check = menu_page_url($page-&gt;slug, 0); if($menu_check == ""){ $menu = add_menu_page($page-&gt;title, $page-&gt;title, 'read', $page-&gt;slug); } } </code></pre> <p>But nothing happens. Maybe I miss what add_menu_page is for and I would like to know how to achieve my goal.</p> <p>To be clearer this is what I've to do by dashboard in section <strong>Appearence</strong> > <strong>Menu</strong> in order to add standard page link to 'Main Menu':</p> <p><a href="https://i.stack.imgur.com/i3g2m.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i3g2m.gif" alt="dashboard interaction"></a></p> <p>I'd like to do the exact same thing but programmatically in a plugin that create some shortcodes, create some pages containing these shortcodes and should link these pages in the main menu of the website. I just miss this last thing.</p> <p>===================</p> <p>In this specific case menu position provided by theme is Main Menu and menu assigned is Main Menu</p> <p><a href="https://i.stack.imgur.com/JDp42.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JDp42.png" alt="menu positions"></a></p> <p>I'd like to do it dinamically, As I do in dashboard where I don't need to manually select theme position or menu assigned.</p> <p>Taking a look at network tab in Chrome developer tools I can see the ajax call that add item to menu:</p> <pre><code> POST: http://wpsped.svi/wp-admin/admin-ajax.php action: add-menu-item menu: 3 menu-settings-column-nonce: 9f6fe75dca menu-item[-1][menu-item-object-id]: 79 menu-item[-1][menu-item-db-id]: 0 menu-item[-1][menu-item-object]: page menu-item[-1][menu-item-parent-id]: 0 menu-item[-1][menu-item-type]: post_type menu-item[-1][menu-item-title]: Accedi menu-item[-1][menu-item-url]: http://wpsped.svi/accedi/ menu-item[-1][menu-item-target]: menu-item[-1][menu-item-classes]: menu-item[-1][menu-item-xfn]: </code></pre> <p>I hope for a less hackish way to do it that doesn't involve ajax requests. </p>
[ { "answer_id": 299835, "author": "Pabamato", "author_id": 60079, "author_profile": "https://wordpress.stackexchange.com/users/60079", "pm_score": 0, "selected": false, "text": "<p>I asume you want to add a new item to the main menu on a given page:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 );\nfunction your_custom_menu_item ( $items, $args ) {\n // is_page() params: Page ID, title, slug, or array of such.\n if (is_page( 'page-slug' ) &amp;&amp; $args-&gt;theme_location == 'primary') {\n $items .= '&lt;li&gt;Show whatever&lt;/li&gt;';\n }\n return $items;\n}\n</code></pre>\n\n<p>Source: <a href=\"http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/</a></p>\n" }, { "answer_id": 299917, "author": "assistbss", "author_id": 73249, "author_profile": "https://wordpress.stackexchange.com/users/73249", "pm_score": 2, "selected": true, "text": "<p>In order to know what are locations provided by theme for menus:</p>\n\n<pre><code>$locations = get_nav_menu_locations();\n</code></pre>\n\n<p>This command will return an associative array that has for keys the locations and for values the ids of menu assigned to that location.</p>\n\n<p>To know what pages are associated to a menu: </p>\n\n<pre><code>$idmenu = $locations['main-menu'];\n$menu = wp_get_nav_menu_object( $idmenu );\n$pagesItem = wp_get_nav_menu_items( $menu, [\"object\"=&gt;\"page\"] );\n</code></pre>\n\n<p>In order to generate a link to a page in a menu</p>\n\n<pre><code> $pageItem = array(\n \"menu-item-object-id\" =&gt; $page-&gt;ID,\n \"menu-item-object\" =&gt; \"page\",\n \"menu-item-type\" =&gt; \"post_type\",\n \"menu-item-title\" =&gt; $page-&gt;post_title,\n \"menu-item-url\" =&gt; get_permalink( $page-&gt;ID ),\n \"menu-item-status\" =&gt; \"publish\",\n );\n\n wp_update_nav_menu_item($idmenu, 0, $pageItem);\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73249/" ]
[LAST UPDATE] Using get\_nav\_menu\_locations() I'm able to find all menu locations provided by theme and relative menu assigned. I'm already able to see if a specific menu contains an item related to a page. Now the problem is to extract a valid menu item from an istance of WP\_Post. Tried this ``` $item = array( "menu-item-title" => $page->post_title, "menu-item-object" => "page", "menu-item-type" => "post_type", "menu-item-object_id" => $page->ID, "menu-item-parent_id" => "0", "menu-item-db_id" => "0", "menu-item-url" => get_permalink( $page->ID ) ); wp_update_nav_menu_item($idmenu, 0, $item); ``` But the new item causes some error and has no reference to page: [![enter image description here](https://i.stack.imgur.com/UOiEm.png)](https://i.stack.imgur.com/UOiEm.png) =================== I'm trying to add a page to main menu (frontend). Here is what I tried: ``` public function paginaAMenu($page){ $menu_check = menu_page_url($page->slug, 0); if($menu_check == ""){ $menu = add_menu_page($page->title, $page->title, 'read', $page->slug); } } ``` But nothing happens. Maybe I miss what add\_menu\_page is for and I would like to know how to achieve my goal. To be clearer this is what I've to do by dashboard in section **Appearence** > **Menu** in order to add standard page link to 'Main Menu': [![dashboard interaction](https://i.stack.imgur.com/i3g2m.gif)](https://i.stack.imgur.com/i3g2m.gif) I'd like to do the exact same thing but programmatically in a plugin that create some shortcodes, create some pages containing these shortcodes and should link these pages in the main menu of the website. I just miss this last thing. =================== In this specific case menu position provided by theme is Main Menu and menu assigned is Main Menu [![menu positions](https://i.stack.imgur.com/JDp42.png)](https://i.stack.imgur.com/JDp42.png) I'd like to do it dinamically, As I do in dashboard where I don't need to manually select theme position or menu assigned. Taking a look at network tab in Chrome developer tools I can see the ajax call that add item to menu: ``` POST: http://wpsped.svi/wp-admin/admin-ajax.php action: add-menu-item menu: 3 menu-settings-column-nonce: 9f6fe75dca menu-item[-1][menu-item-object-id]: 79 menu-item[-1][menu-item-db-id]: 0 menu-item[-1][menu-item-object]: page menu-item[-1][menu-item-parent-id]: 0 menu-item[-1][menu-item-type]: post_type menu-item[-1][menu-item-title]: Accedi menu-item[-1][menu-item-url]: http://wpsped.svi/accedi/ menu-item[-1][menu-item-target]: menu-item[-1][menu-item-classes]: menu-item[-1][menu-item-xfn]: ``` I hope for a less hackish way to do it that doesn't involve ajax requests.
In order to know what are locations provided by theme for menus: ``` $locations = get_nav_menu_locations(); ``` This command will return an associative array that has for keys the locations and for values the ids of menu assigned to that location. To know what pages are associated to a menu: ``` $idmenu = $locations['main-menu']; $menu = wp_get_nav_menu_object( $idmenu ); $pagesItem = wp_get_nav_menu_items( $menu, ["object"=>"page"] ); ``` In order to generate a link to a page in a menu ``` $pageItem = array( "menu-item-object-id" => $page->ID, "menu-item-object" => "page", "menu-item-type" => "post_type", "menu-item-title" => $page->post_title, "menu-item-url" => get_permalink( $page->ID ), "menu-item-status" => "publish", ); wp_update_nav_menu_item($idmenu, 0, $pageItem); ```
299,826
<p>How would you go about setting the correct language returned in AJAX calls, when you are not using any plugin? </p> <p>All other strings in page work fine just by defining WPLANG to a proper locale. </p> <p>Example: </p> <pre><code>function lpml_get_quiz_result_callback() { // do plenty of stuff before this // this is always returned in original english language, even if I setlocale before or load textdomain manually. $message = __('Some english defined string', 'my_txt_domain'); $status = true; echo json_encode(array('status' =&gt; $status, 'message' =&gt; $message)); die(); } add_action('wp_ajax_lpml_get_quiz_result', 'lpml_get_quiz_result_callback'); add_action('wp_ajax_nopriv_lpml_get_quiz_result', 'lpml_get_quiz_result_callback'); </code></pre> <p>I checked these questions: <a href="https://wordpress.stackexchange.com/questions/121732/gettext-does-not-translate-when-called-in-ajax">q1</a>, <a href="https://wordpress.stackexchange.com/questions/121732/gettext-does-not-translate-when-called-in-ajax">q2</a>, but none applies / solves my case. :/</p> <p>I tried setting locale and loading textdomain before using __() strings in ajax, but to no avail (tried it just before, and also in admin_init hook for DOING_AJAX), both did not work. </p> <pre><code>setlocale(LC_ALL, $_POST['lang']); load_theme_textdomain( 'my_txt_domain', get_template_directory() . '/languages' ); </code></pre> <p>Any tips appreciated! </p>
[ { "answer_id": 299835, "author": "Pabamato", "author_id": 60079, "author_profile": "https://wordpress.stackexchange.com/users/60079", "pm_score": 0, "selected": false, "text": "<p>I asume you want to add a new item to the main menu on a given page:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 );\nfunction your_custom_menu_item ( $items, $args ) {\n // is_page() params: Page ID, title, slug, or array of such.\n if (is_page( 'page-slug' ) &amp;&amp; $args-&gt;theme_location == 'primary') {\n $items .= '&lt;li&gt;Show whatever&lt;/li&gt;';\n }\n return $items;\n}\n</code></pre>\n\n<p>Source: <a href=\"http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/</a></p>\n" }, { "answer_id": 299917, "author": "assistbss", "author_id": 73249, "author_profile": "https://wordpress.stackexchange.com/users/73249", "pm_score": 2, "selected": true, "text": "<p>In order to know what are locations provided by theme for menus:</p>\n\n<pre><code>$locations = get_nav_menu_locations();\n</code></pre>\n\n<p>This command will return an associative array that has for keys the locations and for values the ids of menu assigned to that location.</p>\n\n<p>To know what pages are associated to a menu: </p>\n\n<pre><code>$idmenu = $locations['main-menu'];\n$menu = wp_get_nav_menu_object( $idmenu );\n$pagesItem = wp_get_nav_menu_items( $menu, [\"object\"=&gt;\"page\"] );\n</code></pre>\n\n<p>In order to generate a link to a page in a menu</p>\n\n<pre><code> $pageItem = array(\n \"menu-item-object-id\" =&gt; $page-&gt;ID,\n \"menu-item-object\" =&gt; \"page\",\n \"menu-item-type\" =&gt; \"post_type\",\n \"menu-item-title\" =&gt; $page-&gt;post_title,\n \"menu-item-url\" =&gt; get_permalink( $page-&gt;ID ),\n \"menu-item-status\" =&gt; \"publish\",\n );\n\n wp_update_nav_menu_item($idmenu, 0, $pageItem);\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299826", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65585/" ]
How would you go about setting the correct language returned in AJAX calls, when you are not using any plugin? All other strings in page work fine just by defining WPLANG to a proper locale. Example: ``` function lpml_get_quiz_result_callback() { // do plenty of stuff before this // this is always returned in original english language, even if I setlocale before or load textdomain manually. $message = __('Some english defined string', 'my_txt_domain'); $status = true; echo json_encode(array('status' => $status, 'message' => $message)); die(); } add_action('wp_ajax_lpml_get_quiz_result', 'lpml_get_quiz_result_callback'); add_action('wp_ajax_nopriv_lpml_get_quiz_result', 'lpml_get_quiz_result_callback'); ``` I checked these questions: [q1](https://wordpress.stackexchange.com/questions/121732/gettext-does-not-translate-when-called-in-ajax), [q2](https://wordpress.stackexchange.com/questions/121732/gettext-does-not-translate-when-called-in-ajax), but none applies / solves my case. :/ I tried setting locale and loading textdomain before using \_\_() strings in ajax, but to no avail (tried it just before, and also in admin\_init hook for DOING\_AJAX), both did not work. ``` setlocale(LC_ALL, $_POST['lang']); load_theme_textdomain( 'my_txt_domain', get_template_directory() . '/languages' ); ``` Any tips appreciated!
In order to know what are locations provided by theme for menus: ``` $locations = get_nav_menu_locations(); ``` This command will return an associative array that has for keys the locations and for values the ids of menu assigned to that location. To know what pages are associated to a menu: ``` $idmenu = $locations['main-menu']; $menu = wp_get_nav_menu_object( $idmenu ); $pagesItem = wp_get_nav_menu_items( $menu, ["object"=>"page"] ); ``` In order to generate a link to a page in a menu ``` $pageItem = array( "menu-item-object-id" => $page->ID, "menu-item-object" => "page", "menu-item-type" => "post_type", "menu-item-title" => $page->post_title, "menu-item-url" => get_permalink( $page->ID ), "menu-item-status" => "publish", ); wp_update_nav_menu_item($idmenu, 0, $pageItem); ```
299,836
<p>Consider the following class.</p> <pre><code>&lt;?php class MCQAcademy_Endpoint extends WP_REST_Controller { /** * Register the routes for the objects of the controller. */ public function register_routes() { $version = '1'; $namespace = 'custompath/v' . $version; $base = 'endpointbase'; register_rest_route( $namespace, '/' . $base, array( array( 'methods' =&gt; WP_REST_Server::READABLE, 'callback' =&gt; array( $this, 'get_items' ), 'permission_callback' =&gt; array( $this, 'get_items_permissions_check' ), 'args' =&gt; array(), ) ) ); } /** * */ public function get_items( $request ) { $rs = array( 'data' =&gt; array(), 'request' =&gt; array( 'lang' =&gt; 'en', ), ); $args = array(); $items = get_posts( $args ); foreach( $items as $item ) { $itemdata = $this-&gt;prepare_item_for_response( $item, $request ); $rs['data'][] = $this-&gt;prepare_response_for_collection( $itemdata ); } $rs['wp_get_current_user'] = wp_get_current_user(); // Does not output as expected return new WP_REST_Response( $rs, 200 ); } /** * Check if a given request has access to get items */ public function get_items_permissions_check( $request ) { return true; // to make readable by all } /** * Prepare the item for create or update operation */ protected function prepare_item_for_database( $request ) { return $request; } /** * Prepare the item for the REST response */ public function prepare_item_for_response( $item, $request ) { $data = array( 'ID' =&gt; $item-&gt;ID, 'post_content' =&gt; wpautop($item-&gt;post_content), 'post_title' =&gt; $item-&gt;post_title, ); return $data; } /** * Get the query params for collections */ public function get_collection_params() { return array( 'page' =&gt; array( 'description' =&gt; 'Current page of the collection.', 'type' =&gt; 'integer', 'default' =&gt; 1, 'sanitize_callback' =&gt; 'absint', ), 'per_page' =&gt; array( 'description' =&gt; 'Maximum number of items to be returned in result set.', 'type' =&gt; 'integer', 'default' =&gt; 10, 'sanitize_callback' =&gt; 'absint', ), 'search' =&gt; array( 'description' =&gt; 'Limit results to those matching a string.', 'type' =&gt; 'string', 'sanitize_callback' =&gt; 'sanitize_text_field', ), ); } // Register our REST Server public function hook_rest_server(){ add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } } $myEndpoint = new MCQAcademy_Endpoint(); $myEndpoint-&gt;hook_rest_server(); </code></pre> <p>Everything is going well except calling the <code>wp_get_current_user()</code> function in the <code>get_items()</code> function return empty user even though the user is <code>logged in</code> in the website. </p>
[ { "answer_id": 299843, "author": "Pabamato", "author_id": 60079, "author_profile": "https://wordpress.stackexchange.com/users/60079", "pm_score": 4, "selected": false, "text": "<p>Logged in on your website doesn't mean the user is authenticated in the REST API request, that's why you are not getting the correct user or a <code>Id = 0</code></p>\n<p>Please take a look to the REST API authentication methods on the docs:<br />\n<a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/</a></p>\n<blockquote>\n<p>For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress.</p>\n</blockquote>\n<p>For remote authentication I'd recommend the JWT plugin for a quick start:</p>\n<ul>\n<li><a href=\"https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/</a></li>\n</ul>\n<p>Or you can use the ones suggested on the docs:</p>\n<ul>\n<li><a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins</a></li>\n</ul>\n" }, { "answer_id": 329992, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 3, "selected": false, "text": "<p>To have a fully working code sample here comes a sample plugin on how to retrieve the current user's ID via REST.</p>\n\n<p><strong>my-plugin.php</strong></p>\n\n<pre><code>class MyPlugin {\n\n public function __construct() {\n\n add_action('wp_enqueue_scripts', [$this, 'scripts']);\n add_action('rest_api_init', [$this, 'rest']);\n }\n\n function scripts() {\n\n // Add JS.\n wp_enqueue_script('my-plugin', plugin_dir_url(__FILE__) . 'js/scripts.js', ['jquery'], NULL, TRUE);\n // Pass nonce to JS.\n wp_localize_script('my-plugin', 'MyPluginSettings', [\n 'nonce' =&gt; wp_create_nonce('wp_rest'),\n ]);\n }\n\n function rest() {\n\n // Register route.\n register_rest_route('my-plugin/v1', '/uid', [\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; [$this, 'rest_callback'],\n ]);\n }\n\n function rest_callback($data) {\n\n // Get current user ID.\n $data = [\n 'uid' =&gt; get_current_user_id(),\n ];\n\n $response = new WP_REST_Response($data, 200);\n // Set headers.\n $response-&gt;set_headers(['Cache-Control' =&gt; 'must-revalidate, no-cache, no-store, private']);\n\n return $response;\n }\n\n}\n\nnew MyPlugin();\n</code></pre>\n\n<p><strong>js/scripts.js</strong></p>\n\n<pre><code>(function($) {\n\n $(document).ready(function() {\n\n var settings = MyPluginSettings;\n\n $.ajax({\n url: '/wp-json/my-plugin/v1/uid',\n method: 'GET',\n beforeSend: function(xhr) {\n xhr.setRequestHeader('X-WP-Nonce', settings.nonce);\n }\n }).done(function(response) {\n\n // Will return your UID.\n console.log(response);\n });\n\n });\n\n})(jQuery);\n</code></pre>\n\n<hr>\n\n<p>Resource: <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/</a></p>\n" }, { "answer_id": 334555, "author": "user3308965", "author_id": 165235, "author_profile": "https://wordpress.stackexchange.com/users/165235", "pm_score": 1, "selected": false, "text": "<p><code>wp_get_current_user()</code> does not work because your user is not set perfectly. See below code in <code>/wp-includes/user.php</code> for reference.</p>\n\n<pre><code>if ( ! empty( $current_user ) ) {\n if ( $current_user instanceof WP_User ) {\n return $current_user;\n }\n\n // Upgrade stdClass to WP_User\n if ( is_object( $current_user ) &amp;&amp; isset( $current_user-&gt;ID ) ) {\n $cur_id = $current_user-&gt;ID;\n $current_user = null;\n wp_set_current_user( $cur_id );\n return $current_user;\n }\n\n // $current_user has a junk value. Force to WP_User with ID 0.\n $current_user = null;\n wp_set_current_user( 0 );\n return $current_user;\n}\n\nif ( defined( 'XMLRPC_REQUEST' ) &amp;&amp; XMLRPC_REQUEST ) {\n wp_set_current_user( 0 );\n return $current_user;\n}\n</code></pre>\n\n<p>All you need to do is wp_set_current_user( {user_id} ) at the start of your API.</p>\n" }, { "answer_id": 358042, "author": "John Dee", "author_id": 131224, "author_profile": "https://wordpress.stackexchange.com/users/131224", "pm_score": 3, "selected": false, "text": "<p>If an API call comes in that does not have a nonce set, WordPress will de-authenticate the request, killing the current user and making the request unauthenticated. This CSFR protection is automatic, and you don't have to do anything for it to work other than include the nonce.</p>\n\n<p>The way to solve this is to include a nonce. Something like this:</p>\n\n<pre><code>$_wpnonce = wp_create_nonce( 'wp_rest' );\necho \"&lt;input type = 'hidden' name = '_wpnonce' value = '$_wpnonce' /&gt;\";\n</code></pre>\n\n<p>And include it in your API request. The nonce must be called \"_wpnonce\" and the action must be \"wp_rest\" for the API to work. It can go in the URL or in the post body. </p>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130217/" ]
Consider the following class. ``` <?php class MCQAcademy_Endpoint extends WP_REST_Controller { /** * Register the routes for the objects of the controller. */ public function register_routes() { $version = '1'; $namespace = 'custompath/v' . $version; $base = 'endpointbase'; register_rest_route( $namespace, '/' . $base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => array(), ) ) ); } /** * */ public function get_items( $request ) { $rs = array( 'data' => array(), 'request' => array( 'lang' => 'en', ), ); $args = array(); $items = get_posts( $args ); foreach( $items as $item ) { $itemdata = $this->prepare_item_for_response( $item, $request ); $rs['data'][] = $this->prepare_response_for_collection( $itemdata ); } $rs['wp_get_current_user'] = wp_get_current_user(); // Does not output as expected return new WP_REST_Response( $rs, 200 ); } /** * Check if a given request has access to get items */ public function get_items_permissions_check( $request ) { return true; // to make readable by all } /** * Prepare the item for create or update operation */ protected function prepare_item_for_database( $request ) { return $request; } /** * Prepare the item for the REST response */ public function prepare_item_for_response( $item, $request ) { $data = array( 'ID' => $item->ID, 'post_content' => wpautop($item->post_content), 'post_title' => $item->post_title, ); return $data; } /** * Get the query params for collections */ public function get_collection_params() { return array( 'page' => array( 'description' => 'Current page of the collection.', 'type' => 'integer', 'default' => 1, 'sanitize_callback' => 'absint', ), 'per_page' => array( 'description' => 'Maximum number of items to be returned in result set.', 'type' => 'integer', 'default' => 10, 'sanitize_callback' => 'absint', ), 'search' => array( 'description' => 'Limit results to those matching a string.', 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), ); } // Register our REST Server public function hook_rest_server(){ add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } } $myEndpoint = new MCQAcademy_Endpoint(); $myEndpoint->hook_rest_server(); ``` Everything is going well except calling the `wp_get_current_user()` function in the `get_items()` function return empty user even though the user is `logged in` in the website.
Logged in on your website doesn't mean the user is authenticated in the REST API request, that's why you are not getting the correct user or a `Id = 0` Please take a look to the REST API authentication methods on the docs: <https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/> > > For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp\_rest. These can then be passed to the API via the \_wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress. > > > For remote authentication I'd recommend the JWT plugin for a quick start: * <https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/> Or you can use the ones suggested on the docs: * <https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins>
299,844
<p>I am working on a new theme for a site, but the majority of the posts don't have a featured image set. Throughout the new theme I am pulling in featured images using <code>the_post_thumbnail_url</code>. I am wondering if there is a function I can add to <code>functions.php</code> to override this url, globally, with a url to a placeholder image if there is no featured image assigned to the post.</p>
[ { "answer_id": 299845, "author": "Samuel Asor", "author_id": 84265, "author_profile": "https://wordpress.stackexchange.com/users/84265", "pm_score": 2, "selected": false, "text": "<p>Well, depending on the thumbnails you have defined, you could do a check if the post <em>\"has\"</em> a thumbnail, display it; but if it doesn't, you can show a default image stored somewhere in your theme's image directory, like so:</p>\n\n<pre><code>// Other code to fetch the post\nif ( has_post_thumbnail() ) {\n the_post_thumbnail('slide');\n}\nelse {\n &lt;img src=\"&lt;?php echo get_template_directory_uri() ?&gt;/images/default-image.jpg\" class=\"attachment-slide wp-post-image\"&gt;\n}\n</code></pre>\n\n<p>This is assuming you have already added the thumbnail <code>slide</code> like so:</p>\n\n<pre><code>add_image_size( 'slide', 500, 400, true ); // width=500, height=400\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 299847, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>If you know the URL of the placeholder image, you sure can do it.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"nofollow noreferrer\"><code>get_the_post_thumbnail_url()</code></a> function calls the <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_image_url()</code></a> function which in turns calls the\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_image_src()</code></a> function to get the source of the post thumbnail. <code>wp_get_attachment_url()</code> returns the result from <code>wp_get_attachment_image_src</code> filter. So we can use that filter to modify the result if there is no image and the size is 'post-thumbnail'.</p>\n\n<pre><code>namespace StackExchange\\WordPress;\n\nfunction image_src( $image, $attachment_id, $size, $icon ) {\n $default = [\n 'https://example.com/img.gif',\n ];\n return ( false === $image &amp;&amp; 'post-thumbnail' === $size ) ? $default : $image;\n}\n\\add_filter( 'wp_get_attachment_image_src', __NAMESPACE__ . '\\image_src', 10, 4 );\n</code></pre>\n" } ]
2018/04/04
[ "https://wordpress.stackexchange.com/questions/299844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38829/" ]
I am working on a new theme for a site, but the majority of the posts don't have a featured image set. Throughout the new theme I am pulling in featured images using `the_post_thumbnail_url`. I am wondering if there is a function I can add to `functions.php` to override this url, globally, with a url to a placeholder image if there is no featured image assigned to the post.
If you know the URL of the placeholder image, you sure can do it. [`get_the_post_thumbnail_url()`](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/) function calls the [`wp_get_attachment_image_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/) function which in turns calls the [`wp_get_attachment_image_src()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/) function to get the source of the post thumbnail. `wp_get_attachment_url()` returns the result from `wp_get_attachment_image_src` filter. So we can use that filter to modify the result if there is no image and the size is 'post-thumbnail'. ``` namespace StackExchange\WordPress; function image_src( $image, $attachment_id, $size, $icon ) { $default = [ 'https://example.com/img.gif', ]; return ( false === $image && 'post-thumbnail' === $size ) ? $default : $image; } \add_filter( 'wp_get_attachment_image_src', __NAMESPACE__ . '\image_src', 10, 4 ); ```
299,859
<p>I cannot get it so that my user role for a supplier can read the shipments post type. It shows up in their menu but when you click on it you get <em>you are not allowed to view this page</em> error message.</p> <p>It works if I <code>add_cap('read_posts')</code> but I don't want them to view the regular posts just the shipments post type.</p> <p>I have a suppliers user role with the following capabilities.</p> <pre><code>WP_Role Object ( [name] =&gt; supplier [capabilities] =&gt; Array ( [read] =&gt; 1 [edit_shipment] =&gt; 1 [read_shipment] =&gt; 1 [edit_others_shipments] =&gt; 1 [publish_shipments] =&gt; 1 [read_private_shipments] =&gt; 1 [edit_shipments] =&gt; 1 [create_shipment] =&gt; 1 [read_shipments] =&gt; 1 ) ) </code></pre> <p>And I have setup the post type for shipments with the following</p> <pre><code>function shipment_post_type() { $labels = array( 'name' =&gt; _x( 'Shipments', 'Post Type General Name', 'sage' ), 'singular_name' =&gt; _x( 'Shipment', 'Post Type Singular Name', 'sage' ), 'menu_name' =&gt; __( 'Shipments', 'sage' ), 'name_admin_bar' =&gt; __( 'Shipments', 'sage' ), 'archives' =&gt; __( 'Shipment Archives', 'sage' ), 'parent_item_colon' =&gt; __( 'Parent shipment:', 'sage' ), 'all_items' =&gt; __( 'All shipments', 'sage' ), 'add_new_item' =&gt; __( 'Add New shipment', 'sage' ), 'new_item' =&gt; __( 'New shipment', 'sage' ), 'edit_item' =&gt; __( 'Edit shipment', 'sage' ), 'update_item' =&gt; __( 'Update shipment', 'sage' ), 'view_item' =&gt; __( 'View shipment', 'sage' ), 'search_items' =&gt; __( 'Search shipments', 'sage' ), 'not_found' =&gt; __( 'Not found', 'sage' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'sage' ), 'featured_image' =&gt; __( 'Featured Image', 'sage' ), 'set_featured_image' =&gt; __( 'Set shipment image', 'sage' ), 'remove_featured_image' =&gt; __( 'Remove shipment image', 'sage' ), 'use_featured_image' =&gt; __( 'Use as shipment image', 'sage' ), 'insert_into_item' =&gt; __( 'Insert into shipment', 'sage' ), 'uploaded_to_this_item' =&gt; __( 'Uploaded to this shipment', 'sage' ), 'items_list' =&gt; __( 'shipments list', 'sage' ), 'items_list_navigation' =&gt; __( 'Constests list navigation', 'sage' ), 'filter_items_list' =&gt; __( 'Filter shipments list', 'sage' ), ); $args = array( 'label' =&gt; __( 'shipments', 'sage' ), 'description' =&gt; __( 'Manage all shipments, sweepstakes and giveaways.', 'sage' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'revisions' ), 'taxonomies' =&gt; array( '' ), 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-archive', 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; false, 'can_export' =&gt; true, 'has_archive' =&gt; false, 'exclude_from_search' =&gt; true, 'publicly_queryable' =&gt; true, 'map_meta_cap' =&gt; true, 'capabilities' =&gt; array( 'edit_post' =&gt; 'edit_shipment', 'read_post' =&gt; 'read_shipment', 'read_posts' =&gt; 'read_shipments', 'delete_post' =&gt; 'delete_shipment', 'delete_posts' =&gt; 'delete_shipments', 'edit_posts' =&gt; 'edit_shipments', 'edit_others_posts' =&gt; 'edit_others_shipments', 'publish_posts' =&gt; 'publish_shipments', 'read_private_posts' =&gt; 'read_private_shipments', 'create_posts' =&gt; 'create_shipments', ), ); register_post_type( 'shipment', $args ); } add_action( 'init', 'shipment_post_type', 0 ); </code></pre>
[ { "answer_id": 300478, "author": "Myles", "author_id": 141270, "author_profile": "https://wordpress.stackexchange.com/users/141270", "pm_score": 3, "selected": false, "text": "<p>Your custom post type looks like it's set up properly. It works on my test install. Try this instead of whatever add_role and add_cap code you're currently using. (For testing purposes only. Don't use it in production code, for reasons outlined below.) It's working for me:</p>\n\n<pre><code>function prefix_set_up_supplier_role(){\nremove_role( 'supplier' );\nadd_role( 'supplier', 'Supplier', array(\n 'read' =&gt; true,\n 'edit_shipment' =&gt; true,\n 'read_shipment' =&gt; true,\n 'read_shipments' =&gt; true,\n 'delete_shipment' =&gt; true,\n 'delete_shipments' =&gt; true,\n 'edit_shipments' =&gt; true,\n 'edit_others_shipments' =&gt; true,\n 'publish_shipments' =&gt; true,\n 'read_private_shipments' =&gt; true,\n 'create_shipments' =&gt; true,\n )\n);\n}\nadd_action( 'init', 'prefix_set_up_supplier_role' );\n</code></pre>\n\n<p>It's very important to remember that adding user roles and capabilities actually saves data to the database. So if you had a version of your code before that didn't quite work, then added something that would make it work, it might not have taken effect if there is still old data in your database. add_role() returns null if the role already exists in the database. For production code, you should actually be using the plugin activation and deactivation hooks for this stuff instead of running it every time, like this:</p>\n\n<pre><code>register_activation_hook( __FILE__, 'prefix_activate' );\nfunction prefix_activate(){\n add_role( 'supplier', 'Supplier', array(\n 'read' =&gt; true,\n 'edit_shipment' =&gt; true,\n 'read_shipment' =&gt; true,\n 'read_shipments' =&gt; true,\n 'delete_shipment' =&gt; true,\n 'delete_shipments' =&gt; true,\n 'edit_shipments' =&gt; true,\n 'edit_others_shipments' =&gt; true,\n 'publish_shipments' =&gt; true,\n 'read_private_shipments' =&gt; true,\n 'create_shipments' =&gt; true,\n )\n);\n}\n\nregister_deactivation_hook( __FILE__, 'prefix_deactivate' );\nfunction prefix_deactivate(){\n remove_role( 'supplier' );\n}\n</code></pre>\n" }, { "answer_id": 300704, "author": "Myles", "author_id": 141270, "author_profile": "https://wordpress.stackexchange.com/users/141270", "pm_score": 0, "selected": false, "text": "<p>In your role object, you have the capability 'create_shipment' where it should actually say 'create_shipments'. Seems like there might be an 's' missing in your code wherever you're adding that capability.</p>\n" }, { "answer_id": 300821, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p>You might try:</p>\n\n<pre><code>add_action( 'init', 'add_my_caps');\nfunction add_my_caps() {\n global $wp_roles;\n\n if ( isset($wp_roles) ) {\n $wp_roles-&gt;add_cap( 'editor', 'edit_shipment' );\n $wp_roles-&gt;add_cap( 'editor', 'read_shipment' );\n $wp_roles-&gt;add_cap( 'editor', 'delete_shipment' );\n $wp_roles-&gt;add_cap( 'editor', 'publish_shipments' );\n $wp_roles-&gt;add_cap( 'editor', 'edit_shipments' );\n $wp_roles-&gt;add_cap( 'editor', 'edit_others_shipments' );\n $wp_roles-&gt;add_cap( 'editor', 'delete_shipments' );\n $wp_roles-&gt;add_cap( 'editor', 'delete_others_shipments' );\n $wp_roles-&gt;add_cap( 'editor', 'read_private_shipments' );\n ....\n</code></pre>\n" }, { "answer_id": 300938, "author": "James George Dunn", "author_id": 66977, "author_profile": "https://wordpress.stackexchange.com/users/66977", "pm_score": 0, "selected": false, "text": "<p>Try this out. 'dms_document' is the custom post type.</p>\n\n<pre><code>function jgd_add_role_caps() {\n // Add the roles you'd like to administer the custom post types\n $roles = array(\n 'deity_user',\n 'admin_user'\n );\n\n // Loop through each role and assign capabilities\n foreach($roles as $the_role) { \n $role = get_role($the_role);\n\n $role-&gt;add_cap('read');\n $role-&gt;add_cap('read_dms_document');\n $role-&gt;add_cap('read_private_dms_documents');\n $role-&gt;add_cap('edit_dms_document');\n $role-&gt;add_cap('edit_dms_documents');\n $role-&gt;add_cap('edit_others_dms_documents');\n $role-&gt;add_cap('edit_published_dms_documents');\n $role-&gt;add_cap('publish_dms_documents');\n $role-&gt;add_cap('delete_others_dms_documents');\n $role-&gt;add_cap('delete_private_dms_documents');\n $role-&gt;add_cap('delete_dms_documents');\n $role-&gt;add_cap('delete_post_dms_documents');\n $role-&gt;add_cap('delete_published_dms_documents');\n $role-&gt;add_cap('delete_draft_dms_documents');\n $role-&gt;add_cap('delete_others_posts_dms_documents');\n $role-&gt;add_cap('delete_others_posts_dms_document');\n $role-&gt;add_cap('delete_posts_dms_documents');\n $role-&gt;add_cap('delete_posts_dms_document');\n }\n}\nadd_action('admin_init','jgd_add_role_caps', 999);\n</code></pre>\n" } ]
2018/04/05
[ "https://wordpress.stackexchange.com/questions/299859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92318/" ]
I cannot get it so that my user role for a supplier can read the shipments post type. It shows up in their menu but when you click on it you get *you are not allowed to view this page* error message. It works if I `add_cap('read_posts')` but I don't want them to view the regular posts just the shipments post type. I have a suppliers user role with the following capabilities. ``` WP_Role Object ( [name] => supplier [capabilities] => Array ( [read] => 1 [edit_shipment] => 1 [read_shipment] => 1 [edit_others_shipments] => 1 [publish_shipments] => 1 [read_private_shipments] => 1 [edit_shipments] => 1 [create_shipment] => 1 [read_shipments] => 1 ) ) ``` And I have setup the post type for shipments with the following ``` function shipment_post_type() { $labels = array( 'name' => _x( 'Shipments', 'Post Type General Name', 'sage' ), 'singular_name' => _x( 'Shipment', 'Post Type Singular Name', 'sage' ), 'menu_name' => __( 'Shipments', 'sage' ), 'name_admin_bar' => __( 'Shipments', 'sage' ), 'archives' => __( 'Shipment Archives', 'sage' ), 'parent_item_colon' => __( 'Parent shipment:', 'sage' ), 'all_items' => __( 'All shipments', 'sage' ), 'add_new_item' => __( 'Add New shipment', 'sage' ), 'new_item' => __( 'New shipment', 'sage' ), 'edit_item' => __( 'Edit shipment', 'sage' ), 'update_item' => __( 'Update shipment', 'sage' ), 'view_item' => __( 'View shipment', 'sage' ), 'search_items' => __( 'Search shipments', 'sage' ), 'not_found' => __( 'Not found', 'sage' ), 'not_found_in_trash' => __( 'Not found in Trash', 'sage' ), 'featured_image' => __( 'Featured Image', 'sage' ), 'set_featured_image' => __( 'Set shipment image', 'sage' ), 'remove_featured_image' => __( 'Remove shipment image', 'sage' ), 'use_featured_image' => __( 'Use as shipment image', 'sage' ), 'insert_into_item' => __( 'Insert into shipment', 'sage' ), 'uploaded_to_this_item' => __( 'Uploaded to this shipment', 'sage' ), 'items_list' => __( 'shipments list', 'sage' ), 'items_list_navigation' => __( 'Constests list navigation', 'sage' ), 'filter_items_list' => __( 'Filter shipments list', 'sage' ), ); $args = array( 'label' => __( 'shipments', 'sage' ), 'description' => __( 'Manage all shipments, sweepstakes and giveaways.', 'sage' ), 'labels' => $labels, 'supports' => array( 'revisions' ), 'taxonomies' => array( '' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-archive', 'show_in_admin_bar' => true, 'show_in_nav_menus' => false, 'can_export' => true, 'has_archive' => false, 'exclude_from_search' => true, 'publicly_queryable' => true, 'map_meta_cap' => true, 'capabilities' => array( 'edit_post' => 'edit_shipment', 'read_post' => 'read_shipment', 'read_posts' => 'read_shipments', 'delete_post' => 'delete_shipment', 'delete_posts' => 'delete_shipments', 'edit_posts' => 'edit_shipments', 'edit_others_posts' => 'edit_others_shipments', 'publish_posts' => 'publish_shipments', 'read_private_posts' => 'read_private_shipments', 'create_posts' => 'create_shipments', ), ); register_post_type( 'shipment', $args ); } add_action( 'init', 'shipment_post_type', 0 ); ```
Your custom post type looks like it's set up properly. It works on my test install. Try this instead of whatever add\_role and add\_cap code you're currently using. (For testing purposes only. Don't use it in production code, for reasons outlined below.) It's working for me: ``` function prefix_set_up_supplier_role(){ remove_role( 'supplier' ); add_role( 'supplier', 'Supplier', array( 'read' => true, 'edit_shipment' => true, 'read_shipment' => true, 'read_shipments' => true, 'delete_shipment' => true, 'delete_shipments' => true, 'edit_shipments' => true, 'edit_others_shipments' => true, 'publish_shipments' => true, 'read_private_shipments' => true, 'create_shipments' => true, ) ); } add_action( 'init', 'prefix_set_up_supplier_role' ); ``` It's very important to remember that adding user roles and capabilities actually saves data to the database. So if you had a version of your code before that didn't quite work, then added something that would make it work, it might not have taken effect if there is still old data in your database. add\_role() returns null if the role already exists in the database. For production code, you should actually be using the plugin activation and deactivation hooks for this stuff instead of running it every time, like this: ``` register_activation_hook( __FILE__, 'prefix_activate' ); function prefix_activate(){ add_role( 'supplier', 'Supplier', array( 'read' => true, 'edit_shipment' => true, 'read_shipment' => true, 'read_shipments' => true, 'delete_shipment' => true, 'delete_shipments' => true, 'edit_shipments' => true, 'edit_others_shipments' => true, 'publish_shipments' => true, 'read_private_shipments' => true, 'create_shipments' => true, ) ); } register_deactivation_hook( __FILE__, 'prefix_deactivate' ); function prefix_deactivate(){ remove_role( 'supplier' ); } ```
299,868
<p>I tried searching but I can't seem to find a similar question so I am hoping that as an amateur, I am just making a big simple mistake.</p> <p><strong>What I want</strong></p> <p>I want to install Font Awesome to my WordPress theme and I want to do it locally.</p> <p><strong>Folder structure</strong></p> <p>This image is my folder structure:</p> <p><a href="https://i.stack.imgur.com/pmDA3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmDA3.png" alt="enter image description here"></a></p> <p><strong>What I tried</strong></p> <ol> <li><p>I downloaded Font Aweesome 5.0.9 from the official website and followed their instructions. I placed the fontawesome-all.js file in /static/fontawesome and included this line of code in my header.php.</p> <pre><code>&lt;script defer src="/static/fontawesome/fontawesome-all.js"&gt;&lt;/script&gt; </code></pre></li> <li><p>I looked at a blog online and read another method. I took fontawesome.min.css and placed it in the CSS folder with the following line of code added to the header:</p> <pre><code>&lt;link rel="stylesheet" href="css/fontawesome.min.css"&gt; </code></pre></li> <li><p>I then tried to create an action with the following code and it didn't work either.</p> <pre><code>function add_font_awesome() { wp_enqueue_style( 'style', get_stylesheet_uri() ); wp_enqueue_style( 'fontawesome', get_template_directory_uri().'TestTheme/css/fontawesome.min.css' ); } add_action( 'wp_enqueue_scripts', 'add_font_awesome' ); </code></pre></li> </ol> <p><strong>Additional notes</strong></p> <p>For testing I shoved the following code in my main body and header but nothing ever appears.</p> <pre><code>&lt;i class="fab fa-wordpress"&gt;&lt;/i&gt; </code></pre> <p>I am unsure why this is not working, I believe I am probably making some crucial beginners mistake here but after reading multiple blogs and trying many different methods I have decided to try and ask for help. </p>
[ { "answer_id": 299869, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": 2, "selected": false, "text": "<p>You can edit and try again.</p>\n\n<pre><code>function add_font_awesome(){\n wp_enqueue_style( 'style', get_stylesheet_uri() );\n\n //you need to edit this below line.\n wp_enqueue_style( 'fontawesome', \n get_template_directory_uri() . '/css/fontawesome.min.css', array(), '5.0.9', 'all');\n}\nadd_action( 'wp_enqueue_scripts', 'add_font_awesome' );\n</code></pre>\n\n<p>Read more: <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_style/</a></p>\n" }, { "answer_id": 299882, "author": "Sigma Wadbude", "author_id": 134655, "author_profile": "https://wordpress.stackexchange.com/users/134655", "pm_score": 1, "selected": true, "text": "<p>Considering the folder structure \"/public_html/wp-content/themes/TestTheme/static/fontawesome/\" as folder location for Font Awesome use following instead</p>\n\n<p>1 use following instead of the one you used for js include</p>\n\n<pre><code>&lt;script defer src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/static/fontawesome/fontawesome-all.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>2 use following instead of the one you used for CSS include having fontawesome.min.css file in the CSS folder</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php echo get_template_directory_uri(); ?&gt;css/fontawesome.min.css\"&gt;\n</code></pre>\n\n<p>The function get_template_directory_uri(), retrieve theme directory URI and can be used to include files located in the active theme. </p>\n\n<p>3 or you can add the following code to your theme functions.php</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'test_theme_scripts_method');\n\n\n/*\n * Enqueue css and js with the correct path.\n */\nfunction test_theme_scripts_method() {\n\n // Enqueue css\n wp_enqueue_style( 'fontawesome_style', get_template_directory_uri() . '/css/fontawesome.min.css', array(), '5.0.9', 'all');\n\n // Enqueue js\n wp_enqueue_script( 'fontawesome_script', get_template_directory_uri() . '/static/fontawesome/fontawesome-all.js', array('jquery') );\n\n}\n</code></pre>\n\n<p>The action \"wp_enqueue_scripts\" is used to enqueue CSS and JS files to site. </p>\n" } ]
2018/04/05
[ "https://wordpress.stackexchange.com/questions/299868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136144/" ]
I tried searching but I can't seem to find a similar question so I am hoping that as an amateur, I am just making a big simple mistake. **What I want** I want to install Font Awesome to my WordPress theme and I want to do it locally. **Folder structure** This image is my folder structure: [![enter image description here](https://i.stack.imgur.com/pmDA3.png)](https://i.stack.imgur.com/pmDA3.png) **What I tried** 1. I downloaded Font Aweesome 5.0.9 from the official website and followed their instructions. I placed the fontawesome-all.js file in /static/fontawesome and included this line of code in my header.php. ``` <script defer src="/static/fontawesome/fontawesome-all.js"></script> ``` 2. I looked at a blog online and read another method. I took fontawesome.min.css and placed it in the CSS folder with the following line of code added to the header: ``` <link rel="stylesheet" href="css/fontawesome.min.css"> ``` 3. I then tried to create an action with the following code and it didn't work either. ``` function add_font_awesome() { wp_enqueue_style( 'style', get_stylesheet_uri() ); wp_enqueue_style( 'fontawesome', get_template_directory_uri().'TestTheme/css/fontawesome.min.css' ); } add_action( 'wp_enqueue_scripts', 'add_font_awesome' ); ``` **Additional notes** For testing I shoved the following code in my main body and header but nothing ever appears. ``` <i class="fab fa-wordpress"></i> ``` I am unsure why this is not working, I believe I am probably making some crucial beginners mistake here but after reading multiple blogs and trying many different methods I have decided to try and ask for help.
Considering the folder structure "/public\_html/wp-content/themes/TestTheme/static/fontawesome/" as folder location for Font Awesome use following instead 1 use following instead of the one you used for js include ``` <script defer src="<?php echo get_template_directory_uri(); ?>/static/fontawesome/fontawesome-all.js"></script> ``` 2 use following instead of the one you used for CSS include having fontawesome.min.css file in the CSS folder ``` <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>css/fontawesome.min.css"> ``` The function get\_template\_directory\_uri(), retrieve theme directory URI and can be used to include files located in the active theme. 3 or you can add the following code to your theme functions.php ``` add_action('wp_enqueue_scripts', 'test_theme_scripts_method'); /* * Enqueue css and js with the correct path. */ function test_theme_scripts_method() { // Enqueue css wp_enqueue_style( 'fontawesome_style', get_template_directory_uri() . '/css/fontawesome.min.css', array(), '5.0.9', 'all'); // Enqueue js wp_enqueue_script( 'fontawesome_script', get_template_directory_uri() . '/static/fontawesome/fontawesome-all.js', array('jquery') ); } ``` The action "wp\_enqueue\_scripts" is used to enqueue CSS and JS files to site.
299,968
<p>I just rehosted a site for a client, and am now receiving emails from the site stating I've recently requested to have the administration email changed. I didn't request it, and I've deleted the account the former admin could have used to log in. I've also changed all other passwords, and the host has changed. </p> <p>This is the second time this has happened. The first time, I tried clicking the link to see if it would tell me the proposed new email that was requested, but instead it just authorized the change. And I couldn't change it back, because the confirmation email went to the new, unauthorized email. So I changed it directly in the database and now know better than to click the link.</p> <p>I am trying to figure out how these emails are being generated...any ideas? Email I'm receiving is below.</p> <p>Thanks!</p> <p>Howdy [name],</p> <p>You recently requested to have the administration email address on your site changed.</p> <p>If this is correct, please click on the following link to change it: <a href="https://siteurl.com/wp-admin/options.php?adminhash=[hash]" rel="nofollow noreferrer">https://siteurl.com/wp-admin/options.php?adminhash=[hash]</a></p> <p>You can safely ignore and delete this email if you do not want to take this action.</p> <p>This email has been sent to [current admin email]</p> <p>Regards, All at sitename <a href="http://siteurl.com" rel="nofollow noreferrer">http://siteurl.com</a></p>
[ { "answer_id": 299969, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": 2, "selected": false, "text": "<p>I think someone entered the password reset form and you probably have an easy user login for the administrator like 'admin' or so, so that's what they probably entered.</p>\n\n<p>The email also says:</p>\n\n<pre><code>You can safely ignore and delete this email if you do not want to take this action.\n</code></pre>\n\n<p>So just ignore it.</p>\n" }, { "answer_id": 300033, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>In addition to what @beee sez: You might want to create a new admin-level user, log in as that user, then delete (or demote) the 'admin'-named user. Change the email for that admin user to something else. Then you won't care if someone tries to brute-force the user named 'admin'.</p>\n" }, { "answer_id": 300036, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>This is <strong>not</strong> the email sent from the reset password form.</p>\n\n<p>This email is sent when <a href=\"https://developer.wordpress.org/reference/functions/update_option_new_admin_email/\" rel=\"nofollow noreferrer\"><code>update_option_new_admin_email()</code></a> is run, which is when the <code>site_admin</code> option is changed. This option is found under <code>/wp-admin/options-general.php</code> so whoever is attempting to change the site admin email has access to that page. This user must have the <code>manage_options</code> capability and by default that is only granted to user with the administrator role.</p>\n\n<p>If this happens again, you can look at the <code>adminhash</code> option in the database or by PHP:</p>\n\n<pre><code>$adminhash = get_option( 'adminhash' );\n$email = $adminhash[ 'newemail' ];\n</code></pre>\n" } ]
2018/04/06
[ "https://wordpress.stackexchange.com/questions/299968", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69226/" ]
I just rehosted a site for a client, and am now receiving emails from the site stating I've recently requested to have the administration email changed. I didn't request it, and I've deleted the account the former admin could have used to log in. I've also changed all other passwords, and the host has changed. This is the second time this has happened. The first time, I tried clicking the link to see if it would tell me the proposed new email that was requested, but instead it just authorized the change. And I couldn't change it back, because the confirmation email went to the new, unauthorized email. So I changed it directly in the database and now know better than to click the link. I am trying to figure out how these emails are being generated...any ideas? Email I'm receiving is below. Thanks! Howdy [name], You recently requested to have the administration email address on your site changed. If this is correct, please click on the following link to change it: <https://siteurl.com/wp-admin/options.php?adminhash=[hash]> You can safely ignore and delete this email if you do not want to take this action. This email has been sent to [current admin email] Regards, All at sitename <http://siteurl.com>
I think someone entered the password reset form and you probably have an easy user login for the administrator like 'admin' or so, so that's what they probably entered. The email also says: ``` You can safely ignore and delete this email if you do not want to take this action. ``` So just ignore it.
300,008
<p>How can visitors redirect wp-admin to the homepage?</p> <p><strong>My site details:</strong> 1. I used BuddyPress; 2. Users can sign up and login via BuddyPress; 3. User role only Admin and Author;</p> <p><strong>Needs:</strong> 1. wp-admin only admin can access, if not an admin, and visitors and Authors then redirect to home page; 2. Users force use BuddyPress login page.</p> <p>Anyone have ideas?</p>
[ { "answer_id": 300018, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 3, "selected": true, "text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init\" rel=\"nofollow noreferrer\">codex entry for the <code>admin_init</code> hook has an example</a> showing you how to do this.</p>\n\n<pre><code>/**\n * Restrict access to the administration screens.\n *\n * Only administrators will be allowed to access the admin screens,\n * all other users will be automatically redirected to\n * 'example.com/path/to/location' instead.\n *\n * We do allow access for Ajax requests though, since these may be\n * initiated from the front end of the site by non-admin users.\n */\nfunction restrict_admin_with_redirect() {\n\n if ( ! current_user_can( 'manage_options' ) &amp;&amp; ( ! wp_doing_ajax() ) ) {\n wp_safe_redirect( 'example.com/path/to/location' ); // Replace this with the URL to redirect to.\n exit;\n }\n}\n\nadd_action( 'admin_init', 'restrict_admin_with_redirect', 1 );\n</code></pre>\n\n<p>A few notes on how this works:</p>\n\n<ul>\n<li><code>current_user_can( 'manage_options' )</code> checks to see if the logged in user has a capability only admin accounts should have. The proceeding <code>!</code> means \"not\". We are checking for a capability instead of simply checking for the admin role as a best practice. You should treat the role as nothing more than a label and check for capabilities (read: permissions) to check if a user can do something. <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">Read more about the roles &amp; caps here</a>.</li>\n<li><code>wp_doing_ajax()</code> Makes sure the current request is not a WordPress Ajax request. If it is, it's possible the user is not actually on the admin so no need to redirect. The proceeding <code>!</code> means \"not\".</li>\n<li><code>wp_safe_redirect( 'example.com/path/to/location' );</code> Redirects the user to the URL you pass it. <a href=\"https://developer.wordpress.org/reference/functions/wp_safe_redirect/\" rel=\"nofollow noreferrer\">You can find the documentation here</a>. <em>Note: <code>wp_safe_redirect()</code> is the recommended function not <code>wp_redirect()</code></em>. Thanks @Nathan Johnson\n\n<ul>\n<li><code>exit;</code> Stops execution of the script making the redirect the last action we do.</li>\n</ul></li>\n<li><code>add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );</code> Fire this check on the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init\" rel=\"nofollow noreferrer\"><code>admin_init</code></a> because it's the first hook fired after authentication. Pass <code>1</code> as the last argument to make sure out function is fired before any other hooks.</li>\n</ul>\n" }, { "answer_id": 300148, "author": "Melvyn1972", "author_id": 141362, "author_profile": "https://wordpress.stackexchange.com/users/141362", "pm_score": 0, "selected": false, "text": "<p>Is your own internet connection on a static IP? If so you can block wp-admin to everyone except your own IP. This is what I do. It can be achieved via various plugins but can also be done via htaccess.</p>\n" } ]
2018/04/06
[ "https://wordpress.stackexchange.com/questions/300008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
How can visitors redirect wp-admin to the homepage? **My site details:** 1. I used BuddyPress; 2. Users can sign up and login via BuddyPress; 3. User role only Admin and Author; **Needs:** 1. wp-admin only admin can access, if not an admin, and visitors and Authors then redirect to home page; 2. Users force use BuddyPress login page. Anyone have ideas?
The [codex entry for the `admin_init` hook has an example](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init) showing you how to do this. ``` /** * Restrict access to the administration screens. * * Only administrators will be allowed to access the admin screens, * all other users will be automatically redirected to * 'example.com/path/to/location' instead. * * We do allow access for Ajax requests though, since these may be * initiated from the front end of the site by non-admin users. */ function restrict_admin_with_redirect() { if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) { wp_safe_redirect( 'example.com/path/to/location' ); // Replace this with the URL to redirect to. exit; } } add_action( 'admin_init', 'restrict_admin_with_redirect', 1 ); ``` A few notes on how this works: * `current_user_can( 'manage_options' )` checks to see if the logged in user has a capability only admin accounts should have. The proceeding `!` means "not". We are checking for a capability instead of simply checking for the admin role as a best practice. You should treat the role as nothing more than a label and check for capabilities (read: permissions) to check if a user can do something. [Read more about the roles & caps here](https://codex.wordpress.org/Roles_and_Capabilities). * `wp_doing_ajax()` Makes sure the current request is not a WordPress Ajax request. If it is, it's possible the user is not actually on the admin so no need to redirect. The proceeding `!` means "not". * `wp_safe_redirect( 'example.com/path/to/location' );` Redirects the user to the URL you pass it. [You can find the documentation here](https://developer.wordpress.org/reference/functions/wp_safe_redirect/). *Note: `wp_safe_redirect()` is the recommended function not `wp_redirect()`*. Thanks @Nathan Johnson + `exit;` Stops execution of the script making the redirect the last action we do. * `add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );` Fire this check on the [`admin_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init) because it's the first hook fired after authentication. Pass `1` as the last argument to make sure out function is fired before any other hooks.
300,029
<p>I'm working on my first ever WP project.</p> <p>I have a theme that tiles all posts across the homepage - and I need to add a repeating advert every 5-6 posts.</p> <p>My thought was to change the database query that lists the posts and add the advert every so many loops.</p> <p>Can someone point me in the direction of where to find the database query?</p> <p>Or is there a more elegant solution you could suggest?</p> <p>thank you.</p>
[ { "answer_id": 300030, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p>Probably just add a counter, show ad on multiples of 6. </p>\n\n<p>Something like </p>\n\n<pre><code>$count = 0;\n$adEvery = 6;\n\nif (have_posts()) :\n while (have_posts()) : the_post();\n\n // Individual Post\n\n $count++;\n if ($count%$adEvery == 0) { \n // your ad\n } \n endwhile;\nelse :\n // No Posts Found\nendif;\n</code></pre>\n" }, { "answer_id": 300993, "author": "davemac", "author_id": 131, "author_profile": "https://wordpress.stackexchange.com/users/131", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://philkurth.com.au/articles/split-handling-wordpress-loop/\" rel=\"nofollow noreferrer\">Phil Kurth has written an informative article</a> on split handling the WordPress loop using the <code>current_post</code> property within the <code>global $wp_query</code> object.</p>\n\n<p>This can be applied to your question, and allows us to cleanly insert content at any point in a loop.</p>\n\n<p>The function is as follows (place in <code>functions.php</code> or, as I prefer, put in a seperate library file that handles query mods only):</p>\n\n<pre><code>/**\n * Returns the index of the current loop iteration.\n *\n * @return int\n */\nfunction pdk_get_current_loop_index() {\n global $wp_query;\n return $wp_query-&gt;current_post + 1;\n}\n</code></pre>\n\n<p>Then when outputting the loop, if we want to inject the ad after the 6th post:</p>\n\n<pre><code>if ( have_posts() ) :\n while (\n have_posts() ) :\n the_post();\n\n get_template_part( 'content' );\n\n if ( pdk_get_current_loop_index() === 6 ) {\n ?&gt;\n &lt;div class=\"ad-mrec\"&gt;\n &lt;!-- Insert ad coder here --&gt;\n &lt;/div&gt;\n &lt;?php\n }\n\n endwhile;\nendif;\n</code></pre>\n\n<p>If you read Phil's article, there's also more you can do with this function.</p>\n" } ]
2018/04/06
[ "https://wordpress.stackexchange.com/questions/300029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141280/" ]
I'm working on my first ever WP project. I have a theme that tiles all posts across the homepage - and I need to add a repeating advert every 5-6 posts. My thought was to change the database query that lists the posts and add the advert every so many loops. Can someone point me in the direction of where to find the database query? Or is there a more elegant solution you could suggest? thank you.
Probably just add a counter, show ad on multiples of 6. Something like ``` $count = 0; $adEvery = 6; if (have_posts()) : while (have_posts()) : the_post(); // Individual Post $count++; if ($count%$adEvery == 0) { // your ad } endwhile; else : // No Posts Found endif; ```
300,076
<p>We have developed a mobile application using the <a href="https://wordpress.org/plugins/json-api" rel="nofollow noreferrer">JSON API</a> plugin.</p> <p>The current website is running on HTTP, we are planning to change the website to HTTPS.</p> <p>Currently, mobile users on the live app are on HTTP; if we change the website to HTTPS then the app doesn't work so we have to publish a new app to work on HTTPS, but then the <em>old app</em> will not work, and we can't force a user to upgrade the app to the latest version.</p> <p>We have a solution but we don't how to implement it: to make the website HTTPS and only the JSON API plugin to work on HTTP and HTTPS. How can we do this?</p>
[ { "answer_id": 300030, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p>Probably just add a counter, show ad on multiples of 6. </p>\n\n<p>Something like </p>\n\n<pre><code>$count = 0;\n$adEvery = 6;\n\nif (have_posts()) :\n while (have_posts()) : the_post();\n\n // Individual Post\n\n $count++;\n if ($count%$adEvery == 0) { \n // your ad\n } \n endwhile;\nelse :\n // No Posts Found\nendif;\n</code></pre>\n" }, { "answer_id": 300993, "author": "davemac", "author_id": 131, "author_profile": "https://wordpress.stackexchange.com/users/131", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://philkurth.com.au/articles/split-handling-wordpress-loop/\" rel=\"nofollow noreferrer\">Phil Kurth has written an informative article</a> on split handling the WordPress loop using the <code>current_post</code> property within the <code>global $wp_query</code> object.</p>\n\n<p>This can be applied to your question, and allows us to cleanly insert content at any point in a loop.</p>\n\n<p>The function is as follows (place in <code>functions.php</code> or, as I prefer, put in a seperate library file that handles query mods only):</p>\n\n<pre><code>/**\n * Returns the index of the current loop iteration.\n *\n * @return int\n */\nfunction pdk_get_current_loop_index() {\n global $wp_query;\n return $wp_query-&gt;current_post + 1;\n}\n</code></pre>\n\n<p>Then when outputting the loop, if we want to inject the ad after the 6th post:</p>\n\n<pre><code>if ( have_posts() ) :\n while (\n have_posts() ) :\n the_post();\n\n get_template_part( 'content' );\n\n if ( pdk_get_current_loop_index() === 6 ) {\n ?&gt;\n &lt;div class=\"ad-mrec\"&gt;\n &lt;!-- Insert ad coder here --&gt;\n &lt;/div&gt;\n &lt;?php\n }\n\n endwhile;\nendif;\n</code></pre>\n\n<p>If you read Phil's article, there's also more you can do with this function.</p>\n" } ]
2018/04/07
[ "https://wordpress.stackexchange.com/questions/300076", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124623/" ]
We have developed a mobile application using the [JSON API](https://wordpress.org/plugins/json-api) plugin. The current website is running on HTTP, we are planning to change the website to HTTPS. Currently, mobile users on the live app are on HTTP; if we change the website to HTTPS then the app doesn't work so we have to publish a new app to work on HTTPS, but then the *old app* will not work, and we can't force a user to upgrade the app to the latest version. We have a solution but we don't how to implement it: to make the website HTTPS and only the JSON API plugin to work on HTTP and HTTPS. How can we do this?
Probably just add a counter, show ad on multiples of 6. Something like ``` $count = 0; $adEvery = 6; if (have_posts()) : while (have_posts()) : the_post(); // Individual Post $count++; if ($count%$adEvery == 0) { // your ad } endwhile; else : // No Posts Found endif; ```
300,084
<p>On archive pages, I let WordPress handle the archive page and load the first 10 posts, then I load more posts with AJAX requests, and this AJAX request is returning weird results.</p> <p>My query inside the AJAX handler looks like this:</p> <pre><code>$query_args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; get_option( 'posts_per_page' ), // 10 by default 'offset' =&gt; get_option( 'posts_per_page' ), // 10 by default 'cat' =&gt; 8 // the category ID ); $wp_query_archive = new WP_Query( $query_args ); </code></pre> <p><strong>The problem</strong>: If the post count of the AJAX query is less than 10, i get one duplicate post. </p> <p>If the posts were numbered, the first query (the default archive query that returns the first 10 posts in selected category) returns: <code>1,2,3,4,5,6,7,8,9,10</code>, the second query made by AJAX request and described above returns: <code>10,11</code>. Which then results in post duplication on front end.</p> <p>However, if there is 10 or more post for the AJAX query, the query returns: <code>11,12,13,14,15,16,17,18,19,20</code></p> <p>If there is only one post returned by the AJAX query, the query returns only that one post: <code>11</code>, which is right, but when there are two posts to return, the query returns: <code>10,11,12</code>.</p> <p>When there's 5 posts for the AJAX query, the query returns the right posts too, meaning: <code>11,12,13,14,15</code></p> <p>Is there some magic to <code>WP_Query()</code> that makes it behave this way?</p> <p><strong>Addition:</strong> I can't use <code>paged</code> query parameter, as Jacob Peattie pointed out, because I am using that query to load posts from multiple "pages" when the user hits page with <strong>hash</strong> containing string "#page3" for example.</p>
[ { "answer_id": 300088, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Just use the <code>paged</code> parameter to get the 2nd (or 3rd or 4th etc.) page:</p>\n\n<pre><code>$query_args = array(\n 'post_type' =&gt; 'post',\n 'paged' =&gt; 2,\n 'cat' =&gt; 8\n);\n$wp_query_archive = new WP_Query( $query_args );\n</code></pre>\n\n<p>If you keep track of which page you're up to in JS then you can just pass that page number directly into <code>paged</code> to get the right posts.</p>\n\n<p>PS: You were missing a <code>&gt;</code> for the <code>cat</code> argument, and if you're getting the category by ID you should use an integer. I've corrected both of these in my example.</p>\n\n<p>EDIT: If you need to handle multiple pages at once on initial load, based on the URL hash, then handle that with a different parameter in AJAX:</p>\n\n<pre><code>$query_args = array(\n 'post_type' =&gt; 'post',\n 'cat' =&gt; 8\n);\n\nif ( isset( $_GET['pages'] ) ) {\n $query_args['posts_per_page'] = $_GET['pages'] * get_option( 'posts_per_page' );\n} else if ( isset( $GET['page'] ) ) {\n $query_args['paged'] = $_GET['page'];\n}\n\n$wp_query_archive = new WP_Query( $query_args );\n</code></pre>\n\n<p>Then in your JS, if you want multiple pages at once send <code>pages</code> with the number of pages worth of posts that you want, but when loading more send <code>page</code> with the specific page number you are after.</p>\n" }, { "answer_id": 300092, "author": "Vincurekf", "author_id": 91948, "author_profile": "https://wordpress.stackexchange.com/users/91948", "pm_score": 2, "selected": false, "text": "<p>Fixed it. After all it was really dumb error on my part.\nThe <code>WP_Query()</code> does not filter out unpublished posts by default. The internal archive page query does filter these posts out.</p>\n\n<p>I had to add <code>'post_status' =&gt; 'publish'</code> to the <code>$query_args</code> array and everything is now working as expected.</p>\n\n<p>The final query then looks like this:</p>\n\n<pre><code>$query_args = array(\n 'post_status' =&gt; 'publish'\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; get_option( 'posts_per_page' ), // 10 by default\n 'offset' =&gt; get_option( 'posts_per_page' ), // 10 by default\n 'cat' =&gt; 8 // the category ID\n);\n</code></pre>\n" } ]
2018/04/07
[ "https://wordpress.stackexchange.com/questions/300084", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91948/" ]
On archive pages, I let WordPress handle the archive page and load the first 10 posts, then I load more posts with AJAX requests, and this AJAX request is returning weird results. My query inside the AJAX handler looks like this: ``` $query_args = array( 'post_type' => 'post', 'posts_per_page' => get_option( 'posts_per_page' ), // 10 by default 'offset' => get_option( 'posts_per_page' ), // 10 by default 'cat' => 8 // the category ID ); $wp_query_archive = new WP_Query( $query_args ); ``` **The problem**: If the post count of the AJAX query is less than 10, i get one duplicate post. If the posts were numbered, the first query (the default archive query that returns the first 10 posts in selected category) returns: `1,2,3,4,5,6,7,8,9,10`, the second query made by AJAX request and described above returns: `10,11`. Which then results in post duplication on front end. However, if there is 10 or more post for the AJAX query, the query returns: `11,12,13,14,15,16,17,18,19,20` If there is only one post returned by the AJAX query, the query returns only that one post: `11`, which is right, but when there are two posts to return, the query returns: `10,11,12`. When there's 5 posts for the AJAX query, the query returns the right posts too, meaning: `11,12,13,14,15` Is there some magic to `WP_Query()` that makes it behave this way? **Addition:** I can't use `paged` query parameter, as Jacob Peattie pointed out, because I am using that query to load posts from multiple "pages" when the user hits page with **hash** containing string "#page3" for example.
Fixed it. After all it was really dumb error on my part. The `WP_Query()` does not filter out unpublished posts by default. The internal archive page query does filter these posts out. I had to add `'post_status' => 'publish'` to the `$query_args` array and everything is now working as expected. The final query then looks like this: ``` $query_args = array( 'post_status' => 'publish' 'post_type' => 'post', 'posts_per_page' => get_option( 'posts_per_page' ), // 10 by default 'offset' => get_option( 'posts_per_page' ), // 10 by default 'cat' => 8 // the category ID ); ```
300,109
<p>I updated from http to https today. So far, so good. Everything is working, but the redirect command. When I click on external social media or websites that link to my blog still using the old version http, it's not being redirected.</p> <p>This is how part of my file looks:</p> <pre><code># -FrontPage- IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti* &lt;Limit GET POST&gt; order deny,allow deny from all allow from all &lt;/Limit&gt; &lt;Limit PUT DELETE&gt; order deny,allow deny from all &lt;/Limit&gt; AuthName zoomingjapan.com AuthUserFile /home/zoomingj/public_html/_vti_pvt/service.pwd AuthGroupFile /home/zoomingj/public_html/_vti_pvt/service.grp # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteCond %{HTTP_HOST} ^zoomingjapan.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.zoomingjapan.com [NC] RewriteRule ^(.*)$ https://zoomingjapan.com/$1 [L,R=301,NC] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I also tried this instead, no positive result:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_USER_AGENT} !FeedBurner [NC] RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC] RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] &lt;/IfModule&gt; </code></pre> <p>This is an <a href="http://zoomingjapan.com/cuisine/matcha/" rel="nofollow noreferrer">http link</a>. You can test and see for yourself that it's not being redirected.</p> <p>Could a caching plugin be interfering? I'm using LiteSpeed Cache.</p>
[ { "answer_id": 300112, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>You've put the redirect code in the wrong place. It needs to go <em>before</em> the <code># BEGIN WordPress</code> section. By placing the redirect code <em>after</em> the WordPress front-controller it will never be processed unless the request is for a physical file.</p>\n\n<p>However, your first attempt is not correct (it's missing the check for HTTPS), so would result in a redirect loop (if it was executed).</p>\n\n<p>A standard HTTP to HTTPS would take the following form:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n</code></pre>\n\n<p>However, ideally you should also combine this with a canonical www/non-www redirect as well, to avoid duplicate content or multiple redirects. For example, if the preference is for www (and you have no other subdomains), then something like the following:</p>\n\n<pre><code># Redirect bare domain to www and HTTPS\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n\n# Redirect HTTP to HTTPS\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n\n<p><strong>UPDATE:</strong> If your preference is for the non-www version, then you can change the first rule to read something like:</p>\n\n<pre><code># Redirect www to non-www (and HTTPS)\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteRule (.*) https://example.com/$1 [R=301,L]\n</code></pre>\n\n<p>(Assuming you've also changed the necessary settings in WordPress as well.)</p>\n" }, { "answer_id": 314603, "author": "Jasom Dotnet", "author_id": 50021, "author_profile": "https://wordpress.stackexchange.com/users/50021", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} !=https\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2018/04/07
[ "https://wordpress.stackexchange.com/questions/300109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6903/" ]
I updated from http to https today. So far, so good. Everything is working, but the redirect command. When I click on external social media or websites that link to my blog still using the old version http, it's not being redirected. This is how part of my file looks: ``` # -FrontPage- IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti* <Limit GET POST> order deny,allow deny from all allow from all </Limit> <Limit PUT DELETE> order deny,allow deny from all </Limit> AuthName zoomingjapan.com AuthUserFile /home/zoomingj/public_html/_vti_pvt/service.pwd AuthGroupFile /home/zoomingj/public_html/_vti_pvt/service.grp # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteCond %{HTTP_HOST} ^zoomingjapan.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.zoomingjapan.com [NC] RewriteRule ^(.*)$ https://zoomingjapan.com/$1 [L,R=301,NC] </IfModule> # END WordPress ``` I also tried this instead, no positive result: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_USER_AGENT} !FeedBurner [NC] RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC] RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] </IfModule> ``` This is an [http link](http://zoomingjapan.com/cuisine/matcha/). You can test and see for yourself that it's not being redirected. Could a caching plugin be interfering? I'm using LiteSpeed Cache.
You've put the redirect code in the wrong place. It needs to go *before* the `# BEGIN WordPress` section. By placing the redirect code *after* the WordPress front-controller it will never be processed unless the request is for a physical file. However, your first attempt is not correct (it's missing the check for HTTPS), so would result in a redirect loop (if it was executed). A standard HTTP to HTTPS would take the following form: ``` RewriteCond %{HTTPS} off RewriteRule (.*) https://www.example.com/$1 [R=301,L] ``` However, ideally you should also combine this with a canonical www/non-www redirect as well, to avoid duplicate content or multiple redirects. For example, if the preference is for www (and you have no other subdomains), then something like the following: ``` # Redirect bare domain to www and HTTPS RewriteCond %{HTTP_HOST} !^www\. RewriteRule (.*) https://www.example.com/$1 [R=301,L] # Redirect HTTP to HTTPS RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] ``` **UPDATE:** If your preference is for the non-www version, then you can change the first rule to read something like: ``` # Redirect www to non-www (and HTTPS) RewriteCond %{HTTP_HOST} ^www\. RewriteRule (.*) https://example.com/$1 [R=301,L] ``` (Assuming you've also changed the necessary settings in WordPress as well.)
300,147
<p>I have a WP installation in the root of my domain (running on Apache / Linux).</p> <p>I need to create a new WP installation (for various reasons that are outside of this post) and I have a choice of creating this second installation within either a) a subdomain or b) a folder in the main domain. </p> <p>So I can create this new installation in either <strong>new.mydomain.com</strong> or <strong>mydomain.com/new/</strong></p> <p>For SEO and other reasons I prefer to go for the latter ie. creating this new WP installation in a folder.</p> <p>However, I'm concerned about what problems I might run into. For example, the "main WP installation" (in root) has a htaccess file. Rules in that htaccess file might impact the new WP installation in the folder. So if the root htaccess had, for example, a block on a certain IP then that IP might not be able to access mydomain.com/new/</p> <p>Am I right to be concerned about issues with files in root like htaccess and robots.txt (and sitemap and others)? What problems am I likely to run into? What can I do to alleviate these problems? </p> <p>Many thanks in advance. </p>
[ { "answer_id": 300112, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>You've put the redirect code in the wrong place. It needs to go <em>before</em> the <code># BEGIN WordPress</code> section. By placing the redirect code <em>after</em> the WordPress front-controller it will never be processed unless the request is for a physical file.</p>\n\n<p>However, your first attempt is not correct (it's missing the check for HTTPS), so would result in a redirect loop (if it was executed).</p>\n\n<p>A standard HTTP to HTTPS would take the following form:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n</code></pre>\n\n<p>However, ideally you should also combine this with a canonical www/non-www redirect as well, to avoid duplicate content or multiple redirects. For example, if the preference is for www (and you have no other subdomains), then something like the following:</p>\n\n<pre><code># Redirect bare domain to www and HTTPS\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n\n# Redirect HTTP to HTTPS\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n\n<p><strong>UPDATE:</strong> If your preference is for the non-www version, then you can change the first rule to read something like:</p>\n\n<pre><code># Redirect www to non-www (and HTTPS)\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteRule (.*) https://example.com/$1 [R=301,L]\n</code></pre>\n\n<p>(Assuming you've also changed the necessary settings in WordPress as well.)</p>\n" }, { "answer_id": 314603, "author": "Jasom Dotnet", "author_id": 50021, "author_profile": "https://wordpress.stackexchange.com/users/50021", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} !=https\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2018/04/08
[ "https://wordpress.stackexchange.com/questions/300147", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141362/" ]
I have a WP installation in the root of my domain (running on Apache / Linux). I need to create a new WP installation (for various reasons that are outside of this post) and I have a choice of creating this second installation within either a) a subdomain or b) a folder in the main domain. So I can create this new installation in either **new.mydomain.com** or **mydomain.com/new/** For SEO and other reasons I prefer to go for the latter ie. creating this new WP installation in a folder. However, I'm concerned about what problems I might run into. For example, the "main WP installation" (in root) has a htaccess file. Rules in that htaccess file might impact the new WP installation in the folder. So if the root htaccess had, for example, a block on a certain IP then that IP might not be able to access mydomain.com/new/ Am I right to be concerned about issues with files in root like htaccess and robots.txt (and sitemap and others)? What problems am I likely to run into? What can I do to alleviate these problems? Many thanks in advance.
You've put the redirect code in the wrong place. It needs to go *before* the `# BEGIN WordPress` section. By placing the redirect code *after* the WordPress front-controller it will never be processed unless the request is for a physical file. However, your first attempt is not correct (it's missing the check for HTTPS), so would result in a redirect loop (if it was executed). A standard HTTP to HTTPS would take the following form: ``` RewriteCond %{HTTPS} off RewriteRule (.*) https://www.example.com/$1 [R=301,L] ``` However, ideally you should also combine this with a canonical www/non-www redirect as well, to avoid duplicate content or multiple redirects. For example, if the preference is for www (and you have no other subdomains), then something like the following: ``` # Redirect bare domain to www and HTTPS RewriteCond %{HTTP_HOST} !^www\. RewriteRule (.*) https://www.example.com/$1 [R=301,L] # Redirect HTTP to HTTPS RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] ``` **UPDATE:** If your preference is for the non-www version, then you can change the first rule to read something like: ``` # Redirect www to non-www (and HTTPS) RewriteCond %{HTTP_HOST} ^www\. RewriteRule (.*) https://example.com/$1 [R=301,L] ``` (Assuming you've also changed the necessary settings in WordPress as well.)
300,184
<p>I'm creating a WordPress theme in which I'm using the Redux Framework for creating the theme's options page.</p> <p>I want to show multiple blog layouts without creating custom WP templates. I saw in many themes the URL is something like </p> <ul> <li>theme.com?home_layout=grid&amp;sidebar=left</li> <li>theme.com?home_layout=list&amp;sidebar=none</li> </ul> <p>Now in the theme-option file i've got this one for the sidebar:</p> <pre><code>array( 'id' =&gt; 'sidebar_position', 'type' =&gt; 'select', 'title' =&gt; esc_html__( 'Blog sidebar', 'omio' ), 'options' =&gt; array( 'left' =&gt; esc_html__('Left', 'omio'), 'right' =&gt; esc_html__('Right', 'omio'), 'disable' =&gt; esc_html__('Disable', 'omio'), ), 'default' =&gt; 'right' ), </code></pre> <p>Now in the functions.php i've made a GET request code but didn't work.</p> <pre><code>$sidebar = isset( $_GET['sidebar_position'] ) ? $_GET['sidebar_position'] : 'right'; switch ( $sidebar ) { case 'left': set_theme_mod( 'sidebar_position', 'left' ); break; case 'disable': set_theme_mod( 'sidebar_position', 'disable' ); break; default: set_theme_mod( 'sidebar_position', 'right' ); } </code></pre> <p>How to do it, please :) for example when I put the sidebar at the left (theme.com/?sidebar=left) nothing happen, sidebar stay by default at the right</p>
[ { "answer_id": 300112, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>You've put the redirect code in the wrong place. It needs to go <em>before</em> the <code># BEGIN WordPress</code> section. By placing the redirect code <em>after</em> the WordPress front-controller it will never be processed unless the request is for a physical file.</p>\n\n<p>However, your first attempt is not correct (it's missing the check for HTTPS), so would result in a redirect loop (if it was executed).</p>\n\n<p>A standard HTTP to HTTPS would take the following form:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n</code></pre>\n\n<p>However, ideally you should also combine this with a canonical www/non-www redirect as well, to avoid duplicate content or multiple redirects. For example, if the preference is for www (and you have no other subdomains), then something like the following:</p>\n\n<pre><code># Redirect bare domain to www and HTTPS\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n\n# Redirect HTTP to HTTPS\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n\n<p><strong>UPDATE:</strong> If your preference is for the non-www version, then you can change the first rule to read something like:</p>\n\n<pre><code># Redirect www to non-www (and HTTPS)\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteRule (.*) https://example.com/$1 [R=301,L]\n</code></pre>\n\n<p>(Assuming you've also changed the necessary settings in WordPress as well.)</p>\n" }, { "answer_id": 314603, "author": "Jasom Dotnet", "author_id": 50021, "author_profile": "https://wordpress.stackexchange.com/users/50021", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>RewriteCond %{HTTP:X-Forwarded-Proto} !=https\nRewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300184", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141383/" ]
I'm creating a WordPress theme in which I'm using the Redux Framework for creating the theme's options page. I want to show multiple blog layouts without creating custom WP templates. I saw in many themes the URL is something like * theme.com?home\_layout=grid&sidebar=left * theme.com?home\_layout=list&sidebar=none Now in the theme-option file i've got this one for the sidebar: ``` array( 'id' => 'sidebar_position', 'type' => 'select', 'title' => esc_html__( 'Blog sidebar', 'omio' ), 'options' => array( 'left' => esc_html__('Left', 'omio'), 'right' => esc_html__('Right', 'omio'), 'disable' => esc_html__('Disable', 'omio'), ), 'default' => 'right' ), ``` Now in the functions.php i've made a GET request code but didn't work. ``` $sidebar = isset( $_GET['sidebar_position'] ) ? $_GET['sidebar_position'] : 'right'; switch ( $sidebar ) { case 'left': set_theme_mod( 'sidebar_position', 'left' ); break; case 'disable': set_theme_mod( 'sidebar_position', 'disable' ); break; default: set_theme_mod( 'sidebar_position', 'right' ); } ``` How to do it, please :) for example when I put the sidebar at the left (theme.com/?sidebar=left) nothing happen, sidebar stay by default at the right
You've put the redirect code in the wrong place. It needs to go *before* the `# BEGIN WordPress` section. By placing the redirect code *after* the WordPress front-controller it will never be processed unless the request is for a physical file. However, your first attempt is not correct (it's missing the check for HTTPS), so would result in a redirect loop (if it was executed). A standard HTTP to HTTPS would take the following form: ``` RewriteCond %{HTTPS} off RewriteRule (.*) https://www.example.com/$1 [R=301,L] ``` However, ideally you should also combine this with a canonical www/non-www redirect as well, to avoid duplicate content or multiple redirects. For example, if the preference is for www (and you have no other subdomains), then something like the following: ``` # Redirect bare domain to www and HTTPS RewriteCond %{HTTP_HOST} !^www\. RewriteRule (.*) https://www.example.com/$1 [R=301,L] # Redirect HTTP to HTTPS RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] ``` **UPDATE:** If your preference is for the non-www version, then you can change the first rule to read something like: ``` # Redirect www to non-www (and HTTPS) RewriteCond %{HTTP_HOST} ^www\. RewriteRule (.*) https://example.com/$1 [R=301,L] ``` (Assuming you've also changed the necessary settings in WordPress as well.)
300,207
<p>I'm trying to pass an argument in to the 'init' hook (please see below for what I'm trying to do).</p> <pre><code>//define post type name $pt_name = 'post'; //remove default wysiwyg editor add_action('init', function($pt_name) { $post_type = $pt_name; remove_post_type_support( $post_type, 'editor'); }, 100); </code></pre> <p>It seems <code>$pt_name</code> isn't being passed in to the hook function correctly.</p>
[ { "answer_id": 300208, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/init/\" rel=\"nofollow noreferrer\"><code>init</code> hook</a> have no parameters! The hook is fired after WordPress has finished loading but before any headers are sent. You can alternate use the <a href=\"https://stackoverflow.com/questions/1065188/in-php-5-3-0-what-is-the-function-use-identifier\">closure function</a> since php5.6 to add a param on this hook.</p>\n\n<p>From the core, see <a href=\"https://github.com/WordPress/WordPress/blob/eda5ab56af2a26edf65c7b0a3e67e0fc42706e10/wp-settings.php#L463\" rel=\"nofollow noreferrer\">the file on github</a>.</p>\n\n<pre><code>/**\n * Fires after WordPress has finished loading but before any headers are sent.\n *\n * Most of WP is loaded at this stage, and the user is authenticated. WP continues\n * to load on the {@see 'init'} hook that follows (e.g. widgets), and many plugins instantiate\n * themselves on it for all sorts of reasons (e.g. they need a user, a taxonomy, etc.).\n *\n * If you wish to plug an action once WP is loaded, use the {@see 'wp_loaded'} hook below.\n *\n * @since 1.5.0\n */\ndo_action( 'init' );\n</code></pre>\n\n<p>If you need to remove the editor, then is it not necessary to use a parameter no the hook. A simple remove is enough.</p>\n\n<pre><code>//remove default wysiwyg editor\nadd_action( 'init', function() {\n remove_post_type_support( 'post', 'editor' );\n}, 100);\n</code></pre>\n\n<p>In your enhanced comment, see this example to add a param with the help of closures - <strong>use</strong>.</p>\n\n<pre><code>//remove default wysiwyg editor\nadd_action( 'init', function() use ($pt_name) {\n remove_post_type_support( $pt_name, 'editor' );\n}, 100);\n</code></pre>\n" }, { "answer_id": 300217, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>The one thing you are missing is the use of <code>use</code> (<a href=\"http://php.net/manual/en/functions.anonymous.php\" rel=\"noreferrer\">http://php.net/manual/en/functions.anonymous.php</a> example #3)</p>\n\n<p>You code will look something like </p>\n\n<pre><code>//define post type name\n$pt_name = 'post';\n\n//remove default wysiwyg editor\nadd_action('init', function() use ($pt_name) {\n $post_type = $pt_name;\n remove_post_type_support( $post_type, 'editor');\n}, 100);\n</code></pre>\n\n<p>This will let PHP know what is the currect scope to use when evaluating the <code>$pt_name</code> variable.</p>\n\n<p>But this is only part of the solution as you want to do it for several post types, therefor you can not store it in one variable (at least not in a very readable and flexible way), therefor an additional level of indirection is needed.</p>\n\n<pre><code>function remover_editor_from_post_type($pt_name) {\n add_action('init', function() use ($pt_name) {\n $post_type = $pt_name;\n remove_post_type_support( $post_type, 'editor');\n }, 100);\n}\n\nremover_editor_from_post_type('post');\nremover_editor_from_post_type('page');\n</code></pre>\n\n<p>The reason it works is that for each call <code>$pt_name</code> has different context and PHP remembers it correctly for each creation of the closure.</p>\n" }, { "answer_id": 300220, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>There is some method to passing data to the function.</p>\n\n<p><strong>METHOD 1: Use the global in the function:</strong>\n \n\n<pre><code>//remove default wysiwyg editor\nadd_action('init', function($pt_name) {\n global $pt_name;\n $post_type = $pt_name;\n remove_post_type_support( $post_type, 'editor');\n}, 100);\n</code></pre>\n\n<p><strong>METHOD 2: Use the function:</strong></p>\n\n<pre><code>//define post type name\nfunction getPostTypeName($name = '') {\n return 'post';\n}\n\n//remove default wysiwyg editor\nadd_action('init', function($pt_name) {\n remove_post_type_support( getPostTypeName(), 'editor');\n}, 100);\n</code></pre>\n\n<p><strong>METHOD 3: Use the object class:</strong></p>\n\n<pre><code>class ModifyPostType{\n public $post_type_name;\n\n public function __construct() {\n // Set post type name\n $this-&gt;post_type_name = 'post';\n\n //remove default wysiwyg editor\n add_action('init', function($pt_name) {\n remove_post_type_support( $this-&gt;post_type_name, 'editor');\n }, 100);\n }\n}\n</code></pre>\n\n<p>I suggest you it's better you use the method 3.</p>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300207", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141411/" ]
I'm trying to pass an argument in to the 'init' hook (please see below for what I'm trying to do). ``` //define post type name $pt_name = 'post'; //remove default wysiwyg editor add_action('init', function($pt_name) { $post_type = $pt_name; remove_post_type_support( $post_type, 'editor'); }, 100); ``` It seems `$pt_name` isn't being passed in to the hook function correctly.
The one thing you are missing is the use of `use` (<http://php.net/manual/en/functions.anonymous.php> example #3) You code will look something like ``` //define post type name $pt_name = 'post'; //remove default wysiwyg editor add_action('init', function() use ($pt_name) { $post_type = $pt_name; remove_post_type_support( $post_type, 'editor'); }, 100); ``` This will let PHP know what is the currect scope to use when evaluating the `$pt_name` variable. But this is only part of the solution as you want to do it for several post types, therefor you can not store it in one variable (at least not in a very readable and flexible way), therefor an additional level of indirection is needed. ``` function remover_editor_from_post_type($pt_name) { add_action('init', function() use ($pt_name) { $post_type = $pt_name; remove_post_type_support( $post_type, 'editor'); }, 100); } remover_editor_from_post_type('post'); remover_editor_from_post_type('page'); ``` The reason it works is that for each call `$pt_name` has different context and PHP remembers it correctly for each creation of the closure.
300,219
<p>WordPress panel service "log out everywhere else" is doing a nice job. I want to use this as a function outside the panel.</p> <p><strong>Screenshoot</strong></p> <p><a href="https://i.stack.imgur.com/SAGpi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SAGpi.png" alt="enter image description here"></a></p>
[ { "answer_id": 300225, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>That button sends an AJAX request that runs <a href=\"https://developer.wordpress.org/reference/functions/wp_ajax_destroy_sessions/\" rel=\"nofollow noreferrer\"><code>wp_ajax_destroy_sessions()</code></a>. </p>\n\n<p>It's not really abstracted in such a way that you can re-use it outside of AJAX, but if you copy the source into your own function, minus the JSON parts, then you could perform the same action yourself.</p>\n\n<p>The key part is this bit, which will destroy all sessions for a given user ID:</p>\n\n<pre><code>$sessions = WP_Session_Tokens::get_instance( $user_id );\n$sessions-&gt;destroy_all();\n</code></pre>\n\n<p>The rest of the function is just checking the user exists, checking permissions, and sending a JSON response. They might not be relevant for your use case, so the above might suffice.</p>\n" }, { "answer_id": 393351, "author": "Hossein", "author_id": 210264, "author_profile": "https://wordpress.stackexchange.com/users/210264", "pm_score": 2, "selected": false, "text": "<p>I know this is an old topic but <code>destroy_all()</code> will destroy all sessions but <code>destroy_others()</code> destroys all sessions except the current session</p>\n<p><em><strong>Destroy all sessions:</strong></em></p>\n<pre><code>$sessions = WP_Session_Tokens::get_instance( $user_id );\n$sessions-&gt;destroy_all();\n</code></pre>\n<br>\n<p><em><strong>Destroy all sessions (except current session):</strong></em></p>\n<pre><code>$sessions = WP_Session_Tokens::get_instance( $user_id );\n$sessions-&gt;destroy_others( wp_get_session_token() );\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84842/" ]
WordPress panel service "log out everywhere else" is doing a nice job. I want to use this as a function outside the panel. **Screenshoot** [![enter image description here](https://i.stack.imgur.com/SAGpi.png)](https://i.stack.imgur.com/SAGpi.png)
That button sends an AJAX request that runs [`wp_ajax_destroy_sessions()`](https://developer.wordpress.org/reference/functions/wp_ajax_destroy_sessions/). It's not really abstracted in such a way that you can re-use it outside of AJAX, but if you copy the source into your own function, minus the JSON parts, then you could perform the same action yourself. The key part is this bit, which will destroy all sessions for a given user ID: ``` $sessions = WP_Session_Tokens::get_instance( $user_id ); $sessions->destroy_all(); ``` The rest of the function is just checking the user exists, checking permissions, and sending a JSON response. They might not be relevant for your use case, so the above might suffice.
300,222
<p>So over on wordpress I have a custom post type called crosses, and I need to list them on my search results page in order with the shortest titles first and longest titles last. I thought the way to do it would be to create a custom field called "name-length" and then include a function to count the number of letters in each post title and assign it as a number in a that custom field, but the code I'm trying got it isn't working.</p> <pre><code>function update_my_metadata(){ $args = array( 'post_type' =&gt; 'crosses', // Only get the posts 'post_status' =&gt; 'publish', // Only the posts that are published 'posts_per_page' =&gt; -1 // Get every post ); $posts = get_posts($args); foreach ( $posts as $post ) { $step = get_the_title($post-&gt;ID); $title_word = count_chars($step); update_post_meta( $post-&gt;ID, 'name_length_crosses', $title_word ); } } </code></pre> <p>*edit: To clarify, the field isn't being filled with the title length. I can't check the database to see if anything is going in there, but I can view the post edit screen and the values aren't showing up there at least.</p> <p>*edit again: Posts added by ACF, hooked using </p> <pre><code>add_action('init','update_my_metadata'); </code></pre> <p>*final edit: Posted a related question to this one here, if anyone is interested: <a href="https://wordpress.stackexchange.com/questions/300391/front-of-word-preference">Front of word preference</a></p>
[ { "answer_id": 300268, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 1, "selected": true, "text": "<p>Add the following to your <code>functions.php</code> for the on save. This will create a meta value on save that stores the length of the post title.</p>\n\n<pre><code>function save_crosses_title_length( $post_id ) {\n\n $title = get_the_title($post_id);//get the title\n $length = strlen( $title );// get the length of title\n\n if ( get_post_meta( $post_id, 'name_length_crosses' ) ) {//if meta value exists\n update_post_meta( $post_id, 'name_length_crosses', $length );//update meta value\n return;\n }\n\n add_post_meta( $post_id, 'name_length_crosses', $length );//else create meta value\n\n}\n\nadd_action( 'save_post_crosses', 'save_crosses_title_length');\n</code></pre>\n\n<p>For actually querying the posts.. Use the following. You can learn more about WP_Query here: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'crosses',\n 'meta_key' =&gt; 'name_length_crosses',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC'\n);\n\n$custom_query = new WP_Query( $args );\n\n\nwhile ( $custom_query-&gt;have_posts() ) :\n $custom_query-&gt;the_post();\n\n echo '&lt;p&gt;' . the_title() . '&lt;/p&gt;';\n\nendwhile;\n</code></pre>\n\n<p>If you like this approach I can build you a simple loop to run to update the existing posts.</p>\n" }, { "answer_id": 300281, "author": "Greg Much", "author_id": 131594, "author_profile": "https://wordpress.stackexchange.com/users/131594", "pm_score": 1, "selected": false, "text": "<p>Hi @Aaron you can use just simple MySQL query and the CHAR_LENGTH() function;)</p>\n\n<p>Hooking the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_orderby\" rel=\"nofollow noreferrer\"><code>posts_orderby</code></a> filter would be the fastest way to achieve the desired result without saving any meta-field by simply customising the default front-end query for the 'crosses' post type. However, note that this would actually modify all front-end queries, </p>\n\n<pre><code>add_filter('posts_orderby', 'modify_crosses_query', 10, 2);\nfunction modify_crosses_query($orderby_statement, $wp_query){\n if(is_admin()){ //admin queries.\n return $orderby_statement;\n }\n global $wpdb;\n // Verify correct post type, or any other query variable\n if ($wp_query-&gt;get(\"post_type\") === \"crosses\") {\n $orderby_statement = 'ORDER BY CHAR_LENGTH('.$wpdb-&gt;posts.'.post_title) ASC';\n }\n}\n</code></pre>\n" }, { "answer_id": 300312, "author": "Souvik Sikdar", "author_id": 130021, "author_profile": "https://wordpress.stackexchange.com/users/130021", "pm_score": 0, "selected": false, "text": "<p>You can try this code. I think this is the best way to sort them.\nActually, you need to sort the $posts array before using it in foreach.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'crosses', // Only get the posts\n 'post_status' =&gt; 'publish', // Only the posts that are published\n 'posts_per_page' =&gt; -1 // Get every post\n);\n$posts = get_posts($args);\n\n//This funtion is for sorting the array, depends on post's title length\nfunction post_title_length_sort($a, $b){\n return strlen($a-&gt;post_title)-strlen($b-&gt;post_title);\n}\nusort($posts, 'post_title_length_sort');\n\n//You cam check your array now\n//Now $posts is sorted by function \"post_title_length_sort\"\n//and you can use the $posts array in a foreach\n\n//print_r($posts); for checking the array\n\nforeach ( $posts as $post ) {\n\n //Your code goes here...\n}\n</code></pre>\n\n<p>Try the code , then let me know the result.</p>\n" }, { "answer_id": 300313, "author": "Aurovrata", "author_id": 52120, "author_profile": "https://wordpress.stackexchange.com/users/52120", "pm_score": 0, "selected": false, "text": "<p>Hooking on the <code>save_post</code> will only work for new posts. It will not solve the question of existing posts. This can only be solved with a hook on <code>init</code> or even better <code>admin_init</code> and flagging it in the options table to prevent it executing on each subsequent requests.</p>\n\n<p>Furthermore, for new posts it is more efficient to hook on<a href=\"https://developer.wordpress.org/reference/hooks/save_post_post-post_type/\" rel=\"nofollow noreferrer\"><code>save_post_{$post_type}</code></a>,</p>\n\n<pre><code>//for existing posts...\nadd_action('admin_init', 'udpate_crosses_once`);\nfunction udpate_crosses_once(){\n $flag = get_option('crosses_updated', 'no');\n if('no'===$flag){\n $args = array(\n 'post_type' =&gt; 'crosses', \n 'post_status' =&gt; 'publish', \n 'posts_per_page' =&gt; -1 \n );\n $posts = get_posts($args);\n foreach ( $posts as $post ) {\n $length = strlen( trim( $post-&gt;post_title ) );\n update_post_meta( $post-&gt;ID, 'name_length_crosses', $length );\n }\n add_option('crosses_updated', 'yes'); //set flag.\n }\n}\n//for new posts...\nadd_action( 'save_post_crosses', 'save_crosses_title_length', 10, 2 );\nfunction save_crosses_title_length( $post_id, $post) {\n // Check to see if we are autosaving\n if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE){\n return;\n }\n $length = strlen( trim($post-&gt;post_title) );// get the length of title\n //udpate the meta field, in case the post title is being updated\n update_post_meta( $post_id, 'name_length_crosses', $length );\n //note, no need to add_post_meta, udpate_post_meta fn will add the field if not found.\n}\n</code></pre>\n\n<p>For the front-end display, </p>\n\n<pre><code>$crossposts = get_posts(array(\n 'post_type' =&gt; 'crosses',\n 'meta_key' =&gt; 'name_length_crosses',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC'\n));\nif ( $crossposts ) {\n foreach ( $crossposts as $post ) :\n setup_postdata( $crossposts ); ?&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_content(); ?&gt;\n &lt;?php\n endforeach; \n wp_reset_postdata(); //Important, reset the query post data.\n}\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300222", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141421/" ]
So over on wordpress I have a custom post type called crosses, and I need to list them on my search results page in order with the shortest titles first and longest titles last. I thought the way to do it would be to create a custom field called "name-length" and then include a function to count the number of letters in each post title and assign it as a number in a that custom field, but the code I'm trying got it isn't working. ``` function update_my_metadata(){ $args = array( 'post_type' => 'crosses', // Only get the posts 'post_status' => 'publish', // Only the posts that are published 'posts_per_page' => -1 // Get every post ); $posts = get_posts($args); foreach ( $posts as $post ) { $step = get_the_title($post->ID); $title_word = count_chars($step); update_post_meta( $post->ID, 'name_length_crosses', $title_word ); } } ``` \*edit: To clarify, the field isn't being filled with the title length. I can't check the database to see if anything is going in there, but I can view the post edit screen and the values aren't showing up there at least. \*edit again: Posts added by ACF, hooked using ``` add_action('init','update_my_metadata'); ``` \*final edit: Posted a related question to this one here, if anyone is interested: [Front of word preference](https://wordpress.stackexchange.com/questions/300391/front-of-word-preference)
Add the following to your `functions.php` for the on save. This will create a meta value on save that stores the length of the post title. ``` function save_crosses_title_length( $post_id ) { $title = get_the_title($post_id);//get the title $length = strlen( $title );// get the length of title if ( get_post_meta( $post_id, 'name_length_crosses' ) ) {//if meta value exists update_post_meta( $post_id, 'name_length_crosses', $length );//update meta value return; } add_post_meta( $post_id, 'name_length_crosses', $length );//else create meta value } add_action( 'save_post_crosses', 'save_crosses_title_length'); ``` For actually querying the posts.. Use the following. You can learn more about WP\_Query here: <https://codex.wordpress.org/Class_Reference/WP_Query> ``` $args = array( 'post_type' => 'crosses', 'meta_key' => 'name_length_crosses', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); $custom_query = new WP_Query( $args ); while ( $custom_query->have_posts() ) : $custom_query->the_post(); echo '<p>' . the_title() . '</p>'; endwhile; ``` If you like this approach I can build you a simple loop to run to update the existing posts.
300,233
<p>I'm working on my Plugin &amp; i wanted to declare one of the global wordpress variables which is <code>$current_screen</code> To Check whether The user is on the target page or some other page, my Approach was like this , but it didn't work out .</p> <pre><code>class my_Class { public $current_screen; public function __construct() { global $current_screen; add_action( 'current_screen', array( $this, 'Current_Screen') ); } public function Current_Screen() { if ( $current_screen-&gt;parent_base == 'slug-page' ) { // Do Something ... } } } </code></pre> <p>Unfortunately Nothing Happens but Fatal Error . So Please Guys I Wanna Help . Thanks In Advance .</p>
[ { "answer_id": 300234, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>It's not enough to call <code>global</code> in <code>__construct()</code>. <code>global</code> only makes the variable available in the <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">current scope</a>, which is just the <code>__construct()</code> method.</p>\n\n<p>To make it available in other methods you need to call it in each method individually:</p>\n\n<pre><code>class MyClass {\n public function __construct() {\n add_action( 'init', array( $this, 'method') );\n }\n\n public function method() {\n global $global_variable;\n\n if ( $global_variable ) {\n // Do Something ...\n }\n }\n}\n</code></pre>\n\n<p>The other option is to assign the global variable as a class property, then refer to it in each method with <code>$this-&gt;</code>:</p>\n\n<pre><code>class MyClass {\n public $property;\n\n public function __construct() {\n global $global_variable;\n\n $this-&gt;property = $global_variable;\n\n add_action( 'init', array( $this, 'method') );\n }\n\n public function method() {\n if ( $this-&gt;property ) {\n // Do Something ...\n }\n }\n}\n</code></pre>\n\n<p>However, as noted by Nathan in his answer, you need to be wary of when your class is instantiated, as it's possible that the global variable will nit be available at that point. </p>\n\n<p>In those cases you would need to use my first example so that the variable is only referenced in a function that is hooked into the lifecycle at a point where the variable has been created.</p>\n" }, { "answer_id": 300236, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": false, "text": "<p>The <code>$current_screen</code> is passed as a variable to callables hooked from the <code>current_screen</code> hook.</p>\n\n<p>Before this hook, the <code>$current_screen</code> isn't set up, so globalizing the variable won't do anything anyway.</p>\n\n<p>Also, WordPress offers the convenience function <code>get_current_screen()</code> that returns the global <code>$current_screen</code> variable if it exists.</p>\n\n<pre><code>class wpse {\n protected $current_screen;\n public function load() {\n add_action( 'current_screen', [ $this, 'current_screen' ] );\n }\n public function current_screen( $current_screen ) {\n $this-&gt;current_screen = $current_screen;\n }\n}\nadd_action( 'plugins_loaded', [ new wpse(), 'load' ] );\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300233", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133002/" ]
I'm working on my Plugin & i wanted to declare one of the global wordpress variables which is `$current_screen` To Check whether The user is on the target page or some other page, my Approach was like this , but it didn't work out . ``` class my_Class { public $current_screen; public function __construct() { global $current_screen; add_action( 'current_screen', array( $this, 'Current_Screen') ); } public function Current_Screen() { if ( $current_screen->parent_base == 'slug-page' ) { // Do Something ... } } } ``` Unfortunately Nothing Happens but Fatal Error . So Please Guys I Wanna Help . Thanks In Advance .
The `$current_screen` is passed as a variable to callables hooked from the `current_screen` hook. Before this hook, the `$current_screen` isn't set up, so globalizing the variable won't do anything anyway. Also, WordPress offers the convenience function `get_current_screen()` that returns the global `$current_screen` variable if it exists. ``` class wpse { protected $current_screen; public function load() { add_action( 'current_screen', [ $this, 'current_screen' ] ); } public function current_screen( $current_screen ) { $this->current_screen = $current_screen; } } add_action( 'plugins_loaded', [ new wpse(), 'load' ] ); ```
300,240
<p>So basically I have these service categories, under that there are the actual services. I am basically trying to loop through the categories and display category title, then underneath that I want to loop through all of the corresponding child items. I'm using "Toolset" custom field plugin with Wordpress. I have the loop working for the "Service Categories" and now I am trying to loop through the "Service Categories" children custom post type of "Services". </p> <p>Codewise this is what I have right now:</p> <pre><code>&lt;?php $loop = new WP_Query(['post_type' =&gt; 'service-category']); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;h2 class="title"&gt; &lt;?php echo the_title(); ?&gt; &lt;?php if(types_render_field('subtitle')) {?&gt; &lt;span class="subtitle"&gt;&lt;?php echo types_render_field('subtitle');?&gt;&lt;/span&gt; &lt;?php }?&gt; &lt;/h2&gt; &lt;?php $loop2 = new WP_Query(['post_type' =&gt; 'service', 'post_parent' =&gt; get_the_ID()]); ?&gt; &lt;?php while ( $loop2-&gt;have_posts() ) : $loop2-&gt;the_post();?&gt; &lt;h2 class="title"&gt; &lt;?php echo the_title(); ?&gt; &lt;?php if(types_render_field('subtitle')) {?&gt; &lt;span class="subtitle"&gt;&lt;?php echo types_render_field('subtitle');?&gt;&lt;/span&gt; &lt;?php }?&gt; &lt;/h2&gt; &lt;?php endwhile;?&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>This is a screenshot of how I am associating the child custom post "Service" to the parent "Services-Category".</p> <p><a href="https://i.stack.imgur.com/HU9Ty.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HU9Ty.png" alt="enter image description here"></a></p> <p><code>$loop2</code> is where I am having the trouble trying to get the associated child items. How can I accomplish this? Any assistance would be greatly appreciated, I've burnt through two days searching for docs and all I find is the way to do it through the ui and not a template method.</p> <p>@JacobPeattie When I look in the database to see the relationships I was able to find this:</p> <p><a href="https://i.stack.imgur.com/zatXg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zatXg.png" alt="enter image description here"></a></p> <p>So <code>36</code> is the parent <code>Service Category</code> post_id and <code>43</code> is the child <code>Service</code> post_id in the <code>post_meta</code> table. I was able to find the relationship I just have never done a <code>meta_query()</code></p>
[ { "answer_id": 300234, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>It's not enough to call <code>global</code> in <code>__construct()</code>. <code>global</code> only makes the variable available in the <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">current scope</a>, which is just the <code>__construct()</code> method.</p>\n\n<p>To make it available in other methods you need to call it in each method individually:</p>\n\n<pre><code>class MyClass {\n public function __construct() {\n add_action( 'init', array( $this, 'method') );\n }\n\n public function method() {\n global $global_variable;\n\n if ( $global_variable ) {\n // Do Something ...\n }\n }\n}\n</code></pre>\n\n<p>The other option is to assign the global variable as a class property, then refer to it in each method with <code>$this-&gt;</code>:</p>\n\n<pre><code>class MyClass {\n public $property;\n\n public function __construct() {\n global $global_variable;\n\n $this-&gt;property = $global_variable;\n\n add_action( 'init', array( $this, 'method') );\n }\n\n public function method() {\n if ( $this-&gt;property ) {\n // Do Something ...\n }\n }\n}\n</code></pre>\n\n<p>However, as noted by Nathan in his answer, you need to be wary of when your class is instantiated, as it's possible that the global variable will nit be available at that point. </p>\n\n<p>In those cases you would need to use my first example so that the variable is only referenced in a function that is hooked into the lifecycle at a point where the variable has been created.</p>\n" }, { "answer_id": 300236, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": false, "text": "<p>The <code>$current_screen</code> is passed as a variable to callables hooked from the <code>current_screen</code> hook.</p>\n\n<p>Before this hook, the <code>$current_screen</code> isn't set up, so globalizing the variable won't do anything anyway.</p>\n\n<p>Also, WordPress offers the convenience function <code>get_current_screen()</code> that returns the global <code>$current_screen</code> variable if it exists.</p>\n\n<pre><code>class wpse {\n protected $current_screen;\n public function load() {\n add_action( 'current_screen', [ $this, 'current_screen' ] );\n }\n public function current_screen( $current_screen ) {\n $this-&gt;current_screen = $current_screen;\n }\n}\nadd_action( 'plugins_loaded', [ new wpse(), 'load' ] );\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141430/" ]
So basically I have these service categories, under that there are the actual services. I am basically trying to loop through the categories and display category title, then underneath that I want to loop through all of the corresponding child items. I'm using "Toolset" custom field plugin with Wordpress. I have the loop working for the "Service Categories" and now I am trying to loop through the "Service Categories" children custom post type of "Services". Codewise this is what I have right now: ``` <?php $loop = new WP_Query(['post_type' => 'service-category']); while ( $loop->have_posts() ) : $loop->the_post(); ?> <h2 class="title"> <?php echo the_title(); ?> <?php if(types_render_field('subtitle')) {?> <span class="subtitle"><?php echo types_render_field('subtitle');?></span> <?php }?> </h2> <?php $loop2 = new WP_Query(['post_type' => 'service', 'post_parent' => get_the_ID()]); ?> <?php while ( $loop2->have_posts() ) : $loop2->the_post();?> <h2 class="title"> <?php echo the_title(); ?> <?php if(types_render_field('subtitle')) {?> <span class="subtitle"><?php echo types_render_field('subtitle');?></span> <?php }?> </h2> <?php endwhile;?> <?php endwhile; ?> ``` This is a screenshot of how I am associating the child custom post "Service" to the parent "Services-Category". [![enter image description here](https://i.stack.imgur.com/HU9Ty.png)](https://i.stack.imgur.com/HU9Ty.png) `$loop2` is where I am having the trouble trying to get the associated child items. How can I accomplish this? Any assistance would be greatly appreciated, I've burnt through two days searching for docs and all I find is the way to do it through the ui and not a template method. @JacobPeattie When I look in the database to see the relationships I was able to find this: [![enter image description here](https://i.stack.imgur.com/zatXg.png)](https://i.stack.imgur.com/zatXg.png) So `36` is the parent `Service Category` post\_id and `43` is the child `Service` post\_id in the `post_meta` table. I was able to find the relationship I just have never done a `meta_query()`
The `$current_screen` is passed as a variable to callables hooked from the `current_screen` hook. Before this hook, the `$current_screen` isn't set up, so globalizing the variable won't do anything anyway. Also, WordPress offers the convenience function `get_current_screen()` that returns the global `$current_screen` variable if it exists. ``` class wpse { protected $current_screen; public function load() { add_action( 'current_screen', [ $this, 'current_screen' ] ); } public function current_screen( $current_screen ) { $this->current_screen = $current_screen; } } add_action( 'plugins_loaded', [ new wpse(), 'load' ] ); ```
300,261
<p>I am going to make plugin, collecting post views from Google Analytics. The main idea is to get views per post and store them with post meta. </p> <p>Problem:<br> My blog has a lot of posts and google analytics returns data very slow. It is about 30min for example to collect all data.</p> <p>Possible solutions:</p> <ol> <li><p>Use Linux crontab to execute <strong>/cron.php</strong> file from my plugin folder. This file should contains something like: <code>require_once('/../../../wp-blog-header.php');</code></p></li> <li><p>Use <code>wp_schedule_event</code> function to execute heavy query using wordpress core.</p></li> </ol> <p>How do you think, what method more preferred and what props and cons. </p>
[ { "answer_id": 300234, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>It's not enough to call <code>global</code> in <code>__construct()</code>. <code>global</code> only makes the variable available in the <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">current scope</a>, which is just the <code>__construct()</code> method.</p>\n\n<p>To make it available in other methods you need to call it in each method individually:</p>\n\n<pre><code>class MyClass {\n public function __construct() {\n add_action( 'init', array( $this, 'method') );\n }\n\n public function method() {\n global $global_variable;\n\n if ( $global_variable ) {\n // Do Something ...\n }\n }\n}\n</code></pre>\n\n<p>The other option is to assign the global variable as a class property, then refer to it in each method with <code>$this-&gt;</code>:</p>\n\n<pre><code>class MyClass {\n public $property;\n\n public function __construct() {\n global $global_variable;\n\n $this-&gt;property = $global_variable;\n\n add_action( 'init', array( $this, 'method') );\n }\n\n public function method() {\n if ( $this-&gt;property ) {\n // Do Something ...\n }\n }\n}\n</code></pre>\n\n<p>However, as noted by Nathan in his answer, you need to be wary of when your class is instantiated, as it's possible that the global variable will nit be available at that point. </p>\n\n<p>In those cases you would need to use my first example so that the variable is only referenced in a function that is hooked into the lifecycle at a point where the variable has been created.</p>\n" }, { "answer_id": 300236, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": false, "text": "<p>The <code>$current_screen</code> is passed as a variable to callables hooked from the <code>current_screen</code> hook.</p>\n\n<p>Before this hook, the <code>$current_screen</code> isn't set up, so globalizing the variable won't do anything anyway.</p>\n\n<p>Also, WordPress offers the convenience function <code>get_current_screen()</code> that returns the global <code>$current_screen</code> variable if it exists.</p>\n\n<pre><code>class wpse {\n protected $current_screen;\n public function load() {\n add_action( 'current_screen', [ $this, 'current_screen' ] );\n }\n public function current_screen( $current_screen ) {\n $this-&gt;current_screen = $current_screen;\n }\n}\nadd_action( 'plugins_loaded', [ new wpse(), 'load' ] );\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126253/" ]
I am going to make plugin, collecting post views from Google Analytics. The main idea is to get views per post and store them with post meta. Problem: My blog has a lot of posts and google analytics returns data very slow. It is about 30min for example to collect all data. Possible solutions: 1. Use Linux crontab to execute **/cron.php** file from my plugin folder. This file should contains something like: `require_once('/../../../wp-blog-header.php');` 2. Use `wp_schedule_event` function to execute heavy query using wordpress core. How do you think, what method more preferred and what props and cons.
The `$current_screen` is passed as a variable to callables hooked from the `current_screen` hook. Before this hook, the `$current_screen` isn't set up, so globalizing the variable won't do anything anyway. Also, WordPress offers the convenience function `get_current_screen()` that returns the global `$current_screen` variable if it exists. ``` class wpse { protected $current_screen; public function load() { add_action( 'current_screen', [ $this, 'current_screen' ] ); } public function current_screen( $current_screen ) { $this->current_screen = $current_screen; } } add_action( 'plugins_loaded', [ new wpse(), 'load' ] ); ```
300,270
<p>Is it possible to save the content (inside the WP WYSIWYG (<code>the_content</code>)) into a custom field?</p> <p><strong>This is what I have so far:</strong></p> <pre><code>add_action('edit_post', 'save_content_to_field'); function save_content_to_field($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { $content = get_the_content($post_ID); add_post_meta($post_ID, 'desc', $content, true); } } </code></pre>
[ { "answer_id": 300329, "author": "bpy", "author_id": 18693, "author_profile": "https://wordpress.stackexchange.com/users/18693", "pm_score": 1, "selected": true, "text": "<p>OK!</p>\n\n<p>I found this way and this might be useful to someone:</p>\n\n<pre><code>add_action('edit_post', 'save_content_to_field');\nfunction save_content_to_field($post_ID) {\n global $wpdb;\n\n if(!wp_is_post_revision($post_ID)) {\n //$content = get_the_content($post_ID);\n global $post;\n $content = apply_filters('the_content', $post-&gt;post_content);\n\n add_post_meta($post_ID, 'desc', $content, true);\n }\n }\n</code></pre>\n" }, { "answer_id": 300330, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 1, "selected": false, "text": "<p>You can get the content with <code>$_REQUEST</code>, Try the below code:</p>\n\n<pre><code>add_action('publish_post', 'save_content_to_field');\nfunction save_content_to_field($post_ID) {\n if(isset($_REQUEST['content'])) {\n update_post_meta($post_ID, 'desc', $_REQUEST['content']);\n }\n}\n</code></pre>\n\n<p><strong>UPDATED</strong>\nWith the below code if you want to sore with shortcode support:</p>\n\n<pre><code>add_action('publish_post', 'save_content_to_field');\nfunction save_content_to_field($post_ID) {\n $post = get_post($post_ID);\n $result = apply_filters('the_content',$post-&gt;post_content);\n\n if($result) {\n update_post_meta($post_ID, 'desc', $result);\n }\n}\n</code></pre>\n" } ]
2018/04/09
[ "https://wordpress.stackexchange.com/questions/300270", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18693/" ]
Is it possible to save the content (inside the WP WYSIWYG (`the_content`)) into a custom field? **This is what I have so far:** ``` add_action('edit_post', 'save_content_to_field'); function save_content_to_field($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { $content = get_the_content($post_ID); add_post_meta($post_ID, 'desc', $content, true); } } ```
OK! I found this way and this might be useful to someone: ``` add_action('edit_post', 'save_content_to_field'); function save_content_to_field($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { //$content = get_the_content($post_ID); global $post; $content = apply_filters('the_content', $post->post_content); add_post_meta($post_ID, 'desc', $content, true); } } ```
300,316
<p>I have created an <code>opps</code> custom post type and registered a custom API field of <code>closed</code> for it with the following code: </p> <pre><code>public function get_opp_state() { register_rest_field( 'opps', 'closed', array( 'get_callback' =&gt; array( $this, 'get_opp_state_callback' ), 'update_callback' =&gt; null, 'schema' =&gt; null )); } public function get_opp_state_callback( $opp ) { $oppDeadline = get_field( 'deadline', $opp[ 'id' ] ); $today = date( 'Ymd' ); $isClosed = $oppDeadline &lt; $today; return $isClosed; } </code></pre> <p>To retrieve all posts that use the <code>opps</code> post type, I use this request: </p> <blockquote> <p><a href="http://example.com/wp-json/wp/v2/opps" rel="nofollow noreferrer">http://example.com/wp-json/wp/v2/opps</a></p> </blockquote> <p>Now how can I extend that request to only fetch <code>opps</code> posts that have a <code>closed</code> field equal to true? I was hoping the following would work, but it doesn't: </p> <blockquote> <p><a href="http://example.com/wp-json/wp/v2/opps?closed=true" rel="nofollow noreferrer">http://example.com/wp-json/wp/v2/opps?closed=true</a></p> </blockquote> <p>I know I can create a custom route, but I really would like to avoid that since the information returned by the default request has all the info I need (except for that <code>closed</code> field). So is there any way to achieve this without a custom route? </p>
[ { "answer_id": 300328, "author": "Aurovrata", "author_id": 52120, "author_profile": "https://wordpress.stackexchange.com/users/52120", "pm_score": 0, "selected": false, "text": "<p>When modifying a REST request, you have <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/\" rel=\"nofollow noreferrer\">2 options</a>,\n - register a field, like you have done, only adds a key:value pair to the json object.\n - register a meta, which allows the addition of a custom meta-field to the json object.</p>\n\n<p>When you make a custom request with,</p>\n\n<p><code>http://example.com/wp-json/wp/v2/pages?slug=my_page</code></p>\n\n<p>for example, you are actually query a field of the post, in this case the <code>slug</code>.</p>\n\n<p>When you do,</p>\n\n<p><code>http://example.com/wp-json/wp/v2/opps?closed=true</code></p>\n\n<p>you are attempting to query a field called <code>closed</code> which does not exists since it has only been added as a key and not a meta-field to the json response.</p>\n\n<p>I think your best option is still a <a href=\"https://wordpress.stackexchange.com/questions/271877/how-to-do-a-meta-query-using-rest-api-in-wordpress-4-7#answer-271887\">custom route</a></p>\n" }, { "answer_id": 300384, "author": "grazdev", "author_id": 129417, "author_profile": "https://wordpress.stackexchange.com/users/129417", "pm_score": 3, "selected": true, "text": "<p>After a lot of digging I seem to have found a solution myself, and a pretty powerful one, which makes use of a <code>rest_{ post_type }_query</code> filter (replace the { post_type } part with the slug of your custom post type. You can use <code>rest_post_query</code> to alter the default <code>/wp-json/wp/v2/posts</code> request):</p>\n<pre><code>public function __construct() { \n // Make sure you add those numbers at the end of the line, or it won't work\n add_filter( 'rest_opps_query', array( $this, 'get_opps_by_state' ), 10, 2 ); \n} \n \npublic function get_opps_by_state( $args, $request ) {\n\n $state = $request-&gt;get_param( 'state' ); \n\n if( $state == 'open' ) {\n $args[ 'meta_query' ] = array(\n 'deadline' =&gt; array(\n 'key' =&gt; 'deadline',\n 'value' =&gt; date( 'Ymd' ), \n 'compare' =&gt; '&gt;',\n 'type' =&gt; 'DATE'\n )\n );\n } elseif ( $state == 'closed' ) {\n $args[ 'meta_query' ] = array(\n 'deadline' =&gt; array(\n 'key' =&gt; 'deadline',\n 'value' =&gt; date( 'Ymd' ), \n 'compare' =&gt; '&lt;',\n 'type' =&gt; 'DATE'\n )\n );\n }\n\n return $args; \n\n}\n</code></pre>\n<p>So now I can use the default Wordpress API route to fetch custom posts:</p>\n<blockquote>\n<p><a href=\"http://example.com/wp-json/wp/v2/opps\" rel=\"nofollow noreferrer\">http://example.com/wp-json/wp/v2/opps</a></p>\n</blockquote>\n<p>and filter its results based on my custom parameter, <code>status</code>:</p>\n<blockquote>\n<p><a href=\"http://example.com/wp-json/wp/v2/opps?status=open\" rel=\"nofollow noreferrer\">http://example.com/wp-json/wp/v2/opps?status=open</a></p>\n<p><a href=\"http://example.com/wp-json/wp/v2/opps?status=closed\" rel=\"nofollow noreferrer\">http://example.com/wp-json/wp/v2/opps?status=closed</a></p>\n</blockquote>\n<p>No custom routes needed!</p>\n" } ]
2018/04/10
[ "https://wordpress.stackexchange.com/questions/300316", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129417/" ]
I have created an `opps` custom post type and registered a custom API field of `closed` for it with the following code: ``` public function get_opp_state() { register_rest_field( 'opps', 'closed', array( 'get_callback' => array( $this, 'get_opp_state_callback' ), 'update_callback' => null, 'schema' => null )); } public function get_opp_state_callback( $opp ) { $oppDeadline = get_field( 'deadline', $opp[ 'id' ] ); $today = date( 'Ymd' ); $isClosed = $oppDeadline < $today; return $isClosed; } ``` To retrieve all posts that use the `opps` post type, I use this request: > > <http://example.com/wp-json/wp/v2/opps> > > > Now how can I extend that request to only fetch `opps` posts that have a `closed` field equal to true? I was hoping the following would work, but it doesn't: > > <http://example.com/wp-json/wp/v2/opps?closed=true> > > > I know I can create a custom route, but I really would like to avoid that since the information returned by the default request has all the info I need (except for that `closed` field). So is there any way to achieve this without a custom route?
After a lot of digging I seem to have found a solution myself, and a pretty powerful one, which makes use of a `rest_{ post_type }_query` filter (replace the { post\_type } part with the slug of your custom post type. You can use `rest_post_query` to alter the default `/wp-json/wp/v2/posts` request): ``` public function __construct() { // Make sure you add those numbers at the end of the line, or it won't work add_filter( 'rest_opps_query', array( $this, 'get_opps_by_state' ), 10, 2 ); } public function get_opps_by_state( $args, $request ) { $state = $request->get_param( 'state' ); if( $state == 'open' ) { $args[ 'meta_query' ] = array( 'deadline' => array( 'key' => 'deadline', 'value' => date( 'Ymd' ), 'compare' => '>', 'type' => 'DATE' ) ); } elseif ( $state == 'closed' ) { $args[ 'meta_query' ] = array( 'deadline' => array( 'key' => 'deadline', 'value' => date( 'Ymd' ), 'compare' => '<', 'type' => 'DATE' ) ); } return $args; } ``` So now I can use the default Wordpress API route to fetch custom posts: > > <http://example.com/wp-json/wp/v2/opps> > > > and filter its results based on my custom parameter, `status`: > > <http://example.com/wp-json/wp/v2/opps?status=open> > > > <http://example.com/wp-json/wp/v2/opps?status=closed> > > > No custom routes needed!
300,356
<p>I need custom CSS for admin. So if user is not logged in or is anything else but admin there is one CSS, and for admin only different CSS.</p> <p>I tried this code in functions.php:</p> <pre><code>function wpa66834_role_admin_body_class( $classes ) { global $current_user; foreach( $current_user-&gt;roles as $role ) $classes .= ' role-' . $role; return trim( $classes ); } add_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' ); </code></pre> <p>and in custom CSS field:</p> <pre><code>#targetElement { display: none; } .role-administrator #targetElement { display: visible; } </code></pre> <p>But it doesn't work.</p>
[ { "answer_id": 300357, "author": "Petra Žagar", "author_id": 141505, "author_profile": "https://wordpress.stackexchange.com/users/141505", "pm_score": -1, "selected": false, "text": "<p>Solution: </p>\n\n<pre><code>function add_custom_styles() {\n if ( is_admin() ) { ?&gt;\n &lt;style type=\"text/css\"&gt;\n .site-description {\n display: none !important;\n }\n .site-title {\n display: none !important;\n }\n &lt;/style&gt;\n&lt;?php }\n}\nadd_action('wp_head', 'add_custom_styles');\n</code></pre>\n" }, { "answer_id": 300358, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 0, "selected": false, "text": "<p>The code that you've tried already adds the role CSS class to the <code>admin_body_class</code>, which only affects the admin area/backend. Simply change the filter to alter the frontend body class <code>body_class</code>, eg.</p>\n\n<pre><code>function wpa66834_role_admin_body_class( $classes ) {\n global $current_user;\n foreach( $current_user-&gt;roles as $role )\n $classes .= ' role-' . $role;\n return trim( $classes );\n}\nadd_filter( 'body_class', 'wpa66834_role_admin_body_class' );\n</code></pre>\n" } ]
2018/04/10
[ "https://wordpress.stackexchange.com/questions/300356", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141505/" ]
I need custom CSS for admin. So if user is not logged in or is anything else but admin there is one CSS, and for admin only different CSS. I tried this code in functions.php: ``` function wpa66834_role_admin_body_class( $classes ) { global $current_user; foreach( $current_user->roles as $role ) $classes .= ' role-' . $role; return trim( $classes ); } add_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' ); ``` and in custom CSS field: ``` #targetElement { display: none; } .role-administrator #targetElement { display: visible; } ``` But it doesn't work.
The code that you've tried already adds the role CSS class to the `admin_body_class`, which only affects the admin area/backend. Simply change the filter to alter the frontend body class `body_class`, eg. ``` function wpa66834_role_admin_body_class( $classes ) { global $current_user; foreach( $current_user->roles as $role ) $classes .= ' role-' . $role; return trim( $classes ); } add_filter( 'body_class', 'wpa66834_role_admin_body_class' ); ```
300,379
<p>I'm currently using twentyseventeen child theme and I need to <strong>modify the link on single post page below the article</strong>. His href is forwarding to category of the post. </p> <p>I'm pretty new to filters in wp so I really don't know which filter should I use in this case. Also i would love to know, how could i know or where to find these filters?</p>
[ { "answer_id": 300385, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 3, "selected": true, "text": "<p>The category link that you are referring to, that is displayed beneath the single post page content is not added with a filter. It is displayed via a function called <code>twentyseventeen_entry_footer()</code>.</p>\n\n<p>If you take a look at the themes files you can find the function on line #59, within the file:</p>\n\n<p><code>/wp-content/themes/twentyseventeen/inc/template-tags.php</code></p>\n\n<p>Here is the <code>twentyseventeen_entry_footer()</code> functions code:</p>\n\n<pre><code>if ( ! function_exists( 'twentyseventeen_entry_footer' ) ) :\n /**\n * Prints HTML with meta information for the categories, tags and comments.\n */\n function twentyseventeen_entry_footer() {\n\n /* translators: used between list items, there is a space after the comma */\n $separate_meta = __( ', ', 'twentyseventeen' );\n\n // Get Categories for posts.\n $categories_list = get_the_category_list( $separate_meta );\n\n // Get Tags for posts.\n $tags_list = get_the_tag_list( '', $separate_meta );\n\n // We don't want to output .entry-footer if it will be empty, so make sure its not.\n if ( ( ( twentyseventeen_categorized_blog() &amp;&amp; $categories_list ) || $tags_list ) || get_edit_post_link() ) {\n\n echo '&lt;footer class=\"entry-footer\"&gt;';\n\n if ( 'post' === get_post_type() ) {\n if ( ( $categories_list &amp;&amp; twentyseventeen_categorized_blog() ) || $tags_list ) {\n echo '&lt;span class=\"cat-tags-links\"&gt;';\n\n // Make sure there's more than one category before displaying.\n if ( $categories_list &amp;&amp; twentyseventeen_categorized_blog() ) {\n echo '&lt;span class=\"cat-links\"&gt;' . twentyseventeen_get_svg( array( 'icon' =&gt; 'folder-open' ) ) . '&lt;span class=\"screen-reader-text\"&gt;' . __( 'Categories', 'twentyseventeen' ) . '&lt;/span&gt;' . $categories_list . '&lt;/span&gt;';\n }\n\n if ( $tags_list &amp;&amp; ! is_wp_error( $tags_list ) ) {\n echo '&lt;span class=\"tags-links\"&gt;' . twentyseventeen_get_svg( array( 'icon' =&gt; 'hashtag' ) ) . '&lt;span class=\"screen-reader-text\"&gt;' . __( 'Tags', 'twentyseventeen' ) . '&lt;/span&gt;' . $tags_list . '&lt;/span&gt;';\n }\n\n echo '&lt;/span&gt;';\n }\n }\n\n twentyseventeen_edit_link();\n\n echo '&lt;/footer&gt; &lt;!-- .entry-footer --&gt;';\n }\n }\nendif;\n</code></pre>\n\n<p>As you should see from the original function code, the first line is:</p>\n\n<p><code>if ( ! function_exists( 'twentyseventeen_entry_footer' ) ) :</code></p>\n\n<p>So, if the function already exists the code in the parent theme will be ignored. Due to the way WordPress works, it loads the child themes functions.php file first, before the parent theme.</p>\n\n<p>In order to modify this code you would copy or create your own <code>twentyseventeen_entry_footer()</code> function within your child themes <code>functions.php</code> file (without the <code>function_exists()</code> line, and without the final <code>endif;</code> line).</p>\n\n<p>Therefore, by creating the <code>twentyseventeen_entry_footer()</code> function within your child theme, this will override the default functionality of the parent themes function.</p>\n\n<p><strong>Update</strong> To remove this category link completely with a template override:</p>\n\n<p>On line #24 of the Twenty Seventeen themes <code>single.php</code> file, you should see the following code:</p>\n\n<p><code>get_template_part( 'template-parts/post/content', get_post_format() );</code></p>\n\n<p>If you then look in the folder referenced in the line above:</p>\n\n<p><code>/wp-content/themes/twentyseventeen/template-parts/post/</code></p>\n\n<p>You will see various 'content' PHP files for the various post formats. The default one for normal posts is <code>content.php</code></p>\n\n<p>Simply copy this file to your child theme within a new folder called in your child theme called <code>/template-parts/post/</code> and then remove the lines that references the <code>twentyseventeen_entry_footer()</code> function (lines #73-#77):</p>\n\n<pre><code>&lt;?php\nif ( is_single() ) {\n twentyseventeen_entry_footer();\n}\n?&gt;\n</code></pre>\n\n<p>You can use template overrides for any template files in the parent themes root folder or within the <code>/template-parts/</code> folder. Simply copy the file to your child theme in the same folder structure.</p>\n\n<p>NB. However, it might be simpler, in this particular case, to just create an empty/blank <code>twentyseventeen_entry_footer()</code> function in your child theme - it just depends whether you would still want this function to work for other post types or post formats (if it's used elsewhere)...</p>\n" }, { "answer_id": 312750, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 0, "selected": false, "text": "<p>I coming late to this party, but I have just found that the method suggested above is NOT recommended.</p>\n\n<p>Refer this post (\"<a href=\"https://wordpress.stackexchange.com/questions/300379/filter-and-modify-entry-footer-link-in-twentyseventeen\">get_parent_theme_file_path vs. get_template_directory</a>\") and this article (\"<a href=\"https://bravokeyl.com/get-theme-file-uri-and-get-theme-file-path/\" rel=\"nofollow noreferrer\">get_theme_file_uri and get_theme_file_path</a>\") (mentioned in the post). They are both authored by Bravokeyl.</p>\n\n<p>As noted above, the display of post footer is driven by the function \"twentyseventeen_entry_footer\" on line #59 of '/wp-content/themes/twentyseventeen/inc/template-tags.php'. The question that bugged me was... 'how did the system know to activate this function?'. If you look at the parent 'functions.php' lines #566-#586, you can see that all the files in the 'inc' folder are \"required'. This is the trigger to activate \"twentyseventeen_entry_footer\". The method used to \"require\" the 'inc' folder files uses a new function (from Vn4.7) called \"<strong>get_parent_theme_file_path</strong>\". </p>\n\n<p>Bravokeyl provides an excellent discussion of what the function does and why. There's also an example of how one can/should move control of the included files from the parent to the child theme. </p>\n\n<p>In my case, I created a new folder (inc) in my child theme and I copied the parent template-tags.php to a copy in the child. Here's my code for template-tags.php. It worked a treat and is much easier and more reliable than the alternatives suggested.</p>\n\n<pre><code>add_filter('parent_theme_file_path','twentyseventeen_parent_template_tags',10,2);\nfunction twentyseventeen_parent_template_tags($path,$file){\n if('inc/template-tags.php' == $file) {\n $gsd=get_stylesheet_directory();\n $file = 'inc/template-tags.php';\n $path = $gsd.\"/\".$file;\n }\n return $path;\n}\n</code></pre>\n" } ]
2018/04/10
[ "https://wordpress.stackexchange.com/questions/300379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141518/" ]
I'm currently using twentyseventeen child theme and I need to **modify the link on single post page below the article**. His href is forwarding to category of the post. I'm pretty new to filters in wp so I really don't know which filter should I use in this case. Also i would love to know, how could i know or where to find these filters?
The category link that you are referring to, that is displayed beneath the single post page content is not added with a filter. It is displayed via a function called `twentyseventeen_entry_footer()`. If you take a look at the themes files you can find the function on line #59, within the file: `/wp-content/themes/twentyseventeen/inc/template-tags.php` Here is the `twentyseventeen_entry_footer()` functions code: ``` if ( ! function_exists( 'twentyseventeen_entry_footer' ) ) : /** * Prints HTML with meta information for the categories, tags and comments. */ function twentyseventeen_entry_footer() { /* translators: used between list items, there is a space after the comma */ $separate_meta = __( ', ', 'twentyseventeen' ); // Get Categories for posts. $categories_list = get_the_category_list( $separate_meta ); // Get Tags for posts. $tags_list = get_the_tag_list( '', $separate_meta ); // We don't want to output .entry-footer if it will be empty, so make sure its not. if ( ( ( twentyseventeen_categorized_blog() && $categories_list ) || $tags_list ) || get_edit_post_link() ) { echo '<footer class="entry-footer">'; if ( 'post' === get_post_type() ) { if ( ( $categories_list && twentyseventeen_categorized_blog() ) || $tags_list ) { echo '<span class="cat-tags-links">'; // Make sure there's more than one category before displaying. if ( $categories_list && twentyseventeen_categorized_blog() ) { echo '<span class="cat-links">' . twentyseventeen_get_svg( array( 'icon' => 'folder-open' ) ) . '<span class="screen-reader-text">' . __( 'Categories', 'twentyseventeen' ) . '</span>' . $categories_list . '</span>'; } if ( $tags_list && ! is_wp_error( $tags_list ) ) { echo '<span class="tags-links">' . twentyseventeen_get_svg( array( 'icon' => 'hashtag' ) ) . '<span class="screen-reader-text">' . __( 'Tags', 'twentyseventeen' ) . '</span>' . $tags_list . '</span>'; } echo '</span>'; } } twentyseventeen_edit_link(); echo '</footer> <!-- .entry-footer -->'; } } endif; ``` As you should see from the original function code, the first line is: `if ( ! function_exists( 'twentyseventeen_entry_footer' ) ) :` So, if the function already exists the code in the parent theme will be ignored. Due to the way WordPress works, it loads the child themes functions.php file first, before the parent theme. In order to modify this code you would copy or create your own `twentyseventeen_entry_footer()` function within your child themes `functions.php` file (without the `function_exists()` line, and without the final `endif;` line). Therefore, by creating the `twentyseventeen_entry_footer()` function within your child theme, this will override the default functionality of the parent themes function. **Update** To remove this category link completely with a template override: On line #24 of the Twenty Seventeen themes `single.php` file, you should see the following code: `get_template_part( 'template-parts/post/content', get_post_format() );` If you then look in the folder referenced in the line above: `/wp-content/themes/twentyseventeen/template-parts/post/` You will see various 'content' PHP files for the various post formats. The default one for normal posts is `content.php` Simply copy this file to your child theme within a new folder called in your child theme called `/template-parts/post/` and then remove the lines that references the `twentyseventeen_entry_footer()` function (lines #73-#77): ``` <?php if ( is_single() ) { twentyseventeen_entry_footer(); } ?> ``` You can use template overrides for any template files in the parent themes root folder or within the `/template-parts/` folder. Simply copy the file to your child theme in the same folder structure. NB. However, it might be simpler, in this particular case, to just create an empty/blank `twentyseventeen_entry_footer()` function in your child theme - it just depends whether you would still want this function to work for other post types or post formats (if it's used elsewhere)...
300,397
<p>I have a simple database query script alongside with my WordPress installation, to which I pass a parameter using the following URL: <code>http://example.com/db/?p=foo</code>.</p> <p>My database script reads the parameter with</p> <pre><code>$pid = $_GET['p']; </code></pre> <p>Everthing works fine, IF the parameter does NOT START WITH A NUMBER.</p> <p>so, <code>?p=foo</code> is ok, but <code>?p=3poo</code> is EMPTY.</p> <p>Edit: I confirmed this by changing my script to</p> <pre><code>&lt;?php print_r($_GET); exit; </code></pre> <p>which gives as an output</p> <pre><code>Array ( ) </code></pre> <p>I suspect that it's the mod_rewrite who suppresses the parameters starting with a number. But I have no clue why, and how I can change this behavior. Any ideas?</p> <p>Edit: Unfortunately, I can not change the name of the parameter 'p', nor can I change the values of the parameter so they do not start with numbers, since the URLs where released as QR-tags to the public already, so I need a workaround to make this exact URLs work.</p> <p>Here is my <code>.htaccess</code> file in the root folder (edited as suggested by MrWhite, works as expected)</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; </code></pre>
[ { "answer_id": 300506, "author": "nounours", "author_id": 141532, "author_profile": "https://wordpress.stackexchange.com/users/141532", "pm_score": 2, "selected": false, "text": "<p>Thanks to Tom, I looked more carefully to the plugins.</p>\n\n<p>And I can confirm that the problem is NOT RELATED to mod_rewrite, but to a plugin conflict. (sorry that I posted such a suspicion, but I read somewhere a very similar problem that was explained like that.)</p>\n\n<p>Deactivating plugin by plugin, I found that one you made this behaviour. Still no clue why, but at least I have now a workaround: deactivating this plugin.</p>\n\n<p>Thanks Tom and all the others for your help!</p>\n" }, { "answer_id": 300844, "author": "nounours", "author_id": 141532, "author_profile": "https://wordpress.stackexchange.com/users/141532", "pm_score": 1, "selected": false, "text": "<p>Finally, completely understood and solved the problem using @MrWhite 's advice to use mod_rewrite to rewrite the query. Thanks!</p>\n\n<p>To explain:</p>\n\n<p>1) My <a href=\"http://example.com/db/?p=foo\" rel=\"nofollow noreferrer\">http://example.com/db/?p=foo</a> is (and this I didn't realise) actually not accessing the dbquery.php script, but a wordpress-page \"db\", which calls the dbquery.php script using the Plugin \"INCLUDEME\".</p>\n\n<p>2) So, the query-string is first processed by Wordpress (or whatever, don't know the right term), and since - as @Tom J Nowell pointed out - my parameter \"p\" has a special meaning, it was emptied by \"Wordpress\", and already no query string made it to the plugin. So it was not the plugins fault.</p>\n\n<p>3) Conclusion: not mod_rewrite, not the plugin, not the value starting with a number was the problem, but the simple fact that I used \"p\" was the source of the problem.</p>\n\n<p>4) The solution consisted in:</p>\n\n<p>a) rename the WP-page \"db\" into \"nachverfolgbarkeit\"</p>\n\n<p>b) create a directory called \"db\"</p>\n\n<p>c) place a .htaccess file in db containing the below redirection, to redirect from db to the new page \"nachverfolgbarkeit\" (which calls dbquery.php using INCLUDEME); and correcting the parameter from \"p\" to \"pid\"</p>\n\n<p>Not very nice patch, but it works well. So my advice to every reader: \"Never use p as a parametername\" ...</p>\n\n<p>Thanks to all for their help. Nounours</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{QUERY_STRING} ^p=(.*)$\nRewriteRule ^$ /nachverfolgbarkeit/?pid=%1 [R=301]\n</code></pre>\n" } ]
2018/04/10
[ "https://wordpress.stackexchange.com/questions/300397", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141532/" ]
I have a simple database query script alongside with my WordPress installation, to which I pass a parameter using the following URL: `http://example.com/db/?p=foo`. My database script reads the parameter with ``` $pid = $_GET['p']; ``` Everthing works fine, IF the parameter does NOT START WITH A NUMBER. so, `?p=foo` is ok, but `?p=3poo` is EMPTY. Edit: I confirmed this by changing my script to ``` <?php print_r($_GET); exit; ``` which gives as an output ``` Array ( ) ``` I suspect that it's the mod\_rewrite who suppresses the parameters starting with a number. But I have no clue why, and how I can change this behavior. Any ideas? Edit: Unfortunately, I can not change the name of the parameter 'p', nor can I change the values of the parameter so they do not start with numbers, since the URLs where released as QR-tags to the public already, so I need a workaround to make this exact URLs work. Here is my `.htaccess` file in the root folder (edited as suggested by MrWhite, works as expected) ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ```
Thanks to Tom, I looked more carefully to the plugins. And I can confirm that the problem is NOT RELATED to mod\_rewrite, but to a plugin conflict. (sorry that I posted such a suspicion, but I read somewhere a very similar problem that was explained like that.) Deactivating plugin by plugin, I found that one you made this behaviour. Still no clue why, but at least I have now a workaround: deactivating this plugin. Thanks Tom and all the others for your help!
300,406
<p>I am trying to add a custom coloumn to post quick edit and everything is almost working. Custom meta is saved and passed but if I click on quick edit the preview is blank. This is the error it gives me:</p> <blockquote> <p><strong>Notice</strong>: Undefined variable: <strong>post_id</strong> in /home/etimueit/public_html/wp-content/themes/caru/functions.php on line 626</p> </blockquote> <p><a href="https://i.stack.imgur.com/6uCMo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6uCMo.png" alt="I can see the data here (last coloumn)" /></a><br /> <a href="https://i.stack.imgur.com/xQgkh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xQgkh.png" alt="No variable here (but still saved in DB)" /></a></p> <p>Here is my code.</p> <pre><code>function disponibilitaet_quickedit_custom_posts_columns( $posts_columns ) { $posts_columns['disponibilitaet_edit_time'] = __( 'Modifica Disponibilit&amp;agrave;', 'disponibilitaet' ); return $posts_columns; } add_filter( 'manage_post_posts_columns', 'disponibilitaet_quickedit_custom_posts_columns' );` function disponibilitaet_quickedit_custom_column_display( $column_name, $post_id ) { if ( 'disponibilitaet_edit_time' == $column_name ) { $dispo_registrata = get_post_meta( $post_id, 'disponibilitaet_edit_time', true ); if ( $dispo_registrata ) { echo esc_html( $dispo_registrata ); } else { esc_html_e( 'N/A', 'disponibilitaet' ); } } } add_action( 'manage_post_posts_custom_column', 'disponibilitaet_quickedit_custom_column_display', 10, 2 ); function disponibilitaet_quickedit_fields( $column_name, $post_type ) { if ( 'disponibilitaet_edit_time' != $column_name ) return;` //This is line 626 $dispo_registrata = get_post_meta( $post_id, 'disponibilitaet_edit_time', true ); ?&gt; &lt;fieldset class=&quot;inline-edit-col-right&quot;&gt; &lt;div class=&quot;inline-edit-col&quot;&gt; &lt;label&gt; &lt;span class=&quot;title&quot;&gt;&lt;?php esc_html_e( 'Disponibilit&amp;agrave;', 'disponibilitaet' ); ?&gt;&lt;/span&gt; &lt;span class=&quot;input-text-wrap&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;disponibilitaet_edit_time&quot; class=&quot;disponibilitaetedittime&quot; value=&quot;&lt;?php echo $dispo_registrata;?&gt;&quot;&gt; &lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;?php } add_action( 'quick_edit_custom_box', 'disponibilitaet_quickedit_fields', 10, 2 ); function disponibilitaet_quickedit_save_post( $post_id, $post ) { // if called by autosave, then bail here if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return; // if this &quot;post&quot; post type? if ( $post-&gt;post_type != 'post' ) return; // does this user have permissions? if ( ! current_user_can( 'edit_post', $post_id ) ) return; // update! if ( isset( $_POST['disponibilitaet_edit_time'] ) ) { update_post_meta( $post_id, 'disponibilitaet_edit_time', $_POST['disponibilitaet_edit_time'] ); } } add_action( 'save_post', 'disponibilitaet_quickedit_save_post', 10, 2 ); function disponibilitaet_quickedit_javascript() { $current_screen = get_current_screen(); if ( $current_screen-&gt;id != 'edit-post' || $current_screen-&gt;post_type != 'post' ) return; // Ensure jQuery library loads wp_enqueue_script( 'jquery' ); ?&gt; &lt;script type=&quot;text/javascript&quot;&gt; jQuery( function( $ ) { $( '#the-list' ).on( 'click', 'a.editinline', function( e ) { e.preventDefault(); var editTime = $(this).data( 'edit-time' ); inlineEditPost.revert(); $( '.disponibilitaetedittime' ).val( editTime ? editTime : '' ); }); }); &lt;/script&gt; &lt;?php } add_action( 'admin_print_footer_scripts-edit.php', 'disponibilitaet_quickedit_javascript' ); </code></pre>
[ { "answer_id": 300407, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 2, "selected": false, "text": "<p>Sorry, I've had to change my answer after checking the WordPress Codex on adding custom editable data to the quick edit. So you'll have to remove the references to <code>$post_id</code> too (from the <code>add_action</code> arguments and from within your function).</p>\n\n<p>It looks like the <code>quick_edit_custom_box</code> only takes 2 arguments: <code>$column_name</code> and <code>$post_type</code>. Then for getting and displaying the value, this has to be done using some more PHP and Javascript.</p>\n\n<p>If you read further in to the WordPress Codex on the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box\" rel=\"nofollow noreferrer\">quick edit custom box</a> and read further down to the section on '<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box#Setting_Existing_Values\" rel=\"nofollow noreferrer\">Setting Existing Values</a>', you'll see there's a fair bit more work required in order to do this.</p>\n\n<p>I'd suggest reading the docs in a bit more detail as it's not quite as straight-forward as I first thought...</p>\n" }, { "answer_id": 300948, "author": "Downloadtaky", "author_id": 4107, "author_profile": "https://wordpress.stackexchange.com/users/4107", "pm_score": 2, "selected": true, "text": "<p>Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ).</p>\n\n<pre><code>/**\n</code></pre>\n\n<p>*\n * Aggiungi Disponibilità nel Quick Edit\n*/</p>\n\n<pre><code>function etdispo_quickedit_custom_posts_columns( $posts_columns ) {\n $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' );\n return $posts_columns;\n}\nadd_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' );\n\nfunction etdispo_quickedit_custom_column_display( $column_name, $post_id ) {\n if ( 'et2018-quantita_birra' == $column_name ) {\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n\n if ( $etdispo_regi ) {\n echo esc_html( $etdispo_regi );\n } else {\n esc_html_e( 'N/A', 'etdispo' );\n }\n }\n}\nadd_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 );\n\nfunction etdispo_quickedit_fields( $column_name, $post_type, $post_id ) {\n if ( 'et2018-quantita_birra' != $column_name )\n return;\n\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n ?&gt;\n &lt;fieldset class=\"inline-edit-col-right\"&gt;\n &lt;div class=\"inline-edit-col\"&gt;\n &lt;label&gt;\n &lt;span class=\"title\"&gt;&lt;?php esc_html_e( 'Disponibilità', 'etdispo' ); ?&gt;&lt;/span&gt;\n &lt;span class=\"input-text-wrap\"&gt;\n &lt;input type=\"text\" name=\"et2018-quantita_birra\" class=\"etdispoedit\" value=\"\"&gt;\n &lt;/span&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;/fieldset&gt;\n &lt;?php\n}\nadd_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 );\nfunction etdispo_quickedit_save_post( $post_id, $post ) {\n // if called by autosave, then bail here\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n\n // if this \"post\" post type?\n if ( $post-&gt;post_type != 'post' )\n return;\n\n // does this user have permissions?\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n\n // update!\n if ( isset( $_POST['et2018-quantita_birra'] ) ) {\n update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] );\n }\n}\nadd_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 );\n\nfunction etdispo_quickedit_javascript() {\n $current_screen = get_current_screen();\n if ( $current_screen-&gt;id != 'edit-post' || $current_screen-&gt;post_type != 'post' )\n return;\n\n // Ensure jQuery library loads\n wp_enqueue_script( 'jquery' );\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery( function( $ ) {\n $( '#the-list' ).on( 'click', 'a.editinline', function( e ) {\n e.preventDefault();\n var editDispo = $(this).data( 'edit-dispo' );\n inlineEditPost.revert();\n $( '.etdispoedit' ).val( editDispo ? editDispo : '' );\n });\n });\n &lt;/script&gt;\n &lt;?php\n}\nadd_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' );\n/* Qui */\nfunction etdispo_quickedit_set_data( $actions, $post ) {\n $found_value = get_post_meta( $post-&gt;ID, 'et2018-quantita_birra', true );\n\n if ( $found_value ) {\n if ( isset( $actions['inline hide-if-no-js'] ) ) {\n $new_attribute = sprintf( 'data-edit-dispo=\"%s\"', esc_attr( $found_value ) );\n $actions['inline hide-if-no-js'] = str_replace( 'class=', \"$new_attribute class=\", $actions['inline hide-if-no-js'] );\n }\n }\n\n return $actions;\n}\nadd_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2);\n</code></pre>\n" } ]
2018/04/10
[ "https://wordpress.stackexchange.com/questions/300406", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4107/" ]
I am trying to add a custom coloumn to post quick edit and everything is almost working. Custom meta is saved and passed but if I click on quick edit the preview is blank. This is the error it gives me: > > **Notice**: Undefined variable: **post\_id** in /home/etimueit/public\_html/wp-content/themes/caru/functions.php on line 626 > > > [![I can see the data here (last coloumn)](https://i.stack.imgur.com/6uCMo.png)](https://i.stack.imgur.com/6uCMo.png) [![No variable here (but still saved in DB)](https://i.stack.imgur.com/xQgkh.png)](https://i.stack.imgur.com/xQgkh.png) Here is my code. ``` function disponibilitaet_quickedit_custom_posts_columns( $posts_columns ) { $posts_columns['disponibilitaet_edit_time'] = __( 'Modifica Disponibilit&agrave;', 'disponibilitaet' ); return $posts_columns; } add_filter( 'manage_post_posts_columns', 'disponibilitaet_quickedit_custom_posts_columns' );` function disponibilitaet_quickedit_custom_column_display( $column_name, $post_id ) { if ( 'disponibilitaet_edit_time' == $column_name ) { $dispo_registrata = get_post_meta( $post_id, 'disponibilitaet_edit_time', true ); if ( $dispo_registrata ) { echo esc_html( $dispo_registrata ); } else { esc_html_e( 'N/A', 'disponibilitaet' ); } } } add_action( 'manage_post_posts_custom_column', 'disponibilitaet_quickedit_custom_column_display', 10, 2 ); function disponibilitaet_quickedit_fields( $column_name, $post_type ) { if ( 'disponibilitaet_edit_time' != $column_name ) return;` //This is line 626 $dispo_registrata = get_post_meta( $post_id, 'disponibilitaet_edit_time', true ); ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <label> <span class="title"><?php esc_html_e( 'Disponibilit&agrave;', 'disponibilitaet' ); ?></span> <span class="input-text-wrap"> <input type="text" name="disponibilitaet_edit_time" class="disponibilitaetedittime" value="<?php echo $dispo_registrata;?>"> </span> </label> </div> </fieldset> <?php } add_action( 'quick_edit_custom_box', 'disponibilitaet_quickedit_fields', 10, 2 ); function disponibilitaet_quickedit_save_post( $post_id, $post ) { // if called by autosave, then bail here if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // if this "post" post type? if ( $post->post_type != 'post' ) return; // does this user have permissions? if ( ! current_user_can( 'edit_post', $post_id ) ) return; // update! if ( isset( $_POST['disponibilitaet_edit_time'] ) ) { update_post_meta( $post_id, 'disponibilitaet_edit_time', $_POST['disponibilitaet_edit_time'] ); } } add_action( 'save_post', 'disponibilitaet_quickedit_save_post', 10, 2 ); function disponibilitaet_quickedit_javascript() { $current_screen = get_current_screen(); if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' ) return; // Ensure jQuery library loads wp_enqueue_script( 'jquery' ); ?> <script type="text/javascript"> jQuery( function( $ ) { $( '#the-list' ).on( 'click', 'a.editinline', function( e ) { e.preventDefault(); var editTime = $(this).data( 'edit-time' ); inlineEditPost.revert(); $( '.disponibilitaetedittime' ).val( editTime ? editTime : '' ); }); }); </script> <?php } add_action( 'admin_print_footer_scripts-edit.php', 'disponibilitaet_quickedit_javascript' ); ```
Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ). ``` /** ``` \* \* Aggiungi Disponibilità nel Quick Edit \*/ ``` function etdispo_quickedit_custom_posts_columns( $posts_columns ) { $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' ); return $posts_columns; } add_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' ); function etdispo_quickedit_custom_column_display( $column_name, $post_id ) { if ( 'et2018-quantita_birra' == $column_name ) { $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); if ( $etdispo_regi ) { echo esc_html( $etdispo_regi ); } else { esc_html_e( 'N/A', 'etdispo' ); } } } add_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 ); function etdispo_quickedit_fields( $column_name, $post_type, $post_id ) { if ( 'et2018-quantita_birra' != $column_name ) return; $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <label> <span class="title"><?php esc_html_e( 'Disponibilità', 'etdispo' ); ?></span> <span class="input-text-wrap"> <input type="text" name="et2018-quantita_birra" class="etdispoedit" value=""> </span> </label> </div> </fieldset> <?php } add_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 ); function etdispo_quickedit_save_post( $post_id, $post ) { // if called by autosave, then bail here if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // if this "post" post type? if ( $post->post_type != 'post' ) return; // does this user have permissions? if ( ! current_user_can( 'edit_post', $post_id ) ) return; // update! if ( isset( $_POST['et2018-quantita_birra'] ) ) { update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] ); } } add_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 ); function etdispo_quickedit_javascript() { $current_screen = get_current_screen(); if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' ) return; // Ensure jQuery library loads wp_enqueue_script( 'jquery' ); ?> <script type="text/javascript"> jQuery( function( $ ) { $( '#the-list' ).on( 'click', 'a.editinline', function( e ) { e.preventDefault(); var editDispo = $(this).data( 'edit-dispo' ); inlineEditPost.revert(); $( '.etdispoedit' ).val( editDispo ? editDispo : '' ); }); }); </script> <?php } add_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' ); /* Qui */ function etdispo_quickedit_set_data( $actions, $post ) { $found_value = get_post_meta( $post->ID, 'et2018-quantita_birra', true ); if ( $found_value ) { if ( isset( $actions['inline hide-if-no-js'] ) ) { $new_attribute = sprintf( 'data-edit-dispo="%s"', esc_attr( $found_value ) ); $actions['inline hide-if-no-js'] = str_replace( 'class=', "$new_attribute class=", $actions['inline hide-if-no-js'] ); } } return $actions; } add_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2); ```
300,411
<p>I'm currently developing a wordpress version of a website on a dev.acme.com domain, while the old site (www.acme.com) remains active (if it's relevant, it's not on a wordpress platform.) The content will be migrated over at some point (that part has been tested and is going to work fine.)</p> <p>All my URLs (for images and links) inside posts are relative, so there's no worry about them when I switch to live....</p> <p>But I notice that Yoast stores its FB images with an absolute path of dev.acme.com, and I think I am hearing that WP stores its featured images that way too.</p> <p>Any things / thoughts for how to avoid utter chaos on these two stored image paths when I do switch live? </p>
[ { "answer_id": 300407, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 2, "selected": false, "text": "<p>Sorry, I've had to change my answer after checking the WordPress Codex on adding custom editable data to the quick edit. So you'll have to remove the references to <code>$post_id</code> too (from the <code>add_action</code> arguments and from within your function).</p>\n\n<p>It looks like the <code>quick_edit_custom_box</code> only takes 2 arguments: <code>$column_name</code> and <code>$post_type</code>. Then for getting and displaying the value, this has to be done using some more PHP and Javascript.</p>\n\n<p>If you read further in to the WordPress Codex on the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box\" rel=\"nofollow noreferrer\">quick edit custom box</a> and read further down to the section on '<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box#Setting_Existing_Values\" rel=\"nofollow noreferrer\">Setting Existing Values</a>', you'll see there's a fair bit more work required in order to do this.</p>\n\n<p>I'd suggest reading the docs in a bit more detail as it's not quite as straight-forward as I first thought...</p>\n" }, { "answer_id": 300948, "author": "Downloadtaky", "author_id": 4107, "author_profile": "https://wordpress.stackexchange.com/users/4107", "pm_score": 2, "selected": true, "text": "<p>Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ).</p>\n\n<pre><code>/**\n</code></pre>\n\n<p>*\n * Aggiungi Disponibilità nel Quick Edit\n*/</p>\n\n<pre><code>function etdispo_quickedit_custom_posts_columns( $posts_columns ) {\n $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' );\n return $posts_columns;\n}\nadd_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' );\n\nfunction etdispo_quickedit_custom_column_display( $column_name, $post_id ) {\n if ( 'et2018-quantita_birra' == $column_name ) {\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n\n if ( $etdispo_regi ) {\n echo esc_html( $etdispo_regi );\n } else {\n esc_html_e( 'N/A', 'etdispo' );\n }\n }\n}\nadd_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 );\n\nfunction etdispo_quickedit_fields( $column_name, $post_type, $post_id ) {\n if ( 'et2018-quantita_birra' != $column_name )\n return;\n\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n ?&gt;\n &lt;fieldset class=\"inline-edit-col-right\"&gt;\n &lt;div class=\"inline-edit-col\"&gt;\n &lt;label&gt;\n &lt;span class=\"title\"&gt;&lt;?php esc_html_e( 'Disponibilità', 'etdispo' ); ?&gt;&lt;/span&gt;\n &lt;span class=\"input-text-wrap\"&gt;\n &lt;input type=\"text\" name=\"et2018-quantita_birra\" class=\"etdispoedit\" value=\"\"&gt;\n &lt;/span&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;/fieldset&gt;\n &lt;?php\n}\nadd_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 );\nfunction etdispo_quickedit_save_post( $post_id, $post ) {\n // if called by autosave, then bail here\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n\n // if this \"post\" post type?\n if ( $post-&gt;post_type != 'post' )\n return;\n\n // does this user have permissions?\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n\n // update!\n if ( isset( $_POST['et2018-quantita_birra'] ) ) {\n update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] );\n }\n}\nadd_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 );\n\nfunction etdispo_quickedit_javascript() {\n $current_screen = get_current_screen();\n if ( $current_screen-&gt;id != 'edit-post' || $current_screen-&gt;post_type != 'post' )\n return;\n\n // Ensure jQuery library loads\n wp_enqueue_script( 'jquery' );\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery( function( $ ) {\n $( '#the-list' ).on( 'click', 'a.editinline', function( e ) {\n e.preventDefault();\n var editDispo = $(this).data( 'edit-dispo' );\n inlineEditPost.revert();\n $( '.etdispoedit' ).val( editDispo ? editDispo : '' );\n });\n });\n &lt;/script&gt;\n &lt;?php\n}\nadd_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' );\n/* Qui */\nfunction etdispo_quickedit_set_data( $actions, $post ) {\n $found_value = get_post_meta( $post-&gt;ID, 'et2018-quantita_birra', true );\n\n if ( $found_value ) {\n if ( isset( $actions['inline hide-if-no-js'] ) ) {\n $new_attribute = sprintf( 'data-edit-dispo=\"%s\"', esc_attr( $found_value ) );\n $actions['inline hide-if-no-js'] = str_replace( 'class=', \"$new_attribute class=\", $actions['inline hide-if-no-js'] );\n }\n }\n\n return $actions;\n}\nadd_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2);\n</code></pre>\n" } ]
2018/04/10
[ "https://wordpress.stackexchange.com/questions/300411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59932/" ]
I'm currently developing a wordpress version of a website on a dev.acme.com domain, while the old site (www.acme.com) remains active (if it's relevant, it's not on a wordpress platform.) The content will be migrated over at some point (that part has been tested and is going to work fine.) All my URLs (for images and links) inside posts are relative, so there's no worry about them when I switch to live.... But I notice that Yoast stores its FB images with an absolute path of dev.acme.com, and I think I am hearing that WP stores its featured images that way too. Any things / thoughts for how to avoid utter chaos on these two stored image paths when I do switch live?
Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ). ``` /** ``` \* \* Aggiungi Disponibilità nel Quick Edit \*/ ``` function etdispo_quickedit_custom_posts_columns( $posts_columns ) { $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' ); return $posts_columns; } add_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' ); function etdispo_quickedit_custom_column_display( $column_name, $post_id ) { if ( 'et2018-quantita_birra' == $column_name ) { $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); if ( $etdispo_regi ) { echo esc_html( $etdispo_regi ); } else { esc_html_e( 'N/A', 'etdispo' ); } } } add_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 ); function etdispo_quickedit_fields( $column_name, $post_type, $post_id ) { if ( 'et2018-quantita_birra' != $column_name ) return; $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <label> <span class="title"><?php esc_html_e( 'Disponibilità', 'etdispo' ); ?></span> <span class="input-text-wrap"> <input type="text" name="et2018-quantita_birra" class="etdispoedit" value=""> </span> </label> </div> </fieldset> <?php } add_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 ); function etdispo_quickedit_save_post( $post_id, $post ) { // if called by autosave, then bail here if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // if this "post" post type? if ( $post->post_type != 'post' ) return; // does this user have permissions? if ( ! current_user_can( 'edit_post', $post_id ) ) return; // update! if ( isset( $_POST['et2018-quantita_birra'] ) ) { update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] ); } } add_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 ); function etdispo_quickedit_javascript() { $current_screen = get_current_screen(); if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' ) return; // Ensure jQuery library loads wp_enqueue_script( 'jquery' ); ?> <script type="text/javascript"> jQuery( function( $ ) { $( '#the-list' ).on( 'click', 'a.editinline', function( e ) { e.preventDefault(); var editDispo = $(this).data( 'edit-dispo' ); inlineEditPost.revert(); $( '.etdispoedit' ).val( editDispo ? editDispo : '' ); }); }); </script> <?php } add_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' ); /* Qui */ function etdispo_quickedit_set_data( $actions, $post ) { $found_value = get_post_meta( $post->ID, 'et2018-quantita_birra', true ); if ( $found_value ) { if ( isset( $actions['inline hide-if-no-js'] ) ) { $new_attribute = sprintf( 'data-edit-dispo="%s"', esc_attr( $found_value ) ); $actions['inline hide-if-no-js'] = str_replace( 'class=', "$new_attribute class=", $actions['inline hide-if-no-js'] ); } } return $actions; } add_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2); ```
300,415
<p>I'm trying to add a filter to the add media button for a custom post type. I'm using add_filter('media_send_to_editor') and it work's fine, but I'm having difficulty finding a way to determine the post type of the admin page so that I can only perform the filter on that specific post type. Any ideas on how I can get the post post type?</p> <p>I'm trying to filter the output of the image and caption, but I only want to do it on a specific post type. I would need the other post types to function as normally when adding images. I need the the image to be wrapped in a shortcode and the caption to be included in a parameter for that shortcode. I have it working. I just need a way to make it conditional for post types.</p>
[ { "answer_id": 300407, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 2, "selected": false, "text": "<p>Sorry, I've had to change my answer after checking the WordPress Codex on adding custom editable data to the quick edit. So you'll have to remove the references to <code>$post_id</code> too (from the <code>add_action</code> arguments and from within your function).</p>\n\n<p>It looks like the <code>quick_edit_custom_box</code> only takes 2 arguments: <code>$column_name</code> and <code>$post_type</code>. Then for getting and displaying the value, this has to be done using some more PHP and Javascript.</p>\n\n<p>If you read further in to the WordPress Codex on the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box\" rel=\"nofollow noreferrer\">quick edit custom box</a> and read further down to the section on '<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box#Setting_Existing_Values\" rel=\"nofollow noreferrer\">Setting Existing Values</a>', you'll see there's a fair bit more work required in order to do this.</p>\n\n<p>I'd suggest reading the docs in a bit more detail as it's not quite as straight-forward as I first thought...</p>\n" }, { "answer_id": 300948, "author": "Downloadtaky", "author_id": 4107, "author_profile": "https://wordpress.stackexchange.com/users/4107", "pm_score": 2, "selected": true, "text": "<p>Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ).</p>\n\n<pre><code>/**\n</code></pre>\n\n<p>*\n * Aggiungi Disponibilità nel Quick Edit\n*/</p>\n\n<pre><code>function etdispo_quickedit_custom_posts_columns( $posts_columns ) {\n $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' );\n return $posts_columns;\n}\nadd_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' );\n\nfunction etdispo_quickedit_custom_column_display( $column_name, $post_id ) {\n if ( 'et2018-quantita_birra' == $column_name ) {\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n\n if ( $etdispo_regi ) {\n echo esc_html( $etdispo_regi );\n } else {\n esc_html_e( 'N/A', 'etdispo' );\n }\n }\n}\nadd_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 );\n\nfunction etdispo_quickedit_fields( $column_name, $post_type, $post_id ) {\n if ( 'et2018-quantita_birra' != $column_name )\n return;\n\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n ?&gt;\n &lt;fieldset class=\"inline-edit-col-right\"&gt;\n &lt;div class=\"inline-edit-col\"&gt;\n &lt;label&gt;\n &lt;span class=\"title\"&gt;&lt;?php esc_html_e( 'Disponibilità', 'etdispo' ); ?&gt;&lt;/span&gt;\n &lt;span class=\"input-text-wrap\"&gt;\n &lt;input type=\"text\" name=\"et2018-quantita_birra\" class=\"etdispoedit\" value=\"\"&gt;\n &lt;/span&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;/fieldset&gt;\n &lt;?php\n}\nadd_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 );\nfunction etdispo_quickedit_save_post( $post_id, $post ) {\n // if called by autosave, then bail here\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n\n // if this \"post\" post type?\n if ( $post-&gt;post_type != 'post' )\n return;\n\n // does this user have permissions?\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n\n // update!\n if ( isset( $_POST['et2018-quantita_birra'] ) ) {\n update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] );\n }\n}\nadd_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 );\n\nfunction etdispo_quickedit_javascript() {\n $current_screen = get_current_screen();\n if ( $current_screen-&gt;id != 'edit-post' || $current_screen-&gt;post_type != 'post' )\n return;\n\n // Ensure jQuery library loads\n wp_enqueue_script( 'jquery' );\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery( function( $ ) {\n $( '#the-list' ).on( 'click', 'a.editinline', function( e ) {\n e.preventDefault();\n var editDispo = $(this).data( 'edit-dispo' );\n inlineEditPost.revert();\n $( '.etdispoedit' ).val( editDispo ? editDispo : '' );\n });\n });\n &lt;/script&gt;\n &lt;?php\n}\nadd_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' );\n/* Qui */\nfunction etdispo_quickedit_set_data( $actions, $post ) {\n $found_value = get_post_meta( $post-&gt;ID, 'et2018-quantita_birra', true );\n\n if ( $found_value ) {\n if ( isset( $actions['inline hide-if-no-js'] ) ) {\n $new_attribute = sprintf( 'data-edit-dispo=\"%s\"', esc_attr( $found_value ) );\n $actions['inline hide-if-no-js'] = str_replace( 'class=', \"$new_attribute class=\", $actions['inline hide-if-no-js'] );\n }\n }\n\n return $actions;\n}\nadd_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2);\n</code></pre>\n" } ]
2018/04/11
[ "https://wordpress.stackexchange.com/questions/300415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136939/" ]
I'm trying to add a filter to the add media button for a custom post type. I'm using add\_filter('media\_send\_to\_editor') and it work's fine, but I'm having difficulty finding a way to determine the post type of the admin page so that I can only perform the filter on that specific post type. Any ideas on how I can get the post post type? I'm trying to filter the output of the image and caption, but I only want to do it on a specific post type. I would need the other post types to function as normally when adding images. I need the the image to be wrapped in a shortcode and the caption to be included in a parameter for that shortcode. I have it working. I just need a way to make it conditional for post types.
Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ). ``` /** ``` \* \* Aggiungi Disponibilità nel Quick Edit \*/ ``` function etdispo_quickedit_custom_posts_columns( $posts_columns ) { $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' ); return $posts_columns; } add_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' ); function etdispo_quickedit_custom_column_display( $column_name, $post_id ) { if ( 'et2018-quantita_birra' == $column_name ) { $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); if ( $etdispo_regi ) { echo esc_html( $etdispo_regi ); } else { esc_html_e( 'N/A', 'etdispo' ); } } } add_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 ); function etdispo_quickedit_fields( $column_name, $post_type, $post_id ) { if ( 'et2018-quantita_birra' != $column_name ) return; $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <label> <span class="title"><?php esc_html_e( 'Disponibilità', 'etdispo' ); ?></span> <span class="input-text-wrap"> <input type="text" name="et2018-quantita_birra" class="etdispoedit" value=""> </span> </label> </div> </fieldset> <?php } add_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 ); function etdispo_quickedit_save_post( $post_id, $post ) { // if called by autosave, then bail here if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // if this "post" post type? if ( $post->post_type != 'post' ) return; // does this user have permissions? if ( ! current_user_can( 'edit_post', $post_id ) ) return; // update! if ( isset( $_POST['et2018-quantita_birra'] ) ) { update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] ); } } add_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 ); function etdispo_quickedit_javascript() { $current_screen = get_current_screen(); if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' ) return; // Ensure jQuery library loads wp_enqueue_script( 'jquery' ); ?> <script type="text/javascript"> jQuery( function( $ ) { $( '#the-list' ).on( 'click', 'a.editinline', function( e ) { e.preventDefault(); var editDispo = $(this).data( 'edit-dispo' ); inlineEditPost.revert(); $( '.etdispoedit' ).val( editDispo ? editDispo : '' ); }); }); </script> <?php } add_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' ); /* Qui */ function etdispo_quickedit_set_data( $actions, $post ) { $found_value = get_post_meta( $post->ID, 'et2018-quantita_birra', true ); if ( $found_value ) { if ( isset( $actions['inline hide-if-no-js'] ) ) { $new_attribute = sprintf( 'data-edit-dispo="%s"', esc_attr( $found_value ) ); $actions['inline hide-if-no-js'] = str_replace( 'class=', "$new_attribute class=", $actions['inline hide-if-no-js'] ); } } return $actions; } add_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2); ```
300,424
<p>I'm trying to set WordPress permalink in sitename/post name in Hindi language but it's gives me <code>%e0%a4%b2%e0%a5%8b%e0%a4%b0%e0%a4%ae-%e0%a4%87%e0%a4%aa%e0%a5%8d%e0%a4%b8%e0%a4%ae-%e0%a4%95%e0%a5%8d%e0%a4%af%e0%a4%be-%e0%a4%b9%e0%a5%88/</code></p> <p>This kind of permalink .</p>
[ { "answer_id": 300407, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 2, "selected": false, "text": "<p>Sorry, I've had to change my answer after checking the WordPress Codex on adding custom editable data to the quick edit. So you'll have to remove the references to <code>$post_id</code> too (from the <code>add_action</code> arguments and from within your function).</p>\n\n<p>It looks like the <code>quick_edit_custom_box</code> only takes 2 arguments: <code>$column_name</code> and <code>$post_type</code>. Then for getting and displaying the value, this has to be done using some more PHP and Javascript.</p>\n\n<p>If you read further in to the WordPress Codex on the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box\" rel=\"nofollow noreferrer\">quick edit custom box</a> and read further down to the section on '<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/quick_edit_custom_box#Setting_Existing_Values\" rel=\"nofollow noreferrer\">Setting Existing Values</a>', you'll see there's a fair bit more work required in order to do this.</p>\n\n<p>I'd suggest reading the docs in a bit more detail as it's not quite as straight-forward as I first thought...</p>\n" }, { "answer_id": 300948, "author": "Downloadtaky", "author_id": 4107, "author_profile": "https://wordpress.stackexchange.com/users/4107", "pm_score": 2, "selected": true, "text": "<p>Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ).</p>\n\n<pre><code>/**\n</code></pre>\n\n<p>*\n * Aggiungi Disponibilità nel Quick Edit\n*/</p>\n\n<pre><code>function etdispo_quickedit_custom_posts_columns( $posts_columns ) {\n $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' );\n return $posts_columns;\n}\nadd_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' );\n\nfunction etdispo_quickedit_custom_column_display( $column_name, $post_id ) {\n if ( 'et2018-quantita_birra' == $column_name ) {\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n\n if ( $etdispo_regi ) {\n echo esc_html( $etdispo_regi );\n } else {\n esc_html_e( 'N/A', 'etdispo' );\n }\n }\n}\nadd_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 );\n\nfunction etdispo_quickedit_fields( $column_name, $post_type, $post_id ) {\n if ( 'et2018-quantita_birra' != $column_name )\n return;\n\n $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );\n ?&gt;\n &lt;fieldset class=\"inline-edit-col-right\"&gt;\n &lt;div class=\"inline-edit-col\"&gt;\n &lt;label&gt;\n &lt;span class=\"title\"&gt;&lt;?php esc_html_e( 'Disponibilità', 'etdispo' ); ?&gt;&lt;/span&gt;\n &lt;span class=\"input-text-wrap\"&gt;\n &lt;input type=\"text\" name=\"et2018-quantita_birra\" class=\"etdispoedit\" value=\"\"&gt;\n &lt;/span&gt;\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;/fieldset&gt;\n &lt;?php\n}\nadd_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 );\nfunction etdispo_quickedit_save_post( $post_id, $post ) {\n // if called by autosave, then bail here\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n\n // if this \"post\" post type?\n if ( $post-&gt;post_type != 'post' )\n return;\n\n // does this user have permissions?\n if ( ! current_user_can( 'edit_post', $post_id ) )\n return;\n\n // update!\n if ( isset( $_POST['et2018-quantita_birra'] ) ) {\n update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] );\n }\n}\nadd_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 );\n\nfunction etdispo_quickedit_javascript() {\n $current_screen = get_current_screen();\n if ( $current_screen-&gt;id != 'edit-post' || $current_screen-&gt;post_type != 'post' )\n return;\n\n // Ensure jQuery library loads\n wp_enqueue_script( 'jquery' );\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery( function( $ ) {\n $( '#the-list' ).on( 'click', 'a.editinline', function( e ) {\n e.preventDefault();\n var editDispo = $(this).data( 'edit-dispo' );\n inlineEditPost.revert();\n $( '.etdispoedit' ).val( editDispo ? editDispo : '' );\n });\n });\n &lt;/script&gt;\n &lt;?php\n}\nadd_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' );\n/* Qui */\nfunction etdispo_quickedit_set_data( $actions, $post ) {\n $found_value = get_post_meta( $post-&gt;ID, 'et2018-quantita_birra', true );\n\n if ( $found_value ) {\n if ( isset( $actions['inline hide-if-no-js'] ) ) {\n $new_attribute = sprintf( 'data-edit-dispo=\"%s\"', esc_attr( $found_value ) );\n $actions['inline hide-if-no-js'] = str_replace( 'class=', \"$new_attribute class=\", $actions['inline hide-if-no-js'] );\n }\n }\n\n return $actions;\n}\nadd_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2);\n</code></pre>\n" } ]
2018/04/11
[ "https://wordpress.stackexchange.com/questions/300424", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141551/" ]
I'm trying to set WordPress permalink in sitename/post name in Hindi language but it's gives me `%e0%a4%b2%e0%a5%8b%e0%a4%b0%e0%a4%ae-%e0%a4%87%e0%a4%aa%e0%a5%8d%e0%a4%b8%e0%a4%ae-%e0%a4%95%e0%a5%8d%e0%a4%af%e0%a4%be-%e0%a4%b9%e0%a5%88/` This kind of permalink .
Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ). ``` /** ``` \* \* Aggiungi Disponibilità nel Quick Edit \*/ ``` function etdispo_quickedit_custom_posts_columns( $posts_columns ) { $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' ); return $posts_columns; } add_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' ); function etdispo_quickedit_custom_column_display( $column_name, $post_id ) { if ( 'et2018-quantita_birra' == $column_name ) { $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); if ( $etdispo_regi ) { echo esc_html( $etdispo_regi ); } else { esc_html_e( 'N/A', 'etdispo' ); } } } add_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 ); function etdispo_quickedit_fields( $column_name, $post_type, $post_id ) { if ( 'et2018-quantita_birra' != $column_name ) return; $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true ); ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <label> <span class="title"><?php esc_html_e( 'Disponibilità', 'etdispo' ); ?></span> <span class="input-text-wrap"> <input type="text" name="et2018-quantita_birra" class="etdispoedit" value=""> </span> </label> </div> </fieldset> <?php } add_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 ); function etdispo_quickedit_save_post( $post_id, $post ) { // if called by autosave, then bail here if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // if this "post" post type? if ( $post->post_type != 'post' ) return; // does this user have permissions? if ( ! current_user_can( 'edit_post', $post_id ) ) return; // update! if ( isset( $_POST['et2018-quantita_birra'] ) ) { update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] ); } } add_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 ); function etdispo_quickedit_javascript() { $current_screen = get_current_screen(); if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' ) return; // Ensure jQuery library loads wp_enqueue_script( 'jquery' ); ?> <script type="text/javascript"> jQuery( function( $ ) { $( '#the-list' ).on( 'click', 'a.editinline', function( e ) { e.preventDefault(); var editDispo = $(this).data( 'edit-dispo' ); inlineEditPost.revert(); $( '.etdispoedit' ).val( editDispo ? editDispo : '' ); }); }); </script> <?php } add_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' ); /* Qui */ function etdispo_quickedit_set_data( $actions, $post ) { $found_value = get_post_meta( $post->ID, 'et2018-quantita_birra', true ); if ( $found_value ) { if ( isset( $actions['inline hide-if-no-js'] ) ) { $new_attribute = sprintf( 'data-edit-dispo="%s"', esc_attr( $found_value ) ); $actions['inline hide-if-no-js'] = str_replace( 'class=', "$new_attribute class=", $actions['inline hide-if-no-js'] ); } } return $actions; } add_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2); ```
300,472
<p>I'm trying to set up a number of 301 redirects using the .htaccess file. For some reason it is not working for me.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress # BEGIN 301 Redirects Redirect 301 /about-us/ http://www.newsite.com/new-page/about-us/ # END 301 Redirects </code></pre> <p>Can anyone shed light on why this may not be working for my Wordpress site?</p>
[ { "answer_id": 300545, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>In general it is much better to handle redirect on the PHP side. (assuming is is implemented by semi competent developer) It is more flexible and uses less overhead.</p>\n\n<p>Specifically to the question, the set of wordpress rules will handle <strong>all</strong> URLs, therefor your rule is too late and you should move it to be before the wordpress rules.</p>\n" }, { "answer_id": 300554, "author": "Tejas", "author_id": 130562, "author_profile": "https://wordpress.stackexchange.com/users/130562", "pm_score": 0, "selected": false, "text": "<p>Try to use following code:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\n\nRewriteRule ^old-page-name(/.*)?$ https://www.myurl.com/new-page-name/ [L,R=301,NC]\n\nRewriteRule ^another-old-page(/.*)?$ https://www.myurl.com/another-new-page/ [L,R=301,NC]\n\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 303176, "author": "gintsg", "author_id": 110326, "author_profile": "https://wordpress.stackexchange.com/users/110326", "pm_score": 0, "selected": false, "text": "<p>For redirects like these, I would recommend using this plugin: <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/redirection/</a> It's easy to use and support even advanced REGEX redirects.</p>\n\n<p>I personally used the .htaccess file just for more advanced and domain related redirects, i.e. domain canonicalization.</p>\n\n<p>But if you really want to do this redirect in .htaccess file, then here is how you need to do it:</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\n# BEGIN 301 Redirects\nRedirect 301 /about-us/ http://www.newsite.com/new-page/about-us/\n# END 301 Redirects\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2018/04/11
[ "https://wordpress.stackexchange.com/questions/300472", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69376/" ]
I'm trying to set up a number of 301 redirects using the .htaccess file. For some reason it is not working for me. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # BEGIN 301 Redirects Redirect 301 /about-us/ http://www.newsite.com/new-page/about-us/ # END 301 Redirects ``` Can anyone shed light on why this may not be working for my Wordpress site?
In general it is much better to handle redirect on the PHP side. (assuming is is implemented by semi competent developer) It is more flexible and uses less overhead. Specifically to the question, the set of wordpress rules will handle **all** URLs, therefor your rule is too late and you should move it to be before the wordpress rules.
300,555
<p>I'm bringing up an issue that could not be solved after googling for solutions over a few days. The goal I have to meet is to output a pagination for a custom post type named office-magazines with working links. I already managed to output the pagination but clicking any of the links within it takes me to the top page. </p> <p>Here's the code I embedded into the page template:</p> <pre><code> &lt;?php global $wp_query, $paged; $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $args = array( 'post_type' =&gt; 'office-magazines', 'posts_per_page' =&gt; 9, 'paged' =&gt; $paged, 'has_archieve' =&gt; true ); $catquery = new WP_Query($args); ?&gt; &lt;p class="pagination"&gt; &lt;?php echo custom_pagination_bar( $loop ); ?&gt; &lt;/p&gt; </code></pre> <p>Passing <code>'post_type' =&gt; 'office-magazines'</code> is meant to filter out all posts apart from the ones belonging to the custom post type, <code>'office-magazines'</code>.</p> <p>Using the next code in functions.php, I intended to define the function of the pagination:</p> <pre><code>function custom_pagination_bar($custom_loop) { $big = 999999999; echo paginate_links( array( 'base' =&gt; str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' =&gt; '?paged=%#%', 'current' =&gt; max( 1, get_query_var('paged') ), 'total' =&gt; $custom_loop-&gt;max_num_pages ) ); } </code></pre> <p>The same code works for the main post pagination which is output in a separate template page but fails for the custom post pagination.</p> <p>Could someone please help me find a solution to getting the custom post pagination links to work?</p> <p>Hoping for some advice,</p> <p>Ead</p>
[ { "answer_id": 300531, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>It's a bit different in WP than in Drupal. First, the <code>admin</code> role is specifically designed to be the role that can do everything. Rather than try to restrict the admin role, it's best practice to create whatever custom roles you need - you would set up an <code>almost-admin</code> type role that has all the capabilities except the one you want to restrict. This is typically best for the site owners anyway since you can strip away a few of the more technical capabilities that only a developer would really need, and by having the owners' logins a bit more restricted, you don't have quite as many admin-level users floating around to where it becomes more and more likely that the site could be hacked. If the site is hacked but they've obtained a lower-level user login, you may be able to prevent some damage.</p>\n\n<p>The other problem is that the WP roles and capabilities system isn't set up to allow users to have partial access to capabilities. So, you can't allow any role to have <code>delete_users</code> capability for some roles and not others, even if you use popular user management plugins. But perhaps the other roles would suffice: if you deny them the ability to <code>delete_users</code> across the board you can still give them the ability to <code>add_users</code>, <code>edit_users</code>, and <code>promote_users</code> if those are what you really need to restrict.</p>\n" }, { "answer_id": 300532, "author": "Milan Bastola", "author_id": 137372, "author_profile": "https://wordpress.stackexchange.com/users/137372", "pm_score": -1, "selected": true, "text": "<ol>\n<li>Install User Role Editor Plugin</li>\n<li>Create a Role for them assign everything except removing admin. </li>\n</ol>\n" }, { "answer_id": 300535, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>This is a perfect use for the <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>map_meta_cap</code></a> filter.</p>\n\n<pre><code>function my_map_meta_cap( $caps, $cap, $user_id, $args ) {\n if( 'delete_user' !== $cap ) {\n return $caps;\n }\n if( isset( $args[0] ) &amp;&amp; 1 === $args[0] ) {\n $caps[] = 'cant_do_this';\n }\n return $caps;\n}\nadd_filter( 'map_meta_cap', 'my_map_meta_cap', 10, 4 );\n</code></pre>\n\n<p>This code requires that anyone trying to delete the user with a user_id of 1 must have the <code>cant_do_this</code> capability. Since no one has that capability, then nobody can delete this user.</p>\n\n<p>Of course, if your administrators can edit plugins then they can just disable the plugin and delete the user anyway. Probably best to use it as a must-use plugin.</p>\n" } ]
2018/04/12
[ "https://wordpress.stackexchange.com/questions/300555", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141638/" ]
I'm bringing up an issue that could not be solved after googling for solutions over a few days. The goal I have to meet is to output a pagination for a custom post type named office-magazines with working links. I already managed to output the pagination but clicking any of the links within it takes me to the top page. Here's the code I embedded into the page template: ``` <?php global $wp_query, $paged; $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $args = array( 'post_type' => 'office-magazines', 'posts_per_page' => 9, 'paged' => $paged, 'has_archieve' => true ); $catquery = new WP_Query($args); ?> <p class="pagination"> <?php echo custom_pagination_bar( $loop ); ?> </p> ``` Passing `'post_type' => 'office-magazines'` is meant to filter out all posts apart from the ones belonging to the custom post type, `'office-magazines'`. Using the next code in functions.php, I intended to define the function of the pagination: ``` function custom_pagination_bar($custom_loop) { $big = 999999999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $custom_loop->max_num_pages ) ); } ``` The same code works for the main post pagination which is output in a separate template page but fails for the custom post pagination. Could someone please help me find a solution to getting the custom post pagination links to work? Hoping for some advice, Ead
1. Install User Role Editor Plugin 2. Create a Role for them assign everything except removing admin.
300,582
<p>I'm working on a rather large WordPress project with over 40 plugins, also including a bunch of custom-made plugins specific to this project.</p> <p>This makes navigating the WordPress plugins folder rather troublesome. Is it possible to "organize" the plugins folder to look more like the example below?</p> <pre><code>- plugins - wp-plugins // All plugins downloaded from WordPress - custom-plugins // All custom written plugins </code></pre>
[ { "answer_id": 300531, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>It's a bit different in WP than in Drupal. First, the <code>admin</code> role is specifically designed to be the role that can do everything. Rather than try to restrict the admin role, it's best practice to create whatever custom roles you need - you would set up an <code>almost-admin</code> type role that has all the capabilities except the one you want to restrict. This is typically best for the site owners anyway since you can strip away a few of the more technical capabilities that only a developer would really need, and by having the owners' logins a bit more restricted, you don't have quite as many admin-level users floating around to where it becomes more and more likely that the site could be hacked. If the site is hacked but they've obtained a lower-level user login, you may be able to prevent some damage.</p>\n\n<p>The other problem is that the WP roles and capabilities system isn't set up to allow users to have partial access to capabilities. So, you can't allow any role to have <code>delete_users</code> capability for some roles and not others, even if you use popular user management plugins. But perhaps the other roles would suffice: if you deny them the ability to <code>delete_users</code> across the board you can still give them the ability to <code>add_users</code>, <code>edit_users</code>, and <code>promote_users</code> if those are what you really need to restrict.</p>\n" }, { "answer_id": 300532, "author": "Milan Bastola", "author_id": 137372, "author_profile": "https://wordpress.stackexchange.com/users/137372", "pm_score": -1, "selected": true, "text": "<ol>\n<li>Install User Role Editor Plugin</li>\n<li>Create a Role for them assign everything except removing admin. </li>\n</ol>\n" }, { "answer_id": 300535, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>This is a perfect use for the <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>map_meta_cap</code></a> filter.</p>\n\n<pre><code>function my_map_meta_cap( $caps, $cap, $user_id, $args ) {\n if( 'delete_user' !== $cap ) {\n return $caps;\n }\n if( isset( $args[0] ) &amp;&amp; 1 === $args[0] ) {\n $caps[] = 'cant_do_this';\n }\n return $caps;\n}\nadd_filter( 'map_meta_cap', 'my_map_meta_cap', 10, 4 );\n</code></pre>\n\n<p>This code requires that anyone trying to delete the user with a user_id of 1 must have the <code>cant_do_this</code> capability. Since no one has that capability, then nobody can delete this user.</p>\n\n<p>Of course, if your administrators can edit plugins then they can just disable the plugin and delete the user anyway. Probably best to use it as a must-use plugin.</p>\n" } ]
2018/04/12
[ "https://wordpress.stackexchange.com/questions/300582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22588/" ]
I'm working on a rather large WordPress project with over 40 plugins, also including a bunch of custom-made plugins specific to this project. This makes navigating the WordPress plugins folder rather troublesome. Is it possible to "organize" the plugins folder to look more like the example below? ``` - plugins - wp-plugins // All plugins downloaded from WordPress - custom-plugins // All custom written plugins ```
1. Install User Role Editor Plugin 2. Create a Role for them assign everything except removing admin.
300,585
<p>I've a bug that I cannot reproduce on my local/staging evn and occurs only on prod(having the same code, db and files). Here is what I get when visiting all of the default post types/taxonomies or custom created by me or plugins(it's not bugged on settings pages for ex):</p> <p>When visiting <code>/wp-admin/edit.php?post_type=page</code> the page loads as it should, immediately after it load the URL changes to </p> <pre><code>/wp-admin/edit.php?post_type=page%3Fpost_type%3Dpage </code></pre> <p>therefore any further action in this window will lead to Invalid post type. Updating the core and all of the plugins, or removing all of them didn't fixes the issue. Couldn't find anything related in the debug.log. Only when I disable my browser JS it's working fine, but I don't load any custom script to the wp admin. </p> <p>I'll really appreciate if someone can give a hint, thanks in advance.</p>
[ { "answer_id": 300592, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 1, "selected": false, "text": "<p>What you can do is copy live DB, and deploy it to dev. Once you do that, start to disabling plugins one by one to see which one causes an error. If it doesn't help - check where else you have code injections ( theme or drop-in or must use plugins). If it doesn't help you need to perform the same actions on live (which isn't better solution). I would suggest to open (with js disabled page \"<code>/wp-admin/edit.php?post_type=page</code>\" and see what js file and code included - from which plugins, this will be a massive hint where to search next.)</p>\n" }, { "answer_id": 301953, "author": "Kuliraj", "author_id": 128600, "author_profile": "https://wordpress.stackexchange.com/users/128600", "pm_score": 1, "selected": true, "text": "<p>Posting the solution I've found for my problem. </p>\n\n<p>It appears that we have mod_security on our prod env, and recommended clause is to replace \"server info\" and on what the site is hosted on(for security reasons).</p>\n\n<p>In my case it was replaced with IIS 6, and that tricked the WordPress installation as well, which on it's end is doing additional URL optimizations...</p>\n" } ]
2018/04/12
[ "https://wordpress.stackexchange.com/questions/300585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128600/" ]
I've a bug that I cannot reproduce on my local/staging evn and occurs only on prod(having the same code, db and files). Here is what I get when visiting all of the default post types/taxonomies or custom created by me or plugins(it's not bugged on settings pages for ex): When visiting `/wp-admin/edit.php?post_type=page` the page loads as it should, immediately after it load the URL changes to ``` /wp-admin/edit.php?post_type=page%3Fpost_type%3Dpage ``` therefore any further action in this window will lead to Invalid post type. Updating the core and all of the plugins, or removing all of them didn't fixes the issue. Couldn't find anything related in the debug.log. Only when I disable my browser JS it's working fine, but I don't load any custom script to the wp admin. I'll really appreciate if someone can give a hint, thanks in advance.
Posting the solution I've found for my problem. It appears that we have mod\_security on our prod env, and recommended clause is to replace "server info" and on what the site is hosted on(for security reasons). In my case it was replaced with IIS 6, and that tricked the WordPress installation as well, which on it's end is doing additional URL optimizations...
300,594
<p>Let's say I want to build a function that allows my users to like posts in my website.</p> <p>My intention is to store the ID of the user that liked the post as metadata.</p> <p>My question is what's the best way to go in terms of performance and 'queribility'.</p> <p>Separate row for each like:</p> <p><code>'liked_by'=>'3'</code><br> <code>'liked_by'=>'21'</code><br> <code>'liked_by'=>'17'</code></p> <p>Or just one row to hold a serialized array (json) with all IDs</p> <p><code>'liked_by'=>array('3','21','17')</code></p> <p>Considere I would like to store the date of each like too.</p> <p><code>array( $user_id => $current_date )</code></p> <p>Else take in consideration that I most ensure that all post metadata is useful for queries!</p> <p>EDIT...</p> <p>I used the "likes" example for simplicity, but in reality the function I want to create for my application is for users to pay to unlock extra content per post. The market for my applications isn't too big, lets say I don't expect more than 400 unlocks per post, but that means 400 additional rows per post just to hold the users that unlocked the post content + the date of each unlock.</p>
[ { "answer_id": 300595, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Very simple, meta should not be queried as it do not scale. Once this is out of the way, you should prefer storing data as serialized array as it makes the meta table smaller and therefor all operations on it faster.</p>\n\n<p>OTOH, the array method will not scale very well if your use case require updating a specific post data frequently, as the cost for each \"write\" operation gets higher the bigger the array is, but I don't think I ever heard of any wordpress site that found this to be a bottle neck.</p>\n" }, { "answer_id": 300610, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p><strong>Neither option are the correct option for your use case</strong></p>\n\n<p>Your question is barking up the wrong tree, because you neglected to mention that you intend to search for these posts based on the values the meta holds.</p>\n\n<p>If you're displaying a post, you can use either method, though the first is cleaner/simpler to handle in code. <code>get_post_meta</code> is fast and relies on table indexes, and WP fetches the post meta in advance anyway.</p>\n\n<p>The problem here is if you have thousands of post meta, or a handful of hyper big post meta, in the extreme cases this can cause you to run out of memory or prevent it being cached by object caches</p>\n\n<h2>But What If You Searched For Them?</h2>\n\n<p>Showing a list of users who liked the post is going to be fast, but showing a list of posts a user liked?</p>\n\n<p><strong>This is what would happen to your sites speed and performance</strong>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/24k2J.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/24k2J.gif\" alt=\"enter image description here\"></a></p>\n\n<p>Searching for posts by their post meta is very, very bad. I've seen sites running on huge servers crippled by just a handful of these. It's a huge slowdown, the kind of query that could take 10-20 seconds if it finishes at all once you have more than a handful of posts.</p>\n\n<p>In this case, you would face a new problem too, if you had chosen option 2, the very ability to find those posts would become an issue. Thus option 1 would be superior, but performance would still be terrible</p>\n\n<h2>A Marginally Superior Solution With the Opposite Tradeoff</h2>\n\n<p>Use user meta to store the post IDs, rather than post meta to store the user IDs. Still has issues, aka showing a list of users who liked or unlocked a post is now super expensive. But showing a user all the posts they've liked is fast.</p>\n\n<h2>The Real Solution, and a General Rule of Thumb</h2>\n\n<p>If you need to store something, and you need to search/find/filter or show posts that have this special information, <strong>use a taxonomy</strong>.</p>\n\n<p>In this case, a taxonomy named <code>unlocked_by</code>, where the term slug/name is the user ID that liked it.</p>\n\n<p>Now your query is <strong>super</strong> fast:</p>\n\n<pre><code>$q = new WP_Query([\n 'unlocked_by' =&gt; get_current_user_id()\n]);\n</code></pre>\n\n<p>In fact, it's so fast, you don't even need that query, WP created a post archive at <code>/unlocked_by/2/</code> ( I'm user number 2 btw ), assuming you enabled that.</p>\n\n<p>You could even add the parameter via <code>pre_get_posts</code> so it happens transparently.</p>\n\n<p>The <code>wp_get_object_terms</code> and <code>wp_get_object_terms</code> functions are your friend here</p>\n" } ]
2018/04/12
[ "https://wordpress.stackexchange.com/questions/300594", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126374/" ]
Let's say I want to build a function that allows my users to like posts in my website. My intention is to store the ID of the user that liked the post as metadata. My question is what's the best way to go in terms of performance and 'queribility'. Separate row for each like: `'liked_by'=>'3'` `'liked_by'=>'21'` `'liked_by'=>'17'` Or just one row to hold a serialized array (json) with all IDs `'liked_by'=>array('3','21','17')` Considere I would like to store the date of each like too. `array( $user_id => $current_date )` Else take in consideration that I most ensure that all post metadata is useful for queries! EDIT... I used the "likes" example for simplicity, but in reality the function I want to create for my application is for users to pay to unlock extra content per post. The market for my applications isn't too big, lets say I don't expect more than 400 unlocks per post, but that means 400 additional rows per post just to hold the users that unlocked the post content + the date of each unlock.
**Neither option are the correct option for your use case** Your question is barking up the wrong tree, because you neglected to mention that you intend to search for these posts based on the values the meta holds. If you're displaying a post, you can use either method, though the first is cleaner/simpler to handle in code. `get_post_meta` is fast and relies on table indexes, and WP fetches the post meta in advance anyway. The problem here is if you have thousands of post meta, or a handful of hyper big post meta, in the extreme cases this can cause you to run out of memory or prevent it being cached by object caches But What If You Searched For Them? ---------------------------------- Showing a list of users who liked the post is going to be fast, but showing a list of posts a user liked? **This is what would happen to your sites speed and performance**: [![enter image description here](https://i.stack.imgur.com/24k2J.gif)](https://i.stack.imgur.com/24k2J.gif) Searching for posts by their post meta is very, very bad. I've seen sites running on huge servers crippled by just a handful of these. It's a huge slowdown, the kind of query that could take 10-20 seconds if it finishes at all once you have more than a handful of posts. In this case, you would face a new problem too, if you had chosen option 2, the very ability to find those posts would become an issue. Thus option 1 would be superior, but performance would still be terrible A Marginally Superior Solution With the Opposite Tradeoff --------------------------------------------------------- Use user meta to store the post IDs, rather than post meta to store the user IDs. Still has issues, aka showing a list of users who liked or unlocked a post is now super expensive. But showing a user all the posts they've liked is fast. The Real Solution, and a General Rule of Thumb ---------------------------------------------- If you need to store something, and you need to search/find/filter or show posts that have this special information, **use a taxonomy**. In this case, a taxonomy named `unlocked_by`, where the term slug/name is the user ID that liked it. Now your query is **super** fast: ``` $q = new WP_Query([ 'unlocked_by' => get_current_user_id() ]); ``` In fact, it's so fast, you don't even need that query, WP created a post archive at `/unlocked_by/2/` ( I'm user number 2 btw ), assuming you enabled that. You could even add the parameter via `pre_get_posts` so it happens transparently. The `wp_get_object_terms` and `wp_get_object_terms` functions are your friend here
300,621
<p>In my functions.php file I am loading a particular js script on only the page it is required, as I don't want to load it unnecessarily on pages that don't require it.</p> <pre><code>function tabs_enqueue() { if(is_page( 205 )) { wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true); } } add_action('wp_enqueue_scripts', 'tabs_enqueue'); </code></pre> <p>After testing, this works 100% but my problem is that I don't know where to put the actual jquery on the page that I want it. I can't put it into the footer because then I get errors on the other pages because it is trying to run the code without the js file being loaded. I want to place the code just before the closing body tag. If I put this after the get_footer() code then it is right at the bottom of the source code and if I put it before the get_footer() then it is called before I even load the js files. So, how would I get this code to display just before the closing body tag?</p> <pre><code> &lt;script&gt; jQuery(window).load(function() { //code here }); &lt;/script&gt; </code></pre>
[ { "answer_id": 300623, "author": "Felipe Elia", "author_id": 122788, "author_profile": "https://wordpress.stackexchange.com/users/122788", "pm_score": 2, "selected": false, "text": "<p>You don't need to add it on a template, you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\">wp_add_inline_script()</a> function. It'd be something like:</p>\n\n<pre><code>function tabs_enqueue() {\n if(is_page( 205 )) {\n wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true);\n wp_add_inline_script( 'ui',\n 'jQuery(window).load(function() {\n //code here\n });' );\n }\n}\nadd_action('wp_enqueue_scripts', 'tabs_enqueue');\n</code></pre>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 300626, "author": "dawoodman71", "author_id": 76486, "author_profile": "https://wordpress.stackexchange.com/users/76486", "pm_score": 1, "selected": false, "text": "<p>While Felipe Elia's answer works, it's better to separate your code. You don't want to have to update your PHP file to change Javascript.</p>\n\n<p>I would add a reference to your javascript file within your page check and be sure to include 'ui' in your required array so your new script won't load until after 'ui' is loaded.</p>\n\n<pre><code>wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/myScript.js', ['ui']);\n</code></pre>\n\n<p>Then create a file (js/myScript.js) that holds your custom Javascript. I recommend putting your code in a closure so it doesn't get affected by any other scripts.</p>\n\n<pre><code>(function($, window, document){\n // Use strict mode to reduce development errors.\n \"use strict\";\n\n // Put your code here.\n\n})(jQuery, window, document);\n</code></pre>\n" } ]
2018/04/12
[ "https://wordpress.stackexchange.com/questions/300621", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140276/" ]
In my functions.php file I am loading a particular js script on only the page it is required, as I don't want to load it unnecessarily on pages that don't require it. ``` function tabs_enqueue() { if(is_page( 205 )) { wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true); } } add_action('wp_enqueue_scripts', 'tabs_enqueue'); ``` After testing, this works 100% but my problem is that I don't know where to put the actual jquery on the page that I want it. I can't put it into the footer because then I get errors on the other pages because it is trying to run the code without the js file being loaded. I want to place the code just before the closing body tag. If I put this after the get\_footer() code then it is right at the bottom of the source code and if I put it before the get\_footer() then it is called before I even load the js files. So, how would I get this code to display just before the closing body tag? ``` <script> jQuery(window).load(function() { //code here }); </script> ```
You don't need to add it on a template, you can use the [wp\_add\_inline\_script()](https://developer.wordpress.org/reference/functions/wp_add_inline_script/) function. It'd be something like: ``` function tabs_enqueue() { if(is_page( 205 )) { wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true); wp_add_inline_script( 'ui', 'jQuery(window).load(function() { //code here });' ); } } add_action('wp_enqueue_scripts', 'tabs_enqueue'); ``` Hope it helps!
300,624
<p>I have created a new control (checkbox) in WP Customizer. The way it should work is as it follows: the corresponding section should display the last published post when the checkbox is checked (true) or a custom background image (and some content) when the checkbox is unchecked (false).</p> <p>Everything works fine on first setting change. Let's say the input is unchecked on page load - the section will display a custom background image. If I check the checkbox the section refreshes and the last post gets displayed. Until here everything is fine. </p> <p>But if I uncheck the checkbox (as a second action on same control) nothing happens. Still nothing on next checks/unchecks.</p> <p>I don't have any JS related to this control (I've also removed all custom JS and the issue persists).</p> <p><strong>customizer.php</strong></p> <pre><code>$wp_customize-&gt;add_setting( 'latest_post', array( 'default' =&gt; "", 'type' =&gt; 'theme_mod', 'capability' =&gt; 'edit_theme_options', 'transport' =&gt; 'postMessage', ) ); $wp_customize-&gt;add_control('latest_post', array( 'label' =&gt; __( 'Header Content', 'mytheme' ), 'section' =&gt; 'header_section', 'settings' =&gt; 'latest_post', 'type' =&gt; 'checkbox' ) ); $wp_customize-&gt;selective_refresh-&gt;add_partial( 'latest_post', array( 'selector' =&gt; '.header-section', 'render_callback' =&gt; 'header_markup' ) ); function header_markup(){ $latest_post = get_theme_mod('latest_post'); switch($latest_post): case true: return "latest post"; case false: return "custom media"; default: return "custom media"; endswitch; } </code></pre> <p><strong>html</strong></p> <pre><code>&lt;div class="header-section"&gt; &lt;php echo header_markup(); ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 300623, "author": "Felipe Elia", "author_id": 122788, "author_profile": "https://wordpress.stackexchange.com/users/122788", "pm_score": 2, "selected": false, "text": "<p>You don't need to add it on a template, you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\">wp_add_inline_script()</a> function. It'd be something like:</p>\n\n<pre><code>function tabs_enqueue() {\n if(is_page( 205 )) {\n wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true);\n wp_add_inline_script( 'ui',\n 'jQuery(window).load(function() {\n //code here\n });' );\n }\n}\nadd_action('wp_enqueue_scripts', 'tabs_enqueue');\n</code></pre>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 300626, "author": "dawoodman71", "author_id": 76486, "author_profile": "https://wordpress.stackexchange.com/users/76486", "pm_score": 1, "selected": false, "text": "<p>While Felipe Elia's answer works, it's better to separate your code. You don't want to have to update your PHP file to change Javascript.</p>\n\n<p>I would add a reference to your javascript file within your page check and be sure to include 'ui' in your required array so your new script won't load until after 'ui' is loaded.</p>\n\n<pre><code>wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/myScript.js', ['ui']);\n</code></pre>\n\n<p>Then create a file (js/myScript.js) that holds your custom Javascript. I recommend putting your code in a closure so it doesn't get affected by any other scripts.</p>\n\n<pre><code>(function($, window, document){\n // Use strict mode to reduce development errors.\n \"use strict\";\n\n // Put your code here.\n\n})(jQuery, window, document);\n</code></pre>\n" } ]
2018/04/12
[ "https://wordpress.stackexchange.com/questions/300624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141683/" ]
I have created a new control (checkbox) in WP Customizer. The way it should work is as it follows: the corresponding section should display the last published post when the checkbox is checked (true) or a custom background image (and some content) when the checkbox is unchecked (false). Everything works fine on first setting change. Let's say the input is unchecked on page load - the section will display a custom background image. If I check the checkbox the section refreshes and the last post gets displayed. Until here everything is fine. But if I uncheck the checkbox (as a second action on same control) nothing happens. Still nothing on next checks/unchecks. I don't have any JS related to this control (I've also removed all custom JS and the issue persists). **customizer.php** ``` $wp_customize->add_setting( 'latest_post', array( 'default' => "", 'type' => 'theme_mod', 'capability' => 'edit_theme_options', 'transport' => 'postMessage', ) ); $wp_customize->add_control('latest_post', array( 'label' => __( 'Header Content', 'mytheme' ), 'section' => 'header_section', 'settings' => 'latest_post', 'type' => 'checkbox' ) ); $wp_customize->selective_refresh->add_partial( 'latest_post', array( 'selector' => '.header-section', 'render_callback' => 'header_markup' ) ); function header_markup(){ $latest_post = get_theme_mod('latest_post'); switch($latest_post): case true: return "latest post"; case false: return "custom media"; default: return "custom media"; endswitch; } ``` **html** ``` <div class="header-section"> <php echo header_markup(); ?> </div> ```
You don't need to add it on a template, you can use the [wp\_add\_inline\_script()](https://developer.wordpress.org/reference/functions/wp_add_inline_script/) function. It'd be something like: ``` function tabs_enqueue() { if(is_page( 205 )) { wp_enqueue_script( 'ui', get_template_directory_uri() . '/js/ui/jquery-ui.min.js', [], '1.8', true); wp_add_inline_script( 'ui', 'jQuery(window).load(function() { //code here });' ); } } add_action('wp_enqueue_scripts', 'tabs_enqueue'); ``` Hope it helps!
300,683
<p>I am playing with Gutenberg and I am a bit confused about how it should save to meta. Here is my custom post and meta:</p> <pre><code>add_action( 'init', function() { register_post_type( 'game', [ 'label' =&gt; 'Games', 'public' =&gt; true, 'supports' =&gt; [ 'editor', 'custom-fields' ], 'show_in_rest' =&gt; true, ] ); register_meta( 'game', 'logo', [ 'single' =&gt; true, 'show_in_rest' =&gt; true, 'description' =&gt; 'A meta key associated with a string meta value.', 'type' =&gt; 'string' ] ); } ); </code></pre> <p>And my Block JS file:</p> <pre><code>( function( blocks, i18n, element ) { var el = element.createElement; var MediaUploadButton = wp.blocks.MediaUploadButton; var BlockControls = wp.blocks.BlockControls; blocks.registerBlockType( 'game-post/meta', { title: i18n.__( 'Game' ), description: i18n.__( 'Meta Box for Game' ), icon: 'businessman', category: 'common', attributes: { logo: { type: 'string', source: 'meta', meta: 'logo' } }, edit: function(props) { console.log(props.attributes); var mediaURL = props.attributes.logo; return el('div', { classname: mediaURL ? 'image-active' : 'image-inactive' }, el('input', { defaultValue: mediaURL, type: 'text', onChange: function(e) { props.setAttributes({ logo: e.target.value }); } })); }, save: function(props) { return el( 'img', { src: props.attributes.logo } ); } } ); } )( window.wp.blocks, window.wp.i18n, window.wp.element, ); </code></pre> <p>I took the source idea from <a href="https://wordpress.org/gutenberg/handbook/block-api/attributes/#meta" rel="nofollow noreferrer">WP Gutenberg Handbook</a>. The attribute is created etc but the values are empty and the meta field is not saved. And the console log in edit function always returns null because there is no meta attribute. What am I doing wrong? If I change the attribute source to <code>attribute</code>, the field is saved properly. </p>
[ { "answer_id": 306402, "author": "LABCAT", "author_id": 145531, "author_profile": "https://wordpress.stackexchange.com/users/145531", "pm_score": 0, "selected": false, "text": "<p>I am trying to learn how to do this also. You have incorrectly registered your meta value, it should be:</p>\n\n<pre><code>register_meta( 'post', 'logo', [\n 'single' =&gt; true,\n 'show_in_rest' =&gt; true,\n 'description' =&gt; 'A meta key associated with a string meta value.',\n 'type' =&gt; 'string'\n] );\n</code></pre>\n\n<p>See the documentation for the $object_type param here:\n<a href=\"https://codex.wordpress.org/Function_Reference/register_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_meta</a></p>\n\n<p>I don't think will make your JS code work though.</p>\n" }, { "answer_id": 320131, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 1, "selected": false, "text": "<p>The meta value is read when the block loads and assigned to the block attribute. Changes to the block will update the attribute and when the post saves the value will save to the meta. So, as far as I understood, there is no need to actually save anything in the <code>registerBlockType</code> js function. The block only saves to the meta so in the front end nothing will be rendered (unlike non-meta blocks).</p>\n\n<p>So in your case:</p>\n\n<pre><code>add_action( 'init', function() {\n register_post_type( 'game', [\n 'label' =&gt; 'Games',\n 'public' =&gt; true,\n 'supports' =&gt; [ 'editor', 'custom-fields' ],\n 'show_in_rest' =&gt; true,\n ] );\n\n register_post_meta( 'game', 'logo', [\n 'single' =&gt; true,\n 'show_in_rest' =&gt; true,\n 'description' =&gt; 'A meta key associated with a string meta value.',\n 'type' =&gt; 'string'\n ] );\n} );\n</code></pre>\n\n<p>Notice that I used <code>register_post_meta</code> which was included in version 4.9.8 and allows to use the post type name (\"game\" in this case). As noticed by @LABCAT in the other answer using <code>register_meta</code> requires the type to be \"post\" even for custom post types.</p>\n\n<p>Then in the JavaScript file:</p>\n\n<pre><code>registerBlockType( 'game-post/meta', {\n //...\n save: () =&gt; null,\n});\n</code></pre>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 371165, "author": "Dale de Silva", "author_id": 188957, "author_profile": "https://wordpress.stackexchange.com/users/188957", "pm_score": 0, "selected": false, "text": "<p>Apart from any other errors that might be in your code that some others have pointed out, I've found that accessing attributes defined as <em>&quot;meta&quot;</em> from the save function has issues.</p>\n<p>I've posted my own question about it <a href=\"https://stackoverflow.com/questions/62909686/can-i-access-attributes-with-source-meta-from-the-save-class\">here</a>.\nand a bug report about it <a href=\"https://github.com/WordPress/gutenberg/issues/23979\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Essentially, while the documentation says <em><strong>&quot;meta attributes can be read and written by a block using the same interface as any attribute&quot;</strong></em> ... it doesn't seem to be true from within the save function.</p>\n<p>I've found the attributes (of source <em>&quot;meta&quot;</em>) don't appear in the save function until the edit function specifically sets them using <strong>setAttribute</strong> it during that particular session on the editor page.</p>\n<p><em>(Which means getting alignment between save and edit function output when returning to edit the page is very difficult).</em></p>\n<p>My bug report linked above has more detail on what I've found if you need it.</p>\n" } ]
2018/04/13
[ "https://wordpress.stackexchange.com/questions/300683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67305/" ]
I am playing with Gutenberg and I am a bit confused about how it should save to meta. Here is my custom post and meta: ``` add_action( 'init', function() { register_post_type( 'game', [ 'label' => 'Games', 'public' => true, 'supports' => [ 'editor', 'custom-fields' ], 'show_in_rest' => true, ] ); register_meta( 'game', 'logo', [ 'single' => true, 'show_in_rest' => true, 'description' => 'A meta key associated with a string meta value.', 'type' => 'string' ] ); } ); ``` And my Block JS file: ``` ( function( blocks, i18n, element ) { var el = element.createElement; var MediaUploadButton = wp.blocks.MediaUploadButton; var BlockControls = wp.blocks.BlockControls; blocks.registerBlockType( 'game-post/meta', { title: i18n.__( 'Game' ), description: i18n.__( 'Meta Box for Game' ), icon: 'businessman', category: 'common', attributes: { logo: { type: 'string', source: 'meta', meta: 'logo' } }, edit: function(props) { console.log(props.attributes); var mediaURL = props.attributes.logo; return el('div', { classname: mediaURL ? 'image-active' : 'image-inactive' }, el('input', { defaultValue: mediaURL, type: 'text', onChange: function(e) { props.setAttributes({ logo: e.target.value }); } })); }, save: function(props) { return el( 'img', { src: props.attributes.logo } ); } } ); } )( window.wp.blocks, window.wp.i18n, window.wp.element, ); ``` I took the source idea from [WP Gutenberg Handbook](https://wordpress.org/gutenberg/handbook/block-api/attributes/#meta). The attribute is created etc but the values are empty and the meta field is not saved. And the console log in edit function always returns null because there is no meta attribute. What am I doing wrong? If I change the attribute source to `attribute`, the field is saved properly.
The meta value is read when the block loads and assigned to the block attribute. Changes to the block will update the attribute and when the post saves the value will save to the meta. So, as far as I understood, there is no need to actually save anything in the `registerBlockType` js function. The block only saves to the meta so in the front end nothing will be rendered (unlike non-meta blocks). So in your case: ``` add_action( 'init', function() { register_post_type( 'game', [ 'label' => 'Games', 'public' => true, 'supports' => [ 'editor', 'custom-fields' ], 'show_in_rest' => true, ] ); register_post_meta( 'game', 'logo', [ 'single' => true, 'show_in_rest' => true, 'description' => 'A meta key associated with a string meta value.', 'type' => 'string' ] ); } ); ``` Notice that I used `register_post_meta` which was included in version 4.9.8 and allows to use the post type name ("game" in this case). As noticed by @LABCAT in the other answer using `register_meta` requires the type to be "post" even for custom post types. Then in the JavaScript file: ``` registerBlockType( 'game-post/meta', { //... save: () => null, }); ``` I hope this helps.
300,710
<p>I am new to wordpress, and I am trying to add multiple custom post types in the functions.php. </p> <p>Adding one cpt is fine. but if I use the same function to add the second cpt (with just a change of the function name), the second cpt doesn't show in the dashboard menu.</p> <p>Below are the codes. I would greatly appreciate help in this. Thank you!</p> <pre><code>// register a new post type with Divi builder on function create_new_cpt() { $labels = array( 'name' =&gt; _x('Article', 'Article', 'divi'), // CPT name is Article. Replace every instance of this CPT name with your own 'singular_name' =&gt; _x('Article', 'article', 'divi'), 'menu_name' =&gt; __('Article', 'divi'), 'edit_item' =&gt; __('Edit Article', 'divi'), 'add_new_item' =&gt; __( 'Add New Article', 'divi' ), 'update_item' =&gt; __( 'Update Article', 'text_domain' ), 'view_item' =&gt; __( 'View Article', 'text_domain' ), 'not_found_in_trash' =&gt; __('Not found in Trash', 'divi') ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; __('Articles', 'divi'), 'supports' =&gt; array('title', 'author', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields'), 'menu_icon' =&gt; 'dashicons-welcome-write-blog', 'menu-position' =&gt; null, 'public' =&gt; true, 'publicly_queryable'=&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_admin_bar' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'article' ), 'capability_type' =&gt; 'post', 'can_export' =&gt; true, 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'publicly_queryable'=&gt; true ); register_post_type('article', $args); // registering the CPT. $labels = array( 'name' =&gt; esc_html__( 'Article Categories', 'divi' ), 'singular_name' =&gt; esc_html__( 'Article Category', 'divi' ), 'search_items' =&gt; esc_html__( 'Search Categories', 'divi' ), 'all_items' =&gt; esc_html__( 'All Categories', 'divi' ), 'parent_item' =&gt; esc_html__( 'Parent Category', 'divi' ), 'parent_item_colon' =&gt; esc_html__( 'Parent Category:', 'divi' ), 'edit_item' =&gt; esc_html__( 'Edit Category', 'divi' ), 'update_item' =&gt; esc_html__( 'Update Category', 'divi' ), 'add_new_item' =&gt; esc_html__( 'Add New Category', 'divi' ), 'new_item_name' =&gt; esc_html__( 'New Category Name', 'divi' ), 'menu_name' =&gt; esc_html__( 'Categories', 'divi' ), ); // registering the custom taxomoy for this CPT. register_taxonomy( 'article_category', array( 'article' ), array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, ) ); $labels = array( 'name' =&gt; esc_html__( 'Article Tags', 'divi' ), 'singular_name' =&gt; esc_html__( 'Article Tag', 'divi' ), 'search_items' =&gt; esc_html__( 'Search Tags', 'divi' ), 'all_items' =&gt; esc_html__( 'All Tags', 'divi' ), 'parent_item' =&gt; esc_html__( 'Parent Tag', 'divi' ), 'parent_item_colon' =&gt; esc_html__( 'Parent Tag:', 'divi' ), 'edit_item' =&gt; esc_html__( 'Edit Tag', 'divi' ), 'update_item' =&gt; esc_html__( 'Update Tag', 'divi' ), 'add_new_item' =&gt; esc_html__( 'Add New Tag', 'divi' ), 'new_item_name' =&gt; esc_html__( 'New Tag Name', 'divi' ), 'menu_name' =&gt; esc_html__( 'Tags', 'divi' ), ); register_taxonomy( 'article_tag', array( 'article' ), array( 'hierarchical' =&gt; false, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, ) ); } // adding divi page builder to this CPT function add_db_to_article ($post_types) { $custom_post_types = array ('article'); $output = array_merge($post_types, $custom_post_types); return $output; } add_action('init', 'create_new_cpt'); add_filter( 'et_builder_post_types', 'add_db_to_article' ); // register a new post type with Divi builder on function create_new_cpt2() { $labels = array( 'name' =&gt; _x('News', 'News', 'divi'), // CPT name is News. Replace every instance of this CPT name with your own 'singular_name' =&gt; _x('News', 'news', 'divi'), 'menu_name' =&gt; __('News', 'divi'), 'edit_item' =&gt; __('Edit News', 'divi'), 'add_new_item' =&gt; __( 'Add New News', 'divi' ), 'update_item' =&gt; __( 'Update News', 'text_domain' ), 'view_item' =&gt; __( 'View News', 'text_domain' ), 'not_found_in_trash' =&gt; __('Not found in Trash', 'divi') ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; __('News', 'divi'), 'supports' =&gt; array('title', 'author', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields'), 'menu_icon' =&gt; 'dashicons-welcome-write-blog', 'menu-position' =&gt; null, 'public' =&gt; true, 'publicly_queryable'=&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_admin_bar' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'news' ), 'capability_type' =&gt; 'post', 'can_export' =&gt; true, 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'publicly_queryable'=&gt; true ); register_post_type('news', $args); // registering the CPT. $labels = array( 'name' =&gt; esc_html__( 'News Categories', 'divi' ), 'singular_name' =&gt; esc_html__( 'News Category', 'divi' ), 'search_items' =&gt; esc_html__( 'Search Categories', 'divi' ), 'all_items' =&gt; esc_html__( 'All Categories', 'divi' ), 'parent_item' =&gt; esc_html__( 'Parent Category', 'divi' ), 'parent_item_colon' =&gt; esc_html__( 'Parent Category:', 'divi' ), 'edit_item' =&gt; esc_html__( 'Edit Category', 'divi' ), 'update_item' =&gt; esc_html__( 'Update Category', 'divi' ), 'add_new_item' =&gt; esc_html__( 'Add New Category', 'divi' ), 'new_item_name' =&gt; esc_html__( 'New Category Name', 'divi' ), 'menu_name' =&gt; esc_html__( 'Categories', 'divi' ), ); // registering the custom taxomoy for this CPT. register_taxonomy( 'news_category', array( 'news' ), array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, ) ); $labels = array( 'name' =&gt; esc_html__( 'News Tags', 'divi' ), 'singular_name' =&gt; esc_html__( 'News Tag', 'divi' ), 'search_items' =&gt; esc_html__( 'Search Tags', 'divi' ), 'all_items' =&gt; esc_html__( 'All Tags', 'divi' ), 'parent_item' =&gt; esc_html__( 'Parent Tag', 'divi' ), 'parent_item_colon' =&gt; esc_html__( 'Parent Tag:', 'divi' ), 'edit_item' =&gt; esc_html__( 'Edit Tag', 'divi' ), 'update_item' =&gt; esc_html__( 'Update Tag', 'divi' ), 'add_new_item' =&gt; esc_html__( 'Add New Tag', 'divi' ), 'new_item_name' =&gt; esc_html__( 'New Tag Name', 'divi' ), 'menu_name' =&gt; esc_html__( 'Tags', 'divi' ), ); register_taxonomy( 'news_tag', array( 'news' ), array( 'hierarchical' =&gt; false, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, ) ); } </code></pre>
[ { "answer_id": 300711, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p>Your snippet is missing</p>\n\n<pre><code>add_action('init', 'create_new_cpt2');\n</code></pre>\n" }, { "answer_id": 300714, "author": "VishwasDhamale", "author_id": 119127, "author_profile": "https://wordpress.stackexchange.com/users/119127", "pm_score": 2, "selected": false, "text": "<p>add <code>add_action('init', 'create_new_cpt2');</code> in your snippet and modify <strong>add_db_to_article</strong> function as below,</p>\n\n<pre><code>function add_db_to_article ($post_types) {\n $custom_post_types = array ('article', 'news');\n $output = array_merge($post_types, $custom_post_types);\n return $output;\n}\n</code></pre>\n\n<p><strong><em>Note: 'news' is added in $custom_post_types array.</em></strong></p>\n" } ]
2018/04/13
[ "https://wordpress.stackexchange.com/questions/300710", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141736/" ]
I am new to wordpress, and I am trying to add multiple custom post types in the functions.php. Adding one cpt is fine. but if I use the same function to add the second cpt (with just a change of the function name), the second cpt doesn't show in the dashboard menu. Below are the codes. I would greatly appreciate help in this. Thank you! ``` // register a new post type with Divi builder on function create_new_cpt() { $labels = array( 'name' => _x('Article', 'Article', 'divi'), // CPT name is Article. Replace every instance of this CPT name with your own 'singular_name' => _x('Article', 'article', 'divi'), 'menu_name' => __('Article', 'divi'), 'edit_item' => __('Edit Article', 'divi'), 'add_new_item' => __( 'Add New Article', 'divi' ), 'update_item' => __( 'Update Article', 'text_domain' ), 'view_item' => __( 'View Article', 'text_domain' ), 'not_found_in_trash' => __('Not found in Trash', 'divi') ); $args = array( 'labels' => $labels, 'description' => __('Articles', 'divi'), 'supports' => array('title', 'author', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields'), 'menu_icon' => 'dashicons-welcome-write-blog', 'menu-position' => null, 'public' => true, 'publicly_queryable'=> true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_admin_bar' => true, 'rewrite' => array( 'slug' => 'article' ), 'capability_type' => 'post', 'can_export' => true, 'has_archive' => true, 'hierarchical' => false, 'publicly_queryable'=> true ); register_post_type('article', $args); // registering the CPT. $labels = array( 'name' => esc_html__( 'Article Categories', 'divi' ), 'singular_name' => esc_html__( 'Article Category', 'divi' ), 'search_items' => esc_html__( 'Search Categories', 'divi' ), 'all_items' => esc_html__( 'All Categories', 'divi' ), 'parent_item' => esc_html__( 'Parent Category', 'divi' ), 'parent_item_colon' => esc_html__( 'Parent Category:', 'divi' ), 'edit_item' => esc_html__( 'Edit Category', 'divi' ), 'update_item' => esc_html__( 'Update Category', 'divi' ), 'add_new_item' => esc_html__( 'Add New Category', 'divi' ), 'new_item_name' => esc_html__( 'New Category Name', 'divi' ), 'menu_name' => esc_html__( 'Categories', 'divi' ), ); // registering the custom taxomoy for this CPT. register_taxonomy( 'article_category', array( 'article' ), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, ) ); $labels = array( 'name' => esc_html__( 'Article Tags', 'divi' ), 'singular_name' => esc_html__( 'Article Tag', 'divi' ), 'search_items' => esc_html__( 'Search Tags', 'divi' ), 'all_items' => esc_html__( 'All Tags', 'divi' ), 'parent_item' => esc_html__( 'Parent Tag', 'divi' ), 'parent_item_colon' => esc_html__( 'Parent Tag:', 'divi' ), 'edit_item' => esc_html__( 'Edit Tag', 'divi' ), 'update_item' => esc_html__( 'Update Tag', 'divi' ), 'add_new_item' => esc_html__( 'Add New Tag', 'divi' ), 'new_item_name' => esc_html__( 'New Tag Name', 'divi' ), 'menu_name' => esc_html__( 'Tags', 'divi' ), ); register_taxonomy( 'article_tag', array( 'article' ), array( 'hierarchical' => false, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, ) ); } // adding divi page builder to this CPT function add_db_to_article ($post_types) { $custom_post_types = array ('article'); $output = array_merge($post_types, $custom_post_types); return $output; } add_action('init', 'create_new_cpt'); add_filter( 'et_builder_post_types', 'add_db_to_article' ); // register a new post type with Divi builder on function create_new_cpt2() { $labels = array( 'name' => _x('News', 'News', 'divi'), // CPT name is News. Replace every instance of this CPT name with your own 'singular_name' => _x('News', 'news', 'divi'), 'menu_name' => __('News', 'divi'), 'edit_item' => __('Edit News', 'divi'), 'add_new_item' => __( 'Add New News', 'divi' ), 'update_item' => __( 'Update News', 'text_domain' ), 'view_item' => __( 'View News', 'text_domain' ), 'not_found_in_trash' => __('Not found in Trash', 'divi') ); $args = array( 'labels' => $labels, 'description' => __('News', 'divi'), 'supports' => array('title', 'author', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields'), 'menu_icon' => 'dashicons-welcome-write-blog', 'menu-position' => null, 'public' => true, 'publicly_queryable'=> true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_admin_bar' => true, 'rewrite' => array( 'slug' => 'news' ), 'capability_type' => 'post', 'can_export' => true, 'has_archive' => true, 'hierarchical' => false, 'publicly_queryable'=> true ); register_post_type('news', $args); // registering the CPT. $labels = array( 'name' => esc_html__( 'News Categories', 'divi' ), 'singular_name' => esc_html__( 'News Category', 'divi' ), 'search_items' => esc_html__( 'Search Categories', 'divi' ), 'all_items' => esc_html__( 'All Categories', 'divi' ), 'parent_item' => esc_html__( 'Parent Category', 'divi' ), 'parent_item_colon' => esc_html__( 'Parent Category:', 'divi' ), 'edit_item' => esc_html__( 'Edit Category', 'divi' ), 'update_item' => esc_html__( 'Update Category', 'divi' ), 'add_new_item' => esc_html__( 'Add New Category', 'divi' ), 'new_item_name' => esc_html__( 'New Category Name', 'divi' ), 'menu_name' => esc_html__( 'Categories', 'divi' ), ); // registering the custom taxomoy for this CPT. register_taxonomy( 'news_category', array( 'news' ), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, ) ); $labels = array( 'name' => esc_html__( 'News Tags', 'divi' ), 'singular_name' => esc_html__( 'News Tag', 'divi' ), 'search_items' => esc_html__( 'Search Tags', 'divi' ), 'all_items' => esc_html__( 'All Tags', 'divi' ), 'parent_item' => esc_html__( 'Parent Tag', 'divi' ), 'parent_item_colon' => esc_html__( 'Parent Tag:', 'divi' ), 'edit_item' => esc_html__( 'Edit Tag', 'divi' ), 'update_item' => esc_html__( 'Update Tag', 'divi' ), 'add_new_item' => esc_html__( 'Add New Tag', 'divi' ), 'new_item_name' => esc_html__( 'New Tag Name', 'divi' ), 'menu_name' => esc_html__( 'Tags', 'divi' ), ); register_taxonomy( 'news_tag', array( 'news' ), array( 'hierarchical' => false, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, ) ); } ```
Your snippet is missing ``` add_action('init', 'create_new_cpt2'); ```
300,736
<p>i'm working in android application that use wordpress rest api to get blog from website to , i don't have any knowledge about php or wordpress , but i take some time to learn about it , any way my problem is on the json .the content contain paragraphs unknown and i don't know how to solve this problem ,please help <a href="https://i.stack.imgur.com/eHVMl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eHVMl.png" alt="android application"></a> <a href="https://i.stack.imgur.com/mRBcz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRBcz.png" alt="json"></a> <a href="https://i.stack.imgur.com/4LCvf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4LCvf.png" alt="youtube video"></a></p>
[ { "answer_id": 300738, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 3, "selected": true, "text": "<p>The content that you are referring to is coming from the Elegant Themes Page Builder plugin on that site.</p>\n\n<p>The page builder uses <a href=\"https://codex.wordpress.org/shortcode\" rel=\"nofollow noreferrer\">WordPress Shortcodes</a> to render the content on the WordPress site. However, when you use the REST API, the content is pulled from the WordPress database and the shortcodes are not processed/rendered first.</p>\n\n<p>You would need to remove the shortcodes from the returned JSON before it is displayed in your app. You could use something like this to remove the shortcodes before displaying your content in the app:</p>\n\n<pre><code>// Remove Divi/ET Page Builder shortcodes\n$content = preg_replace('/\\[\\/?et_pb.*?\\]/', '', $content);\n</code></pre>\n" }, { "answer_id": 337125, "author": "Joe", "author_id": 167432, "author_profile": "https://wordpress.stackexchange.com/users/167432", "pm_score": 1, "selected": false, "text": "<p>You can place this code in your themes functions.php file: </p>\n\n<pre><code>function awh_filter_post_json( $data, $post, $context ) {\n $data = json_encode($data); //convert array or object to JSON string\n $data = preg_replace('/\\[\\/?et_pb.*?\\]/', '', $data); //remove shortcodes\n $data = json_decode($data); //convert JSON String to array or object\n return $data;\n}\n\nadd_filter( 'rest_prepare_post', 'awh_filter_post_json', 10, 3 );\n</code></pre>\n" }, { "answer_id": 391851, "author": "Lukid", "author_id": 116016, "author_profile": "https://wordpress.stackexchange.com/users/116016", "pm_score": 0, "selected": false, "text": "<p>Thanks to the other answers, I solved it like this (in my WP theme functions.php file) :</p>\n<pre><code>add_filter( 'rest_prepare_post', 'lb_filter_post_content', 11, 3 );\n\nfunction lb_filter_post_content($data, $post, $context){\n // remove shortcode just on content &gt; rendered\n $data-&gt;data[&quot;content&quot;][&quot;rendered&quot;] = preg_replace('/\\[\\/?et_pb.*?\\]/', '', $data-&gt;data[&quot;content&quot;][&quot;rendered&quot;]);\n return $data;\n}\n\n</code></pre>\n<p>PS. The shortcodes with &quot;et_pb&quot; derive from the fact that the Divi theme is used on the WP with its page builder, so I just remove those shortcodes.\nI wrote the above in the functions.php of my Divi child-theme.\nThis solution is good if you want to fix the WP side problem, which is where the problem is generated.</p>\n" } ]
2018/04/13
[ "https://wordpress.stackexchange.com/questions/300736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140958/" ]
i'm working in android application that use wordpress rest api to get blog from website to , i don't have any knowledge about php or wordpress , but i take some time to learn about it , any way my problem is on the json .the content contain paragraphs unknown and i don't know how to solve this problem ,please help [![android application](https://i.stack.imgur.com/eHVMl.png)](https://i.stack.imgur.com/eHVMl.png) [![json](https://i.stack.imgur.com/mRBcz.png)](https://i.stack.imgur.com/mRBcz.png) [![youtube video](https://i.stack.imgur.com/4LCvf.png)](https://i.stack.imgur.com/4LCvf.png)
The content that you are referring to is coming from the Elegant Themes Page Builder plugin on that site. The page builder uses [WordPress Shortcodes](https://codex.wordpress.org/shortcode) to render the content on the WordPress site. However, when you use the REST API, the content is pulled from the WordPress database and the shortcodes are not processed/rendered first. You would need to remove the shortcodes from the returned JSON before it is displayed in your app. You could use something like this to remove the shortcodes before displaying your content in the app: ``` // Remove Divi/ET Page Builder shortcodes $content = preg_replace('/\[\/?et_pb.*?\]/', '', $content); ```
300,764
<p>There are two ways that WordPress updates translation files inside Languages folder: 1. Automatic updates whenever it gets triggered. 2. Manually when user requests it on "Updates" page.</p> <p>Is there a way to disable both of them, so no changes can apply to Languages folder?</p>
[ { "answer_id": 301821, "author": "Rahmat Baghdadi", "author_id": 131970, "author_profile": "https://wordpress.stackexchange.com/users/131970", "pm_score": 2, "selected": false, "text": "<p>I have this snippet that disables automatic translation update:</p>\n\n<pre><code>if( function_exists('add_filter') ){add_filter( 'auto_update_translation', '__return_false' );}\n</code></pre>\n\n<p>That's one problem solved. But if I update plugins manually, WordPress updates translations afterward. How to fix this part too? Any ideas?</p>\n" }, { "answer_id": 302390, "author": "Tim", "author_id": 48306, "author_profile": "https://wordpress.stackexchange.com/users/48306", "pm_score": 2, "selected": true, "text": "<p>You've already given the answer using <code>auto_update_translation</code>. I wasn't aware this didn't work after manual updates (and haven't tried it) but perhaps also look at <a href=\"https://developer.wordpress.org/reference/hooks/async_update_translation/\" rel=\"nofollow noreferrer\">async_update_translation</a> which according the documentation <em>\"Asynchronously upgrades language packs after other upgrades have been made\"</em>.</p>\n\n<hr>\n\n<p>Regardless of the above, I recommend a different approach whereby the community translations are still installed, but your own custom translations override when (and only when) they exist.</p>\n\n<p>This means you have the advantage of improving the translations you dislike, while still benefiting from any new translations appearing before you know about them. (i.e. source strings changing after plugin updates).</p>\n\n<p>To do this you'll have two copies of each language file and force WordPress to load them on top of each other with yours taking precedence.</p>\n\n<p>(1) Mimic the <code>languages</code> folder structure in a parallel directory, and move your own custom translation files so you have paths like this for whatever your language is:</p>\n\n<pre><code>wp-content/my-translations/plugins/foo-en_GB.mo\n</code></pre>\n\n<p>(2) Add the following code as a <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">must-use</a> plugin to ensure it's ready before anything else tries to bootstrap its translations.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Custom Translations\nDescription: Merges translations under my-languages on top of those installed.\n*/\n\nfunction my_custom_load_textdomain_hook( $domain = '', $mofile = '' ){\n $basedir = trailingslashit(WP_LANG_DIR);\n $baselen = strlen($basedir);\n // only run this if file being loaded is under WP_LANG_DIR\n if( $basedir === substr($mofile,0,$baselen) ){\n // Our custom directory is parallel to languages directory\n if( $mofile = realpath( $basedir.'../my-languages/'.substr($mofile,$baselen) ) ){\n load_textdomain( $domain, $mofile );\n }\n }\n}\n\nadd_action( 'load_textdomain', 'my_custom_load_textdomain_hook', 10, 2 );\n</code></pre>\n\n<p>Note that your custom files need only contain the strings you want to change. This relies on WordPress's current <a href=\"https://developer.wordpress.org/reference/classes/translations/merge_with/\" rel=\"nofollow noreferrer\">merging</a> strategy. In the code above your file actually completes first, then is merged on top of the installed file. </p>\n" } ]
2018/04/14
[ "https://wordpress.stackexchange.com/questions/300764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131970/" ]
There are two ways that WordPress updates translation files inside Languages folder: 1. Automatic updates whenever it gets triggered. 2. Manually when user requests it on "Updates" page. Is there a way to disable both of them, so no changes can apply to Languages folder?
You've already given the answer using `auto_update_translation`. I wasn't aware this didn't work after manual updates (and haven't tried it) but perhaps also look at [async\_update\_translation](https://developer.wordpress.org/reference/hooks/async_update_translation/) which according the documentation *"Asynchronously upgrades language packs after other upgrades have been made"*. --- Regardless of the above, I recommend a different approach whereby the community translations are still installed, but your own custom translations override when (and only when) they exist. This means you have the advantage of improving the translations you dislike, while still benefiting from any new translations appearing before you know about them. (i.e. source strings changing after plugin updates). To do this you'll have two copies of each language file and force WordPress to load them on top of each other with yours taking precedence. (1) Mimic the `languages` folder structure in a parallel directory, and move your own custom translation files so you have paths like this for whatever your language is: ``` wp-content/my-translations/plugins/foo-en_GB.mo ``` (2) Add the following code as a [must-use](https://codex.wordpress.org/Must_Use_Plugins) plugin to ensure it's ready before anything else tries to bootstrap its translations. ``` <?php /* Plugin Name: Custom Translations Description: Merges translations under my-languages on top of those installed. */ function my_custom_load_textdomain_hook( $domain = '', $mofile = '' ){ $basedir = trailingslashit(WP_LANG_DIR); $baselen = strlen($basedir); // only run this if file being loaded is under WP_LANG_DIR if( $basedir === substr($mofile,0,$baselen) ){ // Our custom directory is parallel to languages directory if( $mofile = realpath( $basedir.'../my-languages/'.substr($mofile,$baselen) ) ){ load_textdomain( $domain, $mofile ); } } } add_action( 'load_textdomain', 'my_custom_load_textdomain_hook', 10, 2 ); ``` Note that your custom files need only contain the strings you want to change. This relies on WordPress's current [merging](https://developer.wordpress.org/reference/classes/translations/merge_with/) strategy. In the code above your file actually completes first, then is merged on top of the installed file.
300,776
<p>I try to find a way to get products ID by custom field in a category. I use this:</p> <pre><code>// Get the category $catsearched = $atts['category_id']; // Get all product of categoryselected $product_args = array( 'post_type' =&gt; 'product', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'fields' =&gt; 'ids', // Only return product IDs 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'id', 'terms' =&gt; $catsearched, 'operator' =&gt; 'IN', )) ); $products = get_posts($product_args); //$products = implode(",", $products); //return $products; /** * FIND ALL PRODUCT WITH SAME CIP AND KEEP ONLY ONE PRODUCT BY CIP (array_unique) * * ====================================================================================== */ foreach ( $products as $id ) { $cip = $product_obj['product_cip'] = get_post_meta($id,'product_cip'); $arrayCip[] = $cip[0]; } //echo '&lt;b&gt;TotalNumberOfCIP = '.count($arrayCip).'&lt;/b&gt;&lt;br&gt;'; $result = array_unique($arrayCip); //echo '&lt;b&gt;TotalNumberOfUniqueCIP = '.count($result).'&lt;/b&gt;&lt;br&gt;'; //$results = implode(",", $result); //var_dump($results); /** * FIND ID BY CIP * **/ global $wpdb; // Find product id by CIP foreach($result as $cip) { $arrayid[] = $wpdb-&gt;get_var( "SELECT post_id FROM $wpdb-&gt;postmeta WHERE meta_key='product_cip' AND meta_value='.$cip.' AND {$wpdb-&gt;term_relationships}.term_taxonomy_id IN ($catsearched)"); } </code></pre> <p>All works fine before FIND ID BY CIP After $arrayid is null.</p> <p>I also tried:</p> <pre><code> global $wpdb; $meta = $wpdb-&gt;get_results( $wpdb-&gt;prepare( "SELECT post_id FROM $wpdb-&gt;postmeta WHERE meta_key = %s AND meta_value = %s AND {$wpdb-&gt;term_relationships}.term_taxonomy_id IN ($catsearched)", $key, $value ) ); //var_dump(($meta)); if (is_array($meta) &amp;&amp; !empty($meta) &amp;&amp; isset($meta[0])) { $meta = $meta[0]; } if (is_object($meta)) { return $meta-&gt;post_id; } else { return false; } </code></pre> <p>But always bool(false)</p> <p>Any idea ? Thanks</p>
[ { "answer_id": 333185, "author": "Bret Weinraub", "author_id": 70438, "author_profile": "https://wordpress.stackexchange.com/users/70438", "pm_score": 0, "selected": false, "text": "<p>This may help; this function returns a list of product where a custom field is set to any value.</p>\n\n<pre><code>function get_wc_products_where_custom_field_is_set($field) {\n $products = wc_get_products(array('status' =&gt; 'publish'));\n\n foreach ($products as $product) {\n $id = $product-&gt;get_id();\n if (get_post_meta($id,$field,true)) /* if my custom field is set */\n $ret[] = new \\WC_Product($id);\n }\n return $ret;\n}\n</code></pre>\n\n<p>Works fine unless you've got 1000s of products.....</p>\n" }, { "answer_id": 344871, "author": "Navnit Viradiya", "author_id": 173329, "author_profile": "https://wordpress.stackexchange.com/users/173329", "pm_score": 1, "selected": false, "text": "<p>Try This.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1,\n 'meta_key' =&gt; 'ingredients', //Your Custom field name\n 'meta_value' =&gt; ' ', //Custom field value\n 'meta_compare' =&gt; '='\n);\n\n$the_query = new WP_Query( $args );\n$count = $the_query-&gt;post_count;\nif ( $the_query-&gt;have_posts() ) :\n while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;'; \n endwhile;\nendif;\n</code></pre>\n\n<p><a href=\"https://gist.github.com/navnit-viradiya/07fcd47a7f8cd6604244ac3515d9a504\" rel=\"nofollow noreferrer\">Click here</a> to see multipal custom field condition.</p>\n" }, { "answer_id": 345439, "author": "user173757", "author_id": 173757, "author_profile": "https://wordpress.stackexchange.com/users/173757", "pm_score": 3, "selected": false, "text": "<pre><code>$args = array(\n 'post_type' =&gt; 'product',\n 'meta_key' =&gt; 'YOUR_FIELD_ID',\n 'meta_value' =&gt; array('yes'), //'meta_value' =&gt; array('yes'),\n 'meta_compare' =&gt; 'IN' //'meta_compare' =&gt; 'NOT IN'\n);\n$products = wc_get_products($args);\n\nforeach ($products as $product) {\n//do your logic\n}\n</code></pre>\n" } ]
2018/04/14
[ "https://wordpress.stackexchange.com/questions/300776", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114157/" ]
I try to find a way to get products ID by custom field in a category. I use this: ``` // Get the category $catsearched = $atts['category_id']; // Get all product of categoryselected $product_args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', // Only return product IDs 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $catsearched, 'operator' => 'IN', )) ); $products = get_posts($product_args); //$products = implode(",", $products); //return $products; /** * FIND ALL PRODUCT WITH SAME CIP AND KEEP ONLY ONE PRODUCT BY CIP (array_unique) * * ====================================================================================== */ foreach ( $products as $id ) { $cip = $product_obj['product_cip'] = get_post_meta($id,'product_cip'); $arrayCip[] = $cip[0]; } //echo '<b>TotalNumberOfCIP = '.count($arrayCip).'</b><br>'; $result = array_unique($arrayCip); //echo '<b>TotalNumberOfUniqueCIP = '.count($result).'</b><br>'; //$results = implode(",", $result); //var_dump($results); /** * FIND ID BY CIP * **/ global $wpdb; // Find product id by CIP foreach($result as $cip) { $arrayid[] = $wpdb->get_var( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='product_cip' AND meta_value='.$cip.' AND {$wpdb->term_relationships}.term_taxonomy_id IN ($catsearched)"); } ``` All works fine before FIND ID BY CIP After $arrayid is null. I also tried: ``` global $wpdb; $meta = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = %s AND {$wpdb->term_relationships}.term_taxonomy_id IN ($catsearched)", $key, $value ) ); //var_dump(($meta)); if (is_array($meta) && !empty($meta) && isset($meta[0])) { $meta = $meta[0]; } if (is_object($meta)) { return $meta->post_id; } else { return false; } ``` But always bool(false) Any idea ? Thanks
``` $args = array( 'post_type' => 'product', 'meta_key' => 'YOUR_FIELD_ID', 'meta_value' => array('yes'), //'meta_value' => array('yes'), 'meta_compare' => 'IN' //'meta_compare' => 'NOT IN' ); $products = wc_get_products($args); foreach ($products as $product) { //do your logic } ```
300,807
<p>Is there a way to alter/change core <code>has_post_thumbnail</code> function?</p> <p>I need to check folder on server with images first before code looks for post image attachment.</p> <p>I see lots of filters to change image html but they either affect single post page or loop thumbnail and with woocommerce several other places plus admin tables, etc.</p> <p>I need to place the server directory check before it even hits <code>_post_thumbnail()</code> or <code>get_image</code> so it looks like <code>has_post_thumbnail</code> is very first check unless I'm wrong.</p> <p>Please help, suggest what can be done.</p> <p>Thank you</p> <p>EDIT: tried putting if statement inside <code>post-thumbnail-template.php</code> <code>has_post_thumbnail</code> function but did not work. Where can I check for image in folder early and possibly not edit WordPress core file?</p> <p>EDIT: it somewhat works I think. Issue is I need to match image name in directory to another post meta, woocommerce product in my case.</p> <p>I check for image in custom folder first then for post attachment here is how I have done that so far overiding product template files:</p> <pre><code>global $post; $picname = get_post_meta( get_the_ID(), '_box_upc', true ); $file = '/var/www/html/images/products/' . $picname . '.jpg'; if (file_exists($file)) { $filesrc = home_url( '/' ).'images/products/' . $picname . '.jpg'; //show the image $result = '&lt;img src="' . $filesrc. '" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" title=""&gt;'; }else{ //return post attachment if exists code } </code></pre> <p>using @krzysiek-dróżdż code this is what I have but seems like I can't use global $post to get other post meta to match file name, nor post title it gives server error:</p> <pre><code>function my_override_has_post_thumbnail( $result, $object_id, $meta_key, $single ) { global $post; // Get post other meta, neither one works so I uncommeneted //$picname = get_post_meta( $post-&gt;get_id(), '_box_upc', true ); //$picname = get_post_meta( get_the_ID(), '_box_upc', true ); if ( '_thumbnail_id' === $meta_key ) { // perform your checks and return some ID if thumbnail exists // Get image from custom folder $filelocation = '/var/www/html/images/products/' . $picname . '.jpg'; if (file_exists($filelocation)) { $filesrc = home_url( '/' ).'images/products/' . $picname . '.jpg'; //show the image $result = '&lt;img src="' . $filesrc. '" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="'.$post-&gt;get_title().'" title="'.$post-&gt;get_title().'"&gt;'; } } return $result; } add_filter( 'get_post_metadata', 'my_override_has_post_thumbnail', 10, 4 ); </code></pre>
[ { "answer_id": 300811, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": false, "text": "<p>Yes, there is a way to do that... Let's take a look at <code>has_post_thumbnail</code> function itself:</p>\n\n<pre><code>function has_post_thumbnail( $post = null ) {\n return (bool) get_post_thumbnail_id( $post );\n}\n</code></pre>\n\n<p>As you can see, all it really does is getting post thumbnail ID and checking if it exists. But there are no filters in here. Let's go deeper:</p>\n\n<pre><code>function get_post_thumbnail_id( $post = null ) {\n $post = get_post( $post );\n if ( ! $post ) {\n return '';\n }\n return get_post_meta( $post-&gt;ID, '_thumbnail_id', true );\n}\n</code></pre>\n\n<p>Still no filters, but there is a hope:</p>\n\n<pre><code>function get_post_meta( $post_id, $key = '', $single = false ) {\n return get_metadata('post', $post_id, $key, $single);\n}\n</code></pre>\n\n<p>And at last in <code>get_metadata</code>...</p>\n\n<pre><code>function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {\n if ( ! $meta_type || ! is_numeric( $object_id ) ) {\n return false;\n }\n\n $object_id = absint( $object_id );\n if ( ! $object_id ) {\n return false;\n }\n\n /**\n * Filters whether to retrieve metadata of a specific type.\n *\n * The dynamic portion of the hook, `$meta_type`, refers to the meta\n * object type (comment, post, or user). Returning a non-null value\n * will effectively short-circuit the function.\n *\n * @since 3.1.0\n *\n * @param null|array|string $value The value get_metadata() should return - a single metadata value,\n * or an array of values.\n * @param int $object_id Object ID.\n * @param string $meta_key Meta key.\n * @param bool $single Whether to return only the first value of the specified $meta_key.\n */\n $check = apply_filters( \"get_{$meta_type}_metadata\", null, $object_id, $meta_key, $single );\n if ( null !== $check ) {\n if ( $single &amp;&amp; is_array( $check ) )\n return $check[0];\n else\n return $check;\n }\n ...\n</code></pre>\n\n<p>It looks like we can use <code>get_post_metadata</code> hook to override <code>has_post_thumbnail</code> result. The only thing you have to remember is that it will change the behavior of <code>get_post_thumbnail_id</code> also...</p>\n\n<p>Something like this should do the trick:</p>\n\n<pre><code>function my_override_has_post_thumbnail( $result, $object_id, $meta_key, $single ) {\n if ( '_thumbnail_id' === $meta_key ) {\n // perform your checks and return some ID if thumbnail exists\n }\n\n return $result;\n}\nadd_filter( 'get_post_metadata', 'my_override_has_post_thumbnail', 10, 4 );\n</code></pre>\n" }, { "answer_id": 300812, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>@Krzysiek Dróżdż answer is a very correct one to the question you are asking, but you should ask yourself whether you are asking the right question....</p>\n\n<p>Wordpress assumes that some amount of image related information is properly stored in the DB for its APIs to be able to properly handle them. Images that are not in the DB are external and the APIs will just not apply to them. Right now you have identified one API which gives you problems, but the more complex your code becomes, or the more 3rd party code is used on the site, you are going to run into more APIs which do not work for your images.</p>\n\n<p>So the right answer might be to avoid the problem in the first place and properly import the images into wordpress.</p>\n" } ]
2018/04/15
[ "https://wordpress.stackexchange.com/questions/300807", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125675/" ]
Is there a way to alter/change core `has_post_thumbnail` function? I need to check folder on server with images first before code looks for post image attachment. I see lots of filters to change image html but they either affect single post page or loop thumbnail and with woocommerce several other places plus admin tables, etc. I need to place the server directory check before it even hits `_post_thumbnail()` or `get_image` so it looks like `has_post_thumbnail` is very first check unless I'm wrong. Please help, suggest what can be done. Thank you EDIT: tried putting if statement inside `post-thumbnail-template.php` `has_post_thumbnail` function but did not work. Where can I check for image in folder early and possibly not edit WordPress core file? EDIT: it somewhat works I think. Issue is I need to match image name in directory to another post meta, woocommerce product in my case. I check for image in custom folder first then for post attachment here is how I have done that so far overiding product template files: ``` global $post; $picname = get_post_meta( get_the_ID(), '_box_upc', true ); $file = '/var/www/html/images/products/' . $picname . '.jpg'; if (file_exists($file)) { $filesrc = home_url( '/' ).'images/products/' . $picname . '.jpg'; //show the image $result = '<img src="' . $filesrc. '" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" title="">'; }else{ //return post attachment if exists code } ``` using @krzysiek-dróżdż code this is what I have but seems like I can't use global $post to get other post meta to match file name, nor post title it gives server error: ``` function my_override_has_post_thumbnail( $result, $object_id, $meta_key, $single ) { global $post; // Get post other meta, neither one works so I uncommeneted //$picname = get_post_meta( $post->get_id(), '_box_upc', true ); //$picname = get_post_meta( get_the_ID(), '_box_upc', true ); if ( '_thumbnail_id' === $meta_key ) { // perform your checks and return some ID if thumbnail exists // Get image from custom folder $filelocation = '/var/www/html/images/products/' . $picname . '.jpg'; if (file_exists($filelocation)) { $filesrc = home_url( '/' ).'images/products/' . $picname . '.jpg'; //show the image $result = '<img src="' . $filesrc. '" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="'.$post->get_title().'" title="'.$post->get_title().'">'; } } return $result; } add_filter( 'get_post_metadata', 'my_override_has_post_thumbnail', 10, 4 ); ```
Yes, there is a way to do that... Let's take a look at `has_post_thumbnail` function itself: ``` function has_post_thumbnail( $post = null ) { return (bool) get_post_thumbnail_id( $post ); } ``` As you can see, all it really does is getting post thumbnail ID and checking if it exists. But there are no filters in here. Let's go deeper: ``` function get_post_thumbnail_id( $post = null ) { $post = get_post( $post ); if ( ! $post ) { return ''; } return get_post_meta( $post->ID, '_thumbnail_id', true ); } ``` Still no filters, but there is a hope: ``` function get_post_meta( $post_id, $key = '', $single = false ) { return get_metadata('post', $post_id, $key, $single); } ``` And at last in `get_metadata`... ``` function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) { if ( ! $meta_type || ! is_numeric( $object_id ) ) { return false; } $object_id = absint( $object_id ); if ( ! $object_id ) { return false; } /** * Filters whether to retrieve metadata of a specific type. * * The dynamic portion of the hook, `$meta_type`, refers to the meta * object type (comment, post, or user). Returning a non-null value * will effectively short-circuit the function. * * @since 3.1.0 * * @param null|array|string $value The value get_metadata() should return - a single metadata value, * or an array of values. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param bool $single Whether to return only the first value of the specified $meta_key. */ $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single ); if ( null !== $check ) { if ( $single && is_array( $check ) ) return $check[0]; else return $check; } ... ``` It looks like we can use `get_post_metadata` hook to override `has_post_thumbnail` result. The only thing you have to remember is that it will change the behavior of `get_post_thumbnail_id` also... Something like this should do the trick: ``` function my_override_has_post_thumbnail( $result, $object_id, $meta_key, $single ) { if ( '_thumbnail_id' === $meta_key ) { // perform your checks and return some ID if thumbnail exists } return $result; } add_filter( 'get_post_metadata', 'my_override_has_post_thumbnail', 10, 4 ); ```
300,857
<p>I am creating a single-page child theme, in which (apologies to the Wordpress community) I am basically trying to stay out of using PHP or the Wordpress API as much as possible, because I really just want to deploy a single page with its own scripts and style.</p> <p>I'm having problems with relative file paths. I have gathered that when it comes to PHP pages I need to use the <code>get_theme_file_uri()</code> function, and that is working fine in my main PHP page (page-my-slug.php). (As a side note, I would prefer to use <code>get_template_directory_uri()</code> but this is giving the parent theme folder. How to get round this? [edit: this part is solved])</p> <p>But what is the solution for my CSS file (eg. for images)? <a href="https://stackoverflow.com/questions/10058167/wordpress-3-3-relative-paths-in-css">This page</a> suggests I should just be able to insert relative links in there, but that's not working for me.</p> <p>I am linking my stylesheet directly in my <code>page-my-slug.php</code>, because I want to override the parent theme style totally, and don't want to get into the details of enqueuing:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/style.css"&gt; &lt;!-- or, for exactly the same effect... --&gt; &lt;link rel="stylesheet" type="text/css" href="&lt;?php echo get_theme_file_uri('style.css'); ?&gt;"&gt; </code></pre> <p>In my <code>style.css</code> I am using, for example:</p> <pre><code>#ffw { background-image: url(images/ffw.png); } </code></pre> <p>But, when loading the page I get an error:</p> <pre><code>GET https://domain.com/images/ffw.png 404 () </code></pre> <p>Which suggests it is looking in the root directory rather than relative to the stylesheet.</p> <p>What am I doing wrong? I wonder if it has something to do with the fact that I have linked my CSS directly rather than enqueued it...</p>
[ { "answer_id": 300860, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>You should be using <code>get_stylesheet_directory_uri()</code>. This is the same function as <code>get_template_directory_uri()</code> but it uses the directory of the child theme.</p>\n\n<p>as an example:</p>\n\n<pre><code>get_template_directory_uri().'/logos/coollogo.png';\n</code></pre>\n\n<p>will pull the logo from the logos folder in your child theme.</p>\n" }, { "answer_id": 300865, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Relative paths in CSS are relative to the stylesheet file. So if you have this structure:</p>\n\n<pre><code>- style.css\n- images/\n-- logo.png\n-- background.jpg\n</code></pre>\n\n<p>Then the paths in CSS for the images would be <code>url(images/logo.png)</code> and <code>url(images/background.jpg)</code>. This is because the relative paths in CSS are relative to the stylesheet itself, not the main domain (if you want that, start with a slash: <code>url(/images/logo.png)</code>).</p>\n\n<p>None of this is affected by how you choose to enqueue the file.</p>\n\n<p>Where you might be going wrong is that you mentioned a parent theme. If you're trying to load an image from the parent theme, a relative path like the above example isn't going to work. CSS has no knowledge or concept of a parent/child theme relationship.</p>\n\n<p>So if your directory structure looks like this:</p>\n\n<pre><code>- parent-theme/\n-- images/\n--- logo.png\n- child-theme/\n-- style.css\n-- images/\n--- background.jpg\n</code></pre>\n\n<p>So if you want to go up a directory and then into the parent directory your path needs to look be <code>url(../parent-theme/images/logo.png)</code>.</p>\n" }, { "answer_id": 300940, "author": "Igid", "author_id": 141801, "author_profile": "https://wordpress.stackexchange.com/users/141801", "pm_score": 0, "selected": false, "text": "<p>I think I know what the answer is. I just clicked through from the source code to my stylesheet, and found that the server is caching an old version in which I had mistakenly written <code>url(/images/logo.png)</code> with the initial slash taking me to the root.</p>\n\n<p>Sorry everyone, another question about CSS paths that comes down to a silly peripheral issue.</p>\n" } ]
2018/04/15
[ "https://wordpress.stackexchange.com/questions/300857", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141801/" ]
I am creating a single-page child theme, in which (apologies to the Wordpress community) I am basically trying to stay out of using PHP or the Wordpress API as much as possible, because I really just want to deploy a single page with its own scripts and style. I'm having problems with relative file paths. I have gathered that when it comes to PHP pages I need to use the `get_theme_file_uri()` function, and that is working fine in my main PHP page (page-my-slug.php). (As a side note, I would prefer to use `get_template_directory_uri()` but this is giving the parent theme folder. How to get round this? [edit: this part is solved]) But what is the solution for my CSS file (eg. for images)? [This page](https://stackoverflow.com/questions/10058167/wordpress-3-3-relative-paths-in-css) suggests I should just be able to insert relative links in there, but that's not working for me. I am linking my stylesheet directly in my `page-my-slug.php`, because I want to override the parent theme style totally, and don't want to get into the details of enqueuing: ``` <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_directory_uri(); ?>/style.css"> <!-- or, for exactly the same effect... --> <link rel="stylesheet" type="text/css" href="<?php echo get_theme_file_uri('style.css'); ?>"> ``` In my `style.css` I am using, for example: ``` #ffw { background-image: url(images/ffw.png); } ``` But, when loading the page I get an error: ``` GET https://domain.com/images/ffw.png 404 () ``` Which suggests it is looking in the root directory rather than relative to the stylesheet. What am I doing wrong? I wonder if it has something to do with the fact that I have linked my CSS directly rather than enqueued it...
Relative paths in CSS are relative to the stylesheet file. So if you have this structure: ``` - style.css - images/ -- logo.png -- background.jpg ``` Then the paths in CSS for the images would be `url(images/logo.png)` and `url(images/background.jpg)`. This is because the relative paths in CSS are relative to the stylesheet itself, not the main domain (if you want that, start with a slash: `url(/images/logo.png)`). None of this is affected by how you choose to enqueue the file. Where you might be going wrong is that you mentioned a parent theme. If you're trying to load an image from the parent theme, a relative path like the above example isn't going to work. CSS has no knowledge or concept of a parent/child theme relationship. So if your directory structure looks like this: ``` - parent-theme/ -- images/ --- logo.png - child-theme/ -- style.css -- images/ --- background.jpg ``` So if you want to go up a directory and then into the parent directory your path needs to look be `url(../parent-theme/images/logo.png)`.
300,896
<p>I got a weird problem: First of all I provide my folder structure:</p> <pre><code> wp-content/themes/theme ├──content.php ├──footer.php ├──functions.php ├──header.php ├──home.php ├──index.php ├──page.php ├──main.js ├──style.css │ ├── media/ │ └── img/ │ ├── beach.mp4 │ ├── contact-1.jpg │ └── offers-1.jpg │ └── scripts/ └── map.js </code></pre> <p>So, in my <code>style.css</code> I defined a background image like this:</p> <pre><code>background-image:url('media/img/offers-1.jpg'); </code></pre> <p>That get's shown perfectly, but whatever file I load from my <code>index.php</code> (which loads <code>content.php</code>) won't get found, i.e. I got a normal image like this</p> <pre><code>&lt;img src="media/img/contact-1.jpg"&gt; </code></pre> <p>which doesn't get found with the following error:</p> <pre><code>GET http://url/newer/media/img/contact-1.jpg 404 (Not Found) </code></pre> <p>Same for <code>map.js</code>, <code>main.js</code> and some other images.</p> <p>Does anyone know what I may did wrong?</p>
[ { "answer_id": 300897, "author": "wpdev", "author_id": 133897, "author_profile": "https://wordpress.stackexchange.com/users/133897", "pm_score": 0, "selected": false, "text": "<p>If you are using tag in any php file, just use <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\">get_template_directory_uri()</a></p>\n\n<pre><code>&lt;img src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/img/contact-1.jpg\"&gt;\n</code></pre>\n" }, { "answer_id": 300898, "author": "Ibrahim Mohamed", "author_id": 141791, "author_profile": "https://wordpress.stackexchange.com/users/141791", "pm_score": 4, "selected": true, "text": "<p>Relative paths in css files are relative to the css file location, but in PHP they are relative to the website URL not to the php file location in the server.</p>\n\n<p>So to make sure you get the right URL for any resource you want to load in PHP files you can use the function <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\">get_template_directory_uri()</a>\nlike this: </p>\n\n<p><code>\"&lt;?php echo get_template_directory_uri(); ?&gt;\"</code>:</p>\n\n<p>For example in <code>img</code> the attribute <code>src</code> would be:</p>\n\n<p><code>&lt;img src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/media/img/contact-1.jpg\" /&gt;</code></p>\n\n<p>And so on for js files and css files.</p>\n\n<p><strong>Notice:</strong>\nIn the case of using a Child theme, use this function instead <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow noreferrer\">get_stylesheet_directory_uri()</a> the same way:</p>\n\n<p><code>&lt;img src=\"&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/assets/img.jpg\" /&gt;</code></p>\n\n<p>Otherwise the <code>get_template_directory_uri()</code> function in this case will only return the current <strong>parent</strong> theme URL and not the URL of the child theme which you are using in this case.</p>\n" } ]
2018/04/16
[ "https://wordpress.stackexchange.com/questions/300896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141857/" ]
I got a weird problem: First of all I provide my folder structure: ``` wp-content/themes/theme ├──content.php ├──footer.php ├──functions.php ├──header.php ├──home.php ├──index.php ├──page.php ├──main.js ├──style.css │ ├── media/ │ └── img/ │ ├── beach.mp4 │ ├── contact-1.jpg │ └── offers-1.jpg │ └── scripts/ └── map.js ``` So, in my `style.css` I defined a background image like this: ``` background-image:url('media/img/offers-1.jpg'); ``` That get's shown perfectly, but whatever file I load from my `index.php` (which loads `content.php`) won't get found, i.e. I got a normal image like this ``` <img src="media/img/contact-1.jpg"> ``` which doesn't get found with the following error: ``` GET http://url/newer/media/img/contact-1.jpg 404 (Not Found) ``` Same for `map.js`, `main.js` and some other images. Does anyone know what I may did wrong?
Relative paths in css files are relative to the css file location, but in PHP they are relative to the website URL not to the php file location in the server. So to make sure you get the right URL for any resource you want to load in PHP files you can use the function [get\_template\_directory\_uri()](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) like this: `"<?php echo get_template_directory_uri(); ?>"`: For example in `img` the attribute `src` would be: `<img src="<?php echo get_template_directory_uri(); ?>/media/img/contact-1.jpg" />` And so on for js files and css files. **Notice:** In the case of using a Child theme, use this function instead [get\_stylesheet\_directory\_uri()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri) the same way: `<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/img.jpg" />` Otherwise the `get_template_directory_uri()` function in this case will only return the current **parent** theme URL and not the URL of the child theme which you are using in this case.
300,912
<p>I'm new to WordPress I want to add simple color picker in theme options.I tried but not getting can anyone suggest me? </p>
[ { "answer_id": 300916, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 3, "selected": true, "text": "<p>Working code to set color customizer in wordpress theme settings:</p>\n\n<pre><code> function color_customizer($wp_customize){\n $wp_customize-&gt;add_section( 'theme_colors_settings', array(\n 'title' =&gt; __( 'Theme Colors Settings', 'themeslug' ),\n 'priority' =&gt; 5,\n ) );\n\n $theme_colors = array();\n\n // Navigation Background Color\n $theme_colors[] = array(\n 'slug'=&gt;'color_section_name',\n 'default' =&gt; '#000000',\n 'label' =&gt; __('Color Section Title', 'themeslug')\n );\n\n foreach( $theme_colors as $color ) {\n\n $wp_customize-&gt;add_setting(\n $color['slug'], array(\n 'default' =&gt; $color['default'],\n 'sanitize_callback' =&gt; 'sanitize_hex_color',\n 'type' =&gt; 'option',\n 'capability' =&gt; 'edit_theme_options'\n )\n );\n\n $wp_customize-&gt;add_control(\n new WP_Customize_Color_Control(\n $wp_customize,\n $color['slug'],\n array('label' =&gt; $color['label'],\n 'section' =&gt; 'theme_colors_settings',\n 'settings' =&gt; $color['slug'])\n )\n );\n }\n }\n\n add_action( 'customize_register', 'color_customizer' );\n</code></pre>\n" }, { "answer_id": 381765, "author": "Alexius The Coder", "author_id": 151351, "author_profile": "https://wordpress.stackexchange.com/users/151351", "pm_score": 0, "selected": false, "text": "<p>Use WordPress Customizer.\nTo add WordPress Color Picker just use Customizer Manager with add_ methods for each Customizer object.\nCode may be used in functions.php file or in a separate customizer specific file.</p>\n<pre><code>function diwp_customizer_add_colorPicker( $wp_customize){\n \n // Add New Section: Background Colors\n $wp_customize-&gt;add_section( 'diwp_color_section', array(\n 'title' =&gt; 'Background Color',\n 'description' =&gt; 'Set Color For Background',\n 'priority' =&gt; '40'\n ));\n \n // Add Settings\n $wp_customize-&gt;add_setting( 'diwp_background_color', array(\n 'default' =&gt; '#370d07',\n ));\n \n \n // Add Controls\n $wp_customize-&gt;add_control( new WP_Customize_Color_Control( $wp_customize, 'diwp_background_color', array(\n 'label' =&gt; 'Choose Color',\n 'section' =&gt; 'diwp_color_section',\n 'settings' =&gt; 'diwp_background_color'\n \n )));\n \n \n}\n\nadd_action( 'customize_register', 'diwp_customizer_add_colorPicker' );\n</code></pre>\n<p>To display changed color add this code in functions.php:</p>\n<pre><code>// displays custom background color\nfunction diwp_generate_theme_option_css() {\n \n $backColor = get_theme_mod( 'diwp_background_color' );\n \n if ( ! empty( $backColor ) ):\n \n ?&gt;\n &lt;style type=&quot;text/css&quot; id=&quot;diwp-theme-option-css&quot;&gt;\n \n .container {\n background: &lt;?php echo esc_html($backColor); ?&gt;\n }\n \n &lt;/style&gt;\n \n &lt;?php\n \n endif;\n}\n\nadd_action( 'wp_head', 'diwp_generate_theme_option_css' );\n</code></pre>\n<p><a href=\"https://diveinwp.com/add-wordpress-customizer-color-picker-palette/\" rel=\"nofollow noreferrer\">Original code here</a></p>\n<p>Or You can see how to change a color with jQuery in this answer <a href=\"https://wordpress.stackexchange.com/a/360001/151351\">https://wordpress.stackexchange.com/a/360001/151351</a></p>\n" }, { "answer_id": 381782, "author": "en0ndev", "author_id": 199873, "author_profile": "https://wordpress.stackexchange.com/users/199873", "pm_score": 0, "selected": false, "text": "<p>Try these codes to your Functions.php</p>\n<p>We add the details of customizer setting.</p>\n<pre><code>function theme_customize_register( $wp_customize ) {\n $wp_customize-&gt;add_setting( 'main_color', array(\n 'default' =&gt; '#ffffff',\n 'transport' =&gt; 'refresh',\n 'sanitize_callback' =&gt; 'sanitize_hex_color',\n ) );\nadd_action( 'customize_register', 'theme_customize_register' );\n</code></pre>\n<p>It then integrates the customizer and attribute in CSS file.</p>\n<pre><code>function theme_get_customizer_css() {\n ob_start();\n $main_color = get_theme_mod( 'main_color', '' );\n if ( ! empty( $main_color ) ) {\n ?&gt;\n .contentDetails a {\n color: &lt;?php echo $main_color; ?&gt;;\n }\n &lt;?php\n }\n $css = ob_get_clean();\n return $css;\n}\n</code></pre>\n<p>And for CSS and the customizer connection.</p>\n<pre><code>function theme_enqueue_styles() {\n wp_enqueue_style( 'theme-styles', get_stylesheet_uri() );\n $custom_css = theme_get_customizer_css();\n wp_add_inline_style( 'theme-styles', $custom_css );\n}\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n</code></pre>\n" } ]
2018/04/16
[ "https://wordpress.stackexchange.com/questions/300912", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131806/" ]
I'm new to WordPress I want to add simple color picker in theme options.I tried but not getting can anyone suggest me?
Working code to set color customizer in wordpress theme settings: ``` function color_customizer($wp_customize){ $wp_customize->add_section( 'theme_colors_settings', array( 'title' => __( 'Theme Colors Settings', 'themeslug' ), 'priority' => 5, ) ); $theme_colors = array(); // Navigation Background Color $theme_colors[] = array( 'slug'=>'color_section_name', 'default' => '#000000', 'label' => __('Color Section Title', 'themeslug') ); foreach( $theme_colors as $color ) { $wp_customize->add_setting( $color['slug'], array( 'default' => $color['default'], 'sanitize_callback' => 'sanitize_hex_color', 'type' => 'option', 'capability' => 'edit_theme_options' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, $color['slug'], array('label' => $color['label'], 'section' => 'theme_colors_settings', 'settings' => $color['slug']) ) ); } } add_action( 'customize_register', 'color_customizer' ); ```
300,925
<p>For some reason I cant seem to enqueue external JS files. I can enqueue external css files but not the JS files. I have a custom theme using the bootstrap css frame work. My functions.php is as follows:</p> <pre><code>function add_css_scripts(){ wp_enqueue_style('boot-strap','https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css',false); wp_enqueue_style('style', get_template_directory_uri() . '/style.css', false, 'all'); wp_enqueue_style('media', get_template_directory_uri(). '/assets/css/media.css', false, all); } add_action('wp_enqueue_scripts', 'add_css_scripts'); /*Jquery Scripst*/ function add_js_scripts(){ wp_deregister_script( 'jquery' ); //wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', false, '3.3.1', true); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', false, '3.3.1', true); wp_enqueue_script('jquery'); wp_register_script('pre', get_template_directory_uri(). '/assets/js/pre.js','1.0.0', array('jquery'), '1.0.0', true); wp_enqueue_script('pre'); //wp_enqueue_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', array('jquery'), '4.1.0', true); wp_register_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', array('jquery'), '4.1.0', true); wp_enqueue_script('bootstrap'); //wp_enqueue_script('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', array('jquery'), '1.12.9', true); wp_register_script('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', array('jquery'), '1.12.9', true); wp_enqueue_script('popper'); } add_action('wp_enqueue_scripts','add_js_scripts'); </code></pre> <p>Everything commented out are bits of code I've tried and hasnt work, the <code>wp_deregister('jquery');</code> works since I need the jquery version 3 and when I add the scripts to my footer.php it works.</p>
[ { "answer_id": 300927, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 1, "selected": false, "text": "<p>Using external jQuery is a bad idea. The bundled one is optimized to work better with WordPress. </p>\n\n<p>For your problem, I think the issue is with your way of registering external jquery. Use an empty array instead of <code>false</code> in dependency. </p>\n\n<pre><code>function add_js_scripts(){\n wp_deregister_script( 'jquery' );\n\n wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', array(), '3.3.1', true);\n\n wp_enqueue_script('pre', get_template_directory_uri(). '/assets/js/pre.js','1.0.0', array('jquery'), '1.0.0', true);\n\n wp_enqueue_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', array('jquery'), '4.1.0', true);\n\n wp_enqueue_script('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', array('jquery'), '1.12.9', true);\n\n}\nadd_action('wp_enqueue_scripts','add_js_scripts'); \n</code></pre>\n\n<p>Also, you don't need to enqueue jquery separately. When you set any script dependent to jquery, it will automatically enqueue it before your script.</p>\n" }, { "answer_id": 339172, "author": "Pwilson77", "author_id": 169125, "author_profile": "https://wordpress.stackexchange.com/users/169125", "pm_score": 2, "selected": false, "text": "<p>instead of using <code>get_template_directory_uri().'/assets/js/pre.js','1.0.0'</code></p>\n\n<p>try using <code>get_theme_file_uri('/assets/js/pre.js','1.0.0')</code></p>\n\n<p>It worked for me, for some reason when use <code>get_template_directory_uri()</code> you will get a 403 error </p>\n" } ]
2018/04/16
[ "https://wordpress.stackexchange.com/questions/300925", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93537/" ]
For some reason I cant seem to enqueue external JS files. I can enqueue external css files but not the JS files. I have a custom theme using the bootstrap css frame work. My functions.php is as follows: ``` function add_css_scripts(){ wp_enqueue_style('boot-strap','https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css',false); wp_enqueue_style('style', get_template_directory_uri() . '/style.css', false, 'all'); wp_enqueue_style('media', get_template_directory_uri(). '/assets/css/media.css', false, all); } add_action('wp_enqueue_scripts', 'add_css_scripts'); /*Jquery Scripst*/ function add_js_scripts(){ wp_deregister_script( 'jquery' ); //wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', false, '3.3.1', true); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', false, '3.3.1', true); wp_enqueue_script('jquery'); wp_register_script('pre', get_template_directory_uri(). '/assets/js/pre.js','1.0.0', array('jquery'), '1.0.0', true); wp_enqueue_script('pre'); //wp_enqueue_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', array('jquery'), '4.1.0', true); wp_register_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', array('jquery'), '4.1.0', true); wp_enqueue_script('bootstrap'); //wp_enqueue_script('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', array('jquery'), '1.12.9', true); wp_register_script('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', array('jquery'), '1.12.9', true); wp_enqueue_script('popper'); } add_action('wp_enqueue_scripts','add_js_scripts'); ``` Everything commented out are bits of code I've tried and hasnt work, the `wp_deregister('jquery');` works since I need the jquery version 3 and when I add the scripts to my footer.php it works.
instead of using `get_template_directory_uri().'/assets/js/pre.js','1.0.0'` try using `get_theme_file_uri('/assets/js/pre.js','1.0.0')` It worked for me, for some reason when use `get_template_directory_uri()` you will get a 403 error
300,988
<p>maybe u can help to solve this problem. for example i have this link</p> <pre><code>https://direktoriku.com/shopping/?user= </code></pre> <p>and i want to add username after login, like <code>https://direktoriku.com/shopping/?user=admin</code></p> <p>I want to make it on button.</p> <pre><code>&lt;a href="https://direktoriku.com/shopping/?user=username"&gt; &lt;button&gt;Click me&lt;/button&gt; &lt;/a&gt; </code></pre> <p>I want to put this on post / page. </p>
[ { "answer_id": 300927, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 1, "selected": false, "text": "<p>Using external jQuery is a bad idea. The bundled one is optimized to work better with WordPress. </p>\n\n<p>For your problem, I think the issue is with your way of registering external jquery. Use an empty array instead of <code>false</code> in dependency. </p>\n\n<pre><code>function add_js_scripts(){\n wp_deregister_script( 'jquery' );\n\n wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', array(), '3.3.1', true);\n\n wp_enqueue_script('pre', get_template_directory_uri(). '/assets/js/pre.js','1.0.0', array('jquery'), '1.0.0', true);\n\n wp_enqueue_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js', array('jquery'), '4.1.0', true);\n\n wp_enqueue_script('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', array('jquery'), '1.12.9', true);\n\n}\nadd_action('wp_enqueue_scripts','add_js_scripts'); \n</code></pre>\n\n<p>Also, you don't need to enqueue jquery separately. When you set any script dependent to jquery, it will automatically enqueue it before your script.</p>\n" }, { "answer_id": 339172, "author": "Pwilson77", "author_id": 169125, "author_profile": "https://wordpress.stackexchange.com/users/169125", "pm_score": 2, "selected": false, "text": "<p>instead of using <code>get_template_directory_uri().'/assets/js/pre.js','1.0.0'</code></p>\n\n<p>try using <code>get_theme_file_uri('/assets/js/pre.js','1.0.0')</code></p>\n\n<p>It worked for me, for some reason when use <code>get_template_directory_uri()</code> you will get a 403 error </p>\n" } ]
2018/04/17
[ "https://wordpress.stackexchange.com/questions/300988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141909/" ]
maybe u can help to solve this problem. for example i have this link ``` https://direktoriku.com/shopping/?user= ``` and i want to add username after login, like `https://direktoriku.com/shopping/?user=admin` I want to make it on button. ``` <a href="https://direktoriku.com/shopping/?user=username"> <button>Click me</button> </a> ``` I want to put this on post / page.
instead of using `get_template_directory_uri().'/assets/js/pre.js','1.0.0'` try using `get_theme_file_uri('/assets/js/pre.js','1.0.0')` It worked for me, for some reason when use `get_template_directory_uri()` you will get a 403 error
301,030
<p>I get 500 error on wp-json.</p> <p>if I try to <code>echo get_rest_url()</code> I get <code>example.com/wp-json</code>, which then gives me error 500. I added <code>RewriteCond %{REQUEST_URI} !^/wp-json</code> to my .htaccess, which gave me 404 error instead.</p> <p>I use postname as settings for permalinks. I've tried <code>http://example.com/?rest_route=/wp-json/v2/posts</code> as well, and it gives me error 500.</p> <p>EDIT: Okay, I turned on wp_debug. Now I get the error: <code>Fatal error: Call to undefined function register_rest_route() in /customers/0/2/1/</code>. So this is my new error. Any clue for this?</p>
[ { "answer_id": 308870, "author": "Tiago Aranha", "author_id": 137668, "author_profile": "https://wordpress.stackexchange.com/users/137668", "pm_score": -1, "selected": false, "text": "<p>Create a .htaccess file with</p>\n\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n" }, { "answer_id": 369690, "author": "Tex0gen", "author_id": 97070, "author_profile": "https://wordpress.stackexchange.com/users/97070", "pm_score": 1, "selected": false, "text": "<p>Are you trying to use that function without first initiating it in an action? It should be done like so:</p>\n<pre><code>add_action( 'rest_api_init', 'add_custom_users_api');\n\nfunction add_custom_users_api()\n{\n register_rest_route( 'route', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'function',\n ));\n}\n</code></pre>\n" } ]
2018/04/17
[ "https://wordpress.stackexchange.com/questions/301030", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134908/" ]
I get 500 error on wp-json. if I try to `echo get_rest_url()` I get `example.com/wp-json`, which then gives me error 500. I added `RewriteCond %{REQUEST_URI} !^/wp-json` to my .htaccess, which gave me 404 error instead. I use postname as settings for permalinks. I've tried `http://example.com/?rest_route=/wp-json/v2/posts` as well, and it gives me error 500. EDIT: Okay, I turned on wp\_debug. Now I get the error: `Fatal error: Call to undefined function register_rest_route() in /customers/0/2/1/`. So this is my new error. Any clue for this?
Are you trying to use that function without first initiating it in an action? It should be done like so: ``` add_action( 'rest_api_init', 'add_custom_users_api'); function add_custom_users_api() { register_rest_route( 'route', array( 'methods' => 'GET', 'callback' => 'function', )); } ```
301,048
<p>I've created a custom loop for posts, that works with Bootstrap, in which, I've added pagination - however it doesn't seem to be working. It just shows an empty button...</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { $i = 0; while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); if($i % 2 == 0) { ?&gt; &lt;div class="row"&gt;&lt;?php } ?&gt; &lt;div class="col-md-6"&gt; &lt;div class="overview"&gt; &lt;!-- Post details here --&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $i++; if($i != 0 &amp;&amp; $i % 2 == 0) { ?&gt; &lt;/div&gt;&lt;!--/.row--&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;?php } endwhile; ?&gt; &lt;nav class="pagination"&gt; &lt;button class="btn-whole"&gt;&lt;?php previous_posts_link('Previous') ?&gt;&lt;/button&gt; &lt;button class="btn-whole"&gt;&lt;?php next_posts_link('Next') ?&gt;&lt;/button&gt; &lt;/nav&gt; &lt;?php } wp_reset_query(); ?&gt; </code></pre> <p>Any ideas on why this might be happening?</p>
[ { "answer_id": 301050, "author": "NikHiL Gadhiya", "author_id": 136899, "author_profile": "https://wordpress.stackexchange.com/users/136899", "pm_score": 2, "selected": false, "text": "<p>only just use echo and get_</p>\n\n<pre><code>&lt;?php $args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 1\n);\n\n$my_query = null;\n$my_query = new WP_Query($args);\nif( $my_query-&gt;have_posts() ) {\n $i = 0;\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();\n if($i % 2 == 0) { ?&gt;\n &lt;div class=\"row\"&gt;&lt;?php } ?&gt;\n &lt;div class=\"col-md-6\"&gt;\n &lt;div class=\"overview\"&gt;\n &lt;!-- Post details here --&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php $i++; if($i != 0 &amp;&amp; $i % 2 == 0) { ?&gt;\n &lt;/div&gt;&lt;!--/.row--&gt;\n &lt;div class=\"clearfix\"&gt;&lt;/div&gt;\n &lt;?php }\n endwhile; ?&gt;\n &lt;nav class=\"pagination\"&gt;\n &lt;button class=\"btn-whole\"&gt;&lt;?php echo get_previous_posts_link('Previous'); ?&gt;&lt;/button&gt;\n &lt;button class=\"btn-whole\"&gt;&lt;?php echo get_next_posts_link('Next'); ?&gt;&lt;/button&gt;\n &lt;/nav&gt;\n&lt;?php } wp_reset_query(); ?&gt;\n</code></pre>\n" }, { "answer_id": 301109, "author": "NikHiL Gadhiya", "author_id": 136899, "author_profile": "https://wordpress.stackexchange.com/users/136899", "pm_score": 0, "selected": false, "text": "<pre><code>try now this code\n&lt;? \n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n $args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 1,\n 'paged' =&gt; $paged,\n );\n\n $my_query = null;\n $my_query = new WP_Query($args);\n if( $my_query-&gt;have_posts() ) {\n $i = 0;\n while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();\n if($i % 2 == 0) { ?&gt;\n &lt;div class=\"row\"&gt;&lt;?php } ?&gt;\n &lt;div class=\"col-md-6\"&gt;\n &lt;div class=\"overview\"&gt;\n &lt;!-- Post details here --&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php $i++; if($i != 0 &amp;&amp; $i % 2 == 0) { ?&gt;\n &lt;/div&gt;&lt;!--/.row--&gt;\n &lt;div class=\"clearfix\"&gt;&lt;/div&gt;\n &lt;?php }\n endwhile; ?&gt;\n &lt;nav class=\"pagination\"&gt;\n &lt;button class=\"btn-whole\"&gt;&lt;?php previous_posts_link('prev', $my_query-&gt;max_num_pages); ?&gt;&lt;/button&gt;\n &lt;button class=\"btn-whole\"&gt;&lt;?php next_posts_link('next', $my_query-&gt;max_num_pages); ?&gt;&lt;/button&gt;\n &lt;/nav&gt;\n &lt;?php } wp_reset_query(); ?&gt;\n</code></pre>\n" }, { "answer_id": 348529, "author": "Matt_Geo", "author_id": 175331, "author_profile": "https://wordpress.stackexchange.com/users/175331", "pm_score": 1, "selected": false, "text": "<p>I know this post is a bit old but I got stuck in the same point and probably other will stumble upon in question to find an answer. \nI wanted to create a custom loop in the file <code>index.php</code> and I solved using the <a href=\"https://codex.wordpress.org/Function_Reference/next_posts_link#Usage_when_querying_the_loop_with_WP_Query\" rel=\"nofollow noreferrer\">documentation</a> <a href=\"https://wordpress.stackexchange.com/users/4884/michael\">@Michael</a> posted in the comment. I'm just converting it to a solved answer. </p>\n\n<pre><code>&lt;?php\n// set the \"paged\" parameter (use 'page' if the query is on a static front page)\n$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n\n$args_blog = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 9,\n 'category__in' =&gt; array( 2, 3 ),\n 'paged' =&gt; $paged\n );\n\n// the query\n$the_query = new WP_Query( $args_blog ); \n?&gt;\n\n&lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt;\n\n&lt;?php\n// the loop\nwhile ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); \n?&gt;\n&lt;?php the_title(); ?&gt;\n&lt;?php endwhile; ?&gt;\n\n&lt;?php\n\n// next_posts_link() usage with max_num_pages\nnext_posts_link( 'Older Entries', $the_query-&gt;max_num_pages );\nprevious_posts_link( 'Newer Entries' );\n?&gt;\n\n&lt;?php \n// clean up after the query and pagination\nwp_reset_postdata(); \n?&gt;\n\n&lt;?php else: ?&gt;\n&lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2018/04/17
[ "https://wordpress.stackexchange.com/questions/301048", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122279/" ]
I've created a custom loop for posts, that works with Bootstrap, in which, I've added pagination - however it doesn't seem to be working. It just shows an empty button... ``` <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { $i = 0; while ($my_query->have_posts()) : $my_query->the_post(); if($i % 2 == 0) { ?> <div class="row"><?php } ?> <div class="col-md-6"> <div class="overview"> <!-- Post details here --> </div> </div> <?php $i++; if($i != 0 && $i % 2 == 0) { ?> </div><!--/.row--> <div class="clearfix"></div> <?php } endwhile; ?> <nav class="pagination"> <button class="btn-whole"><?php previous_posts_link('Previous') ?></button> <button class="btn-whole"><?php next_posts_link('Next') ?></button> </nav> <?php } wp_reset_query(); ?> ``` Any ideas on why this might be happening?
only just use echo and get\_ ``` <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { $i = 0; while ($my_query->have_posts()) : $my_query->the_post(); if($i % 2 == 0) { ?> <div class="row"><?php } ?> <div class="col-md-6"> <div class="overview"> <!-- Post details here --> </div> </div> <?php $i++; if($i != 0 && $i % 2 == 0) { ?> </div><!--/.row--> <div class="clearfix"></div> <?php } endwhile; ?> <nav class="pagination"> <button class="btn-whole"><?php echo get_previous_posts_link('Previous'); ?></button> <button class="btn-whole"><?php echo get_next_posts_link('Next'); ?></button> </nav> <?php } wp_reset_query(); ?> ```
301,051
<p>I am able to filter tags archives by adding a parameter like ?post_type=slug to the url and this works fine except for search results. I mean where the url contains a search term like:</p> <pre><code>site.com/?s=searched&amp;post_type=slug </code></pre> <p>How can i make the "&amp;post_type=slug" also work in this case?</p> <p>EDIT: It wasn't working on my end due to custom function.php code.</p>
[ { "answer_id": 301054, "author": "Aurovrata", "author_id": 52120, "author_profile": "https://wordpress.stackexchange.com/users/52120", "pm_score": 0, "selected": false, "text": "<p>The <code>s=keyword</code> url parameter is by default used to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter\" rel=\"nofollow noreferrer\">search posts that contain that keyword</a>.</p>\n\n<p>To customise this such as the post_type, you need to either:</p>\n\n<ol>\n<li>build a <a href=\"https://codex.wordpress.org/Creating_a_Search_Page\" rel=\"nofollow noreferrer\">custom search page</a>, you can also see this <a href=\"https://wordpress.stackexchange.com/questions/140664/custom-search-query\">answer</a>. This <a href=\"https://stackoverflow.com/questions/14802498/how-to-display-wordpress-search-results\">question</a> also has some good examples.</li>\n<li>Use a <a href=\"http://www.wpbeginner.com/showcase/12-wordpress-search-plugins-to-improve-your-site-search/\" rel=\"nofollow noreferrer\">plugin</a></li>\n</ol>\n" }, { "answer_id": 301077, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>By all rights it should work, here's the same thing applied to my own site:</p>\n\n<p>tomjn.com/?s=talk&amp;post_type=tomjn_talks vs tomjn.com/?s=talk . Something else is the problem</p>\n\n<p>Specifically, if you replace the main query with a <code>query_posts</code> call or a <code>WP_Query</code>, that query won't take into account parameters passed via the URL unless explicitly passed through manually.</p>\n\n<p>Instead, use the <code>pre_get_posts</code> filter to modify the main query, rather than creating a new query to replace it.This ensures any additional queries passed via the URL will also work, and reduces time spent querying the database significantly for a nice performance boost.</p>\n\n<p>Additionally, if you already use <code>pre_get_posts</code>, setting the <code>post_type</code> will override the URL parameter, so you need to check for its existence</p>\n" } ]
2018/04/17
[ "https://wordpress.stackexchange.com/questions/301051", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
I am able to filter tags archives by adding a parameter like ?post\_type=slug to the url and this works fine except for search results. I mean where the url contains a search term like: ``` site.com/?s=searched&post_type=slug ``` How can i make the "&post\_type=slug" also work in this case? EDIT: It wasn't working on my end due to custom function.php code.
By all rights it should work, here's the same thing applied to my own site: tomjn.com/?s=talk&post\_type=tomjn\_talks vs tomjn.com/?s=talk . Something else is the problem Specifically, if you replace the main query with a `query_posts` call or a `WP_Query`, that query won't take into account parameters passed via the URL unless explicitly passed through manually. Instead, use the `pre_get_posts` filter to modify the main query, rather than creating a new query to replace it.This ensures any additional queries passed via the URL will also work, and reduces time spent querying the database significantly for a nice performance boost. Additionally, if you already use `pre_get_posts`, setting the `post_type` will override the URL parameter, so you need to check for its existence
301,056
<p>I want to create a helper redirect function that looks like the following:</p> <pre><code>/** * Just an example of using redirect() */ public function validate_something() { if (1 == 0) { $this-&gt;redirect('register'); } } </code></pre> <p>However, on <code>public function redirect()</code>, I would like to use some functions that are only available after WordPress core has loaded, such as <code>get_site_url()</code>.</p> <p>With that in mind, I created a sort of intermediate function, that looks like the following:</p> <pre><code>/** * Receives a redirect request and passes it to an add_action */ public function redirect($to) { $this-&gt;to = $to; add_action( 'init', [$this, 'redirect_wp'], 10, 1 ); } /** * Processes an redirect request */ public function redirect_wp() { header('Location: '.get_site_url().'/'.$this-&gt;to); exit; } </code></pre> <p>However, <code>redirect_wp()</code> is never called. Moreover, I feel like I'm doing something architecturally wrong, but I don't know exactly what.</p> <p>Please, take into account that these redirect methods are much more complex in live code, passing for example error messages and old inputs through sessions. The code above is just an example of the strucutre.</p>
[ { "answer_id": 301057, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": -1, "selected": false, "text": "<p>Add actions/filters in constructor method.</p>\n\n<pre><code>public function __construct(){\n add_action('init', [ $this, 'real_constructor_goes_here' ]);\n}\n</code></pre>\n" }, { "answer_id": 301063, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The core problem is that you are not writing OOP. OOP is about identifying objects in your system, not actions. If you want to identify actions than you are better to follow functional design paradigms (and with wordpress hook system, functional design make much more sense).</p>\n\n<p>In your case redirect is an action, that probably follows an object state transition, therefor it should not be an external API of the class.</p>\n\n<p>Of course the object in this case can be a \"redirect controller\", or better a \"browser\" object but for most people that will be one abstraction level too much.</p>\n\n<blockquote>\n <p>Please, take into account that these redirect methods are much more complex in live code, passing for example error messages and old inputs through sessions</p>\n</blockquote>\n\n<p>So this is a case where you have a complex decision tree, but it doesn't sound like you have any object state transition, therefor it is not actually something that should be part of an object, at least not more than a utility function.</p>\n" } ]
2018/04/17
[ "https://wordpress.stackexchange.com/questions/301056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27278/" ]
I want to create a helper redirect function that looks like the following: ``` /** * Just an example of using redirect() */ public function validate_something() { if (1 == 0) { $this->redirect('register'); } } ``` However, on `public function redirect()`, I would like to use some functions that are only available after WordPress core has loaded, such as `get_site_url()`. With that in mind, I created a sort of intermediate function, that looks like the following: ``` /** * Receives a redirect request and passes it to an add_action */ public function redirect($to) { $this->to = $to; add_action( 'init', [$this, 'redirect_wp'], 10, 1 ); } /** * Processes an redirect request */ public function redirect_wp() { header('Location: '.get_site_url().'/'.$this->to); exit; } ``` However, `redirect_wp()` is never called. Moreover, I feel like I'm doing something architecturally wrong, but I don't know exactly what. Please, take into account that these redirect methods are much more complex in live code, passing for example error messages and old inputs through sessions. The code above is just an example of the strucutre.
The core problem is that you are not writing OOP. OOP is about identifying objects in your system, not actions. If you want to identify actions than you are better to follow functional design paradigms (and with wordpress hook system, functional design make much more sense). In your case redirect is an action, that probably follows an object state transition, therefor it should not be an external API of the class. Of course the object in this case can be a "redirect controller", or better a "browser" object but for most people that will be one abstraction level too much. > > Please, take into account that these redirect methods are much more complex in live code, passing for example error messages and old inputs through sessions > > > So this is a case where you have a complex decision tree, but it doesn't sound like you have any object state transition, therefor it is not actually something that should be part of an object, at least not more than a utility function.
301,067
<p><strong>What I tested</strong></p> <p><strong>Wordpress Version</strong>: 4.9.5</p> <p><strong>PHP Version</strong>: 7.1.7/7.1.4/7.2.0/7.0.3/5.6.20/5.5.38/5.4.45</p> <p><strong>Web Server</strong>: Nginx 1.10.1/Apache 2.4.10</p> <p><strong>Environment/Host</strong>: Flywheel local <a href="https://local.getflywheel.com/" rel="nofollow noreferrer">https://local.getflywheel.com/</a></p> <p><strong>PCRE Library Version</strong>: 8.38 2015-11-23</p> <p>I have been trying to work with <code>register_rest_route</code> but running into regex issues. It seems that there is some filtering on the regex before its executed.</p> <p>The function I am trying to create is grabbing a post by the permalink. Basically I have a client that is structuring its url's similar to wordpress so it wants to pass the permalink to wordpress so I can get the post data</p> <pre><code>register_rest_route( $this-&gt;namespace, '/post_by_permalink/(?P&lt;path&gt;[\w-]+)', array( 'methods' =&gt; WP_REST_Server::READABLE, 'callback' =&gt; array( $this, 'postByPermalink' ), 'permission_callback' =&gt; array( $this, 'permissions' ), 'show_in_rest' =&gt; true )); </code></pre> <p>This is the function I am using and it works in some cases. However that is only because the ones that work do not produce any special characters.</p> <p>Right now my plan was in the client to convert the permalink to base64 to make it easier to pass through the url, though I am open to suggestions if they work (I only thought of base64 since urlencode was even more of a nightmare).</p> <p>Basically the only regex that work in wordpress seems to be <code>(?P&lt;path&gt;[\w-]+)</code> and <code>(?P&lt;path&gt;[\d]+)</code>. Anything else, does not work, even if it was successful testing it in something like <a href="http://www.phpliveregex.com" rel="nofollow noreferrer">http://www.phpliveregex.com</a></p> <p>For instance, according to the tester <code>(?P&lt;path&gt;[\S]+)</code> should work, but all I get from wordpress is <code>rest_no_route</code></p> <p>Is there anyway to get wordpress to handle regex normally? Or at least tell it to allow an expression that could catch base64? I have seen some options online, but none work, likely due to changes in wp rest over time (all say "just use regex", yet it seems to filter more complex regex)</p> <p><strong><em>EDIT: extending example</em></strong></p> <p><code>app/v1/post_by_permalink/(?P&lt;path&gt;[\S-]+)</code></p> <p>Is what will work in <a href="http://www.phpliveregex.com" rel="nofollow noreferrer">http://www.phpliveregex.com</a></p> <p>The search string being</p> <p><code>/wp-json/app/v1/post_by_permalink/dGVzdC90ZXN0</code></p> <p>That same regex will not work in wordpress, only <code>(?P&lt;path&gt;[\w-]+)</code> will work, and for the the above example, it will work as well in both since there are no special characters.</p> <p>However for this string it will not</p> <p><code>/wp-json/app/v1/post_by_permalink/dGVzdC90ZXN0LzM1NzM0Ly0=</code></p> <p>Since it has an <code>=</code> So although in the regex tester <code>(?P&lt;path&gt;[\S]+)</code> works, it will not work in wordpress.</p> <p><strong><em>Edit: further testing</em></strong></p> <p>I managed to look up <code>rest_pre_dispatch</code> and get it working to catch the request before it checks the routes.</p> <pre><code>add_filter('rest_pre_dispatch', 'filter_request'); function filter_request($result) { global $wp; //print_r($wp-&gt;request); die; preg_match("/app\/v1\/post_by_permalink\/(?P&lt;path&gt;[\S]+)/", $wp-&gt;request, $output); print_r($output); die; return $result; } </code></pre> <p>Is able to set the path correctly, so it does not seem to be a preg_match problem. At least with this I can bypass wp-rest and get around this issue, but I still have not found what is actually causing every environment I try this in to fail, and yet no one else can recreate it.....</p> <p><em>After testing more thoroughly I got the below to work, I was using <code>$wp-&gt;request</code> witch included <code>wp-json</code> that was causing the regex to fail.</em></p> <p>Though when I use <code>preg_match( '@^' . $route . '$@i', $path, $matches )</code> I cannot get it to work (that is how wp-rest does it, $route being what is passed through <code>register_rest_route</code>), and using <code>preg_match</code> in this way is not supported in the regex tester <a href="http://www.phpliveregex.com/" rel="nofollow noreferrer">http://www.phpliveregex.com/</a> either. It adds more questions then answers.</p>
[ { "answer_id": 301076, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>I got curious, so I tested this barebone demo:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'wpse/v1', '/post_by_permalink/(?P&lt;path&gt;[\\S]+)', [\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; 'wpse_callback',\n 'show_in_rest' =&gt; true\n ] );\n});\n\nfunction wpse_callback( $request ) {\n $data = [ 'path' =&gt; base64_decode( $request['path'] ) ];\n return $data;\n}\n</code></pre>\n\n<p>Testing: </p>\n\n<p><a href=\"https://example.com/wp-json/wpse/v1/post_by_permalink/aHR0cHM6Ly93b3JkcHJlc3Muc3RhY2tleGNoYW5nZS5jb20vcS8zMDEwNjcv\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wpse/v1/post_by_permalink/aHR0cHM6Ly93b3JkcHJlc3Muc3RhY2tleGNoYW5nZS5jb20vcS8zMDEwNjcv</a></p>\n\n<p>gives</p>\n\n<pre><code>{\n path: \"https://wordpress.stackexchange.com/q/301067/\"\n}\n</code></pre>\n\n<p>Tested also </p>\n\n<p><a href=\"https://example.com/wp-json/wpse/v1/post_by_permalink/aHR0cHM6Ly93b3JkcHJlc3Muc3RhY2tleGNoYW5nZS5jb20vcXVlc3Rpb25zLzMwMTA2Ny9yZWdpc3Rlci1yZXN0LXJvdXRlLXJlZ2V4LW9wdGlvbi1mb3ItYmFzZTY0LW9yLWFsdGVybmF0ZS8zMDEwNzY=\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wpse/v1/post_by_permalink/aHR0cHM6Ly93b3JkcHJlc3Muc3RhY2tleGNoYW5nZS5jb20vcXVlc3Rpb25zLzMwMTA2Ny9yZWdpc3Rlci1yZXN0LXJvdXRlLXJlZ2V4LW9wdGlvbi1mb3ItYmFzZTY0LW9yLWFsdGVybmF0ZS8zMDEwNzY=</a></p>\n\n<p>that gave:</p>\n\n<pre><code>{\npath: \"https://wordpress.stackexchange.com/questions/301067/register-rest-route-regex-option-for-base64-or-alternate/301076\"\n}\n</code></pre>\n\n<p>Tested further:</p>\n\n<p><a href=\"https://example.com/wp-json/wpse/v1/post_by_permalink/dGVzdC90ZXN0LzM1NzM0Ly0=\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wpse/v1/post_by_permalink/dGVzdC90ZXN0LzM1NzM0Ly0=</a></p>\n\n<p>with output:</p>\n\n<pre><code>{\npath: \"test/test/35734/-\"\n}\n</code></pre>\n" }, { "answer_id": 301094, "author": "Jordan Ramstad", "author_id": 63445, "author_profile": "https://wordpress.stackexchange.com/users/63445", "pm_score": 1, "selected": false, "text": "<p>Finally figured it out, and I can only blame myself....</p>\n\n<p>When I was testing, I had disabled all plugins, but during that time I had left it using <code>(?P&lt;path&gt;[\\w-]+)</code> while testing with a base64 string that contained an <code>=</code>. The whole time I had eliminated plugins as an issue thinking I had recreated it despite having no plugins active.</p>\n\n<p>The culprit was <code>Rest Manager</code> <a href=\"https://wordpress.org/plugins/rest-manager/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/rest-manager/</a></p>\n\n<p>I have opened a support ticket to let the developer know.</p>\n\n<p>It utilizes <code>rest_pre_dispatch</code> to filter out routes you set as inactive, problem is if you change routes you need to go in and resave the configuration. Thankfully it was repairable since it has a hook before it filters out the routes, so I could \"fix\" the function and assume routes that had no configurations should default to active.</p>\n\n<p>Thank you to @mmm, @birire and @Otto for taking the time to try to recreate the issue.</p>\n\n<p>Disable plugins when trying to isolate an issue kids ;-)</p>\n" } ]
2018/04/17
[ "https://wordpress.stackexchange.com/questions/301067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63445/" ]
**What I tested** **Wordpress Version**: 4.9.5 **PHP Version**: 7.1.7/7.1.4/7.2.0/7.0.3/5.6.20/5.5.38/5.4.45 **Web Server**: Nginx 1.10.1/Apache 2.4.10 **Environment/Host**: Flywheel local <https://local.getflywheel.com/> **PCRE Library Version**: 8.38 2015-11-23 I have been trying to work with `register_rest_route` but running into regex issues. It seems that there is some filtering on the regex before its executed. The function I am trying to create is grabbing a post by the permalink. Basically I have a client that is structuring its url's similar to wordpress so it wants to pass the permalink to wordpress so I can get the post data ``` register_rest_route( $this->namespace, '/post_by_permalink/(?P<path>[\w-]+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'postByPermalink' ), 'permission_callback' => array( $this, 'permissions' ), 'show_in_rest' => true )); ``` This is the function I am using and it works in some cases. However that is only because the ones that work do not produce any special characters. Right now my plan was in the client to convert the permalink to base64 to make it easier to pass through the url, though I am open to suggestions if they work (I only thought of base64 since urlencode was even more of a nightmare). Basically the only regex that work in wordpress seems to be `(?P<path>[\w-]+)` and `(?P<path>[\d]+)`. Anything else, does not work, even if it was successful testing it in something like <http://www.phpliveregex.com> For instance, according to the tester `(?P<path>[\S]+)` should work, but all I get from wordpress is `rest_no_route` Is there anyway to get wordpress to handle regex normally? Or at least tell it to allow an expression that could catch base64? I have seen some options online, but none work, likely due to changes in wp rest over time (all say "just use regex", yet it seems to filter more complex regex) ***EDIT: extending example*** `app/v1/post_by_permalink/(?P<path>[\S-]+)` Is what will work in <http://www.phpliveregex.com> The search string being `/wp-json/app/v1/post_by_permalink/dGVzdC90ZXN0` That same regex will not work in wordpress, only `(?P<path>[\w-]+)` will work, and for the the above example, it will work as well in both since there are no special characters. However for this string it will not `/wp-json/app/v1/post_by_permalink/dGVzdC90ZXN0LzM1NzM0Ly0=` Since it has an `=` So although in the regex tester `(?P<path>[\S]+)` works, it will not work in wordpress. ***Edit: further testing*** I managed to look up `rest_pre_dispatch` and get it working to catch the request before it checks the routes. ``` add_filter('rest_pre_dispatch', 'filter_request'); function filter_request($result) { global $wp; //print_r($wp->request); die; preg_match("/app\/v1\/post_by_permalink\/(?P<path>[\S]+)/", $wp->request, $output); print_r($output); die; return $result; } ``` Is able to set the path correctly, so it does not seem to be a preg\_match problem. At least with this I can bypass wp-rest and get around this issue, but I still have not found what is actually causing every environment I try this in to fail, and yet no one else can recreate it..... *After testing more thoroughly I got the below to work, I was using `$wp->request` witch included `wp-json` that was causing the regex to fail.* Though when I use `preg_match( '@^' . $route . '$@i', $path, $matches )` I cannot get it to work (that is how wp-rest does it, $route being what is passed through `register_rest_route`), and using `preg_match` in this way is not supported in the regex tester <http://www.phpliveregex.com/> either. It adds more questions then answers.
I got curious, so I tested this barebone demo: ``` add_action( 'rest_api_init', function () { register_rest_route( 'wpse/v1', '/post_by_permalink/(?P<path>[\S]+)', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'wpse_callback', 'show_in_rest' => true ] ); }); function wpse_callback( $request ) { $data = [ 'path' => base64_decode( $request['path'] ) ]; return $data; } ``` Testing: <https://example.com/wp-json/wpse/v1/post_by_permalink/aHR0cHM6Ly93b3JkcHJlc3Muc3RhY2tleGNoYW5nZS5jb20vcS8zMDEwNjcv> gives ``` { path: "https://wordpress.stackexchange.com/q/301067/" } ``` Tested also <https://example.com/wp-json/wpse/v1/post_by_permalink/aHR0cHM6Ly93b3JkcHJlc3Muc3RhY2tleGNoYW5nZS5jb20vcXVlc3Rpb25zLzMwMTA2Ny9yZWdpc3Rlci1yZXN0LXJvdXRlLXJlZ2V4LW9wdGlvbi1mb3ItYmFzZTY0LW9yLWFsdGVybmF0ZS8zMDEwNzY=> that gave: ``` { path: "https://wordpress.stackexchange.com/questions/301067/register-rest-route-regex-option-for-base64-or-alternate/301076" } ``` Tested further: <https://example.com/wp-json/wpse/v1/post_by_permalink/dGVzdC90ZXN0LzM1NzM0Ly0=> with output: ``` { path: "test/test/35734/-" } ```
301,152
<p>I've got an archive page for to display custom post types. </p> <p>Within the WP_Query that displays the custom posts types I want to display an ACF (Advanced Custom Field) or, if the user hasn't filled out the ACF, then the title should appear.</p> <p>I've tried this and the ACF field displays ok, but when it's not filled out, the title doesn't display, just the content of the post instead.</p> <p>Here's the code I have (just for the title section):</p> <pre><code>&lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'project', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'menu_order' ) ); ?&gt; &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;div class="project col-md-4"&gt; &lt;div class="col-xs-12 short-testimonial"&gt; &lt;?php if(get_field('short_testimonial')): ?&gt; &lt;?php the_field('short_testimonial'); ?&gt; &lt;?php else: ?&gt; &lt;?php echo the_title(); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 301153, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 0, "selected": false, "text": "<p>If in doubt, check the documentation first: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n\n<p><strong>Check if value exists</strong></p>\n\n<p>This example shows how to check if a value exists for a field.</p>\n\n<pre><code>$value = get_field( 'text_field' );\n\nif ( $value ) {\n echo $value;\n} else {\n echo 'empty';\n}\n</code></pre>\n\n<p>So, in for your case you would need to use:</p>\n\n<pre><code>&lt;?php\n\n$short_testimonial = get_field( 'short_testimonial' );\n\nif ( $short_testimonial ) {\n echo $short_testimonial;\n} else {\n the_title();\n}\n\n?&gt;\n</code></pre>\n\n<p>Also, you should note, as others have mentioned, that you don't need to echo <code>the_title()</code> as it echoes itself...</p>\n" }, { "answer_id": 301154, "author": "danrodrigues", "author_id": 135610, "author_profile": "https://wordpress.stackexchange.com/users/135610", "pm_score": -1, "selected": false, "text": "<p>You should try removing \"echo\" from \"the_title()\". </p>\n\n<p>This should work</p>\n\n<pre><code>&lt;div class=\"project col-md-4\"&gt;\n &lt;div class=\"col-xs-12 short-testimonial\"&gt;\n &lt;?php \n if( get_field( 'short_testimonial' ) ): \n the_field( 'short_testimonial' );\n else:\n the_title();\n endif;\n ?&gt; \n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You could also look at the official documentation <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You will notice that <em>the_title</em> already <strong>displays it by default</strong>.</p>\n\n<pre><code>&lt;?php the_title( $before, $after, $echo ); ?&gt;\n</code></pre>\n" } ]
2018/04/18
[ "https://wordpress.stackexchange.com/questions/301152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76109/" ]
I've got an archive page for to display custom post types. Within the WP\_Query that displays the custom posts types I want to display an ACF (Advanced Custom Field) or, if the user hasn't filled out the ACF, then the title should appear. I've tried this and the ACF field displays ok, but when it's not filled out, the title doesn't display, just the content of the post instead. Here's the code I have (just for the title section): ``` <?php $loop = new WP_Query( array( 'post_type' => 'project', 'posts_per_page' => -1, 'orderby' => 'menu_order' ) ); ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="project col-md-4"> <div class="col-xs-12 short-testimonial"> <?php if(get_field('short_testimonial')): ?> <?php the_field('short_testimonial'); ?> <?php else: ?> <?php echo the_title(); ?> <?php endif; ?> </div> ```
If in doubt, check the documentation first: <https://www.advancedcustomfields.com/resources/get_field/> **Check if value exists** This example shows how to check if a value exists for a field. ``` $value = get_field( 'text_field' ); if ( $value ) { echo $value; } else { echo 'empty'; } ``` So, in for your case you would need to use: ``` <?php $short_testimonial = get_field( 'short_testimonial' ); if ( $short_testimonial ) { echo $short_testimonial; } else { the_title(); } ?> ``` Also, you should note, as others have mentioned, that you don't need to echo `the_title()` as it echoes itself...
301,172
<p>My Wordpress website is often going down with the error message "error establishing a database connection" and when I contacted my hosting server, they replied that the query takes a long time(more than 25 sec) and killed the database connection. So that they asked to optimize the wp_option table. Kindly guide me to optimize wp_option table and improve the site performance.</p> <pre><code> Killed queries for the database(s):- ---------------------------- vn_wp3 Also, the following error message regarding the database(s):- ------ 2018-04-18 12:34:01 +0000 [info] killed_thread_id:30117883 user:vn_wp3 host:localhost db:vn_wp3 command:Query time:25 query:SELECT option_value FROM wp_options WHERE option_name = '_transient_timeout_srcmnt_notices' LIMIT 1 2018-04-18 12:34:11 +0000 [info] killed_thread_id:30118047 user:vn_wp3 host:localhost db:vn_wp3 command:Query time:25 query:SELECT option_value FROM wp_options WHERE option_name = '_transient_timeout_srcmnt_notices' LIMIT 1 ------ ------ </code></pre> <p>I checked the wp_option table size, it's around 21 MB.</p>
[ { "answer_id": 301153, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 0, "selected": false, "text": "<p>If in doubt, check the documentation first: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n\n<p><strong>Check if value exists</strong></p>\n\n<p>This example shows how to check if a value exists for a field.</p>\n\n<pre><code>$value = get_field( 'text_field' );\n\nif ( $value ) {\n echo $value;\n} else {\n echo 'empty';\n}\n</code></pre>\n\n<p>So, in for your case you would need to use:</p>\n\n<pre><code>&lt;?php\n\n$short_testimonial = get_field( 'short_testimonial' );\n\nif ( $short_testimonial ) {\n echo $short_testimonial;\n} else {\n the_title();\n}\n\n?&gt;\n</code></pre>\n\n<p>Also, you should note, as others have mentioned, that you don't need to echo <code>the_title()</code> as it echoes itself...</p>\n" }, { "answer_id": 301154, "author": "danrodrigues", "author_id": 135610, "author_profile": "https://wordpress.stackexchange.com/users/135610", "pm_score": -1, "selected": false, "text": "<p>You should try removing \"echo\" from \"the_title()\". </p>\n\n<p>This should work</p>\n\n<pre><code>&lt;div class=\"project col-md-4\"&gt;\n &lt;div class=\"col-xs-12 short-testimonial\"&gt;\n &lt;?php \n if( get_field( 'short_testimonial' ) ): \n the_field( 'short_testimonial' );\n else:\n the_title();\n endif;\n ?&gt; \n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You could also look at the official documentation <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You will notice that <em>the_title</em> already <strong>displays it by default</strong>.</p>\n\n<pre><code>&lt;?php the_title( $before, $after, $echo ); ?&gt;\n</code></pre>\n" } ]
2018/04/18
[ "https://wordpress.stackexchange.com/questions/301172", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119805/" ]
My Wordpress website is often going down with the error message "error establishing a database connection" and when I contacted my hosting server, they replied that the query takes a long time(more than 25 sec) and killed the database connection. So that they asked to optimize the wp\_option table. Kindly guide me to optimize wp\_option table and improve the site performance. ``` Killed queries for the database(s):- ---------------------------- vn_wp3 Also, the following error message regarding the database(s):- ------ 2018-04-18 12:34:01 +0000 [info] killed_thread_id:30117883 user:vn_wp3 host:localhost db:vn_wp3 command:Query time:25 query:SELECT option_value FROM wp_options WHERE option_name = '_transient_timeout_srcmnt_notices' LIMIT 1 2018-04-18 12:34:11 +0000 [info] killed_thread_id:30118047 user:vn_wp3 host:localhost db:vn_wp3 command:Query time:25 query:SELECT option_value FROM wp_options WHERE option_name = '_transient_timeout_srcmnt_notices' LIMIT 1 ------ ------ ``` I checked the wp\_option table size, it's around 21 MB.
If in doubt, check the documentation first: <https://www.advancedcustomfields.com/resources/get_field/> **Check if value exists** This example shows how to check if a value exists for a field. ``` $value = get_field( 'text_field' ); if ( $value ) { echo $value; } else { echo 'empty'; } ``` So, in for your case you would need to use: ``` <?php $short_testimonial = get_field( 'short_testimonial' ); if ( $short_testimonial ) { echo $short_testimonial; } else { the_title(); } ?> ``` Also, you should note, as others have mentioned, that you don't need to echo `the_title()` as it echoes itself...
301,176
<p>I was wondering if you can change "the type" of a wordpress custom post type. So: when I create a custom post type to somehow remove the post list:<img src="https://i.stack.imgur.com/3Bipq.jpg" alt="enter image description here"> and jump directly to the edit page...</p> <p>I am trying to do this because I got a section on my page where arent any posts. Only one section whose content changes...<img src="https://i.stack.imgur.com/gVClp.jpg" alt="enter image description here"></p>
[ { "answer_id": 301153, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 0, "selected": false, "text": "<p>If in doubt, check the documentation first: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n\n<p><strong>Check if value exists</strong></p>\n\n<p>This example shows how to check if a value exists for a field.</p>\n\n<pre><code>$value = get_field( 'text_field' );\n\nif ( $value ) {\n echo $value;\n} else {\n echo 'empty';\n}\n</code></pre>\n\n<p>So, in for your case you would need to use:</p>\n\n<pre><code>&lt;?php\n\n$short_testimonial = get_field( 'short_testimonial' );\n\nif ( $short_testimonial ) {\n echo $short_testimonial;\n} else {\n the_title();\n}\n\n?&gt;\n</code></pre>\n\n<p>Also, you should note, as others have mentioned, that you don't need to echo <code>the_title()</code> as it echoes itself...</p>\n" }, { "answer_id": 301154, "author": "danrodrigues", "author_id": 135610, "author_profile": "https://wordpress.stackexchange.com/users/135610", "pm_score": -1, "selected": false, "text": "<p>You should try removing \"echo\" from \"the_title()\". </p>\n\n<p>This should work</p>\n\n<pre><code>&lt;div class=\"project col-md-4\"&gt;\n &lt;div class=\"col-xs-12 short-testimonial\"&gt;\n &lt;?php \n if( get_field( 'short_testimonial' ) ): \n the_field( 'short_testimonial' );\n else:\n the_title();\n endif;\n ?&gt; \n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You could also look at the official documentation <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You will notice that <em>the_title</em> already <strong>displays it by default</strong>.</p>\n\n<pre><code>&lt;?php the_title( $before, $after, $echo ); ?&gt;\n</code></pre>\n" } ]
2018/04/18
[ "https://wordpress.stackexchange.com/questions/301176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141857/" ]
I was wondering if you can change "the type" of a wordpress custom post type. So: when I create a custom post type to somehow remove the post list:![enter image description here](https://i.stack.imgur.com/3Bipq.jpg) and jump directly to the edit page... I am trying to do this because I got a section on my page where arent any posts. Only one section whose content changes...![enter image description here](https://i.stack.imgur.com/gVClp.jpg)
If in doubt, check the documentation first: <https://www.advancedcustomfields.com/resources/get_field/> **Check if value exists** This example shows how to check if a value exists for a field. ``` $value = get_field( 'text_field' ); if ( $value ) { echo $value; } else { echo 'empty'; } ``` So, in for your case you would need to use: ``` <?php $short_testimonial = get_field( 'short_testimonial' ); if ( $short_testimonial ) { echo $short_testimonial; } else { the_title(); } ?> ``` Also, you should note, as others have mentioned, that you don't need to echo `the_title()` as it echoes itself...
301,183
<p>I need for a specific plugin to override the wordpress function <code>get_avatar()</code> to bind the profile image to an other image with some condition.</p> <p>How can I do this ? Is there a specific hook or filter to do this ?</p>
[ { "answer_id": 301153, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 0, "selected": false, "text": "<p>If in doubt, check the documentation first: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n\n<p><strong>Check if value exists</strong></p>\n\n<p>This example shows how to check if a value exists for a field.</p>\n\n<pre><code>$value = get_field( 'text_field' );\n\nif ( $value ) {\n echo $value;\n} else {\n echo 'empty';\n}\n</code></pre>\n\n<p>So, in for your case you would need to use:</p>\n\n<pre><code>&lt;?php\n\n$short_testimonial = get_field( 'short_testimonial' );\n\nif ( $short_testimonial ) {\n echo $short_testimonial;\n} else {\n the_title();\n}\n\n?&gt;\n</code></pre>\n\n<p>Also, you should note, as others have mentioned, that you don't need to echo <code>the_title()</code> as it echoes itself...</p>\n" }, { "answer_id": 301154, "author": "danrodrigues", "author_id": 135610, "author_profile": "https://wordpress.stackexchange.com/users/135610", "pm_score": -1, "selected": false, "text": "<p>You should try removing \"echo\" from \"the_title()\". </p>\n\n<p>This should work</p>\n\n<pre><code>&lt;div class=\"project col-md-4\"&gt;\n &lt;div class=\"col-xs-12 short-testimonial\"&gt;\n &lt;?php \n if( get_field( 'short_testimonial' ) ): \n the_field( 'short_testimonial' );\n else:\n the_title();\n endif;\n ?&gt; \n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You could also look at the official documentation <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You will notice that <em>the_title</em> already <strong>displays it by default</strong>.</p>\n\n<pre><code>&lt;?php the_title( $before, $after, $echo ); ?&gt;\n</code></pre>\n" } ]
2018/04/18
[ "https://wordpress.stackexchange.com/questions/301183", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I need for a specific plugin to override the wordpress function `get_avatar()` to bind the profile image to an other image with some condition. How can I do this ? Is there a specific hook or filter to do this ?
If in doubt, check the documentation first: <https://www.advancedcustomfields.com/resources/get_field/> **Check if value exists** This example shows how to check if a value exists for a field. ``` $value = get_field( 'text_field' ); if ( $value ) { echo $value; } else { echo 'empty'; } ``` So, in for your case you would need to use: ``` <?php $short_testimonial = get_field( 'short_testimonial' ); if ( $short_testimonial ) { echo $short_testimonial; } else { the_title(); } ?> ``` Also, you should note, as others have mentioned, that you don't need to echo `the_title()` as it echoes itself...
301,188
<p>I am trying to create a function which either deletes all the postmeta with the meta_key "bakground-video", or edits the meta_value to empty it from the values. There might be multiple postmeta with the meta_key "background-video" and I want the function to run on all of them.</p> <p>I will use this function on a multisite when a user changes role to "basic" this will fire and delete or edit all the postmetas with the key. How would I make this happen? All of the functions I can find when searching requires me to know the post_id, which I don't know.</p> <p>This is what I have come up with after some searching, but I can't make it work!</p> <pre><code> $args = array( 'fields' =&gt; 'ids', 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'attachment', 'meta_key' =&gt; 'background-video' ); $all_ids = new WP_Query( $args ); foreach( $all_ids as $ai ) { update_post_meta( $ai-&gt;post-&gt;ID, 'background-video', '' ); } wp_reset_postdata(); </code></pre> <p>This is inserted in a function which fires when a user changes role to a role called "basic".</p> <p>EDIT: Together with user role change function:</p> <pre><code>add_action( 'set_user_role', function( $user_id, $role, $old_roles ) { if ( 'basic' == $role ) { $args = array( 'fields' =&gt; 'ids', 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'attachment', 'meta_key' =&gt; 'background-video' ); $all_ids = new WP_Query( $args ); if ( $all_ids-&gt;have_posts() ) { while ( $all_ids-&gt;have_posts() ) { $all_ids-&gt;the_post(); update_post_meta( $p-&gt;ID, 'background-video', '' ); } } wp_reset_postdata(); } }, 10, 3 ); </code></pre>
[ { "answer_id": 301192, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": true, "text": "<p>Untested, but this might be what you're looking for:</p>\n\n<pre><code>$args = array( 'fields' =&gt; 'ids',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'attachment',\n 'meta_key' =&gt; 'background-video'\n );\n$all_ids = new WP_Query( $args );\nif ( $all_ids-&gt;have_posts() ) {\n while ( $all_ids-&gt;have_posts() ) {\n $all_ids-&gt;the_post();\n update_post_meta( get_the_ID(), 'background-video', '' );\n }\n}\nwp_reset_postdata();\n</code></pre>\n\n<h2>References</h2>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/classes/wp_query/#standard-loop\" rel=\"nofollow noreferrer\"><code>WP_Query</code> » Usage » Standard Loop</a></li>\n</ul>\n" }, { "answer_id": 301206, "author": "jockebq", "author_id": 138051, "author_profile": "https://wordpress.stackexchange.com/users/138051", "pm_score": 1, "selected": false, "text": "<p>Finally solved it, I think the issue was that I hade the wrong post_type. Now it works fantastically!</p>\n\n<p>Thanks a lot for all the help!</p>\n\n<pre><code>add_action( 'set_user_role', function( $user_id, $role, $old_roles )\n{\n if ( 'basic' == $role ) {\n $args = array( 'fields' =&gt; 'ids',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'slide',\n 'meta_key' =&gt; 'background-video'\n );\n $all_ids = new WP_Query( $args );\n if ( $all_ids-&gt;have_posts() ) {\n while ( $all_ids-&gt;have_posts() ) {\n $all_ids-&gt;the_post();\n update_post_meta( get_the_ID(), 'background-video', '' );\n }\n }\n wp_reset_postdata();\n }\n\n}, 10, 3 );\n</code></pre>\n" } ]
2018/04/18
[ "https://wordpress.stackexchange.com/questions/301188", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138051/" ]
I am trying to create a function which either deletes all the postmeta with the meta\_key "bakground-video", or edits the meta\_value to empty it from the values. There might be multiple postmeta with the meta\_key "background-video" and I want the function to run on all of them. I will use this function on a multisite when a user changes role to "basic" this will fire and delete or edit all the postmetas with the key. How would I make this happen? All of the functions I can find when searching requires me to know the post\_id, which I don't know. This is what I have come up with after some searching, but I can't make it work! ``` $args = array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => 'attachment', 'meta_key' => 'background-video' ); $all_ids = new WP_Query( $args ); foreach( $all_ids as $ai ) { update_post_meta( $ai->post->ID, 'background-video', '' ); } wp_reset_postdata(); ``` This is inserted in a function which fires when a user changes role to a role called "basic". EDIT: Together with user role change function: ``` add_action( 'set_user_role', function( $user_id, $role, $old_roles ) { if ( 'basic' == $role ) { $args = array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => 'attachment', 'meta_key' => 'background-video' ); $all_ids = new WP_Query( $args ); if ( $all_ids->have_posts() ) { while ( $all_ids->have_posts() ) { $all_ids->the_post(); update_post_meta( $p->ID, 'background-video', '' ); } } wp_reset_postdata(); } }, 10, 3 ); ```
Untested, but this might be what you're looking for: ``` $args = array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => 'attachment', 'meta_key' => 'background-video' ); $all_ids = new WP_Query( $args ); if ( $all_ids->have_posts() ) { while ( $all_ids->have_posts() ) { $all_ids->the_post(); update_post_meta( get_the_ID(), 'background-video', '' ); } } wp_reset_postdata(); ``` References ---------- * [`WP_Query` » Usage » Standard Loop](https://developer.wordpress.org/reference/classes/wp_query/#standard-loop)
301,190
<p>I want a function to check if the comment id has children (replies) or not.</p>
[ { "answer_id": 301195, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Here's one example how to construct such a custom function:</p>\n\n<pre><code>/**\n * Check if a comment has children.\n *\n * @param int $comment_id Comment ID\n * @return bool Has comment children.\n */\nfunction has_comment_children_wpse( $comment_id ) {\n return get_comments( [ 'parent' =&gt; $comment_id, 'count' =&gt; true ] ) &gt; 0;\n}\n</code></pre>\n\n<p>using the <code>get_comments()</code> function with the <code>count</code> attribute (to return the number of comments) and the <code>parent</code> attribute to find the children.</p>\n" }, { "answer_id": 356389, "author": "scmccarthy22", "author_id": 181005, "author_profile": "https://wordpress.stackexchange.com/users/181005", "pm_score": 0, "selected": false, "text": "<p>Here's another method in case you want to check if a comment has replies (children) within a get_comments() query. (You would likely not want to use birgire's method inside of a get_comments() query since you would be doing a get_comments() query inside of another get_comments() query.</p>\n\n<p>My method is to use the WP_comment_query class's get_children() method:</p>\n\n<pre><code>$args = array(\n'order' =&gt; 'DESC',\n'status' =&gt; 'approve',\n);\n\n$comments = get_comments( $args ); \nforeach ( $comments as $comment ) {\n $content = $comment-&gt;comment_content;\n $comment_children = $comment-&gt;get_children();\n\n if($comment_children){\n //code for comment with children\n } else {\n //code for comment without children \n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 405808, "author": "anonim", "author_id": 222274, "author_profile": "https://wordpress.stackexchange.com/users/222274", "pm_score": 0, "selected": false, "text": "<p>You can use this</p>\n<pre><code>$child_comments = get_comments(array(\n 'post_id' =&gt; get_the_ID(),\n 'status' =&gt; 'approve',\n 'parent' =&gt; $comment-&gt;comment_ID,\n));\nif($child_comments){}\n</code></pre>\n" } ]
2018/04/18
[ "https://wordpress.stackexchange.com/questions/301190", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138795/" ]
I want a function to check if the comment id has children (replies) or not.
Here's one example how to construct such a custom function: ``` /** * Check if a comment has children. * * @param int $comment_id Comment ID * @return bool Has comment children. */ function has_comment_children_wpse( $comment_id ) { return get_comments( [ 'parent' => $comment_id, 'count' => true ] ) > 0; } ``` using the `get_comments()` function with the `count` attribute (to return the number of comments) and the `parent` attribute to find the children.
301,222
<p>Where could I find a framework for a homepage where I can have an HTML video stretched all the way across (to a certain max resolution would be fine, like max-width: 2500px or something)?</p> <p>I am using a TwentyTwelve theme I customized. All I need is a top header bar for logo and nav (100px tall) and a footer of the same size. The rest of the screen can be the video.</p> <p>This is kind of what I have as a simple base to start. Defining the #page width as something large seems to fill the screen. The rest of the elements inside are set to width: 100% by default so that seems fine too. Just can't seem to make the video stretch and fill the parent div.</p> <p>Thanks!</p> <pre><code>&lt;div id="page" style="width: 2400px; max-width: 2500px;"&gt; &lt;header&gt; &lt;!-- Logo and nav here --&gt; &lt;/header&gt; &lt;div id="main" class="wrapper"&gt; &lt;video id="video_688987199_html5_api" class="vjs-tech" preload="auto" autoplay="" data-setup="{}" src="/wp-content/uploads/2018/04/video.mp4" poster="null"&gt; &lt;source src="/wp-content/uploads/2018/04/video.webm" type="video/webm"&gt; &lt;/video&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 301195, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Here's one example how to construct such a custom function:</p>\n\n<pre><code>/**\n * Check if a comment has children.\n *\n * @param int $comment_id Comment ID\n * @return bool Has comment children.\n */\nfunction has_comment_children_wpse( $comment_id ) {\n return get_comments( [ 'parent' =&gt; $comment_id, 'count' =&gt; true ] ) &gt; 0;\n}\n</code></pre>\n\n<p>using the <code>get_comments()</code> function with the <code>count</code> attribute (to return the number of comments) and the <code>parent</code> attribute to find the children.</p>\n" }, { "answer_id": 356389, "author": "scmccarthy22", "author_id": 181005, "author_profile": "https://wordpress.stackexchange.com/users/181005", "pm_score": 0, "selected": false, "text": "<p>Here's another method in case you want to check if a comment has replies (children) within a get_comments() query. (You would likely not want to use birgire's method inside of a get_comments() query since you would be doing a get_comments() query inside of another get_comments() query.</p>\n\n<p>My method is to use the WP_comment_query class's get_children() method:</p>\n\n<pre><code>$args = array(\n'order' =&gt; 'DESC',\n'status' =&gt; 'approve',\n);\n\n$comments = get_comments( $args ); \nforeach ( $comments as $comment ) {\n $content = $comment-&gt;comment_content;\n $comment_children = $comment-&gt;get_children();\n\n if($comment_children){\n //code for comment with children\n } else {\n //code for comment without children \n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 405808, "author": "anonim", "author_id": 222274, "author_profile": "https://wordpress.stackexchange.com/users/222274", "pm_score": 0, "selected": false, "text": "<p>You can use this</p>\n<pre><code>$child_comments = get_comments(array(\n 'post_id' =&gt; get_the_ID(),\n 'status' =&gt; 'approve',\n 'parent' =&gt; $comment-&gt;comment_ID,\n));\nif($child_comments){}\n</code></pre>\n" } ]
2018/04/19
[ "https://wordpress.stackexchange.com/questions/301222", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31630/" ]
Where could I find a framework for a homepage where I can have an HTML video stretched all the way across (to a certain max resolution would be fine, like max-width: 2500px or something)? I am using a TwentyTwelve theme I customized. All I need is a top header bar for logo and nav (100px tall) and a footer of the same size. The rest of the screen can be the video. This is kind of what I have as a simple base to start. Defining the #page width as something large seems to fill the screen. The rest of the elements inside are set to width: 100% by default so that seems fine too. Just can't seem to make the video stretch and fill the parent div. Thanks! ``` <div id="page" style="width: 2400px; max-width: 2500px;"> <header> <!-- Logo and nav here --> </header> <div id="main" class="wrapper"> <video id="video_688987199_html5_api" class="vjs-tech" preload="auto" autoplay="" data-setup="{}" src="/wp-content/uploads/2018/04/video.mp4" poster="null"> <source src="/wp-content/uploads/2018/04/video.webm" type="video/webm"> </video> </div> </div> ```
Here's one example how to construct such a custom function: ``` /** * Check if a comment has children. * * @param int $comment_id Comment ID * @return bool Has comment children. */ function has_comment_children_wpse( $comment_id ) { return get_comments( [ 'parent' => $comment_id, 'count' => true ] ) > 0; } ``` using the `get_comments()` function with the `count` attribute (to return the number of comments) and the `parent` attribute to find the children.
301,239
<p>[<strong>Edited</strong>]</p> <p>I changed the purpose of my site into an language learning site.</p> <p>Now the CPT is setup as following:</p> <p><strong>{ Language } - { Subject }</strong></p> <ul> <li>English speaking (slug: english-speaking )</li> <li>English writing (english-writing )</li> <li>English reading ( english-speaking )</li> <li>English writing (english-writing)</li> </ul> <hr> <p><strong>Single CPT setup</strong></p> <p>Because each CPT might have different taxonomy… so it is preferred this would be taking into consideration of the code. </p> <p>Say: CPT “English Speaking” has a custom taxonomy of “Speaking Task” (speaking-task) with terms “task-1”, “task-2”, “task-3” … . But: CPT “English Writing” has no taxonomy at all.</p> <p>Desired URL for single CPT post item:</p> <p><strong>With custom taxonomy terms:</strong></p> <ul> <li>www.domain.com/{language}/{subject}/{ term-slug }/{custom-question-id}/{post-name} </li> <li>ex. www.domain.com/english/speaking/speaking-1/32/blah-blah-blah </li> </ul> <p><strong>Without custom taxonomy terms:</strong></p> <ul> <li>www.domain.com/{language}/{subject}/{custom-question-id}/{post-name} </li> <li>ex. www.domain.com/english/writing/32/blah-blah-blah </li> </ul> <p><strong>The URL rewrite part for Single CPT is not a problem for me now thanks to your teaching and genius code provided in the new answer</strong></p> <p>What I am struggling with is the rewrite for the CPT Archive page below:</p> <hr> <p><strong>CPT Archive setup</strong></p> <p>I am trying to create a custom CPT Archive template with the following setup for URL:</p> <ul> <li><p>www.domain.com/ { language } / { subject } ex. www.domain.com/english/speaking </p></li> <li><p>www.domain.com/ { language } / { subject } / { terms-slug }</p></li> <li>ex1. www.domain.com/english/speaking (instead of listing all posts, I wish to make it default to list out to “speaking-1”)</li> <li>ex2. www.domain.com/english/speaking/speaking-1 (only list out post under “speaking-1” )</li> <li>ex3. www.domain.com/english/speaking/speaking-2 (only list out post under “speaking-2” )</li> </ul> <p>———————————————————————————————————</p> <p>In [<strong>archive-english-speaking.php</strong>] , I have the following code: </p> <pre><code>// use add_rewrite_rule in funcitons; query_vars "task" is terms of speaking-task taxonomy global $wp_query; $task_no = $wp_query-&gt;query_vars['task']; if (preg_match("/[1-6]/", $task_no)) { $task = ( 'speaking-' . $task_no ); } else { $task_no = ( '1' ); $task = ( 'speaking-' . $task_no ); } $posts_per_page = 10; $the_query = new WP_Query( array( 'post_type' =&gt; 'english-speaking', 'taxonomy' =&gt; 'speaking-task', 'term' =&gt; $task, /*'paged' =&gt; $paged, 'posts_per_page' =&gt; $posts_per_page,*/ 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'wpcf-question-id', 'order' =&gt; 'ASC', /* ASC/DESC */ ) ); </code></pre> <p>———————————————————————————————————</p> <p>In [<strong>functions.php</strong>] , I have the following code: </p> <pre><code>function custom_rewrite_tag() { //taxonomy speaking-task =? add_rewrite_tag('%task%', '([^/]*)'); } add_action('init', 'custom_rewrite_tag', 10, 0); // Custom Question ID from custom field function cqid() { $cqid = get_post_meta( get_the_ID(), 'wpcf-question-id', true ); return $cqid; } function my_questions_cpt_list() { return [ // Format: POST_TYPE =&gt; QUESTION_SUBJECT_SLUG 'english-listening' =&gt; 'listening', 'english-speaking' =&gt; 'speaking', 'english-reading' =&gt; 'reading', 'english-writing' =&gt; 'writing', // Add more items as needed, or if and when you register another CPT // for questions. ]; } add_action( 'init', 'my_questions_cpt_add_rewrite_rules' ); function my_questions_cpt_add_rewrite_rules() { // Archive Page add_rewrite_rule( '^english/speaking/?$','index.php?post_type=english-speaking&amp;taxonomy=speaking-task&amp;task=$matches[1]', 'top' ); add_rewrite_rule( '^english/speaking/([^/]*)/?$','index.php?post_type=english-speaking&amp;taxonomy=speaking-task&amp;task=$matches[1]', 'top' ); // $cpt_list = my_questions_cpt_list(); foreach ( $cpt_list as $post_type =&gt; $q_subject ) { if ( empty( $post_type ) ) { continue; } if ( ! $s = preg_quote( $q_subject ) ) { continue; } add_rewrite_rule('^english/(' . $s . ')/(\d+)/(\d+)/([^/]+)/?','index.php?' . $post_type . '=$matches[4]','top'); } } add_filter( 'post_type_link', 'my_questions_cpt_custom_permalink', 10, 2 ); function my_questions_cpt_custom_permalink( $permalink, $post ) { $taxonomy = 'speaking-task'; $cpt_list = my_questions_cpt_list(); if ( false === strpos( $permalink, '?' ) &amp;&amp; $post &amp;&amp; isset( $cpt_list[ $post-&gt;post_type ] ) ) { $cats = get_the_terms( $post, $taxonomy ); if ( $cats &amp;&amp; ! is_wp_error( $cats ) ) { // If assigned to multiple tasks (or categories), then we use just // the first task/term. $cat_id = $cats[0]-&gt;slug; //term_id $task = $cat_id[strlen($cat_id)-1]; $cqid = cqid(); $s = $cpt_list[ $post-&gt;post_type ]; $permalink = home_url( 'english/' . $s . '/' . $task . '/' . $cqid . '/' . $post-&gt;post_name . '/' ); $permalink = user_trailingslashit( $permalink, 'single' ); } } return $permalink; } </code></pre> <p>———————————————————————————————————</p> <p>@Sally The code above is limited to my programming level, I used your first answer and modified it... it is kind working in localhost but the archive url got 404 or blank page when I moved it to online hosting server...</p>
[ { "answer_id": 301195, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Here's one example how to construct such a custom function:</p>\n\n<pre><code>/**\n * Check if a comment has children.\n *\n * @param int $comment_id Comment ID\n * @return bool Has comment children.\n */\nfunction has_comment_children_wpse( $comment_id ) {\n return get_comments( [ 'parent' =&gt; $comment_id, 'count' =&gt; true ] ) &gt; 0;\n}\n</code></pre>\n\n<p>using the <code>get_comments()</code> function with the <code>count</code> attribute (to return the number of comments) and the <code>parent</code> attribute to find the children.</p>\n" }, { "answer_id": 356389, "author": "scmccarthy22", "author_id": 181005, "author_profile": "https://wordpress.stackexchange.com/users/181005", "pm_score": 0, "selected": false, "text": "<p>Here's another method in case you want to check if a comment has replies (children) within a get_comments() query. (You would likely not want to use birgire's method inside of a get_comments() query since you would be doing a get_comments() query inside of another get_comments() query.</p>\n\n<p>My method is to use the WP_comment_query class's get_children() method:</p>\n\n<pre><code>$args = array(\n'order' =&gt; 'DESC',\n'status' =&gt; 'approve',\n);\n\n$comments = get_comments( $args ); \nforeach ( $comments as $comment ) {\n $content = $comment-&gt;comment_content;\n $comment_children = $comment-&gt;get_children();\n\n if($comment_children){\n //code for comment with children\n } else {\n //code for comment without children \n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 405808, "author": "anonim", "author_id": 222274, "author_profile": "https://wordpress.stackexchange.com/users/222274", "pm_score": 0, "selected": false, "text": "<p>You can use this</p>\n<pre><code>$child_comments = get_comments(array(\n 'post_id' =&gt; get_the_ID(),\n 'status' =&gt; 'approve',\n 'parent' =&gt; $comment-&gt;comment_ID,\n));\nif($child_comments){}\n</code></pre>\n" } ]
2018/04/19
[ "https://wordpress.stackexchange.com/questions/301239", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137035/" ]
[**Edited**] I changed the purpose of my site into an language learning site. Now the CPT is setup as following: **{ Language } - { Subject }** * English speaking (slug: english-speaking ) * English writing (english-writing ) * English reading ( english-speaking ) * English writing (english-writing) --- **Single CPT setup** Because each CPT might have different taxonomy… so it is preferred this would be taking into consideration of the code. Say: CPT “English Speaking” has a custom taxonomy of “Speaking Task” (speaking-task) with terms “task-1”, “task-2”, “task-3” … . But: CPT “English Writing” has no taxonomy at all. Desired URL for single CPT post item: **With custom taxonomy terms:** * www.domain.com/{language}/{subject}/{ term-slug }/{custom-question-id}/{post-name} * ex. www.domain.com/english/speaking/speaking-1/32/blah-blah-blah **Without custom taxonomy terms:** * www.domain.com/{language}/{subject}/{custom-question-id}/{post-name} * ex. www.domain.com/english/writing/32/blah-blah-blah **The URL rewrite part for Single CPT is not a problem for me now thanks to your teaching and genius code provided in the new answer** What I am struggling with is the rewrite for the CPT Archive page below: --- **CPT Archive setup** I am trying to create a custom CPT Archive template with the following setup for URL: * www.domain.com/ { language } / { subject } ex. www.domain.com/english/speaking * www.domain.com/ { language } / { subject } / { terms-slug } * ex1. www.domain.com/english/speaking (instead of listing all posts, I wish to make it default to list out to “speaking-1”) * ex2. www.domain.com/english/speaking/speaking-1 (only list out post under “speaking-1” ) * ex3. www.domain.com/english/speaking/speaking-2 (only list out post under “speaking-2” ) ——————————————————————————————————— In [**archive-english-speaking.php**] , I have the following code: ``` // use add_rewrite_rule in funcitons; query_vars "task" is terms of speaking-task taxonomy global $wp_query; $task_no = $wp_query->query_vars['task']; if (preg_match("/[1-6]/", $task_no)) { $task = ( 'speaking-' . $task_no ); } else { $task_no = ( '1' ); $task = ( 'speaking-' . $task_no ); } $posts_per_page = 10; $the_query = new WP_Query( array( 'post_type' => 'english-speaking', 'taxonomy' => 'speaking-task', 'term' => $task, /*'paged' => $paged, 'posts_per_page' => $posts_per_page,*/ 'orderby' => 'meta_value_num', 'meta_key' => 'wpcf-question-id', 'order' => 'ASC', /* ASC/DESC */ ) ); ``` ——————————————————————————————————— In [**functions.php**] , I have the following code: ``` function custom_rewrite_tag() { //taxonomy speaking-task =? add_rewrite_tag('%task%', '([^/]*)'); } add_action('init', 'custom_rewrite_tag', 10, 0); // Custom Question ID from custom field function cqid() { $cqid = get_post_meta( get_the_ID(), 'wpcf-question-id', true ); return $cqid; } function my_questions_cpt_list() { return [ // Format: POST_TYPE => QUESTION_SUBJECT_SLUG 'english-listening' => 'listening', 'english-speaking' => 'speaking', 'english-reading' => 'reading', 'english-writing' => 'writing', // Add more items as needed, or if and when you register another CPT // for questions. ]; } add_action( 'init', 'my_questions_cpt_add_rewrite_rules' ); function my_questions_cpt_add_rewrite_rules() { // Archive Page add_rewrite_rule( '^english/speaking/?$','index.php?post_type=english-speaking&taxonomy=speaking-task&task=$matches[1]', 'top' ); add_rewrite_rule( '^english/speaking/([^/]*)/?$','index.php?post_type=english-speaking&taxonomy=speaking-task&task=$matches[1]', 'top' ); // $cpt_list = my_questions_cpt_list(); foreach ( $cpt_list as $post_type => $q_subject ) { if ( empty( $post_type ) ) { continue; } if ( ! $s = preg_quote( $q_subject ) ) { continue; } add_rewrite_rule('^english/(' . $s . ')/(\d+)/(\d+)/([^/]+)/?','index.php?' . $post_type . '=$matches[4]','top'); } } add_filter( 'post_type_link', 'my_questions_cpt_custom_permalink', 10, 2 ); function my_questions_cpt_custom_permalink( $permalink, $post ) { $taxonomy = 'speaking-task'; $cpt_list = my_questions_cpt_list(); if ( false === strpos( $permalink, '?' ) && $post && isset( $cpt_list[ $post->post_type ] ) ) { $cats = get_the_terms( $post, $taxonomy ); if ( $cats && ! is_wp_error( $cats ) ) { // If assigned to multiple tasks (or categories), then we use just // the first task/term. $cat_id = $cats[0]->slug; //term_id $task = $cat_id[strlen($cat_id)-1]; $cqid = cqid(); $s = $cpt_list[ $post->post_type ]; $permalink = home_url( 'english/' . $s . '/' . $task . '/' . $cqid . '/' . $post->post_name . '/' ); $permalink = user_trailingslashit( $permalink, 'single' ); } } return $permalink; } ``` ——————————————————————————————————— @Sally The code above is limited to my programming level, I used your first answer and modified it... it is kind working in localhost but the archive url got 404 or blank page when I moved it to online hosting server...
Here's one example how to construct such a custom function: ``` /** * Check if a comment has children. * * @param int $comment_id Comment ID * @return bool Has comment children. */ function has_comment_children_wpse( $comment_id ) { return get_comments( [ 'parent' => $comment_id, 'count' => true ] ) > 0; } ``` using the `get_comments()` function with the `count` attribute (to return the number of comments) and the `parent` attribute to find the children.
301,255
<p>I realise this is perhaps more of a php question, but it relates to WP use.</p> <p>Can the example below, be modified (and if so, how?) to fully concatenate the 2 echos rather than having them separate?</p> <pre><code>if... { echo '&lt;p&gt;', get_template_part( 'templates/xxx' ); echo '&lt;/p&gt;'; } </code></pre>
[ { "answer_id": 301257, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 2, "selected": true, "text": "<p>this is more a PHP question </p>\n\n<p>you can try these folowing forms : </p>\n\n<pre><code>if (...) {\n echo '&lt;p&gt;';\n get_template_part('templates/xxx');\n echo '&lt;/p&gt;';\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (...) {\n ?&gt;\n &lt;p&gt;\n &lt;?php get_template_part('templates/xxx'); ?&gt;\n &lt;/p&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 301303, "author": "Swen", "author_id": 22588, "author_profile": "https://wordpress.stackexchange.com/users/22588", "pm_score": 0, "selected": false, "text": "<p>Alternatively, you can do it like this if you need to return the data instead of echo it. Useful for in functions and AJAX callbacks and such.</p>\n\n<pre><code>// Start HTML\nob_start();\n?&gt;\n\n &lt;p&gt;&lt;?php get_template_part( 'templates/xxx' ); ?&gt;&lt;/p&gt;\n\n&lt;?php \n\n$html = ob_get_contents();\nob_end_clean();\n\nreturn $html;\n</code></pre>\n" } ]
2018/04/19
[ "https://wordpress.stackexchange.com/questions/301255", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I realise this is perhaps more of a php question, but it relates to WP use. Can the example below, be modified (and if so, how?) to fully concatenate the 2 echos rather than having them separate? ``` if... { echo '<p>', get_template_part( 'templates/xxx' ); echo '</p>'; } ```
this is more a PHP question you can try these folowing forms : ``` if (...) { echo '<p>'; get_template_part('templates/xxx'); echo '</p>'; } ``` or ``` if (...) { ?> <p> <?php get_template_part('templates/xxx'); ?> </p> <?php } ```
301,281
<p>I am trying to display WooCommerce products in custom loop. This is my code:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'product', 'posts_per_page' =&gt; 6, 'product_cat' =&gt; 'apparel', 'orderby' =&gt; 'date' ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; ?&gt; &lt;div class="col-4"&gt; &lt;figure class="figure"&gt; &lt;a href="&lt;?php echo get_permalink( $loop-&gt;post-&gt;ID ) ?&gt;"&gt; &lt;?php echo get_the_post_thumbnail($loop-&gt;post-&gt;ID, 'shop_catalog');?&gt; &lt;/a&gt; &lt;div class="updetails"&gt; &lt;p class="price"&gt;$&lt;?php echo $product-&gt;get_price(); ?&gt;&lt;/p&gt; &lt;p class="offer"&gt;&lt;?php woocommerce_show_product_sale_flash( $post, $product ); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;figcaption class="figure-caption"&gt; &lt;h3 class="title"&gt;&lt;?php echo the_title(); ?&gt;&lt;/h3&gt; &lt;div class="rating"&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/img/rating.png" class="img-fluid" /&gt; &lt;/div&gt; &lt;p class="description"&gt;Lightweight nylon and T-back design for a comfortable fit. Junior Sizes...&lt;/p&gt; &lt;div class="useraction"&gt; &lt;a href="#" class="wishlist" data-toggle="tooltip" title="Wishlist"&gt;&lt;i class="fas fa-heart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="#" class="addtocart" data-toggle="tooltip" title="Add To Cart"&gt;&lt;i class="fas fa-cart-plus"&gt;&lt;/i&gt; Add To Cart&lt;/a&gt; &lt;a href="#" class="quickview" data-toggle="tooltip" title="Quickview"&gt;&lt;i class="fas fa-eye"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/figcaption&gt; &lt;/figure&gt; </code></pre> <p></p> <p>I have managed to display title, price and product link, But If you have better option please do let me know, I will appreciate this. I am now trying to display product star rating, short description and add to cart button as well as wishlist and quickview. How can I do that? Do you have any better option? </p>
[ { "answer_id": 301340, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;ul class=\"products\"&gt;\n &lt;?php\n $args = array(\n 'post_type' =&gt; 'product',\n 'posts_per_page' =&gt; 12\n );\n $loop = new WP_Query( $args );\n if ( $loop-&gt;have_posts() ) {\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n wc_get_template_part( 'content', 'product' );\n endwhile;\n } else {\n echo __( 'No products found' );\n }\n wp_reset_postdata();\n ?&gt;\n&lt;/ul&gt;&lt;!--/.products--&gt;\n</code></pre>\n" }, { "answer_id": 346812, "author": "Md. Mehedi Hassan", "author_id": 170555, "author_profile": "https://wordpress.stackexchange.com/users/170555", "pm_score": 0, "selected": false, "text": "<p>For display product star rating in your code</p>\n\n<pre><code>&lt;div class=\"rating\"&gt;\n &lt;?php add_star_rating(); ?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Now go to functios.php in your theme folder and insert the code below</p>\n\n<pre><code>function add_star_rating(){\n global $woocommerce, $product;\n $average = $product-&gt;get_average_rating();\n\n echo '&lt;div class=\"star-rating\"&gt;&lt;span style=\"width:'.( ( $average / 5 ) * 100 ) . '%\"&gt;&lt;strong itemprop=\"ratingValue\" class=\"rating\"&gt;'.$average.'&lt;/strong&gt; '.__( 'out of 5', 'woocommerce' ).'&lt;/span&gt;&lt;/div&gt;';\n}\nadd_action('woocommerce_after_shop_loop_item', 'add_star_rating' );\n</code></pre>\n\n<p>Now go to style.css in your theme folder and insert the code below</p>\n\n<pre><code>@font-face {\n font-family: star;\n src: url(\"../lets_buy_24/assets/fonts/star.woff\") format(\"woff\");\n font-style: normal;\n font-weight: 400;\n}\n\n\n.star-rating {\n /*font-size: .857em;\n display: block;\n float: none;\n float: right;*/\n margin: .3em 0;\n overflow: hidden;\n position: relative;\n height: 1em;\n line-height: 1;\n font-size: 1em;\n width: 5.4em;\n font-family: star;\n}\n\n.star-rating::before {\n content: \"\\73\\73\\73\\73\\73\";\n color: #df3737;\n float: left;\n top: 0;\n left: 0;\n position: absolute;\n}\n\n.star-rating span {\n overflow: hidden;\n float: left;\n top: 0;\n left: 0;\n position: absolute;\n padding-top: 1.5em;\n}\n\n.star-rating span::before {\n content: \"\\53\\53\\53\\53\\53\";\n top: 0;\n position: absolute;\n left: 0;\n color: #df3737;\n}\n\n.star-rating strong {\n display: block;\n}\n</code></pre>\n\n<p><em>you will find the star.woff file in the the below path</em></p>\n\n<p><strong>wordpress\\wp-content\\plugins\\woocommerce\\assets\\fonts\\star.woff</strong></p>\n\n<p>copy it and pest your directory and link it for css file</p>\n" } ]
2018/04/19
[ "https://wordpress.stackexchange.com/questions/301281", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137372/" ]
I am trying to display WooCommerce products in custom loop. This is my code: ``` <?php $args = array( 'post_type' => 'product', 'posts_per_page' => 6, 'product_cat' => 'apparel', 'orderby' => 'date' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?> <div class="col-4"> <figure class="figure"> <a href="<?php echo get_permalink( $loop->post->ID ) ?>"> <?php echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog');?> </a> <div class="updetails"> <p class="price">$<?php echo $product->get_price(); ?></p> <p class="offer"><?php woocommerce_show_product_sale_flash( $post, $product ); ?></p> </div> <figcaption class="figure-caption"> <h3 class="title"><?php echo the_title(); ?></h3> <div class="rating"> <img src="<?php echo get_template_directory_uri(); ?>/img/rating.png" class="img-fluid" /> </div> <p class="description">Lightweight nylon and T-back design for a comfortable fit. Junior Sizes...</p> <div class="useraction"> <a href="#" class="wishlist" data-toggle="tooltip" title="Wishlist"><i class="fas fa-heart"></i></a> <a href="#" class="addtocart" data-toggle="tooltip" title="Add To Cart"><i class="fas fa-cart-plus"></i> Add To Cart</a> <a href="#" class="quickview" data-toggle="tooltip" title="Quickview"><i class="fas fa-eye"></i></a> </div> </figcaption> </figure> ``` I have managed to display title, price and product link, But If you have better option please do let me know, I will appreciate this. I am now trying to display product star rating, short description and add to cart button as well as wishlist and quickview. How can I do that? Do you have any better option?
``` <ul class="products"> <?php $args = array( 'post_type' => 'product', 'posts_per_page' => 12 ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); wc_get_template_part( 'content', 'product' ); endwhile; } else { echo __( 'No products found' ); } wp_reset_postdata(); ?> </ul><!--/.products--> ```
301,282
<p>I currently use this code in the main plugins file itself. But that plugin is not my own so I would prefer to be able to upgrade it normally without every time adding this code.</p> <pre><code>if ( defined( 'WP_CLI' ) &amp;&amp; WP_CLI ) { exit; } </code></pre> <p>I need to do this because this plugin produces errors and stops wp-cli to execute correctly so I can't just disable the plugin with wp-cli, do my tasks and re-enable it.</p> <p>Is there a way I can do something like <code>if x then do not load plugin file x</code> from within a mu-plugin?</p>
[ { "answer_id": 301286, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 5, "selected": true, "text": "<p>One of the first things WordPress does to load plugins is get the active plugins as saved in the database:</p>\n\n<pre><code>$active_plugins = (array) get_option( 'active_plugins', array() );\n</code></pre>\n\n<p>Since it uses <code>get_option()</code> we can use the <a href=\"https://developer.wordpress.org/reference/hooks/option_option/\" rel=\"noreferrer\"><code>option_active_plugins</code></a> filter to modify the list of active plugins on the fly.</p>\n\n<pre><code>function wpse_301282_disable_plugin( $active_plugins ) {\n if ( defined( 'WP_CLI' ) &amp;&amp; WP_CLI ) {\n $key = array_search( 'gravityforms/gravityforms.php', $active_plugins );\n\n if ( $key ) {\n unset( $active_plugins[$key] );\n }\n }\n\n return $active_plugins;\n}\nadd_filter( 'option_active_plugins', 'wpse_301282_disable_plugin' );\n</code></pre>\n\n<p>Just replace <code>gravityforms/gravityforms.php</code> with the directory and filename of the plugin you want to disable.</p>\n\n<p>The problem here is that we are trying to affect the loading of plugins, so we can't do that from <em>within</em> a plugin, because it's too late. In the theme would also be too late.</p>\n\n<p>Thankfully WordPress has <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"noreferrer\">\"Must Use Plugins\"</a> these are plugins you can add that are loaded before and separately to regular plugins, and do not appear in the regular plugins list.</p>\n\n<p>All you need to do to add this code to a Must Use Plugin is to create a <code>wp-content/mu-plugins</code> directory (if it doesn't already exist) and create a PHP file (it can be called anything) with that code in it. You don't need a plugin header or anything else.</p>\n\n<p>Now that code will be loaded before all other plugins when WordPress loads. Since our filter is in place, when WordPress gets the list of active plugins to load the plugin you want to disable will be filtered out of that list if WP-CLI is active.</p>\n" }, { "answer_id": 301287, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 4, "selected": false, "text": "<p>You can use the <code>skip-plugins</code> option in WP-CLI to not load individual plugins when using WP-CLI.</p>\n\n<p>You can either use it in command like this:</p>\n\n<pre><code>wp user list --skip-plugins=my-plugin\n</code></pre>\n\n<p>Or you can add this to your <code>wp-cli.yml</code> file:</p>\n\n<pre><code>skip-plugins:\n- my-plugin\n</code></pre>\n" }, { "answer_id": 301328, "author": "John Dee", "author_id": 131224, "author_profile": "https://wordpress.stackexchange.com/users/131224", "pm_score": -1, "selected": false, "text": "<p>Just re-naming the plugin dir name will disable it. I do it sometimes to temporarily disable a plugin [linux]: </p>\n\n<pre><code>mv my-plugin-dir renamed-my-plugin-dir\n</code></pre>\n" } ]
2018/04/19
[ "https://wordpress.stackexchange.com/questions/301282", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38602/" ]
I currently use this code in the main plugins file itself. But that plugin is not my own so I would prefer to be able to upgrade it normally without every time adding this code. ``` if ( defined( 'WP_CLI' ) && WP_CLI ) { exit; } ``` I need to do this because this plugin produces errors and stops wp-cli to execute correctly so I can't just disable the plugin with wp-cli, do my tasks and re-enable it. Is there a way I can do something like `if x then do not load plugin file x` from within a mu-plugin?
One of the first things WordPress does to load plugins is get the active plugins as saved in the database: ``` $active_plugins = (array) get_option( 'active_plugins', array() ); ``` Since it uses `get_option()` we can use the [`option_active_plugins`](https://developer.wordpress.org/reference/hooks/option_option/) filter to modify the list of active plugins on the fly. ``` function wpse_301282_disable_plugin( $active_plugins ) { if ( defined( 'WP_CLI' ) && WP_CLI ) { $key = array_search( 'gravityforms/gravityforms.php', $active_plugins ); if ( $key ) { unset( $active_plugins[$key] ); } } return $active_plugins; } add_filter( 'option_active_plugins', 'wpse_301282_disable_plugin' ); ``` Just replace `gravityforms/gravityforms.php` with the directory and filename of the plugin you want to disable. The problem here is that we are trying to affect the loading of plugins, so we can't do that from *within* a plugin, because it's too late. In the theme would also be too late. Thankfully WordPress has ["Must Use Plugins"](https://codex.wordpress.org/Must_Use_Plugins) these are plugins you can add that are loaded before and separately to regular plugins, and do not appear in the regular plugins list. All you need to do to add this code to a Must Use Plugin is to create a `wp-content/mu-plugins` directory (if it doesn't already exist) and create a PHP file (it can be called anything) with that code in it. You don't need a plugin header or anything else. Now that code will be loaded before all other plugins when WordPress loads. Since our filter is in place, when WordPress gets the list of active plugins to load the plugin you want to disable will be filtered out of that list if WP-CLI is active.
301,306
<p>I have uploaded a file called page-testtest.php to my template folder. Aren't I supposed to get to this file when I go to <strong>example.com/testtest</strong></p> <p>It seems very strange to me because the documentation clearly states that I should go to that file without any struggle. Instead I get "Oops! That page can’t be found."</p> <p>By the way the permalink is set as: <a href="https://example.com/sample-post/" rel="nofollow noreferrer">https://example.com/sample-post/</a> and I use Underscores template</p> <p>Before somebody bravely refer me to the documentation this is from <a href="https://developer.wordpress.org/themes/template-files-section/page-template-files" rel="nofollow noreferrer">https://developer.wordpress.org/themes/template-files-section/page-template-files</a></p> <pre><code>page-{slug}.php — If no custom template has been assigned, WordPress looks for and uses a specialized template that contains the page’s slug. </code></pre>
[ { "answer_id": 301308, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Just creating the theme template doesn't create the Page itself. You'll also need to create the Page - typically the easiest way is to just log into wp-admin and manually add it. There are also ways to add it programmatically, but unless you are setting this up for other people who will need these pages added when the theme is activated, usually the manual route is best.</p>\n" }, { "answer_id": 301309, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 3, "selected": true, "text": "<p>A template is not a page you can load directly. A template is used for the formatting ('building') of a 'page' (created via Page, Add) or 'post' (created via Post, Add). </p>\n\n<p>On that page/post editing page, there is a place to specify the template that the WP will use when the page is output. There are default templates used (see <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a>) for posts/pages.</p>\n\n<p>But you can't call (load into your browser) a template file directly. The template file is sort of 'output instructions' that WP uses to build the actual page (or post).</p>\n" } ]
2018/04/19
[ "https://wordpress.stackexchange.com/questions/301306", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125637/" ]
I have uploaded a file called page-testtest.php to my template folder. Aren't I supposed to get to this file when I go to **example.com/testtest** It seems very strange to me because the documentation clearly states that I should go to that file without any struggle. Instead I get "Oops! That page can’t be found." By the way the permalink is set as: <https://example.com/sample-post/> and I use Underscores template Before somebody bravely refer me to the documentation this is from <https://developer.wordpress.org/themes/template-files-section/page-template-files> ``` page-{slug}.php — If no custom template has been assigned, WordPress looks for and uses a specialized template that contains the page’s slug. ```
A template is not a page you can load directly. A template is used for the formatting ('building') of a 'page' (created via Page, Add) or 'post' (created via Post, Add). On that page/post editing page, there is a place to specify the template that the WP will use when the page is output. There are default templates used (see [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/)) for posts/pages. But you can't call (load into your browser) a template file directly. The template file is sort of 'output instructions' that WP uses to build the actual page (or post).
301,392
<p>my wordpress shows the wrong time, <a href="https://i.stack.imgur.com/hTOhO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hTOhO.jpg" alt="enter image description here"></a></p> <p>UTC time on the picture should be 18:06:28 and localtime 15:06:28, so the UTC time is showed as local time, I use my own vps on digital ocean and time zone is correct,</p> <pre><code>ls -l /etc/localtime lrwxrwxrwx 1 root root 36 Apr 19 23:20 /etc/localtime -&gt; /usr/share/zoneinfo/America/Santiago </code></pre> <p>also I have anothers php scripts on the server and the time is correct, cron job for whmcs for example works perfect, this is my config time on wordpress</p> <p><a href="https://i.stack.imgur.com/o3m1R.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o3m1R.jpg" alt="enter image description here"></a></p> <p>How to fix this?, the problem is in all my wordpress websites, and the woocommerce websites has the wrong time on order too.</p> <p>I use php 7 and last wordpress</p> <p>I already tried with timezone in php.ini and in global php config I have America/Santiago</p> <p>date on server is ok</p> <pre><code>root@server:~# timedatectl Local time: Fri 2018-04-20 22:15:40 -03 Universal time: Sat 2018-04-21 01:15:40 UTC RTC time: Sat 2018-04-21 01:15:40 Time zone: America/Santiago (-03, -0300) Network time on: yes NTP synchronized: yes RTC in local TZ: no </code></pre> <p>php too</p> <pre><code>php &gt; echo date_default_timezone_get(time()); America/Santiago </code></pre>
[ { "answer_id": 301400, "author": "atempel", "author_id": 132268, "author_profile": "https://wordpress.stackexchange.com/users/132268", "pm_score": 2, "selected": false, "text": "<p>This might be a solution for you:\n<a href=\"https://wordpress.org/support/topic/utc-time-and-local-time-problems/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/utc-time-and-local-time-problems/</a></p>\n\n<p>It says that it's a problem with PHP config, not Wordpress.</p>\n\n<p>(Bringing the solution here for ease of reference)</p>\n\n<ol>\n<li><p>If you have shell access, do you get the correct date/time when you type “date” at the command line? If that’s wrong, contact your host.</p></li>\n<li><p>Try adding the correct timezone to php.ini: <a href=\"http://www.inmotionhosting.com/support/website/php/setting-the-timezone-for-php-in-the-phpini-file\" rel=\"nofollow noreferrer\">http://www.inmotionhosting.com/support/website/php/setting-the-timezone-for-php-in-the-phpini-file</a> (And check if that is displaying the right zone)</p></li>\n<li><p>Check your plugins, if any of them modifies anything on Wordpress clock. On the link I sent above the case was solved by deactivating a calendar plugin.</p></li>\n</ol>\n\n<p>Both these links below can help with your search too, I can't point at what could solve it since there's missing information on this topic about what they say there, but I hope it shine some light into your problem!</p>\n\n<p><a href=\"https://wordpress.org/support/topic/utc-time-wrong/page/2/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/utc-time-wrong/page/2/</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/184332/fixing-utc-time-wordpress-effects\">Fixing UTC time - wordpress effects</a></p>\n" }, { "answer_id": 316001, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 1, "selected": false, "text": "<p>Trying searching through all files in your /wp-content/ folder for any reference to this function:</p>\n\n<pre><code>date_default_timezone_set\n</code></pre>\n\n<p>If a theme or plugin manually defines this it can throw off your WP installation. I had a circumstance exactly like the one you describe here, and the source was this line at the top of the theme's functions.php file:</p>\n\n<pre><code>date_default_timezone_set( 'America/New_York' );\n</code></pre>\n\n<p>This resulted in the wrong UTC time reported under Settings > General:</p>\n\n<pre><code>Universal time (UTC) is 2018-10-05 12:05:18. Local time is 2018-10-05 08:05:18.\n</code></pre>\n\n<p>Once removed, the correct times appeared:</p>\n\n<pre><code>Universal time (UTC) is 2018-10-05 16:06:01. Local time is 2018-10-05 12:06:01.\n</code></pre>\n" }, { "answer_id": 364138, "author": "Jan-Pieter", "author_id": 186140, "author_profile": "https://wordpress.stackexchange.com/users/186140", "pm_score": 0, "selected": false, "text": "<p>I had the same issue, was caused by wrong contents of the /usr/share/zoneinfo/UTC file. After restoring a good version problem fixed. If strings /usr/share/zoneinfo/UTC display more than 3 lines or displays other timezones than UTC this file does not have the correct contents.</p>\n" } ]
2018/04/20
[ "https://wordpress.stackexchange.com/questions/301392", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142149/" ]
my wordpress shows the wrong time, [![enter image description here](https://i.stack.imgur.com/hTOhO.jpg)](https://i.stack.imgur.com/hTOhO.jpg) UTC time on the picture should be 18:06:28 and localtime 15:06:28, so the UTC time is showed as local time, I use my own vps on digital ocean and time zone is correct, ``` ls -l /etc/localtime lrwxrwxrwx 1 root root 36 Apr 19 23:20 /etc/localtime -> /usr/share/zoneinfo/America/Santiago ``` also I have anothers php scripts on the server and the time is correct, cron job for whmcs for example works perfect, this is my config time on wordpress [![enter image description here](https://i.stack.imgur.com/o3m1R.jpg)](https://i.stack.imgur.com/o3m1R.jpg) How to fix this?, the problem is in all my wordpress websites, and the woocommerce websites has the wrong time on order too. I use php 7 and last wordpress I already tried with timezone in php.ini and in global php config I have America/Santiago date on server is ok ``` root@server:~# timedatectl Local time: Fri 2018-04-20 22:15:40 -03 Universal time: Sat 2018-04-21 01:15:40 UTC RTC time: Sat 2018-04-21 01:15:40 Time zone: America/Santiago (-03, -0300) Network time on: yes NTP synchronized: yes RTC in local TZ: no ``` php too ``` php > echo date_default_timezone_get(time()); America/Santiago ```
This might be a solution for you: <https://wordpress.org/support/topic/utc-time-and-local-time-problems/> It says that it's a problem with PHP config, not Wordpress. (Bringing the solution here for ease of reference) 1. If you have shell access, do you get the correct date/time when you type “date” at the command line? If that’s wrong, contact your host. 2. Try adding the correct timezone to php.ini: <http://www.inmotionhosting.com/support/website/php/setting-the-timezone-for-php-in-the-phpini-file> (And check if that is displaying the right zone) 3. Check your plugins, if any of them modifies anything on Wordpress clock. On the link I sent above the case was solved by deactivating a calendar plugin. Both these links below can help with your search too, I can't point at what could solve it since there's missing information on this topic about what they say there, but I hope it shine some light into your problem! <https://wordpress.org/support/topic/utc-time-wrong/page/2/> [Fixing UTC time - wordpress effects](https://wordpress.stackexchange.com/questions/184332/fixing-utc-time-wordpress-effects)
301,413
<p>I need to programmatically create a page that uses a specific/custom template as defined programmatically. Both the page and template are created/used by my plugin.</p> <p>The plugin files include a page template. The plugin code (with a button press) will create the page ('mycustompage') (similar to the technique here <a href="https://wordpress.stackexchange.com/questions/13378/add-custom-template-page-programmatically">Add custom template page programmatically</a> ). </p> <p>But I need to specify the template used by that page. The page has to use the template in my_plugin_folder/templates/mytemplate.php . The template cannot be in the current theme folder structure.</p> <p>Once the page is created, then the plugin will open a new tab with www.example.com/mycustompage (assume plugin code creates a unique/unused page name).</p> <p>How do I specify the template that will be used by the programmatically-created-page when I call the created page (as in www.example.com/mycustompage ? And, the template to use is not in the current theme folder.</p> <p><strong>Added</strong></p> <p>Note that I am creating HTML code 'manually' by using The Loop to output post content. The HTML code is <strong>not</strong> being displayed on a WP page. So there is no WP JS used that converts emoji HMTL characters into the emoji graphic. </p> <p>If I was to create a Page that uses a simple template to display only posts (the template does not use wp_header/sidebars/footers, etc), and then display that page, the emoji are shown as graphics in the browser. If I copy that page (in the browser) and paste that into Word, the graphics are in Word -- because they are on the browser page.</p> <p>But, I am creating all of the HTML (of the post content) with PHP code. And I haven't found a good way to convert emoji HTML code to emoji graphics.</p> <p>So, I figured that (instead of creating HTML code for the entire page) using a simple template that is used by a Page that I create programatically would allow WP to use that Page (and all posts content) that would show emoji graphics. But templates are normally in the theme folder, and as a plugin, I need to use my template (that is stored in the plugin's folders). (I assume that it is not 'polite' for my plugin to write a template file to the theme's folder.)</p> <p>So, <strong>the question</strong>: create a Page programatically that uses a template file that is contained in the plugin's folder, not the theme's folder. Using a template allows the emoji graphics to be displayed by WP. Then I can copy/paste the generated page into Word, and the graphics will be there.</p>
[ { "answer_id": 301476, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": -1, "selected": false, "text": "<p>I'm going to ignore your attempted solution and address the original problem:</p>\n\n<p><strong><em>Emoji are converted into HTML, preventing them from showing when copy pasted into MS Word</em></strong></p>\n\n<p>This is because a script turns all the emoji on the page into SVG icons. Creating child pages for every single page, and a dedicated template to solve this problem is completely unnecessary.</p>\n\n<p>If you look at the source of the page, the emoji are there, intact, but get converted into SVG images by javascript:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xs7ds.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xs7ds.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/RXDQw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RXDQw.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/gc9vP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gc9vP.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here we see they are saved as emoji:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aaptm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aaptm.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here they are intact in the pages source:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PCZHw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PCZHw.png\" alt=\"enter image description here\"></a></p>\n\n<h2>So The Real Problem</h2>\n\n<p>WP Emoji takes the emoji that you can copy into Word, and turns them into SVG icons so that users on browsers and OS's without emoji support can still see them. This breaks copy paste in MS Word.</p>\n\n<p>Of note, it does not have the same effect elsewhere, e.g. here is Sublime Text:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rBOJg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rBOJg.png\" alt=\"enter image description here\"></a></p>\n\n<p>Google Chrome:</p>\n\n<blockquote>\n <p></p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/rI6ej.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rI6ej.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Solution: Disable the WP Emoji script</h2>\n\n<p>You can disable this in form fields using a HTML class:</p>\n\n<blockquote>\n <p>If you are a developer working on forms, you might want to disable this behaviour in your input fields and textareas. You can use the class attribute with 'wp-exclude-emoji' for this.</p>\n</blockquote>\n\n<p>But for general content, this code snippet will do the trick:</p>\n\n<pre><code>remove_action('wp_head', 'print_emoji_detection_script', 7);\nremove_action('wp_print_styles', 'print_emoji_styles');\n</code></pre>\n\n<p>There are also plugins to do this for you. The end result is that emoji are no longer swapped out for images:</p>\n\n<p><a href=\"https://i.stack.imgur.com/V5LMs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V5LMs.png\" alt=\"enter image description here\"></a></p>\n\n<p>You should now be able to copy paste to Word without issue, and without a complicated setup involving additional templates and child pages</p>\n\n<p>There are other avenues too:</p>\n\n<ul>\n<li>Add a copy button that when clicked, fetches the original source from the REST API and puts it in the clipboard</li>\n<li>When text is selected, convert the image icons back to emoji using their <code>alt</code> text</li>\n<li>Use a modified wp emoji script that only converts if it detects that the users system is unable to render emojis. That user won't get an emoji in Word anyway no matter what you do.</li>\n</ul>\n" }, { "answer_id": 301638, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": true, "text": "<p>The question was about how to use a template that is not in the theme's folder, but in a plugin's folder. The template needs to be used for a specific page. The need for the answer doesn't matter. There is a need; how do I do it?</p>\n\n<p>And the answer is to use the <code>template_include</code> filter (see <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow noreferrer\">here</a>) . Here's my explanation of my answer:</p>\n\n<p>The plugin that I am developing creates a page. That page then needs to use a template that the plugin provides. I could do it by </p>\n\n<ul>\n<li><p>creating a whole new theme (too much work - overkill); </p></li>\n<li><p>copying the template to the theme's folder (not polite to the theme); </p></li>\n<li><p>creating a child theme (overkill again); </p></li>\n<li><p>putting the code in the functions.php file (not polite or good to edit a theme's function.php file; better in a child theme, but that's no good); </p></li>\n<li><p>setting the pages meta to specify a template by name (but that requires a template in the theme's folder); </p></li>\n<li><p>or changing the template used by the Page (hence the question).</p></li>\n</ul>\n\n<p>The code I used to do this is as follows. The template file I want to use is in the plugin's templates folder. My plugin has previously created the \"My Custom Page\" page.</p>\n\n<pre><code>// include our template\nadd_filter( 'template_include', 'use_our_page_template', 99 );\n\nfunction use_our_page_template( $template ) {\n\n if ( is_page( 'My Custom Page' ) ) {\n $new_template = plugin_dir_path( __FILE__ ) . 'templates/mycustomtemplate.php';\n return $new_template;\n }\nreturn;\n</code></pre>\n\n<p>The <code>is_page()</code> function can use the ID# of the page, or it's title, or it's slug (see <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\">docs</a>). I use the page title as my parameter.</p>\n\n<p>Note that if you edit the \"My Custom Page\", you will not see the name of the template being used in the Template field of the editing screen. That doesn't bother me, but could probably be fixed. Doesn't matter; my template is used to output the page.</p>\n\n<p>I put the above code in my plugin's code. The filter is available as long as the plugin is enabled. Yeah, maybe a slight performance hit because the filter is enabled for the whole site, but acceptable to me. And I could probably change the page name to make it fully unique. </p>\n\n<p>So, my solution solves the question: how to set a Page to use a template outside of the theme's folder. The other answers, while containing some useful information, did not answer the original question.</p>\n\n<p>And it works.</p>\n\n<p>(Note: <a href=\"https://wordpress.stackexchange.com/questions/3396/create-custom-page-templates-with-plugins/3558\">this question from 2010</a> pointed me to the ultimate solution.)</p>\n" } ]
2018/04/20
[ "https://wordpress.stackexchange.com/questions/301413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29416/" ]
I need to programmatically create a page that uses a specific/custom template as defined programmatically. Both the page and template are created/used by my plugin. The plugin files include a page template. The plugin code (with a button press) will create the page ('mycustompage') (similar to the technique here [Add custom template page programmatically](https://wordpress.stackexchange.com/questions/13378/add-custom-template-page-programmatically) ). But I need to specify the template used by that page. The page has to use the template in my\_plugin\_folder/templates/mytemplate.php . The template cannot be in the current theme folder structure. Once the page is created, then the plugin will open a new tab with www.example.com/mycustompage (assume plugin code creates a unique/unused page name). How do I specify the template that will be used by the programmatically-created-page when I call the created page (as in www.example.com/mycustompage ? And, the template to use is not in the current theme folder. **Added** Note that I am creating HTML code 'manually' by using The Loop to output post content. The HTML code is **not** being displayed on a WP page. So there is no WP JS used that converts emoji HMTL characters into the emoji graphic. If I was to create a Page that uses a simple template to display only posts (the template does not use wp\_header/sidebars/footers, etc), and then display that page, the emoji are shown as graphics in the browser. If I copy that page (in the browser) and paste that into Word, the graphics are in Word -- because they are on the browser page. But, I am creating all of the HTML (of the post content) with PHP code. And I haven't found a good way to convert emoji HTML code to emoji graphics. So, I figured that (instead of creating HTML code for the entire page) using a simple template that is used by a Page that I create programatically would allow WP to use that Page (and all posts content) that would show emoji graphics. But templates are normally in the theme folder, and as a plugin, I need to use my template (that is stored in the plugin's folders). (I assume that it is not 'polite' for my plugin to write a template file to the theme's folder.) So, **the question**: create a Page programatically that uses a template file that is contained in the plugin's folder, not the theme's folder. Using a template allows the emoji graphics to be displayed by WP. Then I can copy/paste the generated page into Word, and the graphics will be there.
The question was about how to use a template that is not in the theme's folder, but in a plugin's folder. The template needs to be used for a specific page. The need for the answer doesn't matter. There is a need; how do I do it? And the answer is to use the `template_include` filter (see [here](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include)) . Here's my explanation of my answer: The plugin that I am developing creates a page. That page then needs to use a template that the plugin provides. I could do it by * creating a whole new theme (too much work - overkill); * copying the template to the theme's folder (not polite to the theme); * creating a child theme (overkill again); * putting the code in the functions.php file (not polite or good to edit a theme's function.php file; better in a child theme, but that's no good); * setting the pages meta to specify a template by name (but that requires a template in the theme's folder); * or changing the template used by the Page (hence the question). The code I used to do this is as follows. The template file I want to use is in the plugin's templates folder. My plugin has previously created the "My Custom Page" page. ``` // include our template add_filter( 'template_include', 'use_our_page_template', 99 ); function use_our_page_template( $template ) { if ( is_page( 'My Custom Page' ) ) { $new_template = plugin_dir_path( __FILE__ ) . 'templates/mycustomtemplate.php'; return $new_template; } return; ``` The `is_page()` function can use the ID# of the page, or it's title, or it's slug (see [docs](https://developer.wordpress.org/reference/functions/is_page/)). I use the page title as my parameter. Note that if you edit the "My Custom Page", you will not see the name of the template being used in the Template field of the editing screen. That doesn't bother me, but could probably be fixed. Doesn't matter; my template is used to output the page. I put the above code in my plugin's code. The filter is available as long as the plugin is enabled. Yeah, maybe a slight performance hit because the filter is enabled for the whole site, but acceptable to me. And I could probably change the page name to make it fully unique. So, my solution solves the question: how to set a Page to use a template outside of the theme's folder. The other answers, while containing some useful information, did not answer the original question. And it works. (Note: [this question from 2010](https://wordpress.stackexchange.com/questions/3396/create-custom-page-templates-with-plugins/3558) pointed me to the ultimate solution.)
301,426
<p>I want to remove the link from the date, this link leads to archiving. I'd be happy to get help - thank you very much</p> <p><a href="https://i.stack.imgur.com/Oh03C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Oh03C.png" alt="Attached picture"></a></p>
[ { "answer_id": 301427, "author": "Munish Kumar", "author_id": 142176, "author_profile": "https://wordpress.stackexchange.com/users/142176", "pm_score": 2, "selected": true, "text": "<p>I don't know which theme your are using, I am explaining you same thing for twenty seventeen theme, go to wp-content\\themes\\twentyseventeen\\inc\\template-tags.php, </p>\n\n<p>You will find function twentyseventeen_time_link() there. In this function you will get code as like </p>\n\n<pre><code>return sprintf(\n /* translators: %s: post date */\n __( '&lt;span class=\"screen-reader-text\"&gt;Posted on&lt;/span&gt; %s', 'twentyseventeen' ),\n '&lt;a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\"&gt;' . $time_string . '&lt;/a&gt;'\n );\n</code></pre>\n\n<p>Remove 'a' tag and it will become as like </p>\n\n<pre><code>return sprintf(\n /* translators: %s: post date */\n __( '&lt;span class=\"screen-reader-text\"&gt;Posted on&lt;/span&gt; %s', 'twentyseventeen' ),\n $time_string\n );\n</code></pre>\n\n<p>In your theme may be similar code with some other function name, search and do same. Hope it will help you.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 301430, "author": "Omry Biton", "author_id": 142174, "author_profile": "https://wordpress.stackexchange.com/users/142174", "pm_score": 0, "selected": false, "text": "<p>In my template it does not exist, I went to a single.php file\nI think I found something similar, I'll copy the code here</p>\n\n<pre><code>&lt;div class=\"entry-meta\"&gt;\n &lt;?php if ( po_single_metadata_show( 'author' ) ) : ?&gt;\n &lt;span class=\"entry-user vcard author\"&gt;&lt;?php echo get_avatar( get_the_author_meta( 'email' ), '24' ); ?&gt; &lt;?php the_author_link(); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;?php if ( po_single_metadata_show( 'date' ) ) : ?&gt;\n &lt;span&gt;&lt;time datetime=\"&lt;?php the_time('o-m-d'); ?&gt;\" class=\"entry-date date published updated\"&gt;&lt;a href=\"&lt;?php echo get_month_link( get_the_time('Y'), get_the_time('m') ); ?&gt;\"&gt;&lt;?php echo get_the_date(); ?&gt;&lt;/a&gt;&lt;/time&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;?php if ( po_single_metadata_show( 'time' ) ) : ?&gt;\n &lt;span class=\"entry-time\"&gt;&lt;?php echo get_the_time(); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;?php if ( po_single_metadata_show( 'comments' ) ) : ?&gt;\n &lt;span class=\"entry-comment\"&gt;&lt;?php comments_popup_link( __( 'No Comments', 'pojo' ), __( 'One Comment', 'pojo' ), __( '% Comments', 'pojo' ), 'comments' ); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2018/04/21
[ "https://wordpress.stackexchange.com/questions/301426", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142174/" ]
I want to remove the link from the date, this link leads to archiving. I'd be happy to get help - thank you very much [![Attached picture](https://i.stack.imgur.com/Oh03C.png)](https://i.stack.imgur.com/Oh03C.png)
I don't know which theme your are using, I am explaining you same thing for twenty seventeen theme, go to wp-content\themes\twentyseventeen\inc\template-tags.php, You will find function twentyseventeen\_time\_link() there. In this function you will get code as like ``` return sprintf( /* translators: %s: post date */ __( '<span class="screen-reader-text">Posted on</span> %s', 'twentyseventeen' ), '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>' ); ``` Remove 'a' tag and it will become as like ``` return sprintf( /* translators: %s: post date */ __( '<span class="screen-reader-text">Posted on</span> %s', 'twentyseventeen' ), $time_string ); ``` In your theme may be similar code with some other function name, search and do same. Hope it will help you. Thanks
301,438
<p>I have made two dropdown list which is a custom fields.</p> <p><strong>Custom Field 1</strong> :- industry </p> <p><strong>Values of Custom Field 1</strong> :- financial_services,ecommerce,insurances, etc.</p> <p><strong>Custom Field 2</strong> :- primary_functionality</p> <p><strong>Values of Custom Field 2</strong> :- platform_decision_engine,user_authentication,data_provider_verification etc.</p> <p>And My <strong>Post Type Name</strong> is :- providers.</p> <p>Now, I want to fetch posts with multiple custom fields.</p> <p>So, I have tried this query. But it's not working.</p> <pre><code>$args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'providers', 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'industry', 'value' =&gt; 'financial_services', 'compare' =&gt; '=' ), array( 'key' =&gt; 'primary_functionality', 'value' =&gt; 'platform_decision_engine', 'compare' =&gt; '=' ) ) ); </code></pre> <p>Even I tried with for single custom field but it's also not working.</p> <pre><code>// args $args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'providers', 'meta_key' =&gt; 'industry', 'meta_value' =&gt; 'financial_services' ); </code></pre> <p>I'm not that much experienced in wordpress. I have read wordpress document but nothing works. I'm confused about <strong>relation</strong> and <strong>compare</strong> in this query.</p>
[ { "answer_id": 301427, "author": "Munish Kumar", "author_id": 142176, "author_profile": "https://wordpress.stackexchange.com/users/142176", "pm_score": 2, "selected": true, "text": "<p>I don't know which theme your are using, I am explaining you same thing for twenty seventeen theme, go to wp-content\\themes\\twentyseventeen\\inc\\template-tags.php, </p>\n\n<p>You will find function twentyseventeen_time_link() there. In this function you will get code as like </p>\n\n<pre><code>return sprintf(\n /* translators: %s: post date */\n __( '&lt;span class=\"screen-reader-text\"&gt;Posted on&lt;/span&gt; %s', 'twentyseventeen' ),\n '&lt;a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\"&gt;' . $time_string . '&lt;/a&gt;'\n );\n</code></pre>\n\n<p>Remove 'a' tag and it will become as like </p>\n\n<pre><code>return sprintf(\n /* translators: %s: post date */\n __( '&lt;span class=\"screen-reader-text\"&gt;Posted on&lt;/span&gt; %s', 'twentyseventeen' ),\n $time_string\n );\n</code></pre>\n\n<p>In your theme may be similar code with some other function name, search and do same. Hope it will help you.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 301430, "author": "Omry Biton", "author_id": 142174, "author_profile": "https://wordpress.stackexchange.com/users/142174", "pm_score": 0, "selected": false, "text": "<p>In my template it does not exist, I went to a single.php file\nI think I found something similar, I'll copy the code here</p>\n\n<pre><code>&lt;div class=\"entry-meta\"&gt;\n &lt;?php if ( po_single_metadata_show( 'author' ) ) : ?&gt;\n &lt;span class=\"entry-user vcard author\"&gt;&lt;?php echo get_avatar( get_the_author_meta( 'email' ), '24' ); ?&gt; &lt;?php the_author_link(); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;?php if ( po_single_metadata_show( 'date' ) ) : ?&gt;\n &lt;span&gt;&lt;time datetime=\"&lt;?php the_time('o-m-d'); ?&gt;\" class=\"entry-date date published updated\"&gt;&lt;a href=\"&lt;?php echo get_month_link( get_the_time('Y'), get_the_time('m') ); ?&gt;\"&gt;&lt;?php echo get_the_date(); ?&gt;&lt;/a&gt;&lt;/time&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;?php if ( po_single_metadata_show( 'time' ) ) : ?&gt;\n &lt;span class=\"entry-time\"&gt;&lt;?php echo get_the_time(); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;?php if ( po_single_metadata_show( 'comments' ) ) : ?&gt;\n &lt;span class=\"entry-comment\"&gt;&lt;?php comments_popup_link( __( 'No Comments', 'pojo' ), __( 'One Comment', 'pojo' ), __( '% Comments', 'pojo' ), 'comments' ); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2018/04/21
[ "https://wordpress.stackexchange.com/questions/301438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103292/" ]
I have made two dropdown list which is a custom fields. **Custom Field 1** :- industry **Values of Custom Field 1** :- financial\_services,ecommerce,insurances, etc. **Custom Field 2** :- primary\_functionality **Values of Custom Field 2** :- platform\_decision\_engine,user\_authentication,data\_provider\_verification etc. And My **Post Type Name** is :- providers. Now, I want to fetch posts with multiple custom fields. So, I have tried this query. But it's not working. ``` $args = array( 'numberposts' => -1, 'post_type' => 'providers', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'industry', 'value' => 'financial_services', 'compare' => '=' ), array( 'key' => 'primary_functionality', 'value' => 'platform_decision_engine', 'compare' => '=' ) ) ); ``` Even I tried with for single custom field but it's also not working. ``` // args $args = array( 'numberposts' => -1, 'post_type' => 'providers', 'meta_key' => 'industry', 'meta_value' => 'financial_services' ); ``` I'm not that much experienced in wordpress. I have read wordpress document but nothing works. I'm confused about **relation** and **compare** in this query.
I don't know which theme your are using, I am explaining you same thing for twenty seventeen theme, go to wp-content\themes\twentyseventeen\inc\template-tags.php, You will find function twentyseventeen\_time\_link() there. In this function you will get code as like ``` return sprintf( /* translators: %s: post date */ __( '<span class="screen-reader-text">Posted on</span> %s', 'twentyseventeen' ), '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>' ); ``` Remove 'a' tag and it will become as like ``` return sprintf( /* translators: %s: post date */ __( '<span class="screen-reader-text">Posted on</span> %s', 'twentyseventeen' ), $time_string ); ``` In your theme may be similar code with some other function name, search and do same. Hope it will help you. Thanks
301,484
<p>I have this line of code : </p> <pre><code> $out .= get_the_post_thumbnail('', '', array( 'alt' =&gt; the_title_attribute (array('echo' =&gt; 0) ), 'class' =&gt; 'img-responsive', 'srcset' =&gt; get_the_post_thumbnail_url( "xs" ) ) ); </code></pre> <p>Which is wrong (in respect to the srcset attribute implementation) I'm trying to add srcset/sizes to this, and I'm sure I could do it the easy way and just do as I would normally and add all of the sizes/image sizes manually but this would create several unnecessary lines of code and after doing some research I've come across functions like </p> <ul> <li>wp_calculate_image_sizes(); </li> <li>wp_get_attachment_image_srcset();</li> <li>wp_get_attachment_image_sizes(); </li> <li>wp_add_image_srcset_and_sizes();</li> </ul> <p>And I believe they would be better to use but after doing some research I haven't been able to find a conclusive way of implementing them, the furthest I've gotten is to see the srcset attribute appear but having empty quotes.</p> <p>I've also seen someone mention that if the uploaded image sizes don't have an identical aspect ratio as the original image that none of these functions will work. If anyone has any example/advice I could refer to for adding <code>srcset</code> an ajax-served image, I would be very greatful.</p>
[ { "answer_id": 301488, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_get_attachment_image_srcset</code> is the key here:</p>\n\n<pre><code>wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null )\n</code></pre>\n\n<p>I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with <code>get_post_thumbnail_id</code> you should be able to generate <code>srcset</code> values.</p>\n\n<p>But also keep in mind that while googling, every question I found was asking how to remove <code>srcset</code> not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set <code>srcset</code> at all, and let WP set it for you.</p>\n" }, { "answer_id": 301665, "author": "dan178", "author_id": 142209, "author_profile": "https://wordpress.stackexchange.com/users/142209", "pm_score": 0, "selected": false, "text": "<p>I ended up using a function that I found on codepen and modifying it slightly. \nEdit: It's also worth noting that wp_get_attachment_image_src() returned 0 for all of the image widths so I created my own array of widths and assigned them that way. (Wish I could find a use for these neat built-in methods)</p>\n\n<pre><code>function srcset_post_thumbnail($defaultSize = 'm')\n{\n $thumbnailSizes = [\n 'xs',\n 's',\n 'm',\n 'l',\n 'xl'\n ];\n $html = '&lt;img sizes=\"';\n $html .= '(max-width: 30em) 100vw, ';\n $html .= '(max-width: 50em) 50vw, ';\n $html .= 'calc(33vw - 100px)\" ';\n $html .= 'srcset=\"';\n $thumb_id = get_post_thumbnail_id();\n for ($i = 0; $i &lt; count($thumbnailSizes); $i++) {\n $thumb = wp_get_attachment_image_src($thumb_id, $thumbnailSizes[$i], true);\n\n $url = $thumb[0];\n $width = $thumb[1];\n\n $html .= $url . ' ' . $width . 'w';\n\n if ($i &lt; count($thumbnailSizes) - 1) {\n $html .= ', ';\n }\n }\n $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);\n $thumbMedium = wp_get_attachment_image_src($thumb_id, $defaultSize, true);\n $html .= '\" ';\n $html .= 'src=\"' . $thumbMedium[0] . '\" alt=\"' . $alt . '\"&gt;';\n return $html;\n}\n</code></pre>\n" } ]
2018/04/22
[ "https://wordpress.stackexchange.com/questions/301484", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142209/" ]
I have this line of code : ``` $out .= get_the_post_thumbnail('', '', array( 'alt' => the_title_attribute (array('echo' => 0) ), 'class' => 'img-responsive', 'srcset' => get_the_post_thumbnail_url( "xs" ) ) ); ``` Which is wrong (in respect to the srcset attribute implementation) I'm trying to add srcset/sizes to this, and I'm sure I could do it the easy way and just do as I would normally and add all of the sizes/image sizes manually but this would create several unnecessary lines of code and after doing some research I've come across functions like * wp\_calculate\_image\_sizes(); * wp\_get\_attachment\_image\_srcset(); * wp\_get\_attachment\_image\_sizes(); * wp\_add\_image\_srcset\_and\_sizes(); And I believe they would be better to use but after doing some research I haven't been able to find a conclusive way of implementing them, the furthest I've gotten is to see the srcset attribute appear but having empty quotes. I've also seen someone mention that if the uploaded image sizes don't have an identical aspect ratio as the original image that none of these functions will work. If anyone has any example/advice I could refer to for adding `srcset` an ajax-served image, I would be very greatful.
`wp_get_attachment_image_srcset` is the key here: ``` wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null ) ``` I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with `get_post_thumbnail_id` you should be able to generate `srcset` values. But also keep in mind that while googling, every question I found was asking how to remove `srcset` not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set `srcset` at all, and let WP set it for you.
301,522
<p><strong>Hello Guys</strong></p> <p>I have a running business website for a company that have a lot of plugins and user database ext... The issue that we want to create a fresh WordPress installation + a totally new theme , we need to edit the new theme then import all database including users/posts/comments after that put the new template online .</p> <p>The question is how can be this done am so confused, can i edit the template then import the database or first import db then edit template , also now am using BackupBuddy but unfortunatley this plugin clone the current site so its not usefull i think .</p> <p>Thank you in advance </p>
[ { "answer_id": 301488, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_get_attachment_image_srcset</code> is the key here:</p>\n\n<pre><code>wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null )\n</code></pre>\n\n<p>I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with <code>get_post_thumbnail_id</code> you should be able to generate <code>srcset</code> values.</p>\n\n<p>But also keep in mind that while googling, every question I found was asking how to remove <code>srcset</code> not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set <code>srcset</code> at all, and let WP set it for you.</p>\n" }, { "answer_id": 301665, "author": "dan178", "author_id": 142209, "author_profile": "https://wordpress.stackexchange.com/users/142209", "pm_score": 0, "selected": false, "text": "<p>I ended up using a function that I found on codepen and modifying it slightly. \nEdit: It's also worth noting that wp_get_attachment_image_src() returned 0 for all of the image widths so I created my own array of widths and assigned them that way. (Wish I could find a use for these neat built-in methods)</p>\n\n<pre><code>function srcset_post_thumbnail($defaultSize = 'm')\n{\n $thumbnailSizes = [\n 'xs',\n 's',\n 'm',\n 'l',\n 'xl'\n ];\n $html = '&lt;img sizes=\"';\n $html .= '(max-width: 30em) 100vw, ';\n $html .= '(max-width: 50em) 50vw, ';\n $html .= 'calc(33vw - 100px)\" ';\n $html .= 'srcset=\"';\n $thumb_id = get_post_thumbnail_id();\n for ($i = 0; $i &lt; count($thumbnailSizes); $i++) {\n $thumb = wp_get_attachment_image_src($thumb_id, $thumbnailSizes[$i], true);\n\n $url = $thumb[0];\n $width = $thumb[1];\n\n $html .= $url . ' ' . $width . 'w';\n\n if ($i &lt; count($thumbnailSizes) - 1) {\n $html .= ', ';\n }\n }\n $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);\n $thumbMedium = wp_get_attachment_image_src($thumb_id, $defaultSize, true);\n $html .= '\" ';\n $html .= 'src=\"' . $thumbMedium[0] . '\" alt=\"' . $alt . '\"&gt;';\n return $html;\n}\n</code></pre>\n" } ]
2018/04/22
[ "https://wordpress.stackexchange.com/questions/301522", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142241/" ]
**Hello Guys** I have a running business website for a company that have a lot of plugins and user database ext... The issue that we want to create a fresh WordPress installation + a totally new theme , we need to edit the new theme then import all database including users/posts/comments after that put the new template online . The question is how can be this done am so confused, can i edit the template then import the database or first import db then edit template , also now am using BackupBuddy but unfortunatley this plugin clone the current site so its not usefull i think . Thank you in advance
`wp_get_attachment_image_srcset` is the key here: ``` wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null ) ``` I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with `get_post_thumbnail_id` you should be able to generate `srcset` values. But also keep in mind that while googling, every question I found was asking how to remove `srcset` not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set `srcset` at all, and let WP set it for you.
301,538
<p>I am trying to use a simple <code>publish_post / publish_page</code> hook to get the URL of the post/page when it is either published or updated so I can later turn it into a static page.</p> <p>Is it possible to add this hook outside of the theme functions.php file, because this is far more preferable to me? I also am unsure how to grab the file location / URL from the result? Any help is very much appreciated.</p>
[ { "answer_id": 301488, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_get_attachment_image_srcset</code> is the key here:</p>\n\n<pre><code>wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null )\n</code></pre>\n\n<p>I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with <code>get_post_thumbnail_id</code> you should be able to generate <code>srcset</code> values.</p>\n\n<p>But also keep in mind that while googling, every question I found was asking how to remove <code>srcset</code> not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set <code>srcset</code> at all, and let WP set it for you.</p>\n" }, { "answer_id": 301665, "author": "dan178", "author_id": 142209, "author_profile": "https://wordpress.stackexchange.com/users/142209", "pm_score": 0, "selected": false, "text": "<p>I ended up using a function that I found on codepen and modifying it slightly. \nEdit: It's also worth noting that wp_get_attachment_image_src() returned 0 for all of the image widths so I created my own array of widths and assigned them that way. (Wish I could find a use for these neat built-in methods)</p>\n\n<pre><code>function srcset_post_thumbnail($defaultSize = 'm')\n{\n $thumbnailSizes = [\n 'xs',\n 's',\n 'm',\n 'l',\n 'xl'\n ];\n $html = '&lt;img sizes=\"';\n $html .= '(max-width: 30em) 100vw, ';\n $html .= '(max-width: 50em) 50vw, ';\n $html .= 'calc(33vw - 100px)\" ';\n $html .= 'srcset=\"';\n $thumb_id = get_post_thumbnail_id();\n for ($i = 0; $i &lt; count($thumbnailSizes); $i++) {\n $thumb = wp_get_attachment_image_src($thumb_id, $thumbnailSizes[$i], true);\n\n $url = $thumb[0];\n $width = $thumb[1];\n\n $html .= $url . ' ' . $width . 'w';\n\n if ($i &lt; count($thumbnailSizes) - 1) {\n $html .= ', ';\n }\n }\n $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);\n $thumbMedium = wp_get_attachment_image_src($thumb_id, $defaultSize, true);\n $html .= '\" ';\n $html .= 'src=\"' . $thumbMedium[0] . '\" alt=\"' . $alt . '\"&gt;';\n return $html;\n}\n</code></pre>\n" } ]
2018/04/23
[ "https://wordpress.stackexchange.com/questions/301538", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142252/" ]
I am trying to use a simple `publish_post / publish_page` hook to get the URL of the post/page when it is either published or updated so I can later turn it into a static page. Is it possible to add this hook outside of the theme functions.php file, because this is far more preferable to me? I also am unsure how to grab the file location / URL from the result? Any help is very much appreciated.
`wp_get_attachment_image_srcset` is the key here: ``` wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null ) ``` I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with `get_post_thumbnail_id` you should be able to generate `srcset` values. But also keep in mind that while googling, every question I found was asking how to remove `srcset` not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set `srcset` at all, and let WP set it for you.
301,540
<p>Thank you in advance,</p> <p>I know that if you want to edit the appearence of the search page there is search.php file that you can mess with.</p> <p>I am using TOTAL theme in wordpress, I have decided to customize the themes POSTS page appearance completely, I did inspect element to look and tried matching the code with themes files but I could not find the codes. Where are the codes written. Which file should I look into.</p>
[ { "answer_id": 301488, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>wp_get_attachment_image_srcset</code> is the key here:</p>\n\n<pre><code>wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null )\n</code></pre>\n\n<p>I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with <code>get_post_thumbnail_id</code> you should be able to generate <code>srcset</code> values.</p>\n\n<p>But also keep in mind that while googling, every question I found was asking how to remove <code>srcset</code> not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set <code>srcset</code> at all, and let WP set it for you.</p>\n" }, { "answer_id": 301665, "author": "dan178", "author_id": 142209, "author_profile": "https://wordpress.stackexchange.com/users/142209", "pm_score": 0, "selected": false, "text": "<p>I ended up using a function that I found on codepen and modifying it slightly. \nEdit: It's also worth noting that wp_get_attachment_image_src() returned 0 for all of the image widths so I created my own array of widths and assigned them that way. (Wish I could find a use for these neat built-in methods)</p>\n\n<pre><code>function srcset_post_thumbnail($defaultSize = 'm')\n{\n $thumbnailSizes = [\n 'xs',\n 's',\n 'm',\n 'l',\n 'xl'\n ];\n $html = '&lt;img sizes=\"';\n $html .= '(max-width: 30em) 100vw, ';\n $html .= '(max-width: 50em) 50vw, ';\n $html .= 'calc(33vw - 100px)\" ';\n $html .= 'srcset=\"';\n $thumb_id = get_post_thumbnail_id();\n for ($i = 0; $i &lt; count($thumbnailSizes); $i++) {\n $thumb = wp_get_attachment_image_src($thumb_id, $thumbnailSizes[$i], true);\n\n $url = $thumb[0];\n $width = $thumb[1];\n\n $html .= $url . ' ' . $width . 'w';\n\n if ($i &lt; count($thumbnailSizes) - 1) {\n $html .= ', ';\n }\n }\n $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);\n $thumbMedium = wp_get_attachment_image_src($thumb_id, $defaultSize, true);\n $html .= '\" ';\n $html .= 'src=\"' . $thumbMedium[0] . '\" alt=\"' . $alt . '\"&gt;';\n return $html;\n}\n</code></pre>\n" } ]
2018/04/23
[ "https://wordpress.stackexchange.com/questions/301540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125422/" ]
Thank you in advance, I know that if you want to edit the appearence of the search page there is search.php file that you can mess with. I am using TOTAL theme in wordpress, I have decided to customize the themes POSTS page appearance completely, I did inspect element to look and tried matching the code with themes files but I could not find the codes. Where are the codes written. Which file should I look into.
`wp_get_attachment_image_srcset` is the key here: ``` wp_get_attachment_image_srcset( int $attachment_id, array|string $size = 'medium', array $image_meta = null ) ``` I believe the missing information you lack, is that post thumbnails are actually an attachment ID. In combination with `get_post_thumbnail_id` you should be able to generate `srcset` values. But also keep in mind that while googling, every question I found was asking how to remove `srcset` not add. Apparently what you wanted was actually added in WP 4.4. The answer might actually be to not set `srcset` at all, and let WP set it for you.
301,593
<p>I am trying to build a query that returns all posts, with a meta value that exists in a set of values.</p> <p>My posts have a meta key called <code>Asin_unique</code> and I want to find all posts, that have the value <code>B006MWDNVI</code>,<code>B00BCMCIS2</code>, or <code>B01ARRJFGA</code> in this field.</p> <p>This is what I have built so far, but it only returns me the post with <code>B00BCMCIS2</code>, not the other ones. What do I have to change to make it work?</p> <pre><code>$args = array( 'post_status' =&gt; 'any', 'post_type' =&gt; 'any', 'numberposts' =&gt; -1, 'meta_query' =&gt; array( array( 'key' =&gt; 'Asin_unique', 'value' =&gt; '(B006MWDNVI,B00BCMCIS2,B01ARRJFGA)', 'compare' =&gt; 'IN', ) ) ); $posts = get_posts( $args ); </code></pre>
[ { "answer_id": 301597, "author": "Munish Kumar", "author_id": 142176, "author_profile": "https://wordpress.stackexchange.com/users/142176", "pm_score": 2, "selected": false, "text": "<p>Check This Will Work for you.</p>\n\n<pre><code>$args = array(\n 'post_status' =&gt; 'any',\n 'post_type' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'Asin_unique',\n 'value' =&gt; array('B006MWDNVI','B00BCMCIS2','B01ARRJFGA'),\n 'compare' =&gt; 'IN',\n )\n )\n);\n\n$posts = get_posts( $args );\n</code></pre>\n\n<p>Help Link: <a href=\"https://rudrastyh.com/wordpress/meta_query.html\" rel=\"nofollow noreferrer\">https://rudrastyh.com/wordpress/meta_query.html</a></p>\n" }, { "answer_id": 301602, "author": "TheKidsWantDjent", "author_id": 118091, "author_profile": "https://wordpress.stackexchange.com/users/118091", "pm_score": 0, "selected": false, "text": "<p>Leaving out the brackets in the value seems to do the trick. I was mislead by how IN is usually formatted in SQL and thought it would be the same with WP queries, but you have to leave them out:</p>\n\n<pre><code>$args = array(\n 'post_status' =&gt; 'any',\n 'post_type' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'Asin_unique',\n 'value' =&gt; 'B006MWDNVI,B00BCMCIS2,B01ARRJFGA',\n 'compare' =&gt; 'IN',\n )\n )\n);\n\n$posts = get_posts( $args );\n</code></pre>\n" } ]
2018/04/23
[ "https://wordpress.stackexchange.com/questions/301593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118091/" ]
I am trying to build a query that returns all posts, with a meta value that exists in a set of values. My posts have a meta key called `Asin_unique` and I want to find all posts, that have the value `B006MWDNVI`,`B00BCMCIS2`, or `B01ARRJFGA` in this field. This is what I have built so far, but it only returns me the post with `B00BCMCIS2`, not the other ones. What do I have to change to make it work? ``` $args = array( 'post_status' => 'any', 'post_type' => 'any', 'numberposts' => -1, 'meta_query' => array( array( 'key' => 'Asin_unique', 'value' => '(B006MWDNVI,B00BCMCIS2,B01ARRJFGA)', 'compare' => 'IN', ) ) ); $posts = get_posts( $args ); ```
Check This Will Work for you. ``` $args = array( 'post_status' => 'any', 'post_type' => 'any', 'numberposts' => -1, 'meta_query' => array( array( 'key' => 'Asin_unique', 'value' => array('B006MWDNVI','B00BCMCIS2','B01ARRJFGA'), 'compare' => 'IN', ) ) ); $posts = get_posts( $args ); ``` Help Link: <https://rudrastyh.com/wordpress/meta_query.html>
301,621
<p>Despite using;</p> <pre><code>$mysqli = new mysqli("localhost", "user", "pass", "db"); $mysqli-&gt;query('SET SQL_BIG_SELECTS = 1'); $mysqli-&gt;query('SET MAX_JOIN_SIZE = 999'); $the_query = new WP_Query( $args ); </code></pre> <p>I'm receiving;</p> <blockquote> <p>[23-Apr-2018 14:37:31 UTC] WordPress database error The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay for query... WP_Query->__construct, WP_Query->query, WP_Query->get_posts</p> </blockquote> <p>The original query works, but stopped once I added another meta query that exceeded the cap despite that additional meta query working when I comment out another. </p> <p>How can I get the $mysqli query settings to apply to $the_query?</p>
[ { "answer_id": 301597, "author": "Munish Kumar", "author_id": 142176, "author_profile": "https://wordpress.stackexchange.com/users/142176", "pm_score": 2, "selected": false, "text": "<p>Check This Will Work for you.</p>\n\n<pre><code>$args = array(\n 'post_status' =&gt; 'any',\n 'post_type' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'Asin_unique',\n 'value' =&gt; array('B006MWDNVI','B00BCMCIS2','B01ARRJFGA'),\n 'compare' =&gt; 'IN',\n )\n )\n);\n\n$posts = get_posts( $args );\n</code></pre>\n\n<p>Help Link: <a href=\"https://rudrastyh.com/wordpress/meta_query.html\" rel=\"nofollow noreferrer\">https://rudrastyh.com/wordpress/meta_query.html</a></p>\n" }, { "answer_id": 301602, "author": "TheKidsWantDjent", "author_id": 118091, "author_profile": "https://wordpress.stackexchange.com/users/118091", "pm_score": 0, "selected": false, "text": "<p>Leaving out the brackets in the value seems to do the trick. I was mislead by how IN is usually formatted in SQL and thought it would be the same with WP queries, but you have to leave them out:</p>\n\n<pre><code>$args = array(\n 'post_status' =&gt; 'any',\n 'post_type' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'Asin_unique',\n 'value' =&gt; 'B006MWDNVI,B00BCMCIS2,B01ARRJFGA',\n 'compare' =&gt; 'IN',\n )\n )\n);\n\n$posts = get_posts( $args );\n</code></pre>\n" } ]
2018/04/23
[ "https://wordpress.stackexchange.com/questions/301621", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134867/" ]
Despite using; ``` $mysqli = new mysqli("localhost", "user", "pass", "db"); $mysqli->query('SET SQL_BIG_SELECTS = 1'); $mysqli->query('SET MAX_JOIN_SIZE = 999'); $the_query = new WP_Query( $args ); ``` I'm receiving; > > [23-Apr-2018 14:37:31 UTC] WordPress database error > The SELECT would examine more than MAX\_JOIN\_SIZE rows; > check your WHERE and use SET SQL\_BIG\_SELECTS=1 > or SET MAX\_JOIN\_SIZE=# if the SELECT is okay for query... > WP\_Query->\_\_construct, WP\_Query->query, WP\_Query->get\_posts > > > The original query works, but stopped once I added another meta query that exceeded the cap despite that additional meta query working when I comment out another. How can I get the $mysqli query settings to apply to $the\_query?
Check This Will Work for you. ``` $args = array( 'post_status' => 'any', 'post_type' => 'any', 'numberposts' => -1, 'meta_query' => array( array( 'key' => 'Asin_unique', 'value' => array('B006MWDNVI','B00BCMCIS2','B01ARRJFGA'), 'compare' => 'IN', ) ) ); $posts = get_posts( $args ); ``` Help Link: <https://rudrastyh.com/wordpress/meta_query.html>
301,647
<p>As an example, my site is <code>mysite.com</code></p> <p>I want <code>mysite.com/wordpress_plugins</code> to return the output of <code>get_plugins()</code> from <a href="https://codex.wordpress.org/Function_Reference/get_plugins" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/get_plugins</a> </p> <p>How can I do this? </p>
[ { "answer_id": 301597, "author": "Munish Kumar", "author_id": 142176, "author_profile": "https://wordpress.stackexchange.com/users/142176", "pm_score": 2, "selected": false, "text": "<p>Check This Will Work for you.</p>\n\n<pre><code>$args = array(\n 'post_status' =&gt; 'any',\n 'post_type' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'Asin_unique',\n 'value' =&gt; array('B006MWDNVI','B00BCMCIS2','B01ARRJFGA'),\n 'compare' =&gt; 'IN',\n )\n )\n);\n\n$posts = get_posts( $args );\n</code></pre>\n\n<p>Help Link: <a href=\"https://rudrastyh.com/wordpress/meta_query.html\" rel=\"nofollow noreferrer\">https://rudrastyh.com/wordpress/meta_query.html</a></p>\n" }, { "answer_id": 301602, "author": "TheKidsWantDjent", "author_id": 118091, "author_profile": "https://wordpress.stackexchange.com/users/118091", "pm_score": 0, "selected": false, "text": "<p>Leaving out the brackets in the value seems to do the trick. I was mislead by how IN is usually formatted in SQL and thought it would be the same with WP queries, but you have to leave them out:</p>\n\n<pre><code>$args = array(\n 'post_status' =&gt; 'any',\n 'post_type' =&gt; 'any',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'Asin_unique',\n 'value' =&gt; 'B006MWDNVI,B00BCMCIS2,B01ARRJFGA',\n 'compare' =&gt; 'IN',\n )\n )\n);\n\n$posts = get_posts( $args );\n</code></pre>\n" } ]
2018/04/23
[ "https://wordpress.stackexchange.com/questions/301647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/139891/" ]
As an example, my site is `mysite.com` I want `mysite.com/wordpress_plugins` to return the output of `get_plugins()` from <https://codex.wordpress.org/Function_Reference/get_plugins> How can I do this?
Check This Will Work for you. ``` $args = array( 'post_status' => 'any', 'post_type' => 'any', 'numberposts' => -1, 'meta_query' => array( array( 'key' => 'Asin_unique', 'value' => array('B006MWDNVI','B00BCMCIS2','B01ARRJFGA'), 'compare' => 'IN', ) ) ); $posts = get_posts( $args ); ``` Help Link: <https://rudrastyh.com/wordpress/meta_query.html>
301,649
<p>What is the secure way to use wp_get_attachment_image() in a template?</p>
[ { "answer_id": 301650, "author": "Levi Dulstein", "author_id": 101988, "author_profile": "https://wordpress.stackexchange.com/users/101988", "pm_score": 3, "selected": true, "text": "<p>Running the output through escaping function should be just fine.\nYou can either use <code>wp_kses_post()</code>, which by default allows the same html attributes that you would use in the post content (<a href=\"https://developer.wordpress.org/reference/functions/wp_kses_post/\" rel=\"nofollow noreferrer\">see in code reference</a>):</p>\n<pre><code>echo wp_kses_post( wp_get_attachment_image( $image_id ) ); \n</code></pre>\n<p>or if you want to be more precise and strict, you can pass an <a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\">array with allowed attributes</a> for that particular context, like so:</p>\n<pre><code>echo wp_kses( wp_get_attachment_image( $image_id ), [\n 'img' =&gt; [\n 'src' =&gt; true,\n 'srcset' =&gt; true,\n 'sizes' =&gt; true,\n 'class' =&gt; true,\n 'id' =&gt; true,\n 'width' =&gt; true,\n 'height' =&gt; true,\n 'alt' =&gt; true,\n 'loading' =&gt; true,\n 'decoding' =&gt; true,\n ],\n] );\n</code></pre>\n<p>It's up to you to decide what is allowed, just change the array contents to adjust to your needs!</p>\n" }, { "answer_id": 388841, "author": "Ivan Frolov", "author_id": 178434, "author_profile": "https://wordpress.stackexchange.com/users/178434", "pm_score": 0, "selected": false, "text": "<p>For now (28 of May 2021) <code>wp_kses</code> does not output <code>srcset</code> and <code>sizes</code> attributes (although ticket <a href=\"https://core.trac.wordpress.org/ticket/29807\" rel=\"nofollow noreferrer\">created ticket</a> 7 years ago...).</p>\n<p>But it's easy to enable via filter:</p>\n<pre><code>function starter_wpkses_post_tags( $tags, $context ) {\n $tags['img']['sizes'] = true;\n $tags['img']['srcset'] = true;\n return $tags;\n}\nadd_filter( 'wp_kses_allowed_html', 'starter_wpkses_post_tags', 10, 2 );\n</code></pre>\n<p>Nowadays all modern browsers supports <strong>webp</strong> so it could be useful also to enable additional attributes for <code>source</code> tag, so full solution for <code>srcset</code> and <code>sizes</code> for both <code>img</code> and <code>source</code> tags is:</p>\n<pre><code>function starter_wpkses_post_tags( $tags, $context ) {\n $tags['img']['sizes'] = true;\n $tags['img']['srcset'] = true;\n $tags['source'] = array(\n 'srcset' =&gt; true,\n 'sizes' =&gt; true,\n 'type' =&gt; true,\n );\n return $tags;\n}\nadd_filter( 'wp_kses_allowed_html', 'starter_wpkses_post_tags', 10, 2 );\n</code></pre>\n" } ]
2018/04/23
[ "https://wordpress.stackexchange.com/questions/301649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59289/" ]
What is the secure way to use wp\_get\_attachment\_image() in a template?
Running the output through escaping function should be just fine. You can either use `wp_kses_post()`, which by default allows the same html attributes that you would use in the post content ([see in code reference](https://developer.wordpress.org/reference/functions/wp_kses_post/)): ``` echo wp_kses_post( wp_get_attachment_image( $image_id ) ); ``` or if you want to be more precise and strict, you can pass an [array with allowed attributes](https://developer.wordpress.org/reference/functions/wp_kses/) for that particular context, like so: ``` echo wp_kses( wp_get_attachment_image( $image_id ), [ 'img' => [ 'src' => true, 'srcset' => true, 'sizes' => true, 'class' => true, 'id' => true, 'width' => true, 'height' => true, 'alt' => true, 'loading' => true, 'decoding' => true, ], ] ); ``` It's up to you to decide what is allowed, just change the array contents to adjust to your needs!
301,670
<p>I have an existing website with pages like:</p> <pre><code>http://www.website.come/page1.htm http://www.website.come/page2.htm http://www.website.come/page3.htm </code></pre> <p>etc.</p> <p>And I have redesigned my website in WordPress that has links like:</p> <pre><code>http://www.website.come/page1/ http://www.website.come/page2/ http://www.website.come/page3/ </code></pre> <p>but I need old links because they are posted on various websites and I don't want to redirect those links.</p> <p>So, when someone clicks on:</p> <pre><code>http://www.website.come/page1.htm </code></pre> <p>without redirection, it should show the content of:</p> <pre><code>http://www.website.come/page1/ </code></pre> <p>and so on...</p> <p>So, I want that when anyone opens an old link like</p> <pre><code>http://www.website.come/page1.htm </code></pre> <p>in my new WordPress based website, I want the user to neither redirect nor show 404 error. Instead, I want that URL to stay as it is but show the content of the page</p> <pre><code>http://www.website.come/page1/ </code></pre>
[ { "answer_id": 301672, "author": "ssk8323", "author_id": 142341, "author_profile": "https://wordpress.stackexchange.com/users/142341", "pm_score": 1, "selected": false, "text": "<p>Sorry for incomplete answer,\nUse the 301 redirects.\nThis link give an idea about redirects <a href=\"https://moz.com/learn/seo/redirection\" rel=\"nofollow noreferrer\">https://moz.com/learn/seo/redirection</a></p>\n\n<p><a href=\"https://wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/simple-301-redirects/</a></p>\n\n<p>For the wordpres there are free good plugins for add <em>html / htm</em> extension to urls.</p>\n\n<p>This for - \"<em>.html</em>\"\n<a href=\"https://wordpress.org/plugins/html-in-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/html-in-url/</a></p>\n\n<p>I think you can edit it and change it to \"<em>.htm</em>\"</p>\n\n<p>If you dont want to use plugins,follow this and change it according to your requirement,</p>\n\n<p><a href=\"http://carlofontanos.com/add-html-extension-to-permalinks/\" rel=\"nofollow noreferrer\">http://carlofontanos.com/add-html-extension-to-permalinks/</a></p>\n" }, { "answer_id": 301680, "author": "robwatson_dev", "author_id": 137115, "author_profile": "https://wordpress.stackexchange.com/users/137115", "pm_score": 1, "selected": false, "text": "<p>I know this isn't what you've asked for but you'd be better IMO to 301 redirect these old links. </p>\n\n<p>If you have access to the .htaccess file (in the root of your site) then you can use the following code</p>\n\n<pre><code>RedirectMatch 301 page1.htm http://www.website.com/page1/\nRedirectMatch 301 page2.htm http://www.website.com/page2/\nRedirectMatch 301 page3.htm http://www.website.com/page3/\n</code></pre>\n\n<p>Place this above the code added by WordPress</p>\n\n<p>A 301 Redirect tells search engines that the resource has permanently moved, any existing Page Rank your page currently has on Google for example will move across with it. They also redirect any visitor who hits the old URL to the new one.</p>\n\n<p>Failing that you can install a plugin to do this such as <a href=\"https://en-gb.wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">Simple 301 Redirects</a>.</p>\n\n<p>However if you insist on having the .htm extension then I think you can change the rewrite rule WordPress created in your .htaccess file (untested)</p>\n\n<pre><code>Options +FollowSymlinks\nRewriteEngine on\nRewriteRule ^(.*) $1.htm [nc]\n</code></pre>\n" }, { "answer_id": 301714, "author": "Sovit Tamrakar", "author_id": 43861, "author_profile": "https://wordpress.stackexchange.com/users/43861", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://github.com/WPPress/WPUrlMapper\" rel=\"nofollow noreferrer\">https://github.com/WPPress/WPUrlMapper</a></p>\n\n<p>This could be what you are looking for.</p>\n\n<p>Provides custom meta box to enter old url which would be mapped to new url without redirection.</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142337/" ]
I have an existing website with pages like: ``` http://www.website.come/page1.htm http://www.website.come/page2.htm http://www.website.come/page3.htm ``` etc. And I have redesigned my website in WordPress that has links like: ``` http://www.website.come/page1/ http://www.website.come/page2/ http://www.website.come/page3/ ``` but I need old links because they are posted on various websites and I don't want to redirect those links. So, when someone clicks on: ``` http://www.website.come/page1.htm ``` without redirection, it should show the content of: ``` http://www.website.come/page1/ ``` and so on... So, I want that when anyone opens an old link like ``` http://www.website.come/page1.htm ``` in my new WordPress based website, I want the user to neither redirect nor show 404 error. Instead, I want that URL to stay as it is but show the content of the page ``` http://www.website.come/page1/ ```
Sorry for incomplete answer, Use the 301 redirects. This link give an idea about redirects <https://moz.com/learn/seo/redirection> <https://wordpress.org/plugins/simple-301-redirects/> For the wordpres there are free good plugins for add *html / htm* extension to urls. This for - "*.html*" <https://wordpress.org/plugins/html-in-url/> I think you can edit it and change it to "*.htm*" If you dont want to use plugins,follow this and change it according to your requirement, <http://carlofontanos.com/add-html-extension-to-permalinks/>
301,675
<p>I am new to plugin develop and I have a problem with settings page of my new plugin.</p> <p>My page seems to save correctly settings data to wordpress database, but after a few hours/days value stored on database disappear.</p> <p>the code of the main page of the plugin is:</p> <pre><code>//security defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); //define path define('ffita_gads_DIR', plugin_dir_path(__FILE__)); require_once(ffita_gads_DIR.'inc/settings.php'); //add shortcode add_shortcode('ffita_gads', 'ffita_view_ads'); /* Runs on plugin deactivation*/ register_deactivation_hook( __FILE__, 'ffita_gads_remove' ); function ffita_gads_remove() { /* Deletes shortcodes */ remove_shortcode ('ffita_gads'); } //add menu add_action('admin_menu', 'ffita_gads_admin_menu'); function ffita_gads_admin_menu () { // richiama la funzione ffi_gads_setting_page definita nel file settings.php add_menu_page( 'Impostazioni', 'FFI G Ads settings', 'manage_options', 'ffita_gads_option', 'ffi_gads_setting_page', 'dashicons-images-alt' ); } </code></pre> <p>The code of setting page is:</p> <pre><code>function ffi_gads_setting_page() { // security defined('ABSPATH') or die('No script kiddies please!'); // verifica che l'utente possa gestire le impostazioni if (!current_user_can('manage_options')) { wp_die(__('You do not have sufficient permissions to access this page.', 'FFita G Ads')); } // form wordpress ?&gt; &lt;div class="wrap"&gt; &lt;h1 class="dashicons-before dashicons-admin-settings"&gt;FFItalia Options&lt;/h1&gt; &lt;form name="ffiset_gads_form" method="post" action="options.php"&gt; &lt;?php // add_settings_section callback is displayed here. For every new section we need to call settings_fields. settings_fields("ffita_gads_settings"); // all the add_settings_field callbacks is displayed here do_settings_sections("ffita_gads_settings"); ?&gt; &lt;table class="widefat" style="margin-top: 10px;"&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;h2&gt;Connection parameters&lt;/h2&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th scope="row" style="width: 15%;"&gt;ID VALUE&lt;/th&gt; &lt;td style="vertical-align: middle; width: 45%;"&gt;&lt;input type="text" name="ffita_gads_capub" value="&lt;?php echo esc_attr( get_option('ffita_gads_capub') ); ?&gt;" style="width: 90%" required /&gt;&lt;/td&gt; &lt;td&gt;ID value" .&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th scope="row" style="width: 15%;"&gt;IP debug&lt;/th&gt; &lt;td style="vertical-align: middle; width: 45%;"&gt;&lt;input type="text" name="ffita_gads_ipdebug" value="&lt;?php echo esc_attr( get_option('ffita_gads_ipdebug') ); ?&gt;" style="width: 90%"&gt;&lt;/td&gt; &lt;td&gt;Ip for debug....&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table class="widefat Product" style="margin-top: 10px;"&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;h2&gt;Parameter&lt;/h2&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th scope="row" style="width: 10%;"&gt;ID&lt;/th&gt; &lt;td style="width: 20%;"&gt;Product id&lt;/td&gt; &lt;td&gt;Product description&lt;/td&gt; &lt;td&gt;Shortcode&lt;/td&gt; &lt;/tr&gt; &lt;?php $Product_options = get_option('ffita_gads_option'); $num_Product = 0; if (empty($Product_options)) { $codice_html = "&lt;tr&gt;&lt;td colspan=4 bgcolor=red&gt;Imposta i dettagli di almeno un Product&lt;/td&gt;&lt;/tr&gt;"; $codice_html .= '&lt;tr&gt;&lt;td&gt;&lt;input type="text" size="2" name="listaProduct[1][Product1][id_shortcode_Product]" value="1" readonly&gt;&lt;/td&gt;'; $codice_html .= '&lt;td&gt;&lt;input type="text" name="listaProduct[1][Product1][id_Product]]" value="" required/&gt;&lt;/td&gt;'; $codice_html .= '&lt;td&gt;&lt;input type="text" name="listaProduct[1][Product1][desc_Product]]" value="" size="60"/&gt;&lt;/td&gt;'; $codice_html .= '&lt;td&gt;[ffita_gads id="1" ] &lt;/td&gt;&lt;/tr&gt;'; echo $codice_html; $num_Product++; } else { foreach ($Product_options as $dati_Product) { $html = '&lt;tr&gt;&lt;td&gt;&lt;input type="text" size="2" name="listaProduct[' . $dati_Product[id_shortcode_Product] . '][Product' . $dati_Product[id_shortcode_Product] . '][id_shortcode_Product]" value="' . $dati_Product[id_shortcode_Product] . '" readonly&gt;&lt;/td&gt;'; $html .= '&lt;td&gt;&lt;input type="text" name="listaProduct[' . $dati_Product[id_shortcode_Product] . '][Product' . $dati_Product[id_shortcode_Product] . '][id_Product]]" value="' . $dati_Product[id_Product] . '" required/&gt;&lt;/td&gt;'; $html .= '&lt;td&gt;&lt;input type="text" name="listaProduct[' . $dati_Product[id_shortcode_Product] . '][Product' . $dati_Product[id_shortcode_Product] . '][desc_Product]]" value="' . $dati_Product[desc_Product] . '" size="60"/&gt;&lt;/td&gt;'; $html .= '&lt;td&gt; [ffita_gads id="' . $dati_Product[id_shortcode_Product] . '" ]&lt;/td&gt;&lt;/tr&gt;'; echo $html; $num_Product++; } } ?&gt; &lt;/table&gt; &lt;div align="right"&gt; &lt;input type="button" value="Add Product" id="add_ban_but" data-value="&lt;?php echo $num_Product ?&gt;" /&gt; &lt;input type="button" value="Remove last Product" id="remove_ban_but" /&gt; &lt;/div&gt; &lt;input type="text" id="n_tot" name="ffita_n_tot" value="&lt;?php echo $num_Product; ?&gt;" /&gt; &lt;?php // Add the submit button to serialize the options submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } if (isset($_POST['submit'])) { // registra i dati dei Product $nuovi_Product = $_POST['listaProduct']; $array_Product = array(); // print_r ($nuovi_Product); foreach ($nuovi_Product as $key) { $nuovo_Product = $key; $array_Product = array_merge($array_Product, $nuovo_Product); } update_option('ffita_gads_option', $array_Product); // registra i dati ca-pub-xxxx $nuovo_ca = $_POST['ffita_gads_capub']; update_option('ffita_gads_capub', $nuovo_ca); // registra i dati ipdebug $nuovo_ipdeb = $_POST['ffita_gads_ipdebug']; update_option('ffita_gads_ipdebug', $nuovo_ipdeb); } function ffita_gads_option_init() { // registra il codice publisher ca-pub xxxx register_setting("ffita_gads_settings", "ffita_gads_capub"); // delete_option("ffita_gads_capub"); } add_action("admin_init", "ffita_gads_option_init"); </code></pre> <p>Any idea of the problem? many thanks in advance</p>
[ { "answer_id": 301672, "author": "ssk8323", "author_id": 142341, "author_profile": "https://wordpress.stackexchange.com/users/142341", "pm_score": 1, "selected": false, "text": "<p>Sorry for incomplete answer,\nUse the 301 redirects.\nThis link give an idea about redirects <a href=\"https://moz.com/learn/seo/redirection\" rel=\"nofollow noreferrer\">https://moz.com/learn/seo/redirection</a></p>\n\n<p><a href=\"https://wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/simple-301-redirects/</a></p>\n\n<p>For the wordpres there are free good plugins for add <em>html / htm</em> extension to urls.</p>\n\n<p>This for - \"<em>.html</em>\"\n<a href=\"https://wordpress.org/plugins/html-in-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/html-in-url/</a></p>\n\n<p>I think you can edit it and change it to \"<em>.htm</em>\"</p>\n\n<p>If you dont want to use plugins,follow this and change it according to your requirement,</p>\n\n<p><a href=\"http://carlofontanos.com/add-html-extension-to-permalinks/\" rel=\"nofollow noreferrer\">http://carlofontanos.com/add-html-extension-to-permalinks/</a></p>\n" }, { "answer_id": 301680, "author": "robwatson_dev", "author_id": 137115, "author_profile": "https://wordpress.stackexchange.com/users/137115", "pm_score": 1, "selected": false, "text": "<p>I know this isn't what you've asked for but you'd be better IMO to 301 redirect these old links. </p>\n\n<p>If you have access to the .htaccess file (in the root of your site) then you can use the following code</p>\n\n<pre><code>RedirectMatch 301 page1.htm http://www.website.com/page1/\nRedirectMatch 301 page2.htm http://www.website.com/page2/\nRedirectMatch 301 page3.htm http://www.website.com/page3/\n</code></pre>\n\n<p>Place this above the code added by WordPress</p>\n\n<p>A 301 Redirect tells search engines that the resource has permanently moved, any existing Page Rank your page currently has on Google for example will move across with it. They also redirect any visitor who hits the old URL to the new one.</p>\n\n<p>Failing that you can install a plugin to do this such as <a href=\"https://en-gb.wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">Simple 301 Redirects</a>.</p>\n\n<p>However if you insist on having the .htm extension then I think you can change the rewrite rule WordPress created in your .htaccess file (untested)</p>\n\n<pre><code>Options +FollowSymlinks\nRewriteEngine on\nRewriteRule ^(.*) $1.htm [nc]\n</code></pre>\n" }, { "answer_id": 301714, "author": "Sovit Tamrakar", "author_id": 43861, "author_profile": "https://wordpress.stackexchange.com/users/43861", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://github.com/WPPress/WPUrlMapper\" rel=\"nofollow noreferrer\">https://github.com/WPPress/WPUrlMapper</a></p>\n\n<p>This could be what you are looking for.</p>\n\n<p>Provides custom meta box to enter old url which would be mapped to new url without redirection.</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301675", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142301/" ]
I am new to plugin develop and I have a problem with settings page of my new plugin. My page seems to save correctly settings data to wordpress database, but after a few hours/days value stored on database disappear. the code of the main page of the plugin is: ``` //security defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); //define path define('ffita_gads_DIR', plugin_dir_path(__FILE__)); require_once(ffita_gads_DIR.'inc/settings.php'); //add shortcode add_shortcode('ffita_gads', 'ffita_view_ads'); /* Runs on plugin deactivation*/ register_deactivation_hook( __FILE__, 'ffita_gads_remove' ); function ffita_gads_remove() { /* Deletes shortcodes */ remove_shortcode ('ffita_gads'); } //add menu add_action('admin_menu', 'ffita_gads_admin_menu'); function ffita_gads_admin_menu () { // richiama la funzione ffi_gads_setting_page definita nel file settings.php add_menu_page( 'Impostazioni', 'FFI G Ads settings', 'manage_options', 'ffita_gads_option', 'ffi_gads_setting_page', 'dashicons-images-alt' ); } ``` The code of setting page is: ``` function ffi_gads_setting_page() { // security defined('ABSPATH') or die('No script kiddies please!'); // verifica che l'utente possa gestire le impostazioni if (!current_user_can('manage_options')) { wp_die(__('You do not have sufficient permissions to access this page.', 'FFita G Ads')); } // form wordpress ?> <div class="wrap"> <h1 class="dashicons-before dashicons-admin-settings">FFItalia Options</h1> <form name="ffiset_gads_form" method="post" action="options.php"> <?php // add_settings_section callback is displayed here. For every new section we need to call settings_fields. settings_fields("ffita_gads_settings"); // all the add_settings_field callbacks is displayed here do_settings_sections("ffita_gads_settings"); ?> <table class="widefat" style="margin-top: 10px;"> <tr> <td colspan="3"><h2>Connection parameters</h2></td> </tr> <tr> <th scope="row" style="width: 15%;">ID VALUE</th> <td style="vertical-align: middle; width: 45%;"><input type="text" name="ffita_gads_capub" value="<?php echo esc_attr( get_option('ffita_gads_capub') ); ?>" style="width: 90%" required /></td> <td>ID value" .</td> </tr> <tr> <th scope="row" style="width: 15%;">IP debug</th> <td style="vertical-align: middle; width: 45%;"><input type="text" name="ffita_gads_ipdebug" value="<?php echo esc_attr( get_option('ffita_gads_ipdebug') ); ?>" style="width: 90%"></td> <td>Ip for debug....</td> </tr> </table> <table class="widefat Product" style="margin-top: 10px;"> <tr> <td colspan="3"><h2>Parameter</h2></td> </tr> <tr> <th scope="row" style="width: 10%;">ID</th> <td style="width: 20%;">Product id</td> <td>Product description</td> <td>Shortcode</td> </tr> <?php $Product_options = get_option('ffita_gads_option'); $num_Product = 0; if (empty($Product_options)) { $codice_html = "<tr><td colspan=4 bgcolor=red>Imposta i dettagli di almeno un Product</td></tr>"; $codice_html .= '<tr><td><input type="text" size="2" name="listaProduct[1][Product1][id_shortcode_Product]" value="1" readonly></td>'; $codice_html .= '<td><input type="text" name="listaProduct[1][Product1][id_Product]]" value="" required/></td>'; $codice_html .= '<td><input type="text" name="listaProduct[1][Product1][desc_Product]]" value="" size="60"/></td>'; $codice_html .= '<td>[ffita_gads id="1" ] </td></tr>'; echo $codice_html; $num_Product++; } else { foreach ($Product_options as $dati_Product) { $html = '<tr><td><input type="text" size="2" name="listaProduct[' . $dati_Product[id_shortcode_Product] . '][Product' . $dati_Product[id_shortcode_Product] . '][id_shortcode_Product]" value="' . $dati_Product[id_shortcode_Product] . '" readonly></td>'; $html .= '<td><input type="text" name="listaProduct[' . $dati_Product[id_shortcode_Product] . '][Product' . $dati_Product[id_shortcode_Product] . '][id_Product]]" value="' . $dati_Product[id_Product] . '" required/></td>'; $html .= '<td><input type="text" name="listaProduct[' . $dati_Product[id_shortcode_Product] . '][Product' . $dati_Product[id_shortcode_Product] . '][desc_Product]]" value="' . $dati_Product[desc_Product] . '" size="60"/></td>'; $html .= '<td> [ffita_gads id="' . $dati_Product[id_shortcode_Product] . '" ]</td></tr>'; echo $html; $num_Product++; } } ?> </table> <div align="right"> <input type="button" value="Add Product" id="add_ban_but" data-value="<?php echo $num_Product ?>" /> <input type="button" value="Remove last Product" id="remove_ban_but" /> </div> <input type="text" id="n_tot" name="ffita_n_tot" value="<?php echo $num_Product; ?>" /> <?php // Add the submit button to serialize the options submit_button(); ?> </form> </div> <?php } if (isset($_POST['submit'])) { // registra i dati dei Product $nuovi_Product = $_POST['listaProduct']; $array_Product = array(); // print_r ($nuovi_Product); foreach ($nuovi_Product as $key) { $nuovo_Product = $key; $array_Product = array_merge($array_Product, $nuovo_Product); } update_option('ffita_gads_option', $array_Product); // registra i dati ca-pub-xxxx $nuovo_ca = $_POST['ffita_gads_capub']; update_option('ffita_gads_capub', $nuovo_ca); // registra i dati ipdebug $nuovo_ipdeb = $_POST['ffita_gads_ipdebug']; update_option('ffita_gads_ipdebug', $nuovo_ipdeb); } function ffita_gads_option_init() { // registra il codice publisher ca-pub xxxx register_setting("ffita_gads_settings", "ffita_gads_capub"); // delete_option("ffita_gads_capub"); } add_action("admin_init", "ffita_gads_option_init"); ``` Any idea of the problem? many thanks in advance
Sorry for incomplete answer, Use the 301 redirects. This link give an idea about redirects <https://moz.com/learn/seo/redirection> <https://wordpress.org/plugins/simple-301-redirects/> For the wordpres there are free good plugins for add *html / htm* extension to urls. This for - "*.html*" <https://wordpress.org/plugins/html-in-url/> I think you can edit it and change it to "*.htm*" If you dont want to use plugins,follow this and change it according to your requirement, <http://carlofontanos.com/add-html-extension-to-permalinks/>
301,687
<p>I have been to trying to add one more column of mobile number field in the account page of a user in admin. So i found this good looking code from </p> <p><a href="https://coderwall.com/p/g72jfg/adding-a-phone-numer-field-to-wordpress-user-profile" rel="nofollow noreferrer">https://coderwall.com/p/g72jfg/adding-a-phone-numer-field-to-wordpress-user-profile</a></p> <p>Now what i am trying to do, is to build a custom widget for the dashboard so that the user will also have access to change his mobile number directly from there (So it must also be there an update button in the widget). You can see photos attached for the idea<a href="https://i.stack.imgur.com/V22yx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V22yx.png" alt="this is what you can see in users account"></a></p> <p><a href="https://i.stack.imgur.com/ugMQJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ugMQJ.png" alt="this is how the widget should look like"></a></p> <p>-first image is how the widget should look like in the dashboad, </p> <p>-second image is what you can see in users account now. </p> <p>I know some simple examples to create a dashboard widget with echo like this </p> <p><a href="http://www.wpbeginner.com/wp-themes/how-to-add-custom-dashboard-widgets-in-wordpress/" rel="nofollow noreferrer">http://www.wpbeginner.com/wp-themes/how-to-add-custom-dashboard-widgets-in-wordpress/</a></p> <p>, but until now i couldn't build it . </p> <p>Any help would be appreciated.</p>
[ { "answer_id": 302224, "author": "user141080", "author_id": 141080, "author_profile": "https://wordpress.stackexchange.com/users/141080", "pm_score": 3, "selected": true, "text": "<p>i built an small/simple example and i hope it will help you.</p>\n\n<p><strong>Admin dashboard widget with an save button</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/WZjxz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WZjxz.png\" alt=\"Admin dashboard widget with an save button\"></a></p>\n\n<p>First, we register a function which tells wordpress that we want to create an admin dashboard widget</p>\n\n<pre><code>/**\n * Registration of the Admin dashboard widget\n */\nfunction ch_add_dashboard_widgets() {\n\n wp_add_dashboard_widget(\n 'user_email_admin_dashboard_widget', // Widget slug\n __('Extra profile information', 'ch_user_widget'), // Title\n 'ch_user_email_admin_dashboard_widget' // Display function\n ); \n}\n\n// hook to register the Admin dashboard widget\nadd_action( 'wp_dashboard_setup', 'ch_add_dashboard_widgets' );\n</code></pre>\n\n<p>Then we create the function that renders your widget </p>\n\n<pre><code>/**\n * Output the html content of the dashboard widget\n */\nfunction ch_user_email_admin_dashboard_widget() {\n\n // detect the current user to get his phone number\n $user = wp_get_current_user();\n ?&gt;\n\n\n &lt;form id=\"ch_form\" action=\"&lt;?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?&gt;\" method=\"post\" &gt;\n\n &lt;!-- controlls on which function the post will send --&gt;\n &lt;input type=\"hidden\" name=\"cp_action\" id=\"cp_action\" value=\"ch_user_data\"&gt;\n\n &lt;?php wp_nonce_field( 'ch_nonce', 'ch_nonce_field' ); ?&gt;\n\n &lt;p&gt;Please add your phone number&lt;/p&gt;\n\n &lt;p&gt;\n &lt;label for=\"phone\"&gt;Phone Number&lt;/label&gt;\n &lt;input type=\"text\" name=\"phone\" id=\"cp_phone_number\" value=\"&lt;?php echo esc_attr( get_the_author_meta( 'phone', $user-&gt;ID ) ); ?&gt;\" class=\"regular-text\" /&gt;\n &lt;/p&gt;\n &lt;p&gt;\n\n &lt;input name=\"save-data\" id=\"save-data\" class=\"button button-primary\" value=\"Save\" type=\"submit\"&gt; \n &lt;br class=\"clear\"&gt;\n &lt;/p&gt;\n\n&lt;/form&gt;\n\n&lt;?php\n}\n</code></pre>\n\n<p>Ok the next part is the saving. There are two ways to save your widget data. </p>\n\n<p>The first one is to send the data via a normal \"form-post-request\". That the way how typical forms on websites works. Which means you have an form, you put your date in, hit the submit button and the data will send to the server. The server does someting with that data and than the user will redirect to onther page for instance an \"Thank you\"-page.</p>\n\n<p>The second way is almost the same as the first but with one exception the \"form-post-request\" will send via AJAX (short for \"<a href=\"https://en.wikipedia.org/wiki/Ajax_(programming)\" rel=\"nofollow noreferrer\">Asynchronous JavaScript And XML</a>\"). The advantage of this way is, we stay on the same page (expressed in a very simple way).</p>\n\n<p>To you use the second way we have to tell wordpress two thinks. First which function should be called by the ajax request and where your javascript file lies.</p>\n\n<pre><code>/**\n * Saves the data from the admin widget\n */\nfunction ch_save_user_data() {\n\n $msg = '';\n if(array_key_exists('nonce', $_POST) AND wp_verify_nonce( $_POST['nonce'], 'ch_nonce' ) ) \n { \n // detect the current user to get his phone number\n $user = wp_get_current_user();\n\n // change the phone number\n update_usermeta( $user-&gt;id, 'phone', $_POST['phone_number'] );\n\n // success message\n $msg = 'Phone number was saved';\n }\n else\n { \n // error message\n $msg = 'Phone number was not saved';\n }\n\n wp_send_json( $msg );\n}\n\n/**\n * ajax hook for registered users\n */\n add_action( 'wp_ajax_ch_user_data', 'ch_save_user_data' );\n\n\n\n/**\n * Add javascript file\n */\nfunction ch_add_script($hook){\n\n // add JS-File only on the dashboard page\n if ('index.php' !== $hook) {\n return;\n }\n\n wp_enqueue_script( 'ch_widget_script', plugin_dir_url(__FILE__) .\"/js/widget-script.js\", array(), NULL, true );\n}\n\n/**\n * hook to add js\n */\nadd_action( 'admin_enqueue_scripts', 'ch_add_script' );\n</code></pre>\n\n<p>ok the last point this the content of the javascript file.</p>\n\n<pre><code>jQuery(\"#ch_form\").submit(function(event) {\n\n /* stop form from submitting normally */\n event.preventDefault();\n\n /* get the action attribute from the form element */\n var url = jQuery( this ).attr( 'action' );\n\n /* Send the data using post */\n jQuery.ajax({\n type: 'POST',\n url: url,\n data: {\n action: jQuery('#cp_action').val(),\n phone_number: jQuery('#cp_phone_number').val(), \n nonce: jQuery('#ch_nonce_field').val()\n },\n success: function (data, textStatus, XMLHttpRequest) {\n alert(data);\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n alert(errorThrown);\n }\n });\n\n});\n</code></pre>\n\n<p>Ok and to the end some usefull links:</p>\n\n<p><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">\"AJAX in Plugins\" on wordpress.org</a> </p>\n\n<p><a href=\"https://developer.wordpress.org/plugins/javascript/ajax/\" rel=\"nofollow noreferrer\">What is Ajax? Plugin Handbook on wordpress.org</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Dashboard_Widgets_API\" rel=\"nofollow noreferrer\">Dashboard Widgets API on wordpress.org</a></p>\n\n<p><a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">Handling POST Requests the WordPress Way on sitepoint.com</a></p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>I put the whole code into an plugin and published it on github.</p>\n\n<p>Link: <a href=\"https://github.com/user141080/admindashboardwidget\" rel=\"nofollow noreferrer\">https://github.com/user141080/admindashboardwidget</a></p>\n" }, { "answer_id": 302436, "author": "Honoluluman", "author_id": 129972, "author_profile": "https://wordpress.stackexchange.com/users/129972", "pm_score": 0, "selected": false, "text": "<p>Wooooow, thank you very much user141080,</p>\n\n<p>To me it looks a lot of work what you did there! I can understand the html part for form, and most of the php saving the data part, but regarding the js i am totally out of the game :) </p>\n\n<p>I confirm that i tested your plugin and works perfectly fine! I was even able to add more fields by just adding in the js in the area of the code</p>\n\n<pre><code>data: {\n action: jQuery('#cp_action').val(),\n phone_number: jQuery('#cp_phone_number').val(),\n city_area: jQuery('#cp_city').val(), \n nonce: jQuery('#ch_nonce_field').val()\n },\n</code></pre>\n\n<p>aside with the appropriate fields.</p>\n\n<p>The only issue that i have noticed is that, since i want this plugin to run aside with the code that i used (<a href=\"https://coderwall.com/p/g72jfg/adding-a-phone-numer-field-to-wordpress-user-profile\" rel=\"nofollow noreferrer\">https://coderwall.com/p/g72jfg/adding-a-phone-numer-field-to-wordpress-user-profile</a>) for saving also the fields in the users profile page, when i save the data from the dashboard widget then after a simple refresh page on the users profile page,i can see the new updated data, but if i save the data from the users profile page then after a simple refresh page on the dashboard i don't have the new updated data. If i logout and login the user, then i get them. I suppose this have to do with something like this command?</p>\n\n<pre><code>// detect the current user to get his phone number\n$user = wp_get_current_user();\n</code></pre>\n\n<p>Thank you for your effort, i guess i would never be able to go so far and built it as you did :)</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301687", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129972/" ]
I have been to trying to add one more column of mobile number field in the account page of a user in admin. So i found this good looking code from <https://coderwall.com/p/g72jfg/adding-a-phone-numer-field-to-wordpress-user-profile> Now what i am trying to do, is to build a custom widget for the dashboard so that the user will also have access to change his mobile number directly from there (So it must also be there an update button in the widget). You can see photos attached for the idea[![this is what you can see in users account](https://i.stack.imgur.com/V22yx.png)](https://i.stack.imgur.com/V22yx.png) [![this is how the widget should look like](https://i.stack.imgur.com/ugMQJ.png)](https://i.stack.imgur.com/ugMQJ.png) -first image is how the widget should look like in the dashboad, -second image is what you can see in users account now. I know some simple examples to create a dashboard widget with echo like this <http://www.wpbeginner.com/wp-themes/how-to-add-custom-dashboard-widgets-in-wordpress/> , but until now i couldn't build it . Any help would be appreciated.
i built an small/simple example and i hope it will help you. **Admin dashboard widget with an save button** [![Admin dashboard widget with an save button](https://i.stack.imgur.com/WZjxz.png)](https://i.stack.imgur.com/WZjxz.png) First, we register a function which tells wordpress that we want to create an admin dashboard widget ``` /** * Registration of the Admin dashboard widget */ function ch_add_dashboard_widgets() { wp_add_dashboard_widget( 'user_email_admin_dashboard_widget', // Widget slug __('Extra profile information', 'ch_user_widget'), // Title 'ch_user_email_admin_dashboard_widget' // Display function ); } // hook to register the Admin dashboard widget add_action( 'wp_dashboard_setup', 'ch_add_dashboard_widgets' ); ``` Then we create the function that renders your widget ``` /** * Output the html content of the dashboard widget */ function ch_user_email_admin_dashboard_widget() { // detect the current user to get his phone number $user = wp_get_current_user(); ?> <form id="ch_form" action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" method="post" > <!-- controlls on which function the post will send --> <input type="hidden" name="cp_action" id="cp_action" value="ch_user_data"> <?php wp_nonce_field( 'ch_nonce', 'ch_nonce_field' ); ?> <p>Please add your phone number</p> <p> <label for="phone">Phone Number</label> <input type="text" name="phone" id="cp_phone_number" value="<?php echo esc_attr( get_the_author_meta( 'phone', $user->ID ) ); ?>" class="regular-text" /> </p> <p> <input name="save-data" id="save-data" class="button button-primary" value="Save" type="submit"> <br class="clear"> </p> </form> <?php } ``` Ok the next part is the saving. There are two ways to save your widget data. The first one is to send the data via a normal "form-post-request". That the way how typical forms on websites works. Which means you have an form, you put your date in, hit the submit button and the data will send to the server. The server does someting with that data and than the user will redirect to onther page for instance an "Thank you"-page. The second way is almost the same as the first but with one exception the "form-post-request" will send via AJAX (short for "[Asynchronous JavaScript And XML](https://en.wikipedia.org/wiki/Ajax_(programming))"). The advantage of this way is, we stay on the same page (expressed in a very simple way). To you use the second way we have to tell wordpress two thinks. First which function should be called by the ajax request and where your javascript file lies. ``` /** * Saves the data from the admin widget */ function ch_save_user_data() { $msg = ''; if(array_key_exists('nonce', $_POST) AND wp_verify_nonce( $_POST['nonce'], 'ch_nonce' ) ) { // detect the current user to get his phone number $user = wp_get_current_user(); // change the phone number update_usermeta( $user->id, 'phone', $_POST['phone_number'] ); // success message $msg = 'Phone number was saved'; } else { // error message $msg = 'Phone number was not saved'; } wp_send_json( $msg ); } /** * ajax hook for registered users */ add_action( 'wp_ajax_ch_user_data', 'ch_save_user_data' ); /** * Add javascript file */ function ch_add_script($hook){ // add JS-File only on the dashboard page if ('index.php' !== $hook) { return; } wp_enqueue_script( 'ch_widget_script', plugin_dir_url(__FILE__) ."/js/widget-script.js", array(), NULL, true ); } /** * hook to add js */ add_action( 'admin_enqueue_scripts', 'ch_add_script' ); ``` ok the last point this the content of the javascript file. ``` jQuery("#ch_form").submit(function(event) { /* stop form from submitting normally */ event.preventDefault(); /* get the action attribute from the form element */ var url = jQuery( this ).attr( 'action' ); /* Send the data using post */ jQuery.ajax({ type: 'POST', url: url, data: { action: jQuery('#cp_action').val(), phone_number: jQuery('#cp_phone_number').val(), nonce: jQuery('#ch_nonce_field').val() }, success: function (data, textStatus, XMLHttpRequest) { alert(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); }); ``` Ok and to the end some usefull links: ["AJAX in Plugins" on wordpress.org](https://codex.wordpress.org/AJAX_in_Plugins) [What is Ajax? Plugin Handbook on wordpress.org](https://developer.wordpress.org/plugins/javascript/ajax/) [Dashboard Widgets API on wordpress.org](https://codex.wordpress.org/Dashboard_Widgets_API) [Handling POST Requests the WordPress Way on sitepoint.com](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/) **EDIT:** I put the whole code into an plugin and published it on github. Link: <https://github.com/user141080/admindashboardwidget>
301,706
<p>I'm using custom instances of <code>wp_editor();</code> to allow rich text editing of Post Meta associated with a Post Object.</p> <p>I'd like to perform much of the same sanitization that occurs with <code>post_content</code> for the values of these fields.</p> <p><strong>Here's what I've come up with:</strong></p> <blockquote> <p>Please let me know if this is an okay approach, or if there is more I should be doing in either of these three steps, or if there's a better or easier way.</p> </blockquote> <p><strong>On <code>save_post</code>:</strong></p> <pre><code>$value = wp_filter_post_kses( sanitize_post_field( 'post_content', $value, 0, 'db' ) ); </code></pre> <p><strong>Passing Value to <code>wp_editor();</code>:</strong></p> <pre><code>$value = wp_unslash( sanitize_post_field( 'post_content', $value, 0, 'edit' ) ); </code></pre> <p><strong>Outputting Value on Frontend:</strong></p> <pre><code>$value = wp_unslash( sanitize_post_field( 'post_content', $value, 0, 'display' ) ); </code></pre>
[ { "answer_id": 301717, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p><code>wp_kses</code> to the rescue!</p>\n\n<h2>My Editor Contains everything a Post Might</h2>\n\n<p>Pass the result through <code>wp_kses_post</code> on the way in and out, and all should be good.</p>\n\n<p>Remember, this will strip out anything added by <code>the_content</code> filter, so to preserve oembeds and shortcodes, use this:</p>\n\n<pre><code>echo apply_filters( 'the_content', wp_kses_post( $content ) );\n</code></pre>\n\n<p>You might also want <code>esc_textarea</code> for outputting the form if you're using <code>&lt;textarea&gt;</code> tags directly</p>\n\n<h2>My Editor contains text, but no markup</h2>\n\n<p>On output, <code>esc_html</code> is your friend. Use this for situations when you have a text area that will never contain markup. On input, try <code>wp_strip_all_tags</code> on input to sanitise. The other WP APIs will make sure no SQL injections occur</p>\n\n<h2>My Editor contains markup, but a limited subset</h2>\n\n<p><code>wp_kses</code> to the rescue, pass it through <code>wp_kses</code> along with a second parameter, an array defining what tags and attributes are allowed. E.g.:</p>\n\n<pre><code>$allowed = [\n 'a' =&gt; [\n 'href' =&gt; [],\n 'title' =&gt; []\n ],\n 'br' =&gt; [],\n 'em' =&gt; [],\n 'strong' =&gt; [],\n];\n\necho wp_kses( $content, $allowed );\n</code></pre>\n\n<p>Be wary though of overextending. If you add script and iframe tags, is there really any point in using <code>wp_kses</code>?</p>\n\n<h2>wp_editor</h2>\n\n<p><code>wp_editor</code> outputs internally, it can't be escaped, therefore it is responsible for escaping itself. Do not try to be unhelpful by passing it pre-escaped content, this can lead ot mangled output and double escaping ( a great way for malformed content to bypass escaping ).</p>\n\n<p>The function that outputs has the responsibility for escaping. This enables late escaping. Escaping earlier or multiple times is dangerous and introduces new complex problems, as you no longer know with certainty what is or isn't escaped.</p>\n" }, { "answer_id": 301732, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>I think you're on the right track.</p>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/sanitize_post_field/\" rel=\"nofollow noreferrer\"><code>sanitize_post_field()</code></a> function calls the <a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post.php#L2060\" rel=\"nofollow noreferrer\"><code>content_save_pre</code></a> hook which, when given the DB context, will also call the <a href=\"https://developer.wordpress.org/reference/functions/kses_init_filters/\" rel=\"nofollow noreferrer\"><code>wp_filter_post_kses</code> function</a> so there's no need to wrap it/call it again.</p>\n\n<p>As far as I can tell at this point once it's been saved to the database we don't need to unslash anything for display. Here's what I have which is fairly similar to what you already had:</p>\n\n<p><strong>Saving Value</strong></p>\n\n<pre><code>update_post_meta( $post-&gt;ID, '_test', sanitize_post_field( 'post_content', $_POST['_test'], $post-&gt;ID, 'db' ) );\n</code></pre>\n\n<p><strong>Passing Value</strong></p>\n\n<pre><code>$editor_content = get_post_meta( $post-&gt;ID, '_test', true );\n\nwp_editor( $editor_content, 'editor_id_here', array(\n 'textarea_name' =&gt; '_test',\n) );\n</code></pre>\n\n<p><strong>Displaying Value</strong></p>\n\n<pre><code>$editor_content = get_post_meta( $post-&gt;ID, '_test', true );\n$display_content = apply_filters( 'the_content', $display_content );\n</code></pre>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301706", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9579/" ]
I'm using custom instances of `wp_editor();` to allow rich text editing of Post Meta associated with a Post Object. I'd like to perform much of the same sanitization that occurs with `post_content` for the values of these fields. **Here's what I've come up with:** > > Please let me know if this is an okay approach, or if there is more I > should be doing in either of these three steps, or if there's a better > or easier way. > > > **On `save_post`:** ``` $value = wp_filter_post_kses( sanitize_post_field( 'post_content', $value, 0, 'db' ) ); ``` **Passing Value to `wp_editor();`:** ``` $value = wp_unslash( sanitize_post_field( 'post_content', $value, 0, 'edit' ) ); ``` **Outputting Value on Frontend:** ``` $value = wp_unslash( sanitize_post_field( 'post_content', $value, 0, 'display' ) ); ```
`wp_kses` to the rescue! My Editor Contains everything a Post Might ------------------------------------------ Pass the result through `wp_kses_post` on the way in and out, and all should be good. Remember, this will strip out anything added by `the_content` filter, so to preserve oembeds and shortcodes, use this: ``` echo apply_filters( 'the_content', wp_kses_post( $content ) ); ``` You might also want `esc_textarea` for outputting the form if you're using `<textarea>` tags directly My Editor contains text, but no markup -------------------------------------- On output, `esc_html` is your friend. Use this for situations when you have a text area that will never contain markup. On input, try `wp_strip_all_tags` on input to sanitise. The other WP APIs will make sure no SQL injections occur My Editor contains markup, but a limited subset ----------------------------------------------- `wp_kses` to the rescue, pass it through `wp_kses` along with a second parameter, an array defining what tags and attributes are allowed. E.g.: ``` $allowed = [ 'a' => [ 'href' => [], 'title' => [] ], 'br' => [], 'em' => [], 'strong' => [], ]; echo wp_kses( $content, $allowed ); ``` Be wary though of overextending. If you add script and iframe tags, is there really any point in using `wp_kses`? wp\_editor ---------- `wp_editor` outputs internally, it can't be escaped, therefore it is responsible for escaping itself. Do not try to be unhelpful by passing it pre-escaped content, this can lead ot mangled output and double escaping ( a great way for malformed content to bypass escaping ). The function that outputs has the responsibility for escaping. This enables late escaping. Escaping earlier or multiple times is dangerous and introduces new complex problems, as you no longer know with certainty what is or isn't escaped.
301,710
<p>I’m lost I don’t know where to turn.</p> <p>I am trying to get my thumbnails to NOT be compressed at all. My uploads are nice and colorful, but the thumbnails gets very visibly duller and poorer quality. I already added this code to my function.php file in my child and parent theme:</p> <pre><code>add_filter(‘jpeg_quality’, function($arg){return 100;}); echo get_the_post_thumbnail($id, array(100,100) ); add_filter( ‘jpeg_quality’, create_function( ”, ‘return 100;’ ) ); add_filter( 'wp_editor_set_quality', 'wpse246186_image_quality' ); add_filter( 'jpeg_quality', 'wpse246186_image_quality' ); function wpse246186_image_quality( $quality ) { return 100; // 0 - 100% quality } </code></pre> <p>I’ve installed ‘Disable JPEG Compression’, and I’ve installed EWWW Image Optimizer and upped the compression quality to 100. I keep regenerating thumbnails using the ‘Regenerate Thumbnails’ plugin. But there is still a huge difference. I do not know what to do, I’ve searched the web up and down, idk what I am missing. Is it because my images are Adobe 1998 and not sRGB when I uploaded them?</p> <p>Here is an example of the good image: <a href="http://ninasveganrecipes.com/wp-content/uploads/2018/03/web-blackberry-icecream-4863.jpg" rel="nofollow noreferrer">http://ninasveganrecipes.com/wp-content/uploads/2018/03/web-blackberry-icecream-4863.jpg</a></p> <p>Here is a thumbnail of it looking BAD (dull!): <a href="http://ninasveganrecipes.com/wp-content/uploads/2018/03/web-blackberry-icecream-4863-1080" rel="nofollow noreferrer">http://ninasveganrecipes.com/wp-content/uploads/2018/03/web-blackberry-icecream-4863-1080</a>×1619.jpg</p> <p>Please help me! I don’t know what to try or what I am doing wrong. Running PHP 5.6.30 on my wordpress site.</p> <p>Thank you. -Nina Marie</p>
[ { "answer_id": 301711, "author": "robwatson_dev", "author_id": 137115, "author_profile": "https://wordpress.stackexchange.com/users/137115", "pm_score": 2, "selected": false, "text": "<p>Uninstall the plugin and add this to your functions.php file</p>\n\n<pre><code>add_filter('jpeg_quality', function($arg){return 100;});\nadd_filter( 'wp_editor_set_quality', function($arg){return 100;} );\n</code></pre>\n\n<p>However please be aware that . you should still compress you images prior to uploading them for the performance enhancement.</p>\n" }, { "answer_id": 326522, "author": "Bigue Nique", "author_id": 152860, "author_profile": "https://wordpress.stackexchange.com/users/152860", "pm_score": 2, "selected": false, "text": "<p>Make sure you convert your images to sRGB before uploading them to WordPress.</p>\n\n<p>Image compression should not dramatically affect the colors and tones of the picture. When you witness a significant shift in color, hue, saturation or contrast, it might be a color space issue (as the asker pointed out herself).</p>\n" }, { "answer_id": 338732, "author": "kubi", "author_id": 152837, "author_profile": "https://wordpress.stackexchange.com/users/152837", "pm_score": 2, "selected": false, "text": "<p>(this should be a comment, but my reputation is too low)</p>\n\n<p>Setting <code>jpeg_quality</code> will not disable compression because it does not disable processing. JPEGs will be always compressed, and they are <a href=\"https://stackoverflow.com/questions/7982409/is-jpeg-lossless-when-quality-is-set-to-100\">almost never</a> lossless, not even at 100 - it does not stand for \"100% original quality\".</p>\n\n<p>What happens here, is that WordPress's default image processing does not respect color profiles, just as @Bigue Nique says.<br>\nTo add some insight: WP ignores color profiles from the images and the browser sees them as unprofiled/sRGB. The <strong>loss of saturation is a typical artifact when the AdobeRGB profile is stripped</strong>.<br>\nAs a photography student I had made that mistake for years (luckily, my pictures were usally grey ;).</p>\n\n<p>It still makes sense to shoot and use AdobeRGB, or other color profiles, just make sure to <em>convert to sRGB</em> (important: <em>convert to profile</em>, not <em>apply profile</em>) at the very last step of your workflow. You can then even <em>strip</em> the potentially embedded sRGB profile and thus make the image <em>unprofiled</em>, since it does not make a difference in appearance - this is what image size optimizers do to save a couple of bytes.</p>\n\n<p>I'm sure there are plugins to do the profile conversions automatically, but it is good practice to be aware of color profile issues when you publish to the web (say, forums or customers who don't have that plugin).</p>\n\n<p>@Nina Marie - please mark an answer (Bigue Nique's) as the correct one.</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301710", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142379/" ]
I’m lost I don’t know where to turn. I am trying to get my thumbnails to NOT be compressed at all. My uploads are nice and colorful, but the thumbnails gets very visibly duller and poorer quality. I already added this code to my function.php file in my child and parent theme: ``` add_filter(‘jpeg_quality’, function($arg){return 100;}); echo get_the_post_thumbnail($id, array(100,100) ); add_filter( ‘jpeg_quality’, create_function( ”, ‘return 100;’ ) ); add_filter( 'wp_editor_set_quality', 'wpse246186_image_quality' ); add_filter( 'jpeg_quality', 'wpse246186_image_quality' ); function wpse246186_image_quality( $quality ) { return 100; // 0 - 100% quality } ``` I’ve installed ‘Disable JPEG Compression’, and I’ve installed EWWW Image Optimizer and upped the compression quality to 100. I keep regenerating thumbnails using the ‘Regenerate Thumbnails’ plugin. But there is still a huge difference. I do not know what to do, I’ve searched the web up and down, idk what I am missing. Is it because my images are Adobe 1998 and not sRGB when I uploaded them? Here is an example of the good image: <http://ninasveganrecipes.com/wp-content/uploads/2018/03/web-blackberry-icecream-4863.jpg> Here is a thumbnail of it looking BAD (dull!): <http://ninasveganrecipes.com/wp-content/uploads/2018/03/web-blackberry-icecream-4863-1080>×1619.jpg Please help me! I don’t know what to try or what I am doing wrong. Running PHP 5.6.30 on my wordpress site. Thank you. -Nina Marie
Uninstall the plugin and add this to your functions.php file ``` add_filter('jpeg_quality', function($arg){return 100;}); add_filter( 'wp_editor_set_quality', function($arg){return 100;} ); ``` However please be aware that . you should still compress you images prior to uploading them for the performance enhancement.
301,721
<pre><code>// Creates the function function my_custom_javascript() { // Loads the script into the function wp_enqueue_scripts('my_custom_javascript', plugin_dir_url(__FILE__) . '/assets/js/custom.js', array('jquery')); } // calls the function where the script is located add_action('wp_enqueue_scripts', 'my_custom_javascript'); </code></pre> <p>I think this is written right. I am calling this script in the functions.php file in my theme but it's not loading, so I was hoping I could get some suggestions. </p>
[ { "answer_id": 301724, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>You're using the function <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts()</code></a> where you should be using <strong><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a></strong>.</p>\n\n<pre><code>function my_custom_javascript(){ // Creates the function\n wp_enqueue_script(\n 'my_custom_javascript',\n plugin_dir_url(__FILE__) . '/assets/js/custom.js',\n array('jquery')\n ); // Loads the script into the function\n}\nadd_action('wp_enqueue_scripts', 'my_custom_javascript'); \n// calls the function where the script is located\n</code></pre>\n\n<p><code>wp_enqueue_script()</code> enqueues the script; <code>wp_enqueue_scripts()</code> is a wrapper for <code>do_action( 'wp_enqueue_scripts' )</code>.</p>\n" }, { "answer_id": 301726, "author": "Milan Bastola", "author_id": 137372, "author_profile": "https://wordpress.stackexchange.com/users/137372", "pm_score": 0, "selected": false, "text": "<pre><code>function my_custom_javascript() {\n wp_enqueue_scripts('my_custom_javascript', plugin_dir_url(__FILE__) . 'assets/js/custom.js', array('jquery'));\nadd_action('wp_enqueue_scripts', 'my_custom_javascript'); \n</code></pre>\n\n<p>** You don't need to use trailing slash before assets/js/custom.js because plugin_dir_url outputs it. Instead you can use plugins_url and you should use wp_enqueue_script NOT wp_enqueue_scripts while enqueuing file</p>\n\n<p>I think this will help you: <a href=\"https://wordpress.stackexchange.com/questions/61679/plugins-url-vs-plugin-dir-url/61698#61698\">plugins_url vs plugin_dir_url</a></p>\n" }, { "answer_id": 301730, "author": "Mat Lipe", "author_id": 129914, "author_profile": "https://wordpress.stackexchange.com/users/129914", "pm_score": 0, "selected": false, "text": "<p>To cue your script you want to use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script()</a> instead of <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">wp_enqueue_scripts()</a> like so.</p>\n\n<pre><code>function my_custom_javascript() {\n wp_enqueue_script('my_custom_javascript', plugin_dir_url(__FILE__) . 'assets/js/custom.js', array('jquery'));\n}\nadd_action('wp_enqueue_scripts', 'my_custom_javascript'); \n</code></pre>\n\n<p>You don't need to add the / slash before assets/js/custom.js because plugin_dir_url uses <a href=\"https://codex.wordpress.org/Function_Reference/trailingslashit\" rel=\"nofollow noreferrer\">trailingslashit()</a> to include it.</p>\n\n<p>If you really want to add the / yourself, you use <a href=\"https://codex.wordpress.org/Function_Reference/plugins_url\" rel=\"nofollow noreferrer\">plugins_url()</a> which gets called anyway minus the trailingslashit()</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301721", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142388/" ]
``` // Creates the function function my_custom_javascript() { // Loads the script into the function wp_enqueue_scripts('my_custom_javascript', plugin_dir_url(__FILE__) . '/assets/js/custom.js', array('jquery')); } // calls the function where the script is located add_action('wp_enqueue_scripts', 'my_custom_javascript'); ``` I think this is written right. I am calling this script in the functions.php file in my theme but it's not loading, so I was hoping I could get some suggestions.
You're using the function [`wp_enqueue_scripts()`](https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/) where you should be using **[`wp_enqueue_script()`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)**. ``` function my_custom_javascript(){ // Creates the function wp_enqueue_script( 'my_custom_javascript', plugin_dir_url(__FILE__) . '/assets/js/custom.js', array('jquery') ); // Loads the script into the function } add_action('wp_enqueue_scripts', 'my_custom_javascript'); // calls the function where the script is located ``` `wp_enqueue_script()` enqueues the script; `wp_enqueue_scripts()` is a wrapper for `do_action( 'wp_enqueue_scripts' )`.
301,729
<p>When WooCoomerce updated to version 3.3, the 'Uncategorized' product category was added and then appeared on all pages (including the WooCommerce shop page) where products were displayed if there are any products with. All products that do not have at least one assigned category is then then (logically I guess) assigned to the 'uncategorised' category.</p> <p>I always used the (possibly not ideal) approach of hiding seasonal products by removing all categories from these products when they were out of season. This new change meant that these 'hidden' products all of a sudden appeared on the site for sale in this new category which I do not want on any page.</p> <p>I have searched the web looking for a way of hiding the 'Uncategorized' product category and found that this problem is widespread. A number of solutions were proposed including making the “uncategorized” category a subcategory and then hiding all the subcategories or hiding categories using CSS.</p> <p>See <a href="https://wordpress.org/support/topic/uncategorized-product-category-still-showing-after-3-3-1/" rel="nofollow noreferrer">https://wordpress.org/support/topic/uncategorized-product-category-still-showing-after-3-3-1/</a></p> <p>However, none of these solutions are 'clean' or robust enough.</p> <p>My work-around has been to only show the products that I want visible by using the product categories shortcode (without the uncategorised category id). For example:</p> <pre><code>[product_categories ids="11, 19, 18, 14, 7, 8, 9, 10, 15, 98, 16, 17"] </code></pre> <p>but this does not solve the issue on the shop page (which does not use shortcodes).</p> <p>I wonder if anyone has a robust method for hiding the 'Uncategorized' product category as is an issue that is topical and appears to be widespread at the moment.</p>
[ { "answer_id": 301731, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 4, "selected": true, "text": "<p>I solved this problem based on code kindly provided by rynoldos (<a href=\"https://gist.github.com/rynaldos/a9d357b1e3791afd9bea48833ff95994\" rel=\"noreferrer\">https://gist.github.com/rynaldos/a9d357b1e3791afd9bea48833ff95994</a>) as follows:</p>\n\n<p>Include the following code in your functions.php file:</p>\n\n<pre><code>/** Remove categories from shop and other pages\n * in Woocommerce\n */\nfunction wc_hide_selected_terms( $terms, $taxonomies, $args ) {\n $new_terms = array();\n if ( in_array( 'product_cat', $taxonomies ) &amp;&amp; !is_admin() &amp;&amp; is_shop() ) {\n foreach ( $terms as $key =&gt; $term ) {\n if ( ! in_array( $term-&gt;slug, array( 'uncategorized' ) ) ) {\n $new_terms[] = $term;\n }\n }\n $terms = $new_terms;\n }\n return $terms;\n}\nadd_filter( 'get_terms', 'wc_hide_selected_terms', 10, 3 );\n</code></pre>\n\n<p>This code applies to the shop page on WooCommerce. If you would like to apply this to a different page, replace is_shop() with is_page('YOUR_PAGE_SLUG').</p>\n\n<p>I too had a run-around trying to find a solution to this problem, but the above code works well for me.</p>\n" }, { "answer_id": 303559, "author": "Marianne", "author_id": 143613, "author_profile": "https://wordpress.stackexchange.com/users/143613", "pm_score": 1, "selected": false, "text": "<p>I have found a simple way to hide Uncategorized category in the shop page: I have changed its Parent category \"None\" by another category I have. </p>\n\n<p>Hope it helps :-)</p>\n\n<p>Marianne</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129826/" ]
When WooCoomerce updated to version 3.3, the 'Uncategorized' product category was added and then appeared on all pages (including the WooCommerce shop page) where products were displayed if there are any products with. All products that do not have at least one assigned category is then then (logically I guess) assigned to the 'uncategorised' category. I always used the (possibly not ideal) approach of hiding seasonal products by removing all categories from these products when they were out of season. This new change meant that these 'hidden' products all of a sudden appeared on the site for sale in this new category which I do not want on any page. I have searched the web looking for a way of hiding the 'Uncategorized' product category and found that this problem is widespread. A number of solutions were proposed including making the “uncategorized” category a subcategory and then hiding all the subcategories or hiding categories using CSS. See <https://wordpress.org/support/topic/uncategorized-product-category-still-showing-after-3-3-1/> However, none of these solutions are 'clean' or robust enough. My work-around has been to only show the products that I want visible by using the product categories shortcode (without the uncategorised category id). For example: ``` [product_categories ids="11, 19, 18, 14, 7, 8, 9, 10, 15, 98, 16, 17"] ``` but this does not solve the issue on the shop page (which does not use shortcodes). I wonder if anyone has a robust method for hiding the 'Uncategorized' product category as is an issue that is topical and appears to be widespread at the moment.
I solved this problem based on code kindly provided by rynoldos (<https://gist.github.com/rynaldos/a9d357b1e3791afd9bea48833ff95994>) as follows: Include the following code in your functions.php file: ``` /** Remove categories from shop and other pages * in Woocommerce */ function wc_hide_selected_terms( $terms, $taxonomies, $args ) { $new_terms = array(); if ( in_array( 'product_cat', $taxonomies ) && !is_admin() && is_shop() ) { foreach ( $terms as $key => $term ) { if ( ! in_array( $term->slug, array( 'uncategorized' ) ) ) { $new_terms[] = $term; } } $terms = $new_terms; } return $terms; } add_filter( 'get_terms', 'wc_hide_selected_terms', 10, 3 ); ``` This code applies to the shop page on WooCommerce. If you would like to apply this to a different page, replace is\_shop() with is\_page('YOUR\_PAGE\_SLUG'). I too had a run-around trying to find a solution to this problem, but the above code works well for me.
301,747
<p>i'm developing a plugin wich uses GET parametters to decide what to render to the user(example: login, logout, change password etc..), the thing is this works in the standards wordpress themes but when i changed to my clients theme(Sereno) every time i call the url with the parametter it render a POST page... example</p> <p>if a call <a href="http://localhost/myclient/?page_id=822&amp;action=passresset" rel="nofollow noreferrer">http://localhost/myclient/?page_id=822&amp;action=passresset</a> in the standard wp theme it will show what i want but if a change to sereno shows a post page, its weird to my that does not show an 404 error, like this recognizes the URL like a valid one</p> <p>I'm trying to fix this but i have no idea where to start, i guess the problem should be in the way the template decides what kind of loop it will use but i don't know where the **** its that script..</p> <p>Pleace help!!</p> <p>--------------UPDATE---------------</p> <p>first than all, fuxia thanks a lot for taking time on helping me...</p> <p>i'm using a widget to handle a type of users (not the same users of WP) which will have access to login, logout, change password, resset password and send requests via a form so my widget class is as follows</p> <pre><code>class SucursalWidget extends baseWidget { public function __construct() { $widgetOptions = [ 'classname' =&gt; 'SucursalWidget', 'description' =&gt; 'Panel de búsqueda para las sucursales', ]; parent::__construct('sucursalwidget', "Widget para las sucursales", $widgetOptions); } public function login() { //process user login } public function logout() { session_destroy(); echo "&lt;h2&gt;Su sesion ha sido terminada&lt;/h2&gt;"; $model = new LoginForm(); $this-&gt;renderPartial('loginform', ['model' =&gt; $model]); } public function solicitud() { //Gets a form an save it on db } /** * Cambiar contraseña para usuario ya logeado */ public function passChange() { } /** * Recuperar contraseña perdida vía email */ public function passResset() { //PROCEESS pass resset } public function widget($args, $instance) { $action = isset($_GET['action']) ? $_GET['action'] : 'login'; switch ($action) { case 'login': { $this-&gt;login(); } break; case 'logout': { $this-&gt;logout(); } break; case 'solicite': { $this-&gt;solicitud(); } break; case 'passchange': { $this-&gt;passChange(); } break; case 'passresset': { $this-&gt;passResset(); } break; default: { echo "Página no encontrada"; } break; } } } </code></pre> <p>as you can see in the function widget the switch uses the $_GET['action'] to know what to do with depending on the user's actions, this method works just fine when i use a regular WP theme like Twenty Fifteen. I guess the theme (named Sereno) its changing the URLs pattern because when i put any extra get parametter it shows a POST page i would expect an 404 error if something goes wrong, but for some reason is showing the last POST and i have no idea what to search for in the theme code..</p>
[ { "answer_id": 301762, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 1, "selected": false, "text": "<p>WordPress is removing all unknown (not registered) <code>$_GET</code> parameters while processing the request (same is true for <code>$_POST</code>). </p>\n\n<p>You can either register the custom variable, or just go the canonical PHP way by using <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow noreferrer\"><code>filter_input()</code></a>. This will access the original, unchanged <code>GET</code> parameters.</p>\n\n<p>If you are using <code>filter_input()</code>, you have to hook into <code>pre_get_posts</code> to change the fetched resource.</p>\n\n<p>You can also filter <code>query_vars</code> and register your custom variable here. This will make sure it is preserved.</p>\n\n<pre><code>add_filter( 'query_vars', function ( $vars ) {\n $vars[] = 'sereno';\n return $vars;\n});\n</code></pre>\n\n<p>Then you can access it per <code>get_query_var( 'sereno' )</code> now. You still have to change the request somehow if you want to show some custom content.</p>\n" }, { "answer_id": 301830, "author": "Isan Rodriguez Trimiño", "author_id": 136398, "author_profile": "https://wordpress.stackexchange.com/users/136398", "pm_score": 0, "selected": false, "text": "<p>I had found the problem, the thing is this template has taxonomy customizations, i commented </p>\n\n<pre><code>require_once('library/core/twomediax-wp-customizations.php'); // twomediax core custom types and taxonomies\n</code></pre>\n\n<p>this line is in the function.php, and without this customizations it works, now is giving me othe issues with template widget but i have a path to follow... now i have to struggle with taxonomies</p>\n\n<p>fuxia thanks again for helping me</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136398/" ]
i'm developing a plugin wich uses GET parametters to decide what to render to the user(example: login, logout, change password etc..), the thing is this works in the standards wordpress themes but when i changed to my clients theme(Sereno) every time i call the url with the parametter it render a POST page... example if a call <http://localhost/myclient/?page_id=822&action=passresset> in the standard wp theme it will show what i want but if a change to sereno shows a post page, its weird to my that does not show an 404 error, like this recognizes the URL like a valid one I'm trying to fix this but i have no idea where to start, i guess the problem should be in the way the template decides what kind of loop it will use but i don't know where the \*\*\*\* its that script.. Pleace help!! --------------UPDATE--------------- first than all, fuxia thanks a lot for taking time on helping me... i'm using a widget to handle a type of users (not the same users of WP) which will have access to login, logout, change password, resset password and send requests via a form so my widget class is as follows ``` class SucursalWidget extends baseWidget { public function __construct() { $widgetOptions = [ 'classname' => 'SucursalWidget', 'description' => 'Panel de búsqueda para las sucursales', ]; parent::__construct('sucursalwidget', "Widget para las sucursales", $widgetOptions); } public function login() { //process user login } public function logout() { session_destroy(); echo "<h2>Su sesion ha sido terminada</h2>"; $model = new LoginForm(); $this->renderPartial('loginform', ['model' => $model]); } public function solicitud() { //Gets a form an save it on db } /** * Cambiar contraseña para usuario ya logeado */ public function passChange() { } /** * Recuperar contraseña perdida vía email */ public function passResset() { //PROCEESS pass resset } public function widget($args, $instance) { $action = isset($_GET['action']) ? $_GET['action'] : 'login'; switch ($action) { case 'login': { $this->login(); } break; case 'logout': { $this->logout(); } break; case 'solicite': { $this->solicitud(); } break; case 'passchange': { $this->passChange(); } break; case 'passresset': { $this->passResset(); } break; default: { echo "Página no encontrada"; } break; } } } ``` as you can see in the function widget the switch uses the $\_GET['action'] to know what to do with depending on the user's actions, this method works just fine when i use a regular WP theme like Twenty Fifteen. I guess the theme (named Sereno) its changing the URLs pattern because when i put any extra get parametter it shows a POST page i would expect an 404 error if something goes wrong, but for some reason is showing the last POST and i have no idea what to search for in the theme code..
WordPress is removing all unknown (not registered) `$_GET` parameters while processing the request (same is true for `$_POST`). You can either register the custom variable, or just go the canonical PHP way by using [`filter_input()`](http://php.net/manual/en/function.filter-input.php). This will access the original, unchanged `GET` parameters. If you are using `filter_input()`, you have to hook into `pre_get_posts` to change the fetched resource. You can also filter `query_vars` and register your custom variable here. This will make sure it is preserved. ``` add_filter( 'query_vars', function ( $vars ) { $vars[] = 'sereno'; return $vars; }); ``` Then you can access it per `get_query_var( 'sereno' )` now. You still have to change the request somehow if you want to show some custom content.
301,749
<p>I am having a problem with the Wordpress Admin bar covering and overlapping my fixed menu header. The theme originally did not have a fixed menu header but I edited the CSS to add one. Also, I added a background color change for the header's menu (in case this complicates the fix).</p> <p>I have tried using numerous fixes found on StackExchange, Wordpress Blogs, Reddit, Ect. But these fixes moves my slider and body content further down the page, while my fixed header is still showing at the very top of the page covered by the Wordpress Admin Bar still.</p> <p>I have taken screenshots of what happens when I tried using the other fixes found on StackExchange.<br> <a href="https://imgur.com/a/cAI05S5" rel="nofollow noreferrer">https://imgur.com/a/cAI05S5</a></p> <p>And I am seeking a solution that does not involve installing "another" plugin because of the "download this plugin to fix your issue and slow down your website at the same time" compromise. The website is not live yet, but I'm building it using a WAMP local server on my PC.</p> <p>This is my code that I used to make my fixed header</p> <pre><code>header.header-default { position: fixed!important; top: 0px!important; z-index: 2000!important; width: 100%!important; } .jumbotron { padding-top: 55px!important; } div.page-header { padding-top: 115px!important; padding-bottom: 25px!important; } </code></pre>
[ { "answer_id": 301754, "author": "Milan Bastola", "author_id": 137372, "author_profile": "https://wordpress.stackexchange.com/users/137372", "pm_score": 1, "selected": false, "text": "<p>One solution to your problem is hiding admin bar from front-end. Maybe there is problem in your css too. </p>\n\n<p>To hide admin bar from front-end: </p>\n\n<ol>\n<li>To remove the toolbar from your site, go to Users > Your Profile. Scroll down to “Toolbar” and uncheck “Show Toolbar when viewing site.”</li>\n<li>Add <code>add_filter(‘show_admin_bar’, ‘__return_false’);</code> to functions.php of your theme.</li>\n</ol>\n" }, { "answer_id": 301771, "author": "Levi Dulstein", "author_id": 101988, "author_profile": "https://wordpress.stackexchange.com/users/101988", "pm_score": 0, "selected": false, "text": "<p>If adding top margin or padding to <code>body.admin-bar</code> doesn't fix the issue and you want to keep admin bar visible, you could try moving the whole admin bar to the bottom of your page. \nAdd CSS below at the end of your stylesheet:</p>\n\n<pre><code>body.admin-bar #wphead {\n padding-top: 0;\n}\n#wpadminbar {\n top: auto !important;\n bottom: 0;\n position: fixed;\n}\n#wpadminbar .quicklinks .menupop ul {\n position: absolute;\n bottom: 32px;\n background-color: #23282d;\n}\n#wpadminbar .quicklinks .menupop ul + ul {\n bottom: 70px;\n}\n#wpadminbar .quicklinks .menupop ul ul {\n transform: translateY(62px);\n -webkit-transform: translateY(62px);\n -ms-transform: translateY(62px);\n}\n#wpadminbar .quicklinks .menupop ul.ab-sub-secondary {\n bottom: 64px;\n position: absolute;\n}\n@media screen and (max-width: 782px) {\n #wpadminbar .quicklinks .menupop ul {\n bottom: 46px;\n }\n\n #wpadminbar .quicklinks .menupop ul + ul,\n #wpadminbar .quicklinks .menupop ul.ab-sub-secondary {\n bottom: 86px;\n }\n\n #wpadminbar .quicklinks .menupop ul ul {\n transform: translateY(92px);\n -webkit-transform: translateY(92px);\n -ms-transform: translateY(92px);\n }\n}\n</code></pre>\n\n<p>I took CSS from <a href=\"https://poweredbycoffee.co.uk/wordpress-admin-bar-fixed-headers/\" rel=\"nofollow noreferrer\">this tutorial</a> and tested it, it works well.</p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301749", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142398/" ]
I am having a problem with the Wordpress Admin bar covering and overlapping my fixed menu header. The theme originally did not have a fixed menu header but I edited the CSS to add one. Also, I added a background color change for the header's menu (in case this complicates the fix). I have tried using numerous fixes found on StackExchange, Wordpress Blogs, Reddit, Ect. But these fixes moves my slider and body content further down the page, while my fixed header is still showing at the very top of the page covered by the Wordpress Admin Bar still. I have taken screenshots of what happens when I tried using the other fixes found on StackExchange. <https://imgur.com/a/cAI05S5> And I am seeking a solution that does not involve installing "another" plugin because of the "download this plugin to fix your issue and slow down your website at the same time" compromise. The website is not live yet, but I'm building it using a WAMP local server on my PC. This is my code that I used to make my fixed header ``` header.header-default { position: fixed!important; top: 0px!important; z-index: 2000!important; width: 100%!important; } .jumbotron { padding-top: 55px!important; } div.page-header { padding-top: 115px!important; padding-bottom: 25px!important; } ```
One solution to your problem is hiding admin bar from front-end. Maybe there is problem in your css too. To hide admin bar from front-end: 1. To remove the toolbar from your site, go to Users > Your Profile. Scroll down to “Toolbar” and uncheck “Show Toolbar when viewing site.” 2. Add `add_filter(‘show_admin_bar’, ‘__return_false’);` to functions.php of your theme.
301,755
<p>I want to change the word "Tags" in Wordpress to something else, i.e. Related Posts, Locations, etc - I've searched all over and I just cannot find it, can any one help?? </p>
[ { "answer_id": 301758, "author": "Milan Bastola", "author_id": 137372, "author_profile": "https://wordpress.stackexchange.com/users/137372", "pm_score": -1, "selected": false, "text": "<p>My suggestion is, You should try creating custom post types instead changing WP Core functionality. </p>\n\n<p>If you want to change default words of WordPress you should try translation method, please view these two links: </p>\n\n<ol>\n<li><p><a href=\"https://www.ait-themes.club/knowledge-base/how-to-change-fixed-words-in-theme/\" rel=\"nofollow noreferrer\">https://www.ait-themes.club/knowledge-base/how-to-change-fixed-words-in-theme/</a></p></li>\n<li><p><a href=\"https://aristath.github.io/blog/howto-change-plugin-theme-text\" rel=\"nofollow noreferrer\">https://aristath.github.io/blog/howto-change-plugin-theme-text</a></p></li>\n</ol>\n" }, { "answer_id": 301814, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 0, "selected": false, "text": "<p>Provided that your theme and plugins are properly coded to be translatable you can hook in to WordPress’ <code>gettext</code> filter to replace whatever words you want, like this:</p>\n\n<pre><code>function ma_wp_text_convert( $translated_text, $text, $domain ) {\n if ( ! is_admin() ) :\n switch ( $translated_text ) :\n case 'Tag' :\n $translated_text = __( 'Theme', 'mytextdomain' );\n break;\n endswitch; \n endif; \n return $translated_text;\n}\nadd_filter( 'gettext', 'ma_wp_text_convert', 20, 3 );\n</code></pre>\n\n<p>Note that the text you're searching for must match exactly the text given in the theme/plugin/core code, so you will need to do some digging to ensure that you're getting it right.</p>\n\n<p>For example, in the code above the translated text will only match 'Tag' and not 'Tags', so you will need to add another line:</p>\n\n<pre><code> case 'Tags' :\n $translated_text = __( 'Themes', 'mytextdomain' );\n break;\n</code></pre>\n\n<p>Likewise, it won't match the word Tag in <code>Showing All Tags</code>, so you'd need to add one for that too.</p>\n" }, { "answer_id": 380498, "author": "cameronjonesweb", "author_id": 65582, "author_profile": "https://wordpress.stackexchange.com/users/65582", "pm_score": 1, "selected": false, "text": "<p>The other answers here talk about changing how the translation works, which is a bad practice if there are instances of the word &quot;tag&quot; that you actually want to still be tag. What you likely want is to change the labels of the &quot;tag&quot; taxonomy.</p>\n<pre><code>function wpse301755_change_tags_labels( $args, $taxonomy ) {\n if ( 'post_tag' === $taxonomy ) {\n $args['labels'] = array(\n 'name' =&gt; 'Locations',\n 'singular_name' =&gt; 'Location',\n 'menu_name' =&gt; 'Locations',\n );\n }\n return $args;\n}\nadd_filter( 'register_taxonomy_args', 'wpse301755_change_tags_labels', 10, 2 );\n</code></pre>\n<p>That changes the labels of the taxonomy without changing how the word &quot;tag&quot; is translated.</p>\n<p>There are more labels you can customise which you can see here: <a href=\"https://developer.wordpress.org/reference/functions/get_taxonomy_labels/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_taxonomy_labels/</a></p>\n<p>Depending on your use case, it may even be better to register a whole new taxonomy: <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/register_taxonomy/</a></p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142404/" ]
I want to change the word "Tags" in Wordpress to something else, i.e. Related Posts, Locations, etc - I've searched all over and I just cannot find it, can any one help??
The other answers here talk about changing how the translation works, which is a bad practice if there are instances of the word "tag" that you actually want to still be tag. What you likely want is to change the labels of the "tag" taxonomy. ``` function wpse301755_change_tags_labels( $args, $taxonomy ) { if ( 'post_tag' === $taxonomy ) { $args['labels'] = array( 'name' => 'Locations', 'singular_name' => 'Location', 'menu_name' => 'Locations', ); } return $args; } add_filter( 'register_taxonomy_args', 'wpse301755_change_tags_labels', 10, 2 ); ``` That changes the labels of the taxonomy without changing how the word "tag" is translated. There are more labels you can customise which you can see here: <https://developer.wordpress.org/reference/functions/get_taxonomy_labels/> Depending on your use case, it may even be better to register a whole new taxonomy: <https://developer.wordpress.org/reference/functions/register_taxonomy/>
301,761
<p>The theme our site was built with makes the tables look huge and that's fine for almost all of the site but we have one page with an 25-row table that needs to be super compact and simple so it fits in less than one page. Is there a way to tell Wordpress to ignore all themes and table styles for just one section of the site?</p> <p>Also, this may only be relevant to some answers but the table is built and populated by a JS script which is imported into the page by a plugin (Scripts n Styles).</p>
[ { "answer_id": 301758, "author": "Milan Bastola", "author_id": 137372, "author_profile": "https://wordpress.stackexchange.com/users/137372", "pm_score": -1, "selected": false, "text": "<p>My suggestion is, You should try creating custom post types instead changing WP Core functionality. </p>\n\n<p>If you want to change default words of WordPress you should try translation method, please view these two links: </p>\n\n<ol>\n<li><p><a href=\"https://www.ait-themes.club/knowledge-base/how-to-change-fixed-words-in-theme/\" rel=\"nofollow noreferrer\">https://www.ait-themes.club/knowledge-base/how-to-change-fixed-words-in-theme/</a></p></li>\n<li><p><a href=\"https://aristath.github.io/blog/howto-change-plugin-theme-text\" rel=\"nofollow noreferrer\">https://aristath.github.io/blog/howto-change-plugin-theme-text</a></p></li>\n</ol>\n" }, { "answer_id": 301814, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 0, "selected": false, "text": "<p>Provided that your theme and plugins are properly coded to be translatable you can hook in to WordPress’ <code>gettext</code> filter to replace whatever words you want, like this:</p>\n\n<pre><code>function ma_wp_text_convert( $translated_text, $text, $domain ) {\n if ( ! is_admin() ) :\n switch ( $translated_text ) :\n case 'Tag' :\n $translated_text = __( 'Theme', 'mytextdomain' );\n break;\n endswitch; \n endif; \n return $translated_text;\n}\nadd_filter( 'gettext', 'ma_wp_text_convert', 20, 3 );\n</code></pre>\n\n<p>Note that the text you're searching for must match exactly the text given in the theme/plugin/core code, so you will need to do some digging to ensure that you're getting it right.</p>\n\n<p>For example, in the code above the translated text will only match 'Tag' and not 'Tags', so you will need to add another line:</p>\n\n<pre><code> case 'Tags' :\n $translated_text = __( 'Themes', 'mytextdomain' );\n break;\n</code></pre>\n\n<p>Likewise, it won't match the word Tag in <code>Showing All Tags</code>, so you'd need to add one for that too.</p>\n" }, { "answer_id": 380498, "author": "cameronjonesweb", "author_id": 65582, "author_profile": "https://wordpress.stackexchange.com/users/65582", "pm_score": 1, "selected": false, "text": "<p>The other answers here talk about changing how the translation works, which is a bad practice if there are instances of the word &quot;tag&quot; that you actually want to still be tag. What you likely want is to change the labels of the &quot;tag&quot; taxonomy.</p>\n<pre><code>function wpse301755_change_tags_labels( $args, $taxonomy ) {\n if ( 'post_tag' === $taxonomy ) {\n $args['labels'] = array(\n 'name' =&gt; 'Locations',\n 'singular_name' =&gt; 'Location',\n 'menu_name' =&gt; 'Locations',\n );\n }\n return $args;\n}\nadd_filter( 'register_taxonomy_args', 'wpse301755_change_tags_labels', 10, 2 );\n</code></pre>\n<p>That changes the labels of the taxonomy without changing how the word &quot;tag&quot; is translated.</p>\n<p>There are more labels you can customise which you can see here: <a href=\"https://developer.wordpress.org/reference/functions/get_taxonomy_labels/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_taxonomy_labels/</a></p>\n<p>Depending on your use case, it may even be better to register a whole new taxonomy: <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/register_taxonomy/</a></p>\n" } ]
2018/04/24
[ "https://wordpress.stackexchange.com/questions/301761", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142412/" ]
The theme our site was built with makes the tables look huge and that's fine for almost all of the site but we have one page with an 25-row table that needs to be super compact and simple so it fits in less than one page. Is there a way to tell Wordpress to ignore all themes and table styles for just one section of the site? Also, this may only be relevant to some answers but the table is built and populated by a JS script which is imported into the page by a plugin (Scripts n Styles).
The other answers here talk about changing how the translation works, which is a bad practice if there are instances of the word "tag" that you actually want to still be tag. What you likely want is to change the labels of the "tag" taxonomy. ``` function wpse301755_change_tags_labels( $args, $taxonomy ) { if ( 'post_tag' === $taxonomy ) { $args['labels'] = array( 'name' => 'Locations', 'singular_name' => 'Location', 'menu_name' => 'Locations', ); } return $args; } add_filter( 'register_taxonomy_args', 'wpse301755_change_tags_labels', 10, 2 ); ``` That changes the labels of the taxonomy without changing how the word "tag" is translated. There are more labels you can customise which you can see here: <https://developer.wordpress.org/reference/functions/get_taxonomy_labels/> Depending on your use case, it may even be better to register a whole new taxonomy: <https://developer.wordpress.org/reference/functions/register_taxonomy/>
301,797
<p>I'm trying to add an action every time someone presses the 'Publish'-button. I've made this function:</p> <pre><code>function custom_set_category_on_cpt( $post_ID, $post, $update ) { echo '&lt;p&gt;This does not show, unless I hook it onto admin_head or admin_footer&lt;/p&gt;'; if ( 'publish' === $post-&gt;post_status ) { echo '&lt;p&gt;I can't get anything in here to show... Ever!?&lt;/p&gt;'; } add_action( 'save_post', 'custom_set_category_on_cpt', 10 ); // Other attempts, without any change of results //add_action( 'save_post', 'custom_set_category_on_cpt', 10, 3 ); //add_action( 'save_post', 'custom_set_category_on_cpt', 5, 3 ); //add_action( 'save_post', 'custom_set_category_on_cpt', 15, 3 ); </code></pre> <p>I know that the 'save_post'-hook fires, also when it just saves a draft. </p> <p>I've tried a wide variety of things, but I'm unable to get it to work. </p>
[ { "answer_id": 301809, "author": "forsvunnet", "author_id": 45792, "author_profile": "https://wordpress.stackexchange.com/users/45792", "pm_score": 1, "selected": false, "text": "<p>When editing a post using the admin interface the wp-admin/post.php script redirects you after saving the post. This is done to avoid resubmitting the post request if you refresh the page after submitting. It also means that you're not able to output anything during the <code>save_post</code> action.</p>\n\n<pre><code>case 'editpost':\n check_admin_referer('update-post_' . $post_id);\n\n $post_id = edit_post();\n\n // Session cookie flag that the post was saved\n if ( isset( $_COOKIE['wp-saving-post'] ) &amp;&amp; $_COOKIE['wp-saving-post'] === $post_id . '-check' ) {\n setcookie( 'wp-saving-post', $post_id . '-saved', time() + DAY_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl() );\n }\n\n redirect_post($post_id); // Send user on their way while we keep working\n\n exit();\n</code></pre>\n\n<p>You could do what WordPress does and use cookies to store the message you want to display </p>\n\n<pre><code>&lt;?php\n\nclass Your_Class_Name_Here {\n\n /**\n * Setup\n */\n static function setup() {\n add_action( 'save_post', __CLASS__.'::save_post', 10, 2 );\n add_action( 'in_admin_header', __CLASS__.'::display_message' );\n }\n\n /**\n * Action: Save post\n * hooked on save_post\n * @param integer $post_ID\n * @param WP_Post $post\n */\n static function save_post( $post_ID, $post ) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n if ( 'publish' !== $post-&gt;post_status ) {\n return;\n }\n setcookie( 'Your_Class_Name_Here', 'display_message', time() + DAY_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl() );\n }\n\n /**\n * Action: Display message\n * hooked on in_admin_header\n */\n static function display_message() {\n if ( ! isset( $_COOKIE['Your_Class_Name_Here'] ) ) {\n return;\n }\n if ( $_COOKIE['Your_Class_Name_Here'] != 'display_message' ) {\n return;\n }\n // Delete the cookie\n setcookie( 'Your_Class_Name_Here', null, -1, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl() );\n unset( $_COOKIE['Your_Class_Name_Here'] );\n // Output the message\n echo \"Your message here\";\n }\n\n}\n\nYour_Class_Name_Here::setup();\n</code></pre>\n" }, { "answer_id": 301957, "author": "Nitin Sharma", "author_id": 43126, "author_profile": "https://wordpress.stackexchange.com/users/43126", "pm_score": 0, "selected": false, "text": "<p>You also can try below code for specific custom post type only.\n <code>add_action( 'publish_YOUR_CUSTOM_POST_TYPE_SLUG', 'your_function_name', 999, 3 );</code></p>\n" } ]
2018/04/25
[ "https://wordpress.stackexchange.com/questions/301797", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128304/" ]
I'm trying to add an action every time someone presses the 'Publish'-button. I've made this function: ``` function custom_set_category_on_cpt( $post_ID, $post, $update ) { echo '<p>This does not show, unless I hook it onto admin_head or admin_footer</p>'; if ( 'publish' === $post->post_status ) { echo '<p>I can't get anything in here to show... Ever!?</p>'; } add_action( 'save_post', 'custom_set_category_on_cpt', 10 ); // Other attempts, without any change of results //add_action( 'save_post', 'custom_set_category_on_cpt', 10, 3 ); //add_action( 'save_post', 'custom_set_category_on_cpt', 5, 3 ); //add_action( 'save_post', 'custom_set_category_on_cpt', 15, 3 ); ``` I know that the 'save\_post'-hook fires, also when it just saves a draft. I've tried a wide variety of things, but I'm unable to get it to work.
When editing a post using the admin interface the wp-admin/post.php script redirects you after saving the post. This is done to avoid resubmitting the post request if you refresh the page after submitting. It also means that you're not able to output anything during the `save_post` action. ``` case 'editpost': check_admin_referer('update-post_' . $post_id); $post_id = edit_post(); // Session cookie flag that the post was saved if ( isset( $_COOKIE['wp-saving-post'] ) && $_COOKIE['wp-saving-post'] === $post_id . '-check' ) { setcookie( 'wp-saving-post', $post_id . '-saved', time() + DAY_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl() ); } redirect_post($post_id); // Send user on their way while we keep working exit(); ``` You could do what WordPress does and use cookies to store the message you want to display ``` <?php class Your_Class_Name_Here { /** * Setup */ static function setup() { add_action( 'save_post', __CLASS__.'::save_post', 10, 2 ); add_action( 'in_admin_header', __CLASS__.'::display_message' ); } /** * Action: Save post * hooked on save_post * @param integer $post_ID * @param WP_Post $post */ static function save_post( $post_ID, $post ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } if ( 'publish' !== $post->post_status ) { return; } setcookie( 'Your_Class_Name_Here', 'display_message', time() + DAY_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl() ); } /** * Action: Display message * hooked on in_admin_header */ static function display_message() { if ( ! isset( $_COOKIE['Your_Class_Name_Here'] ) ) { return; } if ( $_COOKIE['Your_Class_Name_Here'] != 'display_message' ) { return; } // Delete the cookie setcookie( 'Your_Class_Name_Here', null, -1, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl() ); unset( $_COOKIE['Your_Class_Name_Here'] ); // Output the message echo "Your message here"; } } Your_Class_Name_Here::setup(); ```
301,840
<p>I'm taking my first steps in Gutenberg block development and I'm already stuck. My block JS script makes use of a couple lodash functions (<code>filter</code> and <code>pick</code>). I'm registering my block using the following function:</p> <pre><code>function register_block() { wp_register_script( 'block-script', plugins_url( 'block.build.js', __FILE__ ), array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' ) ); register_block_type( 'my/block', array( 'editor_script' =&gt; 'block-script', ) ); } </code></pre> <p>As you can see I'm adding the lodash lib as a dependency, and checking the page source code it's effectively loaded before my plugin's script. However, I'm getting a <code>ReferenceError: pick is not defined</code> console error.</p> <p>This is the line that calls the <code>pick</code> function:</p> <pre><code>onSelectImages( images ) { this.props.setAttributes( { images: images.map( ( image ) =&gt; pick( image, [ 'alt', 'caption', 'id', 'url' ] ) ), } ); } </code></pre> <p>I don't know what I'm doing wrong. Any ideas?</p> <p>Thanks in advance</p>
[ { "answer_id": 301847, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The problem is that lodash isn't a script dependency, it's an NPM dependency:</p>\n\n<pre><code>array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' )\n</code></pre>\n\n<p>You can't enqueue it this way and expect your application to build. Lodash may be available in WP Admin, but webpack runs in a local Node CLI context, and it doesn't know what <code>lodash</code> is. So instead you need to use <code>npm</code> to acquire the library and include it in your final JS build via babel/webpack/etc. This way webpack/babel know about <code>lodash</code> and can do their job correctly.</p>\n" }, { "answer_id": 301867, "author": "leemon", "author_id": 33049, "author_profile": "https://wordpress.stackexchange.com/users/33049", "pm_score": 3, "selected": true, "text": "<p>In the block script I had to replace:</p>\n\n<pre><code>import pick from 'lodash/pick';\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>const { pick } = lodash;\n</code></pre>\n\n<p>And now it seems to work for me.</p>\n" } ]
2018/04/25
[ "https://wordpress.stackexchange.com/questions/301840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
I'm taking my first steps in Gutenberg block development and I'm already stuck. My block JS script makes use of a couple lodash functions (`filter` and `pick`). I'm registering my block using the following function: ``` function register_block() { wp_register_script( 'block-script', plugins_url( 'block.build.js', __FILE__ ), array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' ) ); register_block_type( 'my/block', array( 'editor_script' => 'block-script', ) ); } ``` As you can see I'm adding the lodash lib as a dependency, and checking the page source code it's effectively loaded before my plugin's script. However, I'm getting a `ReferenceError: pick is not defined` console error. This is the line that calls the `pick` function: ``` onSelectImages( images ) { this.props.setAttributes( { images: images.map( ( image ) => pick( image, [ 'alt', 'caption', 'id', 'url' ] ) ), } ); } ``` I don't know what I'm doing wrong. Any ideas? Thanks in advance
In the block script I had to replace: ``` import pick from 'lodash/pick'; ``` with: ``` const { pick } = lodash; ``` And now it seems to work for me.
301,846
<p>im using this piece of code to show my div only on homepage.</p> <pre><code>&lt;?php if ( is_front_page() ) :?&gt; </code></pre> <p></p> <p>but it's shown on pagination 2, 3 and so on. is there any help regarding to fixing this issue? </p>
[ { "answer_id": 301848, "author": "Shameem Ali", "author_id": 137710, "author_profile": "https://wordpress.stackexchange.com/users/137710", "pm_score": -1, "selected": false, "text": "<p>See: <a href=\"http://codex.wordpress.org/Function_Reference/is_home\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Function_Reference/is_home</a></p>\n\n<pre><code>&lt;?php if(is_home()): ?&gt;\n\n &lt;div&gt;Your div.&lt;/div&gt;\n\n&lt;?php endif;?&gt;\n</code></pre>\n" }, { "answer_id": 301849, "author": "Maan", "author_id": 24762, "author_profile": "https://wordpress.stackexchange.com/users/24762", "pm_score": 2, "selected": true, "text": "<p>Thank you guys for quick response.\nHere is the code that worked for me.</p>\n\n<pre><code>&lt;?php if( is_home() != '' &amp;&amp; !is_paged()) { ?&gt;\n div here\n&lt;?php } ?&gt;\n</code></pre>\n" } ]
2018/04/25
[ "https://wordpress.stackexchange.com/questions/301846", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24762/" ]
im using this piece of code to show my div only on homepage. ``` <?php if ( is_front_page() ) :?> ``` but it's shown on pagination 2, 3 and so on. is there any help regarding to fixing this issue?
Thank you guys for quick response. Here is the code that worked for me. ``` <?php if( is_home() != '' && !is_paged()) { ?> div here <?php } ?> ```