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
238,953
<p>I am trying to insert a small form into a WordPress page that does a minor calculation based on user input and returns an answer. Initially I tried copying the entire thing (HTML and JS (in a <code>&lt;script&gt;</code> tag) in the text editor), which displayed the HTML form fine, but trying to run the JS didn't work.</p> <p>The JS looks like this:</p> <pre><code>function calculateX(){ var inputA, inputB, total; inputA = document.form.inputA.value; inputB = document.form.inputB.value; total = inputA + inputB * 10; document.getElementById("result").innerHTML = parseInt(total); } </code></pre> <p>The HTML form looks like this:</p> <pre><code>&lt;form name="form"&gt; InputA: &lt;input type="text" name="inputA" /&gt;&lt;br /&gt; InputB: &lt;input type="text" name="inputB" /&gt;&lt;br /&gt; &lt;input type="button" value="Calculate" onclick="calculateX()" /&gt;&lt;br /&gt; Your result is: &lt;b&gt;&lt;span id="result"&gt;&lt;/span&gt;&lt;/b&gt; &lt;/form&gt; </code></pre> <p>I later tried creating a plugin that would run the JS while only inserting the above HTML in the page text editor while adding the JS to the <code>calculate.js</code> file. It looked like this:</p> <pre><code> &lt;?php /* Plugin Name: Calculate */ function calculate() { wp_register_script('calculate', plugins_url('/js/calculate.js'), __FILE__), array('jquery'), false); wp_enqueue_script('calculate', plugins_url('/js/calculate.js'), __FILE__); } add_action('wp_enqueue_scripts', 'calculate'); ?&gt; </code></pre> <p>However, neither solution works. I'm pretty new to JavaScript and this is the first time I've attempted to implement a form like this in WordPress by myself, so I'm not entirely sure where it goes wrong.</p> <p>The form is displayed perfectly fine, but when clicking the 'Calculate' button it does nothing.</p> <p><strong>EDIT: See @RRikesh' comments below on the process of fixing this. The code as it stands above works for me now.</strong></p>
[ { "answer_id": 238955, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": -1, "selected": false, "text": "<p>Using jQuery:</p>\n\n<p>First debug and check if the function is getting called. Try <code>alert()</code> in your JS function.</p>\n\n<pre><code>&lt;form name=\"form\"&gt;\n InputA: &lt;input type=\"text\" class=\"inputA\" name=\"inputA\" /&gt;&lt;br /&gt;\n InputB: &lt;input type=\"text\" class=\"inputB\" name=\"inputB\" /&gt;&lt;br /&gt;\n &lt;input type=\"button\" value=\"Calculate\" onclick=\"calculateX()\" /&gt;&lt;br /&gt;\n Your result is: &lt;b&gt;&lt;span id=\"result\"&gt;&lt;/span&gt;&lt;/b&gt;\n&lt;/form&gt;\n\nfunction calculateX(){\n total = jQuery('inputA').val() + jQuery('inputA').val();\n jQuery('#result').html(total);\n}\n</code></pre>\n" }, { "answer_id": 238963, "author": "RRikesh", "author_id": 17305, "author_profile": "https://wordpress.stackexchange.com/users/17305", "pm_score": 1, "selected": false, "text": "<p>You have a bunch of issues:</p>\n<h1>1. WordPress part:</h1>\n<p>Your function is hooked to <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts</code></a> and should be like this:</p>\n<pre><code>function wpse238953_calculate() {\n wp_enqueue_script('calculate', plugins_url('/js/calculate.js'), __FILE__), array('jquery'), false);\n }\n add_action('wp_enqueue_scripts', 'wpse238953_calculate');\n</code></pre>\n<p>Note the different spellings between <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script</code></a></p>\n<h1>2. The HTML/JS part:</h1>\n<p>Let's add some <code>id</code> to the two input fields so that it's easier to target them</p>\n<pre><code>&lt;form name=&quot;form&quot;&gt;\n InputA: &lt;input type=&quot;text&quot; id=&quot;inputA&quot; name=&quot;inputA&quot; /&gt;&lt;br /&gt;\n InputB: &lt;input type=&quot;text&quot; id=&quot;inputB&quot; name=&quot;inputB&quot; /&gt;&lt;br /&gt;\n &lt;input type=&quot;button&quot; id=&quot;calculate&quot; value=&quot;Calculate&quot; /&gt;&lt;br /&gt;\n Your result is: &lt;b&gt;&lt;span id=&quot;result&quot;&gt;&lt;/span&gt;&lt;/b&gt;\n&lt;/form&gt;\n</code></pre>\n<p>Then rewrite your JS and use some jQuery(since you added it as a dependency):</p>\n<pre><code>jQuery(document).ready(function($){\n 'use strict';\n $('#calculate').mousedown(function(){\n var valueA = parseFloat( $('#inputA').val(), 10 ),\n valueB = parseFloat( $('#inputB').val(), 10 ),\n total = ( valueA + valueB ) * 10;\n \n $('#result').text( total );\n });\n});\n</code></pre>\n<p>Read about:</p>\n<ul>\n<li><a href=\"http://api.jquery.com/text/\" rel=\"nofollow noreferrer\">http://api.jquery.com/text/</a></li>\n<li><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat</a></li>\n<li><a href=\"https://api.jquery.com/mousedown/\" rel=\"nofollow noreferrer\">https://api.jquery.com/mousedown/</a></li>\n</ul>\n" } ]
2016/09/12
[ "https://wordpress.stackexchange.com/questions/238953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86933/" ]
I am trying to insert a small form into a WordPress page that does a minor calculation based on user input and returns an answer. Initially I tried copying the entire thing (HTML and JS (in a `<script>` tag) in the text editor), which displayed the HTML form fine, but trying to run the JS didn't work. The JS looks like this: ``` function calculateX(){ var inputA, inputB, total; inputA = document.form.inputA.value; inputB = document.form.inputB.value; total = inputA + inputB * 10; document.getElementById("result").innerHTML = parseInt(total); } ``` The HTML form looks like this: ``` <form name="form"> InputA: <input type="text" name="inputA" /><br /> InputB: <input type="text" name="inputB" /><br /> <input type="button" value="Calculate" onclick="calculateX()" /><br /> Your result is: <b><span id="result"></span></b> </form> ``` I later tried creating a plugin that would run the JS while only inserting the above HTML in the page text editor while adding the JS to the `calculate.js` file. It looked like this: ``` <?php /* Plugin Name: Calculate */ function calculate() { wp_register_script('calculate', plugins_url('/js/calculate.js'), __FILE__), array('jquery'), false); wp_enqueue_script('calculate', plugins_url('/js/calculate.js'), __FILE__); } add_action('wp_enqueue_scripts', 'calculate'); ?> ``` However, neither solution works. I'm pretty new to JavaScript and this is the first time I've attempted to implement a form like this in WordPress by myself, so I'm not entirely sure where it goes wrong. The form is displayed perfectly fine, but when clicking the 'Calculate' button it does nothing. **EDIT: See @RRikesh' comments below on the process of fixing this. The code as it stands above works for me now.**
You have a bunch of issues: 1. WordPress part: ================== Your function is hooked to [`wp_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) and should be like this: ``` function wpse238953_calculate() { wp_enqueue_script('calculate', plugins_url('/js/calculate.js'), __FILE__), array('jquery'), false); } add_action('wp_enqueue_scripts', 'wpse238953_calculate'); ``` Note the different spellings between [`wp_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) and [`wp_enqueue_script`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) 2. The HTML/JS part: ==================== Let's add some `id` to the two input fields so that it's easier to target them ``` <form name="form"> InputA: <input type="text" id="inputA" name="inputA" /><br /> InputB: <input type="text" id="inputB" name="inputB" /><br /> <input type="button" id="calculate" value="Calculate" /><br /> Your result is: <b><span id="result"></span></b> </form> ``` Then rewrite your JS and use some jQuery(since you added it as a dependency): ``` jQuery(document).ready(function($){ 'use strict'; $('#calculate').mousedown(function(){ var valueA = parseFloat( $('#inputA').val(), 10 ), valueB = parseFloat( $('#inputB').val(), 10 ), total = ( valueA + valueB ) * 10; $('#result').text( total ); }); }); ``` Read about: * <http://api.jquery.com/text/> * <https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat> * <https://api.jquery.com/mousedown/>
238,982
<p>I have two different instances of the same server (one for development, one for deployment), built independently but basically the same (same OS, same WordPress version, same content etc.).</p> <p>However, I'm confused about the configuration: it looks to me like they're configured the same (except that the deployment server is told not to write errors/warnings to the browser).</p> <p>Both configurations specify <code>ini_set( 'error_log', '/var/log/wp-debug.log' );</code> and that file is indeed created by both; however, on one server anything written using <code>error_log(...)</code> goes to <code>/var/log/wp-debug.log</code> whereas on the other server, such output instead goes to <code>/var/log/apache2/error.log</code> (although PHP errors and warnings go to <code>/var/log/wp-debug.log</code>).</p> <p>I've tried playing with the defined values of <code>WP_DEBUG</code>, <code>WP_DEBUG_LOG</code> and <code>WP_DEBUG_DISPLAY</code> as well as changing what <code>display_errors</code> is set to via <code>ini_set(...)</code> but nothing seems to make any difference.</p> <p>Can I specify somewhere that I want the output of <code>error_log(...)</code> calls to go to one or other of these logs? (I'd like the output always to go to the Apache <code>error.log</code> because that extra information I want to use.)</p>
[ { "answer_id": 238990, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>On WP side the only handling it does is setting log to <code>WP_CONTENT_DIR . '/debug.log'</code> if <code>WP_DEBUG_LOG</code> is enabled (highly bad idea in production environment as public location). If I remember right the very early implementations of this constant allowed to customize the path, but that's no longer the case.</p>\n\n<p>In my experience <code>ini_set( 'log_errors', 1 ); ini_set( 'error_log', '/path' )</code> in <code>wp-config.php</code> should be sufficient (if you don't enable <code>WP_DEBUG_LOG</code> which will override it).</p>\n\n<p>Your second case sounds strange. I would expect errors to go one destination or another, but not to two separate log files. It might be that something <em>changes</em> the configuration during runtime. It's impossible to say without hands on troubleshooting.</p>\n" }, { "answer_id": 239105, "author": "IpsRich", "author_id": 64675, "author_profile": "https://wordpress.stackexchange.com/users/64675", "pm_score": 1, "selected": true, "text": "<p>As described elsewhere on this page, in my case the solution was simply to reset the value of PHP's <code>error_log</code> setting. I did this by adding to the end of my <code>/var/www/html/wp-config.php</code>:</p>\n\n<pre><code>ini_restore('error_log');\n</code></pre>\n\n<p>One important point: I ended up putting this right at the end because it didn't seem to take effect when included just after the various <code>define('WP_DEBUG...', ...);</code> lines.</p>\n\n<p>Thanks to <strong>Rarst</strong> and <strong>bynicolas</strong> for their advice, which helped lead me to this solution.</p>\n" } ]
2016/09/12
[ "https://wordpress.stackexchange.com/questions/238982", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64675/" ]
I have two different instances of the same server (one for development, one for deployment), built independently but basically the same (same OS, same WordPress version, same content etc.). However, I'm confused about the configuration: it looks to me like they're configured the same (except that the deployment server is told not to write errors/warnings to the browser). Both configurations specify `ini_set( 'error_log', '/var/log/wp-debug.log' );` and that file is indeed created by both; however, on one server anything written using `error_log(...)` goes to `/var/log/wp-debug.log` whereas on the other server, such output instead goes to `/var/log/apache2/error.log` (although PHP errors and warnings go to `/var/log/wp-debug.log`). I've tried playing with the defined values of `WP_DEBUG`, `WP_DEBUG_LOG` and `WP_DEBUG_DISPLAY` as well as changing what `display_errors` is set to via `ini_set(...)` but nothing seems to make any difference. Can I specify somewhere that I want the output of `error_log(...)` calls to go to one or other of these logs? (I'd like the output always to go to the Apache `error.log` because that extra information I want to use.)
As described elsewhere on this page, in my case the solution was simply to reset the value of PHP's `error_log` setting. I did this by adding to the end of my `/var/www/html/wp-config.php`: ``` ini_restore('error_log'); ``` One important point: I ended up putting this right at the end because it didn't seem to take effect when included just after the various `define('WP_DEBUG...', ...);` lines. Thanks to **Rarst** and **bynicolas** for their advice, which helped lead me to this solution.
238,994
<p>I'm having a customer who wants a WordPress page, and I don't have the best overview of the plugins and possibilities for this exact requirement my customer wants.</p> <p>He arranges an seminar once a year, so for each year the site text and pictures look very different, but the main theme of the page stays the same. When the seminar is over for e.g. 2015, he wants to start fresh with the year 2016. The tricky thing, and my question is: He wants to make it possible to browse the 2013, 2014, 2015 ... (etc) versions of the page. So people can look backwards in the history of seminars. <em>Now keep in mind this is a page, and not a blog - so you can't just sort blog entries by the year.</em></p> <p>Now obviously the easiest but also the dirtiest trick to do this, is just to copy the database and page into a folder and link it. Though I was wondering if there is a more clean way of doing this - maybe a plugin of some sort or just some functions I did not think about.</p> <p>It's a big plus, but not the definite requirement that it's easy enough for my customer to perform this yearly sweep on his own. With little knowledge of computers and websites. If not, still tell me your recommendation - then I will just help him that one time a year.</p>
[ { "answer_id": 238990, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>On WP side the only handling it does is setting log to <code>WP_CONTENT_DIR . '/debug.log'</code> if <code>WP_DEBUG_LOG</code> is enabled (highly bad idea in production environment as public location). If I remember right the very early implementations of this constant allowed to customize the path, but that's no longer the case.</p>\n\n<p>In my experience <code>ini_set( 'log_errors', 1 ); ini_set( 'error_log', '/path' )</code> in <code>wp-config.php</code> should be sufficient (if you don't enable <code>WP_DEBUG_LOG</code> which will override it).</p>\n\n<p>Your second case sounds strange. I would expect errors to go one destination or another, but not to two separate log files. It might be that something <em>changes</em> the configuration during runtime. It's impossible to say without hands on troubleshooting.</p>\n" }, { "answer_id": 239105, "author": "IpsRich", "author_id": 64675, "author_profile": "https://wordpress.stackexchange.com/users/64675", "pm_score": 1, "selected": true, "text": "<p>As described elsewhere on this page, in my case the solution was simply to reset the value of PHP's <code>error_log</code> setting. I did this by adding to the end of my <code>/var/www/html/wp-config.php</code>:</p>\n\n<pre><code>ini_restore('error_log');\n</code></pre>\n\n<p>One important point: I ended up putting this right at the end because it didn't seem to take effect when included just after the various <code>define('WP_DEBUG...', ...);</code> lines.</p>\n\n<p>Thanks to <strong>Rarst</strong> and <strong>bynicolas</strong> for their advice, which helped lead me to this solution.</p>\n" } ]
2016/09/12
[ "https://wordpress.stackexchange.com/questions/238994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102661/" ]
I'm having a customer who wants a WordPress page, and I don't have the best overview of the plugins and possibilities for this exact requirement my customer wants. He arranges an seminar once a year, so for each year the site text and pictures look very different, but the main theme of the page stays the same. When the seminar is over for e.g. 2015, he wants to start fresh with the year 2016. The tricky thing, and my question is: He wants to make it possible to browse the 2013, 2014, 2015 ... (etc) versions of the page. So people can look backwards in the history of seminars. *Now keep in mind this is a page, and not a blog - so you can't just sort blog entries by the year.* Now obviously the easiest but also the dirtiest trick to do this, is just to copy the database and page into a folder and link it. Though I was wondering if there is a more clean way of doing this - maybe a plugin of some sort or just some functions I did not think about. It's a big plus, but not the definite requirement that it's easy enough for my customer to perform this yearly sweep on his own. With little knowledge of computers and websites. If not, still tell me your recommendation - then I will just help him that one time a year.
As described elsewhere on this page, in my case the solution was simply to reset the value of PHP's `error_log` setting. I did this by adding to the end of my `/var/www/html/wp-config.php`: ``` ini_restore('error_log'); ``` One important point: I ended up putting this right at the end because it didn't seem to take effect when included just after the various `define('WP_DEBUG...', ...);` lines. Thanks to **Rarst** and **bynicolas** for their advice, which helped lead me to this solution.
239,006
<p>I need a stylesheet to be added to the header before anything else. That means before any styles or scripts that are automatically added by any of the plugins I'm also using.</p> <p>I figured I could add this stylesheet with wp_enqueue_script, but I'm not sure how to force it to be loaded before other stylesheets or scripts that I do not have control over.</p> <p>Thanks.</p> <p>*This is for a theme which I need to add a stylesheet to. This is not for a plugin I'm building.</p>
[ { "answer_id": 239008, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 3, "selected": true, "text": "<p>The tag that you want to call to execute your function is the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\"><code>wp_head()</code></a> with a priority of <code>1</code>.</p>\n\n<p>In your child theme's <a href=\"https://codex.wordpress.org/Child_Themes#Using_functions.php\" rel=\"nofollow\"><code>functions.php</code></a> file, add the following:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_239006_style', 1 );\nfunction wpse_239006_style() {\n wp_enqueue_script();\n}\n</code></pre>\n" }, { "answer_id": 353919, "author": "AndreyP", "author_id": 17413, "author_profile": "https://wordpress.stackexchange.com/users/17413", "pm_score": 0, "selected": false, "text": "<p>To add stylesheet before other stylesheets, use <code>wp_register_style()</code> instead of <code>wp_enqueue_style()</code>, and then manually add your style to be first at queue:</p>\n\n<pre><code>wp_register_style('handle', get_template_directory_uri().\"/custom.css\");\narray_unshift(wp_styles()-&gt;queue, 'handle');\n</code></pre>\n" } ]
2016/09/12
[ "https://wordpress.stackexchange.com/questions/239006", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24617/" ]
I need a stylesheet to be added to the header before anything else. That means before any styles or scripts that are automatically added by any of the plugins I'm also using. I figured I could add this stylesheet with wp\_enqueue\_script, but I'm not sure how to force it to be loaded before other stylesheets or scripts that I do not have control over. Thanks. \*This is for a theme which I need to add a stylesheet to. This is not for a plugin I'm building.
The tag that you want to call to execute your function is the [`wp_head()`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head) with a priority of `1`. In your child theme's [`functions.php`](https://codex.wordpress.org/Child_Themes#Using_functions.php) file, add the following: ``` add_action( 'wp_head', 'wpse_239006_style', 1 ); function wpse_239006_style() { wp_enqueue_script(); } ```
239,042
<p>I'm currently using wp_list_pages to show site pages.</p> <p>It doesn't include private pages, so I need to find a way to produce a list of them too.</p> <p>I can do it with a plugin, but it includes various options I don't need and I prefer to hardcode something appropriate into a template.</p>
[ { "answer_id": 239008, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 3, "selected": true, "text": "<p>The tag that you want to call to execute your function is the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\"><code>wp_head()</code></a> with a priority of <code>1</code>.</p>\n\n<p>In your child theme's <a href=\"https://codex.wordpress.org/Child_Themes#Using_functions.php\" rel=\"nofollow\"><code>functions.php</code></a> file, add the following:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_239006_style', 1 );\nfunction wpse_239006_style() {\n wp_enqueue_script();\n}\n</code></pre>\n" }, { "answer_id": 353919, "author": "AndreyP", "author_id": 17413, "author_profile": "https://wordpress.stackexchange.com/users/17413", "pm_score": 0, "selected": false, "text": "<p>To add stylesheet before other stylesheets, use <code>wp_register_style()</code> instead of <code>wp_enqueue_style()</code>, and then manually add your style to be first at queue:</p>\n\n<pre><code>wp_register_style('handle', get_template_directory_uri().\"/custom.css\");\narray_unshift(wp_styles()-&gt;queue, 'handle');\n</code></pre>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63350/" ]
I'm currently using wp\_list\_pages to show site pages. It doesn't include private pages, so I need to find a way to produce a list of them too. I can do it with a plugin, but it includes various options I don't need and I prefer to hardcode something appropriate into a template.
The tag that you want to call to execute your function is the [`wp_head()`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head) with a priority of `1`. In your child theme's [`functions.php`](https://codex.wordpress.org/Child_Themes#Using_functions.php) file, add the following: ``` add_action( 'wp_head', 'wpse_239006_style', 1 ); function wpse_239006_style() { wp_enqueue_script(); } ```
239,044
<p>So I need to add additional fields in the wordpress tiny mce pop up</p> <p>My current Code</p> <pre><code>(function () { tinymce.PluginManager.add('aptmce_btn', function (editor, url) { editor.addButton('aptmce_btn', { text: 'Add popup', icon: false, onclick: function () { editor.windowManager.open({ title: 'Enter Your PopUp Contents', body: [ { type: 'textbox', name: 'textboxName', label: 'Title', value: '' }, { type: 'textbox', name: 'multilineName', label: 'Content', value: '', multiline: true, minWidth: 300, minHeight: 100 }, ], onsubmit: function (e) { editor.insertContent('[show_popup title="' + e.data.textboxName + '" content="' + e.data.multilineName + '"]'); } }); } }); }); })(); </code></pre> <p>I can a text box and a textarea. But I have having issues adding the following </p> <ul> <li>A drop down</li> <li>A checkbox</li> <li>A radio box</li> </ul> <p>I have also had a look at <a href="http://archive.tinymce.com/wiki.php/Tutorials:Creating_a_plugin" rel="nofollow">this link</a> but nothing is coming up</p> <p>Could one of you let me know how can I add the desired fields?</p> <p>Thanks</p>
[ { "answer_id": 239048, "author": "David Navia", "author_id": 92828, "author_profile": "https://wordpress.stackexchange.com/users/92828", "pm_score": 0, "selected": false, "text": "<p>I've been two days fighting this Tinymce just for make a simple data validation and found this good stuff:</p>\n\n<p>1- Contains all field types supported by Tinymce windowmanager <a href=\"https://jsfiddle.net/aeutaoLf/2/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/aeutaoLf/2/</a></p>\n\n<p>2.- Contains a way to validate windowmanager data before closing <a href=\"https://stackoverflow.com/questions/34783759/how-to-validate-tinymce-popup-textbox-value#answer-38765360\">https://stackoverflow.com/questions/34783759/how-to-validate-tinymce-popup-textbox-value#answer-38765360</a></p>\n\n<p>Hope it helps you.</p>\n" }, { "answer_id": 239050, "author": "mlimon", "author_id": 64458, "author_profile": "https://wordpress.stackexchange.com/users/64458", "pm_score": 1, "selected": false, "text": "<p>See here, I think it's enough for making any kind of TinyMCE Editor button with extended options like dropdown etc</p>\n\n<p><a href=\"https://www.gavick.com/blog/wordpress-tinymce-custom-buttons\" rel=\"nofollow\">https://www.gavick.com/blog/wordpress-tinymce-custom-buttons</a></p>\n\n<p>Anyway if we came down to dropdown, checkbox and radio button on Popup, here is a demonstration.</p>\n\n<pre><code>(function () {\ntinymce.PluginManager.add('aptmce_btn', function (editor, url) {\n editor.addButton('aptmce_btn', {\n text: 'Add popup',\n icon: false,\n onclick: function () {\n editor.windowManager.open({\n title: 'Enter Your PopUp Contents',\n body: [\n {\n type: 'textbox',\n name: 'textboxName',\n label: 'Title',\n value: ''\n\n },\n {\n type: 'textbox',\n name: 'multilineName',\n label: 'Content',\n value: '',\n multiline: true,\n minWidth: 300,\n minHeight: 100\n },\n {\n type: 'listbox', \n name: 'timeformat', \n label: 'Time Format', \n 'values': [\n {text: 'AM', value: 'am'},\n {text: 'PM', value: 'pm'}\n ]\n },\n {\n type: 'checkbox',\n name: 'blank',\n label: 'Open link in a new tab'\n },\n {\n type: 'radio',\n name: 'active',\n label: 'Active Something'\n }\n\n\n ],\n onsubmit: function (e) {\n target = '';\n if(e.data.blank === true) {\n target += 'newtab=\"on\"';\n }\n editor.insertContent('[show_popup title=\"' + e.data.textboxName + '\" content=\"' + e.data.multilineName + '\" timeformat=\"' + e.data.timeformat + '\" something=\"' + e.data.active + '\" ' + target + ' ]');\n }\n });\n }\n });\n });\n})();\n</code></pre>\n\n<p>Remember One thing, radio type will act like a checkbox because radio button not complete yet, see here <a href=\"https://github.com/tinymce/tinymce/blob/ca0f454b9001b9f20aa26349b25f6d839c1a1146/js/tinymce/skins/lightgray/Radio.less\" rel=\"nofollow\">https://github.com/tinymce/tinymce/blob/ca0f454b9001b9f20aa26349b25f6d839c1a1146/js/tinymce/skins/lightgray/Radio.less</a></p>\n\n<p>But if you want to multiple radio button options then you can use listbox (Dropdown) instead multiple radio types.</p>\n\n<p>Hope it helps you.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239044", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80397/" ]
So I need to add additional fields in the wordpress tiny mce pop up My current Code ``` (function () { tinymce.PluginManager.add('aptmce_btn', function (editor, url) { editor.addButton('aptmce_btn', { text: 'Add popup', icon: false, onclick: function () { editor.windowManager.open({ title: 'Enter Your PopUp Contents', body: [ { type: 'textbox', name: 'textboxName', label: 'Title', value: '' }, { type: 'textbox', name: 'multilineName', label: 'Content', value: '', multiline: true, minWidth: 300, minHeight: 100 }, ], onsubmit: function (e) { editor.insertContent('[show_popup title="' + e.data.textboxName + '" content="' + e.data.multilineName + '"]'); } }); } }); }); })(); ``` I can a text box and a textarea. But I have having issues adding the following * A drop down * A checkbox * A radio box I have also had a look at [this link](http://archive.tinymce.com/wiki.php/Tutorials:Creating_a_plugin) but nothing is coming up Could one of you let me know how can I add the desired fields? Thanks
See here, I think it's enough for making any kind of TinyMCE Editor button with extended options like dropdown etc <https://www.gavick.com/blog/wordpress-tinymce-custom-buttons> Anyway if we came down to dropdown, checkbox and radio button on Popup, here is a demonstration. ``` (function () { tinymce.PluginManager.add('aptmce_btn', function (editor, url) { editor.addButton('aptmce_btn', { text: 'Add popup', icon: false, onclick: function () { editor.windowManager.open({ title: 'Enter Your PopUp Contents', body: [ { type: 'textbox', name: 'textboxName', label: 'Title', value: '' }, { type: 'textbox', name: 'multilineName', label: 'Content', value: '', multiline: true, minWidth: 300, minHeight: 100 }, { type: 'listbox', name: 'timeformat', label: 'Time Format', 'values': [ {text: 'AM', value: 'am'}, {text: 'PM', value: 'pm'} ] }, { type: 'checkbox', name: 'blank', label: 'Open link in a new tab' }, { type: 'radio', name: 'active', label: 'Active Something' } ], onsubmit: function (e) { target = ''; if(e.data.blank === true) { target += 'newtab="on"'; } editor.insertContent('[show_popup title="' + e.data.textboxName + '" content="' + e.data.multilineName + '" timeformat="' + e.data.timeformat + '" something="' + e.data.active + '" ' + target + ' ]'); } }); } }); }); })(); ``` Remember One thing, radio type will act like a checkbox because radio button not complete yet, see here <https://github.com/tinymce/tinymce/blob/ca0f454b9001b9f20aa26349b25f6d839c1a1146/js/tinymce/skins/lightgray/Radio.less> But if you want to multiple radio button options then you can use listbox (Dropdown) instead multiple radio types. Hope it helps you.
239,071
<p>This <a href="https://wordpress.stackexchange.com/questions/4725/how-to-change-a-users-role/191433#191433">Stack response</a> explains how to change the role of a given user. Is there a way to execute that when the page loads?</p> <p>I run a language school and there are unique login destinations for Prospective, Active and Inactive students depending on the desired action that I want them to take. Once they make a purchase, I would like them to become Active so that they're not, for instance, looking at taking a trial lesson.</p>
[ { "answer_id": 239048, "author": "David Navia", "author_id": 92828, "author_profile": "https://wordpress.stackexchange.com/users/92828", "pm_score": 0, "selected": false, "text": "<p>I've been two days fighting this Tinymce just for make a simple data validation and found this good stuff:</p>\n\n<p>1- Contains all field types supported by Tinymce windowmanager <a href=\"https://jsfiddle.net/aeutaoLf/2/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/aeutaoLf/2/</a></p>\n\n<p>2.- Contains a way to validate windowmanager data before closing <a href=\"https://stackoverflow.com/questions/34783759/how-to-validate-tinymce-popup-textbox-value#answer-38765360\">https://stackoverflow.com/questions/34783759/how-to-validate-tinymce-popup-textbox-value#answer-38765360</a></p>\n\n<p>Hope it helps you.</p>\n" }, { "answer_id": 239050, "author": "mlimon", "author_id": 64458, "author_profile": "https://wordpress.stackexchange.com/users/64458", "pm_score": 1, "selected": false, "text": "<p>See here, I think it's enough for making any kind of TinyMCE Editor button with extended options like dropdown etc</p>\n\n<p><a href=\"https://www.gavick.com/blog/wordpress-tinymce-custom-buttons\" rel=\"nofollow\">https://www.gavick.com/blog/wordpress-tinymce-custom-buttons</a></p>\n\n<p>Anyway if we came down to dropdown, checkbox and radio button on Popup, here is a demonstration.</p>\n\n<pre><code>(function () {\ntinymce.PluginManager.add('aptmce_btn', function (editor, url) {\n editor.addButton('aptmce_btn', {\n text: 'Add popup',\n icon: false,\n onclick: function () {\n editor.windowManager.open({\n title: 'Enter Your PopUp Contents',\n body: [\n {\n type: 'textbox',\n name: 'textboxName',\n label: 'Title',\n value: ''\n\n },\n {\n type: 'textbox',\n name: 'multilineName',\n label: 'Content',\n value: '',\n multiline: true,\n minWidth: 300,\n minHeight: 100\n },\n {\n type: 'listbox', \n name: 'timeformat', \n label: 'Time Format', \n 'values': [\n {text: 'AM', value: 'am'},\n {text: 'PM', value: 'pm'}\n ]\n },\n {\n type: 'checkbox',\n name: 'blank',\n label: 'Open link in a new tab'\n },\n {\n type: 'radio',\n name: 'active',\n label: 'Active Something'\n }\n\n\n ],\n onsubmit: function (e) {\n target = '';\n if(e.data.blank === true) {\n target += 'newtab=\"on\"';\n }\n editor.insertContent('[show_popup title=\"' + e.data.textboxName + '\" content=\"' + e.data.multilineName + '\" timeformat=\"' + e.data.timeformat + '\" something=\"' + e.data.active + '\" ' + target + ' ]');\n }\n });\n }\n });\n });\n})();\n</code></pre>\n\n<p>Remember One thing, radio type will act like a checkbox because radio button not complete yet, see here <a href=\"https://github.com/tinymce/tinymce/blob/ca0f454b9001b9f20aa26349b25f6d839c1a1146/js/tinymce/skins/lightgray/Radio.less\" rel=\"nofollow\">https://github.com/tinymce/tinymce/blob/ca0f454b9001b9f20aa26349b25f6d839c1a1146/js/tinymce/skins/lightgray/Radio.less</a></p>\n\n<p>But if you want to multiple radio button options then you can use listbox (Dropdown) instead multiple radio types.</p>\n\n<p>Hope it helps you.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96983/" ]
This [Stack response](https://wordpress.stackexchange.com/questions/4725/how-to-change-a-users-role/191433#191433) explains how to change the role of a given user. Is there a way to execute that when the page loads? I run a language school and there are unique login destinations for Prospective, Active and Inactive students depending on the desired action that I want them to take. Once they make a purchase, I would like them to become Active so that they're not, for instance, looking at taking a trial lesson.
See here, I think it's enough for making any kind of TinyMCE Editor button with extended options like dropdown etc <https://www.gavick.com/blog/wordpress-tinymce-custom-buttons> Anyway if we came down to dropdown, checkbox and radio button on Popup, here is a demonstration. ``` (function () { tinymce.PluginManager.add('aptmce_btn', function (editor, url) { editor.addButton('aptmce_btn', { text: 'Add popup', icon: false, onclick: function () { editor.windowManager.open({ title: 'Enter Your PopUp Contents', body: [ { type: 'textbox', name: 'textboxName', label: 'Title', value: '' }, { type: 'textbox', name: 'multilineName', label: 'Content', value: '', multiline: true, minWidth: 300, minHeight: 100 }, { type: 'listbox', name: 'timeformat', label: 'Time Format', 'values': [ {text: 'AM', value: 'am'}, {text: 'PM', value: 'pm'} ] }, { type: 'checkbox', name: 'blank', label: 'Open link in a new tab' }, { type: 'radio', name: 'active', label: 'Active Something' } ], onsubmit: function (e) { target = ''; if(e.data.blank === true) { target += 'newtab="on"'; } editor.insertContent('[show_popup title="' + e.data.textboxName + '" content="' + e.data.multilineName + '" timeformat="' + e.data.timeformat + '" something="' + e.data.active + '" ' + target + ' ]'); } }); } }); }); })(); ``` Remember One thing, radio type will act like a checkbox because radio button not complete yet, see here <https://github.com/tinymce/tinymce/blob/ca0f454b9001b9f20aa26349b25f6d839c1a1146/js/tinymce/skins/lightgray/Radio.less> But if you want to multiple radio button options then you can use listbox (Dropdown) instead multiple radio types. Hope it helps you.
239,093
<p>I have got something like this:</p> <pre><code>$taxonomies = get_object_taxonomies('my_post_type'); foreach($taxonomies as $tax){ $args['labels'] = get_taxonomy_labels( (object) $args ); $args['label'] = $args['labels']-&gt;singular_name; echo $args['label']; } </code></pre> <p>which gives me “Tag” each time, for post_tags but also for all the other (custom) taxonomies. How can I get the label for each $tax ?</p> <p>Thanks</p> <p>ps : by label I mean labels I register when creating my custom taxonomy like this <code>$labels = array( 'name' =&gt; my_custom_taxonomies, 'singular_name' =&gt; my_custom_taxonomy );</code></p>
[ { "answer_id": 239097, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p><strong>EDIT</strong>\nSince I missunderstood your question at first, here's the update that should do what you want.</p>\n\n<pre><code>$taxonomies = get_object_taxonomies( 'my_post_type', 'object' );\n\nforeach($taxonomies as $tax){\n\n echo $tax-&gt;labels-&gt;singular_name;\n\n}\n</code></pre>\n\n<p>Basically, you need to specify to the <code>get_object_taxonomies</code> function that you want an object to be returned.</p>\n\n<p>In your function, I'm not sure where the <code>$args</code> come from and put as is, it can't work.</p>\n\n<p>Finally, use the correct syntax to work with an object. You access the object property with <code>-&gt;</code></p>\n\n<hr>\n\n<p><strong>ORIGINAL</strong></p>\n\n<p>I believe you are looking for the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> function. So you would have something like this:</p>\n\n<pre><code>// Retrieve the taxonomies for your custom post type\n$cpt_taxes = get_object_taxonomies( 'my_post_type', 'object' );\n\n// Build an array of taxonomies slugs to be used in our $args array below to filter only taxes we need.\nforeach( $cpt_taxes as $cpt_tax ){\n $taxonomies[] = $cpt_tax-&gt;name;\n}\n\n// Supply our $args array for the get_terms() function with our newly created $taxonomies array.\n$args = array( \n 'taxonomy' =&gt; $taxonomies,\n 'hide_empty' =&gt; false, \n);\n$terms = get_terms( $args );\n\n\n// Go over the results of the get_terms function and echo each term name.\nforeach( $terms as $term ){\n\n echo $term-&gt;name;\n\n}\n</code></pre>\n" }, { "answer_id": 239102, "author": "Malisa", "author_id": 71627, "author_profile": "https://wordpress.stackexchange.com/users/71627", "pm_score": 0, "selected": false, "text": "<p>Now, I'm not really up to speed on object, object terms, so please be kind..\n@This will return what your after, but not 100% sure its the right way, open to improvement from professional :)</p>\n\n<pre><code>$taxonomies = get_object_taxonomies('dt_properties');\n\nforeach($taxonomies as $tax) {\n $each_tax = get_taxonomy($tax);\n echo '&lt;pre&gt;';\n print_r($each_tax-&gt;labels-&gt;singular_name);\n echo '&lt;/pre&gt;';\n}\n</code></pre>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97280/" ]
I have got something like this: ``` $taxonomies = get_object_taxonomies('my_post_type'); foreach($taxonomies as $tax){ $args['labels'] = get_taxonomy_labels( (object) $args ); $args['label'] = $args['labels']->singular_name; echo $args['label']; } ``` which gives me “Tag” each time, for post\_tags but also for all the other (custom) taxonomies. How can I get the label for each $tax ? Thanks ps : by label I mean labels I register when creating my custom taxonomy like this `$labels = array( 'name' => my_custom_taxonomies, 'singular_name' => my_custom_taxonomy );`
**EDIT** Since I missunderstood your question at first, here's the update that should do what you want. ``` $taxonomies = get_object_taxonomies( 'my_post_type', 'object' ); foreach($taxonomies as $tax){ echo $tax->labels->singular_name; } ``` Basically, you need to specify to the `get_object_taxonomies` function that you want an object to be returned. In your function, I'm not sure where the `$args` come from and put as is, it can't work. Finally, use the correct syntax to work with an object. You access the object property with `->` --- **ORIGINAL** I believe you are looking for the [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) function. So you would have something like this: ``` // Retrieve the taxonomies for your custom post type $cpt_taxes = get_object_taxonomies( 'my_post_type', 'object' ); // Build an array of taxonomies slugs to be used in our $args array below to filter only taxes we need. foreach( $cpt_taxes as $cpt_tax ){ $taxonomies[] = $cpt_tax->name; } // Supply our $args array for the get_terms() function with our newly created $taxonomies array. $args = array( 'taxonomy' => $taxonomies, 'hide_empty' => false, ); $terms = get_terms( $args ); // Go over the results of the get_terms function and echo each term name. foreach( $terms as $term ){ echo $term->name; } ```
239,095
<p>I have the registration workflow set so that my user have to fill out a gravity forms user registration form and then activate their account via a link in an email. The email link sends them to a page that tells the user whether their registration has been successful or a failure. Up on success, I would like my users to click on a password reset link on the activation success page to set their password. I keep getting an invalid link message when I construct the reset link. How do I do construct a valid password reset link?? Here is what I have so far:</p> <pre><code>&lt;?php global $gw_activate_template; extract( $gw_activate_template-&gt;result ); $url = is_multisite() ? get_blogaddress_by_id( (int) $blog_id ) : home_url('', 'http'); $user = new WP_User( (int) $user_id ); ?&gt; &lt;h2&gt;&lt;?php _e('Your account is now active!'); ?&gt;&lt;/h2&gt; &lt;div id="signup-welcome"&gt; &lt;p&gt;&lt;span class="h3"&gt;&lt;?php _e('Username:'); ?&gt;&lt;/span&gt; &lt;?php echo $user-&gt;user_login ?&gt;&lt;/p&gt; &lt;p&gt;To set your password, select the following link: &lt;a href="http://example.com/wp-login.php?action=rp&amp;key=&lt;?php echo $gw_activate_template-&gt;get_activation_key(); ?&gt;&amp;login=&lt;?php echo $user-&gt;user_login; ?&gt;" &gt;http://example.com/wp-login.php?action=rp&amp;amp;key=&lt;?php echo $gw_activate_template-&gt;get_activation_key(); ?&gt;&amp;amp;login=&lt;?php echo $user-&gt;user_login; ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php if ( $url != network_home_url('', 'http') ) : ?&gt; &lt;p class="view"&gt;&lt;?php printf( __('Your account is now activated. &lt;a href="%1$s"&gt;View the site&lt;/a&gt; or &lt;a href="%2$s"&gt;Log in&lt;/a&gt;'), $url, $url . 'wp-login.php' ); ?&gt;&lt;/p&gt; &lt;?php else: ?&gt; &lt;p class="view"&gt;&lt;?php printf( __('Your account is now activated. &lt;a href="%1$s"&gt;Log in&lt;/a&gt; or go back to the &lt;a href="%2$s"&gt;homepage&lt;/a&gt;.' ), network_site_url('wp-login.php', 'login'), network_home_url() ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 239150, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>I am not sure what link are you trying to build and how it ties to specifics of Gravity Forms (questions about which are better aimed at them :)</p>\n\n<p>In native WP case the API method to produce lost password link is generated like this <code>wp_lostpassword_url( home_url() )</code> (redirect argument optional) and resulting URL has following format: <code>\nhttp://example.com/wp-login.php?action=lostpassword&amp;redirect_to=http://example.com</code>.</p>\n" }, { "answer_id": 239370, "author": "ermSO", "author_id": 102710, "author_profile": "https://wordpress.stackexchange.com/users/102710", "pm_score": 5, "selected": true, "text": "<p>After much research, I finally turned to examining the WordPress core file wp_login.php hoping that WP would show how they do it in a non-obtuse manner. From the information around line 331 (WP 4.6.1), I put together the following code.</p>\n\n<pre><code>&lt;?php\n\nglobal $gw_activate_template;\n\nextract( $gw_activate_template-&gt;result );\n\n$url = is_multisite() ? get_blogaddress_by_id( (int) $blog_id ) : home_url('', 'http');\n$user = new WP_User( (int) $user_id );\n\n$adt_rp_key = get_password_reset_key( $user );\n$user_login = $user-&gt;user_login;\n$rp_link = '&lt;a href=\"' . network_site_url(\"wp-login.php?action=rp&amp;key=$adt_rp_key&amp;login=\" . rawurlencode($user_login), 'login') . '\"&gt;' . network_site_url(\"wp-login.php?action=rp&amp;key=$adt_rp_key&amp;login=\" . rawurlencode($user_login), 'login') . '&lt;/a&gt;';\n\nif ( is_wp_error( $key ) ) {\n return $key;\n}\n\n?&gt;\n\n&lt;h2&gt;&lt;?php _e('Your account is now active!'); ?&gt;&lt;/h2&gt;\n\n&lt;div id=\"signup-welcome\"&gt;\n &lt;p&gt;&lt;span class=\"h3\"&gt;&lt;?php _e('Username:'); ?&gt;&lt;/span&gt; &lt;?php echo $user-&gt;user_login ?&gt;&lt;/p&gt;\n &lt;p&gt;To set your password, select the following link: &lt;?php echo $rp_link; ?&gt;&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The important thing to constructing the link is the key that is put together by get_password_reset_key( $user ); This is a key that is stored in the database which allows the $user to have its password changed. I saw a website that refers to it as a cookie; however this is using a loose definition of \"cookie\" because nothing is stored on the users computer. The key is stored in the database and linked to the user account.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239095", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102710/" ]
I have the registration workflow set so that my user have to fill out a gravity forms user registration form and then activate their account via a link in an email. The email link sends them to a page that tells the user whether their registration has been successful or a failure. Up on success, I would like my users to click on a password reset link on the activation success page to set their password. I keep getting an invalid link message when I construct the reset link. How do I do construct a valid password reset link?? Here is what I have so far: ``` <?php global $gw_activate_template; extract( $gw_activate_template->result ); $url = is_multisite() ? get_blogaddress_by_id( (int) $blog_id ) : home_url('', 'http'); $user = new WP_User( (int) $user_id ); ?> <h2><?php _e('Your account is now active!'); ?></h2> <div id="signup-welcome"> <p><span class="h3"><?php _e('Username:'); ?></span> <?php echo $user->user_login ?></p> <p>To set your password, select the following link: <a href="http://example.com/wp-login.php?action=rp&key=<?php echo $gw_activate_template->get_activation_key(); ?>&login=<?php echo $user->user_login; ?>" >http://example.com/wp-login.php?action=rp&amp;key=<?php echo $gw_activate_template->get_activation_key(); ?>&amp;login=<?php echo $user->user_login; ?></a></p> </div> <?php if ( $url != network_home_url('', 'http') ) : ?> <p class="view"><?php printf( __('Your account is now activated. <a href="%1$s">View the site</a> or <a href="%2$s">Log in</a>'), $url, $url . 'wp-login.php' ); ?></p> <?php else: ?> <p class="view"><?php printf( __('Your account is now activated. <a href="%1$s">Log in</a> or go back to the <a href="%2$s">homepage</a>.' ), network_site_url('wp-login.php', 'login'), network_home_url() ); ?></p> <?php endif; ?> ```
After much research, I finally turned to examining the WordPress core file wp\_login.php hoping that WP would show how they do it in a non-obtuse manner. From the information around line 331 (WP 4.6.1), I put together the following code. ``` <?php global $gw_activate_template; extract( $gw_activate_template->result ); $url = is_multisite() ? get_blogaddress_by_id( (int) $blog_id ) : home_url('', 'http'); $user = new WP_User( (int) $user_id ); $adt_rp_key = get_password_reset_key( $user ); $user_login = $user->user_login; $rp_link = '<a href="' . network_site_url("wp-login.php?action=rp&key=$adt_rp_key&login=" . rawurlencode($user_login), 'login') . '">' . network_site_url("wp-login.php?action=rp&key=$adt_rp_key&login=" . rawurlencode($user_login), 'login') . '</a>'; if ( is_wp_error( $key ) ) { return $key; } ?> <h2><?php _e('Your account is now active!'); ?></h2> <div id="signup-welcome"> <p><span class="h3"><?php _e('Username:'); ?></span> <?php echo $user->user_login ?></p> <p>To set your password, select the following link: <?php echo $rp_link; ?></p> </div> ``` The important thing to constructing the link is the key that is put together by get\_password\_reset\_key( $user ); This is a key that is stored in the database which allows the $user to have its password changed. I saw a website that refers to it as a cookie; however this is using a loose definition of "cookie" because nothing is stored on the users computer. The key is stored in the database and linked to the user account.
239,127
<p>I'm working on a rather large and old Wordpress project where someone has previously used <code>query_posts</code> all over the place. For this reason, I'm unwilling to change those method calls. I'm not the maintainer of the site, I'm doing a quick fix.</p> <p>Each post in question has a field called <code>our_date</code>, which represents a date and a time, and <code>title</code>. The customer wants the posts ordered by <code>title</code>, but so that the <em>future</em> posts appear first in the list and all the past dates at the bottom.</p> <p>This is what I'm working with right now:</p> <pre><code>'orderby' =&gt; array('date' =&gt; 'ASC'), </code></pre> <p>What's the best way to accomplish this custom sorting of results from <code>query_posts</code>?</p>
[ { "answer_id": 239138, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Since both wordpress and laravel will most likely try to take control from each other. The best way to do such integration is by defining restful API to the laravel part, and use the <code>wp_get_remote</code> family of functions to retrieve information. </p>\n\n<p>In the long term it is probably a suboptimal solution for people that do not have a permanent developer on a payrole as it means that there are two different code bases to maintain which makes maintenance (and hiring the right freelancers) more complex.</p>\n" }, { "answer_id": 239149, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>There is no \"generic\" way to just smash WP with another app and have it work.</p>\n\n<p>It can be roughly split in two cases:</p>\n\n<ol>\n<li>Applications run separately on server, installed in different directories, and styled to look as one site (possibly talking to same database, possibly talking to each other via REST API or something).</li>\n<li>One of the applications runs whole site (URLs, routing, templates, styles, etc) and incorporates another in PHP runtime to perform specific functionality.</li>\n</ol>\n\n<p>It is hard to advise on specific case without thorough research into circumstances.</p>\n\n<p>In general WP <em>is</em> a PHP runtime and integrating other PHP solutions with it is perfectly possible.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102723/" ]
I'm working on a rather large and old Wordpress project where someone has previously used `query_posts` all over the place. For this reason, I'm unwilling to change those method calls. I'm not the maintainer of the site, I'm doing a quick fix. Each post in question has a field called `our_date`, which represents a date and a time, and `title`. The customer wants the posts ordered by `title`, but so that the *future* posts appear first in the list and all the past dates at the bottom. This is what I'm working with right now: ``` 'orderby' => array('date' => 'ASC'), ``` What's the best way to accomplish this custom sorting of results from `query_posts`?
There is no "generic" way to just smash WP with another app and have it work. It can be roughly split in two cases: 1. Applications run separately on server, installed in different directories, and styled to look as one site (possibly talking to same database, possibly talking to each other via REST API or something). 2. One of the applications runs whole site (URLs, routing, templates, styles, etc) and incorporates another in PHP runtime to perform specific functionality. It is hard to advise on specific case without thorough research into circumstances. In general WP *is* a PHP runtime and integrating other PHP solutions with it is perfectly possible.
239,141
<pre><code>echo do_shortcode('https://www.youtube.com/watch?v=vZBCTc9zHtI'); </code></pre> <p>Is merely printing </p> <pre><code>https://www.youtube.com/watch?v=vZBCTc9zHtI" </code></pre> <p>out onto the page.</p> <p>I know I can display the video with html with</p> <pre><code>&lt;iframe src="http://www.youtube.com/embed/vZBCTc9zHtI" width="560" height="315" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; </code></pre> <p>but I'm trying to leverage wordpress' built-in methods. How do I do this?</p>
[ { "answer_id": 239143, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>If you just want to embed a video in the content area, WordPress does this pretty elegantly with <a href=\"https://codex.wordpress.org/Embeds\" rel=\"nofollow\">oembeds</a>. You just need to paste the URL into the editor and save the post. As long as the embeds are supported, WordPress will work its magic and format your embed.</p>\n\n<p>Your call to <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow\"><code>do_shortcode()</code></a> doesn't make sense. As posted, your code is saying, \"look through this youtube URL string and run the shortcodes found within it\". </p>\n" }, { "answer_id": 239145, "author": "Rituparna sonowal", "author_id": 71232, "author_profile": "https://wordpress.stackexchange.com/users/71232", "pm_score": 4, "selected": true, "text": "<p>I think this is what you are looking for:</p>\n\n<pre><code>&lt;?php echo wp_oembed_get('https://www.youtube.com/watch?v=vZBCTc9zHtI'); ?&gt;\n</code></pre>\n\n<p>For more details check this <a href=\"https://codex.wordpress.org/Function_Reference/wp_oembed_get\" rel=\"noreferrer\">documentation</a>.</p>\n" }, { "answer_id": 239186, "author": "gsjha", "author_id": 52246, "author_profile": "https://wordpress.stackexchange.com/users/52246", "pm_score": 1, "selected": false, "text": "<pre><code>do_shortcode() \n</code></pre>\n\n<p>Is used to printout shortcode. And you are writting URL in it. No use of this.\nTry to implement</p>\n\n<pre><code>wp_oembed_get( $url, $args )\n</code></pre>\n\n<p>This will work for you.\nSo your code will</p>\n\n<pre><code>wp_oembed_get('https://www.youtube.com/watch?v=vZBCTc9zHtI')\n</code></pre>\n\n<p>or if you want to specify width then</p>\n\n<pre><code>wp_oembed_get('https://www.youtube.com/watch?v=vZBCTc9zHtI', array('width'=&gt;400))\n</code></pre>\n" }, { "answer_id": 239187, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>It is not working because using a youtube url in the content has nothing to do with shortcodes, which is why it doesn't work when you try to call <code>do_shortcode</code>, what it actually does is to envoke the oEmbed protocol which is a very different thing.</p>\n\n<p>There is an oEmbed shorcode and you probably can do <code>do_shortcode('[oEmbed youtube.com.....]')</code> but as other answers pointed out, there is an explicit API for that and using the shortcode is the long way to do that.</p>\n\n<p>The most important thing to keep in mind in what you are trying to do, is that oEmbed sends a request to youtube servers and waits to a reply, which means that without some caching this kind of code will slow down the page on every load.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239141", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13170/" ]
``` echo do_shortcode('https://www.youtube.com/watch?v=vZBCTc9zHtI'); ``` Is merely printing ``` https://www.youtube.com/watch?v=vZBCTc9zHtI" ``` out onto the page. I know I can display the video with html with ``` <iframe src="http://www.youtube.com/embed/vZBCTc9zHtI" width="560" height="315" frameborder="0" allowfullscreen></iframe> ``` but I'm trying to leverage wordpress' built-in methods. How do I do this?
I think this is what you are looking for: ``` <?php echo wp_oembed_get('https://www.youtube.com/watch?v=vZBCTc9zHtI'); ?> ``` For more details check this [documentation](https://codex.wordpress.org/Function_Reference/wp_oembed_get).
239,155
<p>Attention: It's <strong>order</strong>, not <strong>orderby</strong>.</p> <p>According to wordpress docs, there are only two options to <strong>order</strong>, which are ASC or DESC.</p> <h3>The problem is:</h3> <p>I would like to randomize <strong>the posts I've selected</strong>, not randomize <strong>WHICH posts I select</strong>.</p> <p>Here's my code for better explanation:</p> <pre><code>&lt;?php return array( &quot;post_type&quot; =&gt; &quot;listings&quot;, &quot;post_status&quot; =&gt; &quot;publish&quot;, 'meta_query'=&gt;array( array('key'=&gt;'featured_until','value'=&gt;$current_date, 'compare'=&gt;'&gt;'), ), 'meta_key'=&gt;'featured_until', &quot;orderby&quot; =&gt; array( 'featured_until' =&gt; 'RAND', /* How can I make this work? */ 'date' =&gt; 'DESC' ), &quot;suppress_filters&quot; =&gt; true, &quot;facetwp&quot; =&gt; true, &quot;posts_per_page&quot; =&gt; 16 ); </code></pre> <p>It's a listings website. The code above selects 16 posts to show on the first page.</p> <p>First, it tries to find 16 featured listings. If there aren't that many featured listings, it completes with regular listings ordered by date.</p> <p>The question is: How can I order the featured listings by RANDOM, instead of ASC or DESC?</p>
[ { "answer_id": 239158, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>You are right that you can't have WordPress order the retrieved posts randomly. So you'll have to do that yourself after you have retrieved the array of post objects. Let's call that <code>$my_posts</code>.</p>\n\n<p>Because you don't know how many of the posts in that array are featured, you will have to loop through them to split the array. I don't know how exactly you have defined 'featured', but it would look something like this:</p>\n\n<pre><code>$featured_posts = array ();\n$nonfeatured_posts = array ();\nforeach ($my_posts as $my_post) {\n if (test if featured)\n $featured_posts[] = $my_post\n else\n $nonfeatured_posts[] = $my_post;\n// now, let's randomize\nshuffle ($featured_posts);\n// join the array again\n$my_posts = array_merge ($featured_posts,$nonfeatured_posts);\n// now you have your array with featured posts randomized\n</code></pre>\n\n<p>Beware, I couldn't test this code, but I trust you get the point.</p>\n" }, { "answer_id": 239159, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 1, "selected": false, "text": "<p>Shuffling a query's results is really as simple as <a href=\"http://php.net/manual/en/function.shuffle.php\" rel=\"nofollow\"><code>shuffle()</code></a>ing a query's results.</p>\n\n<pre><code>$query = new WP_Query( //arguments );\nshuffle( $query-&gt;posts );\n</code></pre>\n" }, { "answer_id": 309510, "author": "Vantron", "author_id": 147535, "author_profile": "https://wordpress.stackexchange.com/users/147535", "pm_score": -1, "selected": false, "text": "<p>You can use too:</p>\n\n<pre><code>'orderby' =&gt;'rand',\n</code></pre>\n\n<p>this way works for me.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239155", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27278/" ]
Attention: It's **order**, not **orderby**. According to wordpress docs, there are only two options to **order**, which are ASC or DESC. ### The problem is: I would like to randomize **the posts I've selected**, not randomize **WHICH posts I select**. Here's my code for better explanation: ``` <?php return array( "post_type" => "listings", "post_status" => "publish", 'meta_query'=>array( array('key'=>'featured_until','value'=>$current_date, 'compare'=>'>'), ), 'meta_key'=>'featured_until', "orderby" => array( 'featured_until' => 'RAND', /* How can I make this work? */ 'date' => 'DESC' ), "suppress_filters" => true, "facetwp" => true, "posts_per_page" => 16 ); ``` It's a listings website. The code above selects 16 posts to show on the first page. First, it tries to find 16 featured listings. If there aren't that many featured listings, it completes with regular listings ordered by date. The question is: How can I order the featured listings by RANDOM, instead of ASC or DESC?
You are right that you can't have WordPress order the retrieved posts randomly. So you'll have to do that yourself after you have retrieved the array of post objects. Let's call that `$my_posts`. Because you don't know how many of the posts in that array are featured, you will have to loop through them to split the array. I don't know how exactly you have defined 'featured', but it would look something like this: ``` $featured_posts = array (); $nonfeatured_posts = array (); foreach ($my_posts as $my_post) { if (test if featured) $featured_posts[] = $my_post else $nonfeatured_posts[] = $my_post; // now, let's randomize shuffle ($featured_posts); // join the array again $my_posts = array_merge ($featured_posts,$nonfeatured_posts); // now you have your array with featured posts randomized ``` Beware, I couldn't test this code, but I trust you get the point.
239,170
<p>I'm making the following query in order to get all the posts sorted by a meta key (wpcf-estado in this case) but it returns the items in no order:</p> <pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; 'proyectos', 'posts_per_page' =&gt; 8, 'paged' =&gt; $paged, 'orderby' =&gt; 'meta_value', 'order' =&gt; 'DESC', 'meta_key' =&gt; 'wpcf-estado', //'meta_value' =&gt; 'a', ); </code></pre> <p>If I uncomment the 'meta_value' parameter, I end up succesfully getting only the posts containing 'a' as wpcf-estado. </p> <p>The possible values of wpcf-estado are: a, b or c.</p> <p>I tried several things but didn't find a proper solution.</p>
[ { "answer_id": 239158, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>You are right that you can't have WordPress order the retrieved posts randomly. So you'll have to do that yourself after you have retrieved the array of post objects. Let's call that <code>$my_posts</code>.</p>\n\n<p>Because you don't know how many of the posts in that array are featured, you will have to loop through them to split the array. I don't know how exactly you have defined 'featured', but it would look something like this:</p>\n\n<pre><code>$featured_posts = array ();\n$nonfeatured_posts = array ();\nforeach ($my_posts as $my_post) {\n if (test if featured)\n $featured_posts[] = $my_post\n else\n $nonfeatured_posts[] = $my_post;\n// now, let's randomize\nshuffle ($featured_posts);\n// join the array again\n$my_posts = array_merge ($featured_posts,$nonfeatured_posts);\n// now you have your array with featured posts randomized\n</code></pre>\n\n<p>Beware, I couldn't test this code, but I trust you get the point.</p>\n" }, { "answer_id": 239159, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 1, "selected": false, "text": "<p>Shuffling a query's results is really as simple as <a href=\"http://php.net/manual/en/function.shuffle.php\" rel=\"nofollow\"><code>shuffle()</code></a>ing a query's results.</p>\n\n<pre><code>$query = new WP_Query( //arguments );\nshuffle( $query-&gt;posts );\n</code></pre>\n" }, { "answer_id": 309510, "author": "Vantron", "author_id": 147535, "author_profile": "https://wordpress.stackexchange.com/users/147535", "pm_score": -1, "selected": false, "text": "<p>You can use too:</p>\n\n<pre><code>'orderby' =&gt;'rand',\n</code></pre>\n\n<p>this way works for me.</p>\n" } ]
2016/09/13
[ "https://wordpress.stackexchange.com/questions/239170", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90416/" ]
I'm making the following query in order to get all the posts sorted by a meta key (wpcf-estado in this case) but it returns the items in no order: ``` $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'proyectos', 'posts_per_page' => 8, 'paged' => $paged, 'orderby' => 'meta_value', 'order' => 'DESC', 'meta_key' => 'wpcf-estado', //'meta_value' => 'a', ); ``` If I uncomment the 'meta\_value' parameter, I end up succesfully getting only the posts containing 'a' as wpcf-estado. The possible values of wpcf-estado are: a, b or c. I tried several things but didn't find a proper solution.
You are right that you can't have WordPress order the retrieved posts randomly. So you'll have to do that yourself after you have retrieved the array of post objects. Let's call that `$my_posts`. Because you don't know how many of the posts in that array are featured, you will have to loop through them to split the array. I don't know how exactly you have defined 'featured', but it would look something like this: ``` $featured_posts = array (); $nonfeatured_posts = array (); foreach ($my_posts as $my_post) { if (test if featured) $featured_posts[] = $my_post else $nonfeatured_posts[] = $my_post; // now, let's randomize shuffle ($featured_posts); // join the array again $my_posts = array_merge ($featured_posts,$nonfeatured_posts); // now you have your array with featured posts randomized ``` Beware, I couldn't test this code, but I trust you get the point.
239,228
<p>I have a real estate theme with custom post: properties. Post has many meta values such as price and taxonomy such as location. I created search engine for this but queries take ridiculous amount of time to execute.</p> <p>I have only 50 properties in the database, but wp_postmeta table has 20044 rows.</p> <p>Sample query, that take over 30s:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6) AND tt1.term_taxonomy_id IN (19,287) ) AND ( wp_postmeta.meta_key = 'featured' AND ( ( mt1.meta_key = 'area' AND CAST(mt1.meta_value AS SIGNED) &lt;= '100000' ) AND ( mt2.meta_key = 'price' AND CAST(mt2.meta_value AS SIGNED) &lt;= '4433356' ) AND ( mt3.meta_key = 'offer_order_status' AND mt3.meta_value = 'active' ) ) ) AND wp_posts.post_type = 'property' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 12 </code></pre> <p>And here is the $args table passed to the WP_Query:</p> <pre><code>array (size=7) 'post_type' =&gt; string 'property' (length=18) 'paged' =&gt; int 1 'meta_key' =&gt; string 'featured' (length=21) 'orderby' =&gt; string 'meta_value_num' (length=14) 'order' =&gt; string 'DESC' (length=4) 'tax_query' =&gt; array (size=3) 0 =&gt; array (size=3) 'taxonomy' =&gt; string 'property_type' (length=13) 'field' =&gt; string 'id' (length=2) 'terms' =&gt; string '6' (length=1) 1 =&gt; array (size=3) 'taxonomy' =&gt; string 'transaction_type' (length=16) 'field' =&gt; string 'id' (length=2) 'terms' =&gt; array (size=2) 0 =&gt; string '19' (length=2) 1 =&gt; string '287' (length=3) 'relation' =&gt; string 'AND' (length=3) 'meta_query' =&gt; array (size=4) 0 =&gt; array (size=4) 'key' =&gt; string 'area' (length=17) 'value' =&gt; int 100000 'type' =&gt; string 'NUMERIC' (length=7) 'compare' =&gt; string '&lt;=' (length=2) 1 =&gt; array (size=4) 'key' =&gt; string 'price' (length=18) 'value' =&gt; int 4433356 'type' =&gt; string 'NUMERIC' (length=7) 'compare' =&gt; string '&lt;=' (length=2) 'relation' =&gt; string 'AND' (length=3) 2 =&gt; array (size=3) 'key' =&gt; string 'offer_order_status' (length=31) 'value' =&gt; string 'active' (length=6) 'compare' =&gt; string '=' (length=1) </code></pre> <p>Here is <code>EXPLAIN</code> result:</p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE wp_term_relationships ref PRIMARY,term_taxonomy_id term_taxonomy_id 8 const 19 Using where; Using index; Using temporary; Using filesort 1 SIMPLE wp_posts eq_ref PRIMARY,post_name,type_status_date,post_parent,post_author PRIMARY 8 wp_real_estate3.wp_term_relationships.object_id 1 Using where 1 SIMPLE tt1 ref PRIMARY,term_taxonomy_id PRIMARY 8 wp_real_estate3.wp_term_relationships.object_id 2 Using where; Using index 1 SIMPLE mt3 ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where 1 SIMPLE mt1 ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where 1 SIMPLE mt2 ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where 1 SIMPLE wp_postmeta ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where </code></pre> <p>I've read many related questions but can't find any answer that describes hot to change the query to seed it up.</p> <p>Thanks</p> <p><strong>EDIT:</strong></p> <p>I've created custom SQL that seems to return the same values with the speed of 0.01s:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6) AND tt1.term_taxonomy_id IN (19,287) ) AND ( wp_postmeta.meta_key = 'apartment_wp_featured' ) AND wp_posts.post_type = 'apartment_property' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND wp_posts.ID IN ( SELECT post_id from wp_postmeta WHERE ((meta_key = 'apartment_wp_area' AND CAST(meta_value AS SIGNED) &lt; '100000') or (meta_key = 'apartment_wp_price' AND CAST(meta_value AS SIGNED) &lt; '4433356') or (meta_key = 'apartment_wp_offer_order_status' AND meta_value = 'active')) ) GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 12 </code></pre> <p>Now I'll try to add all meta_query (which cause performance issues) as a custom SQL with <code>add_filter( 'posts_where' , 'posts_where_statement' );</code></p>
[ { "answer_id": 239241, "author": "Xavi Ivars", "author_id": 6334, "author_profile": "https://wordpress.stackexchange.com/users/6334", "pm_score": 1, "selected": false, "text": "<p>That's a known problem with WordPress and searches involving postmeta.</p>\n\n<p>What I'd try to do is to create a new taxonomy for \"things\" you're usually searching the most: </p>\n\n<ul>\n<li><code>offer_order_status</code> seems the better candidate, as it can be active or not. I'd create a taxonomy with two elements. That would reduce the time of your search considerably</li>\n<li>If that is not enough, the next step I'd probably try is to define \"buckets\" for the other two \"meta\" you're using and create taxonomies for them: area and price. Buckets can be created in to different ways: you could have a \"size\" taxonomy that was <code>&gt; 100000</code>, another one <code>&gt; 200000</code>, etc, and then for prices, you may want to do <code>&lt; 100000</code>, <code>&gt; 100000 &amp;&amp; &lt; 200000</code>. That really depends on how you plan to search.</li>\n</ul>\n\n<p>The whole point for step two is that you can hook into the save action of the post to \"read\" what is the area/size for that property, and then pick the right taxonomies for it and add them automatically in the backend. By doing that, you get the benefit of:\na) having the taxonomies always in sync with the actual meta value (you don't want to have people adding \"the same\" or similar information more than once).\nb) you can change the \"buckets\" of the taxonomies at any time to fullfill your \"new\" needs: as you have the real value for those fields, you'll just need to \"save\" again all posts to get the right taxonomies (and you can do that programatically).\nc) taxonomy-based search is muuuuuuuch faster than meta search (is an indexed&amp;relatively small table, compared to postmeta)</p>\n\n<hr>\n\n<p>A second approach, that won't work that well for this case, but is still an option, is to add indexes to the postmeta table, indexing by post_id, meta_key and meta_value. That will also speed up the query, by using indexes, but probably not that much.</p>\n\n<p>But as it's much easier to implement than the previous one, I'd probably try to implement this second option first and see how it goes.</p>\n" }, { "answer_id": 239248, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Assuming the amount of changes is not big per day you can create a \"shadow DB\" in a format nicer to query, for example each attribute has its own column, and update it on every post save.</p>\n\n<p>The advantage for this approach is that you do not have to change anything in your post/meta/terms usage, no change in admin, and none in front end.The disadvantage is that you do need to write the code to adjust the data on every post and tem save which will create some more work for you in writting the code, and to the DB server on each update.</p>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239228", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102783/" ]
I have a real estate theme with custom post: properties. Post has many meta values such as price and taxonomy such as location. I created search engine for this but queries take ridiculous amount of time to execute. I have only 50 properties in the database, but wp\_postmeta table has 20044 rows. Sample query, that take over 30s: ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6) AND tt1.term_taxonomy_id IN (19,287) ) AND ( wp_postmeta.meta_key = 'featured' AND ( ( mt1.meta_key = 'area' AND CAST(mt1.meta_value AS SIGNED) <= '100000' ) AND ( mt2.meta_key = 'price' AND CAST(mt2.meta_value AS SIGNED) <= '4433356' ) AND ( mt3.meta_key = 'offer_order_status' AND mt3.meta_value = 'active' ) ) ) AND wp_posts.post_type = 'property' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 12 ``` And here is the $args table passed to the WP\_Query: ``` array (size=7) 'post_type' => string 'property' (length=18) 'paged' => int 1 'meta_key' => string 'featured' (length=21) 'orderby' => string 'meta_value_num' (length=14) 'order' => string 'DESC' (length=4) 'tax_query' => array (size=3) 0 => array (size=3) 'taxonomy' => string 'property_type' (length=13) 'field' => string 'id' (length=2) 'terms' => string '6' (length=1) 1 => array (size=3) 'taxonomy' => string 'transaction_type' (length=16) 'field' => string 'id' (length=2) 'terms' => array (size=2) 0 => string '19' (length=2) 1 => string '287' (length=3) 'relation' => string 'AND' (length=3) 'meta_query' => array (size=4) 0 => array (size=4) 'key' => string 'area' (length=17) 'value' => int 100000 'type' => string 'NUMERIC' (length=7) 'compare' => string '<=' (length=2) 1 => array (size=4) 'key' => string 'price' (length=18) 'value' => int 4433356 'type' => string 'NUMERIC' (length=7) 'compare' => string '<=' (length=2) 'relation' => string 'AND' (length=3) 2 => array (size=3) 'key' => string 'offer_order_status' (length=31) 'value' => string 'active' (length=6) 'compare' => string '=' (length=1) ``` Here is `EXPLAIN` result: ``` id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE wp_term_relationships ref PRIMARY,term_taxonomy_id term_taxonomy_id 8 const 19 Using where; Using index; Using temporary; Using filesort 1 SIMPLE wp_posts eq_ref PRIMARY,post_name,type_status_date,post_parent,post_author PRIMARY 8 wp_real_estate3.wp_term_relationships.object_id 1 Using where 1 SIMPLE tt1 ref PRIMARY,term_taxonomy_id PRIMARY 8 wp_real_estate3.wp_term_relationships.object_id 2 Using where; Using index 1 SIMPLE mt3 ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where 1 SIMPLE mt1 ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where 1 SIMPLE mt2 ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where 1 SIMPLE wp_postmeta ref post_id,meta_key post_id 8 wp_real_estate3.wp_term_relationships.object_id 12 Using where ``` I've read many related questions but can't find any answer that describes hot to change the query to seed it up. Thanks **EDIT:** I've created custom SQL that seems to return the same values with the speed of 0.01s: ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6) AND tt1.term_taxonomy_id IN (19,287) ) AND ( wp_postmeta.meta_key = 'apartment_wp_featured' ) AND wp_posts.post_type = 'apartment_property' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND wp_posts.ID IN ( SELECT post_id from wp_postmeta WHERE ((meta_key = 'apartment_wp_area' AND CAST(meta_value AS SIGNED) < '100000') or (meta_key = 'apartment_wp_price' AND CAST(meta_value AS SIGNED) < '4433356') or (meta_key = 'apartment_wp_offer_order_status' AND meta_value = 'active')) ) GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 12 ``` Now I'll try to add all meta\_query (which cause performance issues) as a custom SQL with `add_filter( 'posts_where' , 'posts_where_statement' );`
That's a known problem with WordPress and searches involving postmeta. What I'd try to do is to create a new taxonomy for "things" you're usually searching the most: * `offer_order_status` seems the better candidate, as it can be active or not. I'd create a taxonomy with two elements. That would reduce the time of your search considerably * If that is not enough, the next step I'd probably try is to define "buckets" for the other two "meta" you're using and create taxonomies for them: area and price. Buckets can be created in to different ways: you could have a "size" taxonomy that was `> 100000`, another one `> 200000`, etc, and then for prices, you may want to do `< 100000`, `> 100000 && < 200000`. That really depends on how you plan to search. The whole point for step two is that you can hook into the save action of the post to "read" what is the area/size for that property, and then pick the right taxonomies for it and add them automatically in the backend. By doing that, you get the benefit of: a) having the taxonomies always in sync with the actual meta value (you don't want to have people adding "the same" or similar information more than once). b) you can change the "buckets" of the taxonomies at any time to fullfill your "new" needs: as you have the real value for those fields, you'll just need to "save" again all posts to get the right taxonomies (and you can do that programatically). c) taxonomy-based search is muuuuuuuch faster than meta search (is an indexed&relatively small table, compared to postmeta) --- A second approach, that won't work that well for this case, but is still an option, is to add indexes to the postmeta table, indexing by post\_id, meta\_key and meta\_value. That will also speed up the query, by using indexes, but probably not that much. But as it's much easier to implement than the previous one, I'd probably try to implement this second option first and see how it goes.
239,243
<p>I've created a custom taxonomy, for a custom post type, and created a custom page for it, the usual, etc.</p> <p>Problem is I want to only show the custom posts that are part of the category, and not show the posts from the sub categories. So I wrote the following query for the loop:</p> <pre><code>&lt;?php global $wp_query; $args = array_merge( $wp_query-&gt;query_vars, array( 'post_type' =&gt; 'product', 'include_children' =&gt; 'false' ) ); query_posts( $args ); if(have_posts()) : while(have_posts()) : the_post(); ?&gt; </code></pre> <p>Although <code>'include_children' =&gt; 'false'</code> is included in the <code>$args</code> it still shows the products from the subcategories. I tried changing it for <code>'post_parent' =&gt; 0</code>, and using them both at the same time, but to no avail.</p> <p>Here is the code for my taxonomy:</p> <pre><code>function productcat_taxonomy() { $labels = array( 'name' =&gt; _x( 'Product Categories', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Product Category', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Product Categories' ), 'all_items' =&gt; __( 'All Product Categories' ), 'parent_item' =&gt; __( 'Parent Product Category' ), 'parent_item_colon' =&gt; __( 'Parent Product Category:' ), 'edit_item' =&gt; __( 'Edit Product Category' ), 'update_item' =&gt; __( 'Update Product Category' ), 'add_new_item' =&gt; __( 'Add New Product Category' ), 'new_item_name' =&gt; __( 'New Product Category Name' ), 'menu_name' =&gt; __( 'Product Categories' ), ); register_taxonomy('product-category',array('product'), array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'product-category' ), )); } add_action( 'init', 'productcat_taxonomy', 0 ); </code></pre> <p>Where have I gone wrong?</p>
[ { "answer_id": 239470, "author": "hkchakladar", "author_id": 65568, "author_profile": "https://wordpress.stackexchange.com/users/65568", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<ol>\n<li>As @gdaniel said, you are giving a string in place of boolean value.\nReplace <code>'include_children' =&gt; 'false'</code> to <code>'include_children' =&gt; false</code>\n(Remove quote from <code>false</code>)</li>\n<li>You can hook into the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> to change the query vars before getting the posts. And when on custom taxonomy template page, include your custom query to the global query. This goes to themes <code>functions.php</code></li>\n</ol>\n\n<hr>\n\n<pre><code>function wpse239243_exclude_child( $query ) {\n\n //if on frontend custom taxonomy template\n if( $query-&gt;is_tax( 'product-category' ) &amp;&amp; $query-&gt;is_main_query() &amp;&amp; !is_admin() ) {\n\n $tax_query = array( array(\n 'taxonomy' =&gt; 'product-category',\n 'terms' =&gt; $query-&gt;get( 'product-category' ),\n 'include_children' =&gt; false\n ) );\n $query-&gt;set( 'tax_query', $tax_query );\n }\n}\nadd_action( 'pre_get_posts', 'wpse239243_exclude_child' );\n</code></pre>\n" }, { "answer_id": 239512, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>You have used <code>'include_children' =&gt; 'false'</code>, but you haven't told WordPress <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">which taxonomy this is about</a> and also not what the base category is you don't want the children of. You would do that as follows:</p>\n\n<pre><code>array(\n 'post_type' =&gt; 'product',\n 'tax_query' =&gt; array( array(\n 'taxonomy' =&gt; 'product-category',\n 'include_children' =&gt; 'false' \n 'terms' =&gt; 'base-category-ID',\n ) ),\n);\n</code></pre>\n\n<p>Instead of a fixed <code>base-category-ID</code>, you can off course use a variable containing the name of the first category on the current post:</p>\n\n<pre><code>$categories = get_the_category();\n$category_id = $categories[0]-&gt;cat_ID;\n</code></pre>\n" }, { "answer_id": 280730, "author": "Jesse Sutherland", "author_id": 128334, "author_profile": "https://wordpress.stackexchange.com/users/128334", "pm_score": 1, "selected": false, "text": "<p>There was a lot of hard coding going on in a number of these answers that I felt like may have disadvantages further down the road. Here is an approach that takes the existing tax_query, and swaps out the \"include_children\" argument. </p>\n\n<p>As an aside, I did not have any luck setting \"include_children\" to false in this instance. I only found a zero to work.</p>\n\n<pre><code>function wpse239243_exclude_child_taxonomies( $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n if (is_tax('product-category')) {\n $tax_query = $query-&gt;tax_query-&gt;queries;\n $tax_query[0]['include_children'] = 0;\n $query-&gt;set( 'tax_query', $tax_query );\n }\n }\n return;\n}\nadd_action( 'pre_get_posts', 'wpse239243_exclude_child_taxonomies', 1 );\n</code></pre>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239243", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56659/" ]
I've created a custom taxonomy, for a custom post type, and created a custom page for it, the usual, etc. Problem is I want to only show the custom posts that are part of the category, and not show the posts from the sub categories. So I wrote the following query for the loop: ``` <?php global $wp_query; $args = array_merge( $wp_query->query_vars, array( 'post_type' => 'product', 'include_children' => 'false' ) ); query_posts( $args ); if(have_posts()) : while(have_posts()) : the_post(); ?> ``` Although `'include_children' => 'false'` is included in the `$args` it still shows the products from the subcategories. I tried changing it for `'post_parent' => 0`, and using them both at the same time, but to no avail. Here is the code for my taxonomy: ``` function productcat_taxonomy() { $labels = array( 'name' => _x( 'Product Categories', 'taxonomy general name' ), 'singular_name' => _x( 'Product Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Product Categories' ), 'all_items' => __( 'All Product Categories' ), 'parent_item' => __( 'Parent Product Category' ), 'parent_item_colon' => __( 'Parent Product Category:' ), 'edit_item' => __( 'Edit Product Category' ), 'update_item' => __( 'Update Product Category' ), 'add_new_item' => __( 'Add New Product Category' ), 'new_item_name' => __( 'New Product Category Name' ), 'menu_name' => __( 'Product Categories' ), ); register_taxonomy('product-category',array('product'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'product-category' ), )); } add_action( 'init', 'productcat_taxonomy', 0 ); ``` Where have I gone wrong?
Try this: 1. As @gdaniel said, you are giving a string in place of boolean value. Replace `'include_children' => 'false'` to `'include_children' => false` (Remove quote from `false`) 2. You can hook into the [`pre_get_posts`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) to change the query vars before getting the posts. And when on custom taxonomy template page, include your custom query to the global query. This goes to themes `functions.php` --- ``` function wpse239243_exclude_child( $query ) { //if on frontend custom taxonomy template if( $query->is_tax( 'product-category' ) && $query->is_main_query() && !is_admin() ) { $tax_query = array( array( 'taxonomy' => 'product-category', 'terms' => $query->get( 'product-category' ), 'include_children' => false ) ); $query->set( 'tax_query', $tax_query ); } } add_action( 'pre_get_posts', 'wpse239243_exclude_child' ); ```
239,252
<p>I'm trying to add a custom field to a post title (<a href="https://www.horizonhomes-samui.com/properties/hs0525-chaweng-noi-4-bedroom-coastal-front-villa/" rel="nofollow noreferrer">sample page</a>). To do so, I'm following the instructions given in <a href="https://wordpress.stackexchange.com/questions/224340/how-to-use-custom-fields-in-post-title">this previous question</a>, but the variable is not appearing in the title as expected. In fact, the exact same title appears. Any help would be appreciated. </p> <p>The previous instructions indicate that the following code should be added to functions.php:</p> <pre><code>function wpse_224340_document_title($title){ global $post; // make sure the post object is available to us if(is_singular()){ // check we're on a single post $release_author = get_post_meta(get_the_ID(), "release_author", true); if($release_author != "") { $title["title"].= " (" . $release_author. ")";} } return $title; } add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); }); </code></pre> <p>The variable in my case is <em>propertysq</em>, not <em>release_author</em>. But a simple find/replace resulted in the following...</p> <p><strong>What occurs when I implement this code?</strong></p> <p>The current page title is: <code>HS0525 - Chaweng Noi - Horizon Homes Koh Samui</code> This title has been inserted automatically by a Wordpress plugin "Yoast SEO." But after I disable this automatic title insertion, and insert the above code, the title inserted onto the page is identical to the previous page title: <code>HS0525 - Chaweng Noi - Horizon Homes Koh Samui</code></p> <p><strong>Possible Sources of Error</strong></p> <p><em>Possible Source of Error #1</em>: The aforementioned plugin/mechanism that is forcing its own <code>&lt;title&gt;</code> onto the page. I am currently researching if this is the cause. I'd like to avoid completely removing the plugin, but I may have to.</p> <p><em>Possible Source of Error #2</em>: Would I need to edit the following line to correspond to my theme/functions?</p> <pre><code>$release_author = get_post_meta(get_the_ID(), "release_author", true); </code></pre> <p>I tried replacing it with the following line, but it did not work.</p> <pre><code>$propertysq = ale_get_meta('propertysq'); </code></pre> <hr> <p>I should note:</p> <ul> <li>This site does not have a proper test environment setup where I can easily see PHP errors and dump vars.</li> <li>Per the previous answer, I also remembered to comment out the <code>&lt;title&gt;</code> tag in my header.php. <hr></li> </ul> <p>edit: Here is the exact code I've inserted into functions.php:</p> <pre><code>add_filter("document_title_parts", "wpse_224340_document_title"); function wpse_224340_document_title($title){ global $post; // make sure the post object is available to us if(is_singular()){ // check we're on a single post $propertysq = get_post_meta(get_the_ID(), "propertysq", true); if($propertysq != "") { $title["title"].= " (" . $propertysq. ")";} } return $title; } add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); }); </code></pre>
[ { "answer_id": 239259, "author": "hkchakladar", "author_id": 65568, "author_profile": "https://wordpress.stackexchange.com/users/65568", "pm_score": 2, "selected": false, "text": "<p>I assume that you want to use <code>propertysq</code> custom field/post meta in the title and you use Yoast SEO. ( Correct me if I'm wrong )</p>\n\n<p>So, use this is your <code>functions.php</code></p>\n\n<pre><code>function wpse239252_hook_title($title) {\nglobal $post; // make sure the post object is available to us\nif(is_singular()){ // check we're on a single post\n $propertysq = get_post_meta(get_the_ID(), \"propertysq\", true);\n if($propertysq != \"\") { //check if not empty\n $title = $propertysq.' - '.$title;\n }\n}\nreturn $title;\n}\n\nadd_filter('wpseo_title', 'wpse239252_hook_title', 15, 1);\n</code></pre>\n\n<p>This will add <code>propertysq</code> field to your title as <code>1,002Sq Mt - HS0525 - Chaweng Noi - Horizon Homes Koh Samui</code> in your given example, where <code>propertysq = 1,002Sq Mt</code>.</p>\n\n<p>P.S: To get post_meta propertysq, use <code>$propertysq = get_post_meta(get_the_ID(), \"propertysq\", true);</code></p>\n\n<p>Let me if it works for you.</p>\n" }, { "answer_id": 239367, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>Because so many people want to manipulate it, it is no longer fashionable to include <code>&lt;title&gt;</code> tags in your header. In stead you put <code>wp_head</code> there and allow manipulation of the title by supporting it in your theme:</p>\n\n<pre><code>add_action('after_setup_theme','wpse239252_theme_init');\n function wpse239252_theme_init () { \n add_theme_support('title-tag');\n }\n</code></pre>\n\n<p>Now, all kinds of (SEO) plugins may want to work with that, using the <a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow\"><code>wp_title</code></a> filter. If you do something using this filter and a plugin kicks in later, everything you have done may be lost. Now, I don't know which plugins you have installed, but you can make sure your filter is last by giving it a high priority, like this:</p>\n\n<pre><code>add_filter( 'wp_title', 'wpse239252_title_filter', 9999, 2 );\n function wpse239252_title_filter ($title,$separator) {\n ... do stuff with $title ...\n return $title;\n }\n</code></pre>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239252", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I'm trying to add a custom field to a post title ([sample page](https://www.horizonhomes-samui.com/properties/hs0525-chaweng-noi-4-bedroom-coastal-front-villa/)). To do so, I'm following the instructions given in [this previous question](https://wordpress.stackexchange.com/questions/224340/how-to-use-custom-fields-in-post-title), but the variable is not appearing in the title as expected. In fact, the exact same title appears. Any help would be appreciated. The previous instructions indicate that the following code should be added to functions.php: ``` function wpse_224340_document_title($title){ global $post; // make sure the post object is available to us if(is_singular()){ // check we're on a single post $release_author = get_post_meta(get_the_ID(), "release_author", true); if($release_author != "") { $title["title"].= " (" . $release_author. ")";} } return $title; } add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); }); ``` The variable in my case is *propertysq*, not *release\_author*. But a simple find/replace resulted in the following... **What occurs when I implement this code?** The current page title is: `HS0525 - Chaweng Noi - Horizon Homes Koh Samui` This title has been inserted automatically by a Wordpress plugin "Yoast SEO." But after I disable this automatic title insertion, and insert the above code, the title inserted onto the page is identical to the previous page title: `HS0525 - Chaweng Noi - Horizon Homes Koh Samui` **Possible Sources of Error** *Possible Source of Error #1*: The aforementioned plugin/mechanism that is forcing its own `<title>` onto the page. I am currently researching if this is the cause. I'd like to avoid completely removing the plugin, but I may have to. *Possible Source of Error #2*: Would I need to edit the following line to correspond to my theme/functions? ``` $release_author = get_post_meta(get_the_ID(), "release_author", true); ``` I tried replacing it with the following line, but it did not work. ``` $propertysq = ale_get_meta('propertysq'); ``` --- I should note: * This site does not have a proper test environment setup where I can easily see PHP errors and dump vars. * Per the previous answer, I also remembered to comment out the `<title>` tag in my header.php. --- edit: Here is the exact code I've inserted into functions.php: ``` add_filter("document_title_parts", "wpse_224340_document_title"); function wpse_224340_document_title($title){ global $post; // make sure the post object is available to us if(is_singular()){ // check we're on a single post $propertysq = get_post_meta(get_the_ID(), "propertysq", true); if($propertysq != "") { $title["title"].= " (" . $propertysq. ")";} } return $title; } add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); }); ```
I assume that you want to use `propertysq` custom field/post meta in the title and you use Yoast SEO. ( Correct me if I'm wrong ) So, use this is your `functions.php` ``` function wpse239252_hook_title($title) { global $post; // make sure the post object is available to us if(is_singular()){ // check we're on a single post $propertysq = get_post_meta(get_the_ID(), "propertysq", true); if($propertysq != "") { //check if not empty $title = $propertysq.' - '.$title; } } return $title; } add_filter('wpseo_title', 'wpse239252_hook_title', 15, 1); ``` This will add `propertysq` field to your title as `1,002Sq Mt - HS0525 - Chaweng Noi - Horizon Homes Koh Samui` in your given example, where `propertysq = 1,002Sq Mt`. P.S: To get post\_meta propertysq, use `$propertysq = get_post_meta(get_the_ID(), "propertysq", true);` Let me if it works for you.
239,255
<p>My wp-options keeps crashing and am getting "error establishing a database connecting" when I try loading the page. I don't know whats causing this to happen, I read somewhere that I might need more ram so i upgraded my plan to get 2GB of ram 40GB of space. But today it crashed again, I repaired it and went to the error logs and this the same error i get when the wp-option crashes </p> <pre><code>[14-Sep-2016 11:07:38 UTC] WordPress database error Table './DATABASE_Name/wp_options' is marked as crashed and should be repaired for query INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('_transient_mom_share_plusone_2020', '0', 'no') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`) made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/WDXYZ/single.php'), mom_single_post_content, mom_posts_share, set_transient, add_option </code></pre> <p>Please help me fix this issue. </p>
[ { "answer_id": 239260, "author": "user6736476", "author_id": 102798, "author_profile": "https://wordpress.stackexchange.com/users/102798", "pm_score": 0, "selected": false, "text": "<p>I have find out that you can run cron job to automatically repair and optimize the database for you. By simply running this 2 cron jobs. You will have to create a .db_shadow file in your cpanel public_html and have the permission set to 0400 and past your root password.</p>\n\n<pre><code>mysqlcheck -Aos -u root -p\"$(&lt; .db_shadow)\" &gt; /dev/null 2&gt;&amp;1\n\n/usr/bin/mysqlcheck -Aao --auto-repair -u root -p\"$(&lt; .db_shadow)\"\n</code></pre>\n" }, { "answer_id": 239275, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>It sounds like you may be running a plugin that stores too many transient options. If you can't currently access wp-admin, try FTP'ing in and renaming your /plugins folder to disable all plugins. Then you should be able to log in to wp-admin. Next, back in FTP rename your /plugins folder back to the normal /plugins, and leave all of the plugins deactivated in wp-admin.</p>\n\n<p>From there, go into phpMyAdmin and view the options table. Go to the last few pages and see if you notice any patterns - you may be able to tell which plugin is storing too much in the database, and then the solution is to remove the plugin and replace it with an alternative if you really need the functionality. Once you've found the culprit, run WP-Optimize ( <a href=\"https://wordpress.org/plugins/wp-optimize/\" rel=\"nofollow\">https://wordpress.org/plugins/wp-optimize/</a> ) to clean up your database and reduce its size. It's a great plugin to run on a regular basis to keep things running smoothly.</p>\n" }, { "answer_id": 239297, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 1, "selected": false, "text": "<p>Are you running Jetpack? If so, try updating it. See this:</p>\n\n<p><a href=\"https://wordpress.org/support/topic/jetpack-sync-killing-the-db/\" rel=\"nofollow\">https://wordpress.org/support/topic/jetpack-sync-killing-the-db/</a></p>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239255", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102798/" ]
My wp-options keeps crashing and am getting "error establishing a database connecting" when I try loading the page. I don't know whats causing this to happen, I read somewhere that I might need more ram so i upgraded my plan to get 2GB of ram 40GB of space. But today it crashed again, I repaired it and went to the error logs and this the same error i get when the wp-option crashes ``` [14-Sep-2016 11:07:38 UTC] WordPress database error Table './DATABASE_Name/wp_options' is marked as crashed and should be repaired for query INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('_transient_mom_share_plusone_2020', '0', 'no') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`) made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/WDXYZ/single.php'), mom_single_post_content, mom_posts_share, set_transient, add_option ``` Please help me fix this issue.
It sounds like you may be running a plugin that stores too many transient options. If you can't currently access wp-admin, try FTP'ing in and renaming your /plugins folder to disable all plugins. Then you should be able to log in to wp-admin. Next, back in FTP rename your /plugins folder back to the normal /plugins, and leave all of the plugins deactivated in wp-admin. From there, go into phpMyAdmin and view the options table. Go to the last few pages and see if you notice any patterns - you may be able to tell which plugin is storing too much in the database, and then the solution is to remove the plugin and replace it with an alternative if you really need the functionality. Once you've found the culprit, run WP-Optimize ( <https://wordpress.org/plugins/wp-optimize/> ) to clean up your database and reduce its size. It's a great plugin to run on a regular basis to keep things running smoothly.
239,258
<p>I logged out from wordpress site then,</p> <p>I edited <code>wp-config.php</code> </p> <p>and enabled <code>SSL</code></p> <pre><code>define('FORCE_SSL_LOGIN', true); define('FORCE_SSL_ADMIN', true); </code></pre> <p>then restarted apache</p> <p>but on trying to open I got the is</p> <blockquote> <p>Not Found</p> <p>The requested URL /wp-login.php was not found on this server.</p> </blockquote>
[ { "answer_id": 239273, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>It sounds like you haven't updated the Site URL and Home settings. There are 2 ways to do this:</p>\n\n<ol>\n<li><p>In phpMyAdmin, go to the wp_options table, and change your \"siteurl\" and \"home\" to include the <code>https://</code> instead of <code>http://</code>.</p></li>\n<li><p>Also open <code>/wp-config.php</code>, as the settings are sometimes overridden here. If you don't see lines like this:</p>\n\n<p><code>define('WP_HOME','http://yoursite.com');</code></p>\n\n<p><code>define('WP_SITEURL','http://yoursite.com');</code></p></li>\n</ol>\n\n<p>then there is no need to add them. It's just a way of overriding the database values that some hosts use.</p>\n\n<p>It's a good idea to update <code>.htaccess</code> to enforce SSL while you're at it.</p>\n" }, { "answer_id": 239276, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": true, "text": "<p>As per OP's comment:</p>\n\n<blockquote>\n <p><em>Yes, I have self signed using OpenSSL, now I have the site opening on HTTPS but in browser it still says connection not secure where it is showing HTTPS in the address bar.</em></p>\n</blockquote>\n\n<p>In that case, it sounds like some links are being called through HTTP while other are being called on HTTPS, giving you mixed content issues. Before you do anything, remove the <code>FORCE_SSL_</code> function that you added in your <code>wp-config.php</code>:</p>\n\n<pre><code>define('FORCE_SSL_LOGIN', true);\ndefine('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>Than, try the following steps using the Search Replace DB tool to ensure everything is pointing to HTTPS:</p>\n\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search &amp; Replace Script here</a></li>\n<li>Unzip the file and drop the folder in your <strong>localhost</strong> where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://localhost:8888/wordpress/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>Enter your HTTP URL in the <em>search for…</em> field and the HTTPS URL in the <em>replace with…</em> field, for example:\n\n<ul>\n<li><strong>Search</strong>: <code>http://localhost/wordpress</code></li>\n<li><strong>Replace</strong>: <code>https://localhost/wordpress</code></li>\n</ul></li>\n</ol>\n\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n\n<p>Also, I'd consider looking into the <a href=\"https://wordpress.org/plugins/remove-http/\" rel=\"nofollow noreferrer\">Remove HTTP plugin</a> which will automatically scan your website and remove both HTTP and HTTPS protocols from your URL links. This way it will ensure that your website doesn't have any mixed-content issues.</p>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239258", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102804/" ]
I logged out from wordpress site then, I edited `wp-config.php` and enabled `SSL` ``` define('FORCE_SSL_LOGIN', true); define('FORCE_SSL_ADMIN', true); ``` then restarted apache but on trying to open I got the is > > Not Found > > > The requested URL /wp-login.php was not found on this server. > > >
As per OP's comment: > > *Yes, I have self signed using OpenSSL, now I have the site opening on HTTPS but in browser it still says connection not secure where it is showing HTTPS in the address bar.* > > > In that case, it sounds like some links are being called through HTTP while other are being called on HTTPS, giving you mixed content issues. Before you do anything, remove the `FORCE_SSL_` function that you added in your `wp-config.php`: ``` define('FORCE_SSL_LOGIN', true); define('FORCE_SSL_ADMIN', true); ``` Than, try the following steps using the Search Replace DB tool to ensure everything is pointing to HTTPS: 1. Go and download [Interconnect IT's Database Search & Replace Script here](https://github.com/interconnectit/Search-Replace-DB/archive/master.zip) 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** ([screenshot](https://i.stack.imgur.com/J9Ga5.png)) 3. Navigate to the new folder you created in your browser (ex: `http://localhost:8888/wordpress/replace`) and [you will see the search/replace tool](https://i.stack.imgur.com/pbED1.png) 4. Enter your HTTP URL in the *search for…* field and the HTTPS URL in the *replace with…* field, for example: * **Search**: `http://localhost/wordpress` * **Replace**: `https://localhost/wordpress` You can click the *dry run* button under *actions* to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder. Also, I'd consider looking into the [Remove HTTP plugin](https://wordpress.org/plugins/remove-http/) which will automatically scan your website and remove both HTTP and HTTPS protocols from your URL links. This way it will ensure that your website doesn't have any mixed-content issues.
239,292
<p>I'm new to WordPress and I'm still learning from tutorials, but I'm confused with their conflicted ways. What the difference between these two ways to make the title a link:</p> <pre><code>&lt;h1&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt; &lt;/h1&gt; </code></pre> <p>and</p> <pre><code>&lt;?php the_title(sprintf( '&lt;h1&gt;&lt;a href="%s"&gt;', esc_url(get_permalink())), '&lt;/a&gt;&lt;/h1&gt;'); ?&gt; </code></pre> <p>Is it a performance issue? or a security? or what?</p> <p>thanks.</p> <p><strong>Edit:</strong></p> <p>I know that the function <code>the_permalink()</code> has embedded <code>esc_url</code> functionality while <code>get_permalink</code> doesn't. So in my case, is there still any difference?</p>
[ { "answer_id": 239295, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 0, "selected": false, "text": "<p>There are multiple ways to do most things in WordPress. Either that, or there are no ways at all.</p>\n\n<p>Your first example makes more sense. The second seems unnecessarily complex for no benefit.</p>\n" }, { "answer_id": 239296, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": false, "text": "<p>Going with the first set of code that you provided:</p>\n\n<pre><code>&lt;h1&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n&lt;/h1&gt;\n</code></pre>\n\n<p>Simply put, it's much cleaner and simpler to use. As you already mentioned, <code>the_permalink()</code> already covers the <code>esc_url()</code> functionality, So why do you need to write more code when one of the functions take care of it? Less is more in this case.</p>\n" }, { "answer_id": 239301, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>The second form can be handy too:</p>\n\n<ul>\n<li><p>We can also use the <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow\">third</a> parameter:</p>\n\n<pre><code>the_title( $before, $after, $echo ); \n</code></pre>\n\n<p>to assign the title to a variable. </p>\n\n<p>Here's an example:</p>\n\n<pre><code>$title = the_title( '&lt;h1 class=\"entry-title\"&gt;', '&lt;/h1&gt;', false );\n</code></pre></li>\n<li><p>This can also help reducing the use of <code>&lt;?php ?&gt;</code> delimiters.</p>\n\n<p>Here's an <a href=\"https://github.com/WordPress/WordPress/blob/d4d8ae24222b44e80740ea0b05370089cee2d5ba/wp-content/themes/twentyfifteen/content.php#L21-L25\" rel=\"nofollow\">example</a> from the <em>Twenty Fifteen</em> theme</p>\n\n<pre><code> if ( is_single() ) :\n the_title( '&lt;h1 class=\"entry-title\"&gt;', '&lt;/h1&gt;' );\n else :\n the_title( sprintf( '&lt;h2 class=\"entry-title\"&gt;&lt;a href=\"%s\" rel=\"bookmark\"&gt;', esc_url( get_permalink() ) ), '&lt;/a&gt;&lt;/h2&gt;' );\n endif;\n</code></pre>\n\n<p>but there are of course various ways to get rid of such if/else parts.</p>\n\n<p>Here's an alternative form for comparison:</p>\n\n<pre><code>&lt;?php if( is_single() ) : ?&gt;\n &lt;h1 class=\"entry-title\"&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;\n&lt;?php else : ?&gt;\n &lt;h2 class=\"entry-title\"&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" rel=\"bookmark\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n&lt;?php endif; ?&gt;\n</code></pre></li>\n</ul>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239292", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102827/" ]
I'm new to WordPress and I'm still learning from tutorials, but I'm confused with their conflicted ways. What the difference between these two ways to make the title a link: ``` <h1> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h1> ``` and ``` <?php the_title(sprintf( '<h1><a href="%s">', esc_url(get_permalink())), '</a></h1>'); ?> ``` Is it a performance issue? or a security? or what? thanks. **Edit:** I know that the function `the_permalink()` has embedded `esc_url` functionality while `get_permalink` doesn't. So in my case, is there still any difference?
The second form can be handy too: * We can also use the [third](https://developer.wordpress.org/reference/functions/the_title/) parameter: ``` the_title( $before, $after, $echo ); ``` to assign the title to a variable. Here's an example: ``` $title = the_title( '<h1 class="entry-title">', '</h1>', false ); ``` * This can also help reducing the use of `<?php ?>` delimiters. Here's an [example](https://github.com/WordPress/WordPress/blob/d4d8ae24222b44e80740ea0b05370089cee2d5ba/wp-content/themes/twentyfifteen/content.php#L21-L25) from the *Twenty Fifteen* theme ``` if ( is_single() ) : the_title( '<h1 class="entry-title">', '</h1>' ); else : the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); endif; ``` but there are of course various ways to get rid of such if/else parts. Here's an alternative form for comparison: ``` <?php if( is_single() ) : ?> <h1 class="entry-title"><?php the_title(); ?></h1> <?php else : ?> <h2 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2> <?php endif; ?> ```
239,302
<p>Some plugins place various links under their name on the primary column on the plugin page. So we end up with something like:</p> <pre><code>Home Page | Support Forums | Documentation | Upgrade to Pro Edition | Donate | Settings | Activate | Delete </code></pre> <p>In an effort to keep just the standard links <code>Settings | Activate | Delete</code> we use in our custom <code>01_plugin.php</code> the following code:</p> <pre><code> global $pagenow; if( $pagenow == 'plugins.php' ) { echo '&lt;style type=&quot;text/css&quot;&gt; .visible .proupgrade, .visible .docs, .visible .forum, .visible .jetpack-home, .visible .support {display: none ; } &lt;/style&gt;'; } </code></pre> <p>When debugging, for some reason, it gives a PHP Warning:</p> <pre><code>PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /wp-content/plugins/01-plugin/01_plugin.php:282) in /wp-content/plugins/wp-miniaudioplayer/miniAudioPlayer.php on line 231 </code></pre> <p>Can someone point us to the right direction? Which hook should we use?<br /> Is there another way to achieve our goal?</p> <blockquote> <h3>EDIT</h3> </blockquote> <p>To better understand where these links are located, please have a look at the screenshot:</p> <p><a href="https://i.stack.imgur.com/HfWOR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HfWOR.png" alt="primary-bloated" /></a></p> <p>As you can see <strong>they bloat the primary column out of proportion</strong>, using/wasting precious space, that could be otherwise awarded to the secondary column.<br /> Note: <strong>The primary column does not wrap</strong>. The secondary does.</p>
[ { "answer_id": 241011, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 3, "selected": true, "text": "<p>You have the right approach. You will want to use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\"><code>admin_enqueue_scripts</code></a> hook:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'wpse_239302_hide_action_links' );\nfunction wpse_239302_hide_action_links() {\n global $pagenow; \n if ( $pagenow == 'plugins.php' ) {\n ?&gt;\n &lt;style type=\"text/css\"&gt;\n .visible .proupgrade,\n .visible .docs,\n .visible .forum,\n .visible .jetpack-home,\n .visible .support { display: none; } \n &lt;/style&gt;\n &lt;?php\n }\n}\n</code></pre>\n" }, { "answer_id": 241012, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 1, "selected": false, "text": "<p>you can use this:</p>\n\n<pre><code>add_action('admin_footer', function () {\n if( $GLOBALS['pagenow'] == 'plugins.php' ) {\n echo '&lt;style type=\"text/css\"&gt;.visible .proupgrade, .visible .docs, .visible .forum, .visible .jetpack-home, .visible .support {display: none ; } &lt;/style&gt;'; \n }\n});\n</code></pre>\n\n<p>to style admin dashboard for different roles, then you have to append user-role into body-class (Use <a href=\"https://wordpress.stackexchange.com/questions/66834/how-to-target-with-css-admin-elements-according-to-user-role-level\">this</a>) .</p>\n" }, { "answer_id": 241071, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>We might also try to change the layout via CSS, differently than hiding it.</p>\n\n<p>Here's an example where we target the row actions of that plugin and display each action in a seperate line:</p>\n\n<pre><code>tr.active[data-slug=\"all-in-one-seo-pack\"] .row-actions.visible span{\n display: block;\n}\n</code></pre>\n\n<p>Note that we target only the action rows when the plugin is active:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xyePv.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xyePv.jpg\" alt=\"active\"></a></p>\n\n<p>else it's like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/27DOz.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/27DOz.jpg\" alt=\"deactive\"></a></p>\n" } ]
2016/09/14
[ "https://wordpress.stackexchange.com/questions/239302", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17797/" ]
Some plugins place various links under their name on the primary column on the plugin page. So we end up with something like: ``` Home Page | Support Forums | Documentation | Upgrade to Pro Edition | Donate | Settings | Activate | Delete ``` In an effort to keep just the standard links `Settings | Activate | Delete` we use in our custom `01_plugin.php` the following code: ``` global $pagenow; if( $pagenow == 'plugins.php' ) { echo '<style type="text/css"> .visible .proupgrade, .visible .docs, .visible .forum, .visible .jetpack-home, .visible .support {display: none ; } </style>'; } ``` When debugging, for some reason, it gives a PHP Warning: ``` PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /wp-content/plugins/01-plugin/01_plugin.php:282) in /wp-content/plugins/wp-miniaudioplayer/miniAudioPlayer.php on line 231 ``` Can someone point us to the right direction? Which hook should we use? Is there another way to achieve our goal? > > ### EDIT > > > To better understand where these links are located, please have a look at the screenshot: [![primary-bloated](https://i.stack.imgur.com/HfWOR.png)](https://i.stack.imgur.com/HfWOR.png) As you can see **they bloat the primary column out of proportion**, using/wasting precious space, that could be otherwise awarded to the secondary column. Note: **The primary column does not wrap**. The secondary does.
You have the right approach. You will want to use the [`admin_enqueue_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts) hook: ``` add_action( 'admin_enqueue_scripts', 'wpse_239302_hide_action_links' ); function wpse_239302_hide_action_links() { global $pagenow; if ( $pagenow == 'plugins.php' ) { ?> <style type="text/css"> .visible .proupgrade, .visible .docs, .visible .forum, .visible .jetpack-home, .visible .support { display: none; } </style> <?php } } ```
239,359
<p>I have a page where I want to show Blog Posts on a monthly basis. And I want to show the post of the previous month if the current month has no posts. Something like the image given below. It is showing the posts of August because September has no post. <a href="https://i.stack.imgur.com/PrWRY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PrWRY.jpg" alt="enter image description here"></a></p> <p>here the code I am grabbing current month post:</p> <pre><code> &lt;?php $args = array('date_query' =&gt; array( 'year' =&gt; date( 'Y' ), 'monthnum' =&gt; date( 'm' ), ), 'posts_per_page' =&gt; 10, 'paged' =&gt; $paged, 'order' =&gt; 'ASC', ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ): while($query-&gt;have_posts()): $query-&gt;the_post(); ?&gt; &lt;h2&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h2&gt; &lt;p&gt; &lt;?php the_content();?&gt; &lt;/p&gt; &lt;?php endwhile; else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; // Reset Post Data wp_reset_postdata();?&gt; </code></pre> <p>but how can I show previous month posts, if the current month has no posts</p>
[ { "answer_id": 239362, "author": "sdexp", "author_id": 102830, "author_profile": "https://wordpress.stackexchange.com/users/102830", "pm_score": 1, "selected": false, "text": "<p>I have this code which does something similar but it's only counting posts. If you grab the required info in the SQL something like this should work...</p>\n\n<pre><code>global $wpdb;\n$searchmonth = sprintf(\"%02s\", absint($monthint));\n$searchyear = 2016;\n\n$found_posts = $wpdb -&gt; get_var(\"SELECT COUNT(*) FROM $wpdb-&gt;posts WHERE post_status = 'publish' AND post_type = 'post' AND post_date LIKE '%-$searchmonth-%' AND post_date LIKE '$searchyear%' \");\n\nif($found_posts){\n /* do something */\n}else{\n\n if(1!=$monthint){\n $monthint--;\n }else{\n $monthint=12;\n $searchyear--;\n }\n /* get info for previous month */\n}\n$wpdb -&gt; flush();\n</code></pre>\n" }, { "answer_id": 239364, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>First, get the current month and year:</p>\n\n<pre><code>$month = int(current_time('m'));\n$year = int(current_time('Y'));\n</code></pre>\n\n<p>Next, get the posts in this month:</p>\n\n<pre><code>$query = new WP_Query( 'year=' . $year . '&amp;monthnum=' . $month );\n</code></pre>\n\n<p>If the query returns empty query the month before and repeat this until you have found a non empty month:</p>\n\n<pre><code>while (empty($query)) {\n $month = $month-1;\n if ($month == 0) { $month = 12; $year=$year-1;}\n $query = new WP_Query( 'year=' . $year . '&amp;monthnum=' . $month );\n }\n</code></pre>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102530/" ]
I have a page where I want to show Blog Posts on a monthly basis. And I want to show the post of the previous month if the current month has no posts. Something like the image given below. It is showing the posts of August because September has no post. [![enter image description here](https://i.stack.imgur.com/PrWRY.jpg)](https://i.stack.imgur.com/PrWRY.jpg) here the code I am grabbing current month post: ``` <?php $args = array('date_query' => array( 'year' => date( 'Y' ), 'monthnum' => date( 'm' ), ), 'posts_per_page' => 10, 'paged' => $paged, 'order' => 'ASC', ); $query = new WP_Query( $args ); if ( $query->have_posts() ): while($query->have_posts()): $query->the_post(); ?> <h2> <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h2> <p> <?php the_content();?> </p> <?php endwhile; else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; // Reset Post Data wp_reset_postdata();?> ``` but how can I show previous month posts, if the current month has no posts
First, get the current month and year: ``` $month = int(current_time('m')); $year = int(current_time('Y')); ``` Next, get the posts in this month: ``` $query = new WP_Query( 'year=' . $year . '&monthnum=' . $month ); ``` If the query returns empty query the month before and repeat this until you have found a non empty month: ``` while (empty($query)) { $month = $month-1; if ($month == 0) { $month = 12; $year=$year-1;} $query = new WP_Query( 'year=' . $year . '&monthnum=' . $month ); } ```
239,376
<p>Thanks in advance for any pointers in the right direction. I am not finding any relevant info out there.</p> <p>I have a finished WP site with a customized Bones Theme functioning perfectly locally. I have uploaded it many times and in many variations. The customized theme is recognized by its name and activated. The background-images from the image file show up but the issue is the entire content ie pages and css do not show. I am using the MySQL data for wp-config which the provider has provided. In the current attempt I have used the WP installation provided by the provider and have placed my theme in the themes folder using ftp.</p> <p>I assuming it is not finding the wp_ database. </p> <p>I'd like to post the code but am being told it looks like spam… </p>
[ { "answer_id": 239362, "author": "sdexp", "author_id": 102830, "author_profile": "https://wordpress.stackexchange.com/users/102830", "pm_score": 1, "selected": false, "text": "<p>I have this code which does something similar but it's only counting posts. If you grab the required info in the SQL something like this should work...</p>\n\n<pre><code>global $wpdb;\n$searchmonth = sprintf(\"%02s\", absint($monthint));\n$searchyear = 2016;\n\n$found_posts = $wpdb -&gt; get_var(\"SELECT COUNT(*) FROM $wpdb-&gt;posts WHERE post_status = 'publish' AND post_type = 'post' AND post_date LIKE '%-$searchmonth-%' AND post_date LIKE '$searchyear%' \");\n\nif($found_posts){\n /* do something */\n}else{\n\n if(1!=$monthint){\n $monthint--;\n }else{\n $monthint=12;\n $searchyear--;\n }\n /* get info for previous month */\n}\n$wpdb -&gt; flush();\n</code></pre>\n" }, { "answer_id": 239364, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>First, get the current month and year:</p>\n\n<pre><code>$month = int(current_time('m'));\n$year = int(current_time('Y'));\n</code></pre>\n\n<p>Next, get the posts in this month:</p>\n\n<pre><code>$query = new WP_Query( 'year=' . $year . '&amp;monthnum=' . $month );\n</code></pre>\n\n<p>If the query returns empty query the month before and repeat this until you have found a non empty month:</p>\n\n<pre><code>while (empty($query)) {\n $month = $month-1;\n if ($month == 0) { $month = 12; $year=$year-1;}\n $query = new WP_Query( 'year=' . $year . '&amp;monthnum=' . $month );\n }\n</code></pre>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239376", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102862/" ]
Thanks in advance for any pointers in the right direction. I am not finding any relevant info out there. I have a finished WP site with a customized Bones Theme functioning perfectly locally. I have uploaded it many times and in many variations. The customized theme is recognized by its name and activated. The background-images from the image file show up but the issue is the entire content ie pages and css do not show. I am using the MySQL data for wp-config which the provider has provided. In the current attempt I have used the WP installation provided by the provider and have placed my theme in the themes folder using ftp. I assuming it is not finding the wp\_ database. I'd like to post the code but am being told it looks like spam…
First, get the current month and year: ``` $month = int(current_time('m')); $year = int(current_time('Y')); ``` Next, get the posts in this month: ``` $query = new WP_Query( 'year=' . $year . '&monthnum=' . $month ); ``` If the query returns empty query the month before and repeat this until you have found a non empty month: ``` while (empty($query)) { $month = $month-1; if ($month == 0) { $month = 12; $year=$year-1;} $query = new WP_Query( 'year=' . $year . '&monthnum=' . $month ); } ```
239,392
<p>I'm trying to use WP Crontrol to run a cron job that executes 2 URLS:</p> <p>Cron job 1: exampleurl.com - once every 2 minutes Cron job 2: exampleurl2.com - once every 24 hours</p> <p>How can I right a function to do this that I can execute via the hook name using WP Crontrol?</p> <p>Thanks,</p>
[ { "answer_id": 239398, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>To answer your question, slightly incorrect. You can also use <a href=\"https://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow\"><code>wp_schedule_event()</code></a>, avoiding the need of a plugin.</p>\n" }, { "answer_id": 369870, "author": "Ahmer Wpcoder110", "author_id": 180018, "author_profile": "https://wordpress.stackexchange.com/users/180018", "pm_score": 1, "selected": false, "text": "<p>AS said by Fleuv you can use wp_schedule_event() function to execute your code like this</p>\n<pre><code>add_action('my_twfours_action', 'my_twfours_action_fn');\nmy_twfours_action_fn (){\n //this code will execute every 24 hours\n}\nwp_schedule_event( time(), 'daily', 'my_twfours_action' ); //adding new cron schedule event\n</code></pre>\n<p>To create your 2 minutes filter and then scheduling a cron jo is like</p>\n<pre><code>function my_two_minutes_filter( $schedules ) {\n $schedules['two_minutes'] = array(\n 'interval' =&gt; 120,\n 'display' =&gt; __( 'Every 2 minutes' ),\n );\n return $schedules;\n}\nadd_filter( 'cron_schedules', 'my_two_minutes_filter' );\n</code></pre>\n<p>then add action and shedule the event like</p>\n<pre><code>add_action('my_twominutes_call', 'my_twominutes_call_fn');\nmy_twominutes_call_fn(){\n //this code will execute every 2 minutes\n}\nwp_schedule_event( time(), 'two_minutes', 'my_twominutes_call' ); //adding new cron schedule event\n</code></pre>\n<p>Read more here <a href=\"https://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow noreferrer\">wp_schedule_event();</a></p>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239392", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102370/" ]
I'm trying to use WP Crontrol to run a cron job that executes 2 URLS: Cron job 1: exampleurl.com - once every 2 minutes Cron job 2: exampleurl2.com - once every 24 hours How can I right a function to do this that I can execute via the hook name using WP Crontrol? Thanks,
AS said by Fleuv you can use wp\_schedule\_event() function to execute your code like this ``` add_action('my_twfours_action', 'my_twfours_action_fn'); my_twfours_action_fn (){ //this code will execute every 24 hours } wp_schedule_event( time(), 'daily', 'my_twfours_action' ); //adding new cron schedule event ``` To create your 2 minutes filter and then scheduling a cron jo is like ``` function my_two_minutes_filter( $schedules ) { $schedules['two_minutes'] = array( 'interval' => 120, 'display' => __( 'Every 2 minutes' ), ); return $schedules; } add_filter( 'cron_schedules', 'my_two_minutes_filter' ); ``` then add action and shedule the event like ``` add_action('my_twominutes_call', 'my_twominutes_call_fn'); my_twominutes_call_fn(){ //this code will execute every 2 minutes } wp_schedule_event( time(), 'two_minutes', 'my_twominutes_call' ); //adding new cron schedule event ``` Read more here [wp\_schedule\_event();](https://codex.wordpress.org/Function_Reference/wp_schedule_event)
239,394
<p>Just installed an existing WordPress on my localhost (<a href="https://www.mamp.info/en/" rel="nofollow">MAMP</a>) to check for a few images issues.</p> <p>However, when I visit:</p> <pre><code>localhost:8888/wordpress/ </code></pre> <p>I'm redirected to:</p> <pre><code>localhost/wordpress/ </code></pre> <p>Which is not the path to my files anymore.</p> <p>I've checked for any possible redirection in my <code>.htaccess</code> but it was empty. Where could this be coming from? I've tried to change port as well, but it was the exact same behavior.</p>
[ { "answer_id": 239397, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>Wordpress defines a static value for the site url after installation. This data is stored in the database. However you can override this value with constants in your <code>./wp-config.php</code> or you can change the value in the option table at your database of course. I usually go for the first option, I <a href=\"https://wordpress.stackexchange.com/a/191859\">define the constant with a dynamic value</a>. So it also works with domain aliases.</p>\n" }, { "answer_id": 239399, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": false, "text": "<p>There are a few variables that need to be changed in order for you to update to the new link on your WordPress site since you mention that you've installed an existing WordPress site that has already been set up.</p>\n\n<p>Try the following steps using the Search Replace DB tool:</p>\n\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search &amp; Replace Script here</a></li>\n<li>Unzip the file and drop the folder in your <strong>localhost</strong> where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://localhost:8888/wordpress/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>Enter your old URL in the <em>search for…</em> field and the new URL in the <em>replace with…</em> field, like so:\n\n<ul>\n<li><strong>Search</strong>: <code>localhost/wordpress</code></li>\n<li><strong>Replace</strong>: <code>localhost:8888/wordpress</code></li>\n</ul></li>\n</ol>\n\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n" }, { "answer_id": 262915, "author": "ghanshyam v", "author_id": 117204, "author_profile": "https://wordpress.stackexchange.com/users/117204", "pm_score": 0, "selected": false, "text": "<p>If you’re moving your site from one server to another and changing the URL of your WordPress installation, the approach below allows you to do so easily without affecting the old site:</p>\n\n<p>Backup the database on your current site\nInstall the database on your new host\nOn the new host, define the new site URL in the wp-config.php file,</p>\n\n<p>Log in at your new admin URL and run Better Search Replace on the old site URL for the new site URL\nDelete the site_url constant you added to wp-config.php. You may also need to regenerate your .htaccess by going to Settings -> Permalinks and saving the settings.</p>\n\n<p>USE this plugin: <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a></p>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102883/" ]
Just installed an existing WordPress on my localhost ([MAMP](https://www.mamp.info/en/)) to check for a few images issues. However, when I visit: ``` localhost:8888/wordpress/ ``` I'm redirected to: ``` localhost/wordpress/ ``` Which is not the path to my files anymore. I've checked for any possible redirection in my `.htaccess` but it was empty. Where could this be coming from? I've tried to change port as well, but it was the exact same behavior.
There are a few variables that need to be changed in order for you to update to the new link on your WordPress site since you mention that you've installed an existing WordPress site that has already been set up. Try the following steps using the Search Replace DB tool: 1. Go and download [Interconnect IT's Database Search & Replace Script here](https://github.com/interconnectit/Search-Replace-DB/archive/master.zip) 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** ([screenshot](https://i.stack.imgur.com/J9Ga5.png)) 3. Navigate to the new folder you created in your browser (ex: `http://localhost:8888/wordpress/replace`) and [you will see the search/replace tool](https://i.stack.imgur.com/pbED1.png) 4. Enter your old URL in the *search for…* field and the new URL in the *replace with…* field, like so: * **Search**: `localhost/wordpress` * **Replace**: `localhost:8888/wordpress` You can click the *dry run* button under *actions* to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
239,401
<p>I understand that when using <code>get_template_part('content', get_post_format());</code> it will help choosing a <code>post format</code> for specific page according to post format.</p> <p>And if there is no post format 'i.e it's standard', then it will fallback to <code>content.php</code></p> <p>But what if I used <code>content-single.php</code> with some logic like this:</p> <pre><code>if (get_post_format() == false) { get_template_part('content', 'single'); } else { get_template_part('content', get_post_format()); } </code></pre> <p>Do I still need <code>content.php</code> page? is there any other functionalities that I don't know about? </p>
[ { "answer_id": 262652, "author": "Vishal Kumar Sahu", "author_id": 101300, "author_profile": "https://wordpress.stackexchange.com/users/101300", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>You could get by with only the one template (content.php). That's\n usually less than ideal.</p>\n</blockquote>\n\n<p>From <a href=\"https://teamtreehouse.com/community/unclear-about-the-function-of-contentphp-contentpagephp-and-contentnonephp\" rel=\"nofollow noreferrer\">the teamtreehouse</a>'s blog should clear your question.</p>\n\n<p>For me that approach is a fallback way.</p>\n" }, { "answer_id": 262655, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<p>No, <code>content.php</code> and <code>content-single.php</code> are not the same thing.</p>\n\n<p>In your example CODE:</p>\n\n<pre><code>if (get_post_format() == false) {\n get_template_part('content', 'single');\n} else {\n get_template_part('content', get_post_format());\n}\n</code></pre>\n\n<p>WordPress will load <code>content-single.php</code> when <code>get_post_format()</code> is <code>false</code>. However, <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part( $slug, $name )</code></a> may still try to load <code>content.php</code> when you call it with <code>get_template_part('content', get_post_format());</code> in the following example:</p>\n\n<ol>\n<li><p><code>get_post_format()</code> returns (for example) <code>video</code>.</p></li>\n<li><p>But you don't have <code>content-video.php</code> template part file.</p></li>\n</ol>\n\n<p>So basically, even when <code>get_post_format()</code> is not <code>false</code>, <code>content.php</code> will still provide you with the default template part if the corresponding post format related template part was not created.</p>\n\n<blockquote>\n <p><strong><em>Bottom line:</em></strong> whatever the main <code>$slug</code> is, it's always a good idea to keep the default template part file as the final fallback template part (in your case <code>content.php</code> is that default fallback template part file). <strong>So YES, you may still need it</strong>. So don't delete it, leave it alone.</p>\n</blockquote>\n\n<p>The following is the part of the CODE from core function <code>get_template_part</code>. You'll see that, the core always loads <code>$templates[] = \"{$slug}.php\";</code> as the final fallback template file:</p>\n\n<pre><code>function get_template_part( $slug, $name = null ) {\n // ... more CODE from WP core\n $templates = array();\n $name = (string) $name;\n if ( '' !== $name )\n $templates[] = \"{$slug}-{$name}.php\";\n\n $templates[] = \"{$slug}.php\"; \n locate_template($templates, true, false);\n}\n</code></pre>\n\n<p>Then, in <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\"><code>locate_template</code></a> function it loops through the <code>$templates</code> array until it finds the corresponding file, with the following CODE:</p>\n\n<pre><code>function locate_template($template_names, $load = false, $require_once = true ) {\n $located = '';\n foreach ( (array) $template_names as $template_name ) {\n if ( !$template_name )\n continue;\n if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {\n $located = STYLESHEETPATH . '/' . $template_name;\n break;\n } elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {\n $located = TEMPLATEPATH . '/' . $template_name;\n break;\n } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {\n $located = ABSPATH . WPINC . '/theme-compat/' . $template_name;\n break;\n }\n }\n if ( $load &amp;&amp; '' != $located )\n load_template( $located, $require_once );\n\n return $located;\n}\n</code></pre>\n\n<p>So as you can see from the above CODE, if you delete <code>content.php</code>, and if the theme user has a post format for which you don't have a template part file, WordPress will not find template file to fall back to, so will simply load nothing in that case. As a final attempt, WordPress tries to load a template part file from <code>wp-includes/theme-compat/</code> core directory, but there is no <code>content.php</code> template part file in WP core.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> However, if you are building a child theme and the parent theme already contains the <code>content.php</code> file, then you don't need <code>content.php</code> file in the child theme (if you don't do any modification there), because in that case, WordPress will use the parent theme's <code>content.php</code> file as the fallback template part file.</p>\n</blockquote>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102827/" ]
I understand that when using `get_template_part('content', get_post_format());` it will help choosing a `post format` for specific page according to post format. And if there is no post format 'i.e it's standard', then it will fallback to `content.php` But what if I used `content-single.php` with some logic like this: ``` if (get_post_format() == false) { get_template_part('content', 'single'); } else { get_template_part('content', get_post_format()); } ``` Do I still need `content.php` page? is there any other functionalities that I don't know about?
No, `content.php` and `content-single.php` are not the same thing. In your example CODE: ``` if (get_post_format() == false) { get_template_part('content', 'single'); } else { get_template_part('content', get_post_format()); } ``` WordPress will load `content-single.php` when `get_post_format()` is `false`. However, [`get_template_part( $slug, $name )`](https://developer.wordpress.org/reference/functions/get_template_part/) may still try to load `content.php` when you call it with `get_template_part('content', get_post_format());` in the following example: 1. `get_post_format()` returns (for example) `video`. 2. But you don't have `content-video.php` template part file. So basically, even when `get_post_format()` is not `false`, `content.php` will still provide you with the default template part if the corresponding post format related template part was not created. > > ***Bottom line:*** whatever the main `$slug` is, it's always a good idea to keep the default template part file as the final fallback template part (in your case `content.php` is that default fallback template part file). **So YES, you may still need it**. So don't delete it, leave it alone. > > > The following is the part of the CODE from core function `get_template_part`. You'll see that, the core always loads `$templates[] = "{$slug}.php";` as the final fallback template file: ``` function get_template_part( $slug, $name = null ) { // ... more CODE from WP core $templates = array(); $name = (string) $name; if ( '' !== $name ) $templates[] = "{$slug}-{$name}.php"; $templates[] = "{$slug}.php"; locate_template($templates, true, false); } ``` Then, in [`locate_template`](https://developer.wordpress.org/reference/functions/locate_template/) function it loops through the `$templates` array until it finds the corresponding file, with the following CODE: ``` function locate_template($template_names, $load = false, $require_once = true ) { $located = ''; foreach ( (array) $template_names as $template_name ) { if ( !$template_name ) continue; if ( file_exists(STYLESHEETPATH . '/' . $template_name)) { $located = STYLESHEETPATH . '/' . $template_name; break; } elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) { $located = TEMPLATEPATH . '/' . $template_name; break; } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) { $located = ABSPATH . WPINC . '/theme-compat/' . $template_name; break; } } if ( $load && '' != $located ) load_template( $located, $require_once ); return $located; } ``` So as you can see from the above CODE, if you delete `content.php`, and if the theme user has a post format for which you don't have a template part file, WordPress will not find template file to fall back to, so will simply load nothing in that case. As a final attempt, WordPress tries to load a template part file from `wp-includes/theme-compat/` core directory, but there is no `content.php` template part file in WP core. > > ***Note:*** However, if you are building a child theme and the parent theme already contains the `content.php` file, then you don't need `content.php` file in the child theme (if you don't do any modification there), because in that case, WordPress will use the parent theme's `content.php` file as the fallback template part file. > > >
239,402
<p>I need to create php file like <strong>download.php</strong>.</p> <p>In this file download links for movie or program,</p> <p>when users click on download button, this file <strong>download.php</strong> load in fancybox and display download links.</p> <p><a href="http://sitename/template_path/download.php?post_id=post_id" rel="nofollow">http://sitename/template_path/download.php?post_id=post_id</a></p>
[ { "answer_id": 262652, "author": "Vishal Kumar Sahu", "author_id": 101300, "author_profile": "https://wordpress.stackexchange.com/users/101300", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>You could get by with only the one template (content.php). That's\n usually less than ideal.</p>\n</blockquote>\n\n<p>From <a href=\"https://teamtreehouse.com/community/unclear-about-the-function-of-contentphp-contentpagephp-and-contentnonephp\" rel=\"nofollow noreferrer\">the teamtreehouse</a>'s blog should clear your question.</p>\n\n<p>For me that approach is a fallback way.</p>\n" }, { "answer_id": 262655, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<p>No, <code>content.php</code> and <code>content-single.php</code> are not the same thing.</p>\n\n<p>In your example CODE:</p>\n\n<pre><code>if (get_post_format() == false) {\n get_template_part('content', 'single');\n} else {\n get_template_part('content', get_post_format());\n}\n</code></pre>\n\n<p>WordPress will load <code>content-single.php</code> when <code>get_post_format()</code> is <code>false</code>. However, <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part( $slug, $name )</code></a> may still try to load <code>content.php</code> when you call it with <code>get_template_part('content', get_post_format());</code> in the following example:</p>\n\n<ol>\n<li><p><code>get_post_format()</code> returns (for example) <code>video</code>.</p></li>\n<li><p>But you don't have <code>content-video.php</code> template part file.</p></li>\n</ol>\n\n<p>So basically, even when <code>get_post_format()</code> is not <code>false</code>, <code>content.php</code> will still provide you with the default template part if the corresponding post format related template part was not created.</p>\n\n<blockquote>\n <p><strong><em>Bottom line:</em></strong> whatever the main <code>$slug</code> is, it's always a good idea to keep the default template part file as the final fallback template part (in your case <code>content.php</code> is that default fallback template part file). <strong>So YES, you may still need it</strong>. So don't delete it, leave it alone.</p>\n</blockquote>\n\n<p>The following is the part of the CODE from core function <code>get_template_part</code>. You'll see that, the core always loads <code>$templates[] = \"{$slug}.php\";</code> as the final fallback template file:</p>\n\n<pre><code>function get_template_part( $slug, $name = null ) {\n // ... more CODE from WP core\n $templates = array();\n $name = (string) $name;\n if ( '' !== $name )\n $templates[] = \"{$slug}-{$name}.php\";\n\n $templates[] = \"{$slug}.php\"; \n locate_template($templates, true, false);\n}\n</code></pre>\n\n<p>Then, in <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\"><code>locate_template</code></a> function it loops through the <code>$templates</code> array until it finds the corresponding file, with the following CODE:</p>\n\n<pre><code>function locate_template($template_names, $load = false, $require_once = true ) {\n $located = '';\n foreach ( (array) $template_names as $template_name ) {\n if ( !$template_name )\n continue;\n if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {\n $located = STYLESHEETPATH . '/' . $template_name;\n break;\n } elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {\n $located = TEMPLATEPATH . '/' . $template_name;\n break;\n } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {\n $located = ABSPATH . WPINC . '/theme-compat/' . $template_name;\n break;\n }\n }\n if ( $load &amp;&amp; '' != $located )\n load_template( $located, $require_once );\n\n return $located;\n}\n</code></pre>\n\n<p>So as you can see from the above CODE, if you delete <code>content.php</code>, and if the theme user has a post format for which you don't have a template part file, WordPress will not find template file to fall back to, so will simply load nothing in that case. As a final attempt, WordPress tries to load a template part file from <code>wp-includes/theme-compat/</code> core directory, but there is no <code>content.php</code> template part file in WP core.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> However, if you are building a child theme and the parent theme already contains the <code>content.php</code> file, then you don't need <code>content.php</code> file in the child theme (if you don't do any modification there), because in that case, WordPress will use the parent theme's <code>content.php</code> file as the fallback template part file.</p>\n</blockquote>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239402", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98853/" ]
I need to create php file like **download.php**. In this file download links for movie or program, when users click on download button, this file **download.php** load in fancybox and display download links. <http://sitename/template_path/download.php?post_id=post_id>
No, `content.php` and `content-single.php` are not the same thing. In your example CODE: ``` if (get_post_format() == false) { get_template_part('content', 'single'); } else { get_template_part('content', get_post_format()); } ``` WordPress will load `content-single.php` when `get_post_format()` is `false`. However, [`get_template_part( $slug, $name )`](https://developer.wordpress.org/reference/functions/get_template_part/) may still try to load `content.php` when you call it with `get_template_part('content', get_post_format());` in the following example: 1. `get_post_format()` returns (for example) `video`. 2. But you don't have `content-video.php` template part file. So basically, even when `get_post_format()` is not `false`, `content.php` will still provide you with the default template part if the corresponding post format related template part was not created. > > ***Bottom line:*** whatever the main `$slug` is, it's always a good idea to keep the default template part file as the final fallback template part (in your case `content.php` is that default fallback template part file). **So YES, you may still need it**. So don't delete it, leave it alone. > > > The following is the part of the CODE from core function `get_template_part`. You'll see that, the core always loads `$templates[] = "{$slug}.php";` as the final fallback template file: ``` function get_template_part( $slug, $name = null ) { // ... more CODE from WP core $templates = array(); $name = (string) $name; if ( '' !== $name ) $templates[] = "{$slug}-{$name}.php"; $templates[] = "{$slug}.php"; locate_template($templates, true, false); } ``` Then, in [`locate_template`](https://developer.wordpress.org/reference/functions/locate_template/) function it loops through the `$templates` array until it finds the corresponding file, with the following CODE: ``` function locate_template($template_names, $load = false, $require_once = true ) { $located = ''; foreach ( (array) $template_names as $template_name ) { if ( !$template_name ) continue; if ( file_exists(STYLESHEETPATH . '/' . $template_name)) { $located = STYLESHEETPATH . '/' . $template_name; break; } elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) { $located = TEMPLATEPATH . '/' . $template_name; break; } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) { $located = ABSPATH . WPINC . '/theme-compat/' . $template_name; break; } } if ( $load && '' != $located ) load_template( $located, $require_once ); return $located; } ``` So as you can see from the above CODE, if you delete `content.php`, and if the theme user has a post format for which you don't have a template part file, WordPress will not find template file to fall back to, so will simply load nothing in that case. As a final attempt, WordPress tries to load a template part file from `wp-includes/theme-compat/` core directory, but there is no `content.php` template part file in WP core. > > ***Note:*** However, if you are building a child theme and the parent theme already contains the `content.php` file, then you don't need `content.php` file in the child theme (if you don't do any modification there), because in that case, WordPress will use the parent theme's `content.php` file as the fallback template part file. > > >
239,421
<p>The output of the settings API's function <code>add_settings_field()</code> is this:</p> <pre><code>&lt;tr&gt; &lt;th scope="row"&gt;Your title&lt;/th&gt; &lt;td&gt; Your field output &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I know I can't change the way it's output, but I was wondering if there is a way I can put a <code>display:none;</code> on the <code>&lt;tr&gt;</code> with PHP? I don't want to do it with Javascript because then there is a flash of unstyled content.</p> <p>Basically, I want a way to hide a row that's output via <code>add_settings_field()</code>, because I need it on the frontend - but later on in my flow.</p>
[ { "answer_id": 239435, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>You can hide it using jQuery which will be inserted in the <code>wp-admin</code> header:</p>\n\n<pre><code>add_action( 'admin_head', 'wpse_239421_hide_section' );\nfunction wpse_239421_hide_section() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(document).ready(function($) {\n $('[scope=row]').closest('tr').hide();\n } );\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n\n<p>This will remove the closet <code>tr</code> bases on the <code>scope=row</code>.</p>\n" }, { "answer_id": 271323, "author": "Lachlan Arthur", "author_id": 50425, "author_profile": "https://wordpress.stackexchange.com/users/50425", "pm_score": 1, "selected": false, "text": "<p>The sixth parameter (<code>$args</code>) of the <code>add_settings_field</code> function can contain a <code>class</code> value that will be added to the <code>&lt;tr&gt;</code>.</p>\n\n<p>You can use this with the built-in admin css class <code>.hidden</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_settings_field(\n 'field_id',\n 'Useless Field Label',\n 'render_hidden_field_function',\n 'some_settings_page',\n 'a_section_slug',\n [\n 'class' =&gt; 'hidden'\n ]\n);\n</code></pre>\n" }, { "answer_id": 320893, "author": "welek", "author_id": 155189, "author_profile": "https://wordpress.stackexchange.com/users/155189", "pm_score": 0, "selected": false, "text": "<pre><code> jQuery(document).ready(function(){\n jQuery('.my_add_settings_field_class').find('[scope=row]').hide(); \n });\n</code></pre>\n" }, { "answer_id": 408610, "author": "koolimed", "author_id": 224945, "author_profile": "https://wordpress.stackexchange.com/users/224945", "pm_score": 0, "selected": false, "text": "<pre><code>add_settings_field(\n 'myprefix_setting-id',\n 'This is the setting title',\n 'myprefix_setting_callback_function',\n 'general',\n 'default'',\n array('class' =&gt; 'hidden')\n);\n</code></pre>\n<p>That should/must do the job. Just add the extra arguments &quot;class&quot; used when outputting the field.</p>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102898/" ]
The output of the settings API's function `add_settings_field()` is this: ``` <tr> <th scope="row">Your title</th> <td> Your field output </td> </tr> ``` I know I can't change the way it's output, but I was wondering if there is a way I can put a `display:none;` on the `<tr>` with PHP? I don't want to do it with Javascript because then there is a flash of unstyled content. Basically, I want a way to hide a row that's output via `add_settings_field()`, because I need it on the frontend - but later on in my flow.
You can hide it using jQuery which will be inserted in the `wp-admin` header: ``` add_action( 'admin_head', 'wpse_239421_hide_section' ); function wpse_239421_hide_section() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { $('[scope=row]').closest('tr').hide(); } ); </script> <?php } ``` This will remove the closet `tr` bases on the `scope=row`.
239,423
<p>I'm trying to format the list produced by <code>wp_nav_menu()</code> so that within each <code>&lt;li&gt;</code> is a <code>&lt;span&gt;</code> that wraps the text. At first I thought I could accomplish this using the the <code>items_wrap</code> argument, but that changes only the enclosing <code>&lt;ul&gt;</code>, correct? This seems like it should be simple enough to accomplish. Thanks!</p>
[ { "answer_id": 239435, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>You can hide it using jQuery which will be inserted in the <code>wp-admin</code> header:</p>\n\n<pre><code>add_action( 'admin_head', 'wpse_239421_hide_section' );\nfunction wpse_239421_hide_section() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(document).ready(function($) {\n $('[scope=row]').closest('tr').hide();\n } );\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n\n<p>This will remove the closet <code>tr</code> bases on the <code>scope=row</code>.</p>\n" }, { "answer_id": 271323, "author": "Lachlan Arthur", "author_id": 50425, "author_profile": "https://wordpress.stackexchange.com/users/50425", "pm_score": 1, "selected": false, "text": "<p>The sixth parameter (<code>$args</code>) of the <code>add_settings_field</code> function can contain a <code>class</code> value that will be added to the <code>&lt;tr&gt;</code>.</p>\n\n<p>You can use this with the built-in admin css class <code>.hidden</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_settings_field(\n 'field_id',\n 'Useless Field Label',\n 'render_hidden_field_function',\n 'some_settings_page',\n 'a_section_slug',\n [\n 'class' =&gt; 'hidden'\n ]\n);\n</code></pre>\n" }, { "answer_id": 320893, "author": "welek", "author_id": 155189, "author_profile": "https://wordpress.stackexchange.com/users/155189", "pm_score": 0, "selected": false, "text": "<pre><code> jQuery(document).ready(function(){\n jQuery('.my_add_settings_field_class').find('[scope=row]').hide(); \n });\n</code></pre>\n" }, { "answer_id": 408610, "author": "koolimed", "author_id": 224945, "author_profile": "https://wordpress.stackexchange.com/users/224945", "pm_score": 0, "selected": false, "text": "<pre><code>add_settings_field(\n 'myprefix_setting-id',\n 'This is the setting title',\n 'myprefix_setting_callback_function',\n 'general',\n 'default'',\n array('class' =&gt; 'hidden')\n);\n</code></pre>\n<p>That should/must do the job. Just add the extra arguments &quot;class&quot; used when outputting the field.</p>\n" } ]
2016/09/15
[ "https://wordpress.stackexchange.com/questions/239423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102900/" ]
I'm trying to format the list produced by `wp_nav_menu()` so that within each `<li>` is a `<span>` that wraps the text. At first I thought I could accomplish this using the the `items_wrap` argument, but that changes only the enclosing `<ul>`, correct? This seems like it should be simple enough to accomplish. Thanks!
You can hide it using jQuery which will be inserted in the `wp-admin` header: ``` add_action( 'admin_head', 'wpse_239421_hide_section' ); function wpse_239421_hide_section() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { $('[scope=row]').closest('tr').hide(); } ); </script> <?php } ``` This will remove the closet `tr` bases on the `scope=row`.
239,452
<p>I've been working with embeded content and as many already know, wordpress wraps the_content() lines in p tags.</p> <p>So, found this:</p> <pre><code>$content = preg_replace('/&lt;p&gt;\s*(&lt;img .* \/&gt;)\s*(&lt;\/a&gt;)?\s*&lt;\/p&gt;/iU', '\1\2\3', $content); return preg_replace('/&lt;p&gt;\s*(&lt;iframe .*&gt;*.&lt;\/iframe&gt;)\s*&lt;\/p&gt;/iU', '\1', $content); </code></pre> <p>When I change "iframe" by "script" it works, but then only for one of them, I need both beacuse the twitter embbeds create a hidden script element wich in turn creates a ghost paragraph.</p>
[ { "answer_id": 239457, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 3, "selected": true, "text": "<p>This should do it and also remove <code>&lt;p&gt;</code> tags from images that are linked.</p>\n\n<p>Why it removes it from only one <code>&lt;script&gt;</code> instance is hard to tell. Would have to see your website code to investigate further.</p>\n\n<pre><code>// Remove p tags from images, scripts, and iframes.\nfunction remove_some_ptags( $content ) {\n $content = preg_replace('/&lt;p&gt;\\s*(&lt;a .*&gt;)?\\s*(&lt;img .* \\/&gt;)\\s*(&lt;\\/a&gt;)?\\s*&lt;\\/p&gt;/iU', '\\1\\2\\3', $content);\n $content = preg_replace('/&lt;p&gt;\\s*(&lt;script.*&gt;*.&lt;\\/script&gt;)\\s*&lt;\\/p&gt;/iU', '\\1', $content);\n $content = preg_replace('/&lt;p&gt;\\s*(&lt;iframe.*&gt;*.&lt;\\/iframe&gt;)\\s*&lt;\\/p&gt;/iU', '\\1', $content);\n return $content;\n}\nadd_filter( 'the_content', 'remove_some_ptags' );\n</code></pre>\n" }, { "answer_id": 357330, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 0, "selected": false, "text": "<p>Here is a JavaScript function that does it:</p>\n\n<pre><code>moveIframesOutOfPtags() {\n let iframes = document.querySelectorAll( 'iframe' );\n\n let before = \"&lt;div class=\"iframe-container\"&gt;\";\n let after = \"&lt;/div&gt;\";\n\n Object.entries( iframes ).forEach( entry =&gt; {\n let value = entry[1];\n\n if( value.parentNode.nodeName === 'P' || value.parentNode.nodeName === 'p' ){\n value.parentNode.outerHTML = before + value.parentNode.innerHTML + after;\n }\n });\n}\n</code></pre>\n\n<p>I've written a few more details <a href=\"https://stackoverflow.com/questions/50989733/strip-automatic-p-tags-around-images-videos-iframes-in-wordpress-4-9/59946156#59946156\">over here</a>.</p>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101510/" ]
I've been working with embeded content and as many already know, wordpress wraps the\_content() lines in p tags. So, found this: ``` $content = preg_replace('/<p>\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); ``` When I change "iframe" by "script" it works, but then only for one of them, I need both beacuse the twitter embbeds create a hidden script element wich in turn creates a ghost paragraph.
This should do it and also remove `<p>` tags from images that are linked. Why it removes it from only one `<script>` instance is hard to tell. Would have to see your website code to investigate further. ``` // Remove p tags from images, scripts, and iframes. function remove_some_ptags( $content ) { $content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); $content = preg_replace('/<p>\s*(<script.*>*.<\/script>)\s*<\/p>/iU', '\1', $content); $content = preg_replace('/<p>\s*(<iframe.*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); return $content; } add_filter( 'the_content', 'remove_some_ptags' ); ```
239,475
<p>I'm attempting to order posts by meta data, which is working fine, but the posts without the meta are not shown.</p> <p>I've tried a couple of guides on Stack Exchange that come up with a quick Google, of which people say they work fine, but adding to my site, the code just does not want to show posts without the meta data.</p> <p>What I'm trying to achieve is essentially a sticky post, so when a user clicks "Pin Post", a piece of post meta data is stored as <code>"pin_".$user</code> (so it is unique on this post) with a value of <code>"1"</code>.</p> <p>I would like to show posts that have the value <code>"1"</code> at the top, subsequently ordered by date, after which all other posts without the meta data should be shown, in date order.</p> <p>I realise this code is incomplete, but here is what I have so far;</p> <pre><code>query_posts(array('post_type' =&gt; array('beauty', 'health', 'food'), 'author_in' =&gt; $follow, 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'pin_'.$user, 'showposts' =&gt; -1, 'order' =&gt; 'DESC')); if ( have_posts() ) : while ( have_posts() ) : the_post(); </code></pre> <p>How would I adapt this to produce the desired result?</p>
[ { "answer_id": 239457, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 3, "selected": true, "text": "<p>This should do it and also remove <code>&lt;p&gt;</code> tags from images that are linked.</p>\n\n<p>Why it removes it from only one <code>&lt;script&gt;</code> instance is hard to tell. Would have to see your website code to investigate further.</p>\n\n<pre><code>// Remove p tags from images, scripts, and iframes.\nfunction remove_some_ptags( $content ) {\n $content = preg_replace('/&lt;p&gt;\\s*(&lt;a .*&gt;)?\\s*(&lt;img .* \\/&gt;)\\s*(&lt;\\/a&gt;)?\\s*&lt;\\/p&gt;/iU', '\\1\\2\\3', $content);\n $content = preg_replace('/&lt;p&gt;\\s*(&lt;script.*&gt;*.&lt;\\/script&gt;)\\s*&lt;\\/p&gt;/iU', '\\1', $content);\n $content = preg_replace('/&lt;p&gt;\\s*(&lt;iframe.*&gt;*.&lt;\\/iframe&gt;)\\s*&lt;\\/p&gt;/iU', '\\1', $content);\n return $content;\n}\nadd_filter( 'the_content', 'remove_some_ptags' );\n</code></pre>\n" }, { "answer_id": 357330, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 0, "selected": false, "text": "<p>Here is a JavaScript function that does it:</p>\n\n<pre><code>moveIframesOutOfPtags() {\n let iframes = document.querySelectorAll( 'iframe' );\n\n let before = \"&lt;div class=\"iframe-container\"&gt;\";\n let after = \"&lt;/div&gt;\";\n\n Object.entries( iframes ).forEach( entry =&gt; {\n let value = entry[1];\n\n if( value.parentNode.nodeName === 'P' || value.parentNode.nodeName === 'p' ){\n value.parentNode.outerHTML = before + value.parentNode.innerHTML + after;\n }\n });\n}\n</code></pre>\n\n<p>I've written a few more details <a href=\"https://stackoverflow.com/questions/50989733/strip-automatic-p-tags-around-images-videos-iframes-in-wordpress-4-9/59946156#59946156\">over here</a>.</p>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239475", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52020/" ]
I'm attempting to order posts by meta data, which is working fine, but the posts without the meta are not shown. I've tried a couple of guides on Stack Exchange that come up with a quick Google, of which people say they work fine, but adding to my site, the code just does not want to show posts without the meta data. What I'm trying to achieve is essentially a sticky post, so when a user clicks "Pin Post", a piece of post meta data is stored as `"pin_".$user` (so it is unique on this post) with a value of `"1"`. I would like to show posts that have the value `"1"` at the top, subsequently ordered by date, after which all other posts without the meta data should be shown, in date order. I realise this code is incomplete, but here is what I have so far; ``` query_posts(array('post_type' => array('beauty', 'health', 'food'), 'author_in' => $follow, 'orderby' => 'meta_value_num', 'meta_key' => 'pin_'.$user, 'showposts' => -1, 'order' => 'DESC')); if ( have_posts() ) : while ( have_posts() ) : the_post(); ``` How would I adapt this to produce the desired result?
This should do it and also remove `<p>` tags from images that are linked. Why it removes it from only one `<script>` instance is hard to tell. Would have to see your website code to investigate further. ``` // Remove p tags from images, scripts, and iframes. function remove_some_ptags( $content ) { $content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); $content = preg_replace('/<p>\s*(<script.*>*.<\/script>)\s*<\/p>/iU', '\1', $content); $content = preg_replace('/<p>\s*(<iframe.*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); return $content; } add_filter( 'the_content', 'remove_some_ptags' ); ```
239,491
<p>I have website for local restaurant and for menu there are separate pages (ex: salads, soups etc). Right now the second restaurant was opened and it has a separate menu. </p> <p>What I want to do is to create some kind of switch - so user can select what restaurant he wants to see. And he can switch deserts page of restaurant A and restaurant B. How it should be done?</p>
[ { "answer_id": 239499, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": 2, "selected": false, "text": "<p>If you do this with pages, you will either have to make two pages, or you can put it in the same page and only show the content of restaurant B when you click a button or link (for instance). This can be done with jQuery, for example. In the latter case you will have the same URL for the page. </p>\n\n<p>There are many ways to go at this. You could also make parent pages \"Restaurant A\" and \"Restaurant B\" and have different sets of child pages with the same name. That way you will have a URL like:</p>\n\n<pre><code> /restaurant-a/salads\n</code></pre>\n\n<p>and</p>\n\n<pre><code> /restaurant-b/salads\n</code></pre>\n" }, { "answer_id": 239500, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>There are many ways to achieve this, ranging from simple to complicated. A simple one may suffice in your case. Simply generate three different menus in the backend and display them depending on the page where you are:</p>\n\n<pre><code>if (is_home) wp_nav_menu (array('menu' =&gt; 'home'))\nelseif (is_page (array('menu-a,deserts-a'))) wp_nav_menu (array('menu' =&gt; 'restaurant-a'))\nelseif (is_page (array('menu-b,deserts-b'))) wp_nav_menu (array('menu' =&gt; 'restaurant-b'))\n</code></pre>\n\n<p>This should work perfectly on a site with just a few pages. If there are more pages you could get the array of pages by using <a href=\"https://codex.wordpress.org/Function_Reference/get_children\" rel=\"nofollow\"><code>get_children</code></a>.</p>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16650/" ]
I have website for local restaurant and for menu there are separate pages (ex: salads, soups etc). Right now the second restaurant was opened and it has a separate menu. What I want to do is to create some kind of switch - so user can select what restaurant he wants to see. And he can switch deserts page of restaurant A and restaurant B. How it should be done?
If you do this with pages, you will either have to make two pages, or you can put it in the same page and only show the content of restaurant B when you click a button or link (for instance). This can be done with jQuery, for example. In the latter case you will have the same URL for the page. There are many ways to go at this. You could also make parent pages "Restaurant A" and "Restaurant B" and have different sets of child pages with the same name. That way you will have a URL like: ``` /restaurant-a/salads ``` and ``` /restaurant-b/salads ```
239,501
<p>When I use:</p> <pre><code>define('WP_DEBUG', 1); </code></pre> <p>In my <code>wp-config.php</code>, it works fine, but I am hacking an old theme and I would like to suppress <em>deprecated</em> notices.</p> <p>My understanding is that adding this:</p> <pre><code>error_reporting( E_ERROR | E_NOTICE | E_PARSE ) </code></pre> <p>Should do the trick. I have added it to <code>wp-config.php</code> and to <code>header.php</code> in my theme. Unfortunately, it has no effect. Is this something set at server level? Also the following makes no difference as well:</p> <pre><code>ini_set('display_errors', 1); </code></pre> <p>As asked in the comments below here's a couple of the notices. I am using a hacked version of the Construct 2 theme, quite old now but it would not be safe to update it. I am trying to persuade the client to let me rewrite it, the site is fairly simple, but as he can't see anything wrong, it's not broken, he won't spend the money.</p> <blockquote> <p><strong>Deprecated</strong>: Assigning the return value of new by reference is deprecated in <code>/Volumes/Macintosh HD/Sites/MAMP (custodian)/wordpress/wp-content/themes/construct2/option-tree/ot-loader.php</code> on <em>line 369</em></p> <p><strong>Strict Standards</strong>: Declaration of <code>DropDown_Nav_Menu::start_lvl()</code> should be compatible with <code>Walker_Nav_Menu::start_lvl(&amp;$output, $depth = 0, $args = Array)</code> in <code>/Volumes/Macintosh HD/Sites/MAMP (custodian)/wordpress/wp-content/themes/construct2/dropdown-menus.php</code> on <em>line 192</em></p> </blockquote>
[ { "answer_id": 239517, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 3, "selected": false, "text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/74311/mmm\">mmm</a> stated:</p>\n\n<blockquote>\n <p><em>in which file appears the first notice?</em></p>\n</blockquote>\n\n<p>Wherever the notice is mentioning the location of this deprecated function (<code>path/to/some/file.php</code>), you would insert the following just below the <code>&lt;?php</code> tag which starts off the file:</p>\n\n<pre><code>error_reporting(0);\n</code></pre>\n\n<p>I've tried the above functions you mentioned and inserted them in my <code>wp-config.php</code> when I experience something similar, but they didn't work for me. This will turn off warning, deprecated, and everything else except the errors.</p>\n" }, { "answer_id": 398023, "author": "NRTRX", "author_id": 62948, "author_profile": "https://wordpress.stackexchange.com/users/62948", "pm_score": 3, "selected": false, "text": "<p>I was able to suppress notices in the log and displayed errors by using the error_reporting function in a must-use plugin, which is loaded early enough to catch most of the WP core code warnings. This is helpful for the warnings coming from core/plugin files that you shouldn't modify.</p>\n<p>I created a php file in the /wp-content/mu-plugins/ folder with this code:</p>\n<pre><code>&lt;?php \nerror_reporting(E_ALL &amp; ~E_WARNING &amp; ~E_DEPRECATED &amp; ~E_USER_DEPRECATED &amp; ~E_NOTICE);\n?&gt;\n</code></pre>\n" }, { "answer_id": 413264, "author": "John C", "author_id": 202094, "author_profile": "https://wordpress.stackexchange.com/users/202094", "pm_score": 2, "selected": false, "text": "<p>This is probably the most &quot;WordPress&quot; way to do it.</p>\n<p>The code MUST go in your wp-config file, after the WP_DEBUG (and any other) defines because this particular filter runs before any plugins are loaded.</p>\n<pre><code>$GLOBALS['wp_filter'] = array(\n'enable_wp_debug_mode_checks' =&gt; array(\n 10 =&gt; array(\n array(\n 'accepted_args' =&gt; 0,\n 'function' =&gt; function () {\n if ( defined( 'WP_DEBUG' ) &amp;&amp; WP_DEBUG ) {\n // *** This is the key line - change to adjust to whatever logging state you want\n error_reporting( E_ALL &amp; ~E_DEPRECATED );\n\n ini_set( 'display_errors', defined( 'WP_DEBUG_DISPLAY' ) &amp;&amp; WP_DEBUG_DISPLAY ? 1 : 0 );\n\n if ( in_array( strtolower( (string) WP_DEBUG_LOG ), array( 'true', '1' ), true ) ) {\n $log_path = WP_CONTENT_DIR . '/debug.log';\n } elseif ( is_string( WP_DEBUG_LOG ) ) {\n $log_path = WP_DEBUG_LOG;\n } else {\n $log_path = false;\n }\n\n if ( $log_path ) {\n ini_set( 'log_errors', 1 );\n ini_set( 'error_log', $log_path );\n }\n\n if (\n defined( 'XMLRPC_REQUEST' ) || defined( 'REST_REQUEST' ) || defined( 'MS_FILES_REQUEST' ) ||\n ( defined( 'WP_INSTALLING' ) &amp;&amp; WP_INSTALLING ) ||\n wp_doing_ajax() || wp_is_json_request() ) {\n ini_set( 'display_errors', 0 );\n }\n }\n\n return false;\n },\n ),\n ),\n));\n</code></pre>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239501", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57686/" ]
When I use: ``` define('WP_DEBUG', 1); ``` In my `wp-config.php`, it works fine, but I am hacking an old theme and I would like to suppress *deprecated* notices. My understanding is that adding this: ``` error_reporting( E_ERROR | E_NOTICE | E_PARSE ) ``` Should do the trick. I have added it to `wp-config.php` and to `header.php` in my theme. Unfortunately, it has no effect. Is this something set at server level? Also the following makes no difference as well: ``` ini_set('display_errors', 1); ``` As asked in the comments below here's a couple of the notices. I am using a hacked version of the Construct 2 theme, quite old now but it would not be safe to update it. I am trying to persuade the client to let me rewrite it, the site is fairly simple, but as he can't see anything wrong, it's not broken, he won't spend the money. > > **Deprecated**: Assigning the return value of new by reference is deprecated in `/Volumes/Macintosh HD/Sites/MAMP (custodian)/wordpress/wp-content/themes/construct2/option-tree/ot-loader.php` on *line 369* > > > **Strict Standards**: Declaration of `DropDown_Nav_Menu::start_lvl()` should be compatible with `Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array)` in `/Volumes/Macintosh HD/Sites/MAMP (custodian)/wordpress/wp-content/themes/construct2/dropdown-menus.php` on *line 192* > > >
As [mmm](https://wordpress.stackexchange.com/users/74311/mmm) stated: > > *in which file appears the first notice?* > > > Wherever the notice is mentioning the location of this deprecated function (`path/to/some/file.php`), you would insert the following just below the `<?php` tag which starts off the file: ``` error_reporting(0); ``` I've tried the above functions you mentioned and inserted them in my `wp-config.php` when I experience something similar, but they didn't work for me. This will turn off warning, deprecated, and everything else except the errors.
239,514
<p>I have my WP put under</p> <pre><code>/wp </code></pre> <p>and then my-blog (which is an category, with the slug name 'my-blog') is set to access from (via the plugin 'Top level category')</p> <pre><code>/my-blog/ </code></pre> <p>everything seems fine, except my date-archives goes directly under the root as</p> <pre><code>/2016/09/ </code></pre> <p>which is the default permalink. However, I would like those date-archives of above category permalinks as:</p> <pre><code>/my-blog/2016/09/ </code></pre> <p>Is it possible to change rewrite rules to work? Please help.</p>
[ { "answer_id": 239516, "author": "Jesper Nilsson", "author_id": 102950, "author_profile": "https://wordpress.stackexchange.com/users/102950", "pm_score": 2, "selected": true, "text": "<p>Thats posible by using Custom Structure of the permalinks like below:</p>\n\n<pre><code>/%category%/%year%/%monthnum%/%postname%/\n</code></pre>\n\n<p>You will also be able to get a monthly archive of the category by going to:</p>\n\n<pre><code>/%category%/%year%/%monthnum%/\n</code></pre>\n\n<p>like:</p>\n\n<pre><code>www.yoursite.com/my-blog/2016/09/\n</code></pre>\n" }, { "answer_id": 239518, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 0, "selected": false, "text": "<p>I'd look into <a href=\"https://wordpress.stackexchange.com/a/239516/98212\">Jesper's answer</a> first since it seems to be that permalink settings is not set up the way you want it to be.</p>\n\n<p>If you're still having issues, you can add the following to your <code>.htaccess</code> file in between the <code>&lt;IfModule mod_rewrite.c&gt;</code> tags:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST}\nRewriteRule ^([0-9]+)/(.*)$ /my-blog/$1/$2 [R=301,L]\n</code></pre>\n\n<p>This will add the <code>my-blog</code> slug if someone were to access <code>http://example.com/2016/09/</code>, etc. Your <code>.htaccess</code> should looks like the following:</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# Custom Rewrite\nRewriteCond %{HTTP_HOST}\nRewriteRule ^([0-9]+)/(.*)$ /my-blog/$1/$2 [R=301,L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239514", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102954/" ]
I have my WP put under ``` /wp ``` and then my-blog (which is an category, with the slug name 'my-blog') is set to access from (via the plugin 'Top level category') ``` /my-blog/ ``` everything seems fine, except my date-archives goes directly under the root as ``` /2016/09/ ``` which is the default permalink. However, I would like those date-archives of above category permalinks as: ``` /my-blog/2016/09/ ``` Is it possible to change rewrite rules to work? Please help.
Thats posible by using Custom Structure of the permalinks like below: ``` /%category%/%year%/%monthnum%/%postname%/ ``` You will also be able to get a monthly archive of the category by going to: ``` /%category%/%year%/%monthnum%/ ``` like: ``` www.yoursite.com/my-blog/2016/09/ ```
239,520
<p>I am trying to insert content into a term's <code>description</code> field on save. </p> <pre><code>// insert stuff into description field of taxonomy function insert_taxonomy_content( $term_id, $tt_id, $taxonomy ){ // only insert content on certain taxonomies if ( $taxonomy === 'some_custom_taxonomy' ){ // unhook this function so it doesn't loop infinitely remove_action('edit_term', 'insert_taxonomy_content'); $content = "Some Content"; $update_args = array( 'description' =&gt; $content, ); // update the post, which calls save_post again wp_update_term( $term_id, $taxonomy, $update_args ); // re-hook this function add_action('edit_term', 'insert_taxonomy_content'); } } add_action('edit_term', 'insert_taxonomy_content', 10, 3); </code></pre> <p>The adding of the content works, but now I can't change the title of an existing term anymore. I also can't add a new term. </p> <p>I think this is pointing me in the right direction: <a href="https://wordpress.stackexchange.com/a/183852/10595">https://wordpress.stackexchange.com/a/183852/10595</a></p> <blockquote> <p>The array passed in gets merged with the data already in the DB.</p> </blockquote> <p>So how could I capture a new title and/or slug entered into the Name / Slug field to pass it on to <code>wp_update_term</code>? </p> <p>I also tried this as per <a href="https://wordpress.stackexchange.com/a/239521/10595">cjbj's suggestion</a>:</p> <pre><code>// insert stuff into description field of taxonomy function insert_taxonomy_content( $term_id, $taxonomy ){ // only insert content on certain taxonomies if ( $taxonomy === 'some_custom_taxonomy' ){ // unhook this function so it doesn't loop infinitely remove_action('edit_terms', 'insert_taxonomy_content'); $content = "Some Content"; $update_args = array( 'description' =&gt; $content, ); // update the post, which calls save_post again wp_update_term( $term_id, $taxonomy, $update_args ); // re-hook this function add_action('edit_terms', 'insert_taxonomy_content'); } } add_action('edit_terms', 'insert_taxonomy_content', 10, 2); </code></pre> <p>This lets me edit titles and slugs again, but now the <code>description</code> does not get updated.</p>
[ { "answer_id": 239521, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/edit_term/\" rel=\"nofollow\"><code>edit_term</code></a> hook fires \"<strong>after</strong> a term has been updated, but before the term cache has been cleaned\". So every time you update a term you fire a function that updates the term again, but only its description. I haven't tested this, but I could imagine that somewhere in this process WP looses the first update and thinks the second update is the only one that matters.</p>\n\n<p>Anyway, I suggest you try the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/edit_terms\" rel=\"nofollow\"><code>edit_terms</code></a> hook, which fires <strong>before</strong> the term is being updated. In that way, your update doesn't interrupt the regular update process.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>This may become a bit of a guessing game, but there are a couple more hooks in <a href=\"https://developer.wordpress.org/reference/functions/wp_update_term/\" rel=\"nofollow\"><code>wp_update_term</code></a> that you may try: <code>edited_terms</code>, <code>edit_term_taxonomy</code> and <code>edited_term_taxonomy</code>.</p>\n\n<p>The point remains, however, that you are calling <code>wp_update_term</code> halfway inside <code>wp_update_term</code>. That function manipulates the global variable <code>$wpdb</code>. So the database is first changed by the first part of the outer call, then by the inner call (your function) and then again by the second part of the outer call.</p>\n\n<p>Perhaps a better course of action would be to ditch the call to <code>wp_update_terms</code> in your function. Instead you could try to update the description immediately using <code>$wpdb-&gt;update</code>, so no other manipulation of the database takes place inside your hook function. I couldn't test this, but tracing how <code>wp_update_terms</code> handles the description it would be something like this:</p>\n\n<pre><code>$description = \"Some Content\";\n$wpdb-&gt;update( $wpdb-&gt;term_taxonomy, compact( 'description' ));\n</code></pre>\n" }, { "answer_id": 239602, "author": "Florian", "author_id": 10595, "author_profile": "https://wordpress.stackexchange.com/users/10595", "pm_score": 3, "selected": true, "text": "<p>So, thanks to cjbj I finally found the correct answer! I needed to use <a href=\"https://developer.wordpress.org/reference/hooks/edited_term/\" rel=\"nofollow\"><code>edited_term</code></a> instead of <code>edit_term</code>. Very subtle difference. <code>edited_term</code> fires after a term has been saved. </p>\n\n<pre><code>// insert stuff into description field of taxonomy\nfunction insert_taxonomy_content( $term_id, $tt_id, $taxonomy ){\n // only insert content on certain taxonomies\n if ( $taxonomy === 'some_custom_taxonomy' ){\n\n // unhook this function so it doesn't loop infinitely\n remove_action('edited_term', 'insert_taxonomy_content');\n\n $content = \"Some Content\";\n $update_args = array(\n 'description' =&gt; $content,\n );\n\n // update the post, which calls save_post again\n wp_update_term( $term_id, $taxonomy, $update_args );\n\n // re-hook this function\n add_action('edited_term', 'insert_taxonomy_content');\n }\n }\nadd_action('edited_term', 'insert_taxonomy_content', 10, 3);\n</code></pre>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10595/" ]
I am trying to insert content into a term's `description` field on save. ``` // insert stuff into description field of taxonomy function insert_taxonomy_content( $term_id, $tt_id, $taxonomy ){ // only insert content on certain taxonomies if ( $taxonomy === 'some_custom_taxonomy' ){ // unhook this function so it doesn't loop infinitely remove_action('edit_term', 'insert_taxonomy_content'); $content = "Some Content"; $update_args = array( 'description' => $content, ); // update the post, which calls save_post again wp_update_term( $term_id, $taxonomy, $update_args ); // re-hook this function add_action('edit_term', 'insert_taxonomy_content'); } } add_action('edit_term', 'insert_taxonomy_content', 10, 3); ``` The adding of the content works, but now I can't change the title of an existing term anymore. I also can't add a new term. I think this is pointing me in the right direction: <https://wordpress.stackexchange.com/a/183852/10595> > > The array passed in gets merged with the data already in the DB. > > > So how could I capture a new title and/or slug entered into the Name / Slug field to pass it on to `wp_update_term`? I also tried this as per [cjbj's suggestion](https://wordpress.stackexchange.com/a/239521/10595): ``` // insert stuff into description field of taxonomy function insert_taxonomy_content( $term_id, $taxonomy ){ // only insert content on certain taxonomies if ( $taxonomy === 'some_custom_taxonomy' ){ // unhook this function so it doesn't loop infinitely remove_action('edit_terms', 'insert_taxonomy_content'); $content = "Some Content"; $update_args = array( 'description' => $content, ); // update the post, which calls save_post again wp_update_term( $term_id, $taxonomy, $update_args ); // re-hook this function add_action('edit_terms', 'insert_taxonomy_content'); } } add_action('edit_terms', 'insert_taxonomy_content', 10, 2); ``` This lets me edit titles and slugs again, but now the `description` does not get updated.
So, thanks to cjbj I finally found the correct answer! I needed to use [`edited_term`](https://developer.wordpress.org/reference/hooks/edited_term/) instead of `edit_term`. Very subtle difference. `edited_term` fires after a term has been saved. ``` // insert stuff into description field of taxonomy function insert_taxonomy_content( $term_id, $tt_id, $taxonomy ){ // only insert content on certain taxonomies if ( $taxonomy === 'some_custom_taxonomy' ){ // unhook this function so it doesn't loop infinitely remove_action('edited_term', 'insert_taxonomy_content'); $content = "Some Content"; $update_args = array( 'description' => $content, ); // update the post, which calls save_post again wp_update_term( $term_id, $taxonomy, $update_args ); // re-hook this function add_action('edited_term', 'insert_taxonomy_content'); } } add_action('edited_term', 'insert_taxonomy_content', 10, 3); ```
239,528
<p>I'm currently listing WordPress pages and child pages on a side widget using the following code. </p> <pre><code>&lt;ul class="side-links"&gt; &lt;?php wp_list_pages( array( 'title_li' =&gt; '' ) ); ?&gt; &lt;/ul&gt; </code></pre> <p>This lists all of my WordPress pages, if I add the following code</p> <p><code>'child_of' =&gt; $id</code> </p> <p>into the array I get the children on the parent page, If I go to a specific child page the list will not be displayed. I just need the list of child pages to be displayed on all pages including parent and child pages.</p> <p>If it helps I've placed the following <code>wp_list_pages</code> function on this page in the following theme. <a href="https://github.com/holger1411/understrap/blob/master/loop-templates/content-page.php" rel="nofollow">https://github.com/holger1411/understrap/blob/master/loop-templates/content-page.php</a></p>
[ { "answer_id": 239521, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/edit_term/\" rel=\"nofollow\"><code>edit_term</code></a> hook fires \"<strong>after</strong> a term has been updated, but before the term cache has been cleaned\". So every time you update a term you fire a function that updates the term again, but only its description. I haven't tested this, but I could imagine that somewhere in this process WP looses the first update and thinks the second update is the only one that matters.</p>\n\n<p>Anyway, I suggest you try the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/edit_terms\" rel=\"nofollow\"><code>edit_terms</code></a> hook, which fires <strong>before</strong> the term is being updated. In that way, your update doesn't interrupt the regular update process.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>This may become a bit of a guessing game, but there are a couple more hooks in <a href=\"https://developer.wordpress.org/reference/functions/wp_update_term/\" rel=\"nofollow\"><code>wp_update_term</code></a> that you may try: <code>edited_terms</code>, <code>edit_term_taxonomy</code> and <code>edited_term_taxonomy</code>.</p>\n\n<p>The point remains, however, that you are calling <code>wp_update_term</code> halfway inside <code>wp_update_term</code>. That function manipulates the global variable <code>$wpdb</code>. So the database is first changed by the first part of the outer call, then by the inner call (your function) and then again by the second part of the outer call.</p>\n\n<p>Perhaps a better course of action would be to ditch the call to <code>wp_update_terms</code> in your function. Instead you could try to update the description immediately using <code>$wpdb-&gt;update</code>, so no other manipulation of the database takes place inside your hook function. I couldn't test this, but tracing how <code>wp_update_terms</code> handles the description it would be something like this:</p>\n\n<pre><code>$description = \"Some Content\";\n$wpdb-&gt;update( $wpdb-&gt;term_taxonomy, compact( 'description' ));\n</code></pre>\n" }, { "answer_id": 239602, "author": "Florian", "author_id": 10595, "author_profile": "https://wordpress.stackexchange.com/users/10595", "pm_score": 3, "selected": true, "text": "<p>So, thanks to cjbj I finally found the correct answer! I needed to use <a href=\"https://developer.wordpress.org/reference/hooks/edited_term/\" rel=\"nofollow\"><code>edited_term</code></a> instead of <code>edit_term</code>. Very subtle difference. <code>edited_term</code> fires after a term has been saved. </p>\n\n<pre><code>// insert stuff into description field of taxonomy\nfunction insert_taxonomy_content( $term_id, $tt_id, $taxonomy ){\n // only insert content on certain taxonomies\n if ( $taxonomy === 'some_custom_taxonomy' ){\n\n // unhook this function so it doesn't loop infinitely\n remove_action('edited_term', 'insert_taxonomy_content');\n\n $content = \"Some Content\";\n $update_args = array(\n 'description' =&gt; $content,\n );\n\n // update the post, which calls save_post again\n wp_update_term( $term_id, $taxonomy, $update_args );\n\n // re-hook this function\n add_action('edited_term', 'insert_taxonomy_content');\n }\n }\nadd_action('edited_term', 'insert_taxonomy_content', 10, 3);\n</code></pre>\n" } ]
2016/09/16
[ "https://wordpress.stackexchange.com/questions/239528", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33866/" ]
I'm currently listing WordPress pages and child pages on a side widget using the following code. ``` <ul class="side-links"> <?php wp_list_pages( array( 'title_li' => '' ) ); ?> </ul> ``` This lists all of my WordPress pages, if I add the following code `'child_of' => $id` into the array I get the children on the parent page, If I go to a specific child page the list will not be displayed. I just need the list of child pages to be displayed on all pages including parent and child pages. If it helps I've placed the following `wp_list_pages` function on this page in the following theme. <https://github.com/holger1411/understrap/blob/master/loop-templates/content-page.php>
So, thanks to cjbj I finally found the correct answer! I needed to use [`edited_term`](https://developer.wordpress.org/reference/hooks/edited_term/) instead of `edit_term`. Very subtle difference. `edited_term` fires after a term has been saved. ``` // insert stuff into description field of taxonomy function insert_taxonomy_content( $term_id, $tt_id, $taxonomy ){ // only insert content on certain taxonomies if ( $taxonomy === 'some_custom_taxonomy' ){ // unhook this function so it doesn't loop infinitely remove_action('edited_term', 'insert_taxonomy_content'); $content = "Some Content"; $update_args = array( 'description' => $content, ); // update the post, which calls save_post again wp_update_term( $term_id, $taxonomy, $update_args ); // re-hook this function add_action('edited_term', 'insert_taxonomy_content'); } } add_action('edited_term', 'insert_taxonomy_content', 10, 3); ```
239,549
<p>I want your help as I am new in Ajax and Wordpress. This is a simple plugin and I want to know what I am doing wrong and getting "zero" result</p> <blockquote> <p>ajax.php</p> </blockquote> <pre><code> add_shortcode( 'ajax_shortcode', 'ajax_shortcode_function' ); function ajax_shortcode_function() { wp_enqueue_script('jquery'); wp_register_script ('ajax_script', plugins_url( '/ajax.js', __FILE__ ), plugins_url( '/ajax.js', __FILE__ ), array('jquery')); wp_enqueue_script ( 'ajax_script' ); wp_localize_script ( 'ajax_script', 'ajax', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ))); function my_submit_process() { global $wpdb; $text1 = $_POST['text1']; $text2 = $_POST['text2']; echo $text1 + $text2; wp_die(); echo 'sfdasdfsdfsdfas'; echo $text1 + $text2; } add_action('wp_ajax_submit_process', 'my_submit_process'); add_action('wp_ajax_nopriv_submit_process', 'my_submit_process'); ?&gt; &lt;input type="text" id="text1"&gt; + &lt;input type="text" id="text2"&gt; &lt;button id="button"&gt; = &lt;/button&gt; &lt;div id="result"&gt;&lt;/div&gt; &lt;?php } </code></pre> <blockquote> <p>ajax.js</p> </blockquote> <pre><code>jQuery(document).ready(function($){ $('#button').click(function(e) { var val1 = $('#text1').val(); var val2 = $('#text2').val(); $.ajax({ type: 'POST', url: ajax.ajax_url, data: { action: 'submit_process', text1: val1, text2: val2 }, success: function(response) { $('#result').html(response); } }); return false; }); }); </code></pre>
[ { "answer_id": 239550, "author": "Nick P.", "author_id": 57671, "author_profile": "https://wordpress.stackexchange.com/users/57671", "pm_score": 0, "selected": false, "text": "<p>I just saw that in <code>wp_register_script</code> i have </p>\n\n<pre><code>plugins_url( '/ajax.js', __FILE__ )\n</code></pre>\n\n<p>twice. I removed it and I get the <code>0</code> result again</p>\n" }, { "answer_id": 239847, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>It looks odd to me that your <code>ajax_shortcode_function()</code> registers and enqueues your ajax script. According to the <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">codex</a>, you should register/enqueue in functions.php. Additionally, if you only need the url to ajax-admin.php, the tutorial says you can use the global <code>ajaxurl</code> variable and therefore you don't need to localize your script.</p>\n\n<p>The other thing that looks odd is <code>my_submit_process()</code> seems to be located <em>within</em> <code>ajax_shortcode_function()</code>. I'd check that the closing brace is in the correct location and try again if it isn't.</p>\n" }, { "answer_id": 239874, "author": "sdexp", "author_id": 102830, "author_profile": "https://wordpress.stackexchange.com/users/102830", "pm_score": 1, "selected": false, "text": "<p>I see you are using wp_die(). I would put a die() at the end of the method instead of a wp_die() in the middle like that. I don't know if it would make a difference.</p>\n" } ]
2016/09/17
[ "https://wordpress.stackexchange.com/questions/239549", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57671/" ]
I want your help as I am new in Ajax and Wordpress. This is a simple plugin and I want to know what I am doing wrong and getting "zero" result > > ajax.php > > > ``` add_shortcode( 'ajax_shortcode', 'ajax_shortcode_function' ); function ajax_shortcode_function() { wp_enqueue_script('jquery'); wp_register_script ('ajax_script', plugins_url( '/ajax.js', __FILE__ ), plugins_url( '/ajax.js', __FILE__ ), array('jquery')); wp_enqueue_script ( 'ajax_script' ); wp_localize_script ( 'ajax_script', 'ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ))); function my_submit_process() { global $wpdb; $text1 = $_POST['text1']; $text2 = $_POST['text2']; echo $text1 + $text2; wp_die(); echo 'sfdasdfsdfsdfas'; echo $text1 + $text2; } add_action('wp_ajax_submit_process', 'my_submit_process'); add_action('wp_ajax_nopriv_submit_process', 'my_submit_process'); ?> <input type="text" id="text1"> + <input type="text" id="text2"> <button id="button"> = </button> <div id="result"></div> <?php } ``` > > ajax.js > > > ``` jQuery(document).ready(function($){ $('#button').click(function(e) { var val1 = $('#text1').val(); var val2 = $('#text2').val(); $.ajax({ type: 'POST', url: ajax.ajax_url, data: { action: 'submit_process', text1: val1, text2: val2 }, success: function(response) { $('#result').html(response); } }); return false; }); }); ```
It looks odd to me that your `ajax_shortcode_function()` registers and enqueues your ajax script. According to the [codex](https://codex.wordpress.org/AJAX_in_Plugins), you should register/enqueue in functions.php. Additionally, if you only need the url to ajax-admin.php, the tutorial says you can use the global `ajaxurl` variable and therefore you don't need to localize your script. The other thing that looks odd is `my_submit_process()` seems to be located *within* `ajax_shortcode_function()`. I'd check that the closing brace is in the correct location and try again if it isn't.
239,584
<p>What is the difference between following two codes? (Directly call a function and call a function using add_action)</p> <pre><code>function pp_submit__link_form(){ if(isset( $_POST['action']) &amp;&amp; $_POST['action']="submit_link" ){ echo "Hello"; } } add_action( 'init', 'pp_submit__link_form' ); </code></pre> <hr> <pre><code>function pp_submit__link_form(){ if(isset( $_POST['pp_action']) &amp;&amp; $_POST['pp_action']="submit_link" ){ echo "Hello"; } } pp_submit__link_form(); </code></pre>
[ { "answer_id": 239560, "author": "Por", "author_id": 31832, "author_profile": "https://wordpress.stackexchange.com/users/31832", "pm_score": 0, "selected": false, "text": "<p>For clients website, after you have setup everything, you could upload to your hosting or client's one. But, if you put on client, that would be good if you and the clients have trust relationship.</p>\n\n<ul>\n<li>Make sure when you move local to live server not to be broken. Firstly, create a subdomain to show your clients or you could even install in subfolder.When everything is ready, move it to clients server without breaking. It is your potential.</li>\n<li>How much you should charge is depending on your time consuming. But, not first time should be flexible. not too much lower and not too much higher. Some clients give the project price 1/4 or 1/3. As soon as you get first payment, you have to hit the project and show the project demo to be able to check how the project is going from the client side. And then, take second or third payment like that.</li>\n<li>Use project management software like <a href=\"http://trello.com\" rel=\"nofollow\">trello</a>. So, both you could work well on it without missing anything.</li>\n<li>Take at least 1 days to check your project before, it is online.</li>\n</ul>\n\n<p>Frankly to say, there are some other tips and tricks that need to know. So, read a little bit online. Have a good luck with your clients.</p>\n" }, { "answer_id": 239561, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": false, "text": "<p>Congrats on your first client. I'm glad you are looking around to make sure that you start off on the right foot. Like anything that you start in life, your experience will increase over time and the more you practice.</p>\n\n<p>However, we live in a digital age and popular open-source platforms such as WordPress have great tutorials and communities to answer just about every question.</p>\n\n<p>These are some good, but also heavy questions, I want to keep them brief and too the point with you:</p>\n\n<blockquote>\n <p><em>I've heard that the best way to set up a WordPress site for a client is to set up the site in its own sub-folder on my own hosting. Then, once everything is approved and good to go copy the client's files and database files and transfer them to the client's hosting server. I've never done anything like this before. How do I do this properly?</em></p>\n</blockquote>\n\n<p>Workflows vary depending on how big or small your organization is. For individuals, your resources may be limited and they are simple; corporations would usually have a bigger team of poeple with assigned roles and protocols to follow.</p>\n\n<p>Since you, the developer, have been contracted to rebuild a new website for your clients. It's definitely an ideal way to build the new WordPress site on your own hosting (<code>example.com/client/name</code>) to have full control and hide your client's new website from being.</p>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-create-staging-environment-for-a-wordpress-site/\" rel=\"nofollow\">Check out this helpful guide</a> and also look at our <a href=\"/questions/tagged/migration\" class=\"post-tag\" title=\"show questions tagged &#39;migration&#39;\" rel=\"tag\">migration</a> related Q&amp;A which people have already posted some step-by-step guides.</p>\n\n<blockquote>\n <p>How do you guys normally charge for this type of job? By the hour? A certain amount per job?</p>\n</blockquote>\n\n<p>This will vary per developer because there are a lot of variable to factor in and each scenario is unique. Start off by determining your worth based on your level of experience in web development, the average pricing around your area, and your overall work ethic.</p>\n\n<p>Start at a comfortable price, then work your way up as you become more experienced over time.</p>\n\n<blockquote>\n <p>Any tips for making sure my first ever WordPress client project goes smoothly?</p>\n</blockquote>\n\n<p>While everyone wants every web project to <em>go smoothly</em>, you're guaranteed to run to some issues from time to time. It's part of the learning experience. However, it's more important to be able to fix those issues to improve your skills.</p>\n\n<p>I can guarantee you will run into common issues, but when you learn how to rectify them, you'll know how to prevent them in the future.</p>\n" }, { "answer_id": 239566, "author": "Nabil Kadimi", "author_id": 17187, "author_profile": "https://wordpress.stackexchange.com/users/17187", "pm_score": 0, "selected": false, "text": "<h2>Setup</h2>\n\n<p>Something easy and convenient for you to start:</p>\n\n<ul>\n<li>Buy a cheap domain name like acme.gdn (client is Acme Inc.)</li>\n<li>And a month or two on some cheap but rather good hosting with Cpanel and Fantastico installer</li>\n<li>Install wordpress on it using Fantastico</li>\n<li>Install plugin <a href=\"https://wordpress.org/plugins/backwpup/\" rel=\"nofollow\">BackWPup</a></li>\n<li>Setup automatic daily or semi-daily backup with Dropbox as a destination </li>\n<li>Work on the website ... Do your stuff ... Review until approved </li>\n<li>Remove you backup jobs or replace theme with client credentials</li>\n<li>Install <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">Duplicator</a> and use it to do the migration to the client server, I won't go through the process as it's easy and well documented</li>\n</ul>\n\n<h2>How much to charge</h2>\n\n<p>As much as you are worth, more or less, do not race to the bottom.</p>\n\n<h2>Tips</h2>\n\n<ul>\n<li>Don't overdo it or you'll end up working on the project for ages</li>\n<li>Impress the client with some nice suggestions</li>\n<li>and some freebies that won't take much time</li>\n<li>Make sure site is fast</li>\n<li>Ask a friend with more experience to review the website </li>\n</ul>\n" } ]
2016/09/17
[ "https://wordpress.stackexchange.com/questions/239584", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102125/" ]
What is the difference between following two codes? (Directly call a function and call a function using add\_action) ``` function pp_submit__link_form(){ if(isset( $_POST['action']) && $_POST['action']="submit_link" ){ echo "Hello"; } } add_action( 'init', 'pp_submit__link_form' ); ``` --- ``` function pp_submit__link_form(){ if(isset( $_POST['pp_action']) && $_POST['pp_action']="submit_link" ){ echo "Hello"; } } pp_submit__link_form(); ```
Congrats on your first client. I'm glad you are looking around to make sure that you start off on the right foot. Like anything that you start in life, your experience will increase over time and the more you practice. However, we live in a digital age and popular open-source platforms such as WordPress have great tutorials and communities to answer just about every question. These are some good, but also heavy questions, I want to keep them brief and too the point with you: > > *I've heard that the best way to set up a WordPress site for a client is to set up the site in its own sub-folder on my own hosting. Then, once everything is approved and good to go copy the client's files and database files and transfer them to the client's hosting server. I've never done anything like this before. How do I do this properly?* > > > Workflows vary depending on how big or small your organization is. For individuals, your resources may be limited and they are simple; corporations would usually have a bigger team of poeple with assigned roles and protocols to follow. Since you, the developer, have been contracted to rebuild a new website for your clients. It's definitely an ideal way to build the new WordPress site on your own hosting (`example.com/client/name`) to have full control and hide your client's new website from being. [Check out this helpful guide](http://www.wpbeginner.com/wp-tutorials/how-to-create-staging-environment-for-a-wordpress-site/) and also look at our [migration](/questions/tagged/migration "show questions tagged 'migration'") related Q&A which people have already posted some step-by-step guides. > > How do you guys normally charge for this type of job? By the hour? A certain amount per job? > > > This will vary per developer because there are a lot of variable to factor in and each scenario is unique. Start off by determining your worth based on your level of experience in web development, the average pricing around your area, and your overall work ethic. Start at a comfortable price, then work your way up as you become more experienced over time. > > Any tips for making sure my first ever WordPress client project goes smoothly? > > > While everyone wants every web project to *go smoothly*, you're guaranteed to run to some issues from time to time. It's part of the learning experience. However, it's more important to be able to fix those issues to improve your skills. I can guarantee you will run into common issues, but when you learn how to rectify them, you'll know how to prevent them in the future.
239,608
<p>I'm trying to add a custom menu structure for my WordPress theme. This is how I want it to look:</p> <pre><code>&lt;li&gt; &lt;a href="link_to_parent_item" class="main-category" tabindex="3"&gt;Parent Name&lt;/a&gt; &lt;div class="sub-menu"&gt; &lt;div class="sub-links pull-left"&gt; &lt;a href="link_to_child_item"&gt;Child Name1&lt;/a&gt; &lt;a href="link_to_child_item"&gt;Child Name2&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p>I've written a custom walker to do this, but it is not giving me what I really want. Here's my walker class:</p> <pre><code>class loggmax_class_walker extends Walker_Nav_Menu{ // Start level, beginning tags function start_lvl(&amp;$output, $depth) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= "\n$indent"; $output .= '&lt;div class="sub-menu"&gt;'; $output .= '&lt;div class="sub-links pull-left"&gt;'; } function end_lvl(&amp;$output, $depth) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= "$indent&lt;/div&gt;"; $output .= '&lt;/div&gt;'; } // Start element (beginning list items) function start_el( &amp;$output, $item, $depth=0, $args=array(),$current_object_id=0 ) { $this-&gt;curItem = $item; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $classes[] = 'menu-item-' . $item-&gt;ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $atts = array(); $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : ''; $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : ''; $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : ''; $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : ''; $atts['slug'] = ! empty( $item-&gt;slug ) ? $item-&gt;slug : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; $item_output = ''; foreach ( $atts as $attr =&gt; $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } // Check if it is a submenu if ( $depth == 1 ) { $output .= '&lt;a'. $attributes. ' &gt;'; $output .= apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ); $output .= '&lt;/a&gt;'; } elseif ( $depth == 0 ) { $item_output .= '&lt;li&gt;'; $item_output .= '&lt;a'. $attributes. ' class="main-category"&gt;'; $item_output .= apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ); $item_output .= '&lt;/a&gt;'; } $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } </code></pre> <p>and this code is in my header.php</p> <pre><code>if ( has_nav_menu( 'primary-menu' ) ) wp_nav_menu( array( 'theme_location' =&gt; 'primary-menu', 'container' =&gt; 'ul', 'menu_class' =&gt; 'pull-left', 'items_wrap' =&gt; '&lt;ul id="%1$s" class="%2$s"&gt;%3$s&lt;/ul&gt;', 'walker' =&gt; new loggmax_class_walker() ) ); </code></pre> <p>and this is what is being displayed:</p> <pre><code>&lt;li&gt; &lt;a href="link_here" class="main-category"&gt;Parent Title&lt;/a&gt; &lt;div class="sub-menu"&gt; &lt;div class="sub-links pull-left"&gt; &lt;a href="link_here"&gt;Child Title&lt;/a&gt;&lt;/li&gt; &lt;a href="link_here"&gt;Child Title 2&lt;/a&gt;&lt;/li&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p>How do I remove the ending list tag <code>&lt;/li&gt;</code> that is being printed in the sub-menu items?</p>
[ { "answer_id": 239618, "author": "EBennett", "author_id": 91050, "author_profile": "https://wordpress.stackexchange.com/users/91050", "pm_score": 1, "selected": false, "text": "<p>It appears the</p>\n\n<pre><code>&lt;li&gt;&lt;/li&gt;\n</code></pre>\n\n<p>in the end_lvl function and also within $item_output as well. Although I have no experience with writing walker code, I have previously used a Bootstrap walker, so these might not be of any use to you. Perhaps taking a look through the following links might help?</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/Walker</a></li>\n<li><a href=\"https://github.com/twittem/wp-bootstrap-navwalker\" rel=\"nofollow\">https://github.com/twittem/wp-bootstrap-navwalker</a></li>\n</ul>\n" }, { "answer_id": 312029, "author": "Valentin Born", "author_id": 131050, "author_profile": "https://wordpress.stackexchange.com/users/131050", "pm_score": 2, "selected": false, "text": "<p>Old question, but you can override the <code>&lt;/li&gt;</code> in the Walker's <code>end_el()</code> function (see wp-includes/class-walker-nav-menu.php); in your case, something like:</p>\n\n<pre><code>public function end_el( &amp;$output, $item, $depth = 0, $args = array() ) {\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $n = '';\n } else {\n $n = \"\\n\";\n }\n if ( $depth == 0 ) {\n $output .= \"&lt;/li&gt;{$n}\";\n } else {\n $output .= \"{$n}\";\n }\n}\n</code></pre>\n" } ]
2016/09/17
[ "https://wordpress.stackexchange.com/questions/239608", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84265/" ]
I'm trying to add a custom menu structure for my WordPress theme. This is how I want it to look: ``` <li> <a href="link_to_parent_item" class="main-category" tabindex="3">Parent Name</a> <div class="sub-menu"> <div class="sub-links pull-left"> <a href="link_to_child_item">Child Name1</a> <a href="link_to_child_item">Child Name2</a> </div> </div> </li> ``` I've written a custom walker to do this, but it is not giving me what I really want. Here's my walker class: ``` class loggmax_class_walker extends Walker_Nav_Menu{ // Start level, beginning tags function start_lvl(&$output, $depth) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= "\n$indent"; $output .= '<div class="sub-menu">'; $output .= '<div class="sub-links pull-left">'; } function end_lvl(&$output, $depth) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= "$indent</div>"; $output .= '</div>'; } // Start element (beginning list items) function start_el( &$output, $item, $depth=0, $args=array(),$current_object_id=0 ) { $this->curItem = $item; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts['slug'] = ! empty( $item->slug ) ? $item->slug : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; $item_output = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } // Check if it is a submenu if ( $depth == 1 ) { $output .= '<a'. $attributes. ' >'; $output .= apply_filters( 'the_title', $item->title, $item->ID ); $output .= '</a>'; } elseif ( $depth == 0 ) { $item_output .= '<li>'; $item_output .= '<a'. $attributes. ' class="main-category">'; $item_output .= apply_filters( 'the_title', $item->title, $item->ID ); $item_output .= '</a>'; } $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ``` and this code is in my header.php ``` if ( has_nav_menu( 'primary-menu' ) ) wp_nav_menu( array( 'theme_location' => 'primary-menu', 'container' => 'ul', 'menu_class' => 'pull-left', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'walker' => new loggmax_class_walker() ) ); ``` and this is what is being displayed: ``` <li> <a href="link_here" class="main-category">Parent Title</a> <div class="sub-menu"> <div class="sub-links pull-left"> <a href="link_here">Child Title</a></li> <a href="link_here">Child Title 2</a></li> </div> </li> ``` How do I remove the ending list tag `</li>` that is being printed in the sub-menu items?
Old question, but you can override the `</li>` in the Walker's `end_el()` function (see wp-includes/class-walker-nav-menu.php); in your case, something like: ``` public function end_el( &$output, $item, $depth = 0, $args = array() ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $n = ''; } else { $n = "\n"; } if ( $depth == 0 ) { $output .= "</li>{$n}"; } else { $output .= "{$n}"; } } ```
239,650
<p>I'm new to WP, but have used other CMSs in the past.</p> <p>I wanted to make a simple Woo-commerce store, for practice. I installed WP, Woo-commerce and the Woo-commerce Store Front theme and all went fine.</p> <p>Now I want to start customising the theme. First thing I wanted to change was put a new logo in the header. I opened header.php in the Storefront theme directory and found the div that encompasses where the logo image should be but all I see is:</p> <p><code>do_action( 'storefront_header' );</code></p> <p>I've dug around in the directory but can't find any storefront_header files or functions.</p> <p>So, what am I meant to do here? Is there any guides or map to find each individual elements function or PHP file?</p> <p>How do I find, within the template structure, the elements I want to work on?</p>
[ { "answer_id": 239652, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Looking at the current version of Storefront's <code>header.php</code>:</p>\n\n<pre><code>/**\n * Functions hooked into storefront_header action\n *\n * @hooked storefront_skip_links - 0\n * @hooked storefront_social_icons - 10\n * @hooked storefront_site_branding - 20\n * @hooked storefront_secondary_navigation - 30\n * @hooked storefront_product_search - 40\n * @hooked storefront_primary_navigation_wrapper - 42\n * @hooked storefront_primary_navigation - 50\n * @hooked storefront_header_cart - 60\n * @hooked storefront_primary_navigation_wrapper_close - 68\n */\ndo_action( 'storefront_header' ); ?&gt;\n</code></pre>\n\n<p>That comment block outlines all of the callback functions (with priorities) hooked to the <code>storefront_header</code> action.</p>\n\n<p>If you do a search for text within the files of the <code>storefront</code> directory for the string <code>'storefront_header'</code>, you can find these functions. There is no standard way of organizing where these functions appear, but you would be able to track them down manually starting at <code>functions.php</code> and following all of the code from there. Searching is more efficient though.</p>\n\n<p><code>storefront_site_branding</code> is the function that handles how the logo is displayed. It's located in <code>storefront/inc/storefront-template-functions.php</code>.</p>\n" }, { "answer_id": 239653, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p><code>do_action</code> is not directly related to the template hierarchy, it is basically a trigger for observers that want to observe when the specific action is triggered. </p>\n\n<p>Best way to find out the observers is to do a code search for the name of the action (storefront_header in this case). In this case it is limited to the theme files but if you work on a theme that \"requires\" plugins you will probably want to search the plugin's code as well.</p>\n\n<p>A frequent gotcha (especially in core code) is action which are dynamically created by combining strings, so in case a search for storefront_header do not give results you might want to try search for the prefix or suffix of the action</p>\n" }, { "answer_id": 362873, "author": "Jon", "author_id": 14416, "author_profile": "https://wordpress.stackexchange.com/users/14416", "pm_score": 0, "selected": false, "text": "<p>Look in these 2 files:<br>\nwp-content\\themes\\MyTheme\\inc\\storefront-template-functions.php\nwp-content\\themes\\MyTheme\\inc\\woocommerce\\storefront-woocommerce-template-functions.php</p>\n\n<p>They have the functions that are hooked into <code>storefront_header.</code>\nThen search each hook individually. For example Search for <code>storefront_header_container</code> which is top of the commented out list. It finds this function:</p>\n\n<pre><code>if ( ! function_exists( 'storefront_header_container' ) ) {\n/**\n * The header container\n */\nfunction storefront_header_container() {\n echo '&lt;div class=\"col-full\"&gt;';\n}\n}\n</code></pre>\n\n<p>All that function does is basically add the HTML <code>&lt;div class=\"col-full\"&gt;</code></p>\n\n<p>So you can replace replicate unhook and work with as you wish</p>\n" }, { "answer_id": 379159, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 0, "selected": false, "text": "<p>Once you know where you want to hook on, then use the add_action for storefront_header and position (60 in my case)</p>\n<p><strong>functions.php</strong> inside your child theme:</p>\n<pre><code>&lt;?php\nadd_action( 'storefront_header', function() {\necho '&lt;div class=&quot;my-account&quot;&gt;MY ACCOUNT&lt;/div&gt;';\n}, 60 );\n</code></pre>\n<p>After this you can style with CSS whatever you need</p>\n" } ]
2016/09/18
[ "https://wordpress.stackexchange.com/questions/239650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44964/" ]
I'm new to WP, but have used other CMSs in the past. I wanted to make a simple Woo-commerce store, for practice. I installed WP, Woo-commerce and the Woo-commerce Store Front theme and all went fine. Now I want to start customising the theme. First thing I wanted to change was put a new logo in the header. I opened header.php in the Storefront theme directory and found the div that encompasses where the logo image should be but all I see is: `do_action( 'storefront_header' );` I've dug around in the directory but can't find any storefront\_header files or functions. So, what am I meant to do here? Is there any guides or map to find each individual elements function or PHP file? How do I find, within the template structure, the elements I want to work on?
Looking at the current version of Storefront's `header.php`: ``` /** * Functions hooked into storefront_header action * * @hooked storefront_skip_links - 0 * @hooked storefront_social_icons - 10 * @hooked storefront_site_branding - 20 * @hooked storefront_secondary_navigation - 30 * @hooked storefront_product_search - 40 * @hooked storefront_primary_navigation_wrapper - 42 * @hooked storefront_primary_navigation - 50 * @hooked storefront_header_cart - 60 * @hooked storefront_primary_navigation_wrapper_close - 68 */ do_action( 'storefront_header' ); ?> ``` That comment block outlines all of the callback functions (with priorities) hooked to the `storefront_header` action. If you do a search for text within the files of the `storefront` directory for the string `'storefront_header'`, you can find these functions. There is no standard way of organizing where these functions appear, but you would be able to track them down manually starting at `functions.php` and following all of the code from there. Searching is more efficient though. `storefront_site_branding` is the function that handles how the logo is displayed. It's located in `storefront/inc/storefront-template-functions.php`.
239,663
<p>I have a WordPress site that uses the WPRO (WordPress Read Only) plugin to host all media files on Amazon S3. I've changed the thumbnail and image sizes in my custom theme, and uploading new images to the media library uses the new sizes. However, when I try to regenerate all thumbnails using "Regenerate Thumbnails," it doesn't work, often complaining that the original cannot be found. </p> <p>How can I force the regenerate thumbnails plugin to use the original image on S3 to recreate the thumbnails for existing images?</p>
[ { "answer_id": 239652, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Looking at the current version of Storefront's <code>header.php</code>:</p>\n\n<pre><code>/**\n * Functions hooked into storefront_header action\n *\n * @hooked storefront_skip_links - 0\n * @hooked storefront_social_icons - 10\n * @hooked storefront_site_branding - 20\n * @hooked storefront_secondary_navigation - 30\n * @hooked storefront_product_search - 40\n * @hooked storefront_primary_navigation_wrapper - 42\n * @hooked storefront_primary_navigation - 50\n * @hooked storefront_header_cart - 60\n * @hooked storefront_primary_navigation_wrapper_close - 68\n */\ndo_action( 'storefront_header' ); ?&gt;\n</code></pre>\n\n<p>That comment block outlines all of the callback functions (with priorities) hooked to the <code>storefront_header</code> action.</p>\n\n<p>If you do a search for text within the files of the <code>storefront</code> directory for the string <code>'storefront_header'</code>, you can find these functions. There is no standard way of organizing where these functions appear, but you would be able to track them down manually starting at <code>functions.php</code> and following all of the code from there. Searching is more efficient though.</p>\n\n<p><code>storefront_site_branding</code> is the function that handles how the logo is displayed. It's located in <code>storefront/inc/storefront-template-functions.php</code>.</p>\n" }, { "answer_id": 239653, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p><code>do_action</code> is not directly related to the template hierarchy, it is basically a trigger for observers that want to observe when the specific action is triggered. </p>\n\n<p>Best way to find out the observers is to do a code search for the name of the action (storefront_header in this case). In this case it is limited to the theme files but if you work on a theme that \"requires\" plugins you will probably want to search the plugin's code as well.</p>\n\n<p>A frequent gotcha (especially in core code) is action which are dynamically created by combining strings, so in case a search for storefront_header do not give results you might want to try search for the prefix or suffix of the action</p>\n" }, { "answer_id": 362873, "author": "Jon", "author_id": 14416, "author_profile": "https://wordpress.stackexchange.com/users/14416", "pm_score": 0, "selected": false, "text": "<p>Look in these 2 files:<br>\nwp-content\\themes\\MyTheme\\inc\\storefront-template-functions.php\nwp-content\\themes\\MyTheme\\inc\\woocommerce\\storefront-woocommerce-template-functions.php</p>\n\n<p>They have the functions that are hooked into <code>storefront_header.</code>\nThen search each hook individually. For example Search for <code>storefront_header_container</code> which is top of the commented out list. It finds this function:</p>\n\n<pre><code>if ( ! function_exists( 'storefront_header_container' ) ) {\n/**\n * The header container\n */\nfunction storefront_header_container() {\n echo '&lt;div class=\"col-full\"&gt;';\n}\n}\n</code></pre>\n\n<p>All that function does is basically add the HTML <code>&lt;div class=\"col-full\"&gt;</code></p>\n\n<p>So you can replace replicate unhook and work with as you wish</p>\n" }, { "answer_id": 379159, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 0, "selected": false, "text": "<p>Once you know where you want to hook on, then use the add_action for storefront_header and position (60 in my case)</p>\n<p><strong>functions.php</strong> inside your child theme:</p>\n<pre><code>&lt;?php\nadd_action( 'storefront_header', function() {\necho '&lt;div class=&quot;my-account&quot;&gt;MY ACCOUNT&lt;/div&gt;';\n}, 60 );\n</code></pre>\n<p>After this you can style with CSS whatever you need</p>\n" } ]
2016/09/18
[ "https://wordpress.stackexchange.com/questions/239663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99435/" ]
I have a WordPress site that uses the WPRO (WordPress Read Only) plugin to host all media files on Amazon S3. I've changed the thumbnail and image sizes in my custom theme, and uploading new images to the media library uses the new sizes. However, when I try to regenerate all thumbnails using "Regenerate Thumbnails," it doesn't work, often complaining that the original cannot be found. How can I force the regenerate thumbnails plugin to use the original image on S3 to recreate the thumbnails for existing images?
Looking at the current version of Storefront's `header.php`: ``` /** * Functions hooked into storefront_header action * * @hooked storefront_skip_links - 0 * @hooked storefront_social_icons - 10 * @hooked storefront_site_branding - 20 * @hooked storefront_secondary_navigation - 30 * @hooked storefront_product_search - 40 * @hooked storefront_primary_navigation_wrapper - 42 * @hooked storefront_primary_navigation - 50 * @hooked storefront_header_cart - 60 * @hooked storefront_primary_navigation_wrapper_close - 68 */ do_action( 'storefront_header' ); ?> ``` That comment block outlines all of the callback functions (with priorities) hooked to the `storefront_header` action. If you do a search for text within the files of the `storefront` directory for the string `'storefront_header'`, you can find these functions. There is no standard way of organizing where these functions appear, but you would be able to track them down manually starting at `functions.php` and following all of the code from there. Searching is more efficient though. `storefront_site_branding` is the function that handles how the logo is displayed. It's located in `storefront/inc/storefront-template-functions.php`.
239,684
<p>I've alreday done lots of R&amp;D on this question but not get a suitable answer any where. This is very little task for me if , I need to make a mysql query. But though , I' not good hand on experience in WP so getting much frustrated by the solution of question.</p> <p><strong>How to sort a wp_query by custom column that I added in wp_posts table.</strong></p> <pre><code> $args = array( /*'base' =&gt; '%_%', 'format' =&gt; '?paged=%#%', 'total' =&gt; 1, 'current' =&gt; 0, 'show_all' =&gt; false, 'end_size' =&gt; 1, 'mid_size' =&gt; 2, 'prev_next' =&gt; true, 'prev_text' =&gt; __('« Previous'), 'next_text' =&gt; __('Next »'), 'type' =&gt; 'plain', 'add_args' =&gt; false, 'add_fragment' =&gt; '', 'before_page_number' =&gt; '', 'after_page_number' =&gt; ''*/ 'posts_per_page' =&gt; 10, 'post_type' =&gt; array('food', 'buffets'), 'meta_key' =&gt; 'post_priority', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; 'ASC' ); </code></pre> <p>When I'm trying with this one actually order by wp_postmeta table <strong>wp_postmeta.meta_value+0</strong> Means instead of wp_post table it is ordering by postmeta table <strong>Post_priority is my custom column in wp_post table</strong></p> <p>Here is the result of the query that I got:</p> <pre><code>"SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( \n wp_postmeta.meta_key = 'post_priority'\n) AND wp_posts.post_type IN ('food', 'buffets') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 2 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 ASC LIMIT 0, 10","posts" </code></pre>
[ { "answer_id": 239689, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 0, "selected": false, "text": "<p>You told it to order by meta_value, so it's ordering by the meta value. There is no \"post_priority\" column in the wp-posts table, so it can't order by it. The allowed values for \"orderby\" are not unlimited, they are a fixed set.</p>\n\n<p>You can't modify core tables and expect the code to know about it. The whole reason for the postmeta table is to allow you to insert arbitrary metadata instead of modifying the tables to have columns that the code doesn't know about.</p>\n\n<p>Remove your extra column and store your data as postmeta instead. Set the meta_key to \"priority\" and meta_value to the priority value. Then your query will work.</p>\n" }, { "answer_id": 239693, "author": "LeMike", "author_id": 42974, "author_profile": "https://wordpress.stackexchange.com/users/42974", "pm_score": 1, "selected": false, "text": "<p>I've investigated a bit and your problem is the <code>WP_Query::parse_orderby()</code> function. Everything you like to use as an order is sanitized there which the user Otto liked to point out. Unfortunately it has no filter to hook in. And yes it is better to use some meta_fields if you can afford an expensive JOIN in every get_posts. If not keep in mind that there is the <code>menu_order</code> field can be used for that too as long as you are not dealing with <code>nav_menu_item</code> post types.</p>\n\n<p>Anyway I found two solutions for that and want to share them here. For more details read <a href=\"https://wp-includes.org/296/custom-wp_posts-column-sortable/\" rel=\"nofollow\">https://wp-includes.org/296/custom-wp_posts-column-sortable/</a></p>\n\n<h2>Extend WP_Query</h2>\n\n<p>The cleanest way is to write an own query class:</p>\n\n<pre><code>&lt;?php\n\nclass Enhanced_Post_Table_Query extends \\WP_Query {\n\n /**\n * Extend order clause with own columns.\n *\n * @param string $order_by\n *\n * @return bool|false|string\n */\n protected function parse_orderby( $order_by ) {\n $parent_orderby = parent::parse_orderby( $order_by );\n\n if ( $parent_orderby ) {\n // WordPress knew what to do =&gt; keep it like that\n return $parent_orderby;\n }\n\n // whitelist some fields we extended\n $additional_allowed = array(\n 'something',\n );\n\n if ( ! in_array( $order_by, $additional_allowed, true ) ) {\n // not allowed column =&gt; early exit here\n return false;\n }\n\n // Default: order by post field.\n global $wpdb;\n\n return $wpdb-&gt;posts . '.post_' . sanitize_key( $order_by );\n }\n}\n</code></pre>\n\n<p>Now you can run queries and sort with the custom field:</p>\n\n<pre><code>$get_posts = new Enhanced_Post_Table_Query;\n\n$get_posts-&gt;query(\n array(\n 'orderby' =&gt; 'something'\n )\n);\n</code></pre>\n\n<h2>Late filter to overwrite things</h2>\n\n<p>A bit dirty but it works. As there is no direct filter to do that you can choose a later one and manipulate the query (the later the dirty it is):</p>\n\n<pre><code>&lt;?php\n\n/**\n * Add custom wp_posts column for sorting.\n *\n * @param string $order_clause SQL-Clause for ordering.\n * @param WP_Query $query Query object.\n *\n * @return string Order clause like \"wp_posts.post_foo DESC\" or similar.\n */\nfunction custom_column_sort_filter( $order_clause, $query ) {\n\n // whitelist some fields we extended\n $additional_allowed = array(\n 'something',\n );\n\n if (\n ! in_array(\n $query-&gt;get('orderby'),\n $additional_allowed,\n true\n )\n ) {\n // unknown column =&gt; keep it as before\n return $order_clause;\n }\n\n global $wpdb;\n\n return $wpdb-&gt;posts\n . '.post_'\n . sanitize_key( $query-&gt;get('orderby') )\n . ' ' . $query-&gt;get( 'order' );\n\n}\n\nadd_filter( 'posts_orderby', 'custom_column_sort_filter', 10, 2 );\n</code></pre>\n\n<p>Now almost every call of get_posts is informed about your custom column:</p>\n\n<pre><code>get_posts(\n [\n 'orderby' =&gt; 'something',\n // IMPORTANT:\n 'suppress_filters' =&gt; false,\n ]\n);\n</code></pre>\n\n<p>But only if \"suppress_filters\" is set. This should be used by every plugin. There are more solutions via preg_replace but those are very late and replacing with REGEXP is always dirty and dangerous.</p>\n\n<p>I hope you can work with that!</p>\n" } ]
2016/09/18
[ "https://wordpress.stackexchange.com/questions/239684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103056/" ]
I've alreday done lots of R&D on this question but not get a suitable answer any where. This is very little task for me if , I need to make a mysql query. But though , I' not good hand on experience in WP so getting much frustrated by the solution of question. **How to sort a wp\_query by custom column that I added in wp\_posts table.** ``` $args = array( /*'base' => '%_%', 'format' => '?paged=%#%', 'total' => 1, 'current' => 0, 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => __('« Previous'), 'next_text' => __('Next »'), 'type' => 'plain', 'add_args' => false, 'add_fragment' => '', 'before_page_number' => '', 'after_page_number' => ''*/ 'posts_per_page' => 10, 'post_type' => array('food', 'buffets'), 'meta_key' => 'post_priority', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); ``` When I'm trying with this one actually order by wp\_postmeta table **wp\_postmeta.meta\_value+0** Means instead of wp\_post table it is ordering by postmeta table **Post\_priority is my custom column in wp\_post table** Here is the result of the query that I got: ``` "SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( \n wp_postmeta.meta_key = 'post_priority'\n) AND wp_posts.post_type IN ('food', 'buffets') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 2 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 ASC LIMIT 0, 10","posts" ```
I've investigated a bit and your problem is the `WP_Query::parse_orderby()` function. Everything you like to use as an order is sanitized there which the user Otto liked to point out. Unfortunately it has no filter to hook in. And yes it is better to use some meta\_fields if you can afford an expensive JOIN in every get\_posts. If not keep in mind that there is the `menu_order` field can be used for that too as long as you are not dealing with `nav_menu_item` post types. Anyway I found two solutions for that and want to share them here. For more details read <https://wp-includes.org/296/custom-wp_posts-column-sortable/> Extend WP\_Query ---------------- The cleanest way is to write an own query class: ``` <?php class Enhanced_Post_Table_Query extends \WP_Query { /** * Extend order clause with own columns. * * @param string $order_by * * @return bool|false|string */ protected function parse_orderby( $order_by ) { $parent_orderby = parent::parse_orderby( $order_by ); if ( $parent_orderby ) { // WordPress knew what to do => keep it like that return $parent_orderby; } // whitelist some fields we extended $additional_allowed = array( 'something', ); if ( ! in_array( $order_by, $additional_allowed, true ) ) { // not allowed column => early exit here return false; } // Default: order by post field. global $wpdb; return $wpdb->posts . '.post_' . sanitize_key( $order_by ); } } ``` Now you can run queries and sort with the custom field: ``` $get_posts = new Enhanced_Post_Table_Query; $get_posts->query( array( 'orderby' => 'something' ) ); ``` Late filter to overwrite things ------------------------------- A bit dirty but it works. As there is no direct filter to do that you can choose a later one and manipulate the query (the later the dirty it is): ``` <?php /** * Add custom wp_posts column for sorting. * * @param string $order_clause SQL-Clause for ordering. * @param WP_Query $query Query object. * * @return string Order clause like "wp_posts.post_foo DESC" or similar. */ function custom_column_sort_filter( $order_clause, $query ) { // whitelist some fields we extended $additional_allowed = array( 'something', ); if ( ! in_array( $query->get('orderby'), $additional_allowed, true ) ) { // unknown column => keep it as before return $order_clause; } global $wpdb; return $wpdb->posts . '.post_' . sanitize_key( $query->get('orderby') ) . ' ' . $query->get( 'order' ); } add_filter( 'posts_orderby', 'custom_column_sort_filter', 10, 2 ); ``` Now almost every call of get\_posts is informed about your custom column: ``` get_posts( [ 'orderby' => 'something', // IMPORTANT: 'suppress_filters' => false, ] ); ``` But only if "suppress\_filters" is set. This should be used by every plugin. There are more solutions via preg\_replace but those are very late and replacing with REGEXP is always dirty and dangerous. I hope you can work with that!
239,686
<p>I know this may be a duplicate however I haven't been able to make sense of previous questions.</p> <p>I have a checkbox on a settings page. Everything is okay on the first load of the page, if I check the box and save all is fine. If I then uncheck i get the following error:</p> <blockquote> <p><strong>Notice</strong>: Undefined index: <code>dat_checkbox_field_0</code> in <code>.../wp-content/plugins/divi-auto-testimonials/admin/dat-options.php</code> on <em>line 49</em> value='1'></p> </blockquote> <p>The function:</p> <pre><code>function dat_checkbox_field_0_render( ) { $options = get_option( 'dat_settings' ); ?&gt; &lt;input type='checkbox' name='dat_settings[dat_checkbox_field_0]' &lt;?php checked( $options['dat_checkbox_field_0'], 1 ); ?&gt; value='1'&gt; &lt;?php } </code></pre> <p>Line 49 is the input html.</p> <p>I also get the same error for this code:</p> <pre><code>$options = get_option( 'dat_settings' ); if( $options['dat_checkbox_field_0'] != '1' ) { include_once "admin/notification.php"; } </code></pre> <p>From what I understand I need to set the value as <code>null</code> I think but I am not entirely sure if that is correct and if so how.</p>
[ { "answer_id": 239688, "author": "Ben H", "author_id": 64567, "author_profile": "https://wordpress.stackexchange.com/users/64567", "pm_score": 3, "selected": true, "text": "<p>Managed to fix this by doing the following:</p>\n\n<pre><code>function dat_checkbox_field_0_render( ) { \n\n $options = get_option( 'dat_settings' );\n $a = $options;\nif (array_key_exists(\"dat_checkbox_field_0\",$a))\n { } else { \n $options['data_checkbox_field_0'] = false;\n }\n ?&gt;\n &lt;input type='checkbox' name='dat_settings[dat_checkbox_field_0]' &lt;?php checked( $options['dat_checkbox_field_0'], 1 ); ?&gt; value='1'&gt;\n &lt;?php\n\n}\n</code></pre>\n" }, { "answer_id": 239690, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 2, "selected": false, "text": "<pre><code>$options = get_option( 'dat_settings' );\n$options['dat_checkbox_field_0'] = empty( $options['dat_checkbox_field_0'] ) ? 0 : 1;\n</code></pre>\n\n<p>Basically, if the variable is \"empty\", meaning that it is not set, or that it is equal to false (zero qualifies), then it will be assigned the value of 0. If it's set to true or equivalent (one qualifies) then it will be assigned the value of 1.</p>\n\n<p>Alternatively, reverse the logic for the same result (for purists who like true to come first in ternary statements):</p>\n\n<pre><code>$options['dat_checkbox_field_0'] = !empty( $options['dat_checkbox_field_0'] ) ? 1 : 0;\n</code></pre>\n" }, { "answer_id": 380907, "author": "alev", "author_id": 68337, "author_profile": "https://wordpress.stackexchange.com/users/68337", "pm_score": 0, "selected": false, "text": "<p>A better approach to answer your question and fix the problem is to make the form actually send a zero value and make WordPress save that key with a zero value in the first place.</p>\n<p>I am only posting this here because I was searching with the wrong keywords and only found answers like the ones here that maninuplate the form output to work around the <code>Undefined index:</code> error. But these solutions will still remove the key from the options array. That can cause problems in other places.</p>\n<p>Adding another hidden <code>input</code> field will actually make the form save the zero value in the database like this:</p>\n<pre><code>&lt;form&gt;\n &lt;input type='hidden' value='0' name='selfdestruct'&gt;\n &lt;input type='checkbox' value='1' name='selfdestruct'&gt;\n&lt;/form&gt;\n</code></pre>\n<p>Make sure to place the hidden <code>input</code> above your regular one, with the value <code>'0'</code> and the same name as in the regular input field.</p>\n<p>That answer is from here: <a href=\"https://stackoverflow.com/a/1992745/4688612\">https://stackoverflow.com/a/1992745/4688612</a></p>\n<p>Please send all credit to that poster.</p>\n" } ]
2016/09/18
[ "https://wordpress.stackexchange.com/questions/239686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64567/" ]
I know this may be a duplicate however I haven't been able to make sense of previous questions. I have a checkbox on a settings page. Everything is okay on the first load of the page, if I check the box and save all is fine. If I then uncheck i get the following error: > > **Notice**: Undefined index: `dat_checkbox_field_0` in `.../wp-content/plugins/divi-auto-testimonials/admin/dat-options.php` on *line 49* > value='1'> > > > The function: ``` function dat_checkbox_field_0_render( ) { $options = get_option( 'dat_settings' ); ?> <input type='checkbox' name='dat_settings[dat_checkbox_field_0]' <?php checked( $options['dat_checkbox_field_0'], 1 ); ?> value='1'> <?php } ``` Line 49 is the input html. I also get the same error for this code: ``` $options = get_option( 'dat_settings' ); if( $options['dat_checkbox_field_0'] != '1' ) { include_once "admin/notification.php"; } ``` From what I understand I need to set the value as `null` I think but I am not entirely sure if that is correct and if so how.
Managed to fix this by doing the following: ``` function dat_checkbox_field_0_render( ) { $options = get_option( 'dat_settings' ); $a = $options; if (array_key_exists("dat_checkbox_field_0",$a)) { } else { $options['data_checkbox_field_0'] = false; } ?> <input type='checkbox' name='dat_settings[dat_checkbox_field_0]' <?php checked( $options['dat_checkbox_field_0'], 1 ); ?> value='1'> <?php } ```
239,744
<p>I don't really understand how I can use the new responsive images feature that WordPress provides in my themes.</p> <p>Example:</p> <p>In my theme, I add a header-image. I therefore use the custom-header-image from customizer OR the post-thumbnail:</p> <pre><code>&lt;figure id="header-image" class="uk-margin-remove"&gt; &lt;?php if ( ( is_single() || ! is_home() ) &amp;&amp; has_post_thumbnail() ) : ?&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;?php else: ?&gt; ??? &lt;?php endif; ?&gt; &lt;/figure&gt; </code></pre> <p>So in the first case, the output is this:</p> <pre><code>&lt;img src="http://xxx.dev/wp-content/uploads/x.jpg" srcset="http://xxx.dev/wp-content/uploads/x-300x70.jpg 300w, http://xxx.dev/wp-content/uploads/x-768x180.jpg 768w, http://xxx.dev/wp-content/uploads/x-1024x241.jpg 1024w" sizes="(max-width: 300px) 100vw, 300px" alt=""&gt; </code></pre> <p>which is perfectly fine. But If I want to display an image by attachment ID, no matter which function I use, I don't get the output I expect.</p> <p>Example:</p> <p>In the code above you see "???". In that place, I tried some things. For example this:</p> <pre><code>&lt;?php echo wp_get_attachment_image( get_custom_header()-&gt;attachment_id, 'full' ); ?&gt; </code></pre> <p>Which only results in one size (see sizes attribute):</p> <pre><code>&lt;img src="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg" class="attachment-full size-full" alt="Delft_IMG_6275" srcset="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w" sizes="(max-width: 1920px) 100vw, 1920px" height="451" width="1920"&gt; </code></pre> <p>So, what's the proper way of displaying images in the theme so that it outputs a similar result as <code>the_post_thumbnail()</code>?</p>
[ { "answer_id": 239751, "author": "Malisa", "author_id": 71627, "author_profile": "https://wordpress.stackexchange.com/users/71627", "pm_score": 0, "selected": false, "text": "<p>You could use an <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\" rel=\"nofollow noreferrer\">array</a> as size:</p>\n\n<pre><code>wp_get_attachment_image( get_custom_header()-&gt;attachment_id, array('700', '600'));\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>@downvoter say why you are downvoting. I agree I was in a way wrong, but you could have said \"Yes you can use an array to size the image, BUT, it will only default to the nearest size to a defined image size.</p>\n\n<p>Defined images are either set in the media section of SETTINGS->MEDIA in the backend admin, these will be \"thumbnail, \"medium' and \"full\" OR by custom use and you can use <code>add_image_size('name-you want-use', 340, 230, true);</code> in your functions file ETC...ETC..</p>\n" }, { "answer_id": 239925, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": true, "text": "<p>Following our exchange in the comments I've reread your question and have a pretty straightforward answer:</p>\n\n<p>It looks like it's working fine.</p>\n\n<p>You are worried about the <code>sizes</code> attribute in your second example, but it's the <code>srcset</code> attribute that you should look at and it <em>is</em> showing all of your image sizes:</p>\n\n<pre><code>&lt;img \n\nsrc=\"http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg\" \n\nclass=\"attachment-full size-full\" alt=\"Delft_IMG_6275\" \n\nsrcset=\"http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w,\nhttp://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w,\nhttp://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w,\nhttp://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w\"\n\nsizes=\"(max-width: 1920px) 100vw, 1920px\"\n\nheight=\"451\" width=\"1920\"&gt;\n</code></pre>\n\n<p>Your browser reads the attributes like this:</p>\n\n<p>1 - Look at the <code>sizes</code> attribute and find the first match for the current viewport width. In this case, if the viewport is anything up to <code>1920px</code> wide, then use the <code>100vw</code> value, converted to <code>px</code>, otherwise use <code>1920px</code>.</p>\n\n<p>2 - Look at the <code>srcset</code> attribute and choose an image that fits the value from (1). </p>\n\n<p>On a nice big screen with a full width window the browser chooses the <code>sizes</code> value of <code>1920px</code>. This points the browser to the image marked with <code>1920w</code> in the srcset attribute, with the URL of your full size image. </p>\n\n<p>On a portrait iPad, where the viewport is <code>768px</code> wide, the value obtained in (1) will be <code>100vw</code> which for this viewport is <code>768px</code>. Looking in the <code>srcset</code> for <code>768w</code> we get the URL to the <code>medium_large</code> image size (a new default size in WP4.4 which doesn't show in the admin interface).</p>\n\n<p>When there's no exact match for the viewport width, the browser should choose the next size up.</p>\n\n<p>Now, there are circumstances where you might want to supply a longer list of images which you can add using <code>add_image_size()</code> in your theme. WP will build a <code>srcset</code> attribute using all the images that match the aspect ratio of the image size you choose to display.</p>\n\n<p>There are also circumstances where you want a custom <code>sizes</code> attribute and you can filter the attribute for that, but as your question stands I don't think that's what you're after.</p>\n" }, { "answer_id": 239936, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>On the one hand, there is nothing you should do, on the other, wordpress do not actually create responsive images.</p>\n\n<p>Wordpress will create a <code>srcset</code> attributes whenever you use the image related APIs based on the registered image sizes, with all the images that match the aspect ratio. What you need to do is to have the relevant image sizes registered in order for wordpress to be able to generate the images, and use them in a <code>srcset</code>.</p>\n\n<p>In your \"failed\" example full images will never be responsive since wordpress will not generate images that are bigger then the original image (and in any case it is tricky to code an image generation for size that change from one image to another).</p>\n\n<p>What you need to do in your theme is to decided which sizes you want to support and define them first. for example if you want a 150x150 thumbnail to be served also to x2 retina then you will need to register both a 150x150 size and 300x300 size. If on mobile you allocate a 50x50 space for the thumbnail, then you will also need to register also a 50x50 and 100x100 (for retina) sizes, not sure this is wise in practice but that is the theory of it.</p>\n\n<p>Rant: Calling what wordpress core does a feature is an insult to intelligence. It is a sweetener to help you avoid doing many API call, but it does not help you with actually designing what size you actually need, and still keep it tedious to configure wordpress to use them.</p>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102493/" ]
I don't really understand how I can use the new responsive images feature that WordPress provides in my themes. Example: In my theme, I add a header-image. I therefore use the custom-header-image from customizer OR the post-thumbnail: ``` <figure id="header-image" class="uk-margin-remove"> <?php if ( ( is_single() || ! is_home() ) && has_post_thumbnail() ) : ?> <?php the_post_thumbnail(); ?> <?php else: ?> ??? <?php endif; ?> </figure> ``` So in the first case, the output is this: ``` <img src="http://xxx.dev/wp-content/uploads/x.jpg" srcset="http://xxx.dev/wp-content/uploads/x-300x70.jpg 300w, http://xxx.dev/wp-content/uploads/x-768x180.jpg 768w, http://xxx.dev/wp-content/uploads/x-1024x241.jpg 1024w" sizes="(max-width: 300px) 100vw, 300px" alt=""> ``` which is perfectly fine. But If I want to display an image by attachment ID, no matter which function I use, I don't get the output I expect. Example: In the code above you see "???". In that place, I tried some things. For example this: ``` <?php echo wp_get_attachment_image( get_custom_header()->attachment_id, 'full' ); ?> ``` Which only results in one size (see sizes attribute): ``` <img src="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg" class="attachment-full size-full" alt="Delft_IMG_6275" srcset="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w" sizes="(max-width: 1920px) 100vw, 1920px" height="451" width="1920"> ``` So, what's the proper way of displaying images in the theme so that it outputs a similar result as `the_post_thumbnail()`?
Following our exchange in the comments I've reread your question and have a pretty straightforward answer: It looks like it's working fine. You are worried about the `sizes` attribute in your second example, but it's the `srcset` attribute that you should look at and it *is* showing all of your image sizes: ``` <img src="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg" class="attachment-full size-full" alt="Delft_IMG_6275" srcset="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w" sizes="(max-width: 1920px) 100vw, 1920px" height="451" width="1920"> ``` Your browser reads the attributes like this: 1 - Look at the `sizes` attribute and find the first match for the current viewport width. In this case, if the viewport is anything up to `1920px` wide, then use the `100vw` value, converted to `px`, otherwise use `1920px`. 2 - Look at the `srcset` attribute and choose an image that fits the value from (1). On a nice big screen with a full width window the browser chooses the `sizes` value of `1920px`. This points the browser to the image marked with `1920w` in the srcset attribute, with the URL of your full size image. On a portrait iPad, where the viewport is `768px` wide, the value obtained in (1) will be `100vw` which for this viewport is `768px`. Looking in the `srcset` for `768w` we get the URL to the `medium_large` image size (a new default size in WP4.4 which doesn't show in the admin interface). When there's no exact match for the viewport width, the browser should choose the next size up. Now, there are circumstances where you might want to supply a longer list of images which you can add using `add_image_size()` in your theme. WP will build a `srcset` attribute using all the images that match the aspect ratio of the image size you choose to display. There are also circumstances where you want a custom `sizes` attribute and you can filter the attribute for that, but as your question stands I don't think that's what you're after.
239,748
<p>The URL I am hitting is:</p> <pre><code>home_url('18/profile') </code></pre> <p>I want URL to be executed as:</p> <pre><code>localhost/wordpress/seller?page=profile </code></pre> <p>18 is the page ID for seller page.</p> <p>Also, when I hit on above said URL multiple time then last part of URL appending continuously. </p> <pre><code>add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' ); add_filter( 'query_vars','my_insert_query_vars' ); add_action( 'wp_loaded','my_flush_rules' ); // flush_rules() if our rules are not yet included function my_flush_rules(){ $rules = get_option( 'rewrite_rules' ); if ( ! isset( $rules['(wordpress)/(\d*)$'] ) ) { global $wp_rewrite; $wp_rewrite-&gt;flush_rules(); } } // Adding a new rule function my_insert_rewrite_rules( $rules ) { $newrules = array(); $newrules['(wordpress)/(\d*)$'] = 'index.php?page_id=$matches[1]&amp;page=$matches[2]'; return $newrules + $rules; } // Adding the id var so that WP recognizes it function my_insert_query_vars( $vars ) { array_push($vars, 'page'); return $vars; } </code></pre>
[ { "answer_id": 239751, "author": "Malisa", "author_id": 71627, "author_profile": "https://wordpress.stackexchange.com/users/71627", "pm_score": 0, "selected": false, "text": "<p>You could use an <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\" rel=\"nofollow noreferrer\">array</a> as size:</p>\n\n<pre><code>wp_get_attachment_image( get_custom_header()-&gt;attachment_id, array('700', '600'));\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>@downvoter say why you are downvoting. I agree I was in a way wrong, but you could have said \"Yes you can use an array to size the image, BUT, it will only default to the nearest size to a defined image size.</p>\n\n<p>Defined images are either set in the media section of SETTINGS->MEDIA in the backend admin, these will be \"thumbnail, \"medium' and \"full\" OR by custom use and you can use <code>add_image_size('name-you want-use', 340, 230, true);</code> in your functions file ETC...ETC..</p>\n" }, { "answer_id": 239925, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": true, "text": "<p>Following our exchange in the comments I've reread your question and have a pretty straightforward answer:</p>\n\n<p>It looks like it's working fine.</p>\n\n<p>You are worried about the <code>sizes</code> attribute in your second example, but it's the <code>srcset</code> attribute that you should look at and it <em>is</em> showing all of your image sizes:</p>\n\n<pre><code>&lt;img \n\nsrc=\"http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg\" \n\nclass=\"attachment-full size-full\" alt=\"Delft_IMG_6275\" \n\nsrcset=\"http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w,\nhttp://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w,\nhttp://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w,\nhttp://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w\"\n\nsizes=\"(max-width: 1920px) 100vw, 1920px\"\n\nheight=\"451\" width=\"1920\"&gt;\n</code></pre>\n\n<p>Your browser reads the attributes like this:</p>\n\n<p>1 - Look at the <code>sizes</code> attribute and find the first match for the current viewport width. In this case, if the viewport is anything up to <code>1920px</code> wide, then use the <code>100vw</code> value, converted to <code>px</code>, otherwise use <code>1920px</code>.</p>\n\n<p>2 - Look at the <code>srcset</code> attribute and choose an image that fits the value from (1). </p>\n\n<p>On a nice big screen with a full width window the browser chooses the <code>sizes</code> value of <code>1920px</code>. This points the browser to the image marked with <code>1920w</code> in the srcset attribute, with the URL of your full size image. </p>\n\n<p>On a portrait iPad, where the viewport is <code>768px</code> wide, the value obtained in (1) will be <code>100vw</code> which for this viewport is <code>768px</code>. Looking in the <code>srcset</code> for <code>768w</code> we get the URL to the <code>medium_large</code> image size (a new default size in WP4.4 which doesn't show in the admin interface).</p>\n\n<p>When there's no exact match for the viewport width, the browser should choose the next size up.</p>\n\n<p>Now, there are circumstances where you might want to supply a longer list of images which you can add using <code>add_image_size()</code> in your theme. WP will build a <code>srcset</code> attribute using all the images that match the aspect ratio of the image size you choose to display.</p>\n\n<p>There are also circumstances where you want a custom <code>sizes</code> attribute and you can filter the attribute for that, but as your question stands I don't think that's what you're after.</p>\n" }, { "answer_id": 239936, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>On the one hand, there is nothing you should do, on the other, wordpress do not actually create responsive images.</p>\n\n<p>Wordpress will create a <code>srcset</code> attributes whenever you use the image related APIs based on the registered image sizes, with all the images that match the aspect ratio. What you need to do is to have the relevant image sizes registered in order for wordpress to be able to generate the images, and use them in a <code>srcset</code>.</p>\n\n<p>In your \"failed\" example full images will never be responsive since wordpress will not generate images that are bigger then the original image (and in any case it is tricky to code an image generation for size that change from one image to another).</p>\n\n<p>What you need to do in your theme is to decided which sizes you want to support and define them first. for example if you want a 150x150 thumbnail to be served also to x2 retina then you will need to register both a 150x150 size and 300x300 size. If on mobile you allocate a 50x50 space for the thumbnail, then you will also need to register also a 50x50 and 100x100 (for retina) sizes, not sure this is wise in practice but that is the theory of it.</p>\n\n<p>Rant: Calling what wordpress core does a feature is an insult to intelligence. It is a sweetener to help you avoid doing many API call, but it does not help you with actually designing what size you actually need, and still keep it tedious to configure wordpress to use them.</p>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239748", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103095/" ]
The URL I am hitting is: ``` home_url('18/profile') ``` I want URL to be executed as: ``` localhost/wordpress/seller?page=profile ``` 18 is the page ID for seller page. Also, when I hit on above said URL multiple time then last part of URL appending continuously. ``` add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' ); add_filter( 'query_vars','my_insert_query_vars' ); add_action( 'wp_loaded','my_flush_rules' ); // flush_rules() if our rules are not yet included function my_flush_rules(){ $rules = get_option( 'rewrite_rules' ); if ( ! isset( $rules['(wordpress)/(\d*)$'] ) ) { global $wp_rewrite; $wp_rewrite->flush_rules(); } } // Adding a new rule function my_insert_rewrite_rules( $rules ) { $newrules = array(); $newrules['(wordpress)/(\d*)$'] = 'index.php?page_id=$matches[1]&page=$matches[2]'; return $newrules + $rules; } // Adding the id var so that WP recognizes it function my_insert_query_vars( $vars ) { array_push($vars, 'page'); return $vars; } ```
Following our exchange in the comments I've reread your question and have a pretty straightforward answer: It looks like it's working fine. You are worried about the `sizes` attribute in your second example, but it's the `srcset` attribute that you should look at and it *is* showing all of your image sizes: ``` <img src="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg" class="attachment-full size-full" alt="Delft_IMG_6275" srcset="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w, http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w" sizes="(max-width: 1920px) 100vw, 1920px" height="451" width="1920"> ``` Your browser reads the attributes like this: 1 - Look at the `sizes` attribute and find the first match for the current viewport width. In this case, if the viewport is anything up to `1920px` wide, then use the `100vw` value, converted to `px`, otherwise use `1920px`. 2 - Look at the `srcset` attribute and choose an image that fits the value from (1). On a nice big screen with a full width window the browser chooses the `sizes` value of `1920px`. This points the browser to the image marked with `1920w` in the srcset attribute, with the URL of your full size image. On a portrait iPad, where the viewport is `768px` wide, the value obtained in (1) will be `100vw` which for this viewport is `768px`. Looking in the `srcset` for `768w` we get the URL to the `medium_large` image size (a new default size in WP4.4 which doesn't show in the admin interface). When there's no exact match for the viewport width, the browser should choose the next size up. Now, there are circumstances where you might want to supply a longer list of images which you can add using `add_image_size()` in your theme. WP will build a `srcset` attribute using all the images that match the aspect ratio of the image size you choose to display. There are also circumstances where you want a custom `sizes` attribute and you can filter the attribute for that, but as your question stands I don't think that's what you're after.
239,755
<p>In the <em>Settings</em> menu, I have the following menu items listed:</p> <pre><code>Settings -- General -- Writing -- Reading -- Discussion -- Media -- Permalinks -- Blogging </code></pre> <p>I'd like to the <em>Blogging</em> (<code>options-general.php?page=blogging</code>) reordered underneath <em>General</em> instead of being at the bottom. This was added with the <code>add_options_page()</code> function.</p> <p>From doing some research, this is what I've come up with:</p> <pre><code>add_filter( 'custom_menu_order', array( $this, 'submenu_order' ) ); function submenu_order( $menu_order ) { global $submenu; $order = array(); $order[] = $submenu['options-general.php'][10]; $order[] = $submenu['options-general.php'][41]; $submenu['options-general.php'] = $order; return $menu_order; } </code></pre> <p>This works, but it only shows <em>General</em> and <em>Blogging</em>, the rest are removed:</p> <pre><code>Settings -- General -- Blogging </code></pre> <p>Also, <code>$submenu['options-general.php'][41]</code> is currently index position <code>41</code> for me. Does this mean it will be the same index position for everyone else even if they have another plugin settings listed?</p>
[ { "answer_id": 239762, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>The result you get is not surprising, given that you're directly manipulating a global variable. You're replacing <code>$submenu</code> with only the items with keys 10 and 41. If you want to follow this method you would need to do this (assuming there's nothing at key 11):</p>\n\n<pre><code>$submenu['options-general.php'][11] = $submenu['options-general.php'][41];\nunset ($submenu['options-general.php'][41]);\n</code></pre>\n\n<p>However, note that you are not using the filter function in any way. Nothing happens to the <code>$menu_order</code> that you are passing through the filter. So, this cannot be a very clean solution.</p>\n\n<p>As you doubtlessly have seen, <a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"nofollow\"><code>add_submenu_page</code></a> simply adds a new submenu at the end of the array in the order the function is called. This line:</p>\n\n<pre><code>$submenu[$parent_slug][] = array ( $menu_title, $capability, $menu_slug, $page_title );\n</code></pre>\n\n<p>So if a new plugin would call <code>add_submenu_page</code> before you do, the key of 41 could easily be a different one. To prevent this you would have to loop through <code>$submenu</code> to find the correct key. Quick 'n dirty version:</p>\n\n<pre><code>for ( $i = 1; $i &lt;= 100; $i++ ) {\n if ( array_key_exists( $submenu['options-general.php'][$i] ) ) {\n if ( $submenu['options-general.php'][$i][2] == 'my-custom-slug' ) {\n $the_desired_key = $i;\n // [2] because that is the index of the slug in the submenu item array above\n }\n }\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Better version of the latter loop:</p>\n\n<pre><code>$sub = $submenu['options-general.php'];\nforeach ( $sub as $key =&gt; $details ) {\n if ( $details[2] == 'my-custom-slug' ) {\n $the_desired_key = $key;\n }\n }\n</code></pre>\n\n<p>After finding <code>$the_desired_key</code> in this way, you can safely use the set+unset method above. I've verified 11 is an unused offset.</p>\n" }, { "answer_id": 239806, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 4, "selected": true, "text": "<p>Got it, thanks to <a href=\"https://wordpress.stackexchange.com/users/75495/cjbj\">cjbj</a>'s help, I was able to get the final solution:</p>\n\n<pre><code>add_filter( 'custom_menu_order', 'submenu_order' );\nfunction submenu_order( $menu_order ) {\n # Get submenu key location based on slug\n global $submenu;\n $settings = $submenu['options-general.php'];\n foreach ( $settings as $key =&gt; $details ) {\n if ( $details[2] == 'blogging' ) {\n $index = $key;\n }\n }\n # Set the 'Blogging' menu below 'General'\n $submenu['options-general.php'][11] = $submenu['options-general.php'][$index];\n unset( $submenu['options-general.php'][$index] );\n # Reorder the menu based on the keys in ascending order\n ksort( $submenu['options-general.php'] );\n # Return the new submenu order\n return $menu_order;\n}\n</code></pre>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98212/" ]
In the *Settings* menu, I have the following menu items listed: ``` Settings -- General -- Writing -- Reading -- Discussion -- Media -- Permalinks -- Blogging ``` I'd like to the *Blogging* (`options-general.php?page=blogging`) reordered underneath *General* instead of being at the bottom. This was added with the `add_options_page()` function. From doing some research, this is what I've come up with: ``` add_filter( 'custom_menu_order', array( $this, 'submenu_order' ) ); function submenu_order( $menu_order ) { global $submenu; $order = array(); $order[] = $submenu['options-general.php'][10]; $order[] = $submenu['options-general.php'][41]; $submenu['options-general.php'] = $order; return $menu_order; } ``` This works, but it only shows *General* and *Blogging*, the rest are removed: ``` Settings -- General -- Blogging ``` Also, `$submenu['options-general.php'][41]` is currently index position `41` for me. Does this mean it will be the same index position for everyone else even if they have another plugin settings listed?
Got it, thanks to [cjbj](https://wordpress.stackexchange.com/users/75495/cjbj)'s help, I was able to get the final solution: ``` add_filter( 'custom_menu_order', 'submenu_order' ); function submenu_order( $menu_order ) { # Get submenu key location based on slug global $submenu; $settings = $submenu['options-general.php']; foreach ( $settings as $key => $details ) { if ( $details[2] == 'blogging' ) { $index = $key; } } # Set the 'Blogging' menu below 'General' $submenu['options-general.php'][11] = $submenu['options-general.php'][$index]; unset( $submenu['options-general.php'][$index] ); # Reorder the menu based on the keys in ascending order ksort( $submenu['options-general.php'] ); # Return the new submenu order return $menu_order; } ```
239,768
<p>Featured image is not displaying on wp-admin side. I have also selected 'featured image' option from <strong>Screen Options</strong>. While Selecting image from media it doesn't show selected image in the metabox. I have written the below code:</p> <pre><code>function twentytwelve_setup() { add_theme_support('post-thumbnails'); } add_action( 'after_setup_theme', 'twentytwelve_setup' ); </code></pre>
[ { "answer_id": 240355, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 0, "selected": false, "text": "<p>You can disable/comment these plugin/code one by one by which having <a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow\">remove_meta_box()</a> function. </p>\n\n<p><code>remove_meta_box</code> function is used to removes a meta box or any other element from a particular <a href=\"https://codex.wordpress.org/Writing_Posts\" rel=\"nofollow\">post edit</a> screen of a given <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow\">post type</a>. It can be also used to remove a widget from the <a href=\"https://codex.wordpress.org/Dashboard_Screen\" rel=\"nofollow\">dashboard screen</a>.</p>\n\n<p>Once you filter this things you get the cause point. Best of luck!</p>\n" }, { "answer_id": 317010, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 2, "selected": false, "text": "<p>Have you double checked if the featured-image section is enabled under the <code>Screen Options</code> tab?</p>\n\n<p><a href=\"https://i.stack.imgur.com/hQvWY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hQvWY.png\" alt=\"enter image description here\"></a></p>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239768", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103109/" ]
Featured image is not displaying on wp-admin side. I have also selected 'featured image' option from **Screen Options**. While Selecting image from media it doesn't show selected image in the metabox. I have written the below code: ``` function twentytwelve_setup() { add_theme_support('post-thumbnails'); } add_action( 'after_setup_theme', 'twentytwelve_setup' ); ```
Have you double checked if the featured-image section is enabled under the `Screen Options` tab? [![enter image description here](https://i.stack.imgur.com/hQvWY.png)](https://i.stack.imgur.com/hQvWY.png)
239,769
<p>I currently have this snippet: </p> <pre><code>$user = new WP_User(get_current_user_id()); echo $user-&gt;roles[1]; </code></pre> <p>and the output the slug of the bbPress forum role. (roles[0] would be the general WP role but I don't need that.) </p> <p>What I need is the role <strong>name</strong>, not the slug. So, the expected output should be something like "Keymaster", "Participant", "Spectator" etc.</p> <p>So, how do I get the Role Name of the current user?</p>
[ { "answer_id": 239773, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>I'm not sure if bbPress follows WordPress conventions, but WP has a global class called <a href=\"https://developer.wordpress.org/reference/classes/wp_roles/\" rel=\"noreferrer\"><code>$WP-roles</code></a> that holds the role information. So, starting from what you have, there is the role of the current user:</p>\n\n<pre><code>$current_role = $user-&gt;roles[1];\n</code></pre>\n\n<p>Next, retrieve a list of all roles:</p>\n\n<pre><code>$all_roles = $wp_roles-&gt;roles; \n</code></pre>\n\n<p>Then, loop through <code>$all_roles</code> and find the <code>$current_role\"</code>:</p>\n\n<pre><code>foreach ($all_roles as $role_key =&gt; $role_details) {\n if ($role_key == $current_role) $current_role_name = $role_details['name'];\n }\n</code></pre>\n\n<p>Now, <code>$current_role_name</code> should hold the display name you're looking for (I didn't check this code, however).</p>\n" }, { "answer_id": 336252, "author": "Razon Komar Pal", "author_id": 144761, "author_profile": "https://wordpress.stackexchange.com/users/144761", "pm_score": 0, "selected": false, "text": "<p>You can get current user role name(translatable name but not slug) by following function, you just need to pass current user role slug as a parameter:</p>\n\n<pre><code>function wp_get_current_user_translatable_role_name( $current_user_role_slug = '' ) {\n $role_name = '';\n\n if ( ! function_exists( 'get_editable_roles' ) ) {\n require_once ABSPATH . 'wp-admin/includes/user.php';\n }\n\n // Please note that translate_user_role doesn't work in the front-end currently.\n load_textdomain( 'default', WP_LANG_DIR . '/admin-' . get_locale() . '.mo' );\n\n $editable_roles = array_reverse( get_editable_roles() );\n\n foreach ( $editable_roles as $role =&gt; $details ) {\n $name = translate_user_role( $details['name'] );\n // preselect specified role\n if ( $current_user_role_slug == $role ) {\n $role_name = $name;\n }\n }\n\n echo $role_name ;\n}\n</code></pre>\n\n<p>Now, get current user role slug name by following code:</p>\n\n<pre><code>$user_meta = get_userdata(get_current_user_id());\n$current_user_role_slug = $user_meta-&gt;roles[0];\n</code></pre>\n\n<p>Use <code>wp_get_current_user_translatable_role_name( $current_user_role_slug );</code> function to get current user role name(translatable name but not slug).</p>\n\n<p>NOTE: User must have to login to view role name.</p>\n" }, { "answer_id": 336255, "author": "Jaber Molla", "author_id": 166672, "author_profile": "https://wordpress.stackexchange.com/users/166672", "pm_score": 0, "selected": false, "text": "<p>Here is the way to get it</p>\n\n<pre><code>function get_user_role($user_id) {\n global $wp_roles;\n\n $roles = array();\n $user = new WP_User( $user_id );\n if ( !empty( $user-&gt;roles ) &amp;&amp; is_array( $user-&gt;roles ) ) {\n foreach ( $user-&gt;roles as $role )\n $roles[] .= translate_user_role( $role );\n }\n return implode(', ',$roles);\n} \n//then call the function with userid param\necho get_user_role( 7 );\n</code></pre>\n" }, { "answer_id": 356192, "author": "Daniel Gross", "author_id": 180599, "author_profile": "https://wordpress.stackexchange.com/users/180599", "pm_score": 1, "selected": false, "text": "<p>Maybe they've already solved this issue. But, now I just wrote this and I decided to share it. </p>\n\n<pre><code>&lt;?php\n//Get role name by user ID\nif( !function_exists('get_user_role_name') ){\n function get_user_role_name($user_ID){\n global $wp_roles;\n\n $user_data = get_userdata($user_ID);\n $user_role_slug = $user_data-&gt;roles[0];\n return translate_user_role($wp_roles-&gt;roles[$user_role_slug]['name']);\n }\n}\n?&gt;\n\n&lt;?php echo get_user_role_name(User ID here);?&gt;\n</code></pre>\n" }, { "answer_id": 368660, "author": "Marten Timan", "author_id": 189715, "author_profile": "https://wordpress.stackexchange.com/users/189715", "pm_score": 2, "selected": false, "text": "<p>thnx for this code snippet! I'm running a Buddypress install (and custom theme) where it is possible to add multiple roles to one user. I adjusted your code a little bit for that to work:</p>\n\n<pre><code>&lt;?php\n//Get role name by user ID\nif( !function_exists('get_user_role_name') ){\n function get_user_role_name($user_ID){\n global $wp_roles;\n\n $user_data = get_userdata($user_ID);\n $user_role_slug = $user_data-&gt;roles;\n\n foreach($user_role_slug as $user_role){\n //count user role nrs\n $user_role_nr++;\n //add comma separation of there is more then one role \n if($user_role_nr &gt; 1) { $user_role_list .= \", \"; }\n //add role name \n $user_role_list .= translate_user_role($wp_roles-&gt;roles[$user_role]['name']);\n }\n\n //return user role list\n return $user_role_list;\n\n }\n}\n?&gt;\n</code></pre>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103112/" ]
I currently have this snippet: ``` $user = new WP_User(get_current_user_id()); echo $user->roles[1]; ``` and the output the slug of the bbPress forum role. (roles[0] would be the general WP role but I don't need that.) What I need is the role **name**, not the slug. So, the expected output should be something like "Keymaster", "Participant", "Spectator" etc. So, how do I get the Role Name of the current user?
I'm not sure if bbPress follows WordPress conventions, but WP has a global class called [`$WP-roles`](https://developer.wordpress.org/reference/classes/wp_roles/) that holds the role information. So, starting from what you have, there is the role of the current user: ``` $current_role = $user->roles[1]; ``` Next, retrieve a list of all roles: ``` $all_roles = $wp_roles->roles; ``` Then, loop through `$all_roles` and find the `$current_role"`: ``` foreach ($all_roles as $role_key => $role_details) { if ($role_key == $current_role) $current_role_name = $role_details['name']; } ``` Now, `$current_role_name` should hold the display name you're looking for (I didn't check this code, however).
239,777
<p>I'm writing a plugin that every time you:</p> <ul> <li>publish a post</li> <li>edit an already published one</li> <li>delete a published post</li> </ul> <p>it makes several queries to the database, gets certain post data (title, excerpt, category, id, url, etc) and exports the in JSON file. This one I'm using it on the front end to draw all the elements.</p> <p>I also have some custom metaboxes in the admin panel where you can add some custom meta data.</p> <p><strong>My problem now</strong></p> <p>Every time I'm creating a new post and <strong>publish it directly - without saving it first</strong> (otherwise the export works), the array in the JSON file containing the data from the custom meta data is empty. If I check though the database, through myPhpAdmin, the values are stored. The plugin for the custom meta data is hooked in the "save_post" action. The plugin for exporting to JSON is hooked in the "publish_post" action.</p> <p>I even have this functions in the plugin to find the action with the highest priority number and put mine after it.</p> <pre><code>function get_latest_priority( $filter ) { if ( empty ( $GLOBALS['wp_filter'][ $filter ] ) ){ return PHP_INT_MAX; } $priorities = array_keys( $GLOBALS['wp_filter'][ $filter ] ); $last = end( $priorities ); return $last+1; } function export_posts_in_json (){ function register_plugin (){ add_action( 'publish_post', 'export_posts_in_json', get_latest_priority( current_filter() ), 1); } add_action( 'publish_post', 'register_plugin', 0 ); </code></pre> <p>That is what the <code>var_dump( $GLOBALS['wp_filter'][ $filter ]);</code> where <code>$filter</code> is <code>current_filter()</code> prints out:</p> <pre><code>array(2) { [0]=&gt; array(1) { ["register_custom_save"]=&gt; array(2) { ["function"]=&gt; string(20) "register_custom_save" ["accepted_args"]=&gt; int(1) } } [5]=&gt; array(1) { ["_publish_post_hook"]=&gt; array(2) { ["function"]=&gt; string(18) "_publish_post_hook" ["accepted_args"]=&gt; int(1) } } } </code></pre> <p>So I'm putting 6 as priority.</p> <p>Why on earth it doesn't work? Were should I hook it to work? Is the problem in the custom meta data plugin or in the export one?</p> <p>If you need the whole plugin let me know, but I don't think is necessary since it works when the post is already saved in the database.</p> <p><strong>UPDATE</strong></p> <p>I've hooked the plugin at the 'save_post' with later priority and the export function runs only if the $post_status of the current post is 'publish'.</p> <pre><code>function check_status( $post ){ $p = get_post( $post ); $p_status = $p-&gt;post_status; if($p_status == 'publish'){ export_posts_in_json(); } } add_action( 'save_post', 'check_status', 20, 1 ); </code></pre> <p>This doesn't solves the problem though. I can't capture if the current post changes status from publish to draft. The <code>export_posts_in_json()</code> functions queries only published posts. So if I will be able to run it for the above case, I will manage to delete this post form the JSON file.</p>
[ { "answer_id": 239776, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 4, "selected": true, "text": "<p>Extending the above comment:</p>\n\n<p>Directly changing the files of the plugin or theme is not a good practice as once the plugin/theme is updated, you will loose the changes. Instead use child theme in case of themes and hook to required actions in case of plugins.</p>\n\n<p>In your case since you are only changing the script in plugin and they might have enqueued(they should be) with <code>wp_enqueue_script</code> hooked to <code>wp_enqueue_scripts</code>. You can dequeue that script using <code>wp_dequeue_script</code> all you have to do is findout the script handle from the original plugin. Then you need to enqueue the changed script.</p>\n" }, { "answer_id": 303995, "author": "zod", "author_id": 143945, "author_profile": "https://wordpress.stackexchange.com/users/143945", "pm_score": 2, "selected": false, "text": "<p>Same problem here, but \"wp_dequeue_script\" was not enough. I wanted to override the \"waypoints\" loaded by WPBakery plugin. Adding \"wp_deregister_script\" the code is working.</p>\n\n<pre><code>define( 'MY_CHILD_URI', get_stylesheet_directory_uri().'/' );\n\nadd_action('wp_enqueue_scripts', 'mytheme_scripts');\n\nfunction mytheme_scripts() {\n wp_dequeue_script( 'waypoints' );\n wp_deregister_script( 'waypoints' );\n wp_enqueue_script( 'waypoints', MY_CHILD_URI . 'assets/js/jquery.waypoints.min.js', array('jquery'), '', true );\n} \n</code></pre>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239777", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90258/" ]
I'm writing a plugin that every time you: * publish a post * edit an already published one * delete a published post it makes several queries to the database, gets certain post data (title, excerpt, category, id, url, etc) and exports the in JSON file. This one I'm using it on the front end to draw all the elements. I also have some custom metaboxes in the admin panel where you can add some custom meta data. **My problem now** Every time I'm creating a new post and **publish it directly - without saving it first** (otherwise the export works), the array in the JSON file containing the data from the custom meta data is empty. If I check though the database, through myPhpAdmin, the values are stored. The plugin for the custom meta data is hooked in the "save\_post" action. The plugin for exporting to JSON is hooked in the "publish\_post" action. I even have this functions in the plugin to find the action with the highest priority number and put mine after it. ``` function get_latest_priority( $filter ) { if ( empty ( $GLOBALS['wp_filter'][ $filter ] ) ){ return PHP_INT_MAX; } $priorities = array_keys( $GLOBALS['wp_filter'][ $filter ] ); $last = end( $priorities ); return $last+1; } function export_posts_in_json (){ function register_plugin (){ add_action( 'publish_post', 'export_posts_in_json', get_latest_priority( current_filter() ), 1); } add_action( 'publish_post', 'register_plugin', 0 ); ``` That is what the `var_dump( $GLOBALS['wp_filter'][ $filter ]);` where `$filter` is `current_filter()` prints out: ``` array(2) { [0]=> array(1) { ["register_custom_save"]=> array(2) { ["function"]=> string(20) "register_custom_save" ["accepted_args"]=> int(1) } } [5]=> array(1) { ["_publish_post_hook"]=> array(2) { ["function"]=> string(18) "_publish_post_hook" ["accepted_args"]=> int(1) } } } ``` So I'm putting 6 as priority. Why on earth it doesn't work? Were should I hook it to work? Is the problem in the custom meta data plugin or in the export one? If you need the whole plugin let me know, but I don't think is necessary since it works when the post is already saved in the database. **UPDATE** I've hooked the plugin at the 'save\_post' with later priority and the export function runs only if the $post\_status of the current post is 'publish'. ``` function check_status( $post ){ $p = get_post( $post ); $p_status = $p->post_status; if($p_status == 'publish'){ export_posts_in_json(); } } add_action( 'save_post', 'check_status', 20, 1 ); ``` This doesn't solves the problem though. I can't capture if the current post changes status from publish to draft. The `export_posts_in_json()` functions queries only published posts. So if I will be able to run it for the above case, I will manage to delete this post form the JSON file.
Extending the above comment: Directly changing the files of the plugin or theme is not a good practice as once the plugin/theme is updated, you will loose the changes. Instead use child theme in case of themes and hook to required actions in case of plugins. In your case since you are only changing the script in plugin and they might have enqueued(they should be) with `wp_enqueue_script` hooked to `wp_enqueue_scripts`. You can dequeue that script using `wp_dequeue_script` all you have to do is findout the script handle from the original plugin. Then you need to enqueue the changed script.
239,819
<p>Hey I am trying to come up with some logic for if a tag contains any posts</p> <p>I found the below code for a category </p> <pre><code>&lt;?php if (get_category('17')-&gt;category_count &gt; 0) { ?&gt; &lt;?php } ?&gt; </code></pre> <p>I have tried modifying it with <code>get_tag</code> in place of <code>get_category</code> which did not work. I thought this could be because <code>category_count</code> can't be used with the tag taxonomy but I couldn't find any tag equivalent in the codex</p> <p>Thank you</p>
[ { "answer_id": 239823, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 2, "selected": true, "text": "<p>You can use:</p>\n\n<pre><code>&lt;?php if (get_tag('17')-&gt;count &gt; 0) { ?&gt;\n\n&lt;?php } ?&gt;\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_tag/\" rel=\"nofollow\"><code>get_tag</code></a> is basically a <a href=\"https://developer.wordpress.org/reference/functions/get_term/\" rel=\"nofollow\"><code>get_term</code></a> with taxonomy <code>post_tag</code> and <code>get_term</code> returns <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow\"><code>WP_Term</code></a> object on success, <code>WP_Error</code> on error.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow\"><code>WP_Term</code></a> has property <code>$count</code> which has object count for the term in process.</p>\n" }, { "answer_id": 239832, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>Here's another approach using the <code>get_term_field()</code>:</p>\n\n<pre><code>$count = get_term_field( 'count', 17, 'post_tag' );\n\nif( is_int( $count ) &amp;&amp; $count &gt; 0 )\n{\n // tag contains posts\n} \n</code></pre>\n\n<p>where we check if the output is an integer greater than zero.</p>\n\n<p>We could then create a custom wrapper:</p>\n\n<pre><code>/**\n * Check if a term has any posts assigned to it\n *\n * @param int|WP_Term|object $term\n * @param string $taxonomy \n * @return bool \n */\nfunction wpse_term_has_posts( $term, $taxonomy )\n{\n $count = get_term_field( 'count', $term, $taxonomy );\n return is_int( $count ) &amp;&amp; $count &gt; 0; \n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>if( wpse_term_has_posts( 17, 'post_tag' ) )\n{\n // do stuff\n}\n</code></pre>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239819", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51830/" ]
Hey I am trying to come up with some logic for if a tag contains any posts I found the below code for a category ``` <?php if (get_category('17')->category_count > 0) { ?> <?php } ?> ``` I have tried modifying it with `get_tag` in place of `get_category` which did not work. I thought this could be because `category_count` can't be used with the tag taxonomy but I couldn't find any tag equivalent in the codex Thank you
You can use: ``` <?php if (get_tag('17')->count > 0) { ?> <?php } ?> ``` [`get_tag`](https://developer.wordpress.org/reference/functions/get_tag/) is basically a [`get_term`](https://developer.wordpress.org/reference/functions/get_term/) with taxonomy `post_tag` and `get_term` returns [`WP_Term`](https://developer.wordpress.org/reference/classes/wp_term/) object on success, `WP_Error` on error. [`WP_Term`](https://developer.wordpress.org/reference/classes/wp_term/) has property `$count` which has object count for the term in process.
239,846
<p>I have this code, but it shows the total number of posts published by post type 'code'.</p> <pre><code>&lt;?php $count_posts = wp_count_posts('code')-&gt;publish; echo $count_posts; ?&gt; </code></pre> <p>I have 2 post types: 'code' and 'shop'.<br> Post type code is "a child" for post type 'shop'.<br> Therefore I need to show the post count for the "child" post type 'code' for those attached to the "parrent" post type 'shop'.</p> <p>UPDATE - SOLUTION (if any others are facing same problem) :</p> <pre><code>&lt;?php $result = $wpdb-&gt;get_results( $wpdb-&gt;prepare( "SELECT COUNT(*) AS code_num FROM {$wpdb-&gt;prefix}postmeta AS postmeta LEFT JOIN {$wpdb-&gt;prefix}postmeta AS postmeta1 ON postmeta.post_id = postmeta1.post_id WHERE postmeta1.meta_key = 'code_expire' AND postmeta1.meta_value &gt; %d AND postmeta.meta_key = 'code_shop_id' AND postmeta.meta_value = %s", current_time('timestamp'), $post-&gt;ID ) ); $result = array_shift( $result ); echo ' &lt;li class="list-group-item"&gt; &lt;span class="badge"&gt;'.$result-&gt;code_num.'&lt;/span&gt; &lt;a href="'.esc_url( get_permalink( $post-&gt;ID ) ).'"&gt; '.$post-&gt;post_title.' &lt;/a&gt; &lt;/li&gt;'; ?&gt; </code></pre> <p>Big thanks to Ahmed!</p>
[ { "answer_id": 239848, "author": "RyanCameron.Me", "author_id": 100537, "author_profile": "https://wordpress.stackexchange.com/users/100537", "pm_score": 0, "selected": false, "text": "<pre><code>$count = 0; \n$loop = new WP_Query( array('post_type' =&gt; 'code') );\n\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n $count = $count + 1;\nendwhile;\n\necho $count;\n</code></pre>\n" }, { "answer_id": 239850, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 2, "selected": true, "text": "<p>If you prefer the $wpdb direct queries you can use something like this:</p>\n\n<pre><code>global $wpdb; \n$count = $wpdb-&gt;get_var( \"SELECT COUNT(ID) FROM {$wpdb-&gt;posts} WHERE post_type = 'code' and post_status = 'publish'\" );\necho $count;\n</code></pre>\n\n<p>In the sql query above change the <code>post_type</code> to whatever you like. This will return count of published posts under specific post type only.</p>\n\n<p>If you want to query counts from multiple post types do this query:</p>\n\n<pre><code>global $wpdb; \n$count = $wpdb-&gt;get_var( \"SELECT COUNT(ID) FROM {$wpdb-&gt;posts} WHERE post_type IN ( 'code', 'shop', 'post', 'etc' ) and post_status = 'publish'\" );\necho $count;\n</code></pre>\n\n<p>Hope that helps.</p>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239846", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103161/" ]
I have this code, but it shows the total number of posts published by post type 'code'. ``` <?php $count_posts = wp_count_posts('code')->publish; echo $count_posts; ?> ``` I have 2 post types: 'code' and 'shop'. Post type code is "a child" for post type 'shop'. Therefore I need to show the post count for the "child" post type 'code' for those attached to the "parrent" post type 'shop'. UPDATE - SOLUTION (if any others are facing same problem) : ``` <?php $result = $wpdb->get_results( $wpdb->prepare( "SELECT COUNT(*) AS code_num FROM {$wpdb->prefix}postmeta AS postmeta LEFT JOIN {$wpdb->prefix}postmeta AS postmeta1 ON postmeta.post_id = postmeta1.post_id WHERE postmeta1.meta_key = 'code_expire' AND postmeta1.meta_value > %d AND postmeta.meta_key = 'code_shop_id' AND postmeta.meta_value = %s", current_time('timestamp'), $post->ID ) ); $result = array_shift( $result ); echo ' <li class="list-group-item"> <span class="badge">'.$result->code_num.'</span> <a href="'.esc_url( get_permalink( $post->ID ) ).'"> '.$post->post_title.' </a> </li>'; ?> ``` Big thanks to Ahmed!
If you prefer the $wpdb direct queries you can use something like this: ``` global $wpdb; $count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type = 'code' and post_status = 'publish'" ); echo $count; ``` In the sql query above change the `post_type` to whatever you like. This will return count of published posts under specific post type only. If you want to query counts from multiple post types do this query: ``` global $wpdb; $count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type IN ( 'code', 'shop', 'post', 'etc' ) and post_status = 'publish'" ); echo $count; ``` Hope that helps.
239,853
<p>Sorry for silly question, I'm newbie in Wordpress and PHP. I created a custom post type using <a href="https://code.tutsplus.com/tutorials/a-guide-to-wordpress-custom-post-types-creation-display-and-meta-boxes--wp-27645" rel="nofollow">this</a> tutorial. The category page is working normally, but the single is displaying all posts from category. I need to display only current post on single.php template. How can I do this? Here is the code of my single.php file in movie reviews plugin.</p> <pre><code> &lt;?php get_header(); ?&gt; &lt;section id="content"&gt; &lt;div class="wrap-content blog-single"&gt; &lt;?php $mypost = array( 'post_type' =&gt; 'movie_reviews', ); $loop = new WP_Query( $mypost ); ?&gt; &lt;?php if ($loop-&gt;have_posts()) : while ($loop-&gt;have_posts()) : $loop-&gt;the_post(); ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;?php the_title( '&lt;h1&gt;','&lt;/h1&gt;' ); ?&gt; &lt;div class="post-thumbnail"&gt; &lt;?php the_post_thumbnail(array(250, 250)); ?&gt; &lt;/div&gt; &lt;div class="entry-content"&gt;&lt;?php the_content(); ?&gt;&lt;/div&gt; &lt;/article&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php wp_reset_query(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>And this code defines template files:</p> <pre><code>function include_template_function( $template_path ) { if ( get_post_type() == 'movie_reviews' ) { if ( is_single() ) { // checks if the file exists in the theme first, // otherwise serve the file from the plugin if ( $theme_file = locate_template( array ( 'single-movie.php' ) ) ) { $template_path = $theme_file; } else { $template_path = plugin_dir_path( __FILE__ ) . '/single-movie.php'; } } else { if ( $theme_file = locate_template( array ( 'movie-category.php' ) ) ) { $template_path = $theme_file; } else { $template_path = plugin_dir_path( __FILE__ ) . '/movie-category.php'; } } } return $template_path; } add_filter( 'template_include', 'include_template_function', 1 ); </code></pre>
[ { "answer_id": 239848, "author": "RyanCameron.Me", "author_id": 100537, "author_profile": "https://wordpress.stackexchange.com/users/100537", "pm_score": 0, "selected": false, "text": "<pre><code>$count = 0; \n$loop = new WP_Query( array('post_type' =&gt; 'code') );\n\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n $count = $count + 1;\nendwhile;\n\necho $count;\n</code></pre>\n" }, { "answer_id": 239850, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 2, "selected": true, "text": "<p>If you prefer the $wpdb direct queries you can use something like this:</p>\n\n<pre><code>global $wpdb; \n$count = $wpdb-&gt;get_var( \"SELECT COUNT(ID) FROM {$wpdb-&gt;posts} WHERE post_type = 'code' and post_status = 'publish'\" );\necho $count;\n</code></pre>\n\n<p>In the sql query above change the <code>post_type</code> to whatever you like. This will return count of published posts under specific post type only.</p>\n\n<p>If you want to query counts from multiple post types do this query:</p>\n\n<pre><code>global $wpdb; \n$count = $wpdb-&gt;get_var( \"SELECT COUNT(ID) FROM {$wpdb-&gt;posts} WHERE post_type IN ( 'code', 'shop', 'post', 'etc' ) and post_status = 'publish'\" );\necho $count;\n</code></pre>\n\n<p>Hope that helps.</p>\n" } ]
2016/09/19
[ "https://wordpress.stackexchange.com/questions/239853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81307/" ]
Sorry for silly question, I'm newbie in Wordpress and PHP. I created a custom post type using [this](https://code.tutsplus.com/tutorials/a-guide-to-wordpress-custom-post-types-creation-display-and-meta-boxes--wp-27645) tutorial. The category page is working normally, but the single is displaying all posts from category. I need to display only current post on single.php template. How can I do this? Here is the code of my single.php file in movie reviews plugin. ``` <?php get_header(); ?> <section id="content"> <div class="wrap-content blog-single"> <?php $mypost = array( 'post_type' => 'movie_reviews', ); $loop = new WP_Query( $mypost ); ?> <?php if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_title( '<h1>','</h1>' ); ?> <div class="post-thumbnail"> <?php the_post_thumbnail(array(250, 250)); ?> </div> <div class="entry-content"><?php the_content(); ?></div> </article> <?php endwhile; ?> <?php endif; ?> </div> </section> <?php wp_reset_query(); ?> <?php get_footer(); ?> ``` And this code defines template files: ``` function include_template_function( $template_path ) { if ( get_post_type() == 'movie_reviews' ) { if ( is_single() ) { // checks if the file exists in the theme first, // otherwise serve the file from the plugin if ( $theme_file = locate_template( array ( 'single-movie.php' ) ) ) { $template_path = $theme_file; } else { $template_path = plugin_dir_path( __FILE__ ) . '/single-movie.php'; } } else { if ( $theme_file = locate_template( array ( 'movie-category.php' ) ) ) { $template_path = $theme_file; } else { $template_path = plugin_dir_path( __FILE__ ) . '/movie-category.php'; } } } return $template_path; } add_filter( 'template_include', 'include_template_function', 1 ); ```
If you prefer the $wpdb direct queries you can use something like this: ``` global $wpdb; $count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type = 'code' and post_status = 'publish'" ); echo $count; ``` In the sql query above change the `post_type` to whatever you like. This will return count of published posts under specific post type only. If you want to query counts from multiple post types do this query: ``` global $wpdb; $count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type IN ( 'code', 'shop', 'post', 'etc' ) and post_status = 'publish'" ); echo $count; ``` Hope that helps.
239,876
<p>I'm trying to serve different headers based on what type of page the user is on. This is my code.</p> <pre><code>&lt;!-- IF HOME --&gt; &lt;?php if ( is_front_page() &amp;&amp; is_home() ) : ?&gt; &lt;?php get_template_part( 'template-parts/headers/home-header' ); ?&gt; &lt;!-- IF TEMPLATES --&gt; &lt;?php elseif ( is_page_template('archive-mobile_photo.php') ) : ?&gt; &lt;?php get_template_part( 'template-parts/headers/home-header' ); ?&gt; &lt;!-- IF POST --&gt; &lt;?php else : ?&gt; &lt;?php get_template_part( 'template-parts/headers/zine-header' ); ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>What's weird is that the homepage and post pages are working fine, but the check using <code>is_page_template()</code> isn't working. I have the query monitor plugin and it's confirming the page is the <code>archive-mobile_photo.php</code> template. </p> <p>I'm pretty new to WordPress and I'm at a total loss.</p>
[ { "answer_id": 239878, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>It looks like you're checking if you're on the <code>mobile_photo</code> post type archive with this line:</p>\n\n<pre><code>&lt;?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?&gt;\n</code></pre>\n\n<p>If that's indeed the case, use <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> instead:</p>\n\n<pre><code>&lt;?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 239891, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 0, "selected": false, "text": "<p>Rather than using the conditionals to load headers as template parts, it would be more readable to use the functionality built in to <code>get_header()</code> when you call it for each page template. These files would live in the root of the theme folder.</p>\n\n<p>You would name your two files <code>header-home.php</code> and <code>header-zine.php</code> and call them in the page template with:</p>\n\n<p><code>get_header('home');</code></p>\n\n<p>and</p>\n\n<p><code>get_header('zine');</code></p>\n\n<p>If you do need the conditionals for a more complex page, you can still check the page and load the appropriate file based on your criteria. There's an <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">example</a> of that in the codex as well.</p>\n\n<p>I'm not sure what the difference is between <code>get_header()</code> and <code>get_template_part()</code> but if nothing else, I think it's more readable, and follows the WordPress standard.</p>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239876", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103174/" ]
I'm trying to serve different headers based on what type of page the user is on. This is my code. ``` <!-- IF HOME --> <?php if ( is_front_page() && is_home() ) : ?> <?php get_template_part( 'template-parts/headers/home-header' ); ?> <!-- IF TEMPLATES --> <?php elseif ( is_page_template('archive-mobile_photo.php') ) : ?> <?php get_template_part( 'template-parts/headers/home-header' ); ?> <!-- IF POST --> <?php else : ?> <?php get_template_part( 'template-parts/headers/zine-header' ); ?> <?php endif; ?> ``` What's weird is that the homepage and post pages are working fine, but the check using `is_page_template()` isn't working. I have the query monitor plugin and it's confirming the page is the `archive-mobile_photo.php` template. I'm pretty new to WordPress and I'm at a total loss.
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: ``` <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> ``` If that's indeed the case, use [`is_post_type_archive( $post_types )`](https://codex.wordpress.org/Function_Reference/is_post_type_archive) instead: ``` <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?> ```
239,883
<p>I would like to tick a box while drafting a post which will determine whether:</p> <p>a) only the excerpt for the post is shown on the homepage, linking you to the full post by clicking 'read more' </p> <p>or </p> <p>b) the full post is shown on the homepage with no 'read more' button available... </p> <p>Could you please explain how to do this? Thank you.</p> <p>Tom</p>
[ { "answer_id": 239878, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>It looks like you're checking if you're on the <code>mobile_photo</code> post type archive with this line:</p>\n\n<pre><code>&lt;?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?&gt;\n</code></pre>\n\n<p>If that's indeed the case, use <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> instead:</p>\n\n<pre><code>&lt;?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 239891, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 0, "selected": false, "text": "<p>Rather than using the conditionals to load headers as template parts, it would be more readable to use the functionality built in to <code>get_header()</code> when you call it for each page template. These files would live in the root of the theme folder.</p>\n\n<p>You would name your two files <code>header-home.php</code> and <code>header-zine.php</code> and call them in the page template with:</p>\n\n<p><code>get_header('home');</code></p>\n\n<p>and</p>\n\n<p><code>get_header('zine');</code></p>\n\n<p>If you do need the conditionals for a more complex page, you can still check the page and load the appropriate file based on your criteria. There's an <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">example</a> of that in the codex as well.</p>\n\n<p>I'm not sure what the difference is between <code>get_header()</code> and <code>get_template_part()</code> but if nothing else, I think it's more readable, and follows the WordPress standard.</p>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103175/" ]
I would like to tick a box while drafting a post which will determine whether: a) only the excerpt for the post is shown on the homepage, linking you to the full post by clicking 'read more' or b) the full post is shown on the homepage with no 'read more' button available... Could you please explain how to do this? Thank you. Tom
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: ``` <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> ``` If that's indeed the case, use [`is_post_type_archive( $post_types )`](https://codex.wordpress.org/Function_Reference/is_post_type_archive) instead: ``` <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?> ```
239,901
<p>I have a technology blog based on wordpress. I would like it to show a icon on top of the menu bar to show new post counter for today. Just like Android Authority website (check here <a href="http://prnt.sc/ck4q62" rel="nofollow">http://prnt.sc/ck4q62</a>) Am a newbie here and i dont know a lot about CSS and Function.php the only thing i know is basic wordpress editing skills. I've tried google about it, but without any luck at all. </p> <p>Any ideas on how to do it or the function.php file i can add in my theme child theme am using <a href="http://bunchy.bringthepixel.com/" rel="nofollow">bunchy</a> wordpress theme)</p> <p>Thanks in Advance You For Your Help</p>
[ { "answer_id": 239878, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>It looks like you're checking if you're on the <code>mobile_photo</code> post type archive with this line:</p>\n\n<pre><code>&lt;?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?&gt;\n</code></pre>\n\n<p>If that's indeed the case, use <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> instead:</p>\n\n<pre><code>&lt;?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 239891, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 0, "selected": false, "text": "<p>Rather than using the conditionals to load headers as template parts, it would be more readable to use the functionality built in to <code>get_header()</code> when you call it for each page template. These files would live in the root of the theme folder.</p>\n\n<p>You would name your two files <code>header-home.php</code> and <code>header-zine.php</code> and call them in the page template with:</p>\n\n<p><code>get_header('home');</code></p>\n\n<p>and</p>\n\n<p><code>get_header('zine');</code></p>\n\n<p>If you do need the conditionals for a more complex page, you can still check the page and load the appropriate file based on your criteria. There's an <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">example</a> of that in the codex as well.</p>\n\n<p>I'm not sure what the difference is between <code>get_header()</code> and <code>get_template_part()</code> but if nothing else, I think it's more readable, and follows the WordPress standard.</p>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239901", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103189/" ]
I have a technology blog based on wordpress. I would like it to show a icon on top of the menu bar to show new post counter for today. Just like Android Authority website (check here <http://prnt.sc/ck4q62>) Am a newbie here and i dont know a lot about CSS and Function.php the only thing i know is basic wordpress editing skills. I've tried google about it, but without any luck at all. Any ideas on how to do it or the function.php file i can add in my theme child theme am using [bunchy](http://bunchy.bringthepixel.com/) wordpress theme) Thanks in Advance You For Your Help
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: ``` <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> ``` If that's indeed the case, use [`is_post_type_archive( $post_types )`](https://codex.wordpress.org/Function_Reference/is_post_type_archive) instead: ``` <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?> ```
239,911
<p>I have a hero section on the homepage of my blog that I'd like to be the <strong>main post</strong> and thereafter more posts with a different styles underneath, see below layout: <a href="https://i.stack.imgur.com/Qson1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qson1.png" alt="layout"></a>. </p> <p>I'm not sure how to really approach this and need some guidance in the best way to port this into WordPress. Here is the code I have so far in my <code>index.php</code> file. I have managed to output the posts below the <strong>hero</strong> but not sure how to approach the main post in the hero/splash section. </p> <pre><code>&lt;div id="main"&gt; &lt;!-- hero starts here --&gt; &lt;div class="hero"&gt; &lt;div class="hero-wrapper"&gt; &lt;div class="article-info"&gt; &lt;p class="topic"&gt;&lt;a href=""&gt;Culture&lt;/a&gt;&lt;/p&gt; &lt;h1 class="hero-title"&gt;&lt;a href=""&gt;Title&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Hero end here --&gt; &lt;div class="main-container"&gt; &lt;!-- Posts starts here --&gt; &lt;div class="posts"&gt; &lt;div class="posts__post"&gt; &lt;article&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;a class="posts__post--preview" href=""&gt;&lt;img src="https://placeimg.com/470/310/tech" /&gt;&lt;/a&gt; &lt;a class="posts__post--tag" href=""&gt;&lt;p&gt;Motivation&lt;/p&gt;&lt;/a&gt; &lt;a class="posts__post--title" href="" &gt;&lt;h1&gt;A Good Autoresponder, some more text here&lt;/h1&gt;&lt;/a&gt; &lt;p class="posts__post--meta"&gt; 10 days ago&lt;/p&gt; &lt;/article&gt; &lt;?php endwhile; else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Posts ends here --&gt; &lt;!-- Main ends here --&gt; </code></pre> <p><strong>Things i'm thinking about:</strong></p> <ol> <li>What happens if I add a new main post? Will the previous post be pushed underneath?</li> </ol>
[ { "answer_id": 239878, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>It looks like you're checking if you're on the <code>mobile_photo</code> post type archive with this line:</p>\n\n<pre><code>&lt;?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?&gt;\n</code></pre>\n\n<p>If that's indeed the case, use <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> instead:</p>\n\n<pre><code>&lt;?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 239891, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 0, "selected": false, "text": "<p>Rather than using the conditionals to load headers as template parts, it would be more readable to use the functionality built in to <code>get_header()</code> when you call it for each page template. These files would live in the root of the theme folder.</p>\n\n<p>You would name your two files <code>header-home.php</code> and <code>header-zine.php</code> and call them in the page template with:</p>\n\n<p><code>get_header('home');</code></p>\n\n<p>and</p>\n\n<p><code>get_header('zine');</code></p>\n\n<p>If you do need the conditionals for a more complex page, you can still check the page and load the appropriate file based on your criteria. There's an <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">example</a> of that in the codex as well.</p>\n\n<p>I'm not sure what the difference is between <code>get_header()</code> and <code>get_template_part()</code> but if nothing else, I think it's more readable, and follows the WordPress standard.</p>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103159/" ]
I have a hero section on the homepage of my blog that I'd like to be the **main post** and thereafter more posts with a different styles underneath, see below layout: [![layout](https://i.stack.imgur.com/Qson1.png)](https://i.stack.imgur.com/Qson1.png). I'm not sure how to really approach this and need some guidance in the best way to port this into WordPress. Here is the code I have so far in my `index.php` file. I have managed to output the posts below the **hero** but not sure how to approach the main post in the hero/splash section. ``` <div id="main"> <!-- hero starts here --> <div class="hero"> <div class="hero-wrapper"> <div class="article-info"> <p class="topic"><a href="">Culture</a></p> <h1 class="hero-title"><a href="">Title</a></h1> </div> </div> </div> <!-- Hero end here --> <div class="main-container"> <!-- Posts starts here --> <div class="posts"> <div class="posts__post"> <article> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <a class="posts__post--preview" href=""><img src="https://placeimg.com/470/310/tech" /></a> <a class="posts__post--tag" href=""><p>Motivation</p></a> <a class="posts__post--title" href="" ><h1>A Good Autoresponder, some more text here</h1></a> <p class="posts__post--meta"> 10 days ago</p> </article> <?php endwhile; else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> </div> </div> <!-- Posts ends here --> <!-- Main ends here --> ``` **Things i'm thinking about:** 1. What happens if I add a new main post? Will the previous post be pushed underneath?
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: ``` <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> ``` If that's indeed the case, use [`is_post_type_archive( $post_types )`](https://codex.wordpress.org/Function_Reference/is_post_type_archive) instead: ``` <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?> ```
239,932
<p>I know that I can map multiple domains to individual blogs through plugins. But is it possible to configure WordPress multisite to have more than one parent domain? </p> <p>Ie., a user wants to create a blog. We use the standard form for that, but apart from choosing their own subdomain, I'd like to be able to give them a choice of parent domains as well. Is that possible? </p>
[ { "answer_id": 239878, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>It looks like you're checking if you're on the <code>mobile_photo</code> post type archive with this line:</p>\n\n<pre><code>&lt;?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?&gt;\n</code></pre>\n\n<p>If that's indeed the case, use <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> instead:</p>\n\n<pre><code>&lt;?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 239891, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 0, "selected": false, "text": "<p>Rather than using the conditionals to load headers as template parts, it would be more readable to use the functionality built in to <code>get_header()</code> when you call it for each page template. These files would live in the root of the theme folder.</p>\n\n<p>You would name your two files <code>header-home.php</code> and <code>header-zine.php</code> and call them in the page template with:</p>\n\n<p><code>get_header('home');</code></p>\n\n<p>and</p>\n\n<p><code>get_header('zine');</code></p>\n\n<p>If you do need the conditionals for a more complex page, you can still check the page and load the appropriate file based on your criteria. There's an <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">example</a> of that in the codex as well.</p>\n\n<p>I'm not sure what the difference is between <code>get_header()</code> and <code>get_template_part()</code> but if nothing else, I think it's more readable, and follows the WordPress standard.</p>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3986/" ]
I know that I can map multiple domains to individual blogs through plugins. But is it possible to configure WordPress multisite to have more than one parent domain? Ie., a user wants to create a blog. We use the standard form for that, but apart from choosing their own subdomain, I'd like to be able to give them a choice of parent domains as well. Is that possible?
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: ``` <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> ``` If that's indeed the case, use [`is_post_type_archive( $post_types )`](https://codex.wordpress.org/Function_Reference/is_post_type_archive) instead: ``` <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?> ```
239,942
<p>I have a page template, which is fully working throughout the website other than the pages where the plugin has generated a page such as a job description page, as the plugin that I am using is WP Job Manager. I have tried to include the php file in the functions of the theme and also the template of the theme however, nothing appears and if it does then the content of the template appears above the navigation bar?</p> <p>Is there anyway in which I am able to get this into this page and any other page that is dynamically created via the plugin, as there will be many pages.</p> <p>The plugin creates a Custom Post Type which is what is used to create the pages, the pages are not actually existing in the back end.</p> <p>The plugin is located in the wp-content/wp-job-manager/... and the page template is located in the wp-content/themes/test-theme/universal-template.php</p> <p>The code I have tried is <code>&lt;?php include('/wp-content/themes/test-theme/universal-template.php'); ?&gt;</code> I know this isn't the best way to include a file but I was doing this till I can get it working</p>
[ { "answer_id": 239878, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>It looks like you're checking if you're on the <code>mobile_photo</code> post type archive with this line:</p>\n\n<pre><code>&lt;?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?&gt;\n</code></pre>\n\n<p>If that's indeed the case, use <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> instead:</p>\n\n<pre><code>&lt;?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 239891, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 0, "selected": false, "text": "<p>Rather than using the conditionals to load headers as template parts, it would be more readable to use the functionality built in to <code>get_header()</code> when you call it for each page template. These files would live in the root of the theme folder.</p>\n\n<p>You would name your two files <code>header-home.php</code> and <code>header-zine.php</code> and call them in the page template with:</p>\n\n<p><code>get_header('home');</code></p>\n\n<p>and</p>\n\n<p><code>get_header('zine');</code></p>\n\n<p>If you do need the conditionals for a more complex page, you can still check the page and load the appropriate file based on your criteria. There's an <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">example</a> of that in the codex as well.</p>\n\n<p>I'm not sure what the difference is between <code>get_header()</code> and <code>get_template_part()</code> but if nothing else, I think it's more readable, and follows the WordPress standard.</p>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239942", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103223/" ]
I have a page template, which is fully working throughout the website other than the pages where the plugin has generated a page such as a job description page, as the plugin that I am using is WP Job Manager. I have tried to include the php file in the functions of the theme and also the template of the theme however, nothing appears and if it does then the content of the template appears above the navigation bar? Is there anyway in which I am able to get this into this page and any other page that is dynamically created via the plugin, as there will be many pages. The plugin creates a Custom Post Type which is what is used to create the pages, the pages are not actually existing in the back end. The plugin is located in the wp-content/wp-job-manager/... and the page template is located in the wp-content/themes/test-theme/universal-template.php The code I have tried is `<?php include('/wp-content/themes/test-theme/universal-template.php'); ?>` I know this isn't the best way to include a file but I was doing this till I can get it working
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: ``` <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> ``` If that's indeed the case, use [`is_post_type_archive( $post_types )`](https://codex.wordpress.org/Function_Reference/is_post_type_archive) instead: ``` <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?> ```
239,943
<p>I'm trying to hide posts from a specific category from being featured. Currently, the section shows featured posts from all categories. I need to exclude posts from a category (with category name not by id). </p> <pre><code>$args = array( 'posts_per_page' =&gt; 1, 'meta_key' =&gt; 'meta-checkbox', 'meta_value' =&gt; 'yes', ); $featured = new WP_Query( $args ); </code></pre>
[ { "answer_id": 239944, "author": "vanurag", "author_id": 70096, "author_profile": "https://wordpress.stackexchange.com/users/70096", "pm_score": -1, "selected": false, "text": "<p>you can add <code>'exclude' =&gt; '',</code> in your args array</p>\n\n<p>or just provide the category id ,comma separated like below</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 1,\n 'meta_key' =&gt; 'meta-checkbox',\n 'meta_value' =&gt; 'yes',\n'category' =&gt; '2,3,4,5,6,7,8',\n );\n</code></pre>\n\n<p>See this link :<a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">https://codex.wordpress.org/Template_Tags/get_posts</a></p>\n" }, { "answer_id": 239946, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 3, "selected": true, "text": "<p><strong>Excluding specific categories from WP_Query</strong></p>\n\n<p>This is in the codex. You can exlclude specific categories from WP_Query. Where array(2, 6) are IDs for categories to be excluded in this example.</p>\n\n<pre><code>$query = new WP_Query( array( 'category__not_in' =&gt; array( 2, 6 ) ) );\n</code></pre>\n\n<p>See the codex:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters</a></p>\n\n<p><strong>NOTE: If you are trying to exclude category by the name of category</strong></p>\n\n<p>First you would do this to find the category ID by providing category name.</p>\n\n<pre><code>$category_id = get_cat_ID( 'My Category' );\n</code></pre>\n\n<p>then add the returned <code>$category_id</code> in your WP Query arguments it would look like this:</p>\n\n<pre><code>$query = new WP_Query( array( 'category__not_in' =&gt; array( $category_id ) ) );\n</code></pre>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239943", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86147/" ]
I'm trying to hide posts from a specific category from being featured. Currently, the section shows featured posts from all categories. I need to exclude posts from a category (with category name not by id). ``` $args = array( 'posts_per_page' => 1, 'meta_key' => 'meta-checkbox', 'meta_value' => 'yes', ); $featured = new WP_Query( $args ); ```
**Excluding specific categories from WP\_Query** This is in the codex. You can exlclude specific categories from WP\_Query. Where array(2, 6) are IDs for categories to be excluded in this example. ``` $query = new WP_Query( array( 'category__not_in' => array( 2, 6 ) ) ); ``` See the codex: <https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters> **NOTE: If you are trying to exclude category by the name of category** First you would do this to find the category ID by providing category name. ``` $category_id = get_cat_ID( 'My Category' ); ``` then add the returned `$category_id` in your WP Query arguments it would look like this: ``` $query = new WP_Query( array( 'category__not_in' => array( $category_id ) ) ); ```
239,945
<p>I tried </p> <pre><code>add_filter( 'page_template', 'single_page_template' ); function single_page_template( $template ) { if ( is_singular( 'dwqa-question' ) ) { $template = get_stylesheet_directory() . '/' . page-question.php; } return $template; } </code></pre> <p>now, if I will out put <code>echo get_page_template();</code> I am getting </p> <p><code>/var/www/html/my-site/wp-content/themes/theme-child/page-question.php</code></p> <p>but modifying the page-question.php file not effecting the output ,adding some text to this template like </p> <p><code>get_header(); ?&gt;zzzzzzzzz</code> </p> <p>not getting out put. page.php is assign to single question page using <code>template_include</code> hook is this because of that , but if yes echoing <code>get_page_template()</code> should also give page.php tempalte path as output .</p> <p>Just modified page.php like </p> <p><code>get_header(); ?&gt;aaaa</code> </p> <p>and <code>aaaa</code> is appearing on page .</p> <p>How I should override it ?? please let me know if I should provide any other detail ?</p>
[ { "answer_id": 239951, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>According to the Theme Handbook (<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-custom-page-templates-for-global-use\" rel=\"nofollow\">https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-custom-page-templates-for-global-use</a>), \"Do not use <code>page-</code> as a prefix, as WordPress will interpret the file as a specialized template, meant to apply to only one page on your site.\"</p>\n\n<p>So - try renaming <code>page-question.php</code> something like <code>tpl-question.php</code> (tpl is a common prefix, short for template).</p>\n" }, { "answer_id": 274202, "author": "kenv", "author_id": 124356, "author_profile": "https://wordpress.stackexchange.com/users/124356", "pm_score": 0, "selected": false, "text": "<p>Just try to implement flush of the rewrite rules function.</p>\n\n<pre>\n flush_rewrite_rules();\n</pre>\n\n<p>You are free to use the alternative way,</p>\n\n<pre>\n global $wp_rewrite;\n $wp_rewrite->flush_rules( true );\n</pre>\n" }, { "answer_id": 289722, "author": "elmediano", "author_id": 15089, "author_profile": "https://wordpress.stackexchange.com/users/15089", "pm_score": 3, "selected": false, "text": "<p>From your question, it seems you're trying to override the single template of a custom post type. If so, the filter you want to use is <code>single_template</code> and not <code>page_template</code>:</p>\n<pre><code>function single_page_template($single_template) {\n global $post;\n\n if ($post-&gt;post_type == 'dwqa-question') {\n $single_template = get_stylesheet_directory() . '/page-question.php';\n }\n\n return $single_template;\n}\nadd_filter( 'single_template', 'single_page_template' );\n</code></pre>\n<p>I once had this issue and it was driving me crazy, until I found the filter on the WordPress Codex: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template</a></p>\n" }, { "answer_id": 300215, "author": "Kalamun", "author_id": 131986, "author_profile": "https://wordpress.stackexchange.com/users/131986", "pm_score": 1, "selected": false, "text": "<p>You mispelled the \"page-question.php\" portion of code, it must be included in quotes:</p>\n\n<pre><code>$template = get_stylesheet_directory() . '/page-question.php';\n</code></pre>\n" } ]
2016/09/20
[ "https://wordpress.stackexchange.com/questions/239945", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81273/" ]
I tried ``` add_filter( 'page_template', 'single_page_template' ); function single_page_template( $template ) { if ( is_singular( 'dwqa-question' ) ) { $template = get_stylesheet_directory() . '/' . page-question.php; } return $template; } ``` now, if I will out put `echo get_page_template();` I am getting `/var/www/html/my-site/wp-content/themes/theme-child/page-question.php` but modifying the page-question.php file not effecting the output ,adding some text to this template like `get_header(); ?>zzzzzzzzz` not getting out put. page.php is assign to single question page using `template_include` hook is this because of that , but if yes echoing `get_page_template()` should also give page.php tempalte path as output . Just modified page.php like `get_header(); ?>aaaa` and `aaaa` is appearing on page . How I should override it ?? please let me know if I should provide any other detail ?
From your question, it seems you're trying to override the single template of a custom post type. If so, the filter you want to use is `single_template` and not `page_template`: ``` function single_page_template($single_template) { global $post; if ($post->post_type == 'dwqa-question') { $single_template = get_stylesheet_directory() . '/page-question.php'; } return $single_template; } add_filter( 'single_template', 'single_page_template' ); ``` I once had this issue and it was driving me crazy, until I found the filter on the WordPress Codex: <https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template>
240,042
<p>I want to add additional items to the data returned as <a href="https://codex.wordpress.org/Class_Reference/WP_Post" rel="noreferrer"><code>WP_Post</code></a>. So for every function/query that returns a WP_Post object I want my additional data added.</p> <p>Example of returned result:</p> <pre><code>WP_Post (object) =&gt; [ // Default data returned by WP_Post ID =&gt; int, post_author =&gt; string, post_name =&gt; string, post_type =&gt; string, post_title =&gt; string, post_date =&gt; string, post_date_gmt =&gt; string, post_content =&gt; string, post_excerpt =&gt; string, post_status =&gt; string, comment_status =&gt; string, ping_status =&gt; string, post_password =&gt; string, post_parent =&gt; int, post_modified =&gt; string, post_modified_gmt =&gt; string, comment_count =&gt; string, menu_order =&gt; string, // Additional data I want to add extra_data_1 =&gt; array, more_data_key =&gt; string, another_added =&gt; string ] </code></pre> <p>For example when the functions <a href="https://developer.wordpress.org/reference/functions/get_post/" rel="noreferrer"><code>get_post()</code></a> or <a href="https://developer.wordpress.org/reference/functions/get_page_by_path/" rel="noreferrer"><code>get_page_by_path()</code></a> are run they will return the WP_Post object along with my additional data.</p> <p>I've tried finding the appropriate <a href="https://codex.wordpress.org/Plugin_API/Action_Reference" rel="noreferrer">hook/filter</a> but this has been unsuccessful.</p> <p>I am hoping I can do something like:</p> <pre><code>// This is concept code add_action('pre_wp_post_return', function($data) { $data-&gt;extra_data_1 = get_post_meta($data-&gt;ID, 'extra_data'); $data-&gt;more_data_key = get_post_meta($data-&gt;ID, 'more_data', true); $data-&gt;another_added = get_post_meta($data-&gt;ID, 'another_data', true); return $data; }); </code></pre> <p>My reasoning is I am having to build a custom API for WP that uses a range of different core functions which return WP_Post objects. Being able to add my additional data in one place would prevent me from duplicating code.</p> <p>I hope this is clear enough. Any help would be great!</p>
[ { "answer_id": 240050, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>TLDR; You can't and you shouldn't.</p>\n\n<p>It is <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-post.php#L22\" rel=\"nofollow\">impossible to extend the <code>WP_post</code> class</a> with extra fields, because it has been defined as <a href=\"http://php.net/manual/en/language.oop5.final.php\" rel=\"nofollow\">'final'</a>. You perhaps could get around that by wrapping the class in another class (<a href=\"https://github.com/mhull/helping-friendly-plugin/blob/master/lib/class-hphp-post.php\" rel=\"nofollow\">tutorial</a>), but it still is not advisable.</p>\n\n<p>All kinds of themes and plugins rely on the <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">metadata being stored as metadata</a>. You may get it to work right now, but you'll probably regret it in the future, when you find out that some plugin you want to use cannot handle the way you have stored your metadata.</p>\n" }, { "answer_id": 240051, "author": "David", "author_id": 31323, "author_profile": "https://wordpress.stackexchange.com/users/31323", "pm_score": 4, "selected": false, "text": "<p>If your extra data directly references a post meta you don't have to do anything, because <code>WP_Post</code> implements the »magic« methods <a href=\"https://github.com/WordPress/WordPress/blob/0b81d79c868a3ed3eedbee53805f1cdad5d90351/wp-includes/class-wp-post.php#L252\" rel=\"noreferrer\"><code>__isset()</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/0b81d79c868a3ed3eedbee53805f1cdad5d90351/wp-includes/class-wp-post.php#L274\" rel=\"noreferrer\"><code>__get()</code></a> which directly asks for post meta keys (except for the following four keys: <code>page_template</code>, <code>post_category</code>, <code>tags_input</code> and <code>ancestors</code>). Here's a quick example that shows the behavior:</p>\n\n<pre><code>&lt;?php\n$post_id = 42;\n$meta_key = 'extra_data_1';\nadd_post_meta( $post_id, $meta_key, [ 'some', 'value' ], TRUE );\n$post = get_post( $post_id );\nvar_dump( $post-&gt;{$meta_key} ); // (array) ['some', 'value']\n</code></pre>\n\n<p>In any other case, use the filter <a href=\"https://github.com/WordPress/WordPress/blob/0b81d79c868a3ed3eedbee53805f1cdad5d90351/wp-includes/class-wp-query.php#L2866\" rel=\"noreferrer\"><code>posts_results</code></a>: </p>\n\n<pre><code>&lt;?php\nadd_filter(\n 'posts_results',\n function( array $posts, WP_Query $query ) {\n foreach ( $posts as $post ) {\n $post-&gt;extra_data_1 = get_post_meta( $post-&gt;ID, 'extra_data' );\n // and so on …\n }\n\n return $posts;\n },\n 10,\n 2\n);\n</code></pre>\n\n<p>However I would suggest to use an object oriented approach and create own entity interfaces, that follows your problem domain. The implementations then wrapping <code>WP_Post</code> instances as a dependency. For example, let's say you're dealing with <em>books</em>:</p>\n\n<pre><code>&lt;?php\n\nnamespace Wpse240042\\Type;\n\nuse WP_Post;\n\ninterface Book {\n\n /**\n * @return string\n */\n public function title();\n\n /**\n * @return string\n */\n public function publisher();\n\n /**\n * @return int\n */\n public function year();\n}\n\nclass WpPostBook implements Book {\n\n /**\n * @var WP_Post\n */\n private $post;\n\n /**\n * @param WP_Post $post\n */\n public function __construct( WP_Post $post ) {\n\n $this-&gt;post = $post;\n }\n\n /**\n * @return string\n */\n public function title() {\n\n return $this-&gt;post-&gt;post_title;\n }\n\n /**\n * @return string\n */\n public function publisher() {\n\n return get_post_meta( $this-&gt;post-&gt;ID, '_book_publisher', TRUE );\n }\n\n /**\n * @return int\n */\n public function year() {\n\n return get_post_meta( $this-&gt;post-&gt;ID, '_book_publisher', TRUE );\n }\n}\n</code></pre>\n\n<p>Your business logic can then rely on the structure of a <em>book</em> by type hint the type <code>Book</code> on every dependency. To fetch a list of books you could implement a factory in the first step that wraps a <code>WP_Query</code> or fetch WP_Query arguments and return a list of book instances. You should not use the <code>posts_results</code> filter in that case to replace <code>WP_Query::posts</code> with a list of <code>Type\\Book</code> instances to not break type consistency throughout WP core.</p>\n" }, { "answer_id": 381095, "author": "Mark Rutten", "author_id": 200009, "author_profile": "https://wordpress.stackexchange.com/users/200009", "pm_score": 0, "selected": false, "text": "<p>I know this is an old post but thought share a working solution\nThis can be achieved by doing:</p>\n<pre><code>$posts = get_posts( \n array(\n &quot;post_type&quot; =&gt; $post_type-&gt;name,\n &quot;numberposts&quot; =&gt; -1 \n )\n);\nforeach($posts as &amp;$post)\n{\n $custom_fields = (array)$post;\n // add extra field(s) like this\n $custom_fields[&quot;posttype_link&quot;] = get_permalink($post-&gt;ID);\n $post = (object)$custom_fields;\n}\n</code></pre>\n" }, { "answer_id": 393778, "author": "noahmason", "author_id": 142015, "author_profile": "https://wordpress.stackexchange.com/users/142015", "pm_score": 0, "selected": false, "text": "<p>Use the <strong>the_post</strong> hook: <a href=\"https://developer.wordpress.org/reference/hooks/the_post/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/the_post/</a></p>\n<p>You will be modifying the global <strong>$post</strong> object so no need to return it as if it was a filter. The 2 params <strong>$post</strong> and <strong>$query</strong> are passed for reference.</p>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37896/" ]
I want to add additional items to the data returned as [`WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post). So for every function/query that returns a WP\_Post object I want my additional data added. Example of returned result: ``` WP_Post (object) => [ // Default data returned by WP_Post ID => int, post_author => string, post_name => string, post_type => string, post_title => string, post_date => string, post_date_gmt => string, post_content => string, post_excerpt => string, post_status => string, comment_status => string, ping_status => string, post_password => string, post_parent => int, post_modified => string, post_modified_gmt => string, comment_count => string, menu_order => string, // Additional data I want to add extra_data_1 => array, more_data_key => string, another_added => string ] ``` For example when the functions [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/) or [`get_page_by_path()`](https://developer.wordpress.org/reference/functions/get_page_by_path/) are run they will return the WP\_Post object along with my additional data. I've tried finding the appropriate [hook/filter](https://codex.wordpress.org/Plugin_API/Action_Reference) but this has been unsuccessful. I am hoping I can do something like: ``` // This is concept code add_action('pre_wp_post_return', function($data) { $data->extra_data_1 = get_post_meta($data->ID, 'extra_data'); $data->more_data_key = get_post_meta($data->ID, 'more_data', true); $data->another_added = get_post_meta($data->ID, 'another_data', true); return $data; }); ``` My reasoning is I am having to build a custom API for WP that uses a range of different core functions which return WP\_Post objects. Being able to add my additional data in one place would prevent me from duplicating code. I hope this is clear enough. Any help would be great!
If your extra data directly references a post meta you don't have to do anything, because `WP_Post` implements the »magic« methods [`__isset()`](https://github.com/WordPress/WordPress/blob/0b81d79c868a3ed3eedbee53805f1cdad5d90351/wp-includes/class-wp-post.php#L252) and [`__get()`](https://github.com/WordPress/WordPress/blob/0b81d79c868a3ed3eedbee53805f1cdad5d90351/wp-includes/class-wp-post.php#L274) which directly asks for post meta keys (except for the following four keys: `page_template`, `post_category`, `tags_input` and `ancestors`). Here's a quick example that shows the behavior: ``` <?php $post_id = 42; $meta_key = 'extra_data_1'; add_post_meta( $post_id, $meta_key, [ 'some', 'value' ], TRUE ); $post = get_post( $post_id ); var_dump( $post->{$meta_key} ); // (array) ['some', 'value'] ``` In any other case, use the filter [`posts_results`](https://github.com/WordPress/WordPress/blob/0b81d79c868a3ed3eedbee53805f1cdad5d90351/wp-includes/class-wp-query.php#L2866): ``` <?php add_filter( 'posts_results', function( array $posts, WP_Query $query ) { foreach ( $posts as $post ) { $post->extra_data_1 = get_post_meta( $post->ID, 'extra_data' ); // and so on … } return $posts; }, 10, 2 ); ``` However I would suggest to use an object oriented approach and create own entity interfaces, that follows your problem domain. The implementations then wrapping `WP_Post` instances as a dependency. For example, let's say you're dealing with *books*: ``` <?php namespace Wpse240042\Type; use WP_Post; interface Book { /** * @return string */ public function title(); /** * @return string */ public function publisher(); /** * @return int */ public function year(); } class WpPostBook implements Book { /** * @var WP_Post */ private $post; /** * @param WP_Post $post */ public function __construct( WP_Post $post ) { $this->post = $post; } /** * @return string */ public function title() { return $this->post->post_title; } /** * @return string */ public function publisher() { return get_post_meta( $this->post->ID, '_book_publisher', TRUE ); } /** * @return int */ public function year() { return get_post_meta( $this->post->ID, '_book_publisher', TRUE ); } } ``` Your business logic can then rely on the structure of a *book* by type hint the type `Book` on every dependency. To fetch a list of books you could implement a factory in the first step that wraps a `WP_Query` or fetch WP\_Query arguments and return a list of book instances. You should not use the `posts_results` filter in that case to replace `WP_Query::posts` with a list of `Type\Book` instances to not break type consistency throughout WP core.
240,043
<p>I would like to use the titles within a select element in a form I am echoing to the client side. What would be the best way to do this?</p>
[ { "answer_id": 240048, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 5, "selected": true, "text": "<p><strong>Query all post titles of a specific post type</strong></p>\n\n<pre><code>// Function that returns post titles from specific post type as form select element\n// returns null if found no results.\n\nfunction output_projects_list() {\n global $wpdb;\n\n $custom_post_type = 'page'; // define your custom post type slug here\n\n // A sql query to return all post titles\n $results = $wpdb-&gt;get_results( $wpdb-&gt;prepare( \"SELECT ID, post_title FROM {$wpdb-&gt;posts} WHERE post_type = %s and post_status = 'publish'\", $custom_post_type ), ARRAY_A );\n\n // Return null if we found no results\n if ( ! $results )\n return;\n\n // HTML for our select printing post titles as loop\n $output = '&lt;select name=\"project\" id=\"project\"&gt;';\n\n foreach( $results as $index =&gt; $post ) {\n $output .= '&lt;option value=\"' . $post['ID'] . '\"&gt;' . $post['post_title'] . '&lt;/option&gt;';\n }\n\n $output .= '&lt;/select&gt;'; // end of select element\n\n // get the html\n return $output;\n}\n\n// Then in your project just call the function\n// Where you want the select form to appear\necho output_projects_list();\n</code></pre>\n" }, { "answer_id": 240056, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 4, "selected": false, "text": "<p>You could - and in my mind, should - use API functions to get the data.</p>\n\n<pre><code>// query for your post type\n$post_type_query = new WP_Query( \n array ( \n 'post_type' =&gt; 'your-post-type', \n 'posts_per_page' =&gt; -1 \n ) \n); \n// we need the array of posts\n$posts_array = $post_type_query-&gt;posts; \n// create a list with needed information\n// the key equals the ID, the value is the post_title\n$post_title_array = wp_list_pluck( $posts_array, 'post_title', 'ID' );\n</code></pre>\n" }, { "answer_id": 240059, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>For an <strong>hierarchical</strong> post type, we have the built-in:</p>\n\n<pre><code>wp_dropdown_pages( \n [ \n 'post_type' =&gt; 'page',\n 'echo' =&gt; 1, \n 'name' =&gt; 'wpse_titles', \n 'id' =&gt; 'wpse-titles' \n ] \n);\n</code></pre>\n\n<p>that will generate a <em>select</em> element with <em>post titles</em> and the <em>post ID</em> as the option value. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>&lt;select name='wpse_titles' id='wpse-titles'&gt;\n &lt;option class=\"level-0\" value=\"1\"&gt;AAA&lt;/option&gt;\n &lt;option class=\"level-0\" value=\"2\"&gt;BBB&lt;/option&gt;\n &lt;option class=\"level-1\" value=\"3\"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;CCC&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>It's not clear from the <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_pages/\" rel=\"nofollow\">documentation</a> for <code>wp_dropdown_pages()</code>, but it's a wrapper for <code>get_pages()</code> and also support it's input arguments.</p>\n" }, { "answer_id": 240908, "author": "Tim Roberts", "author_id": 101483, "author_profile": "https://wordpress.stackexchange.com/users/101483", "pm_score": 0, "selected": false, "text": "<p>The way I have always done things like this is using <code>get_posts</code> and <code>foreach</code> like something below:</p>\n\n<pre><code>// Create our arguments for getting our post\n$args = [\n 'post_type'=&gt;'custom-slug'\n];\n\n// we get an array of posts objects\n$posts = get_posts($args);\n\n// start our string\n$str = '&lt;select&gt;';\n// then we create an option for each post\nforeach($posts as $key=&gt;$post){\n $str .= '&lt;option&gt;'.$post-&gt;post_title.'&lt;/option&gt;';\n}\n$str .= '&lt;/select&gt;';\necho $str;\n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240043", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103297/" ]
I would like to use the titles within a select element in a form I am echoing to the client side. What would be the best way to do this?
**Query all post titles of a specific post type** ``` // Function that returns post titles from specific post type as form select element // returns null if found no results. function output_projects_list() { global $wpdb; $custom_post_type = 'page'; // define your custom post type slug here // A sql query to return all post titles $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A ); // Return null if we found no results if ( ! $results ) return; // HTML for our select printing post titles as loop $output = '<select name="project" id="project">'; foreach( $results as $index => $post ) { $output .= '<option value="' . $post['ID'] . '">' . $post['post_title'] . '</option>'; } $output .= '</select>'; // end of select element // get the html return $output; } // Then in your project just call the function // Where you want the select form to appear echo output_projects_list(); ```
240,061
<p>I am creating plugin that redirects users UNLESS they are visiting from a specific IP.</p> <p>Originally I had this code sat in index.php so it would never load on wp-admin, wp-login pages. However since I have moved this code to a plugin it is. </p> <p>Does anyone know how I can stop the plugin from running while user is on wp-login / wp-admin? I was going to simply check the url for these strings but wondered if there was a 'better practice' method of achieving this.</p> <p><strong>Plugin Code:</strong></p> <pre><code>/** * Plugin Name: LSM - Device Detection * Plugin URI: http://no_uri * Description: Makes use of WURFL API to detect what device a user is on and redirect if needed * Version: 1.0 * Author: James Husband * Author URI: http://no_uri * License: GPL2 */ // I DO NOT WANT THE FOLLOWING CODE TO RUN IF USER IS ON WP-ADMIN / WP-LOGIN /* Device Redirects */ $device = getDevice(); if ($_SERVER["REMOTE_ADDR"] != "IPHIDDEN" and $_SERVER["REMOTE_ADDR"] != "IPHIDDEN" and $_SERVER["HTTP_X_FORWARDED_FOR"] != "IPHIDDEN") { switch ($device) { case TABLET: header('Location: http://www.urlhidden.com/tablet/'); exit; break; case DESKTOP: header('Location: http://www.urlhidden.com/'); exit; break; } } </code></pre>
[ { "answer_id": 240085, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 3, "selected": true, "text": "<p>You can try with the following example to stop the code running on <code>admin</code> side or on <code>wp-login.php</code> page.</p>\n\n<pre><code>if ( ! is_admin() || 'wp-login.php' != $GLOBALS['pagenow'] ) {\n // Do stuff here. code inside this statement will \n // not run on wp-admin &amp; login page.\n}\n</code></pre>\n" }, { "answer_id": 240086, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 1, "selected": false, "text": "<p>Hook your code onto the <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow\"><code>template_redirect</code></a> hook which is only fired on the front end of a WP site. </p>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240061", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71177/" ]
I am creating plugin that redirects users UNLESS they are visiting from a specific IP. Originally I had this code sat in index.php so it would never load on wp-admin, wp-login pages. However since I have moved this code to a plugin it is. Does anyone know how I can stop the plugin from running while user is on wp-login / wp-admin? I was going to simply check the url for these strings but wondered if there was a 'better practice' method of achieving this. **Plugin Code:** ``` /** * Plugin Name: LSM - Device Detection * Plugin URI: http://no_uri * Description: Makes use of WURFL API to detect what device a user is on and redirect if needed * Version: 1.0 * Author: James Husband * Author URI: http://no_uri * License: GPL2 */ // I DO NOT WANT THE FOLLOWING CODE TO RUN IF USER IS ON WP-ADMIN / WP-LOGIN /* Device Redirects */ $device = getDevice(); if ($_SERVER["REMOTE_ADDR"] != "IPHIDDEN" and $_SERVER["REMOTE_ADDR"] != "IPHIDDEN" and $_SERVER["HTTP_X_FORWARDED_FOR"] != "IPHIDDEN") { switch ($device) { case TABLET: header('Location: http://www.urlhidden.com/tablet/'); exit; break; case DESKTOP: header('Location: http://www.urlhidden.com/'); exit; break; } } ```
You can try with the following example to stop the code running on `admin` side or on `wp-login.php` page. ``` if ( ! is_admin() || 'wp-login.php' != $GLOBALS['pagenow'] ) { // Do stuff here. code inside this statement will // not run on wp-admin & login page. } ```
240,063
<p>Whilst looking through the <a href="https://codex.wordpress.org/Template_Tags/get_posts" rel="nofollow">codex</a> for the <code>get_posts</code> function, I noticed that in the majority of the examples they do not show an if statement after call to <code>get_posts</code></p> <p>Example: </p> <pre><code>&lt;?php $args = array( 'posts_per_page' =&gt; 10, 'order'=&gt; 'ASC', 'orderby' =&gt; 'title' ); $postslist = get_posts( $args ); foreach ( $postslist as $post ) : setup_postdata( $post ); ?&gt; &lt;div&gt; &lt;?php the_date(); ?&gt; &lt;br /&gt; &lt;?php the_title(); ?&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt; &lt;?php endforeach; wp_reset_postdata(); ?&gt; </code></pre> <p>And:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'attachment', 'posts_per_page' =&gt; -1, 'post_status' =&gt;'any', 'post_parent' =&gt; $post-&gt;ID ); $attachments = get_posts( $args ); **if ( $attachments ) {** foreach ( $attachments as $attachment ) { echo apply_filters( 'the_title' , $attachment-&gt;post_title ); the_attachment_link( $attachment-&gt;ID , false ); } } ?&gt; </code></pre> <p>I'm not sure if the codex is assuming that you will always have posts so no need to check?</p> <p>I personally always use it, but wonder if someone could enlighten me on if its necessary. When is a right time to use the if statement?</p>
[ { "answer_id": 240083, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>The <code>get_posts()</code> can return an empty array</p>\n\n<p>In that case the foreach loop is like:</p>\n\n<pre><code>foreach ( [] as $post ) \n{\n // ...\n}\n</code></pre>\n\n<p>where there's nothing to loop over. This code is valid.</p>\n\n<p>If the code snippet is like:</p>\n\n<pre><code>echo '&lt;ul&gt;';\nforeach ( $postslist as $post ) \n{\n // &lt;li&gt;...&lt;/li&gt;\n}\necho '&lt;/ul&gt;';\n</code></pre>\n\n<p>then we need to check if <code>$postslist</code> is non-empty:</p>\n\n<pre><code>if( $postslist )\n{ \n echo '&lt;ul&gt;';\n foreach ( $postslist as $post ) \n {\n // &lt;li&gt;...&lt;/li&gt;\n }\n echo '&lt;/ul&gt;';\n}\n</code></pre>\n\n<p>to avoid displaying an empty <code>&lt;ul&gt;&lt;/ul&gt;</code> list.</p>\n\n<p>This is an example, out of many, where it would make sense to check if the post list is non-empty, but it's not required, like if you only need the count:</p>\n\n<pre><code>echo count( (array) $postslist );\n</code></pre>\n" }, { "answer_id": 240084, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 2, "selected": false, "text": "<p>In my opinion we cannot guarantee the post existence in db for a specific query. maybe it returns an empty array. so its best practice to use the conditional statement. plus i think we are dealing with an array so to check the empty array we should use php <code>empty</code> function.</p>\n\n<p>for example:</p>\n\n<pre><code>if ( !empty( $attachments ) ) {\n foreach ( $attachments as $attachment ) {\n // do some stuff here.\n }\n}\nelse {\n _e('Sorry! No posts found.');\n}\n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71627/" ]
Whilst looking through the [codex](https://codex.wordpress.org/Template_Tags/get_posts) for the `get_posts` function, I noticed that in the majority of the examples they do not show an if statement after call to `get_posts` Example: ``` <?php $args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' ); $postslist = get_posts( $args ); foreach ( $postslist as $post ) : setup_postdata( $post ); ?> <div> <?php the_date(); ?> <br /> <?php the_title(); ?> <?php the_excerpt(); ?> </div> <?php endforeach; wp_reset_postdata(); ?> ``` And: ``` <?php $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); $attachments = get_posts( $args ); **if ( $attachments ) {** foreach ( $attachments as $attachment ) { echo apply_filters( 'the_title' , $attachment->post_title ); the_attachment_link( $attachment->ID , false ); } } ?> ``` I'm not sure if the codex is assuming that you will always have posts so no need to check? I personally always use it, but wonder if someone could enlighten me on if its necessary. When is a right time to use the if statement?
In my opinion we cannot guarantee the post existence in db for a specific query. maybe it returns an empty array. so its best practice to use the conditional statement. plus i think we are dealing with an array so to check the empty array we should use php `empty` function. for example: ``` if ( !empty( $attachments ) ) { foreach ( $attachments as $attachment ) { // do some stuff here. } } else { _e('Sorry! No posts found.'); } ```
240,075
<p>I have a WordPress marketing site (<code>www.example.com</code>) and a backend app site (<code>app.example.com</code>). What I am trying to do is this: if some body goes to the URL:</p> <pre><code>www.example.com/profile/&lt;&lt;profileId&gt;&gt; </code></pre> <p>I want to create a page that has mostly generic content and one <code>iframe</code> with <code>src</code></p> <pre><code>my.example.com/profile/&lt;&lt;profileId&gt;&gt; </code></pre> <p>Now I have 2 problems:</p> <ol> <li>Can a page have dynamic URL? If i try to set the URL to <code>www.example.com/profile/*/</code> it becomes <code>www.example.com/profile/</code></li> <li>If I do get the page to work, how to pass profileId to the <code>iframe src</code>?</li> </ol> <p>Can somebody please direct me to a plugin/solution?</p>
[ { "answer_id": 240079, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 1, "selected": false, "text": "<p><strong>Step 1:</strong></p>\n\n<p>Create a page with slug 'profile' in your WordPress Dashboard.</p>\n\n<p><strong>Step 2</strong></p>\n\n<p>Use this function to register <code>profileId</code> var.</p>\n\n<pre><code>add_filter('query_vars', 'wp233_query_vars');\nfunction wp233_query_vars( $query_vars ){\n $query_vars[] = 'profileId';\n return $query_vars;\n}\n</code></pre>\n\n<p>And add a rewrite rule to wordpress like this:</p>\n\n<pre><code>add_action( 'init', 'wp233_add_rewrite_rules' );\nfunction wp233_add_rewrite_rules() {\n\n add_rewrite_rule(\n '^profile/([^/]+)?$',\n 'index.php?pagename=profile&amp;profileId=$matches[1]',\n 'top');\n\n}\n</code></pre>\n\n<p><strong>Step 3</strong></p>\n\n<p>Now you can access the query var like this:</p>\n\n<pre><code>http://yoursite.com/profile/xxxx/\n</code></pre>\n\n<p>Now you should be able to extract the profileId by hooking in suitable action</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>add_action( 'template_redirect', 'wp233_get_profile_id' );\nfunction wp233_get_profile_id() {\n\n $profile_id = get_query_var( 'profileId' );\n if ( $profile_id ) {\n\n // do some magic work. you now captured the profile id\n // which was passed to url.com/profile/{ID}/ -&gt; here.\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 240080, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>This shouldn't be too difficult. First you have to get the <code>&lt;&lt;profileID&gt;&gt;</code> part of the current page/post. How to get it, depends on what it is and where in your template you are calling it. If, for instance, \"profile\" is a custom post type, then <code>&lt;&lt;profileID&gt;&gt;</code> is the slug of the post, which you could retrieve like this, presumably in <code>single.php</code>:</p>\n\n<pre><code>$profileID = get_post_field( 'post_name', get_post());\n</code></pre>\n\n<p>The rest is straightforward PHP:</p>\n\n<pre><code>echo '&lt;iframe src=\"my.example.com/profile/' . $profileID '/&gt;&lt;/iframe&gt;';\n</code></pre>\n\n<p>Now you have your page with the <code>iframe</code> and you want to display it without the slug. The answer to that is <a href=\"https://wordpress.stackexchange.com/questions/203951/remove-slug-from-custom-post-type-post-urls\">here</a>.</p>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103307/" ]
I have a WordPress marketing site (`www.example.com`) and a backend app site (`app.example.com`). What I am trying to do is this: if some body goes to the URL: ``` www.example.com/profile/<<profileId>> ``` I want to create a page that has mostly generic content and one `iframe` with `src` ``` my.example.com/profile/<<profileId>> ``` Now I have 2 problems: 1. Can a page have dynamic URL? If i try to set the URL to `www.example.com/profile/*/` it becomes `www.example.com/profile/` 2. If I do get the page to work, how to pass profileId to the `iframe src`? Can somebody please direct me to a plugin/solution?
**Step 1:** Create a page with slug 'profile' in your WordPress Dashboard. **Step 2** Use this function to register `profileId` var. ``` add_filter('query_vars', 'wp233_query_vars'); function wp233_query_vars( $query_vars ){ $query_vars[] = 'profileId'; return $query_vars; } ``` And add a rewrite rule to wordpress like this: ``` add_action( 'init', 'wp233_add_rewrite_rules' ); function wp233_add_rewrite_rules() { add_rewrite_rule( '^profile/([^/]+)?$', 'index.php?pagename=profile&profileId=$matches[1]', 'top'); } ``` **Step 3** Now you can access the query var like this: ``` http://yoursite.com/profile/xxxx/ ``` Now you should be able to extract the profileId by hooking in suitable action **Example** ``` add_action( 'template_redirect', 'wp233_get_profile_id' ); function wp233_get_profile_id() { $profile_id = get_query_var( 'profileId' ); if ( $profile_id ) { // do some magic work. you now captured the profile id // which was passed to url.com/profile/{ID}/ -> here. } } ```
240,081
<p>Im wondering if it's possible to add custom post state's to other pages? Like <em>Frontpage</em> and <em>Blog</em></p> <p>I mean the black text: --Voorpagina (<em>Frontpage</em>)<br> <a href="https://i.stack.imgur.com/gjLzi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gjLzi.png" alt="Post State WordPresss"></a></p> <p>I have tried this in functions.php. </p> <pre><code>add_filter('display_post_states', 'wpsites_custom_post_states'); function wpsites_custom_post_states($states) { global $post; if( ('page' == get_post_type($post-&gt;ID) ) &amp;&amp; ( '/themes/Lef-en-Liefde/woningoverzicht.php' == get_page_templ‌​ate_slug( $post-&gt;ID ) ) ) { $states[] = __('Custom state'); } } </code></pre> <p>But then the original post states (frontpage and blog) are gone.</p> <p>Thanks in advance,</p> <p>Gino</p>
[ { "answer_id": 240088, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>Your function doesn't return a value, so you are effectively wiping the existing states.</p>\n<p>Also, this hook passes you the current post as an object, so you can use that instead of the global $post.</p>\n<p>Additionally <code>get_page_templ‌​ate_slug</code> returns a path that is relative to your theme's root, so if your theme directory is called <code>Lef-en-Liefde</code> and the template file placed at the top level of that directory is called <code>woningoverzicht.php</code>, then your condition <code>'/themes/Lef-en-Liefde/woningoverzicht.php' == get_page_templ‌​ate_slug($post-&gt;ID)</code> can never be true.</p>\n<p>So, correcting/changing for those points, this should work:</p>\n<pre><code>add_filter('display_post_states', 'wpse240081_custom_post_states',10,2);\n\nfunction wpse240081_custom_post_states( $states, $post ) { \n \n if ( ( 'page' == get_post_type( $post-&gt;ID ) ) \n &amp;&amp; ( 'woningoverzicht.php' == get_page_templ‌​ate_slug( $post-&gt;ID ) ) ) {\n\n $states[] = __('Custom state'); \n\n } \n\n return $states;\n} \n</code></pre>\n" }, { "answer_id": 304321, "author": "Roland Soós", "author_id": 71112, "author_profile": "https://wordpress.stackexchange.com/users/71112", "pm_score": 1, "selected": false, "text": "<p>Here is how WooCommerce does it:</p>\n\n<pre><code>&lt;?php\nadd_filter( 'display_post_states', 'add_display_post_states', 10, 2 );\n\n/**\n * Add a post display state for special WC pages in the page list table.\n *\n * @param array $post_states An array of post display states.\n * @param WP_Post $post The current post object.\n */\nfunction add_display_post_states( $post_states, $post ) {\n if ( wc_get_page_id( 'shop' ) === $post-&gt;ID ) {\n $post_states['wc_page_for_shop'] = __( 'Shop Page', 'woocommerce' );\n }\n\n if ( wc_get_page_id( 'cart' ) === $post-&gt;ID ) {\n $post_states['wc_page_for_cart'] = __( 'Cart Page', 'woocommerce' );\n }\n\n if ( wc_get_page_id( 'checkout' ) === $post-&gt;ID ) {\n $post_states['wc_page_for_checkout'] = __( 'Checkout Page', 'woocommerce' );\n }\n\n if ( wc_get_page_id( 'myaccount' ) === $post-&gt;ID ) {\n $post_states['wc_page_for_myaccount'] = __( 'My Account Page', 'woocommerce' );\n }\n\n if ( wc_get_page_id( 'terms' ) === $post-&gt;ID ) {\n $post_states['wc_page_for_terms'] = __( 'Terms and Conditions Page', 'woocommerce' );\n }\n\n return $post_states;\n}\n</code></pre>\n" }, { "answer_id": 383920, "author": "WebMat", "author_id": 96285, "author_profile": "https://wordpress.stackexchange.com/users/96285", "pm_score": 1, "selected": false, "text": "<p>If you use that filter in custom plugin, you will need to use the function &quot;get_post_meta&quot; because the function &quot;get_page_templ‌​ate_slug&quot; is not already loaded</p>\n<p>exemple:</p>\n<pre><code>add_filter('display_post_states', 'wpse240081_custom_post_states', 10, 2);\n\nfunction wpse240081_custom_post_states( $states, $post ) {\n \n // if is list page and name template file php...\n if ( ( 'page' == get_post_type( $post-&gt;ID ) ) &amp;&amp; ( 'your-template-name.php' == get_post_meta( $post-&gt;ID, '_wp_page_template', true ) ) ) {\n\n $states[] = __('Custom state');\n }\n\n return $states;\n}\n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103313/" ]
Im wondering if it's possible to add custom post state's to other pages? Like *Frontpage* and *Blog* I mean the black text: --Voorpagina (*Frontpage*) [![Post State WordPresss](https://i.stack.imgur.com/gjLzi.png)](https://i.stack.imgur.com/gjLzi.png) I have tried this in functions.php. ``` add_filter('display_post_states', 'wpsites_custom_post_states'); function wpsites_custom_post_states($states) { global $post; if( ('page' == get_post_type($post->ID) ) && ( '/themes/Lef-en-Liefde/woningoverzicht.php' == get_page_templ‌​ate_slug( $post->ID ) ) ) { $states[] = __('Custom state'); } } ``` But then the original post states (frontpage and blog) are gone. Thanks in advance, Gino
Your function doesn't return a value, so you are effectively wiping the existing states. Also, this hook passes you the current post as an object, so you can use that instead of the global $post. Additionally `get_page_templ‌​ate_slug` returns a path that is relative to your theme's root, so if your theme directory is called `Lef-en-Liefde` and the template file placed at the top level of that directory is called `woningoverzicht.php`, then your condition `'/themes/Lef-en-Liefde/woningoverzicht.php' == get_page_templ‌​ate_slug($post->ID)` can never be true. So, correcting/changing for those points, this should work: ``` add_filter('display_post_states', 'wpse240081_custom_post_states',10,2); function wpse240081_custom_post_states( $states, $post ) { if ( ( 'page' == get_post_type( $post->ID ) ) && ( 'woningoverzicht.php' == get_page_templ‌​ate_slug( $post->ID ) ) ) { $states[] = __('Custom state'); } return $states; } ```
240,089
<p>On my post page I am trying to display list of other posts from the same category of the original post. So far I got this and this does not seem to work:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'article', 'posts_per_page' =&gt; 5, 'post__not_in' =&gt; array( get_the_ID() ), 'category' =&gt; array( get_the_category() ), 'meta_query' =&gt; array( array( 'key' =&gt; 'recommended_article', 'value' =&gt; '1', 'compare' =&gt; '==' ) ) ); $query = new WP_Query( $args ); ?&gt; &lt;?php if( $query-&gt;have_posts() ) : while( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;a class="popup-article-picture" href="&lt;?php the_permalink(); ?&gt;" style="background-image: url('&lt;?php the_post_thumbnail_url(); ?&gt;');"&gt;&lt;/a&gt; &lt;a class="popup-article-title" href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 240110, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 1, "selected": false, "text": "<p>you are trying to query the custom post type called <code>article</code>. are you using default WordPress post categories for post type <code>article</code>? or have registered any custom taxonomy for that post type? i assume you are using default WordPress category for <code>CPT</code>. \nso first step is to get the current category from single page. following function will return categories attached to the post from outside the loop.</p>\n\n<pre><code>get_the_category();\n</code></pre>\n\n<p>it will return an array of term objects. and you have to get the slug from this array to pass in the query.\nlets assume we have only one category assigned for single post.</p>\n\n<pre><code>$category_obj = get_the_category();\n$category = $category_obj[0]-&gt;slug;\n</code></pre>\n\n<p>now you can use that in your related posts query.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'article',\n 'posts_per_page' =&gt; 5,\n 'category' =&gt; $category,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'recommended_article',\n 'value' =&gt; '1',\n 'compare' =&gt; '=='\n )\n )\n );\n $query = new WP_Query( $args );\n</code></pre>\n\n<p>and if you are using custom taxonomy for post type then let us know so we can help you regarding custom taxonomies. </p>\n" }, { "answer_id": 240130, "author": "ERDFX", "author_id": 103317, "author_profile": "https://wordpress.stackexchange.com/users/103317", "pm_score": 3, "selected": true, "text": "<p>I've found an answer:</p>\n\n<pre><code>&lt;?php\n\n $cats = get_the_category();\n $args = array(\n 'post_type' =&gt; 'article',\n 'post__not_in' =&gt; array( get_the_ID() ),\n 'posts_per_page' =&gt; 5,\n 'cat' =&gt; $cats[0]-&gt;term_id,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'recommended_article',\n 'value' =&gt; '1',\n 'compare' =&gt; '=='\n )\n )\n );\n $query = new WP_Query( $args );\n\n?&gt; \n\n&lt;?php if( $query-&gt;have_posts() ) : while( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; \n\n&lt;!--HTML--&gt;\n\n&lt;?php endwhile; endif; wp_reset_postdata(); ?&gt;\n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240089", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103317/" ]
On my post page I am trying to display list of other posts from the same category of the original post. So far I got this and this does not seem to work: ``` <?php $args = array( 'post_type' => 'article', 'posts_per_page' => 5, 'post__not_in' => array( get_the_ID() ), 'category' => array( get_the_category() ), 'meta_query' => array( array( 'key' => 'recommended_article', 'value' => '1', 'compare' => '==' ) ) ); $query = new WP_Query( $args ); ?> <?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?> <a class="popup-article-picture" href="<?php the_permalink(); ?>" style="background-image: url('<?php the_post_thumbnail_url(); ?>');"></a> <a class="popup-article-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endwhile; endif; wp_reset_postdata(); ?> ```
I've found an answer: ``` <?php $cats = get_the_category(); $args = array( 'post_type' => 'article', 'post__not_in' => array( get_the_ID() ), 'posts_per_page' => 5, 'cat' => $cats[0]->term_id, 'meta_query' => array( array( 'key' => 'recommended_article', 'value' => '1', 'compare' => '==' ) ) ); $query = new WP_Query( $args ); ?> <?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?> <!--HTML--> <?php endwhile; endif; wp_reset_postdata(); ?> ```
240,092
<p>I want to change my image size. Large is now 600px wide but I want it to be 800px wide.</p> <p>In many pages I have embedded images like this:</p> <pre><code>&lt;img class="alignnone size-large wp-image-261" src="http://xxxxxxxxxx-600x456.jpg" width="600" height="456" /&gt; </code></pre> <p>I changed the size of large images in the media settings and regenerated the thumbnails. When I embed a new images into a post it works well. But all the old ones need to be updated.</p> <p>I have too many pages to do it by hand. Is there an automatic way to do this?</p>
[ { "answer_id": 240110, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 1, "selected": false, "text": "<p>you are trying to query the custom post type called <code>article</code>. are you using default WordPress post categories for post type <code>article</code>? or have registered any custom taxonomy for that post type? i assume you are using default WordPress category for <code>CPT</code>. \nso first step is to get the current category from single page. following function will return categories attached to the post from outside the loop.</p>\n\n<pre><code>get_the_category();\n</code></pre>\n\n<p>it will return an array of term objects. and you have to get the slug from this array to pass in the query.\nlets assume we have only one category assigned for single post.</p>\n\n<pre><code>$category_obj = get_the_category();\n$category = $category_obj[0]-&gt;slug;\n</code></pre>\n\n<p>now you can use that in your related posts query.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'article',\n 'posts_per_page' =&gt; 5,\n 'category' =&gt; $category,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'recommended_article',\n 'value' =&gt; '1',\n 'compare' =&gt; '=='\n )\n )\n );\n $query = new WP_Query( $args );\n</code></pre>\n\n<p>and if you are using custom taxonomy for post type then let us know so we can help you regarding custom taxonomies. </p>\n" }, { "answer_id": 240130, "author": "ERDFX", "author_id": 103317, "author_profile": "https://wordpress.stackexchange.com/users/103317", "pm_score": 3, "selected": true, "text": "<p>I've found an answer:</p>\n\n<pre><code>&lt;?php\n\n $cats = get_the_category();\n $args = array(\n 'post_type' =&gt; 'article',\n 'post__not_in' =&gt; array( get_the_ID() ),\n 'posts_per_page' =&gt; 5,\n 'cat' =&gt; $cats[0]-&gt;term_id,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'recommended_article',\n 'value' =&gt; '1',\n 'compare' =&gt; '=='\n )\n )\n );\n $query = new WP_Query( $args );\n\n?&gt; \n\n&lt;?php if( $query-&gt;have_posts() ) : while( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; \n\n&lt;!--HTML--&gt;\n\n&lt;?php endwhile; endif; wp_reset_postdata(); ?&gt;\n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240092", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103320/" ]
I want to change my image size. Large is now 600px wide but I want it to be 800px wide. In many pages I have embedded images like this: ``` <img class="alignnone size-large wp-image-261" src="http://xxxxxxxxxx-600x456.jpg" width="600" height="456" /> ``` I changed the size of large images in the media settings and regenerated the thumbnails. When I embed a new images into a post it works well. But all the old ones need to be updated. I have too many pages to do it by hand. Is there an automatic way to do this?
I've found an answer: ``` <?php $cats = get_the_category(); $args = array( 'post_type' => 'article', 'post__not_in' => array( get_the_ID() ), 'posts_per_page' => 5, 'cat' => $cats[0]->term_id, 'meta_query' => array( array( 'key' => 'recommended_article', 'value' => '1', 'compare' => '==' ) ) ); $query = new WP_Query( $args ); ?> <?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?> <!--HTML--> <?php endwhile; endif; wp_reset_postdata(); ?> ```
240,100
<p>i have a theme where first a featured post is displayed. then there is a grid of posts. Problem is grid also displays the featured post. So, featured post appears twice.</p> <p>Question is <strong>how to hide featured post from grid?</strong></p> <p>Note that a custom meta box has been added to mark post/page as featured.</p> <p>loop that starts featured section is as below...</p> <pre><code>if ($featured-&gt;have_posts()): while($featured-&gt;have_posts()): $featured-&gt;the_post(); ?&gt; </code></pre> <p>grid is formed from below code... (i need to hide featured post from this grid)</p> <pre><code>&lt;?php $counter = 1; $grids = 3; global $query_string; query_posts($query_string . '&amp;caller_get_posts=1&amp;posts_per_page=12&amp;cat=-' . get_cat_ID( 'News' )); if(have_posts()) : while(have_posts()) : the_post(); ?&gt; </code></pre>
[ { "answer_id": 240101, "author": "mlimon", "author_id": 64458, "author_profile": "https://wordpress.stackexchange.com/users/64458", "pm_score": -1, "selected": false, "text": "<p><code>caller_get_posts</code> is deprecated since version 3.1!</p>\n\n<p>Use <code>ignore_sticky_posts</code> instead. <a href=\"https://codex.wordpress.org/Sticky_Posts\" rel=\"nofollow noreferrer\">Read More</a></p>\n\n<p>And don't use query_post it's not a good practice, <a href=\"https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts\">When should you use WP_Query vs query_posts() vs get_posts()?</a></p>\n" }, { "answer_id": 240440, "author": "NehaAgra", "author_id": 102538, "author_profile": "https://wordpress.stackexchange.com/users/102538", "pm_score": 1, "selected": true, "text": "<p>wp section of stackexchange really seems half dead.</p>\n\n<p>you rarely get issue sorted.</p>\n\n<p>have_posts checks whether there is any post, so add another condition that checks whether the post is featured or not.</p>\n\n<pre><code>if(have_posts()) : while(have_posts()) : the_post();\n</code></pre>\n\n<p>replace above with below</p>\n\n<pre><code>if(have_posts() &amp;&amp; the_post() != $featured) : while(have_posts()) : the_post(); \n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86147/" ]
i have a theme where first a featured post is displayed. then there is a grid of posts. Problem is grid also displays the featured post. So, featured post appears twice. Question is **how to hide featured post from grid?** Note that a custom meta box has been added to mark post/page as featured. loop that starts featured section is as below... ``` if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post(); ?> ``` grid is formed from below code... (i need to hide featured post from this grid) ``` <?php $counter = 1; $grids = 3; global $query_string; query_posts($query_string . '&caller_get_posts=1&posts_per_page=12&cat=-' . get_cat_ID( 'News' )); if(have_posts()) : while(have_posts()) : the_post(); ?> ```
wp section of stackexchange really seems half dead. you rarely get issue sorted. have\_posts checks whether there is any post, so add another condition that checks whether the post is featured or not. ``` if(have_posts()) : while(have_posts()) : the_post(); ``` replace above with below ``` if(have_posts() && the_post() != $featured) : while(have_posts()) : the_post(); ```
240,134
<p>I've made <strong>my own PHP page</strong> and used it as a part of my WordPress website. I'm using some WordPress functions and want to have it fully integrated with WordPress itself.</p> <p>Although I've loaded WordPress, the Admin Bar is not loading at the top of the page. <strong>It actually doesn't even show in HTML structure</strong> (I tried to search <kbd>Ctrl</kbd>+<kbd>f</kbd> for <em>wpadminbar</em>, no results.)</p> <hr> <p>What I've done -</p> <h3>1. Included WP file</h3> <pre><code>require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php'); </code></pre> <h3>2. Added wp_head();</h3> <p>Right before <code>&lt;/head&gt;</code></p> <h3>2. Added get_header();</h3> <p>Right after <code>&lt;body&gt;</code></p> <h3>3. Added wp_footer();</h3> <p>Right before <code>&lt;/body&gt;</code></p> <hr> <p>Also tried:</p> <h3>show_admin_bar(true);</h3> <h3>get_footer();</h3>
[ { "answer_id": 240152, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>If WordPress is loaded from outside of the main WordPress files using a separate PHP script that includes <code>wp-load.php</code> then the <code>/template-loader.php</code> file will not be loaded and therefore the <code>template_redirect</code> action will not be triggered.</p>\n\n<p>This is important because <code>template_redirect</code> is how the Toolbar is initialized on the front end. Taking a look at <code>default-filters.php</code> we can see where the Toolbar is initialized:</p>\n\n<pre><code>...\n// Admin Bar\n// Don't remove. Wrong way to disable.\nadd_action( 'template_redirect', '_wp_admin_bar_init', 0 ); // &lt;-- initialize Toolbar\nadd_action( 'admin_init', '_wp_admin_bar_init' ); // &lt;-- initialize Toolbar\nadd_action( 'before_signup_header', '_wp_admin_bar_init' ); // &lt;-- initialize Toolbar\nadd_action( 'activate_header', '_wp_admin_bar_init' ); // &lt;-- initialize Toolbar\nadd_action( 'wp_footer', 'wp_admin_bar_render', 1000 );\nadd_action( 'in_admin_header', 'wp_admin_bar_render', 0 );\n...\n</code></pre>\n\n<p>A function can be added via plugin or theme to trigger the initialization of the Toolbar:</p>\n\n<pre><code>function wpse240134_wp_admin_bar_init() {\n _wp_admin_bar_init();\n}\nadd_action( 'init', 'wpse240134_wp_admin_bar_init' );\n</code></pre>\n\n<p><em>Note that <code>_wp_admin_bar_init()</code> is considered an internal function for WordPress so use it at your own risk.</em></p>\n\n<p>It's also worth noting that if WordPress is being loaded from an external PHP file by including <code>wp-blog-header.php</code> and the <code>WP_USE_THEMES</code> constant is set to <code>false</code>, the <code>template_redirect</code> hook will again not be fired, so the <code>wpse240134_wp_admin_bar_init()</code> function above can be used to get the admin bar to show up when <code>WP_USE_THEMES</code> is set to <code>false</code>:</p>\n\n<pre><code>&lt;?php\n/**\n * Demonstration of loading WordPress from an external PHP file.\n * \n */\ndefine('WP_USE_THEMES', false);\n\n// https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files\n//require ('./wp-load.php');\n\nrequire ('./wp-blog-header.php');\n\n?&gt;&lt;!DOCTYPE html&gt;\n&lt;html class=\"no-js\" &lt;?php language_attributes(); ?&gt;&gt;\n&lt;head&gt;\n &lt;meta charset=\"&lt;?php bloginfo( 'charset' ); ?&gt;\"&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n &lt;link rel=\"profile\" href=\"http://gmpg.org/xfn/11\"&gt;\n &lt;link rel=\"pingback\" href=\"&lt;?php bloginfo( 'pingback_url' ); ?&gt;\"&gt;\n\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n\n&lt;body id=\"body\" &lt;?php body_class(); ?&gt;&gt;\n &lt;div id=\"page\" class=\"site\"&gt;\n &lt;header id=\"header\" class=\"site-header\"&gt;&lt;/header&gt;\n\n &lt;div id=\"content\" class=\"site-content\"&gt;\n &lt;h1&gt;Test of loading WordPress from external PHP file&lt;/h1&gt;\n &lt;/div&gt;\n\n &lt;footer id=\"footer\" class=\"site-footer\"&gt;&lt;/footer&gt;\n &lt;/div&gt;\n&lt;?php wp_footer(); ?&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>More details on loading WP using an external PHP file: <a href=\"https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files\">What is the correct way to use wordpress functions outside wordpress files?</a></p>\n" }, { "answer_id": 295333, "author": "ejntaylor", "author_id": 38077, "author_profile": "https://wordpress.stackexchange.com/users/38077", "pm_score": 0, "selected": false, "text": "<p>I really like Dave Romseys answer, but I think it can be a bit leaner if you solely want the admin bar (as per original question).</p>\n\n<p>Inside wp-blog-header.php you will find the following:</p>\n\n<pre><code> do_action( 'template_redirect' );\n</code></pre>\n\n<p>If you add that to your custom php applications header you will get the admin bar. I was getting a 404 template when using Dave's method, so this may work better for you.</p>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101670/" ]
I've made **my own PHP page** and used it as a part of my WordPress website. I'm using some WordPress functions and want to have it fully integrated with WordPress itself. Although I've loaded WordPress, the Admin Bar is not loading at the top of the page. **It actually doesn't even show in HTML structure** (I tried to search `Ctrl`+`f` for *wpadminbar*, no results.) --- What I've done - ### 1. Included WP file ``` require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php'); ``` ### 2. Added wp\_head(); Right before `</head>` ### 2. Added get\_header(); Right after `<body>` ### 3. Added wp\_footer(); Right before `</body>` --- Also tried: ### show\_admin\_bar(true); ### get\_footer();
If WordPress is loaded from outside of the main WordPress files using a separate PHP script that includes `wp-load.php` then the `/template-loader.php` file will not be loaded and therefore the `template_redirect` action will not be triggered. This is important because `template_redirect` is how the Toolbar is initialized on the front end. Taking a look at `default-filters.php` we can see where the Toolbar is initialized: ``` ... // Admin Bar // Don't remove. Wrong way to disable. add_action( 'template_redirect', '_wp_admin_bar_init', 0 ); // <-- initialize Toolbar add_action( 'admin_init', '_wp_admin_bar_init' ); // <-- initialize Toolbar add_action( 'before_signup_header', '_wp_admin_bar_init' ); // <-- initialize Toolbar add_action( 'activate_header', '_wp_admin_bar_init' ); // <-- initialize Toolbar add_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); add_action( 'in_admin_header', 'wp_admin_bar_render', 0 ); ... ``` A function can be added via plugin or theme to trigger the initialization of the Toolbar: ``` function wpse240134_wp_admin_bar_init() { _wp_admin_bar_init(); } add_action( 'init', 'wpse240134_wp_admin_bar_init' ); ``` *Note that `_wp_admin_bar_init()` is considered an internal function for WordPress so use it at your own risk.* It's also worth noting that if WordPress is being loaded from an external PHP file by including `wp-blog-header.php` and the `WP_USE_THEMES` constant is set to `false`, the `template_redirect` hook will again not be fired, so the `wpse240134_wp_admin_bar_init()` function above can be used to get the admin bar to show up when `WP_USE_THEMES` is set to `false`: ``` <?php /** * Demonstration of loading WordPress from an external PHP file. * */ define('WP_USE_THEMES', false); // https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files //require ('./wp-load.php'); require ('./wp-blog-header.php'); ?><!DOCTYPE html> <html class="no-js" <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <?php wp_head(); ?> </head> <body id="body" <?php body_class(); ?>> <div id="page" class="site"> <header id="header" class="site-header"></header> <div id="content" class="site-content"> <h1>Test of loading WordPress from external PHP file</h1> </div> <footer id="footer" class="site-footer"></footer> </div> <?php wp_footer(); ?> </body> </html> ``` More details on loading WP using an external PHP file: [What is the correct way to use wordpress functions outside wordpress files?](https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files)
240,137
<p>Edit:</p> <p>In a plugin I am developing, I need to store payments, IPN and transactions for customers in both frontend and backend. However I am concerned that the admin will use his actions power to delete the transactions or financial data from site which has bad implications.</p> <h3>Question</h3> <p>How can I prevent the admin from deleting payments/financial data in a way that ensures that I'm not trying to restrict admins too much, but also takes customer information and financial data as high priority. I'm not asking what's the better way for me to do it? But rather asking what's the better way for WordPress community (as administration, as a customer) as I am trying to avoid future complaints about the way implemented to do this action.</p> <p><strong>What I currently have</strong></p> <pre><code>/** * Constructor */ public function __construct() { // Do not allow payments and transactions to be trashed add_action( 'wp_trash_post', array( $this, 'disable_trash' ) ); add_action( 'before_delete_post', array( $this, 'disable_trash' ) ); } /** * Disable trash */ public function disable_trash( $post_id ) { global $post_type; if ( in_array( $post_type, array( 'payment', 'transaction' ) ) ) { wp_die( __( 'You are not allowed to trash payments or transactions.', 'xxx' ) ); } } </code></pre>
[ { "answer_id": 240180, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>A better way to prevent deletion would be to disable that <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">capability</a> for all roles. When you <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register your post types</a> 'payment' and 'transaction' also define a <code>capability_type</code> with the same name as your post type. This will give you capabilities <code>read_payment</code>, <code>edit_payment</code> and <code>delete_payment</code> (same for transaction).</p>\n\n<p>You can then deny this capability on roles in this way:</p>\n\n<pre><code>$wp_roles-&gt;remove_cap( 'editor', 'delete_payment' );\n$wp_roles-&gt;remove_cap( 'admin', 'delete_payment' );\n</code></pre>\n\n<p>Always beware that since admins can edit code on your site, they will still be able to circumvent the deletion, unless you block code editing in the backend and restrict ftp and database access. Also <a href=\"https://wordpress.stackexchange.com/questions/1665/getting-a-list-of-currently-available-roles-on-a-wordpress-site\">read this discussion</a> on getting all available roles.</p>\n" }, { "answer_id": 240198, "author": "Venkatesh Munna", "author_id": 103392, "author_profile": "https://wordpress.stackexchange.com/users/103392", "pm_score": 0, "selected": false, "text": "<p>I used this code in a website , where we can hide edit, trash, view buttons even in bulk edit drop-down, </p>\n\n<pre><code>if(!current_user_can('administrator')) //not an admin\n{\n add_filter( 'post_row_actions', 'remove_row_actions', 10, 1 );\n function remove_row_actions( $actions )\n {\n if( get_post_type() === 'post' ) {\n unset( $actions['edit'] );\n unset( $actions['view'] );\n unset( $actions['trash'] );\n unset( $actions['inline hide-if-no-js'] );\n }\n return $actions;\n }\n}\n\nif(!current_user_can('administrator'))//not and admin\n{\n global $pagenow;\n if ( 'post.php' == $pagenow || 'post-new.php' == $pagenow ) {\n add_action( 'admin_head', 'wpse_125800_custom_publish_box' );\n function wpse_125800_custom_publish_box() {\n $style = '';\n $style .= '&lt;style type=\"text/css\"&gt;';\n $style .= '#delete-action, .bulkactions';\n $style .= '{display: none; }';\n $style .= '&lt;/style&gt;';\n\n echo $style;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 240210, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Here's another approach using the <code>map_meta_cap</code> filter that's applied within the <a href=\"https://developer.wordpress.org/reference/functions/map_meta_cap/\" rel=\"noreferrer\"><code>map_meta_cap()</code></a> function within the <code>has_cap()</code> method of the <code>WP_User</code> class (<em>PHP 5.4+</em>):</p>\n\n<pre><code>add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args )\n{\n // Nothing to do\n if( 'delete_post' !== $cap || empty( $args[0] ) )\n return $caps;\n\n // Target the payment and transaction post types\n if( in_array( get_post_type( $args[0] ), [ 'payment', 'transaction' ], true ) )\n $caps[] = 'do_not_allow'; \n\n return $caps; \n}, 10, 4 );\n</code></pre>\n\n<p>where we target the <em>delete_post</em> meta capability and the <code>payment</code> and <code>transaction</code> custom post types.</p>\n\n<p>As far as I understand and skimming through the <a href=\"https://developer.wordpress.org/reference/functions/get_post_type_capabilities/\" rel=\"noreferrer\"><code>get_post_type_capabilities()</code></a> function we don't need the <code>map_meta_cap</code> argument set as true, in the <code>register_post_type</code> settings, to target the <code>delete_post</code> meta capability. </p>\n\n<p><em>ps:</em>\n<em><a href=\"https://wordpress.stackexchange.com/questions/1684/what-is-the-use-of-map-meta-cap-filter\">Here</a> are some good descriptions of the <code>map_meta_cap</code> filter and helpful examples by Justin Tadlock <a href=\"http://justintadlock.com/archives/2010/07/10/meta-capabilities-for-custom-post-types\" rel=\"noreferrer\">here</a> and Toscho <a href=\"https://wordpress.stackexchange.com/a/53234/26350\">here</a></em>. <em><a href=\"https://wordpress.stackexchange.com/questions/192366/make-certain-pages-uneditable-by-editors/192374#192374\">Here</a> I found an old example that I had forgot I wrote, that we could also adjust to avoid trash/delete on some given pages and user roles.</em> <em><a href=\"https://wordpress.stackexchange.com/a/58292/26350\">Here's</a> an answer by TheDeadMedic that links to an <a href=\"https://stackoverflow.com/questions/3235257/wordpress-disable-add-new-on-custom-post-type/16675677#16675677\">answer</a> by Seamus Leahy regarding <code>register_post_type</code> approach. \n<a href=\"https://wordpress.stackexchange.com/search?q=do_not_allow%20map_meta_cap\">Here</a> are some more examples on this site. Hope it helps!</em></p>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240137", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102371/" ]
Edit: In a plugin I am developing, I need to store payments, IPN and transactions for customers in both frontend and backend. However I am concerned that the admin will use his actions power to delete the transactions or financial data from site which has bad implications. ### Question How can I prevent the admin from deleting payments/financial data in a way that ensures that I'm not trying to restrict admins too much, but also takes customer information and financial data as high priority. I'm not asking what's the better way for me to do it? But rather asking what's the better way for WordPress community (as administration, as a customer) as I am trying to avoid future complaints about the way implemented to do this action. **What I currently have** ``` /** * Constructor */ public function __construct() { // Do not allow payments and transactions to be trashed add_action( 'wp_trash_post', array( $this, 'disable_trash' ) ); add_action( 'before_delete_post', array( $this, 'disable_trash' ) ); } /** * Disable trash */ public function disable_trash( $post_id ) { global $post_type; if ( in_array( $post_type, array( 'payment', 'transaction' ) ) ) { wp_die( __( 'You are not allowed to trash payments or transactions.', 'xxx' ) ); } } ```
Here's another approach using the `map_meta_cap` filter that's applied within the [`map_meta_cap()`](https://developer.wordpress.org/reference/functions/map_meta_cap/) function within the `has_cap()` method of the `WP_User` class (*PHP 5.4+*): ``` add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) { // Nothing to do if( 'delete_post' !== $cap || empty( $args[0] ) ) return $caps; // Target the payment and transaction post types if( in_array( get_post_type( $args[0] ), [ 'payment', 'transaction' ], true ) ) $caps[] = 'do_not_allow'; return $caps; }, 10, 4 ); ``` where we target the *delete\_post* meta capability and the `payment` and `transaction` custom post types. As far as I understand and skimming through the [`get_post_type_capabilities()`](https://developer.wordpress.org/reference/functions/get_post_type_capabilities/) function we don't need the `map_meta_cap` argument set as true, in the `register_post_type` settings, to target the `delete_post` meta capability. *ps:* *[Here](https://wordpress.stackexchange.com/questions/1684/what-is-the-use-of-map-meta-cap-filter) are some good descriptions of the `map_meta_cap` filter and helpful examples by Justin Tadlock [here](http://justintadlock.com/archives/2010/07/10/meta-capabilities-for-custom-post-types) and Toscho [here](https://wordpress.stackexchange.com/a/53234/26350)*. *[Here](https://wordpress.stackexchange.com/questions/192366/make-certain-pages-uneditable-by-editors/192374#192374) I found an old example that I had forgot I wrote, that we could also adjust to avoid trash/delete on some given pages and user roles.* *[Here's](https://wordpress.stackexchange.com/a/58292/26350) an answer by TheDeadMedic that links to an [answer](https://stackoverflow.com/questions/3235257/wordpress-disable-add-new-on-custom-post-type/16675677#16675677) by Seamus Leahy regarding `register_post_type` approach. [Here](https://wordpress.stackexchange.com/search?q=do_not_allow%20map_meta_cap) are some more examples on this site. Hope it helps!*
240,138
<p>i m creating a AJAX live search to filter posts title in my wordpress theme. As i write something in input it show all the post in result, Not filtering it to get custom post..</p> <p><strong>How to search live and find a post with AJAX??</strong></p> <p><strong>Function.php</strong></p> <pre><code>&lt;?php add_action('wp_ajax_my_action' , 'data_fetch'); add_action('wp_ajax_nopriv_my_action','data_fetch'); function data_fetch(){ $the_query = new WP_Query(array('post_per_page'=&gt;5)); if( $the_query-&gt;have_posts() ) : while( $the_query-&gt;have_posts() ): $the_query-&gt;the_post(); ?&gt; &lt;h2&gt;&lt;a href="&lt;?php echo esc_url( post_permalink() ); ?&gt;"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php endwhile; wp_reset_postdata(); endif; die(); }?&gt; </code></pre> <p><strong>Script:</strong></p> <pre><code>&lt;script&gt; function fetch(){ $.post('&lt;?php echo admin_url('admin-ajax.php'); ?&gt;',{'action':'my_action'}, function(response){ $('#datafetch').append(response); console.log(result); }); } &lt;/script&gt; </code></pre> <p><strong>HTML:</strong></p> <pre><code>&lt;input type="text" onkeyup="fetch()"&gt;&lt;/input&gt; &lt;div id="datafetch"&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 240143, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 6, "selected": true, "text": "<p>Here is a working solution (tested as is)</p>\n<p><strong>The HTML (could be part of page content)</strong></p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;keyword&quot; id=&quot;keyword&quot; onkeyup=&quot;fetch()&quot;&gt;&lt;/input&gt;\n\n&lt;div id=&quot;datafetch&quot;&gt;Search results will appear here&lt;/div&gt;\n</code></pre>\n<p><strong>The JavaScript ( goes to your theme's functions.php )</strong></p>\n<pre><code>// add the ajax fetch js\nadd_action( 'wp_footer', 'ajax_fetch' );\nfunction ajax_fetch() {\n?&gt;\n&lt;script type=&quot;text/javascript&quot;&gt;\nfunction fetch(){\n\n jQuery.ajax({\n url: '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;',\n type: 'post',\n data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },\n success: function(data) {\n jQuery('#datafetch').html( data );\n }\n });\n\n}\n&lt;/script&gt;\n\n&lt;?php\n}\n</code></pre>\n<p><strong>And finally the AJAX call</strong> goes to your theme's functions.php</p>\n<pre><code>// the ajax function\nadd_action('wp_ajax_data_fetch' , 'data_fetch');\nadd_action('wp_ajax_nopriv_data_fetch','data_fetch');\nfunction data_fetch(){\n\n $the_query = new WP_Query( array( 'posts_per_page' =&gt; -1, 's' =&gt; esc_attr( $_POST['keyword'] ), 'post_type' =&gt; 'post' ) );\n if( $the_query-&gt;have_posts() ) :\n while( $the_query-&gt;have_posts() ): $the_query-&gt;the_post(); ?&gt;\n \n &lt;h2&gt;&lt;a href=&quot;&lt;?php echo esc_url( get_permalink() ); ?&gt;&quot;&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h2&gt;\n\n &lt;?php endwhile;\n wp_reset_postdata(); \n endif;\n\n die();\n}\n</code></pre>\n<p>Addition:\nHere's how I made my AJAX function search precisely:</p>\n<pre><code>// the ajax function\nadd_action('wp_ajax_data_fetch' , 'data_fetch');\nadd_action('wp_ajax_nopriv_data_fetch','data_fetch');\nfunction data_fetch(){\n\n $the_query = new WP_Query( \n array( \n 'posts_per_page' =&gt; -1, \n 's' =&gt; esc_attr( $_POST['keyword'] ), \n 'post_type' =&gt; 'post' \n ) \n );\n\n\n if( $the_query-&gt;have_posts() ) :\n while( $the_query-&gt;have_posts() ): $the_query-&gt;the_post();\n\n$myquery = esc_attr( $_POST['keyword'] );\n$a = $myquery;\n$search = get_the_title();\nif( stripos(&quot;/{$search}/&quot;, $a) !== false) {?&gt;\n &lt;h4&gt;&lt;a href=&quot;&lt;?php echo esc_url( get_permalink() ); ?&gt;&quot;&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h4&gt;\n &lt;?php\n }\n endwhile;\n wp_reset_postdata(); \n endif;\n\n die();\n}\n</code></pre>\n" }, { "answer_id": 240148, "author": "Kings", "author_id": 103348, "author_profile": "https://wordpress.stackexchange.com/users/103348", "pm_score": -1, "selected": false, "text": "<p>i have been using this plugin :</p>\n\n<p>ajax-search-pro-for-wordpress-live-search-plugin</p>\n\n<p>it is the best plugin</p>\n\n<p>and you can do this in 5 seconds using this.</p>\n\n<p>i have used this plugin in my many Projects.</p>\n" }, { "answer_id": 326903, "author": "Sanjay Parmar", "author_id": 160017, "author_profile": "https://wordpress.stackexchange.com/users/160017", "pm_score": 0, "selected": false, "text": "<pre><code>/* Filled in admin profile */\nadd_action( 'show_user_profile', 'extra_user_profile_fields' );\nadd_action( 'edit_user_profile', 'extra_user_profile_fields' );\nfunction extra_user_profile_fields( $user ) { ?&gt;\n &lt;h3&gt;&lt;?php _e(\"Extra profile information\", \"blank\"); ?&gt;&lt;/h3&gt;\n\n &lt;table class=\"form-table\"&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=\"address\"&gt;&lt;?php _e(\"Address\"); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"postSearch\" id=\"postSearch\" value=\"&lt;?php echo esc_attr( get_the_author_meta( 'postSearch', $user-&gt;ID ) ); ?&gt;\" class=\"regular-text\" /&gt;&lt;br /&gt;\n &lt;span class=\"description\"&gt;&lt;?php _e(\"Please enter your address.\"); ?&gt;&lt;/span&gt;\n &lt;div id=\"datafetch\"&gt;&lt;/div&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;?php }\n\n\n// the jQuery Ajax call here\nadd_action( 'admin_footer', 'ajax_fetch' );\nfunction ajax_fetch() {\n?&gt;\n&lt;script type=\"text/javascript\"&gt;\n\n (function($){\n var searchRequest = null;\n\n jQuery(function () {\n var minlength = 3;\n\n jQuery(\"#postSearch\").keyup(function () {\n var that = this,\n value = jQuery(this).val();\n\n if (value.length &gt;= minlength ) {\n if (searchRequest != null) \n searchRequest.abort();\n searchRequest = jQuery.ajax({\n type: \"POST\",\n url: \"&lt;?php echo admin_url('admin-ajax.php'); ?&gt;\",\n data: {\n\n action: 'data_fetch',\n search_keyword : value\n\n },\n dataType: \"html\",\n success: function(data){\n //we need to check if the value is the same\n if (value==jQuery(that).val()) {\n jQuery('#datafetch').html(data);\n }\n }\n });\n }\n });\n });\n }(jQuery));\n&lt;/script&gt;\n\n&lt;?php\n}\n\n\n// the ajax function\nadd_action('wp_ajax_data_fetch' , 'data_fetch');\nadd_action('wp_ajax_nopriv_data_fetch','data_fetch');\nfunction data_fetch(){\n\n $the_query = new WP_Query( array( 'posts_per_page' =&gt; -1, 's' =&gt; esc_attr( $_POST['search_keyword'] ), 'post_type' =&gt; 'post' ) );\n if( $the_query-&gt;have_posts() ) :\n while( $the_query-&gt;have_posts() ): $the_query-&gt;the_post(); ?&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php echo esc_url( post_permalink() ); ?&gt;\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php endwhile;\n wp_reset_postdata(); \n endif;\n\n die(); \n}\n</code></pre>\n" }, { "answer_id": 349898, "author": "nier", "author_id": 150801, "author_profile": "https://wordpress.stackexchange.com/users/150801", "pm_score": 2, "selected": false, "text": "<p>You forget to call it in as searchinput, you can paste below code in <em>functions.php</em></p>\n\n<pre><code>// the ajax function\nadd_action('wp_ajax_data_fetch' , 'data_fetch');\nadd_action('wp_ajax_nopriv_data_fetch','data_fetch');\nfunction data_fetch(){\n\n $the_query = new WP_Query( array( 'posts_per_page' =&gt; 5, 's' =&gt; esc_attr( $_POST['keyword'] ), 'post_type' =&gt; 'post' ) );\n if( $the_query-&gt;have_posts() ) :\n while( $the_query-&gt;have_posts() ): $the_query-&gt;the_post(); ?&gt;\n\n &lt;a href=\"&lt;?php echo esc_url( post_permalink() ); ?&gt;\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;\n\n &lt;?php endwhile;\n wp_reset_postdata(); \n else: \n echo '&lt;h3&gt;No Results Found&lt;/h3&gt;';\n endif;\n die();\n }\n\n // add the ajax fetch js\n add_action( 'wp_footer', 'ajax_fetch' );\n function ajax_fetch() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n function fetchResults(){\n var keyword = jQuery('#searchInput').val();\n if(keyword == \"\"){\n jQuery('#datafetch').html(\"\");\n } else {\n jQuery.ajax({\n url: '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;',\n type: 'post',\n data: { action: 'data_fetch', keyword: keyword },\n success: function(data) {\n jQuery('#datafetch').html( data );\n }\n });\n }\n\n }\n &lt;/script&gt;\n\n &lt;?php\n }\n</code></pre>\n\n<p>Once you have done, find and open <em>searchform.php</em>. Now what you have to do, replace id element with above id element(searchInput) and add this code </p>\n\n<pre><code>onkeyup=featechResult()\"\n</code></pre>\n\n<p>Next to id element, so overall code will look like this</p>\n\n<pre><code> &lt;form method=\"get\" class=\"td-search-form-widget\" action=\"&lt;?php echo esc_url(home_url( '/' )); ?&gt;\"&gt;\n &lt;div role=\"search\"&gt;\n &lt;input class=\"td-widget-search-input\" type=\"text\" value=\"&lt;?php echo get_search_query(); ?&gt;\" name=\"s\" id=\"searchInput\" onkeyup=\"fetchResults()\" /&gt;&lt;input class=\"wpb_button wpb_btn-inverse btn\" type=\"submit\" id=\"searchsubmit\" value=\"&lt;?php _etd('Search', TD_THEME_NAME)?&gt;\" /&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Make sure you do changes in the child theme.\nNow last step: add <code>&lt;div id=\"datafeatch\"&gt;&lt;/div&gt;</code> just above of and you can see live search in your search form.</p>\n\n<p>You can also do this via <a href=\"https://www.mediumtalk.net/wordpress-live-search-plugins/\" rel=\"nofollow noreferrer\">live search plugin</a>, an easiest way to do if don't know how to code. I hope it helps.</p>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240138", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97572/" ]
i m creating a AJAX live search to filter posts title in my wordpress theme. As i write something in input it show all the post in result, Not filtering it to get custom post.. **How to search live and find a post with AJAX??** **Function.php** ``` <?php add_action('wp_ajax_my_action' , 'data_fetch'); add_action('wp_ajax_nopriv_my_action','data_fetch'); function data_fetch(){ $the_query = new WP_Query(array('post_per_page'=>5)); if( $the_query->have_posts() ) : while( $the_query->have_posts() ): $the_query->the_post(); ?> <h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2> <?php endwhile; wp_reset_postdata(); endif; die(); }?> ``` **Script:** ``` <script> function fetch(){ $.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'}, function(response){ $('#datafetch').append(response); console.log(result); }); } </script> ``` **HTML:** ``` <input type="text" onkeyup="fetch()"></input> <div id="datafetch"> </div> ```
Here is a working solution (tested as is) **The HTML (could be part of page content)** ``` <input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input> <div id="datafetch">Search results will appear here</div> ``` **The JavaScript ( goes to your theme's functions.php )** ``` // add the ajax fetch js add_action( 'wp_footer', 'ajax_fetch' ); function ajax_fetch() { ?> <script type="text/javascript"> function fetch(){ jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val() }, success: function(data) { jQuery('#datafetch').html( data ); } }); } </script> <?php } ``` **And finally the AJAX call** goes to your theme's functions.php ``` // the ajax function add_action('wp_ajax_data_fetch' , 'data_fetch'); add_action('wp_ajax_nopriv_data_fetch','data_fetch'); function data_fetch(){ $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) ); if( $the_query->have_posts() ) : while( $the_query->have_posts() ): $the_query->the_post(); ?> <h2><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title();?></a></h2> <?php endwhile; wp_reset_postdata(); endif; die(); } ``` Addition: Here's how I made my AJAX function search precisely: ``` // the ajax function add_action('wp_ajax_data_fetch' , 'data_fetch'); add_action('wp_ajax_nopriv_data_fetch','data_fetch'); function data_fetch(){ $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) ); if( $the_query->have_posts() ) : while( $the_query->have_posts() ): $the_query->the_post(); $myquery = esc_attr( $_POST['keyword'] ); $a = $myquery; $search = get_the_title(); if( stripos("/{$search}/", $a) !== false) {?> <h4><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title();?></a></h4> <?php } endwhile; wp_reset_postdata(); endif; die(); } ```
240,149
<p>I have a custom field on a WooCommerce product, and I am entering the ID of another product into it. When saving that product, I am adding a meta field to the product that was inputted, creating a "link" between them. I have this working fine, but the issue is that it adds it even it is already there. </p> <pre><code>function part_fits($post_id){ global $post; global $product; $current_diagram_id = get_the_ID(); if( have_rows('product_association') ): while( have_rows('product_association') ): the_row(); $single_part_id = get_sub_field('part'); add_post_meta($single_part_id, 'part_fits', $current_diagram_id); endwhile; endif; } </code></pre> <p>Is there a way I can check if that exact key and value already exists and only add it if it does not?</p>
[ { "answer_id": 240150, "author": "Ahmed Fouad", "author_id": 102371, "author_profile": "https://wordpress.stackexchange.com/users/102371", "pm_score": 3, "selected": true, "text": "<p>It looks like you need to use <code>update_post_meta()</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/update_post_meta\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/update_post_meta</a></p>\n\n<p><strong>Source: WP Codex</strong></p>\n\n<p>The function update_post_meta() updates the value of an existing meta key (custom field) for the specified post.</p>\n\n<p><strong>This may be used in place of add_post_meta() function.</strong> The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned.</p>\n\n<p>Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. It also returns false if the value submitted is the same as the value that is already in the database.</p>\n" }, { "answer_id": 323597, "author": "Matt Sims", "author_id": 65888, "author_profile": "https://wordpress.stackexchange.com/users/65888", "pm_score": 2, "selected": false, "text": "<p><code>add_post_meta()</code> has an optional fourth parameter <code>$unique</code> – when this is set to <code>true</code>, the custom field will not be added if the given key already exists among custom fields of the specified post.</p>\n\n<p>The function will return <code>false</code> if the <code>$unique</code> argument was set to <code>true</code> and a custom field with the given key already exists.</p>\n" }, { "answer_id": 337976, "author": "Kerry Randolph", "author_id": 163132, "author_profile": "https://wordpress.stackexchange.com/users/163132", "pm_score": 0, "selected": false, "text": "<p>I would use the $product->meta_exists function, like this:</p>\n\n<pre><code>if( !$product-&gt;meta_exists( $key ) ) {\n if( $new_val !== $existing_val ) {\n $product-&gt;update_meta_data( $key, $new_val );\n }\n}\n</code></pre>\n\n<p>p.s. Don't forget to save changes:</p>\n\n<pre><code>$product-&gt;save_meta_data();\n</code></pre>\n" }, { "answer_id": 366688, "author": "John White", "author_id": 188143, "author_profile": "https://wordpress.stackexchange.com/users/188143", "pm_score": 0, "selected": false, "text": "<p>That one sentence:</p>\n\n<ul>\n<li>\"It also returns false if the value submitted is the same as the value that is already in the database.\"</li>\n</ul>\n\n<p>...is incredibly important (thanks Ahmed Fouad), because it is entirely counter-intuitive! You would reasonably expect an update of the database to return success (true) when the action is not a genuine failure. But here Wordpress gives failure (false) when the data is unchanged. This had me fooled completely, because it is NOT mentioned in the codex, except in the contributed notes!</p>\n\n<p>Would you not expect \"failure\" to mean failure to reach the database?</p>\n\n<p>As a result I am using a short function to wrap up the problem:</p>\n\n<pre><code>function check_update_post_meta( $postid, $key, $value ) {\n // Get the single/first value of this key in this post's meta\n $response = get_post_meta( $postid, $key, true );\n if ($response == $value) {\n // If the value is already set return true\n return true;\n } else {\n // Replace the old value with the new, or add a key into the db\n $response = update_post_meta( $postid, $key, $value );\n }\n return $response;\n // Now 'false' means a failure to reach the database\n // Now 'true' means the data now exists in the database without or with changes\n // A return int&gt;0 means a new record with this ID was added\n // Note: It's not possible that the ID=1 when calling this function from within a post.\n}\n</code></pre>\n" } ]
2016/09/21
[ "https://wordpress.stackexchange.com/questions/240149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103352/" ]
I have a custom field on a WooCommerce product, and I am entering the ID of another product into it. When saving that product, I am adding a meta field to the product that was inputted, creating a "link" between them. I have this working fine, but the issue is that it adds it even it is already there. ``` function part_fits($post_id){ global $post; global $product; $current_diagram_id = get_the_ID(); if( have_rows('product_association') ): while( have_rows('product_association') ): the_row(); $single_part_id = get_sub_field('part'); add_post_meta($single_part_id, 'part_fits', $current_diagram_id); endwhile; endif; } ``` Is there a way I can check if that exact key and value already exists and only add it if it does not?
It looks like you need to use `update_post_meta()` <https://codex.wordpress.org/Function_Reference/update_post_meta> **Source: WP Codex** The function update\_post\_meta() updates the value of an existing meta key (custom field) for the specified post. **This may be used in place of add\_post\_meta() function.** The first thing this function will do is make sure that $meta\_key already exists on $post\_id. If it does not, add\_post\_meta($post\_id, $meta\_key, $meta\_value) is called instead and its result is returned. Returns meta\_id if the meta doesn't exist, otherwise returns true on success and false on failure. It also returns false if the value submitted is the same as the value that is already in the database.
240,189
<p>I want to seperate my Option-Page functions and functions.php.<br> Therefore i moved Option-Page functions to another file "includes/options.php".<br> Including the file with require_once("includes/options.php") does not work <strong>anymore</strong> (I am absolutely sure that it worked in past), but require_once("includes/options.inc") is working.<br> When should i use *.inc files and when *.php files?<br> Especially when theme or plugin developing. </p> <p>I have done same as here: <a href="https://wordpress.stackexchange.com/questions/1403/organizing-code-in-your-wordpress-themes-functions-php-file/1406#1406">Organizing Code in your WordPress Theme&#39;s functions.php File?</a></p>
[ { "answer_id": 240199, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Never use relative paths to include PHP files, you just have no real idea relative to what it will end up being. Always find the location of your theme file by doing something like <code>$rootdir = dirname(__FILE__)</code> from your functions.php, and then use <code>include($rootdir.'/includes/options.php')</code></p>\n" }, { "answer_id": 240228, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 1, "selected": true, "text": "<p>If you are editing theme files use <code>get_template_directory</code> to retrieve the php files. try the code below in your <code>functions.php</code> file.</p>\n\n<pre><code>require get_template_directory() . '/includes/option.php';\n</code></pre>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240189", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103388/" ]
I want to seperate my Option-Page functions and functions.php. Therefore i moved Option-Page functions to another file "includes/options.php". Including the file with require\_once("includes/options.php") does not work **anymore** (I am absolutely sure that it worked in past), but require\_once("includes/options.inc") is working. When should i use \*.inc files and when \*.php files? Especially when theme or plugin developing. I have done same as here: [Organizing Code in your WordPress Theme's functions.php File?](https://wordpress.stackexchange.com/questions/1403/organizing-code-in-your-wordpress-themes-functions-php-file/1406#1406)
If you are editing theme files use `get_template_directory` to retrieve the php files. try the code below in your `functions.php` file. ``` require get_template_directory() . '/includes/option.php'; ```
240,206
<p>I currently have this custom query which I am trying to filter the product (paintings) by artist.</p> <pre><code> $artistID = $_GET['artist_id']; $args = array( 'post_type' =&gt; 'product', 'meta_query' =&gt; array( array( 'key' =&gt; 'artist', 'value' =&gt; $artistID ) ) ); $loop = new WP_Query( $args ); </code></pre> <p>It isn't working at the moment... </p> <p>When I run </p> <pre><code>var_dump(get_post_meta(get_the_ID())); </code></pre> <p>It outputs the following (interested in the artist key)... Can anyone help me write a query to only get the posts with the given value please? It's worth noting that the meta_data of the post is coming from advanced custom fields relationship field which is a Post Object.</p> <pre><code>array(41) { ["_edit_lock"]=&gt; array(1) { [0]=&gt; string(12) "1473170740:7" } ["_edit_last"]=&gt; array(1) { [0]=&gt; string(1) "7" } ["_thumbnail_id"]=&gt; array(1) { [0]=&gt; string(3) "279" } ["_product_attributes"]=&gt; array(1) { [0]=&gt; string(510) "a:3:{s:12:"pa_hang-type";a:6:{s:4:"name";s:12:"pa_hang-type";s:5:"value";s:0:"";s:8:"position";s:1:"0";s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:1;}s:18:"pa_limited-edition";a:6:{s:4:"name";s:18:"pa_limited-edition";s:5:"value";s:0:"";s:8:"position";s:1:"1";s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:1;}s:7:"pa_size";a:6:{s:4:"name";s:7:"pa_size";s:5:"value";s:0:"";s:8:"position";s:1:"3";s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:1;}}" } ["_visibility"]=&gt; array(1) { [0]=&gt; string(7) "visible" } ["_stock_status"]=&gt; array(1) { [0]=&gt; string(7) "instock" } ["total_sales"]=&gt; array(1) { [0]=&gt; string(1) "0" } ["_downloadable"]=&gt; array(1) { [0]=&gt; string(2) "no" } ["_virtual"]=&gt; array(1) { [0]=&gt; string(2) "no" } ["_tax_status"]=&gt; array(1) { [0]=&gt; string(7) "taxable" } ["_tax_class"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_purchase_note"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_featured"]=&gt; array(1) { [0]=&gt; string(2) "no" } ["_weight"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_length"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_width"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_height"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_sku"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_regular_price"]=&gt; array(1) { [0]=&gt; string(2) "60" } ["_sale_price"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_sale_price_dates_from"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_sale_price_dates_to"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_price"]=&gt; array(1) { [0]=&gt; string(2) "60" } ["_sold_individually"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_manage_stock"]=&gt; array(1) { [0]=&gt; string(2) "no" } ["_backorders"]=&gt; array(1) { [0]=&gt; string(2) "no" } ["_stock"]=&gt; array(1) { [0]=&gt; string(0) "" } ["_upsell_ids"]=&gt; array(1) { [0]=&gt; string(6) "a:0:{}" } ["_crosssell_ids"]=&gt; array(1) { [0]=&gt; string(6) "a:0:{}" } ["_product_version"]=&gt; array(1) { [0]=&gt; string(5) "2.6.4" } ["_product_image_gallery"]=&gt; array(1) { [0]=&gt; string(3) "279" } ["artist"]=&gt; array(1) { [0]=&gt; string(3) "168" } ["_artist"]=&gt; array(1) { [0]=&gt; string(19) "field_57c6d280c7a91" } ["_yoast_wpseo_primary_product_cat"]=&gt; array(1) { [0]=&gt; string(2) "32" } ["_yoast_wpseo_focuskw_text_input"]=&gt; array(1) { [0]=&gt; string(23) "Worker Bee Wildlife Art" } ["_yoast_wpseo_focuskw"]=&gt; array(1) { [0]=&gt; string(23) "Worker Bee Wildlife Art" } ["_yoast_wpseo_linkdex"]=&gt; array(1) { [0]=&gt; string(2) "22" } ["_yoast_wpseo_content_score"]=&gt; array(1) { [0]=&gt; string(2) "30" } ["_wc_rating_count"]=&gt; array(1) { [0]=&gt; string(6) "a:0:{}" } ["_wc_average_rating"]=&gt; array(1) { [0]=&gt; string(1) "0" } ["_a3_dgallery"]=&gt; array(1) { [0]=&gt; string(3) "279" } } </code></pre> <p>Please also see the var_dump($loop) output as well.</p> <pre><code> object(WP_Query)#8961 (49) { ["query"]=&gt; array(2) { ["post_type"]=&gt; string(7) "product" ["meta_query"]=&gt; array(1) { [0]=&gt; array(2) { ["key"]=&gt; string(6) "artist" ["value"]=&gt; string(3) "174" } } } ["query_vars"]=&gt; array(65) { ["post_type"]=&gt; string(7) "product" ["meta_query"]=&gt; array(1) { [0]=&gt; array(2) { ["key"]=&gt; string(6) "artist" ["value"]=&gt; string(3) "174" } } ["error"]=&gt; string(0) "" ["m"]=&gt; string(0) "" ["p"]=&gt; int(0) ["post_parent"]=&gt; string(0) "" ["subpost"]=&gt; string(0) "" ["subpost_id"]=&gt; string(0) "" ["attachment"]=&gt; string(0) "" ["attachment_id"]=&gt; int(0) ["name"]=&gt; string(0) "" ["static"]=&gt; string(0) "" ["pagename"]=&gt; string(0) "" ["page_id"]=&gt; int(0) ["second"]=&gt; string(0) "" ["minute"]=&gt; string(0) "" ["hour"]=&gt; string(0) "" ["day"]=&gt; int(0) ["monthnum"]=&gt; int(0) ["year"]=&gt; int(0) ["w"]=&gt; int(0) ["category_name"]=&gt; string(0) "" ["tag"]=&gt; string(0) "" ["cat"]=&gt; string(0) "" ["tag_id"]=&gt; string(0) "" ["author"]=&gt; string(0) "" ["author_name"]=&gt; string(0) "" ["feed"]=&gt; string(0) "" ["tb"]=&gt; string(0) "" ["paged"]=&gt; int(0) ["meta_key"]=&gt; string(0) "" ["meta_value"]=&gt; string(0) "" ["preview"]=&gt; string(0) "" ["s"]=&gt; string(0) "" ["sentence"]=&gt; string(0) "" ["title"]=&gt; string(0) "" ["fields"]=&gt; string(0) "" ["menu_order"]=&gt; string(0) "" ["embed"]=&gt; string(0) "" ["category__in"]=&gt; array(0) { } ["category__not_in"]=&gt; array(0) { } ["category__and"]=&gt; array(0) { } ["post__in"]=&gt; array(0) { } ["post__not_in"]=&gt; array(0) { } ["post_name__in"]=&gt; array(0) { } ["tag__in"]=&gt; array(0) { } ["tag__not_in"]=&gt; array(0) { } ["tag__and"]=&gt; array(0) { } ["tag_slug__in"]=&gt; array(0) { } ["tag_slug__and"]=&gt; array(0) { } ["post_parent__in"]=&gt; array(0) { } ["post_parent__not_in"]=&gt; array(0) { } ["author__in"]=&gt; array(0) { } ["author__not_in"]=&gt; array(0) { } ["ignore_sticky_posts"]=&gt; bool(false) ["suppress_filters"]=&gt; bool(false) ["cache_results"]=&gt; bool(true) ["update_post_term_cache"]=&gt; bool(true) ["lazy_load_term_meta"]=&gt; bool(true) ["update_post_meta_cache"]=&gt; bool(true) ["posts_per_page"]=&gt; int(8) ["nopaging"]=&gt; bool(false) ["comments_per_page"]=&gt; string(2) "50" ["no_found_rows"]=&gt; bool(false) ["order"]=&gt; string(4) "DESC" } ["tax_query"]=&gt; object(WP_Tax_Query)#8958 (6) { ["queries"]=&gt; array(0) { } ["relation"]=&gt; string(3) "AND" ["table_aliases":protected]=&gt; array(0) { } ["queried_terms"]=&gt; array(0) { } ["primary_table"]=&gt; string(10) "wp_2_posts" ["primary_id_column"]=&gt; string(2) "ID" } ["meta_query"]=&gt; object(WP_Meta_Query)#8959 (9) { ["queries"]=&gt; array(2) { [0]=&gt; array(2) { ["key"]=&gt; string(6) "artist" ["value"]=&gt; string(3) "174" } ["relation"]=&gt; string(2) "OR" } ["relation"]=&gt; string(3) "AND" ["meta_table"]=&gt; string(13) "wp_2_postmeta" ["meta_id_column"]=&gt; string(7) "post_id" ["primary_table"]=&gt; string(10) "wp_2_posts" ["primary_id_column"]=&gt; string(2) "ID" ["table_aliases":protected]=&gt; array(1) { [0]=&gt; string(13) "wp_2_postmeta" } ["clauses":protected]=&gt; array(1) { ["wp_2_postmeta"]=&gt; array(5) { ["key"]=&gt; string(6) "artist" ["value"]=&gt; string(3) "174" ["compare"]=&gt; string(1) "=" ["alias"]=&gt; string(13) "wp_2_postmeta" ["cast"]=&gt; string(4) "CHAR" } } ["has_or_relation":protected]=&gt; bool(false) } ["date_query"]=&gt; bool(false) ["request"]=&gt; string(453) "SELECT SQL_CALC_FOUND_ROWS wp_2_posts.ID FROM wp_2_posts INNER JOIN wp_2_postmeta ON ( wp_2_posts.ID = wp_2_postmeta.post_id ) WHERE 1=1 AND ( ( wp_2_postmeta.meta_key = 'artist' AND wp_2_postmeta.meta_value = '174' ) ) AND wp_2_posts.post_type = 'product' AND (wp_2_posts.post_status = 'publish' OR wp_2_posts.post_status = 'acf-disabled' OR wp_2_posts.post_status = 'private') GROUP BY wp_2_posts.ID ORDER BY wp_2_posts.post_date DESC LIMIT 0, 8" ["posts"]=&gt; array(6) { [0]=&gt; object(WP_Post)#8957 (24) { ["ID"]=&gt; int(297) ["post_author"]=&gt; string(1) "7" ["post_date"]=&gt; string(19) "2016-09-07 15:23:42" ["post_date_gmt"]=&gt; string(19) "2016-09-07 14:23:42" ["post_content"]=&gt; string(0) "" ["post_title"]=&gt; string(5) "Alone" ["post_excerpt"]=&gt; string(0) "" ["post_status"]=&gt; string(7) "publish" ["comment_status"]=&gt; string(4) "open" ["ping_status"]=&gt; string(6) "closed" ["post_password"]=&gt; string(0) "" ["post_name"]=&gt; string(5) "alone" ["to_ping"]=&gt; string(0) "" ["pinged"]=&gt; string(0) "" ["post_modified"]=&gt; string(19) "2016-09-07 15:23:42" ["post_modified_gmt"]=&gt; string(19) "2016-09-07 14:23:42" ["post_content_filtered"]=&gt; string(0) "" ["post_parent"]=&gt; int(0) ["guid"]=&gt; string(55) "http://shop.localhost.com/?post_type=product&amp;p=297" ["menu_order"]=&gt; int(0) ["post_type"]=&gt; string(7) "product" ["post_mime_type"]=&gt; string(0) "" ["comment_count"]=&gt; string(1) "0" ["filter"]=&gt; string(3) "raw" } [1]=&gt; object(WP_Post)#8956 (24) { ["ID"]=&gt; int(295) ["post_author"]=&gt; string(1) "7" ["post_date"]=&gt; string(19) "2016-09-07 09:36:34" ["post_date_gmt"]=&gt; string(19) "2016-09-07 08:36:34" ["post_content"]=&gt; string(0) "" ["post_title"]=&gt; string(11) "Reef Glider" ["post_excerpt"]=&gt; string(69) "This is a description of the Product. It does not need to be entered." ["post_status"]=&gt; string(7) "publish" ["comment_status"]=&gt; string(4) "open" ["ping_status"]=&gt; string(6) "closed" ["post_password"]=&gt; string(0) "" ["post_name"]=&gt; string(11) "reef-glider" ["to_ping"]=&gt; string(0) "" ["pinged"]=&gt; string(0) "" ["post_modified"]=&gt; string(19) "2016-09-19 12:06:24" ["post_modified_gmt"]=&gt; string(19) "2016-09-19 11:06:24" ["post_content_filtered"]=&gt; string(0) "" ["post_parent"]=&gt; int(0) ["guid"]=&gt; string(55) "http://shop.localhost.com/?post_type=product&amp;p=295" ["menu_order"]=&gt; int(0) ["post_type"]=&gt; string(7) "product" ["post_mime_type"]=&gt; string(0) "" ["comment_count"]=&gt; string(1) "0" ["filter"]=&gt; string(3) "raw" } [2]=&gt; object(WP_Post)#8955 (24) { ["ID"]=&gt; int(293) ["post_author"]=&gt; string(1) "7" ["post_date"]=&gt; string(19) "2016-09-07 09:33:30" ["post_date_gmt"]=&gt; string(19) "2016-09-07 08:33:30" ["post_content"]=&gt; string(0) "" ["post_title"]=&gt; string(16) "Heart of The Sea" ["post_excerpt"]=&gt; string(0) "" ["post_status"]=&gt; string(7) "publish" ["comment_status"]=&gt; string(4) "open" ["ping_status"]=&gt; string(6) "closed" ["post_password"]=&gt; string(0) "" ["post_name"]=&gt; string(16) "heart-of-the-sea" ["to_ping"]=&gt; string(0) "" ["pinged"]=&gt; string(0) "" ["post_modified"]=&gt; string(19) "2016-09-19 16:48:53" ["post_modified_gmt"]=&gt; string(19) "2016-09-19 15:48:53" ["post_content_filtered"]=&gt; string(0) "" ["post_parent"]=&gt; int(0) ["guid"]=&gt; string(55) "http://shop.localhost.com/?post_type=product&amp;p=293" ["menu_order"]=&gt; int(0) ["post_type"]=&gt; string(7) "product" ["post_mime_type"]=&gt; string(0) "" ["comment_count"]=&gt; string(1) "0" ["filter"]=&gt; string(3) "raw" } [3]=&gt; object(WP_Post)#8954 (24) { ["ID"]=&gt; int(291) ["post_author"]=&gt; string(1) "7" ["post_date"]=&gt; string(19) "2016-09-06 16:46:38" ["post_date_gmt"]=&gt; string(19) "2016-09-06 15:46:38" ["post_content"]=&gt; string(0) "" ["post_title"]=&gt; string(6) "Escape" ["post_excerpt"]=&gt; string(0) "" ["post_status"]=&gt; string(7) "publish" ["comment_status"]=&gt; string(4) "open" ["ping_status"]=&gt; string(6) "closed" ["post_password"]=&gt; string(0) "" ["post_name"]=&gt; string(6) "escape" ["to_ping"]=&gt; string(0) "" ["pinged"]=&gt; string(0) "" ["post_modified"]=&gt; string(19) "2016-09-06 16:46:38" ["post_modified_gmt"]=&gt; string(19) "2016-09-06 15:46:38" ["post_content_filtered"]=&gt; string(0) "" ["post_parent"]=&gt; int(0) ["guid"]=&gt; string(55) "http://shop.localhost.com/?post_type=product&amp;p=291" ["menu_order"]=&gt; int(0) ["post_type"]=&gt; string(7) "product" ["post_mime_type"]=&gt; string(0) "" ["comment_count"]=&gt; string(1) "0" ["filter"]=&gt; string(3) "raw" } [4]=&gt; object(WP_Post)#8772 (24) { ["ID"]=&gt; int(289) ["post_author"]=&gt; string(1) "7" ["post_date"]=&gt; string(19) "2016-09-06 16:02:57" ["post_date_gmt"]=&gt; s… </code></pre>
[ { "answer_id": 240208, "author": "FaCE", "author_id": 96768, "author_profile": "https://wordpress.stackexchange.com/users/96768", "pm_score": 2, "selected": false, "text": "<p>You're almost there -- you just need to add the comparison to your meta query:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'product',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'artist',\n 'value' =&gt; $artistID,\n 'compare' =&gt; '='\n ) \n )\n);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Meta_Query</a></p>\n\n<p>Remember to filter <code>$artistID</code> before accepting it in your query! </p>\n" }, { "answer_id": 240222, "author": "Amine Faiz", "author_id": 66813, "author_profile": "https://wordpress.stackexchange.com/users/66813", "pm_score": 1, "selected": false, "text": "<p>firstly in term of security you need to filter the artist_id variable before accepting it, secondly you should run the var_dump(get_post_meta(get_the_ID())) inside the query loop, try the following code it should work for you : </p>\n\n<pre><code>&lt;?php \n $artistID = filter_input(INPUT_GET, 'artist_id', FILTER_SANITIZE_NUMBER_INT);\n $args = array(\n //Type &amp; Status Parameters\n 'post_type' =&gt; 'product',\n //Order &amp; Orderby Parameters\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'date',\n\n //Pagination Parameters\n 'posts_per_page' =&gt; -1,\n //Custom Field Parameters\n 'meta_key' =&gt; 'artist',\n 'meta_value' =&gt; $artistID,\n 'meta_compare' =&gt; '=',\n\n );\n\n$query = new WP_Query( $args );\n\nif ($query-&gt;have_posts()) {\n while($query-&gt;have_posts()) {\n $query-&gt;the_post();\n global $post;\n var_dump(get_post_meta($post-&gt;ID);\n }\n}\n</code></pre>\n\n<p>?></p>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59547/" ]
I currently have this custom query which I am trying to filter the product (paintings) by artist. ``` $artistID = $_GET['artist_id']; $args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'artist', 'value' => $artistID ) ) ); $loop = new WP_Query( $args ); ``` It isn't working at the moment... When I run ``` var_dump(get_post_meta(get_the_ID())); ``` It outputs the following (interested in the artist key)... Can anyone help me write a query to only get the posts with the given value please? It's worth noting that the meta\_data of the post is coming from advanced custom fields relationship field which is a Post Object. ``` array(41) { ["_edit_lock"]=> array(1) { [0]=> string(12) "1473170740:7" } ["_edit_last"]=> array(1) { [0]=> string(1) "7" } ["_thumbnail_id"]=> array(1) { [0]=> string(3) "279" } ["_product_attributes"]=> array(1) { [0]=> string(510) "a:3:{s:12:"pa_hang-type";a:6:{s:4:"name";s:12:"pa_hang-type";s:5:"value";s:0:"";s:8:"position";s:1:"0";s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:1;}s:18:"pa_limited-edition";a:6:{s:4:"name";s:18:"pa_limited-edition";s:5:"value";s:0:"";s:8:"position";s:1:"1";s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:1;}s:7:"pa_size";a:6:{s:4:"name";s:7:"pa_size";s:5:"value";s:0:"";s:8:"position";s:1:"3";s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:1;}}" } ["_visibility"]=> array(1) { [0]=> string(7) "visible" } ["_stock_status"]=> array(1) { [0]=> string(7) "instock" } ["total_sales"]=> array(1) { [0]=> string(1) "0" } ["_downloadable"]=> array(1) { [0]=> string(2) "no" } ["_virtual"]=> array(1) { [0]=> string(2) "no" } ["_tax_status"]=> array(1) { [0]=> string(7) "taxable" } ["_tax_class"]=> array(1) { [0]=> string(0) "" } ["_purchase_note"]=> array(1) { [0]=> string(0) "" } ["_featured"]=> array(1) { [0]=> string(2) "no" } ["_weight"]=> array(1) { [0]=> string(0) "" } ["_length"]=> array(1) { [0]=> string(0) "" } ["_width"]=> array(1) { [0]=> string(0) "" } ["_height"]=> array(1) { [0]=> string(0) "" } ["_sku"]=> array(1) { [0]=> string(0) "" } ["_regular_price"]=> array(1) { [0]=> string(2) "60" } ["_sale_price"]=> array(1) { [0]=> string(0) "" } ["_sale_price_dates_from"]=> array(1) { [0]=> string(0) "" } ["_sale_price_dates_to"]=> array(1) { [0]=> string(0) "" } ["_price"]=> array(1) { [0]=> string(2) "60" } ["_sold_individually"]=> array(1) { [0]=> string(0) "" } ["_manage_stock"]=> array(1) { [0]=> string(2) "no" } ["_backorders"]=> array(1) { [0]=> string(2) "no" } ["_stock"]=> array(1) { [0]=> string(0) "" } ["_upsell_ids"]=> array(1) { [0]=> string(6) "a:0:{}" } ["_crosssell_ids"]=> array(1) { [0]=> string(6) "a:0:{}" } ["_product_version"]=> array(1) { [0]=> string(5) "2.6.4" } ["_product_image_gallery"]=> array(1) { [0]=> string(3) "279" } ["artist"]=> array(1) { [0]=> string(3) "168" } ["_artist"]=> array(1) { [0]=> string(19) "field_57c6d280c7a91" } ["_yoast_wpseo_primary_product_cat"]=> array(1) { [0]=> string(2) "32" } ["_yoast_wpseo_focuskw_text_input"]=> array(1) { [0]=> string(23) "Worker Bee Wildlife Art" } ["_yoast_wpseo_focuskw"]=> array(1) { [0]=> string(23) "Worker Bee Wildlife Art" } ["_yoast_wpseo_linkdex"]=> array(1) { [0]=> string(2) "22" } ["_yoast_wpseo_content_score"]=> array(1) { [0]=> string(2) "30" } ["_wc_rating_count"]=> array(1) { [0]=> string(6) "a:0:{}" } ["_wc_average_rating"]=> array(1) { [0]=> string(1) "0" } ["_a3_dgallery"]=> array(1) { [0]=> string(3) "279" } } ``` Please also see the var\_dump($loop) output as well. ``` object(WP_Query)#8961 (49) { ["query"]=> array(2) { ["post_type"]=> string(7) "product" ["meta_query"]=> array(1) { [0]=> array(2) { ["key"]=> string(6) "artist" ["value"]=> string(3) "174" } } } ["query_vars"]=> array(65) { ["post_type"]=> string(7) "product" ["meta_query"]=> array(1) { [0]=> array(2) { ["key"]=> string(6) "artist" ["value"]=> string(3) "174" } } ["error"]=> string(0) "" ["m"]=> string(0) "" ["p"]=> int(0) ["post_parent"]=> string(0) "" ["subpost"]=> string(0) "" ["subpost_id"]=> string(0) "" ["attachment"]=> string(0) "" ["attachment_id"]=> int(0) ["name"]=> string(0) "" ["static"]=> string(0) "" ["pagename"]=> string(0) "" ["page_id"]=> int(0) ["second"]=> string(0) "" ["minute"]=> string(0) "" ["hour"]=> string(0) "" ["day"]=> int(0) ["monthnum"]=> int(0) ["year"]=> int(0) ["w"]=> int(0) ["category_name"]=> string(0) "" ["tag"]=> string(0) "" ["cat"]=> string(0) "" ["tag_id"]=> string(0) "" ["author"]=> string(0) "" ["author_name"]=> string(0) "" ["feed"]=> string(0) "" ["tb"]=> string(0) "" ["paged"]=> int(0) ["meta_key"]=> string(0) "" ["meta_value"]=> string(0) "" ["preview"]=> string(0) "" ["s"]=> string(0) "" ["sentence"]=> string(0) "" ["title"]=> string(0) "" ["fields"]=> string(0) "" ["menu_order"]=> string(0) "" ["embed"]=> string(0) "" ["category__in"]=> array(0) { } ["category__not_in"]=> array(0) { } ["category__and"]=> array(0) { } ["post__in"]=> array(0) { } ["post__not_in"]=> array(0) { } ["post_name__in"]=> array(0) { } ["tag__in"]=> array(0) { } ["tag__not_in"]=> array(0) { } ["tag__and"]=> array(0) { } ["tag_slug__in"]=> array(0) { } ["tag_slug__and"]=> array(0) { } ["post_parent__in"]=> array(0) { } ["post_parent__not_in"]=> array(0) { } ["author__in"]=> array(0) { } ["author__not_in"]=> array(0) { } ["ignore_sticky_posts"]=> bool(false) ["suppress_filters"]=> bool(false) ["cache_results"]=> bool(true) ["update_post_term_cache"]=> bool(true) ["lazy_load_term_meta"]=> bool(true) ["update_post_meta_cache"]=> bool(true) ["posts_per_page"]=> int(8) ["nopaging"]=> bool(false) ["comments_per_page"]=> string(2) "50" ["no_found_rows"]=> bool(false) ["order"]=> string(4) "DESC" } ["tax_query"]=> object(WP_Tax_Query)#8958 (6) { ["queries"]=> array(0) { } ["relation"]=> string(3) "AND" ["table_aliases":protected]=> array(0) { } ["queried_terms"]=> array(0) { } ["primary_table"]=> string(10) "wp_2_posts" ["primary_id_column"]=> string(2) "ID" } ["meta_query"]=> object(WP_Meta_Query)#8959 (9) { ["queries"]=> array(2) { [0]=> array(2) { ["key"]=> string(6) "artist" ["value"]=> string(3) "174" } ["relation"]=> string(2) "OR" } ["relation"]=> string(3) "AND" ["meta_table"]=> string(13) "wp_2_postmeta" ["meta_id_column"]=> string(7) "post_id" ["primary_table"]=> string(10) "wp_2_posts" ["primary_id_column"]=> string(2) "ID" ["table_aliases":protected]=> array(1) { [0]=> string(13) "wp_2_postmeta" } ["clauses":protected]=> array(1) { ["wp_2_postmeta"]=> array(5) { ["key"]=> string(6) "artist" ["value"]=> string(3) "174" ["compare"]=> string(1) "=" ["alias"]=> string(13) "wp_2_postmeta" ["cast"]=> string(4) "CHAR" } } ["has_or_relation":protected]=> bool(false) } ["date_query"]=> bool(false) ["request"]=> string(453) "SELECT SQL_CALC_FOUND_ROWS wp_2_posts.ID FROM wp_2_posts INNER JOIN wp_2_postmeta ON ( wp_2_posts.ID = wp_2_postmeta.post_id ) WHERE 1=1 AND ( ( wp_2_postmeta.meta_key = 'artist' AND wp_2_postmeta.meta_value = '174' ) ) AND wp_2_posts.post_type = 'product' AND (wp_2_posts.post_status = 'publish' OR wp_2_posts.post_status = 'acf-disabled' OR wp_2_posts.post_status = 'private') GROUP BY wp_2_posts.ID ORDER BY wp_2_posts.post_date DESC LIMIT 0, 8" ["posts"]=> array(6) { [0]=> object(WP_Post)#8957 (24) { ["ID"]=> int(297) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2016-09-07 15:23:42" ["post_date_gmt"]=> string(19) "2016-09-07 14:23:42" ["post_content"]=> string(0) "" ["post_title"]=> string(5) "Alone" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(5) "alone" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2016-09-07 15:23:42" ["post_modified_gmt"]=> string(19) "2016-09-07 14:23:42" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(55) "http://shop.localhost.com/?post_type=product&p=297" ["menu_order"]=> int(0) ["post_type"]=> string(7) "product" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } [1]=> object(WP_Post)#8956 (24) { ["ID"]=> int(295) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2016-09-07 09:36:34" ["post_date_gmt"]=> string(19) "2016-09-07 08:36:34" ["post_content"]=> string(0) "" ["post_title"]=> string(11) "Reef Glider" ["post_excerpt"]=> string(69) "This is a description of the Product. It does not need to be entered." ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(11) "reef-glider" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2016-09-19 12:06:24" ["post_modified_gmt"]=> string(19) "2016-09-19 11:06:24" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(55) "http://shop.localhost.com/?post_type=product&p=295" ["menu_order"]=> int(0) ["post_type"]=> string(7) "product" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } [2]=> object(WP_Post)#8955 (24) { ["ID"]=> int(293) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2016-09-07 09:33:30" ["post_date_gmt"]=> string(19) "2016-09-07 08:33:30" ["post_content"]=> string(0) "" ["post_title"]=> string(16) "Heart of The Sea" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(16) "heart-of-the-sea" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2016-09-19 16:48:53" ["post_modified_gmt"]=> string(19) "2016-09-19 15:48:53" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(55) "http://shop.localhost.com/?post_type=product&p=293" ["menu_order"]=> int(0) ["post_type"]=> string(7) "product" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } [3]=> object(WP_Post)#8954 (24) { ["ID"]=> int(291) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2016-09-06 16:46:38" ["post_date_gmt"]=> string(19) "2016-09-06 15:46:38" ["post_content"]=> string(0) "" ["post_title"]=> string(6) "Escape" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(6) "escape" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2016-09-06 16:46:38" ["post_modified_gmt"]=> string(19) "2016-09-06 15:46:38" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(55) "http://shop.localhost.com/?post_type=product&p=291" ["menu_order"]=> int(0) ["post_type"]=> string(7) "product" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } [4]=> object(WP_Post)#8772 (24) { ["ID"]=> int(289) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2016-09-06 16:02:57" ["post_date_gmt"]=> s… ```
You're almost there -- you just need to add the comparison to your meta query: ``` $args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'artist', 'value' => $artistID, 'compare' => '=' ) ) ); ``` <https://codex.wordpress.org/Class_Reference/WP_Meta_Query> Remember to filter `$artistID` before accepting it in your query!
240,219
<p>I am using the WP_bootstrap_navwalker for a dropdown menu. This works fine, but it only shows me the first and second level items. So de dropdown on the first level and a regular second item when dropdown is open. The third level is not visible. </p> <p>I want to display it under my second level items. The walker is now making it an other dropdown (it does not work). </p> <p>I am not skilled enough to properly edit the walker to fit make it fit my needs. can anyone help me?</p> <p>The walker code:</p> <pre><code>class wp_bootstrap_navwalker extends Walker_Nav_Menu { /** * @see Walker::start_lvl() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. */ public function start_lvl( &amp;$output, $depth = 0, $args = array() ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent&lt;ul role=\"menu\" class=\" dropdown-menu\"&gt;\n"; } /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param int $current_page Menu item ID. * @param object $args */ public function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; /** * Dividers, Headers or Disabled * ============================= * Determine whether the item is a Divider, Header, Disabled or regular * menu item. To prevent errors we use the strcasecmp() function to so a * comparison that is not case sensitive. The strcasecmp() function returns * a 0 if the strings are equal. */ if ( strcasecmp( $item-&gt;attr_title, 'divider' ) == 0 &amp;&amp; $depth === 1 ) { $output .= $indent . '&lt;li role="presentation" class="divider"&gt;'; } else if ( strcasecmp( $item-&gt;title, 'divider') == 0 &amp;&amp; $depth === 1 ) { $output .= $indent . '&lt;li role="presentation" class="divider"&gt;'; } else if ( strcasecmp( $item-&gt;attr_title, 'dropdown-header') == 0 &amp;&amp; $depth === 1 ) { $output .= $indent . '&lt;li role="presentation" class="dropdown-header"&gt;' . esc_attr( $item-&gt;title ); } else if ( strcasecmp($item-&gt;attr_title, 'disabled' ) == 0 ) { $output .= $indent . '&lt;li role="presentation" class="disabled"&gt;&lt;a href="#"&gt;' . esc_attr( $item-&gt;title ) . '&lt;/a&gt;'; } else { $class_names = $value = ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $classes[] = 'menu-item-' . $item-&gt;ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); if ( $args-&gt;has_children ) $class_names .= ' dropdown'; if ( in_array( 'current-menu-item', $classes ) ) $class_names .= ' active'; $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '&lt;li' . $id . $value . $class_names .'&gt;'; $atts = array(); $atts['title'] = ! empty( $item-&gt;title ) ? $item-&gt;title : ''; $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : ''; $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : ''; // If item has_children add atts to a. if ( $args-&gt;has_children &amp;&amp; $depth === 0 ) { $atts['href'] = '#'; $atts['data-toggle'] = 'dropdown'; $atts['class'] = 'dropdown-toggle'; $atts['aria-haspopup'] = 'true'; } else { $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : ''; } $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; foreach ( $atts as $attr =&gt; $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $item_output = $args-&gt;before; /* * Glyphicons * =========== * Since the the menu item is NOT a Divider or Header we check the see * if there is a value in the attr_title property. If the attr_title * property is NOT null we apply it as the class name for the glyphicon. */ if ( ! empty( $item-&gt;attr_title ) ) $item_output .= '&lt;a'. $attributes .'&gt;&lt;span class="glyphicon ' . esc_attr( $item-&gt;attr_title ) . '"&gt;&lt;/span&gt;&amp;nbsp;'; else $item_output .= '&lt;a'. $attributes .'&gt;'; $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after; $item_output .= ( $args-&gt;has_children &amp;&amp; 0 === $depth ) ? ' &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt;' : '&lt;/a&gt;' ; $item_output .= $args-&gt;after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } /** * Traverse elements to create list from elements. * * Display one element if the element doesn't have any children otherwise, * display the element and its children. Will only traverse up to the max * depth and no ignore elements under that depth. * * This method shouldn't be called directly, use the walk() method instead. * * @see Walker::start_el() * @since 2.5.0 * * @param object $element Data object * @param array $children_elements List of elements to continue traversing. * @param int $max_depth Max depth to traverse. * @param int $depth Depth of current element. * @param array $args * @param string $output Passed by reference. Used to append additional content. * @return null Null on failure with no changes to parameters. */ public function display_element( $element, &amp;$children_elements, $max_depth, $depth, $args, &amp;$output ) { if ( ! $element ) return; $id_field = $this-&gt;db_fields['id']; // Display this element. if ( is_object( $args[0] ) ) $args[0]-&gt;has_children = ! empty( $children_elements[ $element-&gt;$id_field ] ); parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } /** * Menu Fallback * ============= * If this function is assigned to the wp_nav_menu's fallback_cb variable * and a manu has not been assigned to the theme location in the WordPress * menu manager the function with display nothing to a non-logged in user, * and will add a link to the WordPress menu manager if logged in as an admin. * * @param array $args passed from the wp_nav_menu function. * */ public static function fallback( $args ) { if ( current_user_can( 'manage_options' ) ) { extract( $args ); $fb_output = null; if ( $container ) { $fb_output = '&lt;' . $container; if ( $container_id ) $fb_output .= ' id="' . $container_id . '"'; if ( $container_class ) $fb_output .= ' class="' . $container_class . '"'; $fb_output .= '&gt;'; } $fb_output .= '&lt;ul'; if ( $menu_id ) $fb_output .= ' id="' . $menu_id . '"'; if ( $menu_class ) $fb_output .= ' class="' . $menu_class . '"'; $fb_output .= '&gt;'; $fb_output .= '&lt;li&gt;&lt;a href="' . admin_url( 'nav-menus.php' ) . '"&gt;Add a menu&lt;/a&gt;&lt;/li&gt;'; $fb_output .= '&lt;/ul&gt;'; if ( $container ) $fb_output .= '&lt;/' . $container . '&gt;'; echo $fb_output; } } </code></pre> <p>}</p> <p>Sorry for my English, thanks in advance!</p>
[ { "answer_id": 263781, "author": "Md.Tauhidul Islam", "author_id": 117774, "author_profile": "https://wordpress.stackexchange.com/users/117774", "pm_score": 2, "selected": false, "text": "<p>I solved this problem. follow these instructions.....</p>\n\n<ol>\n<li><p>Add script</p>\n\n<pre><code>(function($){\n$(document).ready(function(){\n $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {\n event.preventDefault(); \n event.stopPropagation(); \n $(this).parent().siblings().removeClass('open');\n $(this).parent().toggleClass('open');\n });\n}); \n})(jQuery);\n</code></pre></li>\n</ol>\n\n<p>2.Remove <code>&amp;&amp; $depth === 0</code>\nfrom this line: <code>if ( $args-&gt;has_children &amp;&amp; $depth === 0 )</code> in <code>wp_bootstrap_navwalker.php</code> file.</p>\n\n<p>See the screenshot <a href=\"https://i.stack.imgur.com/qZnOU.png\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 301001, "author": "Leonardo Palomino", "author_id": 141918, "author_profile": "https://wordpress.stackexchange.com/users/141918", "pm_score": 1, "selected": false, "text": "<p>you have to remove the </p>\n\n<pre><code>&amp;&amp; 0 === $depth\n</code></pre>\n\n<p>on the line</p>\n\n<pre><code>$item_output .= ( $args-&gt;has_children &amp;&amp; 0 === $depth ) ? ' &lt;span class=\"caret\"&gt;&lt;/span&gt;&lt;/a&gt;' : '&lt;/a&gt;';\n</code></pre>\n\n<p>so the carret will be shown beside the text on your menu.</p>\n" }, { "answer_id": 356967, "author": "Nick Taylor", "author_id": 106492, "author_profile": "https://wordpress.stackexchange.com/users/106492", "pm_score": 1, "selected": false, "text": "<p>For those still searching for an answer, I found a solution.</p>\n\n<p>This method just uses a custom class to target the second level dropdowns and toggle the Boostrap <code>.show</code> class on the second level dropdowns.</p>\n\n<p>1) In the WP Dashboard Menus section set the second level dropdown link to an <code>href=\"#\"</code>.</p>\n\n<p>2) Set a custom class to <code>dropdown-sub</code>.</p>\n\n<p>3) Add this to your js:</p>\n\n<pre><code>$('.dropdown-sub', this).click(function(e){\n $('.dropdown-menu', this).toggleClass('show');\n})\n\n//This is to stop the Bootstrap menu from closing when a link is clicked.\n$(document).on('click', '.dropdown', function (e) {\n e.stopPropagation();\n});\n</code></pre>\n\n<p>4) Add this to your css:</p>\n\n<pre><code>.dropdown-sub a[href$='#']:after {\n display: inline-block;\n width: 0;\n height: 0;\n margin-left: .255em;\n vertical-align: .255em;\n content: \"\";\n border-top: .3em solid;\n border-right: .3em solid transparent;\n border-bottom: 0;\n border-left: .3em solid transparent;\n}\n}\n</code></pre>\n\n<p>Step 4 is just to add the carat to the end of the second level dropdown.</p>\n\n<p>You shouldn't need to modify the navwalker with this method.</p>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103408/" ]
I am using the WP\_bootstrap\_navwalker for a dropdown menu. This works fine, but it only shows me the first and second level items. So de dropdown on the first level and a regular second item when dropdown is open. The third level is not visible. I want to display it under my second level items. The walker is now making it an other dropdown (it does not work). I am not skilled enough to properly edit the walker to fit make it fit my needs. can anyone help me? The walker code: ``` class wp_bootstrap_navwalker extends Walker_Nav_Menu { /** * @see Walker::start_lvl() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. */ public function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent<ul role=\"menu\" class=\" dropdown-menu\">\n"; } /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param int $current_page Menu item ID. * @param object $args */ public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; /** * Dividers, Headers or Disabled * ============================= * Determine whether the item is a Divider, Header, Disabled or regular * menu item. To prevent errors we use the strcasecmp() function to so a * comparison that is not case sensitive. The strcasecmp() function returns * a 0 if the strings are equal. */ if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) { $output .= $indent . '<li role="presentation" class="divider">'; } else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) { $output .= $indent . '<li role="presentation" class="divider">'; } else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) { $output .= $indent . '<li role="presentation" class="dropdown-header">' . esc_attr( $item->title ); } else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) { $output .= $indent . '<li role="presentation" class="disabled"><a href="#">' . esc_attr( $item->title ) . '</a>'; } else { $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); if ( $args->has_children ) $class_names .= ' dropdown'; if ( in_array( 'current-menu-item', $classes ) ) $class_names .= ' active'; $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names .'>'; $atts = array(); $atts['title'] = ! empty( $item->title ) ? $item->title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; // If item has_children add atts to a. if ( $args->has_children && $depth === 0 ) { $atts['href'] = '#'; $atts['data-toggle'] = 'dropdown'; $atts['class'] = 'dropdown-toggle'; $atts['aria-haspopup'] = 'true'; } else { $atts['href'] = ! empty( $item->url ) ? $item->url : ''; } $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $item_output = $args->before; /* * Glyphicons * =========== * Since the the menu item is NOT a Divider or Header we check the see * if there is a value in the attr_title property. If the attr_title * property is NOT null we apply it as the class name for the glyphicon. */ if ( ! empty( $item->attr_title ) ) $item_output .= '<a'. $attributes .'><span class="glyphicon ' . esc_attr( $item->attr_title ) . '"></span>&nbsp;'; else $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ( $args->has_children && 0 === $depth ) ? ' <span class="caret"></span></a>' : '</a>' ; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } /** * Traverse elements to create list from elements. * * Display one element if the element doesn't have any children otherwise, * display the element and its children. Will only traverse up to the max * depth and no ignore elements under that depth. * * This method shouldn't be called directly, use the walk() method instead. * * @see Walker::start_el() * @since 2.5.0 * * @param object $element Data object * @param array $children_elements List of elements to continue traversing. * @param int $max_depth Max depth to traverse. * @param int $depth Depth of current element. * @param array $args * @param string $output Passed by reference. Used to append additional content. * @return null Null on failure with no changes to parameters. */ public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) { if ( ! $element ) return; $id_field = $this->db_fields['id']; // Display this element. if ( is_object( $args[0] ) ) $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] ); parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } /** * Menu Fallback * ============= * If this function is assigned to the wp_nav_menu's fallback_cb variable * and a manu has not been assigned to the theme location in the WordPress * menu manager the function with display nothing to a non-logged in user, * and will add a link to the WordPress menu manager if logged in as an admin. * * @param array $args passed from the wp_nav_menu function. * */ public static function fallback( $args ) { if ( current_user_can( 'manage_options' ) ) { extract( $args ); $fb_output = null; if ( $container ) { $fb_output = '<' . $container; if ( $container_id ) $fb_output .= ' id="' . $container_id . '"'; if ( $container_class ) $fb_output .= ' class="' . $container_class . '"'; $fb_output .= '>'; } $fb_output .= '<ul'; if ( $menu_id ) $fb_output .= ' id="' . $menu_id . '"'; if ( $menu_class ) $fb_output .= ' class="' . $menu_class . '"'; $fb_output .= '>'; $fb_output .= '<li><a href="' . admin_url( 'nav-menus.php' ) . '">Add a menu</a></li>'; $fb_output .= '</ul>'; if ( $container ) $fb_output .= '</' . $container . '>'; echo $fb_output; } } ``` } Sorry for my English, thanks in advance!
I solved this problem. follow these instructions..... 1. Add script ``` (function($){ $(document).ready(function(){ $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) { event.preventDefault(); event.stopPropagation(); $(this).parent().siblings().removeClass('open'); $(this).parent().toggleClass('open'); }); }); })(jQuery); ``` 2.Remove `&& $depth === 0` from this line: `if ( $args->has_children && $depth === 0 )` in `wp_bootstrap_navwalker.php` file. See the screenshot [here](https://i.stack.imgur.com/qZnOU.png).
240,221
<p>Currently my page titles are handled by WordPress, in a call to wp_head (I have add_theme_support( 'title-tag' ) in functions.php). I'd like to change the page title format for category archives - currently these look like</p> <pre><code>&lt;Category name&gt; Archives - &lt;Site name&gt; </code></pre> <p>I'd like them just to be:</p> <pre><code>&lt;Category name&gt; - &lt;Site name&gt; </code></pre> <p>Is there a way of achieving this?</p>
[ { "answer_id": 240223, "author": "Fencer04", "author_id": 98527, "author_profile": "https://wordpress.stackexchange.com/users/98527", "pm_score": 0, "selected": false, "text": "<p>If you only want to edit the title tag () and not what is at the top of the page you can do this:</p>\n\n<pre><code>// define the document_title_parts callback \nfunction filter_document_title_parts( $title ) { \n if( is_category() ){\n $title[title] = str_replace( 'Archives', '', $title[title] );\n }\n return $title; \n}; \n\n// add the filter \nadd_filter( 'document_title_parts', 'filter_document_title_parts', 10, 1 );\n</code></pre>\n" }, { "answer_id": 240224, "author": "FaCE", "author_id": 96768, "author_profile": "https://wordpress.stackexchange.com/users/96768", "pm_score": 3, "selected": true, "text": "<p>If you're using the Yoast SEO plugin (which it looks like you are) then <a href=\"https://wordpress.stackexchange.com/a/163023/96768\">this</a> answer might help you</p>\n\n<blockquote>\n <p>If you are using yoast SEO plugin then the easiest method is to remove\n the archive word from \"titles &amp; metas-> Taxonomies->category\"</p>\n \n <p>find:</p>\n \n <p>%%term_title%% Archives %%page%% %%sep%% %%sitename%% replace it with:</p>\n \n <p>%%term_title%% %%page%% %%sep%% %%sitename%%</p>\n</blockquote>\n\n<p>Alternatively you could try changing it using the <code>get_the_archive_title</code> filter as explained <a href=\"https://wordpress.stackexchange.com/a/179590/96768\">here</a></p>\n\n<blockquote>\n<pre><code>add_filter( 'get_the_archive_title', function ($title) {\n\nif ( is_category() ) {\n\n $title = single_cat_title( '', false );\n\n } elseif ( is_tag() ) {\n\n $title = single_tag_title( '', false );\n\n } elseif ( is_author() ) {\n\n $title = '&lt;span class=\"vcard\"&gt;' . get_the_author() . '&lt;/span&gt;' ;\n\n }\n\nreturn $title;\n\n});\n</code></pre>\n</blockquote>\n" }, { "answer_id": 240226, "author": "Amine Faiz", "author_id": 66813, "author_profile": "https://wordpress.stackexchange.com/users/66813", "pm_score": 2, "selected": false, "text": "<p>You need to use the wp_title hook, try this code it should work for you : </p>\n\n<pre>\nadd_filter( 'wp_title', 'my_new_category_title', 10, 2 );\n\nfunction my_new_category_title($title)\n{\n if (is_category() || is_archive()) {\n $title = ' - '.get_bloginfo('name').' '.$title;\n } \n return $title;\n}\n</pre>\n" }, { "answer_id": 388858, "author": "Jodyshop", "author_id": 127580, "author_profile": "https://wordpress.stackexchange.com/users/127580", "pm_score": 0, "selected": false, "text": "<p>Also, you can change the default <code>Category Title</code> without using SEO plugins using a function by override the default filter <code>single_cat_title</code> as follow:</p>\n<pre><code>/**\n* Add Custom Category Title\n*/\nadd_filter( 'single_cat_title', 'custom_category_title', 10, 2 );\nfunction custom_category_title( $title ) {\n if ( is_category() || is_archive() ) {\n $title = $title . ' Example';\n }\n return $title;\n}\n</code></pre>\n<p>The output of the above code is:</p>\n<p>Category Example</p>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29118/" ]
Currently my page titles are handled by WordPress, in a call to wp\_head (I have add\_theme\_support( 'title-tag' ) in functions.php). I'd like to change the page title format for category archives - currently these look like ``` <Category name> Archives - <Site name> ``` I'd like them just to be: ``` <Category name> - <Site name> ``` Is there a way of achieving this?
If you're using the Yoast SEO plugin (which it looks like you are) then [this](https://wordpress.stackexchange.com/a/163023/96768) answer might help you > > If you are using yoast SEO plugin then the easiest method is to remove > the archive word from "titles & metas-> Taxonomies->category" > > > find: > > > %%term\_title%% Archives %%page%% %%sep%% %%sitename%% replace it with: > > > %%term\_title%% %%page%% %%sep%% %%sitename%% > > > Alternatively you could try changing it using the `get_the_archive_title` filter as explained [here](https://wordpress.stackexchange.com/a/179590/96768) > > > ``` > add_filter( 'get_the_archive_title', function ($title) { > > if ( is_category() ) { > > $title = single_cat_title( '', false ); > > } elseif ( is_tag() ) { > > $title = single_tag_title( '', false ); > > } elseif ( is_author() ) { > > $title = '<span class="vcard">' . get_the_author() . '</span>' ; > > } > > return $title; > > }); > > ``` > >
240,254
<p>I want to check if a post already exists. This includes to check if the post exists as draft as well. But I struggle a little bit with the wordpress API v2. <a href="http://v2.wp-api.org/reference/posts/" rel="noreferrer">http://v2.wp-api.org/reference/posts/</a><br> Under <strong>List Posts</strong> -> status they say</p> <blockquote> <p>Limit result set to posts assigned a specific status.<br> Default: publish </p> </blockquote> <p>I tried to assign the value as parameter, but I get an error response:</p> <blockquote> <p>{"code":"rest_invalid_param","message":"Invalid parameter: status","data":{"status":400,"params":{"status":"Status is forbidden"}}}</p> </blockquote> <p>I als asign the title of the post to check:</p> <blockquote> <p>filter[s] = post Title</p> </blockquote> <p>So how to get the posts with draft state? I'm currently using the Basic Auth for developing?</p> <p>I also tried </p> <blockquote> <p>filter[post_status]=draft</p> </blockquote> <p>but with no success.</p> <p>I have the following plugins installed: WP REST API<br> WP REST API - filter fields<br> JSON Basic Authentication</p>
[ { "answer_id": 246781, "author": "Jack Lenox", "author_id": 7437, "author_profile": "https://wordpress.stackexchange.com/users/7437", "pm_score": 3, "selected": true, "text": "<p>I think the query parameter that you want for post status is:</p>\n\n<pre><code>status=draft\n</code></pre>\n\n<p>Let me know if this doesn't work.</p>\n" }, { "answer_id": 389000, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 1, "selected": false, "text": "<p>that is due to the fact, that <code>draft</code> is a protected status. and protected status are not publicly queriable simply by adding the attribute to the url. because that would mean, that everybody could query any wordpress api and query for &quot;hidden&quot; posts. by default protected statuses are ‘future‘, ‘draft‘ and ‘pending‘.</p>\n<p>but you still could change that behavior for your api...</p>\n<p>following is a working example, but it only exposes drafts to logged in users:</p>\n<pre><code>/**\n* make drafts public for logged in users\n*/\nfunction so240254_init()\n{\n if (is_user_logged_in()) :\n global $wp_post_statuses;\n\n $wp_post_statuses['draft']-&gt;public = true;\n $wp_post_statuses['draft']-&gt;exclude_from_search = false;\n $wp_post_statuses['draft']-&gt;publicly_queryable = true;\n endif;\n}\nadd_action('init', 'so240254_init');\n\n/*\n* expose drafts to api for logged in users\n*/\nfunction so240254_rest_post_query($args)\n{\n if (is_user_logged_in()) :\n $args['post_status'] = ['publish', 'draft'];\n endif;\n\n return $args;\n}\nadd_filter('rest_post_query', 'so240254_rest_post_query');\n</code></pre>\n<p>now, when you are logged in and call the rest api, you get published and draft posts (no query parameter required!). if not, you only get published posts.</p>\n<p>you could strip the <code>is_user_logged_in()</code> method, if you really wanted to expose drafts to all queries, no matter the current user status...</p>\n" }, { "answer_id": 390321, "author": "TARKUS", "author_id": 90364, "author_profile": "https://wordpress.stackexchange.com/users/90364", "pm_score": 1, "selected": false, "text": "<p>Having recently been through a similar problem, and learning to solve it, I thought I'd share my learning experience.</p>\n<p>As we learned, anybody can request a post with <code>status=publish</code>. If you get errors like the following or similar, then you should start thinking in terms of problems with authentication or permissions:</p>\n<pre><code>stdClass Object\n(\n [code] =&gt; rest_invalid_param\n [message] =&gt; Invalid parameter(s): status\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 400\n [params] =&gt; stdClass Object\n (\n [status] =&gt; Status is forbidden.\n )\n\n [details] =&gt; stdClass Object\n (\n [status] =&gt; stdClass Object\n (\n [code] =&gt; rest_forbidden_status\n [message] =&gt; Status is forbidden.\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 401\n )\n\n )\n\n )\n\n )\n\n )\n</code></pre>\n<p>...or...</p>\n<pre><code>stdClass Object\n(\n [code] =&gt; jwt_auth_invalid_token\n [message] =&gt; Wrong number of segments\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 403\n )\n\n)\n</code></pre>\n<p>...If you are logged in as an admin, then you should have permission to see draft posts. Therefore, it is likely your API calls are not authenticating for some reason.</p>\n<p>The first thing I tested was the token. I happen to be using the <strong>JWT Authentication for WP-API</strong> plugin, which is actually pretty easy to implement. After installing/activating JWT Auth, go to the user you want to assign to use your API calls, and at the bottom of the user profile you will see :</p>\n<p><a href=\"https://i.stack.imgur.com/Es3ar.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Es3ar.png\" alt=\"Application Account name\" /></a></p>\n<p>Give your application a name, Add New, and then a new application password will pop up. It will look like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Y0rF4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y0rF4.png\" alt=\"Application password\" /></a></p>\n<p>Copy the whole password, keeping the spaces is fine.</p>\n<p>I'm using PHP and cURL, so my get token code looks like this:</p>\n<pre><code>private function getAuthHeader(){\n $JWTtoken = json_decode($this-&gt;getJWTToken());\n $token = $JWTtoken-&gt;token;\n $header = array(\n &quot;Content-type: application/json&quot;, \n &quot;Authorization: Bearer &quot; . $token\n );\n return $header;\n}\n\npublic function getJWTToken(){\n /*\n Request: POST http://basic/wp-json/api/v1/token\n Body:\n username = &lt;wordpress username&gt;\n password = &lt;wordpress password&gt;\n */\n \n $url = $this-&gt;baseurl . &quot;jwt-auth/v1/token&quot;;\n\n $params = array(\n 'requesttype' =&gt; 'POST',\n 'url' =&gt; $url,\n 'post' =&gt; array('username' =&gt; 'admin', 'password' =&gt; 'esmA UJom vxAG LFKU q8oN DSGK')\n );\n $ch = curl_init();\n CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, 1);\n CURL_SETOPT($ch, CURLOPT_URL, $params['url']);\n CURL_SETOPT($ch, CURLOPT_POST, TRUE);\n CURL_SETOPT($ch, CURLOPT_POSTFIELDS, http_build_query($params['post']));\n CURL_SETOPT($ch, CURLOPT_SSL_VERIFYPEER, false);\n $response = curl_exec($ch);\n curl_close($ch);\n return $response;\n}\n</code></pre>\n<p>...You will see way down in $params where I set the username/password. The username is &quot;admin&quot;, because that's the user I set the new application password for, and the password is <code>esmA UJom vxAG LFKU q8oN DSGK</code>. Notice I'm NOT using the admin's WordPress password.</p>\n<p>Your header becomes an array, and it should look something like this, which includes a loooong token string:</p>\n<pre><code>Array ( [0] =&gt; Content-type: application/json [1] =&gt; Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9iYXNpYyIsImlhdCI6MTYyMzI2NjUyNSwibmJmIjoxNjIzMjY2NTI1LCJleHAiOjE2MjM4NzEzMjUsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.YX1UvJ5nlbG2MIlheI2NzTTzaQKBZ8I9WQOr70CE1Tk ) \n</code></pre>\n<p>Finally, the function that makes the request using cURL looks like this:</p>\n<pre><code>public function getResponse($params){\n\n $auth_header = $this-&gt;getAuthHeader();\n\n $ch = curl_init();\n CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, 1);\n CURL_SETOPT($ch, CURLOPT_URL, $params['url']);\n if( isset($params['requesttype']) &amp;&amp; $params['requesttype'] == &quot;POST&quot; ){ //additional code to detect whether I'm making a GET, POST, or PUT request.\n CURL_SETOPT($ch, CURLOPT_POST, TRUE);\n }\n else if( isset($params['requesttype']) &amp;&amp; $params['requesttype'] == &quot;PUT&quot;){\n CURL_SETOPT($ch, CURLOPT_CUSTOMREQUEST, &quot;PUT&quot;);\n }\n if(isset($params['post'])){\n CURL_SETOPT($ch, CURLOPT_POSTFIELDS, http_build_query($params['post']));\n }\n CURL_SETOPT($ch, CURLOPT_SSL_VERIFYPEER, false);\n CURL_SETOPT($ch, CURLOPT_HTTPHEADER, $auth_header);\n $response = curl_exec($ch);\n curl_close($ch);\n return $response;\n}\n</code></pre>\n<p>Notice that before executing the cURL, I want to get my header, with the new token, by calling the getAuthHeader function:</p>\n<pre><code>$auth_header = $this-&gt;getAuthHeader();\n</code></pre>\n<p>and notice that I have to pass that header, which contains the new token, to the web service:</p>\n<pre><code>CURL_SETOPT($ch, CURLOPT_HTTPHEADER, $auth_header);\n</code></pre>\n<p>Barring any typos, which is always my problem, this should return posts with status=draft:</p>\n<pre><code> public function getPosts($params){\n // I passed $params['status'] = &quot;draft&quot;;\n $url = $this-&gt;baseurl . &quot;wp/v2/posts/?status=&quot; . $params['status'] . &quot;&quot;;\n $data = array(\n 'requesttype' =&gt; 'GET',\n 'url' =&gt; $url\n );\n return $this-&gt;getResponse($data);\n }\n</code></pre>\n" }, { "answer_id": 400658, "author": "Govar", "author_id": 147394, "author_profile": "https://wordpress.stackexchange.com/users/147394", "pm_score": 1, "selected": false, "text": "<p>this is work for me as well</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('init', function ()\n{\n if (is_user_logged_in()) :\n global $wp_post_statuses;\n\n $wp_post_statuses['draft']-&gt;public = true;\n $wp_post_statuses['draft']-&gt;exclude_from_search = false;\n $wp_post_statuses['draft']-&gt;publicly_queryable = true;\n endif;\n});\n\nadd_filter('rest_post_query', function ($args)\n{\n $args['post_status'] = ['publish', 'draft'];\n return $args;\n});\n\n</code></pre>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240254", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102247/" ]
I want to check if a post already exists. This includes to check if the post exists as draft as well. But I struggle a little bit with the wordpress API v2. <http://v2.wp-api.org/reference/posts/> Under **List Posts** -> status they say > > Limit result set to posts assigned a specific status. > > Default: publish > > > I tried to assign the value as parameter, but I get an error response: > > {"code":"rest\_invalid\_param","message":"Invalid parameter: status","data":{"status":400,"params":{"status":"Status is forbidden"}}} > > > I als asign the title of the post to check: > > filter[s] = post Title > > > So how to get the posts with draft state? I'm currently using the Basic Auth for developing? I also tried > > filter[post\_status]=draft > > > but with no success. I have the following plugins installed: WP REST API WP REST API - filter fields JSON Basic Authentication
I think the query parameter that you want for post status is: ``` status=draft ``` Let me know if this doesn't work.
240,263
<p>I am using <code>wp_dropdown_pages</code> in the backend of my site to generate a list of pages according to a specific set of criteria.</p> <p>The list only shows <strong><em>published posts</em></strong> where I would like it to show both published posts <strong><em>and drafts</em></strong>.</p> <p>I have found other Stack Exchange threads which show how to accomplish this in the standard wordpress dropdowns, but this does not seem to extend to <code>wp_dropdown_pages</code>.</p> <p>What I am using to show drafts in the standard dropdowns is this:</p> <pre><code>&lt;?php /* Show drafts in dropdown lists */ add_filter('page_attributes_dropdown_pages_args', 'my_attributes_dropdown_pages_args', 1, 1); add_filter('quick_edit_dropdown_pages_args', 'my_attributes_dropdown_pages_args', 1, 1); function my_attributes_dropdown_pages_args($dropdown_args) { $dropdown_args['post_status'] = array('publish','draft'); return $dropdown_args; } ?&gt; </code></pre> <p>The above works great. I would like to do exactly the same thing for custom fields generated using <code>wp_dropdown_pages</code>. To clarify, in the backend, I am generating a dropdown list using the following code:</p> <pre><code>&lt;?php $dropdown_args_food = array( 'depth' =&gt; '2', 'selected' =&gt; $selectedFoodType, 'post_type' =&gt; 'page', 'name' =&gt; 'selected-food-type', 'id' =&gt; 'selected-food-type', 'echo' =&gt; 1, 'meta_key' =&gt; 'category', 'meta_value' =&gt; 'food', 'hierarchical' =&gt; 1, 'show_option_none' =&gt; ' ', ); wp_dropdown_pages( $dropdown_args_food ); ?&gt; </code></pre> <p>The above generates a dropdown list of pages exactly as I want it to be, only without drafts.</p>
[ { "answer_id": 246781, "author": "Jack Lenox", "author_id": 7437, "author_profile": "https://wordpress.stackexchange.com/users/7437", "pm_score": 3, "selected": true, "text": "<p>I think the query parameter that you want for post status is:</p>\n\n<pre><code>status=draft\n</code></pre>\n\n<p>Let me know if this doesn't work.</p>\n" }, { "answer_id": 389000, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 1, "selected": false, "text": "<p>that is due to the fact, that <code>draft</code> is a protected status. and protected status are not publicly queriable simply by adding the attribute to the url. because that would mean, that everybody could query any wordpress api and query for &quot;hidden&quot; posts. by default protected statuses are ‘future‘, ‘draft‘ and ‘pending‘.</p>\n<p>but you still could change that behavior for your api...</p>\n<p>following is a working example, but it only exposes drafts to logged in users:</p>\n<pre><code>/**\n* make drafts public for logged in users\n*/\nfunction so240254_init()\n{\n if (is_user_logged_in()) :\n global $wp_post_statuses;\n\n $wp_post_statuses['draft']-&gt;public = true;\n $wp_post_statuses['draft']-&gt;exclude_from_search = false;\n $wp_post_statuses['draft']-&gt;publicly_queryable = true;\n endif;\n}\nadd_action('init', 'so240254_init');\n\n/*\n* expose drafts to api for logged in users\n*/\nfunction so240254_rest_post_query($args)\n{\n if (is_user_logged_in()) :\n $args['post_status'] = ['publish', 'draft'];\n endif;\n\n return $args;\n}\nadd_filter('rest_post_query', 'so240254_rest_post_query');\n</code></pre>\n<p>now, when you are logged in and call the rest api, you get published and draft posts (no query parameter required!). if not, you only get published posts.</p>\n<p>you could strip the <code>is_user_logged_in()</code> method, if you really wanted to expose drafts to all queries, no matter the current user status...</p>\n" }, { "answer_id": 390321, "author": "TARKUS", "author_id": 90364, "author_profile": "https://wordpress.stackexchange.com/users/90364", "pm_score": 1, "selected": false, "text": "<p>Having recently been through a similar problem, and learning to solve it, I thought I'd share my learning experience.</p>\n<p>As we learned, anybody can request a post with <code>status=publish</code>. If you get errors like the following or similar, then you should start thinking in terms of problems with authentication or permissions:</p>\n<pre><code>stdClass Object\n(\n [code] =&gt; rest_invalid_param\n [message] =&gt; Invalid parameter(s): status\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 400\n [params] =&gt; stdClass Object\n (\n [status] =&gt; Status is forbidden.\n )\n\n [details] =&gt; stdClass Object\n (\n [status] =&gt; stdClass Object\n (\n [code] =&gt; rest_forbidden_status\n [message] =&gt; Status is forbidden.\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 401\n )\n\n )\n\n )\n\n )\n\n )\n</code></pre>\n<p>...or...</p>\n<pre><code>stdClass Object\n(\n [code] =&gt; jwt_auth_invalid_token\n [message] =&gt; Wrong number of segments\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 403\n )\n\n)\n</code></pre>\n<p>...If you are logged in as an admin, then you should have permission to see draft posts. Therefore, it is likely your API calls are not authenticating for some reason.</p>\n<p>The first thing I tested was the token. I happen to be using the <strong>JWT Authentication for WP-API</strong> plugin, which is actually pretty easy to implement. After installing/activating JWT Auth, go to the user you want to assign to use your API calls, and at the bottom of the user profile you will see :</p>\n<p><a href=\"https://i.stack.imgur.com/Es3ar.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Es3ar.png\" alt=\"Application Account name\" /></a></p>\n<p>Give your application a name, Add New, and then a new application password will pop up. It will look like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Y0rF4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y0rF4.png\" alt=\"Application password\" /></a></p>\n<p>Copy the whole password, keeping the spaces is fine.</p>\n<p>I'm using PHP and cURL, so my get token code looks like this:</p>\n<pre><code>private function getAuthHeader(){\n $JWTtoken = json_decode($this-&gt;getJWTToken());\n $token = $JWTtoken-&gt;token;\n $header = array(\n &quot;Content-type: application/json&quot;, \n &quot;Authorization: Bearer &quot; . $token\n );\n return $header;\n}\n\npublic function getJWTToken(){\n /*\n Request: POST http://basic/wp-json/api/v1/token\n Body:\n username = &lt;wordpress username&gt;\n password = &lt;wordpress password&gt;\n */\n \n $url = $this-&gt;baseurl . &quot;jwt-auth/v1/token&quot;;\n\n $params = array(\n 'requesttype' =&gt; 'POST',\n 'url' =&gt; $url,\n 'post' =&gt; array('username' =&gt; 'admin', 'password' =&gt; 'esmA UJom vxAG LFKU q8oN DSGK')\n );\n $ch = curl_init();\n CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, 1);\n CURL_SETOPT($ch, CURLOPT_URL, $params['url']);\n CURL_SETOPT($ch, CURLOPT_POST, TRUE);\n CURL_SETOPT($ch, CURLOPT_POSTFIELDS, http_build_query($params['post']));\n CURL_SETOPT($ch, CURLOPT_SSL_VERIFYPEER, false);\n $response = curl_exec($ch);\n curl_close($ch);\n return $response;\n}\n</code></pre>\n<p>...You will see way down in $params where I set the username/password. The username is &quot;admin&quot;, because that's the user I set the new application password for, and the password is <code>esmA UJom vxAG LFKU q8oN DSGK</code>. Notice I'm NOT using the admin's WordPress password.</p>\n<p>Your header becomes an array, and it should look something like this, which includes a loooong token string:</p>\n<pre><code>Array ( [0] =&gt; Content-type: application/json [1] =&gt; Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9iYXNpYyIsImlhdCI6MTYyMzI2NjUyNSwibmJmIjoxNjIzMjY2NTI1LCJleHAiOjE2MjM4NzEzMjUsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.YX1UvJ5nlbG2MIlheI2NzTTzaQKBZ8I9WQOr70CE1Tk ) \n</code></pre>\n<p>Finally, the function that makes the request using cURL looks like this:</p>\n<pre><code>public function getResponse($params){\n\n $auth_header = $this-&gt;getAuthHeader();\n\n $ch = curl_init();\n CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, 1);\n CURL_SETOPT($ch, CURLOPT_URL, $params['url']);\n if( isset($params['requesttype']) &amp;&amp; $params['requesttype'] == &quot;POST&quot; ){ //additional code to detect whether I'm making a GET, POST, or PUT request.\n CURL_SETOPT($ch, CURLOPT_POST, TRUE);\n }\n else if( isset($params['requesttype']) &amp;&amp; $params['requesttype'] == &quot;PUT&quot;){\n CURL_SETOPT($ch, CURLOPT_CUSTOMREQUEST, &quot;PUT&quot;);\n }\n if(isset($params['post'])){\n CURL_SETOPT($ch, CURLOPT_POSTFIELDS, http_build_query($params['post']));\n }\n CURL_SETOPT($ch, CURLOPT_SSL_VERIFYPEER, false);\n CURL_SETOPT($ch, CURLOPT_HTTPHEADER, $auth_header);\n $response = curl_exec($ch);\n curl_close($ch);\n return $response;\n}\n</code></pre>\n<p>Notice that before executing the cURL, I want to get my header, with the new token, by calling the getAuthHeader function:</p>\n<pre><code>$auth_header = $this-&gt;getAuthHeader();\n</code></pre>\n<p>and notice that I have to pass that header, which contains the new token, to the web service:</p>\n<pre><code>CURL_SETOPT($ch, CURLOPT_HTTPHEADER, $auth_header);\n</code></pre>\n<p>Barring any typos, which is always my problem, this should return posts with status=draft:</p>\n<pre><code> public function getPosts($params){\n // I passed $params['status'] = &quot;draft&quot;;\n $url = $this-&gt;baseurl . &quot;wp/v2/posts/?status=&quot; . $params['status'] . &quot;&quot;;\n $data = array(\n 'requesttype' =&gt; 'GET',\n 'url' =&gt; $url\n );\n return $this-&gt;getResponse($data);\n }\n</code></pre>\n" }, { "answer_id": 400658, "author": "Govar", "author_id": 147394, "author_profile": "https://wordpress.stackexchange.com/users/147394", "pm_score": 1, "selected": false, "text": "<p>this is work for me as well</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('init', function ()\n{\n if (is_user_logged_in()) :\n global $wp_post_statuses;\n\n $wp_post_statuses['draft']-&gt;public = true;\n $wp_post_statuses['draft']-&gt;exclude_from_search = false;\n $wp_post_statuses['draft']-&gt;publicly_queryable = true;\n endif;\n});\n\nadd_filter('rest_post_query', function ($args)\n{\n $args['post_status'] = ['publish', 'draft'];\n return $args;\n});\n\n</code></pre>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103436/" ]
I am using `wp_dropdown_pages` in the backend of my site to generate a list of pages according to a specific set of criteria. The list only shows ***published posts*** where I would like it to show both published posts ***and drafts***. I have found other Stack Exchange threads which show how to accomplish this in the standard wordpress dropdowns, but this does not seem to extend to `wp_dropdown_pages`. What I am using to show drafts in the standard dropdowns is this: ``` <?php /* Show drafts in dropdown lists */ add_filter('page_attributes_dropdown_pages_args', 'my_attributes_dropdown_pages_args', 1, 1); add_filter('quick_edit_dropdown_pages_args', 'my_attributes_dropdown_pages_args', 1, 1); function my_attributes_dropdown_pages_args($dropdown_args) { $dropdown_args['post_status'] = array('publish','draft'); return $dropdown_args; } ?> ``` The above works great. I would like to do exactly the same thing for custom fields generated using `wp_dropdown_pages`. To clarify, in the backend, I am generating a dropdown list using the following code: ``` <?php $dropdown_args_food = array( 'depth' => '2', 'selected' => $selectedFoodType, 'post_type' => 'page', 'name' => 'selected-food-type', 'id' => 'selected-food-type', 'echo' => 1, 'meta_key' => 'category', 'meta_value' => 'food', 'hierarchical' => 1, 'show_option_none' => ' ', ); wp_dropdown_pages( $dropdown_args_food ); ?> ``` The above generates a dropdown list of pages exactly as I want it to be, only without drafts.
I think the query parameter that you want for post status is: ``` status=draft ``` Let me know if this doesn't work.
240,272
<p>I'm am setting up my first network site on a subdirectory based network.</p> <p>My <code>.htaccess</code> is copied directly from the "Network Setup" page of the network admin panel. This is currently in the file:</p> <pre><code># BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] # END WordPress </code></pre> <p>And the correct section of my <code>wp-config.php</code> file was copied from the same page, save the first definition:</p> <pre><code>define( 'WP_ALLOW_MULTISITE', true ); define( 'MULTISITE', true ); define( 'SUBDOMAIN_INSTALL', false ); define( 'DOMAIN_CURRENT_SITE', 'example.com' ); define( 'PATH_CURRENT_SITE', '/' ); define( 'SITE_ID_CURRENT_SITE', 1 ); define( 'BLOG_ID_CURRENT_SITE', 1 ); </code></pre> <p>The resources on the front-end and the admin panel are being requested from <code>https://example.com/</code> whenever we go to <code>https://example.com/</code> and from <code>https://example.com/site1</code> whenever we go to <code>https://example.com/site1</code>. This is the part I'm not familiar with, is that expected functionality?</p> <p>What am I missing to be able to successfully request the resources needed to fully render the page?</p>
[ { "answer_id": 246781, "author": "Jack Lenox", "author_id": 7437, "author_profile": "https://wordpress.stackexchange.com/users/7437", "pm_score": 3, "selected": true, "text": "<p>I think the query parameter that you want for post status is:</p>\n\n<pre><code>status=draft\n</code></pre>\n\n<p>Let me know if this doesn't work.</p>\n" }, { "answer_id": 389000, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 1, "selected": false, "text": "<p>that is due to the fact, that <code>draft</code> is a protected status. and protected status are not publicly queriable simply by adding the attribute to the url. because that would mean, that everybody could query any wordpress api and query for &quot;hidden&quot; posts. by default protected statuses are ‘future‘, ‘draft‘ and ‘pending‘.</p>\n<p>but you still could change that behavior for your api...</p>\n<p>following is a working example, but it only exposes drafts to logged in users:</p>\n<pre><code>/**\n* make drafts public for logged in users\n*/\nfunction so240254_init()\n{\n if (is_user_logged_in()) :\n global $wp_post_statuses;\n\n $wp_post_statuses['draft']-&gt;public = true;\n $wp_post_statuses['draft']-&gt;exclude_from_search = false;\n $wp_post_statuses['draft']-&gt;publicly_queryable = true;\n endif;\n}\nadd_action('init', 'so240254_init');\n\n/*\n* expose drafts to api for logged in users\n*/\nfunction so240254_rest_post_query($args)\n{\n if (is_user_logged_in()) :\n $args['post_status'] = ['publish', 'draft'];\n endif;\n\n return $args;\n}\nadd_filter('rest_post_query', 'so240254_rest_post_query');\n</code></pre>\n<p>now, when you are logged in and call the rest api, you get published and draft posts (no query parameter required!). if not, you only get published posts.</p>\n<p>you could strip the <code>is_user_logged_in()</code> method, if you really wanted to expose drafts to all queries, no matter the current user status...</p>\n" }, { "answer_id": 390321, "author": "TARKUS", "author_id": 90364, "author_profile": "https://wordpress.stackexchange.com/users/90364", "pm_score": 1, "selected": false, "text": "<p>Having recently been through a similar problem, and learning to solve it, I thought I'd share my learning experience.</p>\n<p>As we learned, anybody can request a post with <code>status=publish</code>. If you get errors like the following or similar, then you should start thinking in terms of problems with authentication or permissions:</p>\n<pre><code>stdClass Object\n(\n [code] =&gt; rest_invalid_param\n [message] =&gt; Invalid parameter(s): status\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 400\n [params] =&gt; stdClass Object\n (\n [status] =&gt; Status is forbidden.\n )\n\n [details] =&gt; stdClass Object\n (\n [status] =&gt; stdClass Object\n (\n [code] =&gt; rest_forbidden_status\n [message] =&gt; Status is forbidden.\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 401\n )\n\n )\n\n )\n\n )\n\n )\n</code></pre>\n<p>...or...</p>\n<pre><code>stdClass Object\n(\n [code] =&gt; jwt_auth_invalid_token\n [message] =&gt; Wrong number of segments\n [data] =&gt; stdClass Object\n (\n [status] =&gt; 403\n )\n\n)\n</code></pre>\n<p>...If you are logged in as an admin, then you should have permission to see draft posts. Therefore, it is likely your API calls are not authenticating for some reason.</p>\n<p>The first thing I tested was the token. I happen to be using the <strong>JWT Authentication for WP-API</strong> plugin, which is actually pretty easy to implement. After installing/activating JWT Auth, go to the user you want to assign to use your API calls, and at the bottom of the user profile you will see :</p>\n<p><a href=\"https://i.stack.imgur.com/Es3ar.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Es3ar.png\" alt=\"Application Account name\" /></a></p>\n<p>Give your application a name, Add New, and then a new application password will pop up. It will look like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Y0rF4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y0rF4.png\" alt=\"Application password\" /></a></p>\n<p>Copy the whole password, keeping the spaces is fine.</p>\n<p>I'm using PHP and cURL, so my get token code looks like this:</p>\n<pre><code>private function getAuthHeader(){\n $JWTtoken = json_decode($this-&gt;getJWTToken());\n $token = $JWTtoken-&gt;token;\n $header = array(\n &quot;Content-type: application/json&quot;, \n &quot;Authorization: Bearer &quot; . $token\n );\n return $header;\n}\n\npublic function getJWTToken(){\n /*\n Request: POST http://basic/wp-json/api/v1/token\n Body:\n username = &lt;wordpress username&gt;\n password = &lt;wordpress password&gt;\n */\n \n $url = $this-&gt;baseurl . &quot;jwt-auth/v1/token&quot;;\n\n $params = array(\n 'requesttype' =&gt; 'POST',\n 'url' =&gt; $url,\n 'post' =&gt; array('username' =&gt; 'admin', 'password' =&gt; 'esmA UJom vxAG LFKU q8oN DSGK')\n );\n $ch = curl_init();\n CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, 1);\n CURL_SETOPT($ch, CURLOPT_URL, $params['url']);\n CURL_SETOPT($ch, CURLOPT_POST, TRUE);\n CURL_SETOPT($ch, CURLOPT_POSTFIELDS, http_build_query($params['post']));\n CURL_SETOPT($ch, CURLOPT_SSL_VERIFYPEER, false);\n $response = curl_exec($ch);\n curl_close($ch);\n return $response;\n}\n</code></pre>\n<p>...You will see way down in $params where I set the username/password. The username is &quot;admin&quot;, because that's the user I set the new application password for, and the password is <code>esmA UJom vxAG LFKU q8oN DSGK</code>. Notice I'm NOT using the admin's WordPress password.</p>\n<p>Your header becomes an array, and it should look something like this, which includes a loooong token string:</p>\n<pre><code>Array ( [0] =&gt; Content-type: application/json [1] =&gt; Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9iYXNpYyIsImlhdCI6MTYyMzI2NjUyNSwibmJmIjoxNjIzMjY2NTI1LCJleHAiOjE2MjM4NzEzMjUsImRhdGEiOnsidXNlciI6eyJpZCI6IjEifX19.YX1UvJ5nlbG2MIlheI2NzTTzaQKBZ8I9WQOr70CE1Tk ) \n</code></pre>\n<p>Finally, the function that makes the request using cURL looks like this:</p>\n<pre><code>public function getResponse($params){\n\n $auth_header = $this-&gt;getAuthHeader();\n\n $ch = curl_init();\n CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER, 1);\n CURL_SETOPT($ch, CURLOPT_URL, $params['url']);\n if( isset($params['requesttype']) &amp;&amp; $params['requesttype'] == &quot;POST&quot; ){ //additional code to detect whether I'm making a GET, POST, or PUT request.\n CURL_SETOPT($ch, CURLOPT_POST, TRUE);\n }\n else if( isset($params['requesttype']) &amp;&amp; $params['requesttype'] == &quot;PUT&quot;){\n CURL_SETOPT($ch, CURLOPT_CUSTOMREQUEST, &quot;PUT&quot;);\n }\n if(isset($params['post'])){\n CURL_SETOPT($ch, CURLOPT_POSTFIELDS, http_build_query($params['post']));\n }\n CURL_SETOPT($ch, CURLOPT_SSL_VERIFYPEER, false);\n CURL_SETOPT($ch, CURLOPT_HTTPHEADER, $auth_header);\n $response = curl_exec($ch);\n curl_close($ch);\n return $response;\n}\n</code></pre>\n<p>Notice that before executing the cURL, I want to get my header, with the new token, by calling the getAuthHeader function:</p>\n<pre><code>$auth_header = $this-&gt;getAuthHeader();\n</code></pre>\n<p>and notice that I have to pass that header, which contains the new token, to the web service:</p>\n<pre><code>CURL_SETOPT($ch, CURLOPT_HTTPHEADER, $auth_header);\n</code></pre>\n<p>Barring any typos, which is always my problem, this should return posts with status=draft:</p>\n<pre><code> public function getPosts($params){\n // I passed $params['status'] = &quot;draft&quot;;\n $url = $this-&gt;baseurl . &quot;wp/v2/posts/?status=&quot; . $params['status'] . &quot;&quot;;\n $data = array(\n 'requesttype' =&gt; 'GET',\n 'url' =&gt; $url\n );\n return $this-&gt;getResponse($data);\n }\n</code></pre>\n" }, { "answer_id": 400658, "author": "Govar", "author_id": 147394, "author_profile": "https://wordpress.stackexchange.com/users/147394", "pm_score": 1, "selected": false, "text": "<p>this is work for me as well</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('init', function ()\n{\n if (is_user_logged_in()) :\n global $wp_post_statuses;\n\n $wp_post_statuses['draft']-&gt;public = true;\n $wp_post_statuses['draft']-&gt;exclude_from_search = false;\n $wp_post_statuses['draft']-&gt;publicly_queryable = true;\n endif;\n});\n\nadd_filter('rest_post_query', function ($args)\n{\n $args['post_status'] = ['publish', 'draft'];\n return $args;\n});\n\n</code></pre>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240272", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64943/" ]
I'm am setting up my first network site on a subdirectory based network. My `.htaccess` is copied directly from the "Network Setup" page of the network admin panel. This is currently in the file: ``` # BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] # END WordPress ``` And the correct section of my `wp-config.php` file was copied from the same page, save the first definition: ``` define( 'WP_ALLOW_MULTISITE', true ); define( 'MULTISITE', true ); define( 'SUBDOMAIN_INSTALL', false ); define( 'DOMAIN_CURRENT_SITE', 'example.com' ); define( 'PATH_CURRENT_SITE', '/' ); define( 'SITE_ID_CURRENT_SITE', 1 ); define( 'BLOG_ID_CURRENT_SITE', 1 ); ``` The resources on the front-end and the admin panel are being requested from `https://example.com/` whenever we go to `https://example.com/` and from `https://example.com/site1` whenever we go to `https://example.com/site1`. This is the part I'm not familiar with, is that expected functionality? What am I missing to be able to successfully request the resources needed to fully render the page?
I think the query parameter that you want for post status is: ``` status=draft ``` Let me know if this doesn't work.
240,273
<p>I'm making a plugin that compares data from external API with meta items in WordPress backoffice.</p> <p>I tried using <code>wp_remote_get</code> method to query my API but it doesn't return anything, nobody, nothing. When accessed directly with the same URL in browser the API generates JSON array without problems.</p> <p>What am I doing wrong?</p> <p>This is (partially omitted code in the plugin)</p> <pre><code> .......... $chopped = explode("@", $meta['Email'][0]); $url = 'http://example.com/api/users/'.$chopped[0].'/'.$chopped[1]; global $wp_version; $args = array( 'timeout' =&gt; 5, 'redirection' =&gt; 5, 'httpversion' =&gt; '1.0', 'user-agent' =&gt; 'WordPress/' . $wp_version . '; ' . home_url(), 'blocking' =&gt; true, 'headers' =&gt; array(), 'cookies' =&gt; array(), ); $response = wp_remote_get( $url, $args ); $body = wp_remote_retrieve_body( $response ); $http_code = wp_remote_retrieve_response_code( $response ); echo '&lt;pre&gt; Test dump: '.print_r($http_code,1).'&lt;/pre&gt;'; </code></pre> <p>edit 1: For those who might think it has to do with csrf protection or similiar, I can query the api from <a href="https://www.hurl.it/" rel="nofollow">https://www.hurl.it/</a> without any problems too. Could the error be because I'm calling it inside a hook?</p> <p>edit 2: The response code I'm getting</p> <pre><code>WP_Error Object ( [errors] =&gt; Array ( [http_request_failed] =&gt; Array ( [0] =&gt; Connection timed out after 5003 milliseconds ) ) [error_data] =&gt; Array ( ) ) </code></pre>
[ { "answer_id": 264002, "author": "antonio polastri", "author_id": 117895, "author_profile": "https://wordpress.stackexchange.com/users/117895", "pm_score": 3, "selected": false, "text": "<p>Check with these args</p>\n\n<pre><code>$args = array(\n 'timeout' =&gt; 10,\n 'sslverify' =&gt; false\n); \n</code></pre>\n" }, { "answer_id": 406376, "author": "Ramin eghbalian", "author_id": 221978, "author_profile": "https://wordpress.stackexchange.com/users/221978", "pm_score": 0, "selected": false, "text": "<p>just <strong>set a timeout argument</strong> for that.</p>\n<pre><code>wp_remote_get('Your Rest API URL', ['timeout' =&gt; 20]);\n</code></pre>\n<p>or you can also set it in the <code>functions.php</code> file:</p>\n<pre><code>function custom_timeout_extend( $time )\n{\n return 20;\n}\n\nadd_filter( 'http_request_timeout', 'custom_timeout_extend' );\n</code></pre>\n" } ]
2016/09/22
[ "https://wordpress.stackexchange.com/questions/240273", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103264/" ]
I'm making a plugin that compares data from external API with meta items in WordPress backoffice. I tried using `wp_remote_get` method to query my API but it doesn't return anything, nobody, nothing. When accessed directly with the same URL in browser the API generates JSON array without problems. What am I doing wrong? This is (partially omitted code in the plugin) ``` .......... $chopped = explode("@", $meta['Email'][0]); $url = 'http://example.com/api/users/'.$chopped[0].'/'.$chopped[1]; global $wp_version; $args = array( 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url(), 'blocking' => true, 'headers' => array(), 'cookies' => array(), ); $response = wp_remote_get( $url, $args ); $body = wp_remote_retrieve_body( $response ); $http_code = wp_remote_retrieve_response_code( $response ); echo '<pre> Test dump: '.print_r($http_code,1).'</pre>'; ``` edit 1: For those who might think it has to do with csrf protection or similiar, I can query the api from <https://www.hurl.it/> without any problems too. Could the error be because I'm calling it inside a hook? edit 2: The response code I'm getting ``` WP_Error Object ( [errors] => Array ( [http_request_failed] => Array ( [0] => Connection timed out after 5003 milliseconds ) ) [error_data] => Array ( ) ) ```
Check with these args ``` $args = array( 'timeout' => 10, 'sslverify' => false ); ```
240,295
<p>I want to provide functionality to create a single post into my custom post type. And for this, when user click on main option (name of post) at left side bar in word-press back-end It's automatically redirect on "Add New Post" or if a post already created then automatically redirect on "Edit Post" (existing post edit).</p> <p>Right now at back-end the post option look like this - </p> <p><a href="https://i.stack.imgur.com/JYYwO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JYYwO.png" alt="My Posts"></a></p> <p>So, now i don't want sub menu. and preform add/edit post option on main menu click. Is this possible, if yes then can you please tell me how to achieve this? </p>
[ { "answer_id": 264002, "author": "antonio polastri", "author_id": 117895, "author_profile": "https://wordpress.stackexchange.com/users/117895", "pm_score": 3, "selected": false, "text": "<p>Check with these args</p>\n\n<pre><code>$args = array(\n 'timeout' =&gt; 10,\n 'sslverify' =&gt; false\n); \n</code></pre>\n" }, { "answer_id": 406376, "author": "Ramin eghbalian", "author_id": 221978, "author_profile": "https://wordpress.stackexchange.com/users/221978", "pm_score": 0, "selected": false, "text": "<p>just <strong>set a timeout argument</strong> for that.</p>\n<pre><code>wp_remote_get('Your Rest API URL', ['timeout' =&gt; 20]);\n</code></pre>\n<p>or you can also set it in the <code>functions.php</code> file:</p>\n<pre><code>function custom_timeout_extend( $time )\n{\n return 20;\n}\n\nadd_filter( 'http_request_timeout', 'custom_timeout_extend' );\n</code></pre>\n" } ]
2016/09/23
[ "https://wordpress.stackexchange.com/questions/240295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102479/" ]
I want to provide functionality to create a single post into my custom post type. And for this, when user click on main option (name of post) at left side bar in word-press back-end It's automatically redirect on "Add New Post" or if a post already created then automatically redirect on "Edit Post" (existing post edit). Right now at back-end the post option look like this - [![My Posts](https://i.stack.imgur.com/JYYwO.png)](https://i.stack.imgur.com/JYYwO.png) So, now i don't want sub menu. and preform add/edit post option on main menu click. Is this possible, if yes then can you please tell me how to achieve this?
Check with these args ``` $args = array( 'timeout' => 10, 'sslverify' => false ); ```
240,330
<p>I'm try to exclude a specific category from a list of categories that a custom post has (in this case 'Uncategorized' - ID: 1).</p> <p>I've tried <code>exclude</code>:</p> <pre><code>wp_list_categories([ 'include' =&gt; wp_list_pluck(get_the_category(), 'term_id'), 'title_li' =&gt; '', 'exclude' =&gt; 1 ]); </code></pre> <p>But it still appears. How can I make sure it never appears, even if a post is tagged 'Uncategorized'?</p>
[ { "answer_id": 240332, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>The <code>wp_list_categories()</code> function uses <code>get_terms()</code> behind the scenes, where the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/#parameters\" rel=\"nofollow\">documentation</a> for the <code>exclude</code> argument says:</p>\n\n<blockquote>\n <p>If <code>$include</code> is non-empty, <code>$exclude</code> is ignored.</p>\n</blockquote>\n\n<p>Instead you could try to exclude the <code>term_id</code> from the <code>include</code> values:</p>\n\n<pre><code>$include = wp_filter_object_list( \n get_the_category(), // Data\n [ 'term_id' =&gt; 1 ], // Filter Data\n 'NOT', // Filter Option (exclude)\n 'term_id' // Pluck Data \n);\n</code></pre>\n\n<p>where we use <a href=\"https://codex.wordpress.org/Function_Reference/wp_filter_object_list\" rel=\"nofollow\"><code>wp_filter_object_list()</code></a> to both <em>filter</em> and <em>pluck</em>. In general it could be better to check if the <code>$include</code> array is empty or not:</p>\n\n<pre><code>if( $include )\n{\n // ... stuff above ...\n\n wp_list_categories( [\n 'include' =&gt; $includes,\n 'title_li' =&gt; '',\n ] );\n\n // ... stuff below...\n}\n</code></pre>\n" }, { "answer_id": 240335, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 2, "selected": false, "text": "<p>I build some tricky code to exclude category having ID 1. I'm trying to exclude category(ID:1) even remove from pluck also. Your code has include and exclude both parameter and this conflict the result.</p>\n\n<pre><code>//List the pluck...\n$exclude_cat_id = 1;\n$list_pluck = wp_list_pluck(get_the_category(), 'term_id');\n\n//Get exlude pluck(ID:1) index...\n$exclude_pluck = array_search($exclude_cat_id, $list_pluck);\n\n//unset excluded pluck...\nunset($list_pluck[$exclude_pluck]);\n\n//Get all category except ID=1\n$arrCat = wp_list_categories([\n 'include' =&gt; $list_pluck,\n 'title_li' =&gt; '',\n 'exclude' =&gt; array($exclude_cat_id),\n 'exclude_tree' =&gt; array($exclude_cat_id),\n]);\n</code></pre>\n\n<p>Hope this help you well!</p>\n" }, { "answer_id": 240343, "author": "Django Reinhardt", "author_id": 4109, "author_profile": "https://wordpress.stackexchange.com/users/4109", "pm_score": 2, "selected": false, "text": "<p>If my case, the only time I didn't want the list of categories to appear was if a post was 'Uncategorized'. The simplest solution in the end was just to use <code>in_category()</code>:</p>\n\n<pre><code>if (!in_category(1)) {\n // Display the categories this post belongs to, as links\n wp_list_categories([\n 'include' =&gt; wp_list_pluck(get_the_category(), 'term_id'),\n 'title_li' =&gt; ''\n ]);\n}\n</code></pre>\n" }, { "answer_id": 240356, "author": "rajnik faldu", "author_id": 103482, "author_profile": "https://wordpress.stackexchange.com/users/103482", "pm_score": 0, "selected": false, "text": "<pre><code> $exclude = array();\n foreach (get_categories() as $category) \n {$exclude[] = 1;}\n if (! empty($exclude)) \n { $args .= ('' === $args) ? '' : '&amp;';$args .= exclude='.implode(',', $exclude);}\n wp_list_categories($args);\n</code></pre>\n" }, { "answer_id": 370109, "author": "David Lee", "author_id": 190627, "author_profile": "https://wordpress.stackexchange.com/users/190627", "pm_score": -1, "selected": false, "text": "<p>How can I display only the specific category when accessing the posts related to that category? For example, I want to show only CSR Events under Categories When accessing posts related to CSR events. Here's the link to CSR post <a href=\"https://www.mi-eq.com/blood-donation-compaign/\" rel=\"nofollow noreferrer\">https://www.mi-eq.com/blood-donation-compaign/</a></p>\n<p>Screenshot: <a href=\"https://i.stack.imgur.com/YoTfk.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/YoTfk.jpg</a></p>\n<p>Similarly, when visiting posts related to other categories, only the specific category will be shown. Is there any simplest to achieve that?</p>\n" } ]
2016/09/23
[ "https://wordpress.stackexchange.com/questions/240330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4109/" ]
I'm try to exclude a specific category from a list of categories that a custom post has (in this case 'Uncategorized' - ID: 1). I've tried `exclude`: ``` wp_list_categories([ 'include' => wp_list_pluck(get_the_category(), 'term_id'), 'title_li' => '', 'exclude' => 1 ]); ``` But it still appears. How can I make sure it never appears, even if a post is tagged 'Uncategorized'?
The `wp_list_categories()` function uses `get_terms()` behind the scenes, where the [documentation](https://developer.wordpress.org/reference/functions/get_terms/#parameters) for the `exclude` argument says: > > If `$include` is non-empty, `$exclude` is ignored. > > > Instead you could try to exclude the `term_id` from the `include` values: ``` $include = wp_filter_object_list( get_the_category(), // Data [ 'term_id' => 1 ], // Filter Data 'NOT', // Filter Option (exclude) 'term_id' // Pluck Data ); ``` where we use [`wp_filter_object_list()`](https://codex.wordpress.org/Function_Reference/wp_filter_object_list) to both *filter* and *pluck*. In general it could be better to check if the `$include` array is empty or not: ``` if( $include ) { // ... stuff above ... wp_list_categories( [ 'include' => $includes, 'title_li' => '', ] ); // ... stuff below... } ```
240,352
<p>I often find the need to add class or ID's to Wordpress functions. Preferably I would like to do this in the a template (not in <code>functions.php</code>).</p> <p>Example: <code>&lt;?php the_excerpt(); ?&gt;</code> Will output the excerpt inside <code>&lt;p&gt;</code>. How can I add a class to the paragraph so that I get <code>&lt;p class="something"&gt;The excerpt text...&lt;/p&gt;</code></p>
[ { "answer_id": 240364, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the way to do this is by wrapping everything in a div with whatever class you want, like</p>\n\n<pre><code>&lt;div class=\"myexcerpt\"&gt;\n&lt;?php the_excerpt()?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>and then to style it (or JS) you can use</p>\n\n<pre><code>.myexcerpt p {}\n</code></pre>\n\n<p><code>div</code> has no semantic value and this kind of things is exactly why it exist.</p>\n" }, { "answer_id": 240367, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>If you have only one template it's fine to do something like:</p>\n\n<pre><code>echo '&lt;p class=\"whatever\"&gt;' . get_the_excerpt() . '&lt;/p&gt;';\n</code></pre>\n\n<p>However, if you have multiple templates and want to control the classes centrally, you can make a filter on <a href=\"https://developer.wordpress.org/reference/hooks/get_the_excerpt/\" rel=\"nofollow\"><code>get_the_excerpt</code></a> as follows (but yeah, that would be in <code>functions.php</code>):</p>\n\n<pre><code>add_filter ('get_the_excerpt','wpse240352_filter_excerpt');\n\nfunction wpse240352_filter_excerpt ($post_excerpt) { \n $post_excerpt = '&lt;p class=\"whatever\"&gt;' . $post_excerpt . '&lt;/p&gt;';\n return $post_excerpt;\n } \n</code></pre>\n\n<p>You would then simply have <code>echo get_the_excerpt();</code> in your template files.</p>\n" } ]
2016/09/23
[ "https://wordpress.stackexchange.com/questions/240352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82313/" ]
I often find the need to add class or ID's to Wordpress functions. Preferably I would like to do this in the a template (not in `functions.php`). Example: `<?php the_excerpt(); ?>` Will output the excerpt inside `<p>`. How can I add a class to the paragraph so that I get `<p class="something">The excerpt text...</p>`
If you have only one template it's fine to do something like: ``` echo '<p class="whatever">' . get_the_excerpt() . '</p>'; ``` However, if you have multiple templates and want to control the classes centrally, you can make a filter on [`get_the_excerpt`](https://developer.wordpress.org/reference/hooks/get_the_excerpt/) as follows (but yeah, that would be in `functions.php`): ``` add_filter ('get_the_excerpt','wpse240352_filter_excerpt'); function wpse240352_filter_excerpt ($post_excerpt) { $post_excerpt = '<p class="whatever">' . $post_excerpt . '</p>'; return $post_excerpt; } ``` You would then simply have `echo get_the_excerpt();` in your template files.
240,381
<p>I have this form:</p> <pre><code>&lt;form action="&lt;?php the permalink(); ?&gt;" method="get" &gt; &lt;input type="hidden" name="taxo" value="question" /&gt; &lt;select name = "cata"&gt; &lt;option value='unique_name-a'&gt;xxx&lt;/option&gt; &lt;option value='foo'&gt;yyy&lt;/option&gt; &lt;option value='bar'&gt;zzz&lt;/option&gt; &lt;/select&gt; &lt;select name ="catb"&gt; &lt;option value='unique_name-d'&gt;xxx&lt;/option&gt; &lt;option value='unique_name-e'&gt;yyy&lt;/option&gt; &lt;option value='unique_name-f'&gt;zzz&lt;/option&gt; &lt;/select&gt; &lt;!-- and more select --&gt; &lt;button&gt;send&lt;/button&gt; &lt;/form&gt; </code></pre> <p>And this query in a template page:</p> <pre><code>$query = new WP_Query( array( 'post_type' =&gt; 'page', 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'question', // from $_GET['taxo'] 'field' =&gt; 'slug', 'terms' =&gt; array('unique_name-a','unique_name-e','more'), // from my submit form 'include_children' =&gt; false, 'operator' =&gt; 'AND' ), ) ) ); </code></pre> <p>I would like to play with URL rewriting. I have something like:</p> <pre><code>http://example.com/?taxo=question&amp;cata=foo&amp;catb=bar&amp;catc=more </code></pre> <p>I would like the rewritten URL for the above query to be:</p> <pre><code>http://example.com/questions/cata/foo/catb/bar/catc/…/ </code></pre> <p>EDIT: Why this function is not working?</p> <pre><code> function custom_rewrite() { add_rewrite_rule( 'question-tax/test/4/', 'index.php?tax=question&amp;test=4', 'top' ); } // refresh/flush permalinks in the dashboard if this is changed in any way add_action( 'init', 'custom_rewrite' ); </code></pre>
[ { "answer_id": 240364, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the way to do this is by wrapping everything in a div with whatever class you want, like</p>\n\n<pre><code>&lt;div class=\"myexcerpt\"&gt;\n&lt;?php the_excerpt()?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>and then to style it (or JS) you can use</p>\n\n<pre><code>.myexcerpt p {}\n</code></pre>\n\n<p><code>div</code> has no semantic value and this kind of things is exactly why it exist.</p>\n" }, { "answer_id": 240367, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>If you have only one template it's fine to do something like:</p>\n\n<pre><code>echo '&lt;p class=\"whatever\"&gt;' . get_the_excerpt() . '&lt;/p&gt;';\n</code></pre>\n\n<p>However, if you have multiple templates and want to control the classes centrally, you can make a filter on <a href=\"https://developer.wordpress.org/reference/hooks/get_the_excerpt/\" rel=\"nofollow\"><code>get_the_excerpt</code></a> as follows (but yeah, that would be in <code>functions.php</code>):</p>\n\n<pre><code>add_filter ('get_the_excerpt','wpse240352_filter_excerpt');\n\nfunction wpse240352_filter_excerpt ($post_excerpt) { \n $post_excerpt = '&lt;p class=\"whatever\"&gt;' . $post_excerpt . '&lt;/p&gt;';\n return $post_excerpt;\n } \n</code></pre>\n\n<p>You would then simply have <code>echo get_the_excerpt();</code> in your template files.</p>\n" } ]
2016/09/23
[ "https://wordpress.stackexchange.com/questions/240381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16969/" ]
I have this form: ``` <form action="<?php the permalink(); ?>" method="get" > <input type="hidden" name="taxo" value="question" /> <select name = "cata"> <option value='unique_name-a'>xxx</option> <option value='foo'>yyy</option> <option value='bar'>zzz</option> </select> <select name ="catb"> <option value='unique_name-d'>xxx</option> <option value='unique_name-e'>yyy</option> <option value='unique_name-f'>zzz</option> </select> <!-- and more select --> <button>send</button> </form> ``` And this query in a template page: ``` $query = new WP_Query( array( 'post_type' => 'page', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'question', // from $_GET['taxo'] 'field' => 'slug', 'terms' => array('unique_name-a','unique_name-e','more'), // from my submit form 'include_children' => false, 'operator' => 'AND' ), ) ) ); ``` I would like to play with URL rewriting. I have something like: ``` http://example.com/?taxo=question&cata=foo&catb=bar&catc=more ``` I would like the rewritten URL for the above query to be: ``` http://example.com/questions/cata/foo/catb/bar/catc/…/ ``` EDIT: Why this function is not working? ``` function custom_rewrite() { add_rewrite_rule( 'question-tax/test/4/', 'index.php?tax=question&test=4', 'top' ); } // refresh/flush permalinks in the dashboard if this is changed in any way add_action( 'init', 'custom_rewrite' ); ```
If you have only one template it's fine to do something like: ``` echo '<p class="whatever">' . get_the_excerpt() . '</p>'; ``` However, if you have multiple templates and want to control the classes centrally, you can make a filter on [`get_the_excerpt`](https://developer.wordpress.org/reference/hooks/get_the_excerpt/) as follows (but yeah, that would be in `functions.php`): ``` add_filter ('get_the_excerpt','wpse240352_filter_excerpt'); function wpse240352_filter_excerpt ($post_excerpt) { $post_excerpt = '<p class="whatever">' . $post_excerpt . '</p>'; return $post_excerpt; } ``` You would then simply have `echo get_the_excerpt();` in your template files.
240,422
<p>I am trying to make a query to take first 3 categories with most posts per user, but no luck so far. This is where I am now:</p> <pre> <code> SELECT DISTINCT(terms.term_id) as term_ID, terms.name, terms.slug, posts.post_author, t0.count_id FROM wp_posts as posts JOIN wp_term_relationships as relationships ON posts.ID = relationships.object_ID JOIN wp_term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id JOIN wp_terms as terms ON tax.term_id = terms.term_id JOIN ( SELECT COUNT(*) as count_id, count_terms.term_id FROM wp_posts as posts_count JOIN wp_term_relationships as count_relationships ON posts_count.ID = count_relationships.object_ID JOIN wp_term_taxonomy as count_tax ON count_relationships.term_taxonomy_id = count_tax.term_taxonomy_id JOIN wp_terms as count_terms ON count_tax.term_id = count_terms.term_id WHERE count_tax.taxonomy = "category" AND posts_count.post_status = "publish" AND posts_count.post_author in (1,2,3) group by count_terms.term_id ) as t0 on posts.post_author in (1,2,3) WHERE tax.taxonomy = "category" AND posts.post_status = "publish" AND posts.post_author in (1,2,3) </code> </pre> <p>Which returns the users with categories, but with total sum of all the posts in those categories for this users. And I need first 3 categories with most posts per user. Any idea how to do that?</p>
[ { "answer_id": 240364, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the way to do this is by wrapping everything in a div with whatever class you want, like</p>\n\n<pre><code>&lt;div class=\"myexcerpt\"&gt;\n&lt;?php the_excerpt()?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>and then to style it (or JS) you can use</p>\n\n<pre><code>.myexcerpt p {}\n</code></pre>\n\n<p><code>div</code> has no semantic value and this kind of things is exactly why it exist.</p>\n" }, { "answer_id": 240367, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>If you have only one template it's fine to do something like:</p>\n\n<pre><code>echo '&lt;p class=\"whatever\"&gt;' . get_the_excerpt() . '&lt;/p&gt;';\n</code></pre>\n\n<p>However, if you have multiple templates and want to control the classes centrally, you can make a filter on <a href=\"https://developer.wordpress.org/reference/hooks/get_the_excerpt/\" rel=\"nofollow\"><code>get_the_excerpt</code></a> as follows (but yeah, that would be in <code>functions.php</code>):</p>\n\n<pre><code>add_filter ('get_the_excerpt','wpse240352_filter_excerpt');\n\nfunction wpse240352_filter_excerpt ($post_excerpt) { \n $post_excerpt = '&lt;p class=\"whatever\"&gt;' . $post_excerpt . '&lt;/p&gt;';\n return $post_excerpt;\n } \n</code></pre>\n\n<p>You would then simply have <code>echo get_the_excerpt();</code> in your template files.</p>\n" } ]
2016/09/24
[ "https://wordpress.stackexchange.com/questions/240422", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65361/" ]
I am trying to make a query to take first 3 categories with most posts per user, but no luck so far. This is where I am now: ``` SELECT DISTINCT(terms.term_id) as term_ID, terms.name, terms.slug, posts.post_author, t0.count_id FROM wp_posts as posts JOIN wp_term_relationships as relationships ON posts.ID = relationships.object_ID JOIN wp_term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id JOIN wp_terms as terms ON tax.term_id = terms.term_id JOIN ( SELECT COUNT(*) as count_id, count_terms.term_id FROM wp_posts as posts_count JOIN wp_term_relationships as count_relationships ON posts_count.ID = count_relationships.object_ID JOIN wp_term_taxonomy as count_tax ON count_relationships.term_taxonomy_id = count_tax.term_taxonomy_id JOIN wp_terms as count_terms ON count_tax.term_id = count_terms.term_id WHERE count_tax.taxonomy = "category" AND posts_count.post_status = "publish" AND posts_count.post_author in (1,2,3) group by count_terms.term_id ) as t0 on posts.post_author in (1,2,3) WHERE tax.taxonomy = "category" AND posts.post_status = "publish" AND posts.post_author in (1,2,3) ``` Which returns the users with categories, but with total sum of all the posts in those categories for this users. And I need first 3 categories with most posts per user. Any idea how to do that?
If you have only one template it's fine to do something like: ``` echo '<p class="whatever">' . get_the_excerpt() . '</p>'; ``` However, if you have multiple templates and want to control the classes centrally, you can make a filter on [`get_the_excerpt`](https://developer.wordpress.org/reference/hooks/get_the_excerpt/) as follows (but yeah, that would be in `functions.php`): ``` add_filter ('get_the_excerpt','wpse240352_filter_excerpt'); function wpse240352_filter_excerpt ($post_excerpt) { $post_excerpt = '<p class="whatever">' . $post_excerpt . '</p>'; return $post_excerpt; } ``` You would then simply have `echo get_the_excerpt();` in your template files.
240,429
<p>I have remarked that when clicking on a tag I have a list of posts displayed differently that when I use search box.</p> <p>How to force tag page layout to use same as search layout for any template ?</p>
[ { "answer_id": 240443, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>If you take a look at the <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow\">template hierarchy</a>, you will see that the search page has a different template than the archive page. When there is no <code>search.php</code> search results will be shown using <code>index.php</code>.</p>\n\n<p>From your question I gather you want to show search results using <code>archive.php</code> or perhaps even <code>tag.php</code>. This is easily achieved by making your own one line <code>search.php</code> with <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part</code></a>:</p>\n\n<pre><code>&lt;?php get_template_part('archive.php');\n</code></pre>\n" }, { "answer_id": 240875, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>You can tell WordPress to use the <code>search.php</code> template whenever viewing tags by using the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\"><code>template_include</code></a>. It works like this:</p>\n\n<pre><code>function wpse_240429() {\n\n // IF we're planning on loading a tag template\n if( is_tag() ) {\n\n // Try to locate the search.php template\n $search_template = locate_template( 'search.php' );\n\n // If the search template exists\n if( ! empty( $search_template ) ) {\n\n // Use search.php for display purposes\n return $search_template ;\n }\n }\n}\nadd_action( 'template_include', 'wpse_240429' );\n</code></pre>\n\n<p>You shouldn't have to mess with things like <code>pre_get_posts</code> as the query should already be pulled. </p>\n" } ]
2016/09/24
[ "https://wordpress.stackexchange.com/questions/240429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4078/" ]
I have remarked that when clicking on a tag I have a list of posts displayed differently that when I use search box. How to force tag page layout to use same as search layout for any template ?
You can tell WordPress to use the `search.php` template whenever viewing tags by using the [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include). It works like this: ``` function wpse_240429() { // IF we're planning on loading a tag template if( is_tag() ) { // Try to locate the search.php template $search_template = locate_template( 'search.php' ); // If the search template exists if( ! empty( $search_template ) ) { // Use search.php for display purposes return $search_template ; } } } add_action( 'template_include', 'wpse_240429' ); ``` You shouldn't have to mess with things like `pre_get_posts` as the query should already be pulled.
240,446
<p>I'm trying to override WP's default URL structure for attachments where, if they're attached to a post, the URL is /post-slug/attachment-slug/ and if not it's simply /attachment-slug/.</p> <p>What I'd like instead is for attachments to behave like posts in that they have an archive and all URLs point to /archive-slug/attachment-slug/.</p> <p>I've found a new (with 4.4 I believe) filter that allows you to modify post type options but it doesn't seem to work as advertised;</p> <pre><code>add_filter('register_post_type_args', function ($args, $postType) { if ($postType == 'attachment'){ $args['has_archive'] = true; $args['rewrite'] = [ 'slug' =&gt; 'media' ]; } return $args; }, 10, 2); </code></pre> <p>If I <code>var_dump($args)</code> they do in fact look correct (has_archive is true etc) but it doesn't appear to have any effect on the URLs at all.</p> <p>This might not be very surprising if this comment by the devs is correct; "Does not apply to built-in post types" <a href="https://core.trac.wordpress.org/changeset/34242" rel="noreferrer">https://core.trac.wordpress.org/changeset/34242</a>.</p> <p>So my question is how can I still accomplish this?</p> <p>I've also tried just modifying the post type object in the init hook, but it won't bite:</p> <pre><code>$obj = get_post_type_object('attachment'); $obj-&gt;has_archive = true; $obj-&gt;rewrite = [ 'slug' =&gt; 'media' ]; </code></pre>
[ { "answer_id": 240443, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>If you take a look at the <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow\">template hierarchy</a>, you will see that the search page has a different template than the archive page. When there is no <code>search.php</code> search results will be shown using <code>index.php</code>.</p>\n\n<p>From your question I gather you want to show search results using <code>archive.php</code> or perhaps even <code>tag.php</code>. This is easily achieved by making your own one line <code>search.php</code> with <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part</code></a>:</p>\n\n<pre><code>&lt;?php get_template_part('archive.php');\n</code></pre>\n" }, { "answer_id": 240875, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>You can tell WordPress to use the <code>search.php</code> template whenever viewing tags by using the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\"><code>template_include</code></a>. It works like this:</p>\n\n<pre><code>function wpse_240429() {\n\n // IF we're planning on loading a tag template\n if( is_tag() ) {\n\n // Try to locate the search.php template\n $search_template = locate_template( 'search.php' );\n\n // If the search template exists\n if( ! empty( $search_template ) ) {\n\n // Use search.php for display purposes\n return $search_template ;\n }\n }\n}\nadd_action( 'template_include', 'wpse_240429' );\n</code></pre>\n\n<p>You shouldn't have to mess with things like <code>pre_get_posts</code> as the query should already be pulled. </p>\n" } ]
2016/09/24
[ "https://wordpress.stackexchange.com/questions/240446", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23714/" ]
I'm trying to override WP's default URL structure for attachments where, if they're attached to a post, the URL is /post-slug/attachment-slug/ and if not it's simply /attachment-slug/. What I'd like instead is for attachments to behave like posts in that they have an archive and all URLs point to /archive-slug/attachment-slug/. I've found a new (with 4.4 I believe) filter that allows you to modify post type options but it doesn't seem to work as advertised; ``` add_filter('register_post_type_args', function ($args, $postType) { if ($postType == 'attachment'){ $args['has_archive'] = true; $args['rewrite'] = [ 'slug' => 'media' ]; } return $args; }, 10, 2); ``` If I `var_dump($args)` they do in fact look correct (has\_archive is true etc) but it doesn't appear to have any effect on the URLs at all. This might not be very surprising if this comment by the devs is correct; "Does not apply to built-in post types" <https://core.trac.wordpress.org/changeset/34242>. So my question is how can I still accomplish this? I've also tried just modifying the post type object in the init hook, but it won't bite: ``` $obj = get_post_type_object('attachment'); $obj->has_archive = true; $obj->rewrite = [ 'slug' => 'media' ]; ```
You can tell WordPress to use the `search.php` template whenever viewing tags by using the [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include). It works like this: ``` function wpse_240429() { // IF we're planning on loading a tag template if( is_tag() ) { // Try to locate the search.php template $search_template = locate_template( 'search.php' ); // If the search template exists if( ! empty( $search_template ) ) { // Use search.php for display purposes return $search_template ; } } } add_action( 'template_include', 'wpse_240429' ); ``` You shouldn't have to mess with things like `pre_get_posts` as the query should already be pulled.
240,496
<p>Relatively new to anything that doesn't require common sense in WordPress. My previous site was built poorly etc, so cutting a long story short I installed a new theme and started building up pages again etc. </p> <p>I have ran various diagnostics on seo etc while I am working and seem to have problems with indexability and sitemaps. </p> <p>Getting this message on the onpage.org site check and had something similar on another platform wherby it is saying there are resources that are restricted from indexing. </p> <p>Please help asap as i have good rankings and don't want this to affect the next crawl. </p>
[ { "answer_id": 240499, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>Well, that message is pretty self explanatory. There is no sitemap linked in your <code>robots.txt</code> file. So you check if you have a sitemap (if not install a plugin that will generate one for you) and add this line to your robots.txt file in the root of your site:</p>\n\n<pre><code>Sitemap: http://www.example.com/sitemap.xml\n</code></pre>\n" }, { "answer_id": 359676, "author": "Diego Somar", "author_id": 117002, "author_profile": "https://wordpress.stackexchange.com/users/117002", "pm_score": 0, "selected": false, "text": "<p>First of all, I don't know if you already has a sitemap. If no, I suggest you install <a href=\"https://br.wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">YOAST SEO</a> plugin to manage your sitemaps.</p>\n\n<p>With Yoast, your sitemap has this link:\n<a href=\"http://domain.com/sitemap_index.xml\" rel=\"nofollow noreferrer\">http://domain.com/sitemap_index.xml</a></p>\n\n<p>Then, add your sitemap to your robots.txt file, like that:</p>\n\n<pre><code>Sitemap: http://domain.com/sitemap_index.xml\n</code></pre>\n\n<p>If you already have a sitemap without Yoast, the step is the same. Just add the sitemap URL to your robots.txt like line above.</p>\n\n<p>About your comment: </p>\n\n<blockquote>\n <p>Please help asap as i have good rankings and don't want this to affect the next crawl</p>\n</blockquote>\n\n<p>A sitemap is only a file to help crawlers to find your pages. But, if your new pages are linked in other pages of your site (like homepage), crawlers you identify your new pages same way. </p>\n\n<p>Then, don't worry with this alert. There are many other important things to consider when we talk about SEO, like good content, legibility content, <strong>page speed</strong> and mobile navigation (responsive and amp).</p>\n" }, { "answer_id": 383043, "author": "BishopZ", "author_id": 84724, "author_profile": "https://wordpress.stackexchange.com/users/84724", "pm_score": 0, "selected": false, "text": "<p>You have to use the Yoast Tool, Edit Files to create and modify the robots.text.</p>\n<p><a href=\"https://kinsta.com/blog/wordpress-robots-txt/\" rel=\"nofollow noreferrer\">Wordpress Robot.txt tutorial</a></p>\n<p>Then, yes, add</p>\n<pre><code>Sitemap: https://domain.com/sitemap_index.xml\n</code></pre>\n" } ]
2016/09/25
[ "https://wordpress.stackexchange.com/questions/240496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103596/" ]
Relatively new to anything that doesn't require common sense in WordPress. My previous site was built poorly etc, so cutting a long story short I installed a new theme and started building up pages again etc. I have ran various diagnostics on seo etc while I am working and seem to have problems with indexability and sitemaps. Getting this message on the onpage.org site check and had something similar on another platform wherby it is saying there are resources that are restricted from indexing. Please help asap as i have good rankings and don't want this to affect the next crawl.
Well, that message is pretty self explanatory. There is no sitemap linked in your `robots.txt` file. So you check if you have a sitemap (if not install a plugin that will generate one for you) and add this line to your robots.txt file in the root of your site: ``` Sitemap: http://www.example.com/sitemap.xml ```
240,508
<p>I'm running WP CLI and MAMP on my MacBook for a local development environment. My version of WP CLI is current (0.24.1). I've just upgraded MAMP to it's latest version (4.0.4), which also upgrades to MySQL 5.6. After running the upgrade, I began receiving a fatal error when calling any WP CLI command that involves a database connection. </p> <p>For example, a command involving only the file system ("wp core verify-checksums", for example) produces expected results. However, "wp plugin list", for example, results in the following errors: </p> <pre><code>Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 1490 Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 1520 Warning: mysql_connect(): No such file or directory in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 1520 Fatal error: Call to undefined function wp_die() in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 3103 </code></pre> <p>I don't find any known compatibility issues with the WP CLI latest and MySQL 5.6 when I search, but perhaps I'm missing something. I'm more inclined to think that this is a local environment issue. Site functions without issue after the upgrade, and I'm still able to administrate databases within MAMP via Sequel Pro. </p> <p>Any ideas?</p>
[ { "answer_id": 240509, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The compatibility problem can be a result of your php version, php settings or/and wordpress version. the \"old\" mysql php library was deprecated at 5.5 (IIRC) and replace with the mysqli library. Wordpress core was changed at the time to support mysqli on the appropriate php version.</p>\n\n<p>What you need to do is to make sure you are running a relatively current version of wordpress, and you have the mysqli library enable in your php settings</p>\n" }, { "answer_id": 244353, "author": "DavidBrown", "author_id": 64689, "author_profile": "https://wordpress.stackexchange.com/users/64689", "pm_score": 3, "selected": true, "text": "<p>Resolved the issue. The problem was that the default PHP version changed with the new version of MAMP, and I had set the path in .bash_profile to the explicit version of the previous MAMP install. Once I edited the .bash_profile to dynamically find the version of PHP in use, everything works perfectly. </p>\n" } ]
2016/09/25
[ "https://wordpress.stackexchange.com/questions/240508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64689/" ]
I'm running WP CLI and MAMP on my MacBook for a local development environment. My version of WP CLI is current (0.24.1). I've just upgraded MAMP to it's latest version (4.0.4), which also upgrades to MySQL 5.6. After running the upgrade, I began receiving a fatal error when calling any WP CLI command that involves a database connection. For example, a command involving only the file system ("wp core verify-checksums", for example) produces expected results. However, "wp plugin list", for example, results in the following errors: ``` Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 1490 Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 1520 Warning: mysql_connect(): No such file or directory in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 1520 Fatal error: Call to undefined function wp_die() in /Applications/MAMP/htdocs/wp-includes/wp-db.php on line 3103 ``` I don't find any known compatibility issues with the WP CLI latest and MySQL 5.6 when I search, but perhaps I'm missing something. I'm more inclined to think that this is a local environment issue. Site functions without issue after the upgrade, and I'm still able to administrate databases within MAMP via Sequel Pro. Any ideas?
Resolved the issue. The problem was that the default PHP version changed with the new version of MAMP, and I had set the path in .bash\_profile to the explicit version of the previous MAMP install. Once I edited the .bash\_profile to dynamically find the version of PHP in use, everything works perfectly.
240,517
<p>User registrations are working great, except that the password that he chose isn't being accepted when the user tries to sign in, generating a new password from the back-end and trying to login with the generated password works. what am i missing here?</p> <pre><code>$email = $_POST["email"]; $password = $_POST["password1"]; $firstName = $_POST["fname"]; $lastName = $_POST["lname"]; $company = $_POST["company"]; $website = $_POST["website"]; $address = $_POST["address"]; $street = $_POST["street"]; $city = $_POST["city"]; $state = $_POST["state"]; $zip = $_POST["zip"]; $country = $_POST["country"]; $home = $_POST["home"]; $office = $_POST["office"]; $mobile = $_POST["mobile"]; if( null == username_exists( $email ) ) { $user_id = wp_create_user( $email, $password, $email ); wp_update_user( array( 'ID' =&gt; $user_id, 'nickname' =&gt; $email_address, 'first_name' =&gt; $firstName, 'last_name' =&gt; $lastName, 'user_url' =&gt; $website ) ); update_user_meta( $user_id, 'company', $company ); update_user_meta( $user_id, 'address', $address ); update_user_meta( $user_id, 'street', $street ); update_user_meta( $user_id, 'city', $city ); update_user_meta( $user_id, 'province', $state ); update_user_meta( $user_id, 'postalcode', $zip); update_user_meta( $user_id, 'country', $country ); update_user_meta( $user_id, 'home', $home ); update_user_meta( $user_id, 'office', $office ); update_user_meta( $user_id, 'mobile', $mobile ); $user = new WP_User( $user_id ); $user-&gt;set_role( 'subscriber' ); } else { echo 'user exists'; } </code></pre> <p>replacing <code>$password</code> in <code>wp_create_user()</code> with <code>'testpassword'</code> or adding a new line to the <code>wp_update_user()</code> array <code>'user_pass' =&gt; 'testpassword'</code> both didn't work.</p>
[ { "answer_id": 240509, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The compatibility problem can be a result of your php version, php settings or/and wordpress version. the \"old\" mysql php library was deprecated at 5.5 (IIRC) and replace with the mysqli library. Wordpress core was changed at the time to support mysqli on the appropriate php version.</p>\n\n<p>What you need to do is to make sure you are running a relatively current version of wordpress, and you have the mysqli library enable in your php settings</p>\n" }, { "answer_id": 244353, "author": "DavidBrown", "author_id": 64689, "author_profile": "https://wordpress.stackexchange.com/users/64689", "pm_score": 3, "selected": true, "text": "<p>Resolved the issue. The problem was that the default PHP version changed with the new version of MAMP, and I had set the path in .bash_profile to the explicit version of the previous MAMP install. Once I edited the .bash_profile to dynamically find the version of PHP in use, everything works perfectly. </p>\n" } ]
2016/09/25
[ "https://wordpress.stackexchange.com/questions/240517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98968/" ]
User registrations are working great, except that the password that he chose isn't being accepted when the user tries to sign in, generating a new password from the back-end and trying to login with the generated password works. what am i missing here? ``` $email = $_POST["email"]; $password = $_POST["password1"]; $firstName = $_POST["fname"]; $lastName = $_POST["lname"]; $company = $_POST["company"]; $website = $_POST["website"]; $address = $_POST["address"]; $street = $_POST["street"]; $city = $_POST["city"]; $state = $_POST["state"]; $zip = $_POST["zip"]; $country = $_POST["country"]; $home = $_POST["home"]; $office = $_POST["office"]; $mobile = $_POST["mobile"]; if( null == username_exists( $email ) ) { $user_id = wp_create_user( $email, $password, $email ); wp_update_user( array( 'ID' => $user_id, 'nickname' => $email_address, 'first_name' => $firstName, 'last_name' => $lastName, 'user_url' => $website ) ); update_user_meta( $user_id, 'company', $company ); update_user_meta( $user_id, 'address', $address ); update_user_meta( $user_id, 'street', $street ); update_user_meta( $user_id, 'city', $city ); update_user_meta( $user_id, 'province', $state ); update_user_meta( $user_id, 'postalcode', $zip); update_user_meta( $user_id, 'country', $country ); update_user_meta( $user_id, 'home', $home ); update_user_meta( $user_id, 'office', $office ); update_user_meta( $user_id, 'mobile', $mobile ); $user = new WP_User( $user_id ); $user->set_role( 'subscriber' ); } else { echo 'user exists'; } ``` replacing `$password` in `wp_create_user()` with `'testpassword'` or adding a new line to the `wp_update_user()` array `'user_pass' => 'testpassword'` both didn't work.
Resolved the issue. The problem was that the default PHP version changed with the new version of MAMP, and I had set the path in .bash\_profile to the explicit version of the previous MAMP install. Once I edited the .bash\_profile to dynamically find the version of PHP in use, everything works perfectly.
240,529
<p>I had something really working well - a search page with a custom url. It works fine except when I add the 404.php page to my theme. Then the page 404s. And if I remove it, it starts to work again.</p> <p>Is there a way I can check for a 404 for this url and "cancel" it? I've tried that, sort of, by checking <code>$GLOBALS['wp_query']-&gt;is_404 = false;</code> but that didn't work. Can I put my functions into an action that executes before the 404 check occurs? I've tried creating a post with that slug but obviously that takes me to that page, not my custom page.</p> <p>Here is the code that I created the custom url with:</p> <pre><code>add_action( 'parse_request', 'allow_blank_search'); function allow_blank_search(){ $path = $_SERVER['REQUEST_URI']; if(substr($path, 0, 16) == '/catalog-of-work'){ $_GET['s'] = ''; $GLOBALS['wp_query']-&gt;is_search = true; } $GLOBALS['wp_rewrite']-&gt;search_base = 'catalog-of-work'; } function search_url_rewrite_rule() { if (!empty($_GET['s'])) { wp_redirect(home_url("/catalog-of-work/") . urlencode(get_query_var('s'))); exit(); } } add_action('parse_request', 'search_url_rewrite_rule'); </code></pre>
[ { "answer_id": 241344, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>I think you're looking in the wrong direction for a solution. In stead of trying to prevent a search with zero results ending up at the 404 template, I'd try to catch it there. In other words, in your 404 template include a test if it's a failed search and if yes redirect. Like this:</p>\n\n<pre><code>if (!empty($_GET['s']))\n { search_url_rewrite_rule();}\nelse\n { normal 404 }\n</code></pre>\n" }, { "answer_id": 241359, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 2, "selected": true, "text": "<h1>Redirect early</h1>\n\n<p>First of all, your redirect function should be hooked early: you are not relying on query variables there, so you could use <code>init</code> hook:</p>\n\n<pre><code>function search_redirect() {\n if (!empty($_GET['s'])) {\n $home = trailingslashit(home_url('catalog-of-work'));\n wp_safe_redirect($home.urlencode(get_query_var('s')));\n exit();\n } \n}\n\nadd_action('init', 'search_redirect');\n</code></pre>\n\n<p>The reason is that this will redirect the request much earlier, saving a lot of processing.</p>\n\n<h1>Set query variables properly</h1>\n\n<p>Now, you need to tell WordPress that when the URL <code>/catalog-of-work</code> is visited, it has to consider a search request.</p>\n\n<pre><code>function custom_search_query_var($do, $wp) {\n $path = trim(parse_url(esc_url_raw(add_query_arg([])), PHP_URL_PATH), '/');\n $home_path = trim(parse_url(esc_url_raw(home_url()), PHP_URL_PATH), '/');\n $home_path and $path = trim(substr($path, strlen($home_path)), '/');\n if (strpos($path, 'catalog-of-work') === 0) {\n $wp-&gt;query_vars['s'] = trim(substr($path, 15), '/');\n $do = false;\n }\n\n return $do;\n}\n\nadd_action('do_parse_request', 'custom_search_query_var', 10, 2);\n</code></pre>\n\n<p>There are some things to note in the code above:</p>\n\n<ul>\n<li>I used <code>do_parse_request</code> hook instead of <code>parse_request</code>. This allows me to completely prevent WordPress parsing rules whe the URL <code>/catalog-of-work</code> is visited. Since processing query vars can be a slow process, this could improve your page performance.</li>\n<li>My logic to determine current URL make use of <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow\"><code>add_query_arg</code></a> instead of directing access to <code>$_SERVER</code>. That's better because the function takes care of some edge cases.</li>\n<li>My logic handles the case that your home URL is something like <code>example.com/wp</code> instead of <code>example.com</code>. Since the home URL can easily be changed, this ensure that the function is more stable and will work in different situations.</li>\n<li>The code I used sets the \"s\" query var in the <code>$wp-&gt;query_vars</code> array. <code>$wp</code> is the current instance of <a href=\"https://developer.wordpress.org/reference/classes/wp/\" rel=\"nofollow\"><code>WP</code></a> class that is passed by <code>do_parse_request</code> hook. This is better for two reasons: \n\n<ol>\n<li>you avoid to access global variables directly</li>\n<li>setting variables to global <code>$wp_query</code> is not reliable on <code>do_parse_request</code> (neither on <code>parse_request</code> you used) because that hooks happen before <code>$wp_query</code> is processed and some reset may still happen there, deleting the <code>s</code> query var. By setting the query var to <code>$wp</code> object, it will take care to pass variables to <code>$wp_query</code>.</li>\n</ol></li>\n</ul>\n\n<h1>Prevent 404</h1>\n\n<p>Doing things like I described, having a 404 template does not affect anything, because WordPress do <strong>not</strong> set 404 status for search queries.</p>\n\n<p>However, my code (just like your code, at least the code you posted) does not act on the template so, by default, WordPress will load <code>search.php</code>.</p>\n\n<p>It is very possible that your <code>search.php</code> template (or the template you are using) checks for <code>have_posts()</code> and load 404 template (if found) when there are no posts.</p>\n\n<p>That really depends on the theme you are using.</p>\n\n<p>For example, the theme Twentyfifteen, contains something like:</p>\n\n<pre><code>&lt;?php if ( have_posts() ) : ?&gt;\n // ... redacted loop code here... \nelse :\n // If no content, include the \"No posts found\" template.\n get_template_part( 'content', 'none' );\nendif;\n?&gt;\n</code></pre>\n\n<p>If your theme contains something like this, 404 template could be loaded when there are no posts, which happens when the search query is empty.</p>\n\n<p>If that is the issue, you should edit your search template (or if the theme is third party or a core theme you should create a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">child theme</a>) to make the search template handle the case of no posts according to your needs.</p>\n" } ]
2016/09/26
[ "https://wordpress.stackexchange.com/questions/240529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66892/" ]
I had something really working well - a search page with a custom url. It works fine except when I add the 404.php page to my theme. Then the page 404s. And if I remove it, it starts to work again. Is there a way I can check for a 404 for this url and "cancel" it? I've tried that, sort of, by checking `$GLOBALS['wp_query']->is_404 = false;` but that didn't work. Can I put my functions into an action that executes before the 404 check occurs? I've tried creating a post with that slug but obviously that takes me to that page, not my custom page. Here is the code that I created the custom url with: ``` add_action( 'parse_request', 'allow_blank_search'); function allow_blank_search(){ $path = $_SERVER['REQUEST_URI']; if(substr($path, 0, 16) == '/catalog-of-work'){ $_GET['s'] = ''; $GLOBALS['wp_query']->is_search = true; } $GLOBALS['wp_rewrite']->search_base = 'catalog-of-work'; } function search_url_rewrite_rule() { if (!empty($_GET['s'])) { wp_redirect(home_url("/catalog-of-work/") . urlencode(get_query_var('s'))); exit(); } } add_action('parse_request', 'search_url_rewrite_rule'); ```
Redirect early ============== First of all, your redirect function should be hooked early: you are not relying on query variables there, so you could use `init` hook: ``` function search_redirect() { if (!empty($_GET['s'])) { $home = trailingslashit(home_url('catalog-of-work')); wp_safe_redirect($home.urlencode(get_query_var('s'))); exit(); } } add_action('init', 'search_redirect'); ``` The reason is that this will redirect the request much earlier, saving a lot of processing. Set query variables properly ============================ Now, you need to tell WordPress that when the URL `/catalog-of-work` is visited, it has to consider a search request. ``` function custom_search_query_var($do, $wp) { $path = trim(parse_url(esc_url_raw(add_query_arg([])), PHP_URL_PATH), '/'); $home_path = trim(parse_url(esc_url_raw(home_url()), PHP_URL_PATH), '/'); $home_path and $path = trim(substr($path, strlen($home_path)), '/'); if (strpos($path, 'catalog-of-work') === 0) { $wp->query_vars['s'] = trim(substr($path, 15), '/'); $do = false; } return $do; } add_action('do_parse_request', 'custom_search_query_var', 10, 2); ``` There are some things to note in the code above: * I used `do_parse_request` hook instead of `parse_request`. This allows me to completely prevent WordPress parsing rules whe the URL `/catalog-of-work` is visited. Since processing query vars can be a slow process, this could improve your page performance. * My logic to determine current URL make use of [`add_query_arg`](https://developer.wordpress.org/reference/functions/add_query_arg/) instead of directing access to `$_SERVER`. That's better because the function takes care of some edge cases. * My logic handles the case that your home URL is something like `example.com/wp` instead of `example.com`. Since the home URL can easily be changed, this ensure that the function is more stable and will work in different situations. * The code I used sets the "s" query var in the `$wp->query_vars` array. `$wp` is the current instance of [`WP`](https://developer.wordpress.org/reference/classes/wp/) class that is passed by `do_parse_request` hook. This is better for two reasons: 1. you avoid to access global variables directly 2. setting variables to global `$wp_query` is not reliable on `do_parse_request` (neither on `parse_request` you used) because that hooks happen before `$wp_query` is processed and some reset may still happen there, deleting the `s` query var. By setting the query var to `$wp` object, it will take care to pass variables to `$wp_query`. Prevent 404 =========== Doing things like I described, having a 404 template does not affect anything, because WordPress do **not** set 404 status for search queries. However, my code (just like your code, at least the code you posted) does not act on the template so, by default, WordPress will load `search.php`. It is very possible that your `search.php` template (or the template you are using) checks for `have_posts()` and load 404 template (if found) when there are no posts. That really depends on the theme you are using. For example, the theme Twentyfifteen, contains something like: ``` <?php if ( have_posts() ) : ?> // ... redacted loop code here... else : // If no content, include the "No posts found" template. get_template_part( 'content', 'none' ); endif; ?> ``` If your theme contains something like this, 404 template could be loaded when there are no posts, which happens when the search query is empty. If that is the issue, you should edit your search template (or if the theme is third party or a core theme you should create a [child theme](https://codex.wordpress.org/Child_Themes)) to make the search template handle the case of no posts according to your needs.
240,576
<p>Good afternoon!</p> <p>This is an issue regarding the Wordpress backend and custom post types. I have spent all Friday searching and trying possible solutions and, while they helped others, in my case they're not doing what I need.</p> <h1>Status quo</h1> <p>I have a custom post type called "anco_project" it uses very few WP given data-fields but more custom ones from the ACF addon including a field called "anco_project_year_from" and one called "anco_project_year_to", both set up as a 'true number' format.</p> <p><strong>The goal</strong>: Since those two fields contain years of a construction's start and end, I want to have them sorted by the numbers given. 1998, 2006, 2012, 2016, 2016</p> <p><strong>Frontend</strong>: With following code I managed to sort the projects by their starting year without any problem.</p> <pre><code> $args = array( 'post_type' =&gt; 'anco_project', 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'anco_project_year_from', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; 'ASC' ); query_posts($args); </code></pre> <p><strong>Backend</strong>: Here I followed several guides I can't recall URLs anymore (my brain kinda got wiped over the weekend) but the 'final' solution from Friday looks like this.</p> <pre><code> // Administration: Register columns as sortable function anco_project_manage_sortable_columns( $columns ) { $columns['anco_project_year_from'] = 'anco_project_year_from'; $columns['anco_project_year_to'] = 'anco_project_year_to'; return $columns; } add_filter( 'manage_edit-anco_project_sortable_columns', 'anco_project_manage_sortable_columns' ); // Administration: Teach wordpress to make the column sortable function anco_project_year_column_orderby( $vars ) { if ( isset( $vars['orderby'] ) &amp;&amp; 'anco_project_year_from' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' =&gt; 'anco_project_year_from', 'orderby' =&gt; 'meta_value_num' ) ); } else if ( isset( $vars['orderby'] ) &amp;&amp; 'anco_project_year_to' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' =&gt; 'anco_project_year_to', 'orderby' =&gt; 'meta_value_num' ) ); } return $vars; } add_filter( 'request', 'anco_project_year_column_orderby' ); </code></pre> <p>I rechecked all the hooks used and it looks as if it should work like this.</p> <h1>The problem</h1> <p>From the code above I get pretty filters at the headers and it actually does something when pressing them, but it's not sorting by anything that would make sense.</p> <h2>an example</h2> <p>Posttype opened fresh in backend without any filters. <strong>URL:</strong> /wp-admin/edit.php?post_type=anco_project</p> <p><a href="https://i.stack.imgur.com/sU8hS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sU8hS.jpg" alt="enter image description here"></a></p> <p>Posttype sorted by 'from'. </p> <p><strong>URL:</strong> /wp-admin/edit.php?post_type=anco_project&amp;orderby=anco_project_year_from&amp;order=asc <a href="https://i.stack.imgur.com/B05mg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B05mg.png" alt="enter image description here"></a></p> <p>When I sort by 'anco_project_year_to' or change the code to sort by the 'location' column it always ends up like the second image's order. Reversing the order from ASC to DESC doesn't change the ordering either.</p> <p>Did anyone experience the same problem and has a solution for it?</p>
[ { "answer_id": 240567, "author": "danhgilmore", "author_id": 819, "author_profile": "https://wordpress.stackexchange.com/users/819", "pm_score": 4, "selected": true, "text": "<p>Yes, if you assign 'promote_users' to another user, that user could promote non-site admins to site admin.</p>\n\n<p><a href=\"https://codex.wordpress.org/Roles_and_Capabilities#promote_users\" rel=\"noreferrer\">https://codex.wordpress.org/Roles_and_Capabilities#promote_users</a></p>\n" }, { "answer_id": 240569, "author": "FaCE", "author_id": 96768, "author_profile": "https://wordpress.stackexchange.com/users/96768", "pm_score": 0, "selected": false, "text": "<p>From the <a href=\"https://codex.wordpress.org/Roles_and_Capabilities#promote_users\" rel=\"nofollow\">docs</a>:</p>\n\n<blockquote>\n <ul>\n <li>Enables the \"Change role to...\" dropdown in the admin user list. This\n \n <ul>\n <li>does not depend on 'edit_users' capability.</li>\n </ul></li>\n </ul>\n</blockquote>\n\n<p>So it would appear that yes, a casual contractor could promote a random user to an administrator, but you may be missing the point:</p>\n\n<p><strong>If someone is doing development work on your site and they have any of the following access or permissions they can (should they be so inclined) own your site</strong>:</p>\n\n<ul>\n<li>FTP access with write permissions</li>\n<li>Remote database access</li>\n<li>cPanel or other hosting access</li>\n<li>WordPress user access at Editor level or above</li>\n<li>A whole bunch of individual permissions including, but not limited to:\n\n<ul>\n<li><code>edit_files</code></li>\n<li><code>install_plugins</code></li>\n<li><code>unfiltered_html</code></li>\n</ul></li>\n</ul>\n\n<p>So choose your freelancers with care!</p>\n" } ]
2016/09/26
[ "https://wordpress.stackexchange.com/questions/240576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39243/" ]
Good afternoon! This is an issue regarding the Wordpress backend and custom post types. I have spent all Friday searching and trying possible solutions and, while they helped others, in my case they're not doing what I need. Status quo ========== I have a custom post type called "anco\_project" it uses very few WP given data-fields but more custom ones from the ACF addon including a field called "anco\_project\_year\_from" and one called "anco\_project\_year\_to", both set up as a 'true number' format. **The goal**: Since those two fields contain years of a construction's start and end, I want to have them sorted by the numbers given. 1998, 2006, 2012, 2016, 2016 **Frontend**: With following code I managed to sort the projects by their starting year without any problem. ``` $args = array( 'post_type' => 'anco_project', 'posts_per_page' => -1, 'meta_key' => 'anco_project_year_from', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); query_posts($args); ``` **Backend**: Here I followed several guides I can't recall URLs anymore (my brain kinda got wiped over the weekend) but the 'final' solution from Friday looks like this. ``` // Administration: Register columns as sortable function anco_project_manage_sortable_columns( $columns ) { $columns['anco_project_year_from'] = 'anco_project_year_from'; $columns['anco_project_year_to'] = 'anco_project_year_to'; return $columns; } add_filter( 'manage_edit-anco_project_sortable_columns', 'anco_project_manage_sortable_columns' ); // Administration: Teach wordpress to make the column sortable function anco_project_year_column_orderby( $vars ) { if ( isset( $vars['orderby'] ) && 'anco_project_year_from' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' => 'anco_project_year_from', 'orderby' => 'meta_value_num' ) ); } else if ( isset( $vars['orderby'] ) && 'anco_project_year_to' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' => 'anco_project_year_to', 'orderby' => 'meta_value_num' ) ); } return $vars; } add_filter( 'request', 'anco_project_year_column_orderby' ); ``` I rechecked all the hooks used and it looks as if it should work like this. The problem =========== From the code above I get pretty filters at the headers and it actually does something when pressing them, but it's not sorting by anything that would make sense. an example ---------- Posttype opened fresh in backend without any filters. **URL:** /wp-admin/edit.php?post\_type=anco\_project [![enter image description here](https://i.stack.imgur.com/sU8hS.jpg)](https://i.stack.imgur.com/sU8hS.jpg) Posttype sorted by 'from'. **URL:** /wp-admin/edit.php?post\_type=anco\_project&orderby=anco\_project\_year\_from&order=asc [![enter image description here](https://i.stack.imgur.com/B05mg.png)](https://i.stack.imgur.com/B05mg.png) When I sort by 'anco\_project\_year\_to' or change the code to sort by the 'location' column it always ends up like the second image's order. Reversing the order from ASC to DESC doesn't change the ordering either. Did anyone experience the same problem and has a solution for it?
Yes, if you assign 'promote\_users' to another user, that user could promote non-site admins to site admin. <https://codex.wordpress.org/Roles_and_Capabilities#promote_users>
240,578
<p>when I try to show the thumbnail image with a href tag to refer to the post page it only shows the link next to the picture and the image is not clickable.</p> <pre><code>echo "&lt;head&gt; &lt;style&gt; img { margin-left: 25px; margin-right: 25px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;a href=".the_permalink()." blank='_blank'&gt; &lt;img src=".the_post_thumbnail('video')." &gt; &lt;/a&gt; &lt;/body&gt;"; </code></pre> <p>Anybody knows a fix for that?</p>
[ { "answer_id": 240585, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p><code>the_permalink()</code> and <code>the_post_thumbnail()</code> echo their output. Use the <code>\"get_*</code> version of those functions, <a href=\"https://developer.wordpress.org/reference/functions/get_the_permalink/\" rel=\"nofollow\"><code>get_the_permalink()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\"><code>get_the_post_thumbnail()</code></a> when concatenating a string to be output.</p>\n\n<p>Both <code>the_post_thumbnail()</code> and <code>get_the_post_thumbnail()</code> will echo/return <code>&lt;img&gt;</code> tags so don't wrap their output in an <code>&lt;img&gt;</code> tag because it's already taken care of by those functions.</p>\n\n<p>The original HTML posted is missing quotes and I'm not sure why you have the <code>&lt;head&gt;</code>, <code>&lt;style&gt;</code>, and <code>&lt;body&gt;</code> tags in there; those tags are not necessary. </p>\n\n<p>This code will output a linked image:</p>\n\n<pre><code>&lt;?php\n echo '&lt;a href=\"' . get_the_permalink() . '\" target=\"_blank\"&gt;' .\n get_the_post_thumbnail( get_the_ID(), 'video' ) . '&lt;/a&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 240595, "author": "Tex0gen", "author_id": 97070, "author_profile": "https://wordpress.stackexchange.com/users/97070", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php get_header(); ?&gt;\n\n&lt;a href=\"&lt;?php the_permalink() ?&gt;\" blank=\"_blank\"&gt;\n &lt;?php the_post_thumbnail('video'); ?&gt;\n&lt;/a&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>I'd do some more reading up on PHP.</p>\n\n<p>You should use as little PHP as possible. You don't want to be echoing your entire template.</p>\n\n<p>Also, use get_header and get_footer functions. That means you can add your style to your CSS.</p>\n\n<p>The reason it didn't work to begin with is some functions literally echo data. Others just return it to do as you need.</p>\n" }, { "answer_id": 240807, "author": "Marco", "author_id": 103400, "author_profile": "https://wordpress.stackexchange.com/users/103400", "pm_score": 1, "selected": true, "text": "<p>Found a solution myself:</p>\n\n<pre><code>echo \"&lt;head&gt;\n &lt;style&gt;\n img {\n margin-left: 25px;\n margin-right: 25px;\n }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n\n\n &lt;a href='\".get_the_permalink().\"' target='_blank'&gt;\";\n the_post_thumbnail('video');\n echo \"&lt;/a&gt;\n\n &lt;/body&gt;\";\n</code></pre>\n" } ]
2016/09/26
[ "https://wordpress.stackexchange.com/questions/240578", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103400/" ]
when I try to show the thumbnail image with a href tag to refer to the post page it only shows the link next to the picture and the image is not clickable. ``` echo "<head> <style> img { margin-left: 25px; margin-right: 25px; } </style> </head> <body> <a href=".the_permalink()." blank='_blank'> <img src=".the_post_thumbnail('video')." > </a> </body>"; ``` Anybody knows a fix for that?
Found a solution myself: ``` echo "<head> <style> img { margin-left: 25px; margin-right: 25px; } </style> </head> <body> <a href='".get_the_permalink()."' target='_blank'>"; the_post_thumbnail('video'); echo "</a> </body>"; ```
240,622
<p>I'm a bit puzzled when I after some time did another Wordpress install.</p> <p>I'm using a standard Apache + PHP 7 combination (even under version control) and after checking out 4.6.1 of Wordpress (the tagged version from the Github SVN mirror, the <a href="https://github.com/WordPress/WordPress" rel="nofollow noreferrer">official Git-ified version</a>) the installer greets me in the second step with the obvious error message that the mysql extension is missing in the following form:</p> <blockquote> <p>Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /wp-includes/wp-db.php:1561 Stack trace:<br> #0 /wp-admin/setup-config.php(276): wpdb->db_connect()<br> #1 {main} thrown in /wp-includes/wp-db.php on line 1561`</p> </blockquote> <p>I'm a bit puzzled that the current Wordpress version still is based on the (outdated) php-mysql extension.</p> <p>Maybe I'm missing some configuration setting, even the origin Ezsql class was able to deal with different database backends ca. 15 years ago and as <em>wpdb</em> is forked from it, maybe there is still a leftover to use php-mysqli which is more common nowadays (and should have been straightforward to port to). But perhaps this is beating a dead horse, so I need some feedback for a better orientation.</p> <p>It's just that from the error message it sounds like mysql is still required, however I hope that's not the whole truth. The <a href="https://wordpress.org/about/requirements/" rel="nofollow noreferrer">Wordpress system requirements</a> do not share any information about the required PHP extensions and from these documented requirements it is that I'm matching them perfectly.</p> <p>I've been running <em>phpcompatinfo</em> to find out more and the result is mixed, it looks like that mysqli <em>is</em> supported (or at least could be an option):</p> <pre><code>Extensions Analysis https://github.com/WordPress/WordPress Extension Matches REF EXT min/Max PHP min/Max PHP all Core Core 7.0.2 7.0.2 PDO PDO 5.1.0 5.1.0 [...] memcache memcache 0.2 4.3.3 C mysql user 5.2.3 5.2.3 C mysqli user 5.0.0 5.0.0 C mysqlnd user 4.0.0 C openssl user 5.3.0 5.3.2 [...] Total [41] 7.0.2 =&gt; 5.6.23 </code></pre> <p>Related questions:</p> <ul> <li><p><a href="https://wordpress.stackexchange.com/questions/166188/install-will-not-load-php-does-not-have-mysql-installed">Install will not load: PHP does not have MYSQL installed</a></p></li> <li><p><a href="https://wordpress.stackexchange.com/questions/190071/your-php-installation-appears-to-be-missing-the-mysql-extension-which-is-require">Your PHP installation appears to be missing the MySQL extension which is required by WordPress</a></p></li> </ul>
[ { "answer_id": 240627, "author": "chrisguitarguy", "author_id": 6035, "author_profile": "https://wordpress.stackexchange.com/users/6035", "pm_score": 4, "selected": true, "text": "<p>WordPress will use <a href=\"http://php.net/manual/en/book.mysqli.php\">MySQLi</a> when <a href=\"https://github.com/WordPress/WordPress/blob/4a6f90db58a935abb688cfb91b391dffeda7b35c/wp-includes/wp-db.php#L638-L646\">it can</a> or unless you tell it not to. Unfortunately if WP doesn't see a <code>mysqli_*</code> function, it will assume that you want to use <code>mysql_*</code>.</p>\n\n<p>There <a href=\"https://github.com/WordPress/WordPress/blob/4a6f90db58a935abb688cfb91b391dffeda7b35c/wp-includes/wp-db.php#L1543-L1561\">is some logic</a> that will fall back to plain, old <code>mysql_*</code>, but, from your stack trace, that's not what's happening.</p>\n\n<p>You don't mention what OS you're running on, but I'd guess that the <code>php70-mysql</code> package was not installed. Ubuntu and things like the <a href=\"https://launchpad.net/~ondrej/+archive/ubuntu/php\">ondrej/php PPA</a> won't include the various mysql drivers (pdo mysql and mysqli) by default.</p>\n" }, { "answer_id": 240633, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>To add to what @chrisguitarguy said, <code>mysql</code> extension was deprecated at php 7.0 (or was it 5.6? not important here), in favor of <code>mysqli</code>extension. As chris said, wordpress tries to detect if you have <code>msqli</code> installed and use it, and in case the detection fails it will try to use <code>mysql</code>. The error you got indicates that you don't have <code>mysqli</code>installed or configured.</p>\n" } ]
2016/09/26
[ "https://wordpress.stackexchange.com/questions/240622", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/178/" ]
I'm a bit puzzled when I after some time did another Wordpress install. I'm using a standard Apache + PHP 7 combination (even under version control) and after checking out 4.6.1 of Wordpress (the tagged version from the Github SVN mirror, the [official Git-ified version](https://github.com/WordPress/WordPress)) the installer greets me in the second step with the obvious error message that the mysql extension is missing in the following form: > > Fatal error: Uncaught Error: Call to undefined function mysql\_connect() in /wp-includes/wp-db.php:1561 > Stack trace: > > #0 /wp-admin/setup-config.php(276): wpdb->db\_connect() > > #1 {main} thrown in /wp-includes/wp-db.php on line 1561` > > > I'm a bit puzzled that the current Wordpress version still is based on the (outdated) php-mysql extension. Maybe I'm missing some configuration setting, even the origin Ezsql class was able to deal with different database backends ca. 15 years ago and as *wpdb* is forked from it, maybe there is still a leftover to use php-mysqli which is more common nowadays (and should have been straightforward to port to). But perhaps this is beating a dead horse, so I need some feedback for a better orientation. It's just that from the error message it sounds like mysql is still required, however I hope that's not the whole truth. The [Wordpress system requirements](https://wordpress.org/about/requirements/) do not share any information about the required PHP extensions and from these documented requirements it is that I'm matching them perfectly. I've been running *phpcompatinfo* to find out more and the result is mixed, it looks like that mysqli *is* supported (or at least could be an option): ``` Extensions Analysis https://github.com/WordPress/WordPress Extension Matches REF EXT min/Max PHP min/Max PHP all Core Core 7.0.2 7.0.2 PDO PDO 5.1.0 5.1.0 [...] memcache memcache 0.2 4.3.3 C mysql user 5.2.3 5.2.3 C mysqli user 5.0.0 5.0.0 C mysqlnd user 4.0.0 C openssl user 5.3.0 5.3.2 [...] Total [41] 7.0.2 => 5.6.23 ``` Related questions: * [Install will not load: PHP does not have MYSQL installed](https://wordpress.stackexchange.com/questions/166188/install-will-not-load-php-does-not-have-mysql-installed) * [Your PHP installation appears to be missing the MySQL extension which is required by WordPress](https://wordpress.stackexchange.com/questions/190071/your-php-installation-appears-to-be-missing-the-mysql-extension-which-is-require)
WordPress will use [MySQLi](http://php.net/manual/en/book.mysqli.php) when [it can](https://github.com/WordPress/WordPress/blob/4a6f90db58a935abb688cfb91b391dffeda7b35c/wp-includes/wp-db.php#L638-L646) or unless you tell it not to. Unfortunately if WP doesn't see a `mysqli_*` function, it will assume that you want to use `mysql_*`. There [is some logic](https://github.com/WordPress/WordPress/blob/4a6f90db58a935abb688cfb91b391dffeda7b35c/wp-includes/wp-db.php#L1543-L1561) that will fall back to plain, old `mysql_*`, but, from your stack trace, that's not what's happening. You don't mention what OS you're running on, but I'd guess that the `php70-mysql` package was not installed. Ubuntu and things like the [ondrej/php PPA](https://launchpad.net/~ondrej/+archive/ubuntu/php) won't include the various mysql drivers (pdo mysql and mysqli) by default.
240,644
<p>I have attempted the following a few different ways. The current way I have the functionality works fine but does NOT utilize the WP Media Uploader (which makes finding 1600+ PDF files on the site to upload cumbersome). I recently found the below snippet of code and tweaked it to work for WooCommerce products.</p> <p>The only issue is that I can't seem to figure out what to call to have the URL of the PDF that's uploaded with the meta box presented on the frontend as a link (i.e. Click Here to Download Product Tearsheet).</p> <p>Any help would be greatly appreciated.</p> <pre><code>/* PDF Tear Sheet on Product Pages */ //Add Metabox add_action('add_meta_boxes', 'add_upload_file_metaboxes'); function add_upload_file_metaboxes() { add_meta_box('swp_file_upload', 'File Upload', 'swp_file_upload', 'product', 'normal', 'default'); } function swp_file_upload() { global $post; // Noncename needed to verify where the data originated echo '&lt;input type="hidden" name="tearsheetmeta_noncename" id="tearsheetmeta_noncename" value="'. wp_create_nonce(plugin_basename(__FILE__)). '" /&gt;'; global $wpdb; $strFile = get_post_meta($post -&gt; ID, $key = 'tearsheet_file', true); $media_file = get_post_meta($post -&gt; ID, $key = '_wp_attached_file', true); if (!empty($media_file)) { $strFile = $media_file; } ?&gt; &lt;script type = "text/javascript"&gt; // Uploading files var file_frame; jQuery('#upload_image_button').live('click', function(product) { podcast.preventDefault(); // If the media frame already exists, reopen it. if (file_frame) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: jQuery(this).data('uploader_title'), button: { text: jQuery(this).data('uploader_button_text'), }, multiple: false // Set to true to allow multiple files to be selected }); // When a file is selected, run a callback. file_frame.on('select', function(){ // We set multiple to false so only get one image from the uploader attachment = file_frame.state().get('selection').first().toJSON(); // here are some of the variables you could use for the attachment; //var all = JSON.stringify( attachment ); //var id = attachment.id; //var title = attachment.title; //var filename = attachment.filename; var url = attachment.url; //var link = attachment.link; //var alt = attachment.alt; //var author = attachment.author; //var description = attachment.description; //var caption = attachment.caption; //var name = attachment.name; //var status = attachment.status; //var uploadedTo = attachment.uploadedTo; //var date = attachment.date; //var modified = attachment.modified; //var type = attachment.type; //var subtype = attachment.subtype; //var icon = attachment.icon; //var dateFormatted = attachment.dateFormatted; //var editLink = attachment.editLink; //var fileLength = attachment.fileLength; var field = document.getElementById("tearsheet_file"); field.value = url; //set which variable you want the field to have }); // Finally, open the modal file_frame.open(); }); &lt;/script&gt; &lt;div&gt; &lt;table&gt; &lt;tr valign = "top"&gt; &lt;td&gt; &lt;input type = "text" name = "tearsheet_file" id = "tearsheet_file" size = "70" value = "&lt;?php echo $strFile; ?&gt;" /&gt; &lt;input id = "upload_image_button" type = "button" value = "Upload"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type = "hidden" name = "img_txt_id" id = "img_txt_id" value = "" /&gt; &lt;/div&gt; &lt;?php function admin_scripts() { wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); } function admin_styles() { wp_enqueue_style('thickbox'); } add_action('admin_print_scripts', 'admin_scripts'); add_action('admin_print_styles', 'admin_styles'); } //Saving the file function save_tearsheet_meta($post_id, $post) { // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times if (!wp_verify_nonce($_POST['tearsheetmeta_noncename'], plugin_basename(__FILE__))) { return $post -&gt; ID; } // Is the user allowed to edit the post? if (!current_user_can('edit_post', $post -&gt; ID)) return $post -&gt; ID; // We need to find and save the data // We'll put it into an array to make it easier to loop though. $tearsheet_meta['tearsheet_file'] = $_POST['tearsheet_file']; // Add values of $tearsheet_meta as custom fields foreach($tearsheet_meta as $key =&gt; $value) { if ($post -&gt; post_type == 'revision') return; $value = implode(',', (array) $value); if (get_post_meta($post -&gt; ID, $key, FALSE)) { // If the custom field already has a value it will update update_post_meta($post -&gt; ID, $key, $value); } else { // If the custom field doesn't have a value it will add add_post_meta($post -&gt; ID, $key, $value); } if (!$value) delete_post_meta($post -&gt; ID, $key); // Delete if blank value } } add_action('save_post', 'save_tearsheet_meta', 1, 2); // save the custom fields </code></pre>
[ { "answer_id": 252850, "author": "Laurence Tuck", "author_id": 1426, "author_profile": "https://wordpress.stackexchange.com/users/1426", "pm_score": 1, "selected": false, "text": "<p>The simplest way to do this is with a plugin. I use ACF (<a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow noreferrer\">Advanced Custom Fields</a>) to create the meta box which takes care of all the heavy lifting and displays a nice metabox on the edit product screen. I then add a function on my single product template to display the PDF link which can be done using a function or within the template itself where required. Using some conditional logic, the PDF link only displays when there is one :-)</p>\n\n<p>Here is a snippet for the custom field:</p>\n\n<pre><code>$pdf_media_file = get_post_meta( $post_id, 'pdf_media_file', true);\n\nif(isset($pdf_media_file) &amp;&amp; !empty($pdf_media_file)){\n $pdf_file = wp_get_attachment_url($pdf_media_file); \n}\n</code></pre>\n\n<p>You can then display the link to the file like this:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo $pdf_file; ?&gt;\"&gt;View the PDF&lt;/a&gt;\n</code></pre>\n\n<p>WordPress has a PDF image generator now so you can also have fun using the PDF thumbnail in the media library.</p>\n" }, { "answer_id": 366015, "author": "seanannnigans", "author_id": 103425, "author_profile": "https://wordpress.stackexchange.com/users/103425", "pm_score": 1, "selected": true, "text": "<p>Hey all (especially @Innate), I was able to sort it out ages ago but clearly forgot to come back here and share how I did it. I ended up nixing the idea of using the Media Uploader (due to it being hit-or-miss with larger PDF uploads) and instead just used the text field. I gave the client FTP access under a specific sub-folder (in this case: \"tearsheets\") and instructed them how to copy and paste the URL to the PDFs they upload. Then I just added the snippet (see below) to the correct single product templates for WooCommerce for it to show on the frontend.</p>\n\n<p>Thanks again for trying to help!</p>\n\n<p><code>&lt;a href=\"&lt;?php echo get_post_meta( get_the_ID(), '_nlttearsheet', true ); ?&gt;\"&gt;Download Tear Sheet&lt;/a&gt;</code></p>\n" } ]
2016/09/27
[ "https://wordpress.stackexchange.com/questions/240644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103425/" ]
I have attempted the following a few different ways. The current way I have the functionality works fine but does NOT utilize the WP Media Uploader (which makes finding 1600+ PDF files on the site to upload cumbersome). I recently found the below snippet of code and tweaked it to work for WooCommerce products. The only issue is that I can't seem to figure out what to call to have the URL of the PDF that's uploaded with the meta box presented on the frontend as a link (i.e. Click Here to Download Product Tearsheet). Any help would be greatly appreciated. ``` /* PDF Tear Sheet on Product Pages */ //Add Metabox add_action('add_meta_boxes', 'add_upload_file_metaboxes'); function add_upload_file_metaboxes() { add_meta_box('swp_file_upload', 'File Upload', 'swp_file_upload', 'product', 'normal', 'default'); } function swp_file_upload() { global $post; // Noncename needed to verify where the data originated echo '<input type="hidden" name="tearsheetmeta_noncename" id="tearsheetmeta_noncename" value="'. wp_create_nonce(plugin_basename(__FILE__)). '" />'; global $wpdb; $strFile = get_post_meta($post -> ID, $key = 'tearsheet_file', true); $media_file = get_post_meta($post -> ID, $key = '_wp_attached_file', true); if (!empty($media_file)) { $strFile = $media_file; } ?> <script type = "text/javascript"> // Uploading files var file_frame; jQuery('#upload_image_button').live('click', function(product) { podcast.preventDefault(); // If the media frame already exists, reopen it. if (file_frame) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: jQuery(this).data('uploader_title'), button: { text: jQuery(this).data('uploader_button_text'), }, multiple: false // Set to true to allow multiple files to be selected }); // When a file is selected, run a callback. file_frame.on('select', function(){ // We set multiple to false so only get one image from the uploader attachment = file_frame.state().get('selection').first().toJSON(); // here are some of the variables you could use for the attachment; //var all = JSON.stringify( attachment ); //var id = attachment.id; //var title = attachment.title; //var filename = attachment.filename; var url = attachment.url; //var link = attachment.link; //var alt = attachment.alt; //var author = attachment.author; //var description = attachment.description; //var caption = attachment.caption; //var name = attachment.name; //var status = attachment.status; //var uploadedTo = attachment.uploadedTo; //var date = attachment.date; //var modified = attachment.modified; //var type = attachment.type; //var subtype = attachment.subtype; //var icon = attachment.icon; //var dateFormatted = attachment.dateFormatted; //var editLink = attachment.editLink; //var fileLength = attachment.fileLength; var field = document.getElementById("tearsheet_file"); field.value = url; //set which variable you want the field to have }); // Finally, open the modal file_frame.open(); }); </script> <div> <table> <tr valign = "top"> <td> <input type = "text" name = "tearsheet_file" id = "tearsheet_file" size = "70" value = "<?php echo $strFile; ?>" /> <input id = "upload_image_button" type = "button" value = "Upload"> </td> </tr> </table> <input type = "hidden" name = "img_txt_id" id = "img_txt_id" value = "" /> </div> <?php function admin_scripts() { wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); } function admin_styles() { wp_enqueue_style('thickbox'); } add_action('admin_print_scripts', 'admin_scripts'); add_action('admin_print_styles', 'admin_styles'); } //Saving the file function save_tearsheet_meta($post_id, $post) { // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times if (!wp_verify_nonce($_POST['tearsheetmeta_noncename'], plugin_basename(__FILE__))) { return $post -> ID; } // Is the user allowed to edit the post? if (!current_user_can('edit_post', $post -> ID)) return $post -> ID; // We need to find and save the data // We'll put it into an array to make it easier to loop though. $tearsheet_meta['tearsheet_file'] = $_POST['tearsheet_file']; // Add values of $tearsheet_meta as custom fields foreach($tearsheet_meta as $key => $value) { if ($post -> post_type == 'revision') return; $value = implode(',', (array) $value); if (get_post_meta($post -> ID, $key, FALSE)) { // If the custom field already has a value it will update update_post_meta($post -> ID, $key, $value); } else { // If the custom field doesn't have a value it will add add_post_meta($post -> ID, $key, $value); } if (!$value) delete_post_meta($post -> ID, $key); // Delete if blank value } } add_action('save_post', 'save_tearsheet_meta', 1, 2); // save the custom fields ```
Hey all (especially @Innate), I was able to sort it out ages ago but clearly forgot to come back here and share how I did it. I ended up nixing the idea of using the Media Uploader (due to it being hit-or-miss with larger PDF uploads) and instead just used the text field. I gave the client FTP access under a specific sub-folder (in this case: "tearsheets") and instructed them how to copy and paste the URL to the PDFs they upload. Then I just added the snippet (see below) to the correct single product templates for WooCommerce for it to show on the frontend. Thanks again for trying to help! `<a href="<?php echo get_post_meta( get_the_ID(), '_nlttearsheet', true ); ?>">Download Tear Sheet</a>`
240,647
<p>I tried to upload fonts in WordPress in <code>wp-includes/fonts</code>. Then I go in <code>Apperance -&gt; Editor -&gt; Style.css</code> and here I have something like this</p> <pre><code>@font-face { font-family: helvetica_light; src: url(/wp-includes/fonts/helvetica_light.otf); } </code></pre> <p><a href="https://i.stack.imgur.com/9wUMd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9wUMd.png" alt="Looking in console I saw this error..I want to know why and what can I do to remove the error."></a></p>
[ { "answer_id": 240652, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 1, "selected": false, "text": "<p>You should <em>never</em> touch any files in <code>wp-includes</code> or <code>wp-admin</code>. Why? Because the next time you update WordPress, any changes you made will get erased. </p>\n\n<p><strong>Option 1 - Easy</strong></p>\n\n<p>If you want to use Google fonts with your WordPress theme, try a plugin like <a href=\"https://wordpress.org/plugins/easy-google-fonts/\" rel=\"nofollow\">Easy Google Fonts</a> or <a href=\"https://wordpress.org/plugins/wp-google-fonts/\" rel=\"nofollow\">WP Google Fonts</a>.</p>\n\n<p><strong>Option 2 - More Work</strong></p>\n\n<p>If you want to programmatically add Google fonts without using a plugin, you'd paste this code in your themes' <code>functions.php</code> file. </p>\n\n<p><strong>Note</strong>: there is no <em>Helvetica Light</em> font available from Google. Open Sans seems to be a close match though.</p>\n\n<pre><code>function my_custom_google_fonts() {\n wp_enqueue_style( 'my-google-fonts', '//fonts.googleapis.com/css?family=Open+Sans:300,400', false ); \n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_google_fonts' );\n</code></pre>\n\n<p>Then you need to reference that new font in your themes' <code>style.css</code> file.</p>\n\n<pre><code>body {\n font-family: 'Open Sans', sans-serif;\n}\n</code></pre>\n" }, { "answer_id": 240660, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>If the font is installed on your computer, your browser will show it on your site, regardless of whether the font has been loaded. So I'd start with checking the site on a different device and see if the font shows up there. If not, check the path to the font. Url's in stylesheets are <a href=\"https://stackoverflow.com/questions/940451/using-relative-url-in-css-file-what-location-is-it-relative-to\">relative to the location of the sheet</a>, not of the site root. That should enable you to make sure the font is really loaded on all devices.</p>\n\n<p>Now to the error. Apparently there is code in your site that tries to load any font mentioned in your css file from Google. The error is thrown because Google doesn't know this font. The <code>ver4.6.1</code> at the end of the url is the current WordPress version, which is most likely generated by a call to <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_style</code></a> or <a href=\"https://developer.wordpress.org/reference/functions/wp_register_style/\" rel=\"nofollow noreferrer\"><code>wp_register_style</code></a>. That call is wrong anyway, because Google doesn't like the version part and would throw an error even if the font did exist (the <code>$ver</code> parameter should be <code>null</code>).</p>\n\n<p>Without further knowledge it's impossible to say where this code is. I'd start with checking the theme's <code>functions.php</code>, but it may also be some font related plugin.</p>\n" } ]
2016/09/27
[ "https://wordpress.stackexchange.com/questions/240647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103629/" ]
I tried to upload fonts in WordPress in `wp-includes/fonts`. Then I go in `Apperance -> Editor -> Style.css` and here I have something like this ``` @font-face { font-family: helvetica_light; src: url(/wp-includes/fonts/helvetica_light.otf); } ``` [![Looking in console I saw this error..I want to know why and what can I do to remove the error.](https://i.stack.imgur.com/9wUMd.png)](https://i.stack.imgur.com/9wUMd.png)
You should *never* touch any files in `wp-includes` or `wp-admin`. Why? Because the next time you update WordPress, any changes you made will get erased. **Option 1 - Easy** If you want to use Google fonts with your WordPress theme, try a plugin like [Easy Google Fonts](https://wordpress.org/plugins/easy-google-fonts/) or [WP Google Fonts](https://wordpress.org/plugins/wp-google-fonts/). **Option 2 - More Work** If you want to programmatically add Google fonts without using a plugin, you'd paste this code in your themes' `functions.php` file. **Note**: there is no *Helvetica Light* font available from Google. Open Sans seems to be a close match though. ``` function my_custom_google_fonts() { wp_enqueue_style( 'my-google-fonts', '//fonts.googleapis.com/css?family=Open+Sans:300,400', false ); } add_action( 'wp_enqueue_scripts', 'my_custom_google_fonts' ); ``` Then you need to reference that new font in your themes' `style.css` file. ``` body { font-family: 'Open Sans', sans-serif; } ```
240,653
<p>I'm trying to query a single product. And I searched it to google on how to do it and a found this code.</p> <pre><code>do_shortcode('[product_page id="{$product_id}"]'); </code></pre> <p>but this dispaly the whole content of products. All I want is just an image,description and the price. How can I do this using WP_QUERY()? </p>
[ { "answer_id": 240700, "author": "Anass", "author_id": 77227, "author_profile": "https://wordpress.stackexchange.com/users/77227", "pm_score": -1, "selected": false, "text": "<p>Why not just use the shortcode that provides <em>WooCommerce</em> by default?\nI think is more practical than create another separated code or function to do the same stuff.</p>\n\n<pre><code>[product id=\"99\"]\n</code></pre>\n\n<blockquote>\n <p>Check out it here : <a href=\"https://docs.woocommerce.com/document/woocommerce-shortcodes/#section-8\" rel=\"nofollow\">Shortcodes included with WooCommerce</a></p>\n</blockquote>\n\n<p>Well, with a variable, you can try this in your template:</p>\n\n<pre><code>&lt;?php echo do_shortcode('[product_page id='.$product_id.']'); ?&gt;\n</code></pre>\n" }, { "answer_id": 240726, "author": "Naresh Kumar P", "author_id": 101025, "author_profile": "https://wordpress.stackexchange.com/users/101025", "pm_score": 3, "selected": true, "text": "<p>If you want to use the <code>Wp_Query</code> for selecting the single product from the database you have to pass the <code>p</code> in the <code>$args</code> so that if fetches the data and the <code>post_type</code> should be as <code>product</code>.</p>\n\n<blockquote>\n <p>Follow up the Normal <code>$args</code> method along with that you have to add the following lines of code.</p>\n</blockquote>\n\n<pre><code>&lt;?php\n$params = array(\n 'p' =&gt; 'YOUR PRODUCT ID', id of a page, post, or custom type\n 'post_type' =&gt; 'product'\n);\n$wc_query = new WP_Query($params); \n?&gt;\n&lt;?php if ($wc_query-&gt;have_posts()) : ?&gt;\n&lt;?php while ($wc_query-&gt;have_posts()) : $wc_query-&gt;the_post(); ?&gt;\n&lt;?php the_title(); ?&gt;\n&lt;?php the_content(); ?&gt;\n&lt;?php endwhile; ?&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n&lt;?php else: ?&gt;\n&lt;p&gt;&lt;?php _e( 'No Product' ); ?&gt;&lt;/p&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2016/09/27
[ "https://wordpress.stackexchange.com/questions/240653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103627/" ]
I'm trying to query a single product. And I searched it to google on how to do it and a found this code. ``` do_shortcode('[product_page id="{$product_id}"]'); ``` but this dispaly the whole content of products. All I want is just an image,description and the price. How can I do this using WP\_QUERY()?
If you want to use the `Wp_Query` for selecting the single product from the database you have to pass the `p` in the `$args` so that if fetches the data and the `post_type` should be as `product`. > > Follow up the Normal `$args` method along with that you have to add the following lines of code. > > > ``` <?php $params = array( 'p' => 'YOUR PRODUCT ID', id of a page, post, or custom type 'post_type' => 'product' ); $wc_query = new WP_Query($params); ?> <?php if ($wc_query->have_posts()) : ?> <?php while ($wc_query->have_posts()) : $wc_query->the_post(); ?> <?php the_title(); ?> <?php the_content(); ?> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php else: ?> <p><?php _e( 'No Product' ); ?></p> <?php endif; ?> ```
240,658
<p>jQuery included with WordPress is in <a href="http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/" rel="nofollow">compatibility mode</a>. To avoid conflicts with other libraries we can not use the '$' shortcut for 'jQuery'.</p> <p>To use the '$' sign we use:</p> <pre><code>jQuery(document).ready(function($) { $('#myid').css({'background': 'black', 'color':'white'}); }); </code></pre> <p>This works. But my question is how to do the same with window load. I have been facing this problem since last few projects. So, thought better to make the concept clear.</p> <pre><code>jQuery(window).load(function($) { $('#myid').css({'background': 'black', 'color':'white'}); }); </code></pre> <p>With this I get an error that says : "$ is not a function". So, I am unable to use $ inside of the window.load code block.</p> <p>So, can anyone help how I can use the $ shortcut inside window.load?</p>
[ { "answer_id": 240659, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Using a self invoking anonymous function that passes the jQuery object will do the trick:</p>\n\n<pre><code>(function($){ \n $(window).load(function(){\n $('#myid').css({'background': 'black', 'color':'white'});\n });\n})(jQuery); //Passing the jQuery object as a first argument\n</code></pre>\n" }, { "answer_id": 249897, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 1, "selected": false, "text": "<p>This is because window <a href=\"https://api.jquery.com/load-event/\" rel=\"nofollow noreferrer\">load event</a> is different than Jquery <a href=\"http://api.jquery.com/load/\" rel=\"nofollow noreferrer\">load function</a>.</p>\n\n<p>Note also this function can take multiple parameters. </p>\n\n<pre><code>(function(wordpress, $){ \n $(window).load(function(){\n var emoji = wordpress.emoji; \n // do somehting with emoji ;)\n console.log(emoji);\n $('body').css({'background': 'black', 'color':'white'});\n });\n})(wp, jQuery);\n</code></pre>\n" } ]
2016/09/27
[ "https://wordpress.stackexchange.com/questions/240658", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81898/" ]
jQuery included with WordPress is in [compatibility mode](http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/). To avoid conflicts with other libraries we can not use the '$' shortcut for 'jQuery'. To use the '$' sign we use: ``` jQuery(document).ready(function($) { $('#myid').css({'background': 'black', 'color':'white'}); }); ``` This works. But my question is how to do the same with window load. I have been facing this problem since last few projects. So, thought better to make the concept clear. ``` jQuery(window).load(function($) { $('#myid').css({'background': 'black', 'color':'white'}); }); ``` With this I get an error that says : "$ is not a function". So, I am unable to use $ inside of the window.load code block. So, can anyone help how I can use the $ shortcut inside window.load?
Using a self invoking anonymous function that passes the jQuery object will do the trick: ``` (function($){ $(window).load(function(){ $('#myid').css({'background': 'black', 'color':'white'}); }); })(jQuery); //Passing the jQuery object as a first argument ```
240,670
<p>I have a subdomain:</p> <pre><code>https://blog.example.com/ </code></pre> <p>I forcibly redirects to directory:</p> <pre><code>https://www.example.com/blog </code></pre> <p>By changing site URL and some RewriteRule on .htaccess.</p> <p>My <strong>.htaccess</strong>:</p> <pre><code> &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] RewriteCond %{HTTP:X-Forwarded-Host}i ^example\.com RewriteCond %{HTTP_HOST} ^blog\.example\.com$ RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] &lt;/IfModule&gt; </code></pre> <p>My wordpress address and site address are:</p> <p><strong>WordPress Address (URL)</strong>: <code>/blog</code></p> <p><strong>Site Address (URL)</strong>: <code>https://www.example.com/blog</code></p> <p>Now the website working fine, but I found an error in wp-admin canonical url on all admin pages:</p> <pre><code>Uncaught SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'blog.example.com/wp-admin/index.php'; cannot be created in a document with origin 'example.com'; and URL 'example.com/blog/wp-admin/index.php'; </code></pre> <p>When I dig more I found the canonical link is still subdomain( <strong>blog.example.com</strong> ) :</p> <pre><code>&lt;link id="wp-admin-canonical" rel="canonical" href="http://blog.example.com/wp-admin" /&gt; &lt;script&gt; if ( window.history.replaceState ) { window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash ); } &lt;/script&gt; </code></pre> <p>Is there any solution for changing this canonical url from <strong><a href="https://blog.example.com" rel="nofollow noreferrer">https://blog.example.com</a></strong> to <strong><a href="https://www.example.com/blog" rel="nofollow noreferrer">https://www.example.com/blog</a></strong></p>
[ { "answer_id": 271712, "author": "Diego", "author_id": 122801, "author_profile": "https://wordpress.stackexchange.com/users/122801", "pm_score": 2, "selected": false, "text": "<p>wp-admin-canonical is <a href=\"https://core.trac.wordpress.org/ticket/35561\" rel=\"nofollow noreferrer\">broken</a>, as it assumes how WordPress is installed.</p>\n\n<p>there was a plugin to fix it, but the plugin was removed from the plugin repository apparently. It is still on github and pluginmirror though:\n<a href=\"https://github.com/wp-plugins/remove-wp-canonical-url-admin-hack\" rel=\"nofollow noreferrer\">https://github.com/wp-plugins/remove-wp-canonical-url-admin-hack</a>\n<a href=\"http://www.pluginmirror.com/plugins/remove-wp-canonical-url-admin-hack/\" rel=\"nofollow noreferrer\">http://www.pluginmirror.com/plugins/remove-wp-canonical-url-admin-hack/</a></p>\n" }, { "answer_id": 393132, "author": "campsjos", "author_id": 85685, "author_profile": "https://wordpress.stackexchange.com/users/85685", "pm_score": 1, "selected": false, "text": "<h2>Update</h2>\n<p>The code below didn't really worked for me, as it adds a correct canonical tag but I wasn't able to remove the wrong one with <code>remove_action</code>.</p>\n<p>Also, I found that pagination and sorting links in post and page lists had the wrong URL on it as well.</p>\n<p>So the solution has been much simpler, just add <code>$_SERVER['HTTP_HOST'] = 'www.yoursite.com';</code> anywhere in <code>wp-config.php</code>.</p>\n<hr />\n<h2>Previous answer</h2>\n<p>I've overrided the <code>wp-admin-canonical</code> by adding this hooks in <code>functions.php</code>:</p>\n<pre><code>remove_action( 'admin_head', 'wp_admin_canonical_url' );\nadd_action( 'admin_head', 'wp_set_admin_canonical_url' );\n\nfunction wp_set_admin_canonical_url() {\n $removable_query_args = wp_removable_query_args();\n\n if ( empty( $removable_query_args ) ) {\n return;\n }\n\n // Ensure we're using an absolute URL.\n $current_url = admin_url( preg_replace( '#^[^?]*/wp-admin/#i', '', $_SERVER['REQUEST_URI'] ) );\n $filtered_url = remove_query_arg( $removable_query_args, $current_url );\n ?&gt;\n &lt;link id=&quot;wp-admin-canonical&quot; rel=&quot;canonical&quot; href=&quot;&lt;?php echo esc_url( $filtered_url ); ?&gt;&quot; /&gt;\n &lt;script&gt;\n if ( window.history.replaceState ) {\n window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash );\n }\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n<p>I've taken the code from this pull request: <a href=\"https://github.com/WordPress/wordpress-develop/pull/1504\" rel=\"nofollow noreferrer\">https://github.com/WordPress/wordpress-develop/pull/1504</a></p>\n" } ]
2016/09/27
[ "https://wordpress.stackexchange.com/questions/240670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63027/" ]
I have a subdomain: ``` https://blog.example.com/ ``` I forcibly redirects to directory: ``` https://www.example.com/blog ``` By changing site URL and some RewriteRule on .htaccess. My **.htaccess**: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] RewriteCond %{HTTP:X-Forwarded-Host}i ^example\.com RewriteCond %{HTTP_HOST} ^blog\.example\.com$ RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^/?(.*)$ https://www.example.com/blog/$1 [L,R=301,NC] </IfModule> ``` My wordpress address and site address are: **WordPress Address (URL)**: `/blog` **Site Address (URL)**: `https://www.example.com/blog` Now the website working fine, but I found an error in wp-admin canonical url on all admin pages: ``` Uncaught SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'blog.example.com/wp-admin/index.php'; cannot be created in a document with origin 'example.com'; and URL 'example.com/blog/wp-admin/index.php'; ``` When I dig more I found the canonical link is still subdomain( **blog.example.com** ) : ``` <link id="wp-admin-canonical" rel="canonical" href="http://blog.example.com/wp-admin" /> <script> if ( window.history.replaceState ) { window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash ); } </script> ``` Is there any solution for changing this canonical url from **<https://blog.example.com>** to **<https://www.example.com/blog>**
wp-admin-canonical is [broken](https://core.trac.wordpress.org/ticket/35561), as it assumes how WordPress is installed. there was a plugin to fix it, but the plugin was removed from the plugin repository apparently. It is still on github and pluginmirror though: <https://github.com/wp-plugins/remove-wp-canonical-url-admin-hack> <http://www.pluginmirror.com/plugins/remove-wp-canonical-url-admin-hack/>
240,678
<p>I have a really odd issue:</p> <ol> <li>I have a WP site, staging and live are on the same server.</li> <li>Query string variables aren't registering in the $_GET or $_REQUEST arrays on the live site (but they are on staging). Code in the same place, where QS vars are needed, dumping $_REQUEST, gives the vars as expected on staging, but an empty array on live.</li> <li>If I dump $_REQUEST in a standalone test.php file, it works in both sites in terms of QS vars being registered.</li> <li>If I dump $_REQUEST at the top of WP's index.php, it works on staging, but on live I only see cookie data.</li> </ol> <p>The codebase is the same, same WP version, same plugins, same plugin versions. Obviously <em>something</em> is different! But I'm stuck as to how to do more to track this down. I'm not sure what could be making the difference between something processed in test.php and something at the top of index.php. Any ideas?</p>
[ { "answer_id": 240754, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": false, "text": "<p>Missing GET request variables are sometimes a symptom of improper rewrite rules in the web-server's configuration files. In the case of Apache, rewrites are most often implemented using the <a href=\"http://httpd.apache.org/docs/current/mod/mod_rewrite.html\" rel=\"nofollow\"><code>mod_rewrite</code></a> module's directives in the WordPress installation's directory-level <code>.htaccess</code> configuration file - however, a faulty rewrite rule could also be present in higher-level configuration files (directory, vhost, primary configuration, etc.).</p>\n\n<p>By default, WordPress routes every request for anything except existing files and directories to <code>index.php</code> using a configuration similar to the following:</p>\n\n<pre><code>&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</code></pre>\n\n<p>There are two modifications that will cause these directives to drop the querystring in the process of rewriting the request:</p>\n\n<ul>\n<li><p>The <a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd\" rel=\"nofollow\">discard querystring flag</a>. This is added to the square brackets at the end of a <code>RewriteRule</code> directive as either <code>QSD</code> or <code>qsdiscard</code>. If this flag is present for <em>either</em> of the <code>RewriteRule</code> directives in the configuration above, the querystring will be discarded for virtually every request handled by WordPress. For example:</p>\n\n<pre><code>RewriteRule ^index\\.php$ - [L,QSD]\n</code></pre></li>\n<li><p>Any use of a <code>?</code> in a <code>RewriteRule</code> directive's substitution string (without the <a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa\" rel=\"nofollow\">append querystring flag</a>). Specifying <em>any</em> querystring (even a single <code>?</code> without any subsequent key/value pairs) in the substitution will result in the rewrite completely replacing the original querystring. For example:</p>\n\n<pre><code>RewriteRule . /index.php? [L]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>RewriteRule . /index.php?foo=bar [L]\n</code></pre>\n\n<p>If it is desireable to append a custom GET variable to every rewrite, the append querystring flag can be specified in the brackets as <code>QSA</code> or <code>qsappend</code> in order to merge the querystring in the substitution with the original querystring instead of completely overwriting it:</p>\n\n<pre><code>RewriteRule . /index.php?foo=bar [L,QSA]\n</code></pre></li>\n</ul>\n" }, { "answer_id": 408603, "author": "Wilhelm", "author_id": 223979, "author_profile": "https://wordpress.stackexchange.com/users/223979", "pm_score": -1, "selected": false, "text": "<p>An easy way to get the query string is to do the following:</p>\n<pre><code>$query_string = $_SERVER['QUERY_STRING'];\n</code></pre>\n" } ]
2016/09/27
[ "https://wordpress.stackexchange.com/questions/240678", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2336/" ]
I have a really odd issue: 1. I have a WP site, staging and live are on the same server. 2. Query string variables aren't registering in the $\_GET or $\_REQUEST arrays on the live site (but they are on staging). Code in the same place, where QS vars are needed, dumping $\_REQUEST, gives the vars as expected on staging, but an empty array on live. 3. If I dump $\_REQUEST in a standalone test.php file, it works in both sites in terms of QS vars being registered. 4. If I dump $\_REQUEST at the top of WP's index.php, it works on staging, but on live I only see cookie data. The codebase is the same, same WP version, same plugins, same plugin versions. Obviously *something* is different! But I'm stuck as to how to do more to track this down. I'm not sure what could be making the difference between something processed in test.php and something at the top of index.php. Any ideas?
Missing GET request variables are sometimes a symptom of improper rewrite rules in the web-server's configuration files. In the case of Apache, rewrites are most often implemented using the [`mod_rewrite`](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) module's directives in the WordPress installation's directory-level `.htaccess` configuration file - however, a faulty rewrite rule could also be present in higher-level configuration files (directory, vhost, primary configuration, etc.). By default, WordPress routes every request for anything except existing files and directories to `index.php` using a configuration similar to the following: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` There are two modifications that will cause these directives to drop the querystring in the process of rewriting the request: * The [discard querystring flag](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd). This is added to the square brackets at the end of a `RewriteRule` directive as either `QSD` or `qsdiscard`. If this flag is present for *either* of the `RewriteRule` directives in the configuration above, the querystring will be discarded for virtually every request handled by WordPress. For example: ``` RewriteRule ^index\.php$ - [L,QSD] ``` * Any use of a `?` in a `RewriteRule` directive's substitution string (without the [append querystring flag](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa)). Specifying *any* querystring (even a single `?` without any subsequent key/value pairs) in the substitution will result in the rewrite completely replacing the original querystring. For example: ``` RewriteRule . /index.php? [L] ``` or ``` RewriteRule . /index.php?foo=bar [L] ``` If it is desireable to append a custom GET variable to every rewrite, the append querystring flag can be specified in the brackets as `QSA` or `qsappend` in order to merge the querystring in the substitution with the original querystring instead of completely overwriting it: ``` RewriteRule . /index.php?foo=bar [L,QSA] ```