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
268,495
<p><a href="https://developer.wordpress.org/reference/classes/wp_posts_list_table/extra_tablenav/" rel="noreferrer">WP_Posts_List_Table::extra_tablenav()</a> applies <a href="https://developer.wordpress.org/reference/hooks/restrict_manage_posts/" rel="noreferrer">restrict_manage_posts</a>, which can be used by a plugin to output extra dropdowns (or other markup) that allow filtering the posts in the table by arbitrary criteria.</p> <p>Similarly, <code>WP_(Users|Comments)_List_Table</code> have a <code>resttric_manage_(users|comment)</code> action for similar purposes.</p> <p>However, as far as I can tell, <a href="https://developer.wordpress.org/reference/classes/wp_terms_list_table/" rel="noreferrer">WP_Terms_List_Table</a> does <strong>not</strong>. Is this correct?</p> <p>I'm writing a plugin that relies heavily on <code>termmeta</code> on various custom taxonomies. My plugin adds custom columns to <code>edit-tags.php?taxonomy=my_custom_tax</code> that display the value(s) of the various <code>termmeta</code> for each term. It would greatly enhance the UX of my plugin if users were able to filter the term list by the distinct <code>meta_value</code>'s for my <code>meta_key</code>'s.</p> <p>Before I open a Trac ticket that proposes adding a <code>WP_Terms_List_Table::extra_tablenav()</code> method and <code>restrict_manage_terms</code> filter so that it would be possible to do what I want to do, I wanted to see if anyone here on WPSE knows:</p> <ol> <li>is there a viable work around (that doesn't involve something like hijacking <code>edit-tags.php?taxonomy=my_custom_tax</code> to redirect to a custom page that uses a custom subclass of <code>WP_Terms_List_Table</code>)?</li> <li>is there a (good) reason <code>WP_Terms_List_Table</code> doesn't currently support this functionality? <ol> <li>I realize for core there is no (good) reason to filter by any of the standard <code>WP_Term_List_Table</code> columns, but adding custom columns to it is fairly common and I can't believe I'm the only one who's ever wanted to filter by the values in custom columns.</li> </ol></li> </ol> <p><strong>Edit</strong></p> <p>I should note that I when displaying the <code>meta_value</code> in the custom column, I am outputting it as a link which effectively filters the term list by that value. The the reason the UX would be enchanced if users could choose from a dropdown (like in <code>WP_Posts_List_Table</code>) is that not all values of the <code>meta_value</code> are always visible on any given page of terms displayed in the list table. What <strong>I</strong> do to use the links to filter by a value that is not currently displayed on the current page is click on a random link, then edit the resulting URL in the browser's address field to have the <code>meta_value</code> <strong>I</strong> want to filter by. Not only is that a pain, but not all user's are savy enough to realize they can do this.</p>
[ { "answer_id": 268720, "author": "constancecchen", "author_id": 110820, "author_profile": "https://wordpress.stackexchange.com/users/110820", "pm_score": 2, "selected": false, "text": "<p>I've been searching around for the same answer to your question and running into the exact same issues, and really appreciate your thorough research. I'm definitely +1 here for proposing this addition!</p>\n\n<p>To attempt to answer 2) - I don't think there's a good reason to exclude it. I think WordPress's taxonomy terms are woefully lacking in features compared to the post and user entities (seeing as how term meta came much later, after post and user meta), and would like to see that change.</p>\n\n<p>To answer 1) - I don't know how much <em>better</em> this is than your solution, but the workaround I've come up with involves filtering the taxonomy list via the <code>get_terms_args</code> filter, and then manually inserting a select dropdown + filter button in client-side JS. Here's a sample of my setup (modified to not use my specific classes or constants), which is filtering by a certain term meta field:</p>\n\n<p><strong>PHP Logic</strong></p>\n\n<pre><code>// @see https://developer.wordpress.org/reference/hooks/get_terms_args/\nadd_filter( 'get_terms_args', 'taxonomy_filter', 10, 2 );\n\nfunction taxonomy_filter( $args, $taxonomies ) {\n global $pagenow;\n if ( 'edit-tags.php' !== $pagenow || ! in_array( 'taxonomy-name', $taxonomies, true ) ) { return $args; }\n\n // Sort by most recently added terms, instead of alphabetically\n $args['orderby'] = 'term_id';\n $args['order'] = 'desc';\n\n // Filter by term meta\n $meta_key = ( isset( $_GET['meta_key'] ) ) ? sanitize_text_field( $_GET['meta_key'] ) : null;\n $meta_value = ( isset( $_GET['meta_value'] ) ) ? sanitize_text_field( $_GET['meta_value'] ) : null;\n\n if ( 'meta-filter' === $meta_key &amp;&amp; $meta_value ) {\n $args['meta_key'] = $meta_key;\n $args['meta_value'] = $meta_value;\n }\n\n // Note: for more complex filtering, use the $args['meta_query'] array.\n\n return $args;\n}\n</code></pre>\n\n<p>At this point, you should be able to see this working simply by going to (e.g.) <code>yoursite.com/wp-admin/edit-tags.php?taxonomy=taxonomy-name&amp;meta_key=meta-filter&amp;meta_value=foobar</code>.</p>\n\n<p><strong>Client-side jQuery logic</strong></p>\n\n<p>(Make sure you include this file in <code>wp_enqueue_script()</code>, but only when <code>$pagenow === 'edit-tags.php'</code>).</p>\n\n<pre><code>/**\n * Param helpers\n */\n\n// Get params in a JS object\nvar params = {};\nwindow.location.search.substr(1).split( '&amp;' ).forEach(function(item) {\n params[ item.split( '=' )[0] ] = item.split( '=' )[1];\n});\n\n// Return param string based on the params object\nfunction setParams() {\n var string = '?';\n\n for ( key in params ) {\n var value = params[ key ];\n string += key + '=' + value + '&amp;';\n }\n\n return string.slice(0, -1); // Remove trailing &amp;\n}\n\n/**\n * Add dropdown filters + functionality to term tables\n */\n\nif ( 'taxonomy-name' === params.taxonomy ) {\n // Create the dropdown menu &amp; HTML\n $( document.querySelector( '.tablenav .bulkactions' ) ).after( '\\\n &lt;div class=\"alignleft actions\"&gt; \\\n &lt;select id=\"js-filter-dropdown\"&gt; \\\n &lt;option value=\"\"&gt;Term Meta Filter&lt;/option&gt; \\\n &lt;option value=\"foo\"&gt;Foo&lt;/option&gt; \\\n &lt;option value=\"bar\"&gt;Bar&lt;/option&gt; \\\n &lt;option value=\"baz\"&gt;Baz&lt;/option&gt; \\\n &lt;/select&gt; \\\n &lt;button id=\"js-filter\" class=\"button\" type=\"button\"&gt;Filter&lt;/button&gt; \\\n &lt;/div&gt; \\\n ' );\n\n // If we're already filtering the view, have the dropdown reflect that\n var value = decodeURIComponent( params.meta_value ).replace(/\\+/g, ' ');\n $( '#js-filter-dropdown' ).find( 'option[value=\"' + value + '\"]' ).prop( 'selected', true );\n\n // Set up the button action - see taxonomy_filter() for server-side filtering\n $( '#js-filter' ).click(function() {\n var value = $( '#js-filter-dropdown' ).val();\n\n if ( value ) {\n params.meta_key = 'meta-filter';\n params.meta_value = encodeURIComponent( value );\n } else {\n delete params.meta_key;\n delete params.meta_value;\n }\n\n window.location.search = setParams();\n });\n}\n</code></pre>\n\n<p><strong>Screenshot of the Filtering UI</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/34v2k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/34v2k.png\" alt=\"Before\"></a></p>\n\n<p><strong>Screenshot of the filtered table</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/p2FW5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p2FW5.png\" alt=\"After image\"></a></p>\n" }, { "answer_id": 268723, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Quickly reviewing the class, it looks like we could hijack the <code>bulk_actions-{$this-&gt;screen-&gt;id}</code> filter, to add extra dropdowns at the table top.</p>\n\n<p><strong>Example</strong> </p>\n\n<p>For the category taxonomy:</p>\n\n<pre><code>add_filter( 'bulk_actions-edit-category', function( $actions )\n{\n echo '&lt;select name=\"foo\" &gt;&lt;option value=\"bar\"&gt;Bar&lt;/option&gt;&lt;/select&gt;';\n\n return $actions;\n} );\n</code></pre>\n\n<p>Otherwise there's not an easy way to extend the <code>WP_Terms_List_Table</code> class that's instantiated with:</p>\n\n<pre><code>$wp_list_table = _get_list_table('WP_Terms_List_Table');\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>Here's another adventures hack, for the <em>edit category</em> screen, that needs some testing :-)</p>\n\n<pre><code>add_filter( 'manage_edit-category_columns', function( $columns ) use ( &amp;$wp_list_table )\n{ \n // Include the WP_Terms_List_Table class\n require_once ( ABSPATH . 'wp-admin/includes/class-wp-terms-list-table.php' );\n\n // Extend the WP_Terms_List_Table class\n class WPSE_Terms_List_Table extends WP_Terms_List_Table\n {\n // Override this method\n protected function extra_tablenav( $which )\n {\n echo '&lt;select name=\"foo\" &gt;&lt;option value=\"bar\"&gt;Bar&lt;/option&gt;&lt;/select&gt;';\n }\n } \n // end class\n\n $obj = new WPSE_Terms_List_Table;\n $obj-&gt;prepare_items(); \n\n // Let's clone it to the global object\n $wp_list_table = clone $obj;\n\n return $columns;\n} );\n</code></pre>\n\n<p>Additionally one needs to filter with <code>get_terms_args</code> as mentioned by @winnietherpooh and adjust the location with the <code>redirect_term_location</code>filter as mentioned by @Paul 'Sparrow Hawk' Biron</p>\n" } ]
2017/05/29
[ "https://wordpress.stackexchange.com/questions/268495", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113496/" ]
[WP\_Posts\_List\_Table::extra\_tablenav()](https://developer.wordpress.org/reference/classes/wp_posts_list_table/extra_tablenav/) applies [restrict\_manage\_posts](https://developer.wordpress.org/reference/hooks/restrict_manage_posts/), which can be used by a plugin to output extra dropdowns (or other markup) that allow filtering the posts in the table by arbitrary criteria. Similarly, `WP_(Users|Comments)_List_Table` have a `resttric_manage_(users|comment)` action for similar purposes. However, as far as I can tell, [WP\_Terms\_List\_Table](https://developer.wordpress.org/reference/classes/wp_terms_list_table/) does **not**. Is this correct? I'm writing a plugin that relies heavily on `termmeta` on various custom taxonomies. My plugin adds custom columns to `edit-tags.php?taxonomy=my_custom_tax` that display the value(s) of the various `termmeta` for each term. It would greatly enhance the UX of my plugin if users were able to filter the term list by the distinct `meta_value`'s for my `meta_key`'s. Before I open a Trac ticket that proposes adding a `WP_Terms_List_Table::extra_tablenav()` method and `restrict_manage_terms` filter so that it would be possible to do what I want to do, I wanted to see if anyone here on WPSE knows: 1. is there a viable work around (that doesn't involve something like hijacking `edit-tags.php?taxonomy=my_custom_tax` to redirect to a custom page that uses a custom subclass of `WP_Terms_List_Table`)? 2. is there a (good) reason `WP_Terms_List_Table` doesn't currently support this functionality? 1. I realize for core there is no (good) reason to filter by any of the standard `WP_Term_List_Table` columns, but adding custom columns to it is fairly common and I can't believe I'm the only one who's ever wanted to filter by the values in custom columns. **Edit** I should note that I when displaying the `meta_value` in the custom column, I am outputting it as a link which effectively filters the term list by that value. The the reason the UX would be enchanced if users could choose from a dropdown (like in `WP_Posts_List_Table`) is that not all values of the `meta_value` are always visible on any given page of terms displayed in the list table. What **I** do to use the links to filter by a value that is not currently displayed on the current page is click on a random link, then edit the resulting URL in the browser's address field to have the `meta_value` **I** want to filter by. Not only is that a pain, but not all user's are savy enough to realize they can do this.
I've been searching around for the same answer to your question and running into the exact same issues, and really appreciate your thorough research. I'm definitely +1 here for proposing this addition! To attempt to answer 2) - I don't think there's a good reason to exclude it. I think WordPress's taxonomy terms are woefully lacking in features compared to the post and user entities (seeing as how term meta came much later, after post and user meta), and would like to see that change. To answer 1) - I don't know how much *better* this is than your solution, but the workaround I've come up with involves filtering the taxonomy list via the `get_terms_args` filter, and then manually inserting a select dropdown + filter button in client-side JS. Here's a sample of my setup (modified to not use my specific classes or constants), which is filtering by a certain term meta field: **PHP Logic** ``` // @see https://developer.wordpress.org/reference/hooks/get_terms_args/ add_filter( 'get_terms_args', 'taxonomy_filter', 10, 2 ); function taxonomy_filter( $args, $taxonomies ) { global $pagenow; if ( 'edit-tags.php' !== $pagenow || ! in_array( 'taxonomy-name', $taxonomies, true ) ) { return $args; } // Sort by most recently added terms, instead of alphabetically $args['orderby'] = 'term_id'; $args['order'] = 'desc'; // Filter by term meta $meta_key = ( isset( $_GET['meta_key'] ) ) ? sanitize_text_field( $_GET['meta_key'] ) : null; $meta_value = ( isset( $_GET['meta_value'] ) ) ? sanitize_text_field( $_GET['meta_value'] ) : null; if ( 'meta-filter' === $meta_key && $meta_value ) { $args['meta_key'] = $meta_key; $args['meta_value'] = $meta_value; } // Note: for more complex filtering, use the $args['meta_query'] array. return $args; } ``` At this point, you should be able to see this working simply by going to (e.g.) `yoursite.com/wp-admin/edit-tags.php?taxonomy=taxonomy-name&meta_key=meta-filter&meta_value=foobar`. **Client-side jQuery logic** (Make sure you include this file in `wp_enqueue_script()`, but only when `$pagenow === 'edit-tags.php'`). ``` /** * Param helpers */ // Get params in a JS object var params = {}; window.location.search.substr(1).split( '&' ).forEach(function(item) { params[ item.split( '=' )[0] ] = item.split( '=' )[1]; }); // Return param string based on the params object function setParams() { var string = '?'; for ( key in params ) { var value = params[ key ]; string += key + '=' + value + '&'; } return string.slice(0, -1); // Remove trailing & } /** * Add dropdown filters + functionality to term tables */ if ( 'taxonomy-name' === params.taxonomy ) { // Create the dropdown menu & HTML $( document.querySelector( '.tablenav .bulkactions' ) ).after( '\ <div class="alignleft actions"> \ <select id="js-filter-dropdown"> \ <option value="">Term Meta Filter</option> \ <option value="foo">Foo</option> \ <option value="bar">Bar</option> \ <option value="baz">Baz</option> \ </select> \ <button id="js-filter" class="button" type="button">Filter</button> \ </div> \ ' ); // If we're already filtering the view, have the dropdown reflect that var value = decodeURIComponent( params.meta_value ).replace(/\+/g, ' '); $( '#js-filter-dropdown' ).find( 'option[value="' + value + '"]' ).prop( 'selected', true ); // Set up the button action - see taxonomy_filter() for server-side filtering $( '#js-filter' ).click(function() { var value = $( '#js-filter-dropdown' ).val(); if ( value ) { params.meta_key = 'meta-filter'; params.meta_value = encodeURIComponent( value ); } else { delete params.meta_key; delete params.meta_value; } window.location.search = setParams(); }); } ``` **Screenshot of the Filtering UI** [![Before](https://i.stack.imgur.com/34v2k.png)](https://i.stack.imgur.com/34v2k.png) **Screenshot of the filtered table** [![After image](https://i.stack.imgur.com/p2FW5.png)](https://i.stack.imgur.com/p2FW5.png)
268,513
<p>I'm using the theme customizer where I'm trying to find a way to check two settings. Here's my code and an explanation what it does:</p> <pre><code>// start a setting called 'twsa_show_active_days' $wp_customize-&gt;add_setting( 'twsa_show_active_days' ); // add options to the setting, in this case a radio to select three options $wp_customize-&gt;add_control( 'twsa_show_active_days', array( 'description' =&gt; 'Weekdays and/or weekends?', 'type' =&gt; 'radio', 'section' =&gt; 'twsa_show', 'choices' =&gt; array( 'weekdays' =&gt; 'Weekdays', 'plus_sat' =&gt; 'Weekdays plus Saturday', 'full_week' =&gt; 'Weekdays plus Saturday &amp; Sunday'), // active callback to check if 'active' is selected in another setting 'active_callback' =&gt; function() use ( $wp_customize ) { return 'active' === $wp_customize-&gt;get_setting( 'twsa_show_schedule' )-&gt;value(); }, // another active_callback to check if 'twsa_show_active' is selected in another setting 'active_callback' =&gt; function() use ( $wp_customize ) { return 'daily' === $wp_customize-&gt;get_setting( 'twsa_show_active' )-&gt;value(); }) ); </code></pre> <p>My question is, how do you use <code>active_callback</code> to check two settings? It works on one setting but I need it to check two settings. Do I need to create a function?</p>
[ { "answer_id": 268516, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general, there should not be any limitation on what is being checked in <code>active_callback</code> or how the code is written. There should not be any limitation about checking two (or more) settings at the same time.</p>\n" }, { "answer_id": 268519, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>Maybe I'm misreading your question, but combining these two conditions in one anonymous function doesn't look that difficult:</p>\n\n<pre><code>'active_callback' =&gt; function() use ( $wp_customize ) {\n $condition1 == $wp_customize-&gt;get_setting( 'twsa_show_schedule' )-&gt;value();\n $condition2 == $wp_customize-&gt;get_setting( 'twsa_show_active' )-&gt;value();\n return ($condition1 &amp;&amp; $condition2); \n }\n</code></pre>\n\n<p>For really smart thinking on active callbacks, <a href=\"http://ottopress.com/2015/whats-new-with-the-customizer/\" rel=\"nofollow noreferrer\">read Otto's take on them</a>.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I'm using the theme customizer where I'm trying to find a way to check two settings. Here's my code and an explanation what it does: ``` // start a setting called 'twsa_show_active_days' $wp_customize->add_setting( 'twsa_show_active_days' ); // add options to the setting, in this case a radio to select three options $wp_customize->add_control( 'twsa_show_active_days', array( 'description' => 'Weekdays and/or weekends?', 'type' => 'radio', 'section' => 'twsa_show', 'choices' => array( 'weekdays' => 'Weekdays', 'plus_sat' => 'Weekdays plus Saturday', 'full_week' => 'Weekdays plus Saturday & Sunday'), // active callback to check if 'active' is selected in another setting 'active_callback' => function() use ( $wp_customize ) { return 'active' === $wp_customize->get_setting( 'twsa_show_schedule' )->value(); }, // another active_callback to check if 'twsa_show_active' is selected in another setting 'active_callback' => function() use ( $wp_customize ) { return 'daily' === $wp_customize->get_setting( 'twsa_show_active' )->value(); }) ); ``` My question is, how do you use `active_callback` to check two settings? It works on one setting but I need it to check two settings. Do I need to create a function?
Maybe I'm misreading your question, but combining these two conditions in one anonymous function doesn't look that difficult: ``` 'active_callback' => function() use ( $wp_customize ) { $condition1 == $wp_customize->get_setting( 'twsa_show_schedule' )->value(); $condition2 == $wp_customize->get_setting( 'twsa_show_active' )->value(); return ($condition1 && $condition2); } ``` For really smart thinking on active callbacks, [read Otto's take on them](http://ottopress.com/2015/whats-new-with-the-customizer/).
268,531
<p>I realise this may be a generic php question, but as it's related to WP I'm including it here.</p> <p>If adding a simple conditional to my page.php template, do I need to include an 'else' (for other pages) and 'endif'?</p> <pre><code>&lt;?php if (is_tree(39)) : get_template_part('templates/partial/menu-buy'); elseif (is_tree(117)) : get_template_part('templates/partial/menu-programs'); ?&gt; </code></pre> <p>Other than an 'empty condition' (don't know if that's the right word) I can't see a way to include an 'else' for other pages.</p> <p>My limited knowledge suggests it's probably good practice to finish with 'endif', but I've seen conditionals written with/without an 'endif' and hence wonder whether it's necessary.</p> <p>UPDATE: Thanks to those who've answered, I now realise there's two different forms of syntax: <a href="http://php.net/manual/en/control-structures.alternative-syntax.php" rel="nofollow noreferrer">http://php.net/manual/en/control-structures.alternative-syntax.php</a> PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.</p>
[ { "answer_id": 268533, "author": "Steve", "author_id": 120700, "author_profile": "https://wordpress.stackexchange.com/users/120700", "pm_score": 4, "selected": true, "text": "<p>You just need an else block:</p>\n\n<pre><code>//templating syntax\nif($condOne):\n //do stuff if $condOne is true\nelseif($condTwo):\n //do stuff if $condOne is false and $condTwo is true\nelse:\n //do stuff if both $condOne and $condTwo are false\nendif;\n\n//braces syntax\nif($condOne){\n //do stuff if $condOne is true\n}elseif($condTwo){\n //do stuff if $condOne is false and $condTwo is true\nelse{\n //do stuff if both $condOne and $condTwo are false\n}\n</code></pre>\n\n<p>Regarding \"it's probably good practice to finish with 'endif'\", <code>endif</code> is only used when you are using the templating syntax:</p>\n\n<pre><code>if():\n //do stuff\nendif;\n</code></pre>\n\n<p>the alternative is regular braces syntax:</p>\n\n<pre><code>if(){\n //do stuff\n}\n</code></pre>\n\n<p>The former is preferable when you are outputting html by dropping out of php with a closing php tag, because an <code>endif</code> is easier to match up than a closing brace:</p>\n\n<pre><code>&lt;?php if($someCondition):?&gt;\n\n &lt;h1&gt;Hello &lt;?=$userName?&gt;, how are you today?&lt;/h1&gt;\n &lt;ul&gt;\n &lt;?php foreach($someArray as $key =&gt; $value):?&gt;\n &lt;li&gt;&lt;?=$key?&gt; : &lt;?=$value?&gt;&lt;/li&gt;\n &lt;?php endforeach;?&gt;\n &lt;/ul&gt;\n\n&lt;?php endif;?&gt;\n</code></pre>\n\n<p>VS:</p>\n\n<pre><code>&lt;?php if($someCondition){?&gt;\n\n &lt;h1&gt;Hello &lt;?=$userName?&gt;, how are you today?&lt;/h1&gt;\n &lt;ul&gt;\n &lt;?php foreach($someArray as $key =&gt; $value){?&gt;\n &lt;li&gt;&lt;?=$key?&gt; : &lt;?=$value?&gt;&lt;/li&gt;\n &lt;?php }?&gt;\n &lt;/ul&gt;\n\n&lt;?php }?&gt;\n</code></pre>\n\n<p>However when writting code that does not drop out of php mode, the latter is far more common and arguable easier to read:</p>\n\n<pre><code>$out=[];\nif($someCondition){\n\n $out[$username]=[];\n\n foreach($someArray as $key =&gt; $value){\n\n $out[$username][] = $key . ' : ' . $value;\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 268537, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": false, "text": "<p>Well @gulliver it's kinda opinion based question. See we actually use <code>endif</code> to end the <code>if</code> conditional. If you are in a condition when a thing could change based on a condition then you have to use the <code>else</code> statement. Like below-</p>\n\n<pre><code>if('statement' == true ) {\n // do only when the statement is true\n} else {\n // do only when the statement is false\n}\n// execute the other codes.\n</code></pre>\n\n<p>Notice in above case you can skip the <code>else</code> block if you do <code>return</code>. Cause PHP will not execute anything after <code>return</code>. So the code will be-</p>\n\n<pre><code>if('statement' == true ) {\n // do only when the statement is true \n return 0;\n // Rest of the part will not be executed.\n}\n// This part will only execute when the statement is false.\n</code></pre>\n\n<p>Now the above code blocks can be written like below with different procedure using <code>if():</code>, <code>else</code> and <code>endif</code>-</p>\n\n<p><strong>First code blocks</strong>-</p>\n\n<pre><code>if('statement' == true ) :\n // do only when the statement is true\nelse :\n // do only when the statement is false\nendif;\n// execute the other codes.\n</code></pre>\n\n<p><strong>Second Code Blocks</strong>-</p>\n\n<pre><code>if('statement' == true ) :\n // do only when the statement is true \n return 0;\n // Rest of the part will not be executed.\nendif;\n// This part will only execute when the statement is false.\n</code></pre>\n\n<p>Now decide yourself if you need to include <code>else</code> <strong>and/or</strong> <code>endif</code>. Ask any kinda question in you need to know further more.</p>\n" }, { "answer_id": 268548, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p><code>endif</code> went out of tyle years ago, should just avoid using it. Main reason that pops into my mind is lack of \"block\" detection by editors which make balancing <code>if</code>s harder.</p>\n\n<p>OTOH you should probably always have an else even if it is an empty one. The idea is that you show that you actually thought about what happens in the condition fails. Right now your snippet might have no output, is it intentional?</p>\n\n<p>Best thing is probably use a linter that checks against the wordpress (or the wordpress.com VIP) coding standard. There is criticism against them, but having any coding standard is better then having none, and automatic tool that will test it helps you to actually follow it.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I realise this may be a generic php question, but as it's related to WP I'm including it here. If adding a simple conditional to my page.php template, do I need to include an 'else' (for other pages) and 'endif'? ``` <?php if (is_tree(39)) : get_template_part('templates/partial/menu-buy'); elseif (is_tree(117)) : get_template_part('templates/partial/menu-programs'); ?> ``` Other than an 'empty condition' (don't know if that's the right word) I can't see a way to include an 'else' for other pages. My limited knowledge suggests it's probably good practice to finish with 'endif', but I've seen conditionals written with/without an 'endif' and hence wonder whether it's necessary. UPDATE: Thanks to those who've answered, I now realise there's two different forms of syntax: <http://php.net/manual/en/control-structures.alternative-syntax.php> PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
You just need an else block: ``` //templating syntax if($condOne): //do stuff if $condOne is true elseif($condTwo): //do stuff if $condOne is false and $condTwo is true else: //do stuff if both $condOne and $condTwo are false endif; //braces syntax if($condOne){ //do stuff if $condOne is true }elseif($condTwo){ //do stuff if $condOne is false and $condTwo is true else{ //do stuff if both $condOne and $condTwo are false } ``` Regarding "it's probably good practice to finish with 'endif'", `endif` is only used when you are using the templating syntax: ``` if(): //do stuff endif; ``` the alternative is regular braces syntax: ``` if(){ //do stuff } ``` The former is preferable when you are outputting html by dropping out of php with a closing php tag, because an `endif` is easier to match up than a closing brace: ``` <?php if($someCondition):?> <h1>Hello <?=$userName?>, how are you today?</h1> <ul> <?php foreach($someArray as $key => $value):?> <li><?=$key?> : <?=$value?></li> <?php endforeach;?> </ul> <?php endif;?> ``` VS: ``` <?php if($someCondition){?> <h1>Hello <?=$userName?>, how are you today?</h1> <ul> <?php foreach($someArray as $key => $value){?> <li><?=$key?> : <?=$value?></li> <?php }?> </ul> <?php }?> ``` However when writting code that does not drop out of php mode, the latter is far more common and arguable easier to read: ``` $out=[]; if($someCondition){ $out[$username]=[]; foreach($someArray as $key => $value){ $out[$username][] = $key . ' : ' . $value; } } ```
268,535
<p>How i can create custom post method url in wordpress? For Example i will send data by ajax to urls: </p> <p><a href="http://example.com/?call_option=option1" rel="nofollow noreferrer">http://example.com/?call_option=option1</a> or <a href="http://example.com/?call_option=option2" rel="nofollow noreferrer">http://example.com/?call_option=option2</a></p> <p>And this will execute my code in function.php (in theme folder) </p> <pre><code>$option = trim($_GET['call_option']); if(empty($option)) { header("Location: ./404"); die(); } else { if ( $option == 'option1' ) { // do something } else if ( $option == 'option2' ) { // do something } } </code></pre> <p>Ho do this?</p>
[ { "answer_id": 268540, "author": "Jiten Gaikwad", "author_id": 120716, "author_profile": "https://wordpress.stackexchange.com/users/120716", "pm_score": 3, "selected": true, "text": "<p>WordPress comes with built in support for using AJAX calls from within your plugins or themes functions.php.</p>\n\n<p>Following is the sample example:</p>\n\n<p>Javascript code:</p>\n\n<pre><code>jQuery( document ).on( 'click', '.event-trigger', function() { \n var ajax_url = \"&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;\"; //You can define this parameter globally as well.\n jQuery.ajax({\n url : ajax_url,\n type : 'post',\n data : {\n action : 'youraction',\n param1: param1,\n param2: param2\n },\n success : function( response ) {\n alert(response)\n }\n });\n}) \n</code></pre>\n\n<p>Write the following code in plugin file or functions.php file in your theme:</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_youraction', 'your_functionname' ); //This action calls for non-authenticated users as well\nadd_action( 'wp_ajax_post_youraction', 'your_functionname' ); //This action calls only for authenticated user\n\nfunction your_functionname() {\n //your code goes here\n}\n</code></pre>\n\n<p>Refer <a href=\"https://premium.wpmudev.org/blog/using-ajax-with-wordpress/\" rel=\"nofollow noreferrer\">Ajax Example</a> for more details.</p>\n" }, { "answer_id": 268610, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>There is also another simple solution, which is using the REST-API. It returns a JSON answer which you can use in javaScript, mobile applications, and more.</p>\n\n<p>First you have to register a route to your function:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n //Path to ajax search function\n register_rest_route( 'patryk/v1', '/patryk-rest-api/', array(\n 'methods' =&gt; 'GET', \n 'callback' =&gt; 'my_rest_function' \n ) );\n});\n</code></pre>\n\n<p>Now, let's write a function to return some data:</p>\n\n<pre><code>function my_rest_function(){\n // Return of nothing is sent\n if (!isset($_POST['call_option'])) return;\n // Else, do some calculations and return a value\n $value = $_POST['call_option'];\n // Return the value\n return $data;\n}\n</code></pre>\n\n<p>Now you can access your function at <code>http://example.com/wp-json/patryk/v1/patryk-rest-api/</code>, nice and easy.</p>\n\n<p>However, the response is in JSON, so you have to specify this in your front-end script:</p>\n\n<pre><code>jQuery.ajax({\n type: 'GET', \n url: 'http://example.com/wp-json/patryk/v1/patryk-rest-api/', \n data: { get_param: 'value' }, \n dataType: 'json',\n success: function (data) {\n jQuery.each(data, function(index, element) {\n // Use a loop here to output your data\n }); \n }\n});\n</code></pre>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120726/" ]
How i can create custom post method url in wordpress? For Example i will send data by ajax to urls: <http://example.com/?call_option=option1> or <http://example.com/?call_option=option2> And this will execute my code in function.php (in theme folder) ``` $option = trim($_GET['call_option']); if(empty($option)) { header("Location: ./404"); die(); } else { if ( $option == 'option1' ) { // do something } else if ( $option == 'option2' ) { // do something } } ``` Ho do this?
WordPress comes with built in support for using AJAX calls from within your plugins or themes functions.php. Following is the sample example: Javascript code: ``` jQuery( document ).on( 'click', '.event-trigger', function() { var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; //You can define this parameter globally as well. jQuery.ajax({ url : ajax_url, type : 'post', data : { action : 'youraction', param1: param1, param2: param2 }, success : function( response ) { alert(response) } }); }) ``` Write the following code in plugin file or functions.php file in your theme: ``` add_action( 'wp_ajax_nopriv_youraction', 'your_functionname' ); //This action calls for non-authenticated users as well add_action( 'wp_ajax_post_youraction', 'your_functionname' ); //This action calls only for authenticated user function your_functionname() { //your code goes here } ``` Refer [Ajax Example](https://premium.wpmudev.org/blog/using-ajax-with-wordpress/) for more details.
268,560
<p>I'm desperately trying to make an advanced searchform in order to get posts by their meta fields. I got this: </p> <p>[UPDATE]: This is the correct code:</p> <pre><code>/** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'cabins'; $vars[] = 'base'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); &lt;?php /** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'people'; $vars[] = 'base'; $vars[] = 'duration'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); /** * Build a custom query based on several conditions * The pre_get_posts action gives developers access to the $query object by reference * any changes you make to $query are made directly to the original object - no return value is requested * */ function sy_pre_get_posts( $query ){ if( is_admin() || ! $query-&gt;is_main_query() ){ return; } $query-&gt;set( 'type', get_query_var( 'type' ) ); $query-&gt;set( 'people', get_query_var( 'people' ) ); $query-&gt;set( 'base', get_query_var( 'base' ) ); $query-&gt;set( 'duration', get_query_var( 'duration' ) ); if( !is_post_type_archive( 'fleet' ) ){ return; } $meta_query = array(); if( !empty( get_query_var( 'type' ) ) ) { $meta_query[] = array( 'key' =&gt; 'type', 'value' =&gt; get_query_var( 'type' ), 'compare' =&gt; 'LIKE' ); } elseif ( !empty( get_query_var( 'people' ) ) ){ $meta_query[] = array( 'key' =&gt; 'people', 'value' =&gt; get_query_var( 'people' ), 'compare' =&gt; 'LIKE' ); } elseif ( !empty( get_query_var( 'base' ) ) ){ $meta_query[] = array( 'key' =&gt; 'base', 'value' =&gt; get_query_var( 'base' ), 'compare' =&gt; 'LIKE' ); } elseif ( !empty( get_query_var( 'duration' ) ) ){ $meta_query[] = array( 'key' =&gt; 'duration', 'value' =&gt; get_query_var( 'duration' ), 'compare' =&gt; 'LIKE' ); } if( count( $meta_query ) &gt; 1 ){ $meta_query['relation'] = 'AND'; } if( count( $meta_query ) &gt; 0 ){ $query-&gt;set( 'meta_query', array($meta_query) ); } } add_action( 'pre_get_posts', 'sy_pre_get_posts', 1 ); function sy_search_form(){ $select_type = '&lt;select name="type" style="width: 100%"&gt;'; $select_type .= '&lt;option value="" selected="selected"&gt;' . __( 'Type', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Motor"&gt;' . __( 'Motor', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Sailing"&gt;' . __( 'Sailing', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Ribs"&gt;' . __( 'Ribs', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Caiques"&gt;' . __( 'Caiques', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Speed Boats"&gt;' . __( 'Spead Boats', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;/select&gt;' . "\n"; $select_people = '&lt;select name="people" style="width: 100%"&gt;'; $select_people .= '&lt;option value="" selected="selected"&gt;' . __( 'People', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;option value="3 or less"&gt;' . __( '3 or less', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;option value="4-6"&gt;' . __( '4-6', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;option value="6 or more"&gt;' . __( '6 or more', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;/select&gt;' . "\n"; $select_base = '&lt;select name="base" style="width: 100%"&gt;'; $select_base .= '&lt;option value="" selected="selected"&gt;' . __( 'Base', 'syacht' ) . '&lt;/option&gt;'; $select_base .= '&lt;option value="Mykonos"&gt;' . __( 'Mykonos', 'syacht' ) . '&lt;/option&gt;'; $select_base .= '&lt;option value="Old Port"&gt;' . __( 'Old Port', 'syacht' ) . '&lt;/option&gt;'; $select_base .= '&lt;/select&gt;' . "\n"; $select_duration = '&lt;select name="duration" style="width: 100%"&gt;'; $select_duration .= '&lt;option value="" selected="selected"&gt;' . __( 'Duration', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;option value="1 to 3 days"&gt;' . __( '1 to 3 days', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;option value="1 week"&gt;' . __( '1 week', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;option value="2 weeks"&gt;' . __( '2 weeks', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;/select&gt;' . "\n"; $output = '&lt;form class="advanced-search" action="' . esc_url( home_url() ) . '" method="get" role="search"&gt;'; $output .= '&lt;div class="wrap"&gt;'; $output .= '&lt;div&gt;'. $select_type . '&lt;/div&gt;'; $output .= '&lt;div&gt;'. $select_people . '&lt;/div&gt;'; $output .= '&lt;div&gt;'. $select_base . '&lt;/div&gt;'; $output .= '&lt;div&gt;'. $select_duration . '&lt;/div&gt;'; $output .= '&lt;input type="hidden" name="post_type" value="fleet" /&gt;'; $output .= '&lt;div&gt;&lt;input type="submit" id="as-submit" class="button gold full" value="Search yachts" /&gt;&lt;/div&gt;'; $output .= '&lt;a href="javascript:void(0)" class="search-hide" title="Hide this box"&gt;Hide this box&lt;/a&gt;'; $output .= '&lt;/div&gt;&lt;/form&gt;'; return $output; } </code></pre> <p>Actually this form works, but not at all. In fact, the search page shows all posts belonging to "fleet" custom post type and they are not filtered by the search terms I set. Why this? Where is the error? Please it's been days since I've started trying to solve this. Thanks all.</p> <p>P.s.: Please, do not suggest any plugin. I've tried already many, and none of them worked. </p>
[ { "answer_id": 268540, "author": "Jiten Gaikwad", "author_id": 120716, "author_profile": "https://wordpress.stackexchange.com/users/120716", "pm_score": 3, "selected": true, "text": "<p>WordPress comes with built in support for using AJAX calls from within your plugins or themes functions.php.</p>\n\n<p>Following is the sample example:</p>\n\n<p>Javascript code:</p>\n\n<pre><code>jQuery( document ).on( 'click', '.event-trigger', function() { \n var ajax_url = \"&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;\"; //You can define this parameter globally as well.\n jQuery.ajax({\n url : ajax_url,\n type : 'post',\n data : {\n action : 'youraction',\n param1: param1,\n param2: param2\n },\n success : function( response ) {\n alert(response)\n }\n });\n}) \n</code></pre>\n\n<p>Write the following code in plugin file or functions.php file in your theme:</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_youraction', 'your_functionname' ); //This action calls for non-authenticated users as well\nadd_action( 'wp_ajax_post_youraction', 'your_functionname' ); //This action calls only for authenticated user\n\nfunction your_functionname() {\n //your code goes here\n}\n</code></pre>\n\n<p>Refer <a href=\"https://premium.wpmudev.org/blog/using-ajax-with-wordpress/\" rel=\"nofollow noreferrer\">Ajax Example</a> for more details.</p>\n" }, { "answer_id": 268610, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>There is also another simple solution, which is using the REST-API. It returns a JSON answer which you can use in javaScript, mobile applications, and more.</p>\n\n<p>First you have to register a route to your function:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n //Path to ajax search function\n register_rest_route( 'patryk/v1', '/patryk-rest-api/', array(\n 'methods' =&gt; 'GET', \n 'callback' =&gt; 'my_rest_function' \n ) );\n});\n</code></pre>\n\n<p>Now, let's write a function to return some data:</p>\n\n<pre><code>function my_rest_function(){\n // Return of nothing is sent\n if (!isset($_POST['call_option'])) return;\n // Else, do some calculations and return a value\n $value = $_POST['call_option'];\n // Return the value\n return $data;\n}\n</code></pre>\n\n<p>Now you can access your function at <code>http://example.com/wp-json/patryk/v1/patryk-rest-api/</code>, nice and easy.</p>\n\n<p>However, the response is in JSON, so you have to specify this in your front-end script:</p>\n\n<pre><code>jQuery.ajax({\n type: 'GET', \n url: 'http://example.com/wp-json/patryk/v1/patryk-rest-api/', \n data: { get_param: 'value' }, \n dataType: 'json',\n success: function (data) {\n jQuery.each(data, function(index, element) {\n // Use a loop here to output your data\n }); \n }\n});\n</code></pre>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120682/" ]
I'm desperately trying to make an advanced searchform in order to get posts by their meta fields. I got this: [UPDATE]: This is the correct code: ``` /** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'cabins'; $vars[] = 'base'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); <?php /** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'people'; $vars[] = 'base'; $vars[] = 'duration'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); /** * Build a custom query based on several conditions * The pre_get_posts action gives developers access to the $query object by reference * any changes you make to $query are made directly to the original object - no return value is requested * */ function sy_pre_get_posts( $query ){ if( is_admin() || ! $query->is_main_query() ){ return; } $query->set( 'type', get_query_var( 'type' ) ); $query->set( 'people', get_query_var( 'people' ) ); $query->set( 'base', get_query_var( 'base' ) ); $query->set( 'duration', get_query_var( 'duration' ) ); if( !is_post_type_archive( 'fleet' ) ){ return; } $meta_query = array(); if( !empty( get_query_var( 'type' ) ) ) { $meta_query[] = array( 'key' => 'type', 'value' => get_query_var( 'type' ), 'compare' => 'LIKE' ); } elseif ( !empty( get_query_var( 'people' ) ) ){ $meta_query[] = array( 'key' => 'people', 'value' => get_query_var( 'people' ), 'compare' => 'LIKE' ); } elseif ( !empty( get_query_var( 'base' ) ) ){ $meta_query[] = array( 'key' => 'base', 'value' => get_query_var( 'base' ), 'compare' => 'LIKE' ); } elseif ( !empty( get_query_var( 'duration' ) ) ){ $meta_query[] = array( 'key' => 'duration', 'value' => get_query_var( 'duration' ), 'compare' => 'LIKE' ); } if( count( $meta_query ) > 1 ){ $meta_query['relation'] = 'AND'; } if( count( $meta_query ) > 0 ){ $query->set( 'meta_query', array($meta_query) ); } } add_action( 'pre_get_posts', 'sy_pre_get_posts', 1 ); function sy_search_form(){ $select_type = '<select name="type" style="width: 100%">'; $select_type .= '<option value="" selected="selected">' . __( 'Type', 'syacht' ) . '</option>'; $select_type .= '<option value="Motor">' . __( 'Motor', 'syacht' ) . '</option>'; $select_type .= '<option value="Sailing">' . __( 'Sailing', 'syacht' ) . '</option>'; $select_type .= '<option value="Ribs">' . __( 'Ribs', 'syacht' ) . '</option>'; $select_type .= '<option value="Caiques">' . __( 'Caiques', 'syacht' ) . '</option>'; $select_type .= '<option value="Speed Boats">' . __( 'Spead Boats', 'syacht' ) . '</option>'; $select_type .= '</select>' . "\n"; $select_people = '<select name="people" style="width: 100%">'; $select_people .= '<option value="" selected="selected">' . __( 'People', 'syacht' ) . '</option>'; $select_people .= '<option value="3 or less">' . __( '3 or less', 'syacht' ) . '</option>'; $select_people .= '<option value="4-6">' . __( '4-6', 'syacht' ) . '</option>'; $select_people .= '<option value="6 or more">' . __( '6 or more', 'syacht' ) . '</option>'; $select_people .= '</select>' . "\n"; $select_base = '<select name="base" style="width: 100%">'; $select_base .= '<option value="" selected="selected">' . __( 'Base', 'syacht' ) . '</option>'; $select_base .= '<option value="Mykonos">' . __( 'Mykonos', 'syacht' ) . '</option>'; $select_base .= '<option value="Old Port">' . __( 'Old Port', 'syacht' ) . '</option>'; $select_base .= '</select>' . "\n"; $select_duration = '<select name="duration" style="width: 100%">'; $select_duration .= '<option value="" selected="selected">' . __( 'Duration', 'syacht' ) . '</option>'; $select_duration .= '<option value="1 to 3 days">' . __( '1 to 3 days', 'syacht' ) . '</option>'; $select_duration .= '<option value="1 week">' . __( '1 week', 'syacht' ) . '</option>'; $select_duration .= '<option value="2 weeks">' . __( '2 weeks', 'syacht' ) . '</option>'; $select_duration .= '</select>' . "\n"; $output = '<form class="advanced-search" action="' . esc_url( home_url() ) . '" method="get" role="search">'; $output .= '<div class="wrap">'; $output .= '<div>'. $select_type . '</div>'; $output .= '<div>'. $select_people . '</div>'; $output .= '<div>'. $select_base . '</div>'; $output .= '<div>'. $select_duration . '</div>'; $output .= '<input type="hidden" name="post_type" value="fleet" />'; $output .= '<div><input type="submit" id="as-submit" class="button gold full" value="Search yachts" /></div>'; $output .= '<a href="javascript:void(0)" class="search-hide" title="Hide this box">Hide this box</a>'; $output .= '</div></form>'; return $output; } ``` Actually this form works, but not at all. In fact, the search page shows all posts belonging to "fleet" custom post type and they are not filtered by the search terms I set. Why this? Where is the error? Please it's been days since I've started trying to solve this. Thanks all. P.s.: Please, do not suggest any plugin. I've tried already many, and none of them worked.
WordPress comes with built in support for using AJAX calls from within your plugins or themes functions.php. Following is the sample example: Javascript code: ``` jQuery( document ).on( 'click', '.event-trigger', function() { var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; //You can define this parameter globally as well. jQuery.ajax({ url : ajax_url, type : 'post', data : { action : 'youraction', param1: param1, param2: param2 }, success : function( response ) { alert(response) } }); }) ``` Write the following code in plugin file or functions.php file in your theme: ``` add_action( 'wp_ajax_nopriv_youraction', 'your_functionname' ); //This action calls for non-authenticated users as well add_action( 'wp_ajax_post_youraction', 'your_functionname' ); //This action calls only for authenticated user function your_functionname() { //your code goes here } ``` Refer [Ajax Example](https://premium.wpmudev.org/blog/using-ajax-with-wordpress/) for more details.
268,563
<p>I was able to echo out all terms belonging to a custom taxonomy using the code below:</p> <pre><code>$args = array('post_type' =&gt; 'my_post_type','number' =&gt; '999'); $terms = get_terms( 'my_taxo', [ 'hide_empty' =&gt; true, 'orderby' =&gt; 'wpse_last_word', ] , $args ); foreach ( $terms as $term ) { echo '' . $term-&gt;name . ''; } </code></pre> <p>This code provides the results I want on my localhost (xampp). Basically, it outputs all of the terms assigned to a particular post. But when I upload the code to a live server, the code no longer works as expected. Instead, it shows all the terms without filtering them. I even updates the PHP version on my live server match to the local server; still no luck.</p> <p>Can anyone point out the issue on my code.</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are calling <code>get_terms()</code> with 3 parameters which actually accepts 2 parameters. The last one is extra. </li>\n<li>And secondly <code>get_terms()</code> returns all the terms of a taxonomy, not the terms associated with a post.</li>\n</ol>\n\n<p>For getting the terms associated for a post you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms</code></a>.</p>\n\n<p><strong>Usage of <code>wp_get_post_terms</code> inside <em>WordPress</em> loop-</strong></p>\n\n<p>For each post you'll get the post's terms by calling <code>wp_get_post_terms</code> like below-</p>\n\n<pre><code>//Do something if a specific array value exists within a post\n$term_list = wp_get_post_terms($post-&gt;ID, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>And for outside of the loop-</p>\n\n<pre><code>// Do something if a specific array value exists within a post\n// And somehow you need to get the post ID to pas it to below.\n$term_list = wp_get_post_terms($post_id, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 268671, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 0, "selected": false, "text": "<p>After few researchs I found below script do the work, thanks @the_dramatist pointing me to a right direction, I had use global $post, but not in a correct way</p>\n\n<pre>\nglobal $post;\n$loop = new WP_Query(array('post_type' => 'myCPT', 'posts_per_page' => -1));\nwhile ($loop->have_posts()) : $loop->the_post();\n$terms = wp_get_post_terms($post->ID, 'my_taxonomy'); \nforeach($terms as $term_single) {\necho '' . $term_single->slug. '';\n}\nendwhile;\n\n</pre>\n\n<p>If anyone getting empty results after this, just delete the categories and re-create and apply them.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97402/" ]
I was able to echo out all terms belonging to a custom taxonomy using the code below: ``` $args = array('post_type' => 'my_post_type','number' => '999'); $terms = get_terms( 'my_taxo', [ 'hide_empty' => true, 'orderby' => 'wpse_last_word', ] , $args ); foreach ( $terms as $term ) { echo '' . $term->name . ''; } ``` This code provides the results I want on my localhost (xampp). Basically, it outputs all of the terms assigned to a particular post. But when I upload the code to a live server, the code no longer works as expected. Instead, it shows all the terms without filtering them. I even updates the PHP version on my live server match to the local server; still no luck. Can anyone point out the issue on my code.
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,591
<h1>Background</h1> <p>I am trying to add page templates from inside of a plugin. For this question, I have trimmed my code down into a test plugin which has two files, the PHP main plugin file, and a PHP template file.</p> <p>wp-plugins/test-plugin/test-plugin.php</p> <p>wp-plugins/test-plugin/templates/test-template.php</p> <p>The plugin has two pieces. First off, I tap into the <code>template_include</code> filter, and I return the path to the template file (test-template.php).</p> <p>Next, I have a new extension of <code>Walker_Page</code>, called <code>Walker_Page_New</code> in this example. In the file, it is a word for word copy of <code>Walker_Page</code>.</p> <h1>Current Code</h1> <p><strong>test-plugin.php</strong></p> <pre><code>&lt;?php /** * Plugin Name: Test Plugin * Version: 1.0 * Author: Andy Mercer * Author URI: http://www.andymercer.net * License: GPL2 */ add_filter( 'template_include', 'test_get_template' ); function test_get_template( $template ) { $template_path = plugin_dir_path( __FILE__ ) . 'templates/test-template.php'; if ( file_exists( $template_path ) ) { $template = $template_path; } return $template; } class Walker_Page_New extends Walker_Page { // THE CODE IN HERE IS AN EXACT COPY OF WALKER_PAGE // I AM NOT ENTERING IT ALL IN THIS QUESTION BECAUSE IT'S A COUPLE HUNDRED LINES OF CODE } </code></pre> <p><strong>test-template.php</strong></p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en"&gt; &lt;head&gt; ...head stuff... &lt;/head&gt; &lt;body&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div&gt; &lt;?php $ancestors = get_ancestors( get_the_ID(), 'page' ); wp_list_pages([ 'title_li' =&gt; '', 'sort_column' =&gt; 'menu_order', 'child_of' =&gt; $ancestors[0], 'depth' =&gt; 2, 'walker' =&gt; 'Walker_Page_New', ]); ?&gt; &lt;/div&gt; &lt;div&gt; &lt;?php the_title(); ?&gt; &lt;?php the_content() ?&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h1>Problem</h1> <p>When I then load the page, I only get this error:</p> <blockquote> <p>Fatal error: Uncaught Error: Using $this when not in object context in C:...\wp-includes\class-wp-walker.php:199</p> </blockquote> <p>What is triggering this error is the call to <code>wp_list_pages()</code> with a custom Walker. When I remove the Walker, I am fine and everything works as expected.</p> <h1>Research</h1> <p>From looking around, the only specific mention of this I have found is semi-related here: <a href="https://github.com/Automattic/amp-wp/issues/412#issuecomment-240871878" rel="nofollow noreferrer">https://github.com/Automattic/amp-wp/issues/412#issuecomment-240871878</a>, where it's stated that using <code>template_include</code> will cause this:</p> <blockquote> <p>e.g. we would no longer have the $this context in the templates</p> </blockquote> <h1>Question</h1> <p>Is it expected that using <code>template_include</code> will break stuff? Should I use <code>template_redirect</code> instead?</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are calling <code>get_terms()</code> with 3 parameters which actually accepts 2 parameters. The last one is extra. </li>\n<li>And secondly <code>get_terms()</code> returns all the terms of a taxonomy, not the terms associated with a post.</li>\n</ol>\n\n<p>For getting the terms associated for a post you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms</code></a>.</p>\n\n<p><strong>Usage of <code>wp_get_post_terms</code> inside <em>WordPress</em> loop-</strong></p>\n\n<p>For each post you'll get the post's terms by calling <code>wp_get_post_terms</code> like below-</p>\n\n<pre><code>//Do something if a specific array value exists within a post\n$term_list = wp_get_post_terms($post-&gt;ID, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>And for outside of the loop-</p>\n\n<pre><code>// Do something if a specific array value exists within a post\n// And somehow you need to get the post ID to pas it to below.\n$term_list = wp_get_post_terms($post_id, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 268671, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 0, "selected": false, "text": "<p>After few researchs I found below script do the work, thanks @the_dramatist pointing me to a right direction, I had use global $post, but not in a correct way</p>\n\n<pre>\nglobal $post;\n$loop = new WP_Query(array('post_type' => 'myCPT', 'posts_per_page' => -1));\nwhile ($loop->have_posts()) : $loop->the_post();\n$terms = wp_get_post_terms($post->ID, 'my_taxonomy'); \nforeach($terms as $term_single) {\necho '' . $term_single->slug. '';\n}\nendwhile;\n\n</pre>\n\n<p>If anyone getting empty results after this, just delete the categories and re-create and apply them.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47789/" ]
Background ========== I am trying to add page templates from inside of a plugin. For this question, I have trimmed my code down into a test plugin which has two files, the PHP main plugin file, and a PHP template file. wp-plugins/test-plugin/test-plugin.php wp-plugins/test-plugin/templates/test-template.php The plugin has two pieces. First off, I tap into the `template_include` filter, and I return the path to the template file (test-template.php). Next, I have a new extension of `Walker_Page`, called `Walker_Page_New` in this example. In the file, it is a word for word copy of `Walker_Page`. Current Code ============ **test-plugin.php** ``` <?php /** * Plugin Name: Test Plugin * Version: 1.0 * Author: Andy Mercer * Author URI: http://www.andymercer.net * License: GPL2 */ add_filter( 'template_include', 'test_get_template' ); function test_get_template( $template ) { $template_path = plugin_dir_path( __FILE__ ) . 'templates/test-template.php'; if ( file_exists( $template_path ) ) { $template = $template_path; } return $template; } class Walker_Page_New extends Walker_Page { // THE CODE IN HERE IS AN EXACT COPY OF WALKER_PAGE // I AM NOT ENTERING IT ALL IN THIS QUESTION BECAUSE IT'S A COUPLE HUNDRED LINES OF CODE } ``` **test-template.php** ``` <!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> ...head stuff... </head> <body> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div> <?php $ancestors = get_ancestors( get_the_ID(), 'page' ); wp_list_pages([ 'title_li' => '', 'sort_column' => 'menu_order', 'child_of' => $ancestors[0], 'depth' => 2, 'walker' => 'Walker_Page_New', ]); ?> </div> <div> <?php the_title(); ?> <?php the_content() ?> </div> <?php endwhile; endif; ?> <?php wp_footer(); ?> </body> </html> ``` Problem ======= When I then load the page, I only get this error: > > Fatal error: Uncaught Error: Using $this when not in object context in C:...\wp-includes\class-wp-walker.php:199 > > > What is triggering this error is the call to `wp_list_pages()` with a custom Walker. When I remove the Walker, I am fine and everything works as expected. Research ======== From looking around, the only specific mention of this I have found is semi-related here: <https://github.com/Automattic/amp-wp/issues/412#issuecomment-240871878>, where it's stated that using `template_include` will cause this: > > e.g. we would no longer have the $this context in the templates > > > Question ======== Is it expected that using `template_include` will break stuff? Should I use `template_redirect` instead?
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,607
<p>I've got a page where I only want to display one post per page with pagination at the bottom to go to the next/ previous post. This is my code:</p> <pre><code> &lt;?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1'; $args = array ( 'nopaging' =&gt; false, 'paged' =&gt; $paged, 'posts_per_page' =&gt; '1', 'post_type' =&gt; 'post', 'category_name' =&gt; 'enforcement', ); ?&gt; &lt;?php $wp_query = new WP_Query($args); ?&gt; &lt;?php if ( $wp_query-&gt;have_posts() ) : ?&gt; &lt;?php while ( $wp_query-&gt;have_posts() ) : the_post(); ?&gt; &lt;!--&lt;div class="case-studies-text-banner"&gt; &lt;img src="http://www.mariadev.co.uk/wp-content/uploads/2017/05/case-study-layer.png"/&gt; &lt;div class="case-study-title"&gt;&lt;?php the_title(); ?&gt;&lt;/div&gt; &lt;div class="case-study-pdf"&gt;&lt;?php if (function_exists("wpptopdfenh_display_icon")) echo wpptopdfenh_display_icon();?&gt;&lt;/div&gt; &lt;/div&gt;--&gt; &lt;?php the_content(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php next_posts_link( 'Older Entries »', $query-&gt;max_num_pages ); ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php __('No News'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre> <p>It does only show 1 post on the first page but when clicking on older posts and moving to this url <code>www.testing./?cat=8&amp;paged=2</code> no posts show even though there are 3 posts in this category. Any ideas what I'm doing wrong?</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are calling <code>get_terms()</code> with 3 parameters which actually accepts 2 parameters. The last one is extra. </li>\n<li>And secondly <code>get_terms()</code> returns all the terms of a taxonomy, not the terms associated with a post.</li>\n</ol>\n\n<p>For getting the terms associated for a post you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms</code></a>.</p>\n\n<p><strong>Usage of <code>wp_get_post_terms</code> inside <em>WordPress</em> loop-</strong></p>\n\n<p>For each post you'll get the post's terms by calling <code>wp_get_post_terms</code> like below-</p>\n\n<pre><code>//Do something if a specific array value exists within a post\n$term_list = wp_get_post_terms($post-&gt;ID, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>And for outside of the loop-</p>\n\n<pre><code>// Do something if a specific array value exists within a post\n// And somehow you need to get the post ID to pas it to below.\n$term_list = wp_get_post_terms($post_id, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 268671, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 0, "selected": false, "text": "<p>After few researchs I found below script do the work, thanks @the_dramatist pointing me to a right direction, I had use global $post, but not in a correct way</p>\n\n<pre>\nglobal $post;\n$loop = new WP_Query(array('post_type' => 'myCPT', 'posts_per_page' => -1));\nwhile ($loop->have_posts()) : $loop->the_post();\n$terms = wp_get_post_terms($post->ID, 'my_taxonomy'); \nforeach($terms as $term_single) {\necho '' . $term_single->slug. '';\n}\nendwhile;\n\n</pre>\n\n<p>If anyone getting empty results after this, just delete the categories and re-create and apply them.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268607", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120767/" ]
I've got a page where I only want to display one post per page with pagination at the bottom to go to the next/ previous post. This is my code: ``` <?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1'; $args = array ( 'nopaging' => false, 'paged' => $paged, 'posts_per_page' => '1', 'post_type' => 'post', 'category_name' => 'enforcement', ); ?> <?php $wp_query = new WP_Query($args); ?> <?php if ( $wp_query->have_posts() ) : ?> <?php while ( $wp_query->have_posts() ) : the_post(); ?> <!--<div class="case-studies-text-banner"> <img src="http://www.mariadev.co.uk/wp-content/uploads/2017/05/case-study-layer.png"/> <div class="case-study-title"><?php the_title(); ?></div> <div class="case-study-pdf"><?php if (function_exists("wpptopdfenh_display_icon")) echo wpptopdfenh_display_icon();?></div> </div>--> <?php the_content(); ?> <?php endwhile; ?> <?php next_posts_link( 'Older Entries »', $query->max_num_pages ); ?> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php __('No News'); ?></p> <?php endif; ?> ``` It does only show 1 post on the first page but when clicking on older posts and moving to this url `www.testing./?cat=8&paged=2` no posts show even though there are 3 posts in this category. Any ideas what I'm doing wrong?
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,609
<p>We use Open Live Writer to upload to our Wordpress Blog on GoDaddy. It takes us numerous times to upload the draft with pictures to the Blog as we get the error message of lost connection. I have noticed in the Media file that the pictures are uploading in stages. That is, after I get the connection error message I check the Media file and more pictures have uploaded. Finally the Draft shows up in the Post file and all pictures are there. Sometimes I need to change the hotpot I am using as it also seems to get stuck. </p> <p>Other than a smaller Blog posting what can we due to limit these disconnections?</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are calling <code>get_terms()</code> with 3 parameters which actually accepts 2 parameters. The last one is extra. </li>\n<li>And secondly <code>get_terms()</code> returns all the terms of a taxonomy, not the terms associated with a post.</li>\n</ol>\n\n<p>For getting the terms associated for a post you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms</code></a>.</p>\n\n<p><strong>Usage of <code>wp_get_post_terms</code> inside <em>WordPress</em> loop-</strong></p>\n\n<p>For each post you'll get the post's terms by calling <code>wp_get_post_terms</code> like below-</p>\n\n<pre><code>//Do something if a specific array value exists within a post\n$term_list = wp_get_post_terms($post-&gt;ID, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>And for outside of the loop-</p>\n\n<pre><code>// Do something if a specific array value exists within a post\n// And somehow you need to get the post ID to pas it to below.\n$term_list = wp_get_post_terms($post_id, 'your_taxonomy', array(\"fields\" =&gt; \"all\"));\n// Then you can run a foreach loop to show the taxonomy terms infront.\nforeach($term_list as $term_single) {\n echo $term_single-&gt;slug; //do something here\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 268671, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 0, "selected": false, "text": "<p>After few researchs I found below script do the work, thanks @the_dramatist pointing me to a right direction, I had use global $post, but not in a correct way</p>\n\n<pre>\nglobal $post;\n$loop = new WP_Query(array('post_type' => 'myCPT', 'posts_per_page' => -1));\nwhile ($loop->have_posts()) : $loop->the_post();\n$terms = wp_get_post_terms($post->ID, 'my_taxonomy'); \nforeach($terms as $term_single) {\necho '' . $term_single->slug. '';\n}\nendwhile;\n\n</pre>\n\n<p>If anyone getting empty results after this, just delete the categories and re-create and apply them.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268609", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120768/" ]
We use Open Live Writer to upload to our Wordpress Blog on GoDaddy. It takes us numerous times to upload the draft with pictures to the Blog as we get the error message of lost connection. I have noticed in the Media file that the pictures are uploading in stages. That is, after I get the connection error message I check the Media file and more pictures have uploaded. Finally the Draft shows up in the Post file and all pictures are there. Sometimes I need to change the hotpot I am using as it also seems to get stuck. Other than a smaller Blog posting what can we due to limit these disconnections?
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,615
<p>How can I prevent Headers from being sent?</p> <p>I am trying to list (WordPress) blog posts on a non-WordPress site (both sites share a public web folder). </p> <p>I want to run the following PHP code to get the blog posts:</p> <pre><code> &lt;ul class='list-unstyled'&gt; &lt;?php define('WP_USE_THEMES', false); require($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php'); query_posts('showposts=5'); while (have_posts()): the_post(); ?&gt; &lt;li&gt;&lt;i class='glyphicon glyphicon-menu-right'&gt;&lt;/i&gt; &lt;h4&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" class="myred text-main"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt; &lt;p&gt;&lt;?php the_date(); ?&gt; | Category: &lt;?php the_category(','); ?&gt; | &lt;?php the_tags(); ?&gt;&lt;/p&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; </code></pre> <p>However, it seems running this code sends payload headers to client. Is there any way to retrieve the blog posts without sending headers?</p>
[ { "answer_id": 268617, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 0, "selected": false, "text": "<p>Output of the page started as your php is executing. Look into into <a href=\"http://php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">output buffering</a>.</p>\n\n<p>Putting a <a href=\"http://php.net/manual/en/function.ob-start.php\" rel=\"nofollow noreferrer\">ob_start()</a> function call before any HTML in the file and a call to <a href=\"http://php.net/manual/en/function.ob-get-clean.php\" rel=\"nofollow noreferrer\">ob_get_clean()</a> after should solve the problem.</p>\n\n<p>It would look something like this:</p>\n\n<pre><code>&lt;?php\n\ndefine('WP_USE_THEMES', false);\nrequire($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php');\n//Buffer output instead of immediately sending to the client\n//make sure there is only PHP here\nob_start();\n?&gt;\n//templating stuff...\n &lt;ul class='list-unstyled'&gt;\n &lt;?php\n query_posts('showposts=5');\n while (have_posts()): the_post();\n ?&gt;\n &lt;li&gt;&lt;i class='glyphicon glyphicon-menu-right'&gt;&lt;/i&gt;\n &lt;h4&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" class=\"myred text-main\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;\n &lt;p&gt;&lt;?php the_date(); ?&gt; | Category: &lt;?php the_category(','); ?&gt; | &lt;?php the_tags(); ?&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/ul&gt;\n//More templating stuff...\n&lt;?php\nob_get_clean();\n//output starts\n?&gt;\n</code></pre>\n\n<p>Also as Rick Hellewell pointed out in <a href=\"https://wordpress.stackexchange.com/a/268620/119673\">his answer</a>, make sure the file starts with <em>nothing</em> but an opening <code>&lt;?php</code> tag. No blank space, not HTML, nothing.</p>\n" }, { "answer_id": 268620, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>\"Headers already sent\" is not a WordPress error, it is PHP processing error message. Good explanation here; <a href=\"https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php\">https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php</a> .</p>\n\n<p>I suspect it might be caused by some characters (probably space characters) sent before your <code>&lt;?php</code> code segment. Even space (or tab [code formatting] ) characters will cause an error. </p>\n\n<p>And perhaps move your <code>&lt;ul&gt;</code> code to just above the <code>while</code> loop.</p>\n" }, { "answer_id": 269925, "author": "Jeff Wilkerson", "author_id": 120771, "author_profile": "https://wordpress.stackexchange.com/users/120771", "pm_score": 0, "selected": false, "text": "<p>I solved my problem by installing the REST API plugin, then calling the end point from my non-wordpress site, caching the results, then displaying the blog list from my cache results.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120771/" ]
How can I prevent Headers from being sent? I am trying to list (WordPress) blog posts on a non-WordPress site (both sites share a public web folder). I want to run the following PHP code to get the blog posts: ``` <ul class='list-unstyled'> <?php define('WP_USE_THEMES', false); require($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php'); query_posts('showposts=5'); while (have_posts()): the_post(); ?> <li><i class='glyphicon glyphicon-menu-right'></i> <h4><a href="<?php the_permalink(); ?>" class="myred text-main"><?php the_title(); ?></a></h4> <p><?php the_date(); ?> | Category: <?php the_category(','); ?> | <?php the_tags(); ?></p> </li> <?php endwhile; ?> </ul> ``` However, it seems running this code sends payload headers to client. Is there any way to retrieve the blog posts without sending headers?
"Headers already sent" is not a WordPress error, it is PHP processing error message. Good explanation here; <https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php> . I suspect it might be caused by some characters (probably space characters) sent before your `<?php` code segment. Even space (or tab [code formatting] ) characters will cause an error. And perhaps move your `<ul>` code to just above the `while` loop.
268,630
<p>I'm working on a function where I just want to output a button that links to a specific term. I have used <code>get_the_terms</code> and have gotten it to work successfully, but I've been trying <code>get_term</code> and I've have no luck. I want the shortcode to look like this <code>[see_all_products category="bakery"]</code> and output a button that links to it.</p> <p>This is my function so far:</p> <pre><code>function product_category_button($atts) { extract(shortcode_atts(array( 'category' =&gt; '', ), $atts)); // if( $category ) : // Vars $taxonomy = 'product_categories'; $term = get_term( $category, $taxonomy ); //$post-&gt;ID $cat = $term-&gt;name; $parent = $term-&gt;parent; var_dump($cat); if ($parent == NULL) : // Vars $link = get_term_link( $term-&gt;slug, $taxonomy); $html_out = ''; $html_out .= '&lt;a class="x-btn x-btn-primary x-btn-global hvr-bounce-to-bottom" href="' . $link . '"&gt;' . 'See All Products' . $cat . '&lt;/a&gt;'; endif; return $html_out; // endif; } add_shortcode( 'see_all_products', 'product_category_button' ); </code></pre> <p>Right now, <code>$link</code> gives me this error "Catchable fatal error: Object of class WP_Error could not be converted to string" and <code>$cat</code> returns <code>NULL</code> in the <code>var_dump</code>.</p> <p>Not sure if this could be affecting it, but the <code>$parent</code> stuff here was meant to get only the parent term.</p>
[ { "answer_id": 268617, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 0, "selected": false, "text": "<p>Output of the page started as your php is executing. Look into into <a href=\"http://php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">output buffering</a>.</p>\n\n<p>Putting a <a href=\"http://php.net/manual/en/function.ob-start.php\" rel=\"nofollow noreferrer\">ob_start()</a> function call before any HTML in the file and a call to <a href=\"http://php.net/manual/en/function.ob-get-clean.php\" rel=\"nofollow noreferrer\">ob_get_clean()</a> after should solve the problem.</p>\n\n<p>It would look something like this:</p>\n\n<pre><code>&lt;?php\n\ndefine('WP_USE_THEMES', false);\nrequire($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php');\n//Buffer output instead of immediately sending to the client\n//make sure there is only PHP here\nob_start();\n?&gt;\n//templating stuff...\n &lt;ul class='list-unstyled'&gt;\n &lt;?php\n query_posts('showposts=5');\n while (have_posts()): the_post();\n ?&gt;\n &lt;li&gt;&lt;i class='glyphicon glyphicon-menu-right'&gt;&lt;/i&gt;\n &lt;h4&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" class=\"myred text-main\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;\n &lt;p&gt;&lt;?php the_date(); ?&gt; | Category: &lt;?php the_category(','); ?&gt; | &lt;?php the_tags(); ?&gt;&lt;/p&gt;\n &lt;/li&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/ul&gt;\n//More templating stuff...\n&lt;?php\nob_get_clean();\n//output starts\n?&gt;\n</code></pre>\n\n<p>Also as Rick Hellewell pointed out in <a href=\"https://wordpress.stackexchange.com/a/268620/119673\">his answer</a>, make sure the file starts with <em>nothing</em> but an opening <code>&lt;?php</code> tag. No blank space, not HTML, nothing.</p>\n" }, { "answer_id": 268620, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>\"Headers already sent\" is not a WordPress error, it is PHP processing error message. Good explanation here; <a href=\"https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php\">https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php</a> .</p>\n\n<p>I suspect it might be caused by some characters (probably space characters) sent before your <code>&lt;?php</code> code segment. Even space (or tab [code formatting] ) characters will cause an error. </p>\n\n<p>And perhaps move your <code>&lt;ul&gt;</code> code to just above the <code>while</code> loop.</p>\n" }, { "answer_id": 269925, "author": "Jeff Wilkerson", "author_id": 120771, "author_profile": "https://wordpress.stackexchange.com/users/120771", "pm_score": 0, "selected": false, "text": "<p>I solved my problem by installing the REST API plugin, then calling the end point from my non-wordpress site, caching the results, then displaying the blog list from my cache results.</p>\n" } ]
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96257/" ]
I'm working on a function where I just want to output a button that links to a specific term. I have used `get_the_terms` and have gotten it to work successfully, but I've been trying `get_term` and I've have no luck. I want the shortcode to look like this `[see_all_products category="bakery"]` and output a button that links to it. This is my function so far: ``` function product_category_button($atts) { extract(shortcode_atts(array( 'category' => '', ), $atts)); // if( $category ) : // Vars $taxonomy = 'product_categories'; $term = get_term( $category, $taxonomy ); //$post->ID $cat = $term->name; $parent = $term->parent; var_dump($cat); if ($parent == NULL) : // Vars $link = get_term_link( $term->slug, $taxonomy); $html_out = ''; $html_out .= '<a class="x-btn x-btn-primary x-btn-global hvr-bounce-to-bottom" href="' . $link . '">' . 'See All Products' . $cat . '</a>'; endif; return $html_out; // endif; } add_shortcode( 'see_all_products', 'product_category_button' ); ``` Right now, `$link` gives me this error "Catchable fatal error: Object of class WP\_Error could not be converted to string" and `$cat` returns `NULL` in the `var_dump`. Not sure if this could be affecting it, but the `$parent` stuff here was meant to get only the parent term.
"Headers already sent" is not a WordPress error, it is PHP processing error message. Good explanation here; <https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php> . I suspect it might be caused by some characters (probably space characters) sent before your `<?php` code segment. Even space (or tab [code formatting] ) characters will cause an error. And perhaps move your `<ul>` code to just above the `while` loop.
268,653
<p>Media Library is not loading on grid view and also featured image not select any image from post and page . The progress circle keeps spinning. Due to this issue, I am not able to add any image in the post as insert image option also opens in “grid view” by default.</p> <p>The things I tried but not resolved my issue:</p> <ol> <li>Removed all plugins. Switch to twenty sixteen theme.</li> <li>Deleted whole wordpress installation. Installed fresh. </li> <li>Enabled script debug.Doesn’t show any error in console. Tried reloading the page too.</li> </ol> <p>I am not able to do anything on my website for many days now, please help me.</p>
[ { "answer_id": 268778, "author": "Pavnish Yadav", "author_id": 68882, "author_profile": "https://wordpress.stackexchange.com/users/68882", "pm_score": -1, "selected": false, "text": "<p>I faced same issue on my wordpress site. After the lot of debugging i fixed my problem step by step.</p>\n\n<ol>\n<li>First add given below code your db-config.php</li>\n</ol>\n\n<blockquote>\n<pre><code>define('SCRIPT_DEBUG', TRUE);\ndefine('WP_DEBUG', TRUE);\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n</blockquote>\n\n<ol start=\"2\">\n<li>Then goto /wp-includes/js/wp-util.js files and find the code $.ajax(\noptions ) on line number 100(depand your wordpress version) insert given below code into your file</li>\n</ol>\n\n<blockquote>\n<pre><code>deferred.jqXHR = $.ajax( options ).done( function( response ) {\n try {\n response = JSON.parse(response);\n } catch (Exception) {\n response = response;\n }\n</code></pre>\n</blockquote>\n\n<p>Please check your may be resolved.</p>\n\n<ol>\n<li>if you Removed constant from db-config.php</li>\n</ol>\n\n<blockquote>\n<pre><code>define('SCRIPT_DEBUG', TRUE);\ndefine('WP_DEBUG', TRUE);\ndefine( 'WP_DEBUG_LOG', true ); \n</code></pre>\n</blockquote>\n\n<ol start=\"2\">\n<li>Then compress your /wp-includes/js/wp-util.js file code and put your compressed code into /wp-includes/js/wp-util.min.js </li>\n</ol>\n" }, { "answer_id": 283688, "author": "phpdevpb", "author_id": 127340, "author_profile": "https://wordpress.stackexchange.com/users/127340", "pm_score": -1, "selected": false, "text": "<p>I had same problem before few days. I tried to use the function <a href=\"https://stackoverflow.com/questions/4401949/whats-the-use-of-ob-start-in-php\">ob_start()</a>;</p>\n\n<p>on top in function.php file of active theme. And Media Library loaded well.</p>\n" }, { "answer_id": 306455, "author": "Thomas Herbert", "author_id": 145562, "author_profile": "https://wordpress.stackexchange.com/users/145562", "pm_score": -1, "selected": false, "text": "<p>I know this thread is old, but I just solved this and maybe my solution can help others. I also was not able to create any posts. My site had the list view working, but not the grid view, and every upload actually did go through although the upload feature would display the typical (media upload failed) error. I was able to view all of my photo uploads in /wp-content/uploads even after the library error.</p>\n\n<p>I am new to PHP, and learning how to write my own scripts. I wrote a script to hide menu items/notices on the admin pages for my client, and I used:</p>\n\n<pre><code>add_action('admin_init' , 'makeDashboardPretty');\n</code></pre>\n\n<p>to hook into the admin pages to do this. This would run my script before anything on the admin page would load. One of the items I hid was my theme's menu item, which apparently needs to load in order to get the media library/posting working. I think the <code>echo ''; ?&gt;</code> css in my script would prevent my theme from enabling the media library/posting features. </p>\n\n<p>I changed my admin hook to:</p>\n\n<pre><code>add_action('wp_after_admin_bar_render' , 'makeDashboardPretty');\n</code></pre>\n\n<p>which allowed my script to initialize after my theme's menu item did. This enabled me to hide the item and still get the theme working.</p>\n" }, { "answer_id": 321157, "author": "john", "author_id": 92005, "author_profile": "https://wordpress.stackexchange.com/users/92005", "pm_score": 0, "selected": false, "text": "<p>I ran into a similar issue with the same symptoms. What I determined was in my theme's function.php there was a DEBUG statement that output some html. While this was fine for browsing, when the POST request came into admin-ajax.php to refresh the thumbnails, it was causing the infinite spinning wheel and not showing images. I removed the output from functions.php and problem was resolved.</p>\n\n<p>Not sure if this will work for you, but I found the issue by using the following command:</p>\n\n<pre><code>curl -X POST http://YOUR_DOMAIN_NAME_HERE/wp-admin/admin-ajax.php -d 'action=query-attachments&amp;post_id=0&amp;query[orderby]=date&amp;query[order]=DESC&amp;query[post_per_page]=40&amp;query[paged]=1'\n</code></pre>\n" }, { "answer_id": 400502, "author": "shankar kanase", "author_id": 217117, "author_profile": "https://wordpress.stackexchange.com/users/217117", "pm_score": 0, "selected": false, "text": "<p>Adding following code to functions.php file of theme folder worked for me.</p>\n<pre><code>add_action('admin_head', 'my_custom_style'); \n \n function my_custom_style()\n {\n echo '&lt;style&gt;\n .media-frame.mode-grid .media-toolbar {\n \n height: 60px !important;\n }\n &lt;/style&gt;';\n }\n</code></pre>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68882/" ]
Media Library is not loading on grid view and also featured image not select any image from post and page . The progress circle keeps spinning. Due to this issue, I am not able to add any image in the post as insert image option also opens in “grid view” by default. The things I tried but not resolved my issue: 1. Removed all plugins. Switch to twenty sixteen theme. 2. Deleted whole wordpress installation. Installed fresh. 3. Enabled script debug.Doesn’t show any error in console. Tried reloading the page too. I am not able to do anything on my website for many days now, please help me.
I ran into a similar issue with the same symptoms. What I determined was in my theme's function.php there was a DEBUG statement that output some html. While this was fine for browsing, when the POST request came into admin-ajax.php to refresh the thumbnails, it was causing the infinite spinning wheel and not showing images. I removed the output from functions.php and problem was resolved. Not sure if this will work for you, but I found the issue by using the following command: ``` curl -X POST http://YOUR_DOMAIN_NAME_HERE/wp-admin/admin-ajax.php -d 'action=query-attachments&post_id=0&query[orderby]=date&query[order]=DESC&query[post_per_page]=40&query[paged]=1' ```
268,669
<p>I have a custom post type containing job listings, that is highly volatile. Jobs are frequently added and removed. Our analytics show that a lot of crawling errors are for detail pages of jobs that have been unlisted.</p> <p>The solution I came up with is to redirect all visits for non-existant URLs within the CPT's slug to the job listing overview, and I would like to automate this.</p> <p>How would I go about this? I'm looking for a solution that does this very early and skips as much unnecessary calls as possible. (i.e. something earlier than doing this in header.php, ideally as an action)</p> <p>Example:</p> <ul> <li><code>mydomain.com/jobs/existingjob/</code> delivers the detail page for the job</li> <li><code>mydomain.com/jobs/nojobhere/</code> does not exist and would throw a 404 but instead gets redirected to <code>mydomain.com/jobs/</code></li> </ul>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really be deleting that page? Or should I just make it better? If you decide to make sure you send the proper HTTP header: a 410 content deleted header.</p>\n\n<p><strong>404 and 410 HTTP headers</strong>\nThe difference between a 404 and a 410 header is simple: \n404 means “content not found”, 410 means “content deleted” and is thus more specific. \nIf a URL returns a 410, Google is far more certain you removed the URL on purpose and it \nshould thus remove that URL from its index. This means it will do so much quicker.</p>\n\n<p>You can use Yoast SEO Premium plugin, the redirects module in this plugin is capable of \nserving 410 headers. </p>\n" }, { "answer_id": 268677, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 3, "selected": true, "text": "<p>It looks like <code>template_redirect</code> is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. </p>\n\n<p>You can try adding this into your <code>/wp-content/themes/yourtheme/functions.php</code> file to achieve a dynamic redirect for all 404's that happen when viewing single jobs:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect()\n{\n // check if is a 404 error, and it's on your jobs custom post type\n if( is_404() &amp;&amp; is_singular('your-job-custom-post-type') )\n {\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" }, { "answer_id": 317427, "author": "pilotfryer", "author_id": 152853, "author_profile": "https://wordpress.stackexchange.com/users/152853", "pm_score": 1, "selected": false, "text": "<p>I don't have the rep to comment on Ben HartLenn's answer, and I know this is an old post, but to save future users from wasting time:\nis_singular('post_type') will not work on a 404 page.\n$wp_query->queried_object will also not work.</p>\n\n<p>This does work:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect(){\n //check for 404\n if( is_404()){\n global $wp_query;\n //check that wp has figured out post_type from the request\n //and it's the type you're looking for\n if( isset($wp_query-&gt;query['post_type']) &amp;&amp; $wp_query-&gt;query['post_type'] == 'your-job-custom-post-type' ){\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268669", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120812/" ]
I have a custom post type containing job listings, that is highly volatile. Jobs are frequently added and removed. Our analytics show that a lot of crawling errors are for detail pages of jobs that have been unlisted. The solution I came up with is to redirect all visits for non-existant URLs within the CPT's slug to the job listing overview, and I would like to automate this. How would I go about this? I'm looking for a solution that does this very early and skips as much unnecessary calls as possible. (i.e. something earlier than doing this in header.php, ideally as an action) Example: * `mydomain.com/jobs/existingjob/` delivers the detail page for the job * `mydomain.com/jobs/nojobhere/` does not exist and would throw a 404 but instead gets redirected to `mydomain.com/jobs/`
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,696
<p>Using theme (and child theme) of Sailent, I'm trying to work out a way to completely remove a menu item from my navigation bar while on desktop. See site here: <a href="http://www.boinginflatables.com/2017update/" rel="nofollow noreferrer">http://www.boinginflatables.com/2017update/</a></p> <p><a href="https://i.stack.imgur.com/7eec2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7eec2.png" alt="It&#39;s there, although not visible"></a> As you can see, the text for the menu item isn't there, yet it messes up the alignment of the menu. </p> <p>At the moment, I have that menu item set to a css class of mobile-only with css settings as: </p> <pre><code>.mobile-only { visibility:hidden; } @media (min-width:992px) { .desktop-only { visibility:visible !important; } } @media (max-width: 991px) { .mobile-only { visibility:visible !important; } .desktop-only { visibility:hidden !important; } } </code></pre>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really be deleting that page? Or should I just make it better? If you decide to make sure you send the proper HTTP header: a 410 content deleted header.</p>\n\n<p><strong>404 and 410 HTTP headers</strong>\nThe difference between a 404 and a 410 header is simple: \n404 means “content not found”, 410 means “content deleted” and is thus more specific. \nIf a URL returns a 410, Google is far more certain you removed the URL on purpose and it \nshould thus remove that URL from its index. This means it will do so much quicker.</p>\n\n<p>You can use Yoast SEO Premium plugin, the redirects module in this plugin is capable of \nserving 410 headers. </p>\n" }, { "answer_id": 268677, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 3, "selected": true, "text": "<p>It looks like <code>template_redirect</code> is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. </p>\n\n<p>You can try adding this into your <code>/wp-content/themes/yourtheme/functions.php</code> file to achieve a dynamic redirect for all 404's that happen when viewing single jobs:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect()\n{\n // check if is a 404 error, and it's on your jobs custom post type\n if( is_404() &amp;&amp; is_singular('your-job-custom-post-type') )\n {\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" }, { "answer_id": 317427, "author": "pilotfryer", "author_id": 152853, "author_profile": "https://wordpress.stackexchange.com/users/152853", "pm_score": 1, "selected": false, "text": "<p>I don't have the rep to comment on Ben HartLenn's answer, and I know this is an old post, but to save future users from wasting time:\nis_singular('post_type') will not work on a 404 page.\n$wp_query->queried_object will also not work.</p>\n\n<p>This does work:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect(){\n //check for 404\n if( is_404()){\n global $wp_query;\n //check that wp has figured out post_type from the request\n //and it's the type you're looking for\n if( isset($wp_query-&gt;query['post_type']) &amp;&amp; $wp_query-&gt;query['post_type'] == 'your-job-custom-post-type' ){\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120829/" ]
Using theme (and child theme) of Sailent, I'm trying to work out a way to completely remove a menu item from my navigation bar while on desktop. See site here: <http://www.boinginflatables.com/2017update/> [![It's there, although not visible](https://i.stack.imgur.com/7eec2.png)](https://i.stack.imgur.com/7eec2.png) As you can see, the text for the menu item isn't there, yet it messes up the alignment of the menu. At the moment, I have that menu item set to a css class of mobile-only with css settings as: ``` .mobile-only { visibility:hidden; } @media (min-width:992px) { .desktop-only { visibility:visible !important; } } @media (max-width: 991px) { .mobile-only { visibility:visible !important; } .desktop-only { visibility:hidden !important; } } ```
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,700
<p>I need to get all post ids, post_titles and the according meta_value which is "featured" for a custom post_type. I think I need to do a join, but I don't know how they work.. Could anyone help me out on this? </p>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really be deleting that page? Or should I just make it better? If you decide to make sure you send the proper HTTP header: a 410 content deleted header.</p>\n\n<p><strong>404 and 410 HTTP headers</strong>\nThe difference between a 404 and a 410 header is simple: \n404 means “content not found”, 410 means “content deleted” and is thus more specific. \nIf a URL returns a 410, Google is far more certain you removed the URL on purpose and it \nshould thus remove that URL from its index. This means it will do so much quicker.</p>\n\n<p>You can use Yoast SEO Premium plugin, the redirects module in this plugin is capable of \nserving 410 headers. </p>\n" }, { "answer_id": 268677, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 3, "selected": true, "text": "<p>It looks like <code>template_redirect</code> is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. </p>\n\n<p>You can try adding this into your <code>/wp-content/themes/yourtheme/functions.php</code> file to achieve a dynamic redirect for all 404's that happen when viewing single jobs:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect()\n{\n // check if is a 404 error, and it's on your jobs custom post type\n if( is_404() &amp;&amp; is_singular('your-job-custom-post-type') )\n {\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" }, { "answer_id": 317427, "author": "pilotfryer", "author_id": 152853, "author_profile": "https://wordpress.stackexchange.com/users/152853", "pm_score": 1, "selected": false, "text": "<p>I don't have the rep to comment on Ben HartLenn's answer, and I know this is an old post, but to save future users from wasting time:\nis_singular('post_type') will not work on a 404 page.\n$wp_query->queried_object will also not work.</p>\n\n<p>This does work:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect(){\n //check for 404\n if( is_404()){\n global $wp_query;\n //check that wp has figured out post_type from the request\n //and it's the type you're looking for\n if( isset($wp_query-&gt;query['post_type']) &amp;&amp; $wp_query-&gt;query['post_type'] == 'your-job-custom-post-type' ){\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80443/" ]
I need to get all post ids, post\_titles and the according meta\_value which is "featured" for a custom post\_type. I think I need to do a join, but I don't know how they work.. Could anyone help me out on this?
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,732
<p>Is it possible to password protect a PDF for visitors to our website (not users)? We have uploaded a PDF to our media and created a link to it on a page, but we would like to password protect just that PDF and not the whole page that contains the link to it.</p>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really be deleting that page? Or should I just make it better? If you decide to make sure you send the proper HTTP header: a 410 content deleted header.</p>\n\n<p><strong>404 and 410 HTTP headers</strong>\nThe difference between a 404 and a 410 header is simple: \n404 means “content not found”, 410 means “content deleted” and is thus more specific. \nIf a URL returns a 410, Google is far more certain you removed the URL on purpose and it \nshould thus remove that URL from its index. This means it will do so much quicker.</p>\n\n<p>You can use Yoast SEO Premium plugin, the redirects module in this plugin is capable of \nserving 410 headers. </p>\n" }, { "answer_id": 268677, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 3, "selected": true, "text": "<p>It looks like <code>template_redirect</code> is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. </p>\n\n<p>You can try adding this into your <code>/wp-content/themes/yourtheme/functions.php</code> file to achieve a dynamic redirect for all 404's that happen when viewing single jobs:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect()\n{\n // check if is a 404 error, and it's on your jobs custom post type\n if( is_404() &amp;&amp; is_singular('your-job-custom-post-type') )\n {\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" }, { "answer_id": 317427, "author": "pilotfryer", "author_id": 152853, "author_profile": "https://wordpress.stackexchange.com/users/152853", "pm_score": 1, "selected": false, "text": "<p>I don't have the rep to comment on Ben HartLenn's answer, and I know this is an old post, but to save future users from wasting time:\nis_singular('post_type') will not work on a 404 page.\n$wp_query->queried_object will also not work.</p>\n\n<p>This does work:</p>\n\n<pre><code>add_action( 'template_redirect', 'unlisted_jobs_redirect' );\nfunction unlisted_jobs_redirect(){\n //check for 404\n if( is_404()){\n global $wp_query;\n //check that wp has figured out post_type from the request\n //and it's the type you're looking for\n if( isset($wp_query-&gt;query['post_type']) &amp;&amp; $wp_query-&gt;query['post_type'] == 'your-job-custom-post-type' ){\n // then redirect to yourdomain.com/jobs/\n wp_redirect( home_url( '/jobs/' ) );\n exit();\n }\n}\n</code></pre>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120857/" ]
Is it possible to password protect a PDF for visitors to our website (not users)? We have uploaded a PDF to our media and created a link to it on a page, but we would like to password protect just that PDF and not the whole page that contains the link to it.
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,742
<p>I am using WordPress MU Domain Mapping which works fine, but when I try to these any theme's customizer, I get this error when trying to save:</p> <p><strong>Cheatin’ uh? Sorry, you are not allowed to customize this site.</strong></p> <p>When I deactivate the plugin, the customizer works. I have 'Remote Login' and ' Redirect administration pages...' unchecked in the options as well.</p>
[ { "answer_id": 268947, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 0, "selected": false, "text": "<p>Try mapping without a plugin then. Since WP 4.5 this is possible. Just point the domain to the server with A record and change the site URL by editing the site.\n<a href=\"https://codex.wordpress.org/WordPress_Multisite_Domain_Mapping\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WordPress_Multisite_Domain_Mapping</a></p>\n\n<p>Or contact the plugin developer here and report the issue: <a href=\"https://wordpress.org/support/plugin/wordpress-mu-domain-mapping\" rel=\"nofollow noreferrer\">https://wordpress.org/support/plugin/wordpress-mu-domain-mapping</a></p>\n" }, { "answer_id": 268966, "author": "Keith Petrillo", "author_id": 101588, "author_profile": "https://wordpress.stackexchange.com/users/101588", "pm_score": 1, "selected": false, "text": "<p>After much trial and error, I found the cause to be a conflict with the WP Super Cache plugin, I had to disable the following from my wp-config.php file: </p>\n\n<pre><code>define( 'WPCACHEHOME', '/var/www/html/wp-content/plugins/wp-super-cache/' ); //Added by WP-Cache Manager\n</code></pre>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101588/" ]
I am using WordPress MU Domain Mapping which works fine, but when I try to these any theme's customizer, I get this error when trying to save: **Cheatin’ uh? Sorry, you are not allowed to customize this site.** When I deactivate the plugin, the customizer works. I have 'Remote Login' and ' Redirect administration pages...' unchecked in the options as well.
After much trial and error, I found the cause to be a conflict with the WP Super Cache plugin, I had to disable the following from my wp-config.php file: ``` define( 'WPCACHEHOME', '/var/www/html/wp-content/plugins/wp-super-cache/' ); //Added by WP-Cache Manager ```
268,750
<p>I want to link a external url as follows:</p> <pre><code>$url='www.example.com'; $output ='&lt;div class="button"&gt;&lt;a href="'.$url.'"&gt; View Profile&lt;/a&gt;&lt;/div&gt;'; </code></pre> <p>I run this wordpress web app at my localhost and base url is localhost/wordpress. When I echo <code>$output</code> it produce a link for view profile: <code>localhost/wordpress/www.example.com</code>. But it should be <code>www.facebook.com</code> </p> <p>What change shall i make?</p>
[ { "answer_id": 268752, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": 0, "selected": false, "text": "<p>You have a / thats not needed in the href this will add the link to the end of your current url hence localhost/wordpress/www.example.com </p>\n\n<pre><code> $url='www.example.com';\n $output ='&lt;div class=\"button\"&gt;&lt;a href=\"'.$url.'\"&gt; View Profile&lt;/a&gt;&lt;/div&gt;';\n echo $output; \n</code></pre>\n" }, { "answer_id": 268768, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>@Sam is close, but I think you need to do this:</p>\n\n<pre><code>$url = 'http://www.example.com';\n</code></pre>\n\n<p>Without the protocol in front, you get the wrong result. Change to </p>\n\n<pre><code>$url = 'https://www.example.com';\n</code></pre>\n\n<p>if you need an SSL link.</p>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120824/" ]
I want to link a external url as follows: ``` $url='www.example.com'; $output ='<div class="button"><a href="'.$url.'"> View Profile</a></div>'; ``` I run this wordpress web app at my localhost and base url is localhost/wordpress. When I echo `$output` it produce a link for view profile: `localhost/wordpress/www.example.com`. But it should be `www.facebook.com` What change shall i make?
@Sam is close, but I think you need to do this: ``` $url = 'http://www.example.com'; ``` Without the protocol in front, you get the wrong result. Change to ``` $url = 'https://www.example.com'; ``` if you need an SSL link.
268,755
<p>I'm trying to allow Subscriber roles to be allowed to delete their own posts using the following code:</p> <pre><code>&lt;?php if ($post-&gt;post_author == $current_user-&gt;ID) { ?&gt; &lt;div class="col-sm-12 box-delete" style="margin-top: 20px;"&gt; &lt;a class="option" onclick="return confirm('Are you sure you want to delete &lt;?php the_title();?&gt;')" href="&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;"&gt; &lt;i class="fa fa-trash"&gt;&lt;/i&gt; &lt;span class="option-text"&gt;Delete&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I'm using the User Role Editor, but it only works when I grant access to all the core roles, which gives subscriber access to backend, which I certainly don't want. Any other ideas or solutions to accomplish this?</p>
[ { "answer_id": 268756, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": -1, "selected": false, "text": "<p>You should be able to adapt the below to suit your needs, Just make sure to select the option for delete_posts for the subscriber role this will let them only delete their own posts.</p>\n\n<p>The following can be added to your single.php or php file that displays the post so that it gives a delete post button under the content.</p>\n\n<pre><code>// Check the user is author and has a role ID of subscriber as they don't have by default the delete post privilege but you can use the user role editor to allow subscribers to be able to delete there own posts and then add this code into your file where required on the post single page.\n\n\n if ( get_the_author_meta('ID') == get_current_user_id() &amp;&amp; current_user_can('subscriber') )\n {\n // owner of post and subscriber\n get_delete_post_link( $post-&gt;ID );\n }\n if ( get_the_author_meta('ID') != get_current_user_id() &amp;&amp; current_user_can('subscriber') )\n {\n // not the owner of post and subscriber\n echo 'Not your post';\n }\n else\n {\n // should be ok as not a subscriber and has delete privilages\n get_delete_post_link( $post-&gt;ID );\n }\n</code></pre>\n" }, { "answer_id": 268757, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>The capability required to delete posts is <code>delete_posts</code>. If you want them to be able to delete their own published posts, the capability is <code>delete_published_posts</code>.</p>\n\n<p>The capability required to view the administration panel is <code>read</code>. Subscribers have this capability natively, so unless you have removed it, subscribers can access the backend.</p>\n\n<p>I would write a simple plugin that upon activation adds the required capabilities to the subscriber role and upon deactivation removes those caps.</p>\n\n<p>Then in your theme, you can check for:</p>\n\n<pre><code>if( current_user_can( 'delete_posts' ) ) {\n //* Show delete link\n}\n</code></pre>\n\n<p>Because the subscriber role doesn't have the capability to <code>delete_others_posts</code>, the link will not show on posts that they didn't author, and they will not be able to delete posts that they did not publish.</p>\n\n<pre><code>/**\n * Plugin Name: WordPress StackExchange Question 268755\n * Description: Allow subscribers to delete their own posts\n **/\n\n//* On activation, add the capabilities to the subscriber role\nregister_activation_hook( __FILE__, 'wpse_268755_activation' );\nfunction wpse_268755_activation() {\n $subscriber = get_role( 'subscriber' );\n $subscriber-&gt;add_cap( 'delete_posts' );\n $subscriber-&gt;add_cap( 'delete_published_posts' );\n}\n\n//* On deactivation, remove the capabilities from the subscriber role\nregister_deactivation_hook( __FILE__, 'wpse_268755_deactivation' );\nfunction wpse_268755_deactivation() {\n $subscriber = get_role( 'subscriber' );\n $subscriber-&gt;remove_cap( 'delete_posts' );\n $subscriber-&gt;remove_cap( 'delete_published_posts' );\n}\n</code></pre>\n\n<p>Without giving the user and/or role the capability to delete a post, then they won't be able to do so, even if you show them a delete link. Likewise, a user or role can delete a post if they have the capability even if you don't show a delete link, it will just be more difficult for them.</p>\n" } ]
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54953/" ]
I'm trying to allow Subscriber roles to be allowed to delete their own posts using the following code: ``` <?php if ($post->post_author == $current_user->ID) { ?> <div class="col-sm-12 box-delete" style="margin-top: 20px;"> <a class="option" onclick="return confirm('Are you sure you want to delete <?php the_title();?>')" href="<?php echo get_delete_post_link( $post->ID ) ?>"> <i class="fa fa-trash"></i> <span class="option-text">Delete</span> </a> </div> <?php } ?> ``` I'm using the User Role Editor, but it only works when I grant access to all the core roles, which gives subscriber access to backend, which I certainly don't want. Any other ideas or solutions to accomplish this?
The capability required to delete posts is `delete_posts`. If you want them to be able to delete their own published posts, the capability is `delete_published_posts`. The capability required to view the administration panel is `read`. Subscribers have this capability natively, so unless you have removed it, subscribers can access the backend. I would write a simple plugin that upon activation adds the required capabilities to the subscriber role and upon deactivation removes those caps. Then in your theme, you can check for: ``` if( current_user_can( 'delete_posts' ) ) { //* Show delete link } ``` Because the subscriber role doesn't have the capability to `delete_others_posts`, the link will not show on posts that they didn't author, and they will not be able to delete posts that they did not publish. ``` /** * Plugin Name: WordPress StackExchange Question 268755 * Description: Allow subscribers to delete their own posts **/ //* On activation, add the capabilities to the subscriber role register_activation_hook( __FILE__, 'wpse_268755_activation' ); function wpse_268755_activation() { $subscriber = get_role( 'subscriber' ); $subscriber->add_cap( 'delete_posts' ); $subscriber->add_cap( 'delete_published_posts' ); } //* On deactivation, remove the capabilities from the subscriber role register_deactivation_hook( __FILE__, 'wpse_268755_deactivation' ); function wpse_268755_deactivation() { $subscriber = get_role( 'subscriber' ); $subscriber->remove_cap( 'delete_posts' ); $subscriber->remove_cap( 'delete_published_posts' ); } ``` Without giving the user and/or role the capability to delete a post, then they won't be able to do so, even if you show them a delete link. Likewise, a user or role can delete a post if they have the capability even if you don't show a delete link, it will just be more difficult for them.
268,763
<p>I'm designing a theme for a customer. We have only <strong>one post</strong> for each <strong>TvShow</strong>, And inside that post, We have all the <strong>Seasons</strong> and <strong>Episodes</strong>. (Using <code>meta_post</code>).</p> <p>Now, I have a <code>ul</code> for <strong>filtering seasons</strong> and one for <strong>filtering episodes</strong>, Like <em>Show 1st Season, Episode 3</em>. But that needs adding rules to posts (I don't want to use <strong>js</strong> for this). </p> <p>Something like: <code>www.example.com/tvshow-name/season-3/episode4/</code> </p> <p>Apparently we cannot add rule to posts using <code>add_rewrite_rule</code> (Believe me, I tried a lot!), And I don't know how can I add something to address of the post like pages. </p> <p>Something like: <code>add_rewrite_rules('/([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&amp;season=$matches[2]&amp;episode=$matches[3])</code> </p> <p><strong>The problem is</strong>: After going to <code>www.example.com/tvshow-name/season-3/episode4/</code>, It redirects back to <code>www.example.com/tvshow-name/</code>, And I get no season or episode!</p> <p>Is this possible, Or I have to create a page and create my single post template on that? (It's very ugly, But last hope)</p>
[ { "answer_id": 268770, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You're almost there. You need to add the <code>season</code> and <code>episode</code> query vars to the array of recognized vars. Note the small change to your regex as well-</p>\n\n<pre><code>function wpd_add_my_rule(){\n add_rewrite_rule(\n '^([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$',\n 'index.php?name=$matches[1]&amp;season=$matches[2]&amp;episode=$matches[3]',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_add_my_rule' );\n\nfunction wpd_add_query_vars( $query_vars ) {\n $query_vars[] = 'season';\n $query_vars[] = 'episode';\n return $query_vars;\n}\nadd_filter( 'query_vars', 'wpd_add_query_vars' );\n</code></pre>\n\n<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\"><code>get_query_var()</code></a> in the template to fetch the values.</p>\n" }, { "answer_id": 268788, "author": "Shantia", "author_id": 120875, "author_profile": "https://wordpress.stackexchange.com/users/120875", "pm_score": 0, "selected": false, "text": "<p>It's not pretty that I answer my own problem, But for others that maybe have the same issue:</p>\n\n<p>I just had to add <strong>post_type</strong> in my <code>add_rewrite_rule</code></p>\n\n<pre><code> add_rewrite_rule(\n '^([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$',\n 'index.php?post_type=tvseries&amp;name=$matches[1]&amp;season=$matches[2]&amp;episode=$matches[3]\"',\n 'top'\n);\n</code></pre>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268763", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120875/" ]
I'm designing a theme for a customer. We have only **one post** for each **TvShow**, And inside that post, We have all the **Seasons** and **Episodes**. (Using `meta_post`). Now, I have a `ul` for **filtering seasons** and one for **filtering episodes**, Like *Show 1st Season, Episode 3*. But that needs adding rules to posts (I don't want to use **js** for this). Something like: `www.example.com/tvshow-name/season-3/episode4/` Apparently we cannot add rule to posts using `add_rewrite_rule` (Believe me, I tried a lot!), And I don't know how can I add something to address of the post like pages. Something like: `add_rewrite_rules('/([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&season=$matches[2]&episode=$matches[3])` **The problem is**: After going to `www.example.com/tvshow-name/season-3/episode4/`, It redirects back to `www.example.com/tvshow-name/`, And I get no season or episode! Is this possible, Or I have to create a page and create my single post template on that? (It's very ugly, But last hope)
You're almost there. You need to add the `season` and `episode` query vars to the array of recognized vars. Note the small change to your regex as well- ``` function wpd_add_my_rule(){ add_rewrite_rule( '^([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&season=$matches[2]&episode=$matches[3]', 'top' ); } add_action( 'init', 'wpd_add_my_rule' ); function wpd_add_query_vars( $query_vars ) { $query_vars[] = 'season'; $query_vars[] = 'episode'; return $query_vars; } add_filter( 'query_vars', 'wpd_add_query_vars' ); ``` You can use [`get_query_var()`](https://codex.wordpress.org/Function_Reference/get_query_var) in the template to fetch the values.
268,774
<p>So in WordPress 4.6 they added the localization to the jQuery datepicker to be automatic. I am posting here first because I am not sure if this is actually a bug with WP or if I am doing something wrong.</p> <p>If I set my language in the settings to French then the datepicker correctly gets localized and shows the months etc in French. However, for a demo page I want to show this off and don't want to have the entire site set to French but instead just a single page. Here is what I am using:</p> <pre><code>function change_language( $locale ) { if ( is_page( 156 ) ) { return 'fr_FR'; } return $locale; } add_filter( 'locale', 'change_language' ); </code></pre> <p>It is correctly changing the locale of the page but is not actually loading the datepicker localization based on that locale. Here is a screenshot:</p> <p><a href="https://i.stack.imgur.com/DFjwI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DFjwI.png" alt="enter image description here"></a></p> <p>Is there some kind of timing issue here perhaps? Maybe I am using the wrong filter? Or is this possibly a WP bug?</p> <p>Thanks for any help!</p>
[ { "answer_id": 269354, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>Create <code>page-156.php</code> template with its content matching the page you use right now. Save it in your theme, where your standard page.php is located.</p>\n\n<blockquote>\n <p>Download <code>datepicker-fr.js</code> from\n <a href=\"https://github.com/jquery/jquery-ui/tree/master/ui/i18n\" rel=\"nofollow noreferrer\">https://github.com/jquery/jquery-ui/tree/master/ui/i18n</a> and store it\n in root of your site.</p>\n</blockquote>\n\n<p>Replace inline script for <em>datepicker</em> widget with: </p>\n\n<pre><code>&lt;script src=\"/datepicker-fr.js\"&gt;&lt;/script&gt;\n&lt;script&gt;\n $( function() {\n $( \"#datepicker\" ).datepicker( $.datepicker.regional[ \"fr\" ] );\n } );\n&lt;/script&gt;\n</code></pre>\n\n<p>That's all needed, for your demo page, to display <em>datepicker</em> in French.</p>\n" }, { "answer_id": 269355, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>I was able to successfully change the datepicker's strings to a different locale for a single page using the <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a> function introduced in <a href=\"https://make.wordpress.org/core/2016/11/07/user-admin-languages-and-locale-switching-in-4-7/\" rel=\"nofollow noreferrer\">WordPress v4.7</a>.</p>\n\n<p><code>switch_to_locale()</code> will modify the global <code>$wp_locale</code> variable which is used by <code>wp_localize_jquery_ui_datepicker()</code>. Changing the locale with the <code>locale</code> filter alone does not overwrite <code>$wp_locale</code>.</p>\n\n<pre><code>/**\n * Use switch_to_locale() on a special page.\n * This needs to be done early.\n */\nadd_action( 'pre_get_posts', 'wpse_change_language' );\nfunction wpse_change_language( $query ) {\n if ( $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_page( 156 ) ) {\n // This will change the global $wp_locale which\n // is used by wp_localize_jquery_ui_datepicker() for translations.\n switch_to_locale( 'fr_FR' );\n } \n}\n</code></pre>\n\n<p>Enqueue datepicker styles and scripts.</p>\n\n<pre><code>/**\n * Load jQuery datepicker scripts and styles.\n */\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueue_datepicker' );\nfunction wpse_enqueue_datepicker() {\n wp_enqueue_script( 'jquery-ui-datepicker' );\n\n // Using code.jquery.com for simplicity. Normally I'd use a local file.\n wp_register_style(\n 'jquery-ui',\n 'https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css'\n );\n wp_enqueue_style( 'jquery-ui' );\n\n // A simple datepicker initialization script.\n wp_enqueue_script(\n 'wpse-datepicker',\n plugin_dir_url( __FILE__ ) . '/wpse-datepicker.js',\n [ 'jquery-ui-datepicker' ],\n false,\n true\n );\n}\n</code></pre>\n\n<p><strong>wpse-datepicker.js</strong></p>\n\n<pre><code>/**\n * Attach a datepicker to our markup.\n */\njQuery( document ).ready(function( $ ) {\n $( \"#datepicker\" ).datepicker();\n});\n</code></pre>\n\n<p><strong>Shortcode</strong> (for demo purposes)</p>\n\n<pre><code>/**\n * A simple shortcode used for adding the markup for\n * the datepicker.\n */\nadd_shortcode( 'wpse_datepicker', 'wpse_datepicker' );\nfunction wpse_datepicker() {\n // Start buffering output.\n ob_start(); \n\n // Add some debugging info:\n echo '&lt;p&gt;The locale is: ' . get_locale() . '&lt;/p&gt;';\n ?&gt;\n\n &lt;div id=\"datepicker\"&gt;&lt;/div&gt;\n\n &lt;?php\n // Return output generated up to this point.\n return ob_get_clean();\n}\n</code></pre>\n\n<p><strong>Content of page with ID 156</strong></p>\n\n<blockquote>\n<pre><code>Testing the datepicker:\n\n[wpse_datepicker]\n\nTest complete!\n</code></pre>\n</blockquote>\n\n<p>Also note that it is necessary to have the language files installed for whatever locale is being used. They can be automatically installed by selecting the appropriate language in the admin area under <em>Settings > General > Site Language</em>.</p>\n" }, { "answer_id": 269381, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 1, "selected": false, "text": "<p>WordPress loads default translated strings before loading theme <code>functions.php</code> file (<a href=\"https://github.com/WordPress/WordPress/blob/master/wp-settings.php#L394\" rel=\"nofollow noreferrer\">see <code>wp-settings.php#L394</code></a>). Then, the <code>locale</code> filter doesn't affect the jQuery UI datepicker localization anymore.</p>\n\n<p>There're some improvements I want to add to the answers of @DaveRomsey and @FrankPWalentynowicz:</p>\n\n<p><strong>1. Using <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a></strong>:</p>\n\n<p>This method works for a specific locale if that locale exists in available languages of the global <code>$wp_locale_switcher</code> (see <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-locale-switcher.php#L78\" rel=\"nofollow noreferrer\"><code>WP_Locale_Switcher#L78</code></a>).</p>\n\n<p>Since <code>WP_Locale_Switcher</code> uses <a href=\"https://developer.wordpress.org/reference/functions/get_available_languages/\" rel=\"nofollow noreferrer\"><code>get_available_languages()</code></a> to retrieve available languages, if <code>fr_FR</code> haven't been downloaded before, we have to download it into <code>WP_LANG_DIR</code> before switching to it:</p>\n\n<pre><code>function wpse268774_change_language($query) {\n if ( $query-&gt;is_page(156) &amp;&amp; $query-&gt;is_main_query() ) {\n if (!function_exists('wp_download_language_pack')) {\n require ABSPATH . 'wp-admin/includes/file.php';\n require ABSPATH . 'wp-admin/includes/translation-install.php';\n $downloaded = wp_download_language_pack('fr_FR');\n if ($downloaded) {\n switch_to_locale('fr_FR');\n } else {\n // Maybe do something...\n }\n }\n }\n}\nadd_action( 'pre_get_posts', 'wpse268774_change_language' );\n</code></pre>\n\n<p><strong>Pros</strong>:</p>\n\n<ul>\n<li>You can use standard translations for entire page without having to translate anything manually.</li>\n</ul>\n\n<p><strong>Cons</strong>:</p>\n\n<ul>\n<li>A heavy performance hit because we have to download language pack and reload entire translated strings.</li>\n</ul>\n\n<p>I recommend you to use <code>pre_get_posts</code> hook with <code>$query-&gt;{method}</code>. <code>is_page()</code> alone may not works. You should not use page ID because it may be changed while importing.</p>\n\n<p><strong>2. Using <a href=\"https://api.jqueryui.com/1.12/datepicker/#utility-setDefaults\" rel=\"nofollow noreferrer\"><code>$.datepicker.setDefaults( options )</code></a></strong>:</p>\n\n<p>WordPress doesn't use languages from <a href=\"https://github.com/jquery/jquery-ui/tree/master/ui/i18n\" rel=\"nofollow noreferrer\">jQuery UI Project</a> so the <code>$.datepicker.setDefaults(jQuery.datepicker.regional[\"fr\"])</code> method doesn't work. You must localize default options manually.</p>\n\n<p>Let's checkout <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_jquery_ui_datepicker/\" rel=\"nofollow noreferrer\"><code>wp_localize_jquery_ui_datepicker()</code></a> function added to the <code>wp_enqueue_scripts</code> hook (see <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L435\" rel=\"nofollow noreferrer\"><code>default-filters.php#L435</code></a>). Now, we have to do:</p>\n\n<pre><code>remove_action('wp_enqueue_scripts', 'wp_localize_jquery_ui_datepicker', 1000);\n\nfunction wpse268774_localize_jquery_ui_datepciker() {\n global $wp_locale;\n\n if ( !is_page(156) || !wp_script_is( 'jquery-ui-datepicker', 'enqueued' ) ) {\n return;\n }\n\n // Convert the PHP date format into jQuery UI's format.\n $datepicker_date_format = str_replace(\n array(\n 'd', 'j', 'l', 'z', // Day.\n 'F', 'M', 'n', 'm', // Month.\n 'Y', 'y' // Year.\n ),\n array(\n 'dd', 'd', 'DD', 'o',\n 'MM', 'M', 'm', 'mm',\n 'yy', 'y'\n ),\n get_option( 'date_format' )\n );\n\n // Got this string by switching to fr_FR.\n $datepicker_defaults = '{\"closeText\":\"Fermer\",\"currentText\":\"Aujourd\\u2019hui\",\"monthNames\":[\"janvier\",\"f\\u00e9vrier\",\"mars\",\"avril\",\"mai\",\"juin\",\"juillet\",\"ao\\u00fbt\",\"septembre\",\"octobre\",\"novembre\",\"d\\u00e9cembre\"],\"monthNamesShort\":[\"Jan\",\"F\\u00e9v\",\"Mar\",\"Avr\",\"Mai\",\"Juin\",\"Juil\",\"Ao\\u00fbt\",\"Sep\",\"Oct\",\"Nov\",\"D\\u00e9c\"],\"nextText\":\"Suivant\",\"prevText\":\"Pr\\u00e9c\\u00e9dent\",\"dayNames\":[\"dimanche\",\"lundi\",\"mardi\",\"mercredi\",\"jeudi\",\"vendredi\",\"samedi\"],\"dayNamesShort\":[\"dim\",\"lun\",\"mar\",\"mer\",\"jeu\",\"ven\",\"sam\"],\"dayNamesMin\":[\"D\",\"L\",\"M\",\"M\",\"J\",\"V\",\"S\"],\"dateFormat\":\"MM d, yy\",\"firstDay\":1,\"isRTL\":false}';\n\n wp_add_inline_script( 'jquery-ui-datepicker', \"jQuery(document).ready(function(jQuery){jQuery.datepicker.setDefaults({$datepicker_defaults});});\" );\n}\nadd_action('wp_enqueue_scripts', 'wpse268774_localize_jquery_ui_datepciker', 10, 0);\n</code></pre>\n\n<p><strong>Pros</strong>:</p>\n\n<ul>\n<li>No performance hit</li>\n</ul>\n\n<p><strong>Cons</strong>:</p>\n\n<ul>\n<li>Only localize jQuery UI Datepicker options. Other strings in your page won't be translated.</li>\n<li>You may have to translate the jQuery UI Datepicker options manually.</li>\n</ul>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48502/" ]
So in WordPress 4.6 they added the localization to the jQuery datepicker to be automatic. I am posting here first because I am not sure if this is actually a bug with WP or if I am doing something wrong. If I set my language in the settings to French then the datepicker correctly gets localized and shows the months etc in French. However, for a demo page I want to show this off and don't want to have the entire site set to French but instead just a single page. Here is what I am using: ``` function change_language( $locale ) { if ( is_page( 156 ) ) { return 'fr_FR'; } return $locale; } add_filter( 'locale', 'change_language' ); ``` It is correctly changing the locale of the page but is not actually loading the datepicker localization based on that locale. Here is a screenshot: [![enter image description here](https://i.stack.imgur.com/DFjwI.png)](https://i.stack.imgur.com/DFjwI.png) Is there some kind of timing issue here perhaps? Maybe I am using the wrong filter? Or is this possibly a WP bug? Thanks for any help!
I was able to successfully change the datepicker's strings to a different locale for a single page using the [`switch_to_locale()`](https://developer.wordpress.org/reference/functions/switch_to_locale/) function introduced in [WordPress v4.7](https://make.wordpress.org/core/2016/11/07/user-admin-languages-and-locale-switching-in-4-7/). `switch_to_locale()` will modify the global `$wp_locale` variable which is used by `wp_localize_jquery_ui_datepicker()`. Changing the locale with the `locale` filter alone does not overwrite `$wp_locale`. ``` /** * Use switch_to_locale() on a special page. * This needs to be done early. */ add_action( 'pre_get_posts', 'wpse_change_language' ); function wpse_change_language( $query ) { if ( $query->is_main_query() && $query->is_page( 156 ) ) { // This will change the global $wp_locale which // is used by wp_localize_jquery_ui_datepicker() for translations. switch_to_locale( 'fr_FR' ); } } ``` Enqueue datepicker styles and scripts. ``` /** * Load jQuery datepicker scripts and styles. */ add_action( 'wp_enqueue_scripts', 'wpse_enqueue_datepicker' ); function wpse_enqueue_datepicker() { wp_enqueue_script( 'jquery-ui-datepicker' ); // Using code.jquery.com for simplicity. Normally I'd use a local file. wp_register_style( 'jquery-ui', 'https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css' ); wp_enqueue_style( 'jquery-ui' ); // A simple datepicker initialization script. wp_enqueue_script( 'wpse-datepicker', plugin_dir_url( __FILE__ ) . '/wpse-datepicker.js', [ 'jquery-ui-datepicker' ], false, true ); } ``` **wpse-datepicker.js** ``` /** * Attach a datepicker to our markup. */ jQuery( document ).ready(function( $ ) { $( "#datepicker" ).datepicker(); }); ``` **Shortcode** (for demo purposes) ``` /** * A simple shortcode used for adding the markup for * the datepicker. */ add_shortcode( 'wpse_datepicker', 'wpse_datepicker' ); function wpse_datepicker() { // Start buffering output. ob_start(); // Add some debugging info: echo '<p>The locale is: ' . get_locale() . '</p>'; ?> <div id="datepicker"></div> <?php // Return output generated up to this point. return ob_get_clean(); } ``` **Content of page with ID 156** > > > ``` > Testing the datepicker: > > [wpse_datepicker] > > Test complete! > > ``` > > Also note that it is necessary to have the language files installed for whatever locale is being used. They can be automatically installed by selecting the appropriate language in the admin area under *Settings > General > Site Language*.
268,809
<p>I have a custom user role : Photograph.</p> <p>This role should not be able to log into the back-office, but have to be able to delete their own posts from the front-end.</p> <p>I am using this code to block all non-admin user from connecting to the backoffice with this (function.php) :</p> <pre><code>add_action( 'init', 'blockusers_init' ); function blockusers_init() { if ( is_admin() &amp;&amp; ! current_user_can( 'administrator' ) &amp;&amp; ! ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX ) ) { wp_redirect( home_url() ); exit; } } </code></pre> <p>And I am using this code to delete posts (portfolio.php) :</p> <pre><code>&lt;a href="&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;"&gt;Delete post&lt;/a&gt; </code></pre> <p>I have tried a few other options but have never been able to only allow to photographers to delete their posts (or globally posts because they only can see theirs anyway)</p> <p>Thank you !</p>
[ { "answer_id": 269327, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>Assuming you're talking about a custom user <strong>role</strong> named \"<em>photographer</em>\", I believe something like this should add the <code>delete_posts</code> capability to that role.</p>\n\n<pre><code>function add_delete_cap_to_photog_role() {\n $role = get_role( 'photographer' );\n\n $role-&gt;add_cap( 'delete_posts' );\n}\nadd_action( 'admin_init', 'add_delete_cap_to_photog_role');\n</code></pre>\n\n<hr>\n\n<p>After adding the caps to the role, to solve the rest you could either </p>\n\n<ol>\n<li>keep <code>blockusers_init</code> and ditch <code>get_delete_post_link</code> for an ajax delete.</li>\n<li>ditch the <code>blockusers_init</code> function and do a conditional redirect.</li>\n</ol>\n\n<p>I'll give some ideas on each. I prefer ditching <code>get_delete_post_link</code> in this instance.</p>\n\n<p><strong>Several steps below, so be aware the code is provided as a guide only. Rewrite and rename things as needed.</strong> </p>\n\n<hr>\n\n<h2>Ditch <code>get_delete_post_link</code> aka AJAX Delete</h2>\n\n<p>replace <code>get_delete_post_link</code> line with something like this:</p>\n\n<pre><code>&lt;?php if( current_user_can( 'delete_post' ) ) : ?&gt;\n &lt;a href=\"#\" data-id=\"&lt;?php the_ID() ?&gt;\" data-nonce=\"&lt;?php echo wp_create_nonce('ajax_delete_post_nonce') ?&gt;\" class=\"delete-post\"&gt;delete&lt;/a&gt;\n&lt;?php endif ?&gt;\n</code></pre>\n\n<p><strong>Enqueue some JS</strong> </p>\n\n<p>in file: <em>functions.php</em></p>\n\n<pre><code>function delete_post_ajax() {\n wp_enqueue_script( 'delete_ajax', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true );\n wp_localize_script( 'delete_ajax', 'TheAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) );\n}\n\nadd_action( 'wp_enqueue_scripts', 'delete_post_ajax' );\n</code></pre>\n\n<p><strong>onClick to pass data to delete method</strong></p>\n\n<p>in file: /js/my_script.js</p>\n\n<pre><code>jQuery( document ).ready( function($) {\n $(document).on( 'click', '.delete-post', function() {\n var id = $(this).data('id');\n var nonce = $(this).data('nonce');\n var post = $(this).parents('.post:first');\n $.ajax({\n type: 'post',\n url: TheAjax.ajaxurl,\n data: {\n action: 'wpse_ajax_delete_post',\n nonce: nonce,\n id: id\n },\n success: function( result ) {\n if( result == 'success' ) {\n post.fadeOut( function(){\n post.remove();\n });\n }\n }\n })\n return false;\n })\n})\n</code></pre>\n\n<p><strong>the delete method</strong></p>\n\n<p>in file: functions.php\n(the hook we need is just \"<code>wp_ajax</code>\" prepending the name of the <code>action</code> in js file)</p>\n\n<pre><code>add_action( 'wp_ajax_wpse_ajax_delete_post', 'wpse_ajax_delete_post_func' );\nfunction wpse_ajax_delete_post_func(){\n\n $permission = check_ajax_referer( 'ajax_delete_post_nonce', 'nonce', false );\n if( $permission == false ) {\n echo 'error';\n }\n else {\n wp_delete_post( $_REQUEST['id'] );\n echo 'success';\n }\n\n die();\n\n}\n</code></pre>\n\n<p>To do the above by passing uri params:</p>\n\n<p>Change where we swapped out <code>get_delete_posts_link</code> for this:</p>\n\n<pre><code>&lt;?php if( current_user_can( 'delete_post' ) ) : ?&gt;\n &lt;?php $nonce = wp_create_nonce('ajax_delete_post_nonce') ?&gt;\n &lt;a href=\"&lt;?php echo admin_url( 'admin-ajax.php?action=wpse_ajax_delete_post&amp;id=' . get_the_ID() . '&amp;nonce=' . $nonce ) ?&gt;\" data-id=\"&lt;?php the_ID() ?&gt;\" data-nonce=\"&lt;?php echo $nonce ?&gt;\" class=\"delete-post\"&gt;delete&lt;/a&gt;\n&lt;?php endif ?&gt;\n</code></pre>\n\n<p>See this for <a href=\"http://www.vandelaydesign.com/delete-a-wordpress-post-using-ajax/\" rel=\"nofollow noreferrer\">a more involved walkthrough explaining each step</a> </p>\n\n<hr>\n\n<h2>Ditch <code>blockusers_init</code> (aka conditional redirect)</h2>\n\n<p>This sets a redirect on wp-admin if user does not have <code>manage_options</code> cap, which is an administrator role. But first it pseudo-hides things and adds a message to user with some css:</p>\n\n<p><strong>The CSS bit</strong></p>\n\n<p>in file: <em>functions.php</em></p>\n\n<pre><code>add_action('admin_head', 'hide_admin_via_css');\nfunction hide_admin_via_css() {\n if (!current_user_can( 'manage_options' )) {\n echo '&lt;style&gt;body * {visibility:hidden !important;} body:before {content:\"Give it a second...\";}\n';\n }\n}\n</code></pre>\n\n<p><strong>Enqueueing the JS file</strong></p>\n\n<p>in file: <em>functions.php</em></p>\n\n<pre><code>function my_enqueue( $hook ) {\n if (!current_user_can( 'manage_options' )) {\n wp_enqueue_script( 'my_custom_script', get_template_directory_uri() '/js/block-admin.js' );\n }\n}\nadd_action('admin_enqueue_scripts', 'my_enqueue');\n</code></pre>\n\n<p><strong>Set the JS to just immediately redirect</strong></p>\n\n<p>file: <em>theme_root/js/block-admin.js</em></p>\n\n<pre><code>window.location.href = \"/\";\n</code></pre>\n\n<p><strong>OR a timed redirect</strong></p>\n\n<pre><code>setTimeout(function () {\n window.location.href = \"/\";\n}, 2000);\n</code></pre>\n\n<p>This approach <a href=\"https://clicknathan.com/web-design/allow-subscribers-to-delete-posts-from-the-front-end-while-still-blocking-the-admin-area/\" rel=\"nofollow noreferrer\">came from clicknathan, and he offers more details here.</a></p>\n" }, { "answer_id": 269335, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 1, "selected": false, "text": "<p>hwl's answer is correct, but I'm going to add a check if the current user is the author of the post.</p>\n\n<pre><code>&lt;?php\n$current_user = wp_get_current_user();\nif ( $current_user-&gt;ID == $post-&gt;post_author ) { ?&gt;\n &lt;a href=\"&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;\"&gt;Delete post&lt;/a&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p><strike>Since you might be adding in the ability to <code>'delete_posts</code>', which could delete any post, this might be a safeguard.</strike> &lt; That wasn't right.</p>\n\n<p>That way the link only shows up on posts they can delete, their own.</p>\n" }, { "answer_id": 269340, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>There are three requirements in your question:</p>\n\n<ol>\n<li>The role should not be able to log into the backend</li>\n<li>The role should be able to delete their own posts</li>\n<li>An implied requirement is that they should be able to delete published posts </li>\n</ol>\n\n<p>Presumably, you have a method in place where the user can post and publish their posts without access to the backend. If so, then you can manipulate the role by:</p>\n\n<ol>\n<li>Removing the <code>read</code> capability</li>\n<li>Adding the <code>delete_posts</code> capability</li>\n<li>Add the <code>delete_published_posts</code> capabilty</li>\n</ol>\n\n<p>Since the role doesn't have <code>delete_others_posts</code>, then they won't be able to delete other users posts - even if they're published.</p>\n\n<p>Role capabilities are stored in the database, so you should add and remove them on plugin or theme activation. Here's a sample plugin that adds the required capabilities on activation and removes them on deactivation.</p>\n\n<pre><code>/**\n * Plugin Name: WordPress StackExchange Question 268755\n * Description: Allow subscribers to delete their own posts\n **/\n\n//* On activation, add the capabilities to the subscriber role\nregister_activation_hook( __FILE__, 'wpse_268755_activation' );\nfunction wpse_268755_activation() {\n $photograph = get_role( 'photograph' );\n $photograph-&gt;remove_cap( 'read' );\n $photograph-&gt;add_cap( 'delete_posts' );\n $photograph-&gt;add_cap( 'delete_published_posts' );\n}\n\n//* On deactivation, remove the capabilities from the subscriber role\nregister_deactivation_hook( __FILE__, 'wpse_268755_deactivation' );\nfunction wpse_268755_deactivation() {\n $photograph = get_role( 'photograph' );\n $photograph-&gt;remove_cap( 'delete_posts' );\n $photograph-&gt;remove_cap( 'delete_published_posts' );\n}\n</code></pre>\n\n<p>You then need a way to actually delete the post. If the user had access to the back-end you could use <code>get_delete_post_link</code>.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;\"&gt;Delete post&lt;/a&gt;\n</code></pre>\n\n<p>So what you need to do is write some javascript that when that link is clicked it prevents the default behavior and sends an <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">AJAX</a> request to delete the post.</p>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268809", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97852/" ]
I have a custom user role : Photograph. This role should not be able to log into the back-office, but have to be able to delete their own posts from the front-end. I am using this code to block all non-admin user from connecting to the backoffice with this (function.php) : ``` add_action( 'init', 'blockusers_init' ); function blockusers_init() { if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { wp_redirect( home_url() ); exit; } } ``` And I am using this code to delete posts (portfolio.php) : ``` <a href="<?php echo get_delete_post_link( $post->ID ) ?>">Delete post</a> ``` I have tried a few other options but have never been able to only allow to photographers to delete their posts (or globally posts because they only can see theirs anyway) Thank you !
Assuming you're talking about a custom user **role** named "*photographer*", I believe something like this should add the `delete_posts` capability to that role. ``` function add_delete_cap_to_photog_role() { $role = get_role( 'photographer' ); $role->add_cap( 'delete_posts' ); } add_action( 'admin_init', 'add_delete_cap_to_photog_role'); ``` --- After adding the caps to the role, to solve the rest you could either 1. keep `blockusers_init` and ditch `get_delete_post_link` for an ajax delete. 2. ditch the `blockusers_init` function and do a conditional redirect. I'll give some ideas on each. I prefer ditching `get_delete_post_link` in this instance. **Several steps below, so be aware the code is provided as a guide only. Rewrite and rename things as needed.** --- Ditch `get_delete_post_link` aka AJAX Delete -------------------------------------------- replace `get_delete_post_link` line with something like this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <a href="#" data-id="<?php the_ID() ?>" data-nonce="<?php echo wp_create_nonce('ajax_delete_post_nonce') ?>" class="delete-post">delete</a> <?php endif ?> ``` **Enqueue some JS** in file: *functions.php* ``` function delete_post_ajax() { wp_enqueue_script( 'delete_ajax', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'delete_ajax', 'TheAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'delete_post_ajax' ); ``` **onClick to pass data to delete method** in file: /js/my\_script.js ``` jQuery( document ).ready( function($) { $(document).on( 'click', '.delete-post', function() { var id = $(this).data('id'); var nonce = $(this).data('nonce'); var post = $(this).parents('.post:first'); $.ajax({ type: 'post', url: TheAjax.ajaxurl, data: { action: 'wpse_ajax_delete_post', nonce: nonce, id: id }, success: function( result ) { if( result == 'success' ) { post.fadeOut( function(){ post.remove(); }); } } }) return false; }) }) ``` **the delete method** in file: functions.php (the hook we need is just "`wp_ajax`" prepending the name of the `action` in js file) ``` add_action( 'wp_ajax_wpse_ajax_delete_post', 'wpse_ajax_delete_post_func' ); function wpse_ajax_delete_post_func(){ $permission = check_ajax_referer( 'ajax_delete_post_nonce', 'nonce', false ); if( $permission == false ) { echo 'error'; } else { wp_delete_post( $_REQUEST['id'] ); echo 'success'; } die(); } ``` To do the above by passing uri params: Change where we swapped out `get_delete_posts_link` for this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <?php $nonce = wp_create_nonce('ajax_delete_post_nonce') ?> <a href="<?php echo admin_url( 'admin-ajax.php?action=wpse_ajax_delete_post&id=' . get_the_ID() . '&nonce=' . $nonce ) ?>" data-id="<?php the_ID() ?>" data-nonce="<?php echo $nonce ?>" class="delete-post">delete</a> <?php endif ?> ``` See this for [a more involved walkthrough explaining each step](http://www.vandelaydesign.com/delete-a-wordpress-post-using-ajax/) --- Ditch `blockusers_init` (aka conditional redirect) -------------------------------------------------- This sets a redirect on wp-admin if user does not have `manage_options` cap, which is an administrator role. But first it pseudo-hides things and adds a message to user with some css: **The CSS bit** in file: *functions.php* ``` add_action('admin_head', 'hide_admin_via_css'); function hide_admin_via_css() { if (!current_user_can( 'manage_options' )) { echo '<style>body * {visibility:hidden !important;} body:before {content:"Give it a second...";} '; } } ``` **Enqueueing the JS file** in file: *functions.php* ``` function my_enqueue( $hook ) { if (!current_user_can( 'manage_options' )) { wp_enqueue_script( 'my_custom_script', get_template_directory_uri() '/js/block-admin.js' ); } } add_action('admin_enqueue_scripts', 'my_enqueue'); ``` **Set the JS to just immediately redirect** file: *theme\_root/js/block-admin.js* ``` window.location.href = "/"; ``` **OR a timed redirect** ``` setTimeout(function () { window.location.href = "/"; }, 2000); ``` This approach [came from clicknathan, and he offers more details here.](https://clicknathan.com/web-design/allow-subscribers-to-delete-posts-from-the-front-end-while-still-blocking-the-admin-area/)
268,827
<p>I want to merge two queries together and remove duplicate. I got it working individually. Now I got it working together but the results are not mixed and the duplicates are not removed. So I got the first queries result and then the second query result...</p> <pre><code> $fav_author_list = get_user_option( 'favorite-authors', fav_authors_get_user_id() ); $fav_categorie_list = get_user_option( 'favorite-categories', fav_categories_get_user_id() ); $rm_blog_args = array( 'posts_per_page' =&gt; -1, 'author__in'=&gt; $fav_author_list, 'post_type' =&gt; 'post' ); $rm_blog = new WP_Query($rm_blog_args); $fb_args = array( 'posts_per_page' =&gt; -1, 'category__in'=&gt; $fav_categorie_list, 'post_type' =&gt; 'post' ); $fb = new WP_Query($fb_args); // Final Query $final_query = new WP_Query(); // Merging queries $final_query-&gt;posts = array_merge( $rm_blog-&gt;posts, $fb-&gt;posts); // Recount echo $final_query-&gt;post_count = count( $final_query-&gt;posts ); // Remove duplicate post IDs $post_ids = array(); foreach( $final_query-&gt;posts as $item ) { $post_ids[] = $item-&gt;ID; } $unique_posts = array_unique($post_ids); if($final_query-&gt;have_posts()) : while ( $final_query-&gt;have_posts() ) : $final_query-&gt;the_post(); </code></pre>
[ { "answer_id": 269327, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>Assuming you're talking about a custom user <strong>role</strong> named \"<em>photographer</em>\", I believe something like this should add the <code>delete_posts</code> capability to that role.</p>\n\n<pre><code>function add_delete_cap_to_photog_role() {\n $role = get_role( 'photographer' );\n\n $role-&gt;add_cap( 'delete_posts' );\n}\nadd_action( 'admin_init', 'add_delete_cap_to_photog_role');\n</code></pre>\n\n<hr>\n\n<p>After adding the caps to the role, to solve the rest you could either </p>\n\n<ol>\n<li>keep <code>blockusers_init</code> and ditch <code>get_delete_post_link</code> for an ajax delete.</li>\n<li>ditch the <code>blockusers_init</code> function and do a conditional redirect.</li>\n</ol>\n\n<p>I'll give some ideas on each. I prefer ditching <code>get_delete_post_link</code> in this instance.</p>\n\n<p><strong>Several steps below, so be aware the code is provided as a guide only. Rewrite and rename things as needed.</strong> </p>\n\n<hr>\n\n<h2>Ditch <code>get_delete_post_link</code> aka AJAX Delete</h2>\n\n<p>replace <code>get_delete_post_link</code> line with something like this:</p>\n\n<pre><code>&lt;?php if( current_user_can( 'delete_post' ) ) : ?&gt;\n &lt;a href=\"#\" data-id=\"&lt;?php the_ID() ?&gt;\" data-nonce=\"&lt;?php echo wp_create_nonce('ajax_delete_post_nonce') ?&gt;\" class=\"delete-post\"&gt;delete&lt;/a&gt;\n&lt;?php endif ?&gt;\n</code></pre>\n\n<p><strong>Enqueue some JS</strong> </p>\n\n<p>in file: <em>functions.php</em></p>\n\n<pre><code>function delete_post_ajax() {\n wp_enqueue_script( 'delete_ajax', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true );\n wp_localize_script( 'delete_ajax', 'TheAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) );\n}\n\nadd_action( 'wp_enqueue_scripts', 'delete_post_ajax' );\n</code></pre>\n\n<p><strong>onClick to pass data to delete method</strong></p>\n\n<p>in file: /js/my_script.js</p>\n\n<pre><code>jQuery( document ).ready( function($) {\n $(document).on( 'click', '.delete-post', function() {\n var id = $(this).data('id');\n var nonce = $(this).data('nonce');\n var post = $(this).parents('.post:first');\n $.ajax({\n type: 'post',\n url: TheAjax.ajaxurl,\n data: {\n action: 'wpse_ajax_delete_post',\n nonce: nonce,\n id: id\n },\n success: function( result ) {\n if( result == 'success' ) {\n post.fadeOut( function(){\n post.remove();\n });\n }\n }\n })\n return false;\n })\n})\n</code></pre>\n\n<p><strong>the delete method</strong></p>\n\n<p>in file: functions.php\n(the hook we need is just \"<code>wp_ajax</code>\" prepending the name of the <code>action</code> in js file)</p>\n\n<pre><code>add_action( 'wp_ajax_wpse_ajax_delete_post', 'wpse_ajax_delete_post_func' );\nfunction wpse_ajax_delete_post_func(){\n\n $permission = check_ajax_referer( 'ajax_delete_post_nonce', 'nonce', false );\n if( $permission == false ) {\n echo 'error';\n }\n else {\n wp_delete_post( $_REQUEST['id'] );\n echo 'success';\n }\n\n die();\n\n}\n</code></pre>\n\n<p>To do the above by passing uri params:</p>\n\n<p>Change where we swapped out <code>get_delete_posts_link</code> for this:</p>\n\n<pre><code>&lt;?php if( current_user_can( 'delete_post' ) ) : ?&gt;\n &lt;?php $nonce = wp_create_nonce('ajax_delete_post_nonce') ?&gt;\n &lt;a href=\"&lt;?php echo admin_url( 'admin-ajax.php?action=wpse_ajax_delete_post&amp;id=' . get_the_ID() . '&amp;nonce=' . $nonce ) ?&gt;\" data-id=\"&lt;?php the_ID() ?&gt;\" data-nonce=\"&lt;?php echo $nonce ?&gt;\" class=\"delete-post\"&gt;delete&lt;/a&gt;\n&lt;?php endif ?&gt;\n</code></pre>\n\n<p>See this for <a href=\"http://www.vandelaydesign.com/delete-a-wordpress-post-using-ajax/\" rel=\"nofollow noreferrer\">a more involved walkthrough explaining each step</a> </p>\n\n<hr>\n\n<h2>Ditch <code>blockusers_init</code> (aka conditional redirect)</h2>\n\n<p>This sets a redirect on wp-admin if user does not have <code>manage_options</code> cap, which is an administrator role. But first it pseudo-hides things and adds a message to user with some css:</p>\n\n<p><strong>The CSS bit</strong></p>\n\n<p>in file: <em>functions.php</em></p>\n\n<pre><code>add_action('admin_head', 'hide_admin_via_css');\nfunction hide_admin_via_css() {\n if (!current_user_can( 'manage_options' )) {\n echo '&lt;style&gt;body * {visibility:hidden !important;} body:before {content:\"Give it a second...\";}\n';\n }\n}\n</code></pre>\n\n<p><strong>Enqueueing the JS file</strong></p>\n\n<p>in file: <em>functions.php</em></p>\n\n<pre><code>function my_enqueue( $hook ) {\n if (!current_user_can( 'manage_options' )) {\n wp_enqueue_script( 'my_custom_script', get_template_directory_uri() '/js/block-admin.js' );\n }\n}\nadd_action('admin_enqueue_scripts', 'my_enqueue');\n</code></pre>\n\n<p><strong>Set the JS to just immediately redirect</strong></p>\n\n<p>file: <em>theme_root/js/block-admin.js</em></p>\n\n<pre><code>window.location.href = \"/\";\n</code></pre>\n\n<p><strong>OR a timed redirect</strong></p>\n\n<pre><code>setTimeout(function () {\n window.location.href = \"/\";\n}, 2000);\n</code></pre>\n\n<p>This approach <a href=\"https://clicknathan.com/web-design/allow-subscribers-to-delete-posts-from-the-front-end-while-still-blocking-the-admin-area/\" rel=\"nofollow noreferrer\">came from clicknathan, and he offers more details here.</a></p>\n" }, { "answer_id": 269335, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 1, "selected": false, "text": "<p>hwl's answer is correct, but I'm going to add a check if the current user is the author of the post.</p>\n\n<pre><code>&lt;?php\n$current_user = wp_get_current_user();\nif ( $current_user-&gt;ID == $post-&gt;post_author ) { ?&gt;\n &lt;a href=\"&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;\"&gt;Delete post&lt;/a&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p><strike>Since you might be adding in the ability to <code>'delete_posts</code>', which could delete any post, this might be a safeguard.</strike> &lt; That wasn't right.</p>\n\n<p>That way the link only shows up on posts they can delete, their own.</p>\n" }, { "answer_id": 269340, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p>There are three requirements in your question:</p>\n\n<ol>\n<li>The role should not be able to log into the backend</li>\n<li>The role should be able to delete their own posts</li>\n<li>An implied requirement is that they should be able to delete published posts </li>\n</ol>\n\n<p>Presumably, you have a method in place where the user can post and publish their posts without access to the backend. If so, then you can manipulate the role by:</p>\n\n<ol>\n<li>Removing the <code>read</code> capability</li>\n<li>Adding the <code>delete_posts</code> capability</li>\n<li>Add the <code>delete_published_posts</code> capabilty</li>\n</ol>\n\n<p>Since the role doesn't have <code>delete_others_posts</code>, then they won't be able to delete other users posts - even if they're published.</p>\n\n<p>Role capabilities are stored in the database, so you should add and remove them on plugin or theme activation. Here's a sample plugin that adds the required capabilities on activation and removes them on deactivation.</p>\n\n<pre><code>/**\n * Plugin Name: WordPress StackExchange Question 268755\n * Description: Allow subscribers to delete their own posts\n **/\n\n//* On activation, add the capabilities to the subscriber role\nregister_activation_hook( __FILE__, 'wpse_268755_activation' );\nfunction wpse_268755_activation() {\n $photograph = get_role( 'photograph' );\n $photograph-&gt;remove_cap( 'read' );\n $photograph-&gt;add_cap( 'delete_posts' );\n $photograph-&gt;add_cap( 'delete_published_posts' );\n}\n\n//* On deactivation, remove the capabilities from the subscriber role\nregister_deactivation_hook( __FILE__, 'wpse_268755_deactivation' );\nfunction wpse_268755_deactivation() {\n $photograph = get_role( 'photograph' );\n $photograph-&gt;remove_cap( 'delete_posts' );\n $photograph-&gt;remove_cap( 'delete_published_posts' );\n}\n</code></pre>\n\n<p>You then need a way to actually delete the post. If the user had access to the back-end you could use <code>get_delete_post_link</code>.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;\"&gt;Delete post&lt;/a&gt;\n</code></pre>\n\n<p>So what you need to do is write some javascript that when that link is clicked it prevents the default behavior and sends an <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">AJAX</a> request to delete the post.</p>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120827/" ]
I want to merge two queries together and remove duplicate. I got it working individually. Now I got it working together but the results are not mixed and the duplicates are not removed. So I got the first queries result and then the second query result... ``` $fav_author_list = get_user_option( 'favorite-authors', fav_authors_get_user_id() ); $fav_categorie_list = get_user_option( 'favorite-categories', fav_categories_get_user_id() ); $rm_blog_args = array( 'posts_per_page' => -1, 'author__in'=> $fav_author_list, 'post_type' => 'post' ); $rm_blog = new WP_Query($rm_blog_args); $fb_args = array( 'posts_per_page' => -1, 'category__in'=> $fav_categorie_list, 'post_type' => 'post' ); $fb = new WP_Query($fb_args); // Final Query $final_query = new WP_Query(); // Merging queries $final_query->posts = array_merge( $rm_blog->posts, $fb->posts); // Recount echo $final_query->post_count = count( $final_query->posts ); // Remove duplicate post IDs $post_ids = array(); foreach( $final_query->posts as $item ) { $post_ids[] = $item->ID; } $unique_posts = array_unique($post_ids); if($final_query->have_posts()) : while ( $final_query->have_posts() ) : $final_query->the_post(); ```
Assuming you're talking about a custom user **role** named "*photographer*", I believe something like this should add the `delete_posts` capability to that role. ``` function add_delete_cap_to_photog_role() { $role = get_role( 'photographer' ); $role->add_cap( 'delete_posts' ); } add_action( 'admin_init', 'add_delete_cap_to_photog_role'); ``` --- After adding the caps to the role, to solve the rest you could either 1. keep `blockusers_init` and ditch `get_delete_post_link` for an ajax delete. 2. ditch the `blockusers_init` function and do a conditional redirect. I'll give some ideas on each. I prefer ditching `get_delete_post_link` in this instance. **Several steps below, so be aware the code is provided as a guide only. Rewrite and rename things as needed.** --- Ditch `get_delete_post_link` aka AJAX Delete -------------------------------------------- replace `get_delete_post_link` line with something like this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <a href="#" data-id="<?php the_ID() ?>" data-nonce="<?php echo wp_create_nonce('ajax_delete_post_nonce') ?>" class="delete-post">delete</a> <?php endif ?> ``` **Enqueue some JS** in file: *functions.php* ``` function delete_post_ajax() { wp_enqueue_script( 'delete_ajax', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'delete_ajax', 'TheAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'delete_post_ajax' ); ``` **onClick to pass data to delete method** in file: /js/my\_script.js ``` jQuery( document ).ready( function($) { $(document).on( 'click', '.delete-post', function() { var id = $(this).data('id'); var nonce = $(this).data('nonce'); var post = $(this).parents('.post:first'); $.ajax({ type: 'post', url: TheAjax.ajaxurl, data: { action: 'wpse_ajax_delete_post', nonce: nonce, id: id }, success: function( result ) { if( result == 'success' ) { post.fadeOut( function(){ post.remove(); }); } } }) return false; }) }) ``` **the delete method** in file: functions.php (the hook we need is just "`wp_ajax`" prepending the name of the `action` in js file) ``` add_action( 'wp_ajax_wpse_ajax_delete_post', 'wpse_ajax_delete_post_func' ); function wpse_ajax_delete_post_func(){ $permission = check_ajax_referer( 'ajax_delete_post_nonce', 'nonce', false ); if( $permission == false ) { echo 'error'; } else { wp_delete_post( $_REQUEST['id'] ); echo 'success'; } die(); } ``` To do the above by passing uri params: Change where we swapped out `get_delete_posts_link` for this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <?php $nonce = wp_create_nonce('ajax_delete_post_nonce') ?> <a href="<?php echo admin_url( 'admin-ajax.php?action=wpse_ajax_delete_post&id=' . get_the_ID() . '&nonce=' . $nonce ) ?>" data-id="<?php the_ID() ?>" data-nonce="<?php echo $nonce ?>" class="delete-post">delete</a> <?php endif ?> ``` See this for [a more involved walkthrough explaining each step](http://www.vandelaydesign.com/delete-a-wordpress-post-using-ajax/) --- Ditch `blockusers_init` (aka conditional redirect) -------------------------------------------------- This sets a redirect on wp-admin if user does not have `manage_options` cap, which is an administrator role. But first it pseudo-hides things and adds a message to user with some css: **The CSS bit** in file: *functions.php* ``` add_action('admin_head', 'hide_admin_via_css'); function hide_admin_via_css() { if (!current_user_can( 'manage_options' )) { echo '<style>body * {visibility:hidden !important;} body:before {content:"Give it a second...";} '; } } ``` **Enqueueing the JS file** in file: *functions.php* ``` function my_enqueue( $hook ) { if (!current_user_can( 'manage_options' )) { wp_enqueue_script( 'my_custom_script', get_template_directory_uri() '/js/block-admin.js' ); } } add_action('admin_enqueue_scripts', 'my_enqueue'); ``` **Set the JS to just immediately redirect** file: *theme\_root/js/block-admin.js* ``` window.location.href = "/"; ``` **OR a timed redirect** ``` setTimeout(function () { window.location.href = "/"; }, 2000); ``` This approach [came from clicknathan, and he offers more details here.](https://clicknathan.com/web-design/allow-subscribers-to-delete-posts-from-the-front-end-while-still-blocking-the-admin-area/)
268,829
<p>I need to hook to the users list page.</p> <p>I Need to add a checkbox column for each user to remember if they have paid or not.</p> <p>Thanks for help because can’t find snippet to hook to this admin page.</p>
[ { "answer_id": 268835, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>The users list column is filtered by <code>manage_users_columns</code>. Take a look into this simple example of how to hook into this filter:</p>\n\n<pre><code>// We add another column using 'manage_users_columns' filter\nfunction my_payment_column($columns) {\n return array_merge( $columns, \n array('payment' =&gt; __('Payment')) \n );\n}\n// Now we add some content to each row by using 'manage_users_custom_column' hook\nfunction my_payment_column_value($column_name, $user_id) {\n if ( 'payment' == $column_name ) {\n // Place to add checkbox, text field, etc.\n\n // If the user has paid, show it. Else, show N/A.\n if ( isset($paid) &amp;&amp; $paid ) {\n echo __('Paid','text-domain');\n } else {\n echo __('N/A','text-domain');\n }\n }\n}\n// Hook into filter\nadd_filter( 'manage_users_columns', 'my_payment_column' );\nadd_action( 'manage_users_custom_column', 'my_payment_column_value', 10, 2 );\n</code></pre>\n" }, { "answer_id": 279824, "author": "Aniket Singh", "author_id": 115514, "author_profile": "https://wordpress.stackexchange.com/users/115514", "pm_score": 0, "selected": false, "text": "<p>You can use this </p>\n\n<pre><code>function modify_user_table( $column ) {\n $column['comments'] = 'Comments';\n return $column;\n}\nadd_filter( 'manage_users_columns', 'modify_user_table' );\n\nfunction modify_user_table_row( $val, $column_name, $user_id ) { \n global $wpdb;\n if ($column_name == 'comments') {\n $comment_count = $wpdb-&gt;get_var( wpdb-&gt;prepare( \"SELECT COUNT(*) S total FROM $wpdb-&gt;comments WHERE comment_approved = 1 AND user_id = %s\", $user_id ) );\n return $comment_count; \n }\n return $val;\n}\nadd_filter( 'manage_users_custom_column', 'modify_user_table_row', 10, 3 );\n</code></pre>\n\n<p>For detailed explanation visit <a href=\"http://tekina.info/add-extra-column-user-listing-page-wordpress-admin-panel/\" rel=\"nofollow noreferrer\">http://tekina.info/add-extra-column-user-listing-page-wordpress-admin-panel/</a></p>\n" }, { "answer_id": 353608, "author": "budiony", "author_id": 15465, "author_profile": "https://wordpress.stackexchange.com/users/15465", "pm_score": 2, "selected": false, "text": "<p>One thing you should remember is that function, which will be hooked into <code>manage_users_custom_column</code> action <strong>must have 3 parameters</strong>, the first of which (i.e. <code>$val</code>) should be the returned value:</p>\n\n<pre><code>// Add custom column using 'manage_users_columns' filter\nif(!function_exists('bm_utm_column')){\nfunction bm_utm_column($columns) {\n return array_merge( $columns, \n array('utm_source' =&gt; __('UTM source'),\n 'utm_medium' =&gt; __('UTM medium')\n ) \n );\n }\n}\n\n// Add the content from usermeta's table by using 'manage_users_custom_column' hook\nif(!function_exists('bm_utm_column_value')){\n function bm_utm_column_value($val, $column_name, $user_id) {\n if ( 'utm_source' == $column_name ) {\n //Custom value\n $val = get_user_meta($user_id, 'utm_source', true);\n }\n if ( 'utm_medium' == $column_name ) {\n //Custom value\n $val = get_user_meta($user_id, 'utm_medium', true);\n }\n return $val;\n }\n}\n// Hook into filter\nadd_filter( 'manage_users_columns', 'bm_utm_column' );\nadd_action( 'manage_users_custom_column', 'bm_utm_column_value', 10, 3 );\n</code></pre>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120924/" ]
I need to hook to the users list page. I Need to add a checkbox column for each user to remember if they have paid or not. Thanks for help because can’t find snippet to hook to this admin page.
One thing you should remember is that function, which will be hooked into `manage_users_custom_column` action **must have 3 parameters**, the first of which (i.e. `$val`) should be the returned value: ``` // Add custom column using 'manage_users_columns' filter if(!function_exists('bm_utm_column')){ function bm_utm_column($columns) { return array_merge( $columns, array('utm_source' => __('UTM source'), 'utm_medium' => __('UTM medium') ) ); } } // Add the content from usermeta's table by using 'manage_users_custom_column' hook if(!function_exists('bm_utm_column_value')){ function bm_utm_column_value($val, $column_name, $user_id) { if ( 'utm_source' == $column_name ) { //Custom value $val = get_user_meta($user_id, 'utm_source', true); } if ( 'utm_medium' == $column_name ) { //Custom value $val = get_user_meta($user_id, 'utm_medium', true); } return $val; } } // Hook into filter add_filter( 'manage_users_columns', 'bm_utm_column' ); add_action( 'manage_users_custom_column', 'bm_utm_column_value', 10, 3 ); ```
268,842
<p>I'm moving existing data involving paintings from an old host that didn't use WordPress to a new host that does.</p> <p>With the old site, data was stored in a database so that each painting had its own page with information (artist, name, year, style, etc) and media pertaining to it, and the pages could then be searched by the different info (similar year, artist, etc)</p> <p>With WordPress, is there any way to use my old database to automatically generate pages/posts that could be sorted in this way?</p>
[ { "answer_id": 268845, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>You <em>could</em> use custom rewrite rule so that WP interprets specific URLs to call and present data from old database. However do you want to continue to <em>manage</em> data in the old database? As in create/link WP <em>admin interface</em> for saving data in a way that is foreign to it? At that point you are pretty much writing your own CMS next to WP.</p>\n\n<p>In my opinion, if WP becomes a new canonical way to access and manage this data, then the best approach would be to migrate it properly into appropriate WP data structures.</p>\n\n<p>Of course circumstances wary, depending on needs you could possibly just retain old functionality &amp; data altogether and just integrate/skin it within WP site.</p>\n\n<p>In a nutshell — the more WP will be responsible for doing, the better it would be to consider full migration.</p>\n" }, { "answer_id": 268853, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>Before getting into <a href=\"https://codex.wordpress.org/Importing_Content\" rel=\"nofollow noreferrer\"><em>Importing</em></a>, I would familiarize yourself with both the <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">standard post type</a> and <a href=\"https://codex.wordpress.org/Post_Meta_Data_Section\" rel=\"nofollow noreferrer\">post_meta</a> as well as <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">custom post types</a> and <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">taxonomies</a>. If your end goal would benefit from the latter, you will save yourself quite a bit of headache utilizing them during the import preparation.</p>\n\n<hr>\n\n<p>If you prefer working with the database directly, a dump/convert/import is always possible, of course. The schematic attached below would answer any questions you'd have there.</p>\n\n<p>Another option, in the vein of the importer, would be to send posts from the old site to the wp-json api endpoints of the wordpress site and handle the migration that way.</p>\n\n<p>As <a href=\"https://wordpress.stackexchange.com/users/847/rarst\">@Rarst</a> mentioned, there isn't really a shortcut, but as <a href=\"https://wordpress.stackexchange.com/users/11761/max-yudin\">@Max</a> noted in his comment the Importer can at least assist you in the process on the Wordpress side. </p>\n\n<p>The below just elaborates on and consolidates links for those points.</p>\n\n<h2>Using Wordpress Importer ( <em>Tools > Import</em> )</h2>\n\n<p>There are a multitude of options, (and an even greater multitude of things to consider before using any of them), for importing content into wordpress. <strong>This would be the <em>safest</em> method to take.</strong> \nYou can familiarize yourself with many of them here: <a href=\"https://codex.wordpress.org/Importing_Content\" rel=\"nofollow noreferrer\">Importing Content into Wordpress</a></p>\n\n<p>Including:</p>\n\n<ul>\n<li>Blogger </li>\n<li>Drupal</li>\n<li>Excel Spreadsheet/CSV/XML/JSON </li>\n<li>Google Blog Converters </li>\n<li>Joomla</li>\n<li>LiveJournal </li>\n<li>Magento </li>\n<li>Mambo </li>\n<li>Movable Type </li>\n<li>Nucleus CMS </li>\n<li>Plone </li>\n<li>Posterous </li>\n<li>SPIP </li>\n<li>Tumblr </li>\n<li>Twitter </li>\n<li>TypePad</li>\n<li>etc, etc, you get the point</li>\n</ul>\n\n<p>That pages also lists various plugins for importing an export of a previous cms (multiple types listed).</p>\n\n<p>CSV, XML, RSS... any manner really. You will have to create the file it needs to process, of course.</p>\n\n<hr>\n\n<h2>Database Dump > Import</h2>\n\n<p>(<em>Without knowing any info on the current DB</em>), you could dump the old DBs <em>pages</em> content, and convert it into an sql import. \n<strong>Don't even consider this if you don't really know what you're doing, though. You could seriously muck things up.</strong> But a viable option if you're comfortable with it.</p>\n\n<p>I would not consider this a <em>wordpress</em> solution, just noting it as an approach.</p>\n\n<hr>\n\n<h2>Import Bridge with WP-JSON API</h2>\n\n<p>If you still have access to the old DB/site, you could utilize the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">wp-json api</a> by writing something on your end that <code>posts</code> to the appropriate endpoint on the wordpress end for each entry in your old DB. </p>\n\n<p>You may normally build this for keeping things in sync, but it could work as a one-time import tool as well. </p>\n\n<hr>\n\n<p>Expanding on this in lieu of OP's additional questions in comments:</p>\n\n<p>First, you will want to bookmark <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/\" rel=\"nofollow noreferrer\">this resource for dealing with the WP_REST_request class</a></p>\n\n<p>Assuming we have written a bit of code on the <em>old site</em> that grabs the relevant content and puts it into a formatted POST object, and assuming a custom endpoint:</p>\n\n<p><code>[Old Site Data ]</code> POST http to route <code>http://new-WP-site.com/wp-json/v2/plugin_namespace/v1/posts/</code></p>\n\n<p>On the WP end, <code>/plugin_namespace/v1/posts/</code> we would create. To make this happen, we first <code>extend</code> the <code>WP_REST_Controller</code> class. </p>\n\n<p>Then inside our class we register our routes using <code>register_rest_routes()</code>.\nSomething like:</p>\n\n<pre><code>public function __construct() {\n add_action( 'rest_api_init', array($this, 'register_routes' ) );\n }//end __construct\n\npublic function register_routes() {\n $version = '1';\n $namespace = 'plugin_namespace/v' . $version; \n $base = 'posts';\n register_rest_route( $namespace, '/'. $base, array(\n array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; array( $this, 'this_is_a_callback_function' ),\n //'permission_callback' =&gt; array( $this, 'key_permissions_check' ),\n ),\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; array( $this, 'this_is_a_callback_function' ),\n //'permission_callback' =&gt; array( $this, 'key_permissions_check' ),\n ),)\n );\n\n }//register_routes\n public function this_is_a_callback_function(WP_REST_Request $request) {\n\n //if posted in body like form data\n $posted_data = $request-&gt;get_body_params();\n\n }\n</code></pre>\n\n<p>From this point <code>$posted_data</code> has what was <code>POST</code>ed, and you can walk through it, or pass it on to another function that does. </p>\n\n<p>That function would need to build the post_array out of each entry, and pass that along to <code>wp_insert_post()</code> </p>\n\n<p>An approach could be made utilizing <code>WP_REST_Server::CREATABLE</code> in place of <code>methods =&gt; POST</code> as well. Mine is just a quick/incomplete example.</p>\n\n<p>Also I commented out the <code>permissions_callbacks</code>, but that callback function is where your authorization checks would normally go.</p>\n\n<p><em>Note that <code>wp_insert_post()</code> will allow you to pass an array of meta as well, but <code>wp_update_post</code> will not. <code>wp_insert_post</code> also requires a <code>title</code> and <code>content</code> values. If you pass any ID other than 0, it will run <code>wp_upate_post</code>.</em></p>\n\n<p>You may want to look at using something like <a href=\"https://requestb.in\" rel=\"nofollow noreferrer\">requestb.in</a> while sorting out your <em>old site</em> code to check what it is sending, and <a href=\"https://www.getpostman.com/\" rel=\"nofollow noreferrer\">postman</a> works quite well for checking the api's response.</p>\n\n<p>As I mentioned in the comments, <a href=\"https://ngrok.com/\" rel=\"nofollow noreferrer\">ngrok</a> could be used to do the non-wp to wp migration completely in a dev environment. </p>\n\n<p>Hopefully that gives you enough info to translate it to whomever you need.</p>\n\n<hr>\n\n<h2>Relevant WP Tables (posts)</h2>\n\n<p>Whether building an sql import or writing some other bridge, \nfor <strong>posts</strong>, the tables to map to on the wordpress end of things would be:</p>\n\n<blockquote>\n <p><strong>Table Name</strong> : <strong>data in table</strong></p>\n \n <p>wp_posts : the posts</p>\n \n <p>wp_postmeta : post meta values</p>\n \n <p>wp_term_relationships : posts to taxonomies </p>\n \n <p>wp_term_taxonomy : taxonomies </p>\n \n <p>wp_terms : tag and category values</p>\n</blockquote>\n\n<p>Here is the <a href=\"https://codex.wordpress.org/Database_Description\" rel=\"nofollow noreferrer\">full database schematic</a>\n<a href=\"https://i.stack.imgur.com/F2sGQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/F2sGQ.png\" alt=\"enter image description here\"></a> </p>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268842", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120930/" ]
I'm moving existing data involving paintings from an old host that didn't use WordPress to a new host that does. With the old site, data was stored in a database so that each painting had its own page with information (artist, name, year, style, etc) and media pertaining to it, and the pages could then be searched by the different info (similar year, artist, etc) With WordPress, is there any way to use my old database to automatically generate pages/posts that could be sorted in this way?
Before getting into [*Importing*](https://codex.wordpress.org/Importing_Content), I would familiarize yourself with both the [standard post type](https://codex.wordpress.org/Post_Types) and [post\_meta](https://codex.wordpress.org/Post_Meta_Data_Section) as well as [custom post types](https://codex.wordpress.org/Post_Types) and [taxonomies](https://codex.wordpress.org/Taxonomies). If your end goal would benefit from the latter, you will save yourself quite a bit of headache utilizing them during the import preparation. --- If you prefer working with the database directly, a dump/convert/import is always possible, of course. The schematic attached below would answer any questions you'd have there. Another option, in the vein of the importer, would be to send posts from the old site to the wp-json api endpoints of the wordpress site and handle the migration that way. As [@Rarst](https://wordpress.stackexchange.com/users/847/rarst) mentioned, there isn't really a shortcut, but as [@Max](https://wordpress.stackexchange.com/users/11761/max-yudin) noted in his comment the Importer can at least assist you in the process on the Wordpress side. The below just elaborates on and consolidates links for those points. Using Wordpress Importer ( *Tools > Import* ) --------------------------------------------- There are a multitude of options, (and an even greater multitude of things to consider before using any of them), for importing content into wordpress. **This would be the *safest* method to take.** You can familiarize yourself with many of them here: [Importing Content into Wordpress](https://codex.wordpress.org/Importing_Content) Including: * Blogger * Drupal * Excel Spreadsheet/CSV/XML/JSON * Google Blog Converters * Joomla * LiveJournal * Magento * Mambo * Movable Type * Nucleus CMS * Plone * Posterous * SPIP * Tumblr * Twitter * TypePad * etc, etc, you get the point That pages also lists various plugins for importing an export of a previous cms (multiple types listed). CSV, XML, RSS... any manner really. You will have to create the file it needs to process, of course. --- Database Dump > Import ---------------------- (*Without knowing any info on the current DB*), you could dump the old DBs *pages* content, and convert it into an sql import. **Don't even consider this if you don't really know what you're doing, though. You could seriously muck things up.** But a viable option if you're comfortable with it. I would not consider this a *wordpress* solution, just noting it as an approach. --- Import Bridge with WP-JSON API ------------------------------ If you still have access to the old DB/site, you could utilize the [wp-json api](https://developer.wordpress.org/rest-api/) by writing something on your end that `posts` to the appropriate endpoint on the wordpress end for each entry in your old DB. You may normally build this for keeping things in sync, but it could work as a one-time import tool as well. --- Expanding on this in lieu of OP's additional questions in comments: First, you will want to bookmark [this resource for dealing with the WP\_REST\_request class](https://developer.wordpress.org/reference/classes/wp_rest_request/) Assuming we have written a bit of code on the *old site* that grabs the relevant content and puts it into a formatted POST object, and assuming a custom endpoint: `[Old Site Data ]` POST http to route `http://new-WP-site.com/wp-json/v2/plugin_namespace/v1/posts/` On the WP end, `/plugin_namespace/v1/posts/` we would create. To make this happen, we first `extend` the `WP_REST_Controller` class. Then inside our class we register our routes using `register_rest_routes()`. Something like: ``` public function __construct() { add_action( 'rest_api_init', array($this, 'register_routes' ) ); }//end __construct public function register_routes() { $version = '1'; $namespace = 'plugin_namespace/v' . $version; $base = 'posts'; register_rest_route( $namespace, '/'. $base, array( array( 'methods' => 'GET', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ),) ); }//register_routes public function this_is_a_callback_function(WP_REST_Request $request) { //if posted in body like form data $posted_data = $request->get_body_params(); } ``` From this point `$posted_data` has what was `POST`ed, and you can walk through it, or pass it on to another function that does. That function would need to build the post\_array out of each entry, and pass that along to `wp_insert_post()` An approach could be made utilizing `WP_REST_Server::CREATABLE` in place of `methods => POST` as well. Mine is just a quick/incomplete example. Also I commented out the `permissions_callbacks`, but that callback function is where your authorization checks would normally go. *Note that `wp_insert_post()` will allow you to pass an array of meta as well, but `wp_update_post` will not. `wp_insert_post` also requires a `title` and `content` values. If you pass any ID other than 0, it will run `wp_upate_post`.* You may want to look at using something like [requestb.in](https://requestb.in) while sorting out your *old site* code to check what it is sending, and [postman](https://www.getpostman.com/) works quite well for checking the api's response. As I mentioned in the comments, [ngrok](https://ngrok.com/) could be used to do the non-wp to wp migration completely in a dev environment. Hopefully that gives you enough info to translate it to whomever you need. --- Relevant WP Tables (posts) -------------------------- Whether building an sql import or writing some other bridge, for **posts**, the tables to map to on the wordpress end of things would be: > > **Table Name** : **data in table** > > > wp\_posts : the posts > > > wp\_postmeta : post meta values > > > wp\_term\_relationships : posts to taxonomies > > > wp\_term\_taxonomy : taxonomies > > > wp\_terms : tag and category values > > > Here is the [full database schematic](https://codex.wordpress.org/Database_Description) [![enter image description here](https://i.stack.imgur.com/F2sGQ.png)](https://i.stack.imgur.com/F2sGQ.png)
268,864
<p>I will frequently add a line of text in my article sending the reader to the article page. This is separate from the actual produced permalink. The problem I'm having is that I can't get the permalink until the article is posted. I can copy the text from the displayed permalink, but if the title is too long that won't work. I can also copy that permalink but then I just get the generic ?p=123 type of link and I have to be sure to remove the 'preview' part of it. </p> <p>Is there a nifty piece of code to put in the link field that will pull the permalink for that article? Kind of how it does in the PHP? This would also solve the issue if the permalink was changed and it broke the custom link. </p>
[ { "answer_id": 268845, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>You <em>could</em> use custom rewrite rule so that WP interprets specific URLs to call and present data from old database. However do you want to continue to <em>manage</em> data in the old database? As in create/link WP <em>admin interface</em> for saving data in a way that is foreign to it? At that point you are pretty much writing your own CMS next to WP.</p>\n\n<p>In my opinion, if WP becomes a new canonical way to access and manage this data, then the best approach would be to migrate it properly into appropriate WP data structures.</p>\n\n<p>Of course circumstances wary, depending on needs you could possibly just retain old functionality &amp; data altogether and just integrate/skin it within WP site.</p>\n\n<p>In a nutshell — the more WP will be responsible for doing, the better it would be to consider full migration.</p>\n" }, { "answer_id": 268853, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>Before getting into <a href=\"https://codex.wordpress.org/Importing_Content\" rel=\"nofollow noreferrer\"><em>Importing</em></a>, I would familiarize yourself with both the <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">standard post type</a> and <a href=\"https://codex.wordpress.org/Post_Meta_Data_Section\" rel=\"nofollow noreferrer\">post_meta</a> as well as <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">custom post types</a> and <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">taxonomies</a>. If your end goal would benefit from the latter, you will save yourself quite a bit of headache utilizing them during the import preparation.</p>\n\n<hr>\n\n<p>If you prefer working with the database directly, a dump/convert/import is always possible, of course. The schematic attached below would answer any questions you'd have there.</p>\n\n<p>Another option, in the vein of the importer, would be to send posts from the old site to the wp-json api endpoints of the wordpress site and handle the migration that way.</p>\n\n<p>As <a href=\"https://wordpress.stackexchange.com/users/847/rarst\">@Rarst</a> mentioned, there isn't really a shortcut, but as <a href=\"https://wordpress.stackexchange.com/users/11761/max-yudin\">@Max</a> noted in his comment the Importer can at least assist you in the process on the Wordpress side. </p>\n\n<p>The below just elaborates on and consolidates links for those points.</p>\n\n<h2>Using Wordpress Importer ( <em>Tools > Import</em> )</h2>\n\n<p>There are a multitude of options, (and an even greater multitude of things to consider before using any of them), for importing content into wordpress. <strong>This would be the <em>safest</em> method to take.</strong> \nYou can familiarize yourself with many of them here: <a href=\"https://codex.wordpress.org/Importing_Content\" rel=\"nofollow noreferrer\">Importing Content into Wordpress</a></p>\n\n<p>Including:</p>\n\n<ul>\n<li>Blogger </li>\n<li>Drupal</li>\n<li>Excel Spreadsheet/CSV/XML/JSON </li>\n<li>Google Blog Converters </li>\n<li>Joomla</li>\n<li>LiveJournal </li>\n<li>Magento </li>\n<li>Mambo </li>\n<li>Movable Type </li>\n<li>Nucleus CMS </li>\n<li>Plone </li>\n<li>Posterous </li>\n<li>SPIP </li>\n<li>Tumblr </li>\n<li>Twitter </li>\n<li>TypePad</li>\n<li>etc, etc, you get the point</li>\n</ul>\n\n<p>That pages also lists various plugins for importing an export of a previous cms (multiple types listed).</p>\n\n<p>CSV, XML, RSS... any manner really. You will have to create the file it needs to process, of course.</p>\n\n<hr>\n\n<h2>Database Dump > Import</h2>\n\n<p>(<em>Without knowing any info on the current DB</em>), you could dump the old DBs <em>pages</em> content, and convert it into an sql import. \n<strong>Don't even consider this if you don't really know what you're doing, though. You could seriously muck things up.</strong> But a viable option if you're comfortable with it.</p>\n\n<p>I would not consider this a <em>wordpress</em> solution, just noting it as an approach.</p>\n\n<hr>\n\n<h2>Import Bridge with WP-JSON API</h2>\n\n<p>If you still have access to the old DB/site, you could utilize the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">wp-json api</a> by writing something on your end that <code>posts</code> to the appropriate endpoint on the wordpress end for each entry in your old DB. </p>\n\n<p>You may normally build this for keeping things in sync, but it could work as a one-time import tool as well. </p>\n\n<hr>\n\n<p>Expanding on this in lieu of OP's additional questions in comments:</p>\n\n<p>First, you will want to bookmark <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/\" rel=\"nofollow noreferrer\">this resource for dealing with the WP_REST_request class</a></p>\n\n<p>Assuming we have written a bit of code on the <em>old site</em> that grabs the relevant content and puts it into a formatted POST object, and assuming a custom endpoint:</p>\n\n<p><code>[Old Site Data ]</code> POST http to route <code>http://new-WP-site.com/wp-json/v2/plugin_namespace/v1/posts/</code></p>\n\n<p>On the WP end, <code>/plugin_namespace/v1/posts/</code> we would create. To make this happen, we first <code>extend</code> the <code>WP_REST_Controller</code> class. </p>\n\n<p>Then inside our class we register our routes using <code>register_rest_routes()</code>.\nSomething like:</p>\n\n<pre><code>public function __construct() {\n add_action( 'rest_api_init', array($this, 'register_routes' ) );\n }//end __construct\n\npublic function register_routes() {\n $version = '1';\n $namespace = 'plugin_namespace/v' . $version; \n $base = 'posts';\n register_rest_route( $namespace, '/'. $base, array(\n array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; array( $this, 'this_is_a_callback_function' ),\n //'permission_callback' =&gt; array( $this, 'key_permissions_check' ),\n ),\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; array( $this, 'this_is_a_callback_function' ),\n //'permission_callback' =&gt; array( $this, 'key_permissions_check' ),\n ),)\n );\n\n }//register_routes\n public function this_is_a_callback_function(WP_REST_Request $request) {\n\n //if posted in body like form data\n $posted_data = $request-&gt;get_body_params();\n\n }\n</code></pre>\n\n<p>From this point <code>$posted_data</code> has what was <code>POST</code>ed, and you can walk through it, or pass it on to another function that does. </p>\n\n<p>That function would need to build the post_array out of each entry, and pass that along to <code>wp_insert_post()</code> </p>\n\n<p>An approach could be made utilizing <code>WP_REST_Server::CREATABLE</code> in place of <code>methods =&gt; POST</code> as well. Mine is just a quick/incomplete example.</p>\n\n<p>Also I commented out the <code>permissions_callbacks</code>, but that callback function is where your authorization checks would normally go.</p>\n\n<p><em>Note that <code>wp_insert_post()</code> will allow you to pass an array of meta as well, but <code>wp_update_post</code> will not. <code>wp_insert_post</code> also requires a <code>title</code> and <code>content</code> values. If you pass any ID other than 0, it will run <code>wp_upate_post</code>.</em></p>\n\n<p>You may want to look at using something like <a href=\"https://requestb.in\" rel=\"nofollow noreferrer\">requestb.in</a> while sorting out your <em>old site</em> code to check what it is sending, and <a href=\"https://www.getpostman.com/\" rel=\"nofollow noreferrer\">postman</a> works quite well for checking the api's response.</p>\n\n<p>As I mentioned in the comments, <a href=\"https://ngrok.com/\" rel=\"nofollow noreferrer\">ngrok</a> could be used to do the non-wp to wp migration completely in a dev environment. </p>\n\n<p>Hopefully that gives you enough info to translate it to whomever you need.</p>\n\n<hr>\n\n<h2>Relevant WP Tables (posts)</h2>\n\n<p>Whether building an sql import or writing some other bridge, \nfor <strong>posts</strong>, the tables to map to on the wordpress end of things would be:</p>\n\n<blockquote>\n <p><strong>Table Name</strong> : <strong>data in table</strong></p>\n \n <p>wp_posts : the posts</p>\n \n <p>wp_postmeta : post meta values</p>\n \n <p>wp_term_relationships : posts to taxonomies </p>\n \n <p>wp_term_taxonomy : taxonomies </p>\n \n <p>wp_terms : tag and category values</p>\n</blockquote>\n\n<p>Here is the <a href=\"https://codex.wordpress.org/Database_Description\" rel=\"nofollow noreferrer\">full database schematic</a>\n<a href=\"https://i.stack.imgur.com/F2sGQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/F2sGQ.png\" alt=\"enter image description here\"></a> </p>\n" } ]
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120941/" ]
I will frequently add a line of text in my article sending the reader to the article page. This is separate from the actual produced permalink. The problem I'm having is that I can't get the permalink until the article is posted. I can copy the text from the displayed permalink, but if the title is too long that won't work. I can also copy that permalink but then I just get the generic ?p=123 type of link and I have to be sure to remove the 'preview' part of it. Is there a nifty piece of code to put in the link field that will pull the permalink for that article? Kind of how it does in the PHP? This would also solve the issue if the permalink was changed and it broke the custom link.
Before getting into [*Importing*](https://codex.wordpress.org/Importing_Content), I would familiarize yourself with both the [standard post type](https://codex.wordpress.org/Post_Types) and [post\_meta](https://codex.wordpress.org/Post_Meta_Data_Section) as well as [custom post types](https://codex.wordpress.org/Post_Types) and [taxonomies](https://codex.wordpress.org/Taxonomies). If your end goal would benefit from the latter, you will save yourself quite a bit of headache utilizing them during the import preparation. --- If you prefer working with the database directly, a dump/convert/import is always possible, of course. The schematic attached below would answer any questions you'd have there. Another option, in the vein of the importer, would be to send posts from the old site to the wp-json api endpoints of the wordpress site and handle the migration that way. As [@Rarst](https://wordpress.stackexchange.com/users/847/rarst) mentioned, there isn't really a shortcut, but as [@Max](https://wordpress.stackexchange.com/users/11761/max-yudin) noted in his comment the Importer can at least assist you in the process on the Wordpress side. The below just elaborates on and consolidates links for those points. Using Wordpress Importer ( *Tools > Import* ) --------------------------------------------- There are a multitude of options, (and an even greater multitude of things to consider before using any of them), for importing content into wordpress. **This would be the *safest* method to take.** You can familiarize yourself with many of them here: [Importing Content into Wordpress](https://codex.wordpress.org/Importing_Content) Including: * Blogger * Drupal * Excel Spreadsheet/CSV/XML/JSON * Google Blog Converters * Joomla * LiveJournal * Magento * Mambo * Movable Type * Nucleus CMS * Plone * Posterous * SPIP * Tumblr * Twitter * TypePad * etc, etc, you get the point That pages also lists various plugins for importing an export of a previous cms (multiple types listed). CSV, XML, RSS... any manner really. You will have to create the file it needs to process, of course. --- Database Dump > Import ---------------------- (*Without knowing any info on the current DB*), you could dump the old DBs *pages* content, and convert it into an sql import. **Don't even consider this if you don't really know what you're doing, though. You could seriously muck things up.** But a viable option if you're comfortable with it. I would not consider this a *wordpress* solution, just noting it as an approach. --- Import Bridge with WP-JSON API ------------------------------ If you still have access to the old DB/site, you could utilize the [wp-json api](https://developer.wordpress.org/rest-api/) by writing something on your end that `posts` to the appropriate endpoint on the wordpress end for each entry in your old DB. You may normally build this for keeping things in sync, but it could work as a one-time import tool as well. --- Expanding on this in lieu of OP's additional questions in comments: First, you will want to bookmark [this resource for dealing with the WP\_REST\_request class](https://developer.wordpress.org/reference/classes/wp_rest_request/) Assuming we have written a bit of code on the *old site* that grabs the relevant content and puts it into a formatted POST object, and assuming a custom endpoint: `[Old Site Data ]` POST http to route `http://new-WP-site.com/wp-json/v2/plugin_namespace/v1/posts/` On the WP end, `/plugin_namespace/v1/posts/` we would create. To make this happen, we first `extend` the `WP_REST_Controller` class. Then inside our class we register our routes using `register_rest_routes()`. Something like: ``` public function __construct() { add_action( 'rest_api_init', array($this, 'register_routes' ) ); }//end __construct public function register_routes() { $version = '1'; $namespace = 'plugin_namespace/v' . $version; $base = 'posts'; register_rest_route( $namespace, '/'. $base, array( array( 'methods' => 'GET', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ),) ); }//register_routes public function this_is_a_callback_function(WP_REST_Request $request) { //if posted in body like form data $posted_data = $request->get_body_params(); } ``` From this point `$posted_data` has what was `POST`ed, and you can walk through it, or pass it on to another function that does. That function would need to build the post\_array out of each entry, and pass that along to `wp_insert_post()` An approach could be made utilizing `WP_REST_Server::CREATABLE` in place of `methods => POST` as well. Mine is just a quick/incomplete example. Also I commented out the `permissions_callbacks`, but that callback function is where your authorization checks would normally go. *Note that `wp_insert_post()` will allow you to pass an array of meta as well, but `wp_update_post` will not. `wp_insert_post` also requires a `title` and `content` values. If you pass any ID other than 0, it will run `wp_upate_post`.* You may want to look at using something like [requestb.in](https://requestb.in) while sorting out your *old site* code to check what it is sending, and [postman](https://www.getpostman.com/) works quite well for checking the api's response. As I mentioned in the comments, [ngrok](https://ngrok.com/) could be used to do the non-wp to wp migration completely in a dev environment. Hopefully that gives you enough info to translate it to whomever you need. --- Relevant WP Tables (posts) -------------------------- Whether building an sql import or writing some other bridge, for **posts**, the tables to map to on the wordpress end of things would be: > > **Table Name** : **data in table** > > > wp\_posts : the posts > > > wp\_postmeta : post meta values > > > wp\_term\_relationships : posts to taxonomies > > > wp\_term\_taxonomy : taxonomies > > > wp\_terms : tag and category values > > > Here is the [full database schematic](https://codex.wordpress.org/Database_Description) [![enter image description here](https://i.stack.imgur.com/F2sGQ.png)](https://i.stack.imgur.com/F2sGQ.png)
268,900
<p>I've built a marketplace-type site that lets different users post custom listings to the site.</p> <p>I want to use the WP backend to administer these listings with my admin account. The custom post types are displayed much like normal posts there.</p> <p>The problem is that the post author isn't shown. I googled the issue and quickly found that adding <code>"supports" =&gt; array( "title", "editor", "author" )</code> to the $args for <code>register_post_type()</code> adds a column showing the author to the listings of all custom post items.</p> <p>However, I'm unsure how to add a box displaying the author in the edit screen where the editor and other detailed information about the post shows. As is I just have the box with the publishing information and one for the custom post type's taxonomies.</p> <p>How would I go about having the post's author displayed there too? I'm really a bit lost on this and couldn't find anything on google.</p>
[ { "answer_id": 274573, "author": "PoeHaH", "author_id": 102898, "author_profile": "https://wordpress.stackexchange.com/users/102898", "pm_score": 2, "selected": false, "text": "<p>You can achieve this by using the <code>add_post_type_support</code> function as described here: <a href=\"https://codex.wordpress.org/Function_Reference/add_post_type_support\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_post_type_support</a>.</p>\n\n<p>This code should work:</p>\n\n<pre><code>function add_author_support_to_posts() {\n add_post_type_support( 'your_custom_post_type', 'author' ); \n}\nadd_action( 'init', 'add_author_support_to_posts' );\n</code></pre>\n\n<p>It can be added in your theme's <code>function.php</code> file.</p>\n" }, { "answer_id": 305456, "author": "Lavert", "author_id": 144916, "author_profile": "https://wordpress.stackexchange.com/users/144916", "pm_score": 1, "selected": false, "text": "<p>If you are using the plugin CPT UI you can simply edit the custom post type there.</p>\n\n<ol>\n<li><p>navigate to CPT UI in admin section</p></li>\n<li><p>select the post type you want to add the 'author' feature to</p></li>\n<li><p>scroll down almost to the bottom and in the 'Supports (Add support for various available post editor features on the right...)' and in the checkbox to the right make sure that the checkbox for 'author' is checked.</p></li>\n</ol>\n\n<p>You may then need to refresh your cache but you'll see the 'author' field appear next to each custom post type in the admin screen.</p>\n" } ]
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268900", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104550/" ]
I've built a marketplace-type site that lets different users post custom listings to the site. I want to use the WP backend to administer these listings with my admin account. The custom post types are displayed much like normal posts there. The problem is that the post author isn't shown. I googled the issue and quickly found that adding `"supports" => array( "title", "editor", "author" )` to the $args for `register_post_type()` adds a column showing the author to the listings of all custom post items. However, I'm unsure how to add a box displaying the author in the edit screen where the editor and other detailed information about the post shows. As is I just have the box with the publishing information and one for the custom post type's taxonomies. How would I go about having the post's author displayed there too? I'm really a bit lost on this and couldn't find anything on google.
You can achieve this by using the `add_post_type_support` function as described here: <https://codex.wordpress.org/Function_Reference/add_post_type_support>. This code should work: ``` function add_author_support_to_posts() { add_post_type_support( 'your_custom_post_type', 'author' ); } add_action( 'init', 'add_author_support_to_posts' ); ``` It can be added in your theme's `function.php` file.
268,913
<p>I want to get several post by tag. So I try to use get_posts() function:</p> <pre><code>&lt;?php $args = array( 'numberposts' =&gt; '3', 'post_status' =&gt; 'publish', 'tag' =&gt; 'travel' ); $recent_posts = get_posts($args);?&gt; </code></pre> <p>But it doesn't work. How can I get posts by tag?</p>
[ { "answer_id": 268934, "author": "Jan Čejka", "author_id": 70265, "author_profile": "https://wordpress.stackexchange.com/users/70265", "pm_score": 1, "selected": false, "text": "<p>Look at this section: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters\" rel=\"nofollow noreferrer\">Tag parameters</a> in WP Codex, where is explained search by tags.</p>\n\n<p>Your code like right. Try change numberposts to int:</p>\n\n<pre><code>&lt;?php $args = array(\n 'numberposts' =&gt; 3,\n 'post_status' =&gt; 'publish',\n 'tag' =&gt; 'travel'\n);\n</code></pre>\n" }, { "answer_id": 268936, "author": "thnx-236659", "author_id": 86280, "author_profile": "https://wordpress.stackexchange.com/users/86280", "pm_score": 0, "selected": false, "text": "<p>You may find it helpful to check out this link about <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters\" rel=\"nofollow noreferrer\">WP Queries</a> to query by tag.</p>\n\n<p>The advantage of using this query is you can create your own <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">loop</a>, and you can put the posts in whatever arrangement you need.</p>\n\n<p>For example, you can drop the post titles into a list, or you can generate the standard title headings followed by an excerpt or content.</p>\n\n<p>For a list, the code would look something like this:</p>\n\n<pre><code>&lt;ol&gt;\n\n &lt;?php $args = array(\n 'tag' =&gt; 'travel', \n 'posts_per_page' =&gt; 3); ?&gt;\n\n &lt;?php $recent_posts = new WP_Query( $args ); ?&gt;\n\n &lt;?php if ($recent_posts-&gt;have_posts()) : \n while ($recent_posts-&gt;have_posts()) : $recent_posts-&gt;the_post();\n ?&gt;\n\n\n &lt;li&gt;&lt;?php the_title(); ?&gt;&lt;/li&gt;\n\n &lt;?php endwhile; \n\n else :\n echo \"Nothing\";\n endif;\n wp_reset_postdata();\n ?&gt;\n&lt;/ol&gt;\n</code></pre>\n" } ]
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268913", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103556/" ]
I want to get several post by tag. So I try to use get\_posts() function: ``` <?php $args = array( 'numberposts' => '3', 'post_status' => 'publish', 'tag' => 'travel' ); $recent_posts = get_posts($args);?> ``` But it doesn't work. How can I get posts by tag?
Look at this section: [Tag parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters) in WP Codex, where is explained search by tags. Your code like right. Try change numberposts to int: ``` <?php $args = array( 'numberposts' => 3, 'post_status' => 'publish', 'tag' => 'travel' ); ```
268,928
<p>I would like to redirect users to my home page when the requested page or post cannot be found, but don't know how to go about with that.</p> <p>How do I proceed with such and action?</p>
[ { "answer_id": 268969, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You can set any page/url to handle a 404 error via the <code>htaccess</code> file. This is a good tutorial on doing that: <a href=\"http://www.htaccessbasics.com/404-custom-error-page/\" rel=\"nofollow noreferrer\">http://www.htaccessbasics.com/404-custom-error-page/</a> .</p>\n\n<p>Use their example, but set the error page to a specific page (your home page). </p>\n\n<p>Your theme may have a 404.php template that handles missing pages. But you can override that with the <code>htaccess</code> file. Make sure you first make a backup of the existing <code>htaccess</code> file, in case of problems.</p>\n" }, { "answer_id": 268970, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>You can use this code inside your <code>404.php</code> template file to safely redirect to users to homepage:</p>\n\n<pre><code>wp_safe_redirect(site_url());\nexit();\n</code></pre>\n\n<p>Use this code before every line of code in your <code>404.php</code>. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for.</p>\n\n<p>You don't have to delete the content of your <code>404.php</code> file, since every line of code after the <code>exit()</code> will be ignored.</p>\n" } ]
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268928", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120985/" ]
I would like to redirect users to my home page when the requested page or post cannot be found, but don't know how to go about with that. How do I proceed with such and action?
You can use this code inside your `404.php` template file to safely redirect to users to homepage: ``` wp_safe_redirect(site_url()); exit(); ``` Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
268,978
<p>I need to copy over Wordpress users with roles/passwords intact to a new install. I'd prefer not to copy the entire site (though if I have to I will.)</p> <p>Currently I only have the one main admin account on the new install. Some people have mentioned importing the old user and user-meta tables from the original database, but others have said this could cause problems.</p>
[ { "answer_id": 268969, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You can set any page/url to handle a 404 error via the <code>htaccess</code> file. This is a good tutorial on doing that: <a href=\"http://www.htaccessbasics.com/404-custom-error-page/\" rel=\"nofollow noreferrer\">http://www.htaccessbasics.com/404-custom-error-page/</a> .</p>\n\n<p>Use their example, but set the error page to a specific page (your home page). </p>\n\n<p>Your theme may have a 404.php template that handles missing pages. But you can override that with the <code>htaccess</code> file. Make sure you first make a backup of the existing <code>htaccess</code> file, in case of problems.</p>\n" }, { "answer_id": 268970, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>You can use this code inside your <code>404.php</code> template file to safely redirect to users to homepage:</p>\n\n<pre><code>wp_safe_redirect(site_url());\nexit();\n</code></pre>\n\n<p>Use this code before every line of code in your <code>404.php</code>. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for.</p>\n\n<p>You don't have to delete the content of your <code>404.php</code> file, since every line of code after the <code>exit()</code> will be ignored.</p>\n" } ]
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268978", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106747/" ]
I need to copy over Wordpress users with roles/passwords intact to a new install. I'd prefer not to copy the entire site (though if I have to I will.) Currently I only have the one main admin account on the new install. Some people have mentioned importing the old user and user-meta tables from the original database, but others have said this could cause problems.
You can use this code inside your `404.php` template file to safely redirect to users to homepage: ``` wp_safe_redirect(site_url()); exit(); ``` Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
269,016
<p>Recently I've locked myself out of my WordPress site by changing the site URL. I fixed that problem by reverting the site URL to the original one in PHPmyadmin database.</p> <p>But what happens now is that my website is working properly but whenever i access the back-end, only the HTML part of WordPress is loading and not the CSS part. </p> <p>Can anyone explain to me what is happening and how to fix this?</p>
[ { "answer_id": 268969, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You can set any page/url to handle a 404 error via the <code>htaccess</code> file. This is a good tutorial on doing that: <a href=\"http://www.htaccessbasics.com/404-custom-error-page/\" rel=\"nofollow noreferrer\">http://www.htaccessbasics.com/404-custom-error-page/</a> .</p>\n\n<p>Use their example, but set the error page to a specific page (your home page). </p>\n\n<p>Your theme may have a 404.php template that handles missing pages. But you can override that with the <code>htaccess</code> file. Make sure you first make a backup of the existing <code>htaccess</code> file, in case of problems.</p>\n" }, { "answer_id": 268970, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>You can use this code inside your <code>404.php</code> template file to safely redirect to users to homepage:</p>\n\n<pre><code>wp_safe_redirect(site_url());\nexit();\n</code></pre>\n\n<p>Use this code before every line of code in your <code>404.php</code>. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for.</p>\n\n<p>You don't have to delete the content of your <code>404.php</code> file, since every line of code after the <code>exit()</code> will be ignored.</p>\n" } ]
2017/06/03
[ "https://wordpress.stackexchange.com/questions/269016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121030/" ]
Recently I've locked myself out of my WordPress site by changing the site URL. I fixed that problem by reverting the site URL to the original one in PHPmyadmin database. But what happens now is that my website is working properly but whenever i access the back-end, only the HTML part of WordPress is loading and not the CSS part. Can anyone explain to me what is happening and how to fix this?
You can use this code inside your `404.php` template file to safely redirect to users to homepage: ``` wp_safe_redirect(site_url()); exit(); ``` Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
269,017
<p>I need to know how to write function for registering <code>activation_hook</code> and <code>deactivation_hook</code> following <strong>OOP fashion with best practices</strong>.</p> <p>I know there are some tasks we can do inside plugin activation/deactivation which is really essential in some cases like to create professional plugins.</p> <p>Thanks.</p>
[ { "answer_id": 269023, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<p>Well there I got the below ways better-</p>\n\n<pre><code>// in the main plugin file\ndefine( 'PLUGIN_BASE_FILE', __FILE__ );\n\nclass MainClass {\n public static function init() {\n register_activation_hook( PLUGIN_BASE_FILE, array( 'MainClass', 'install' ) );\n }\n\n public static function install() {\n // Do what ever you like here.\n }\n}\n\nMainClass::init();\n</code></pre>\n\n<p>Another way would be defining a class and on instantiating the class through <code>__construct</code> method create a property with the value of <code>__FILE__</code>. The call the <code>register_activation_hook</code> in the init function. Like below-</p>\n\n<pre><code>class MainClass {\n\n public $file;\n\n public function __construct( $file ) {\n $this-&gt;file = $file;\n }\n\n public function init() {\n register_activation_hook( $this-&gt;file, array( $this, 'install' ) );\n }\n\n public function install() {\n // Do what ever you like here.\n }\n}\n\n// This part must have to be done in main plugin file.\n$class = new MainClass(__FILE__);\n$class-&gt;init();\n</code></pre>\n\n<blockquote>\n <p>But, this instantiation must be done in the plugin main file.</p>\n</blockquote>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 269035, "author": "perfectionist1", "author_id": 119194, "author_profile": "https://wordpress.stackexchange.com/users/119194", "pm_score": 3, "selected": true, "text": "<p>It can be demonstrated like this way:</p>\n<p><strong>Step-1:</strong> Create a folder named <em><code>includes</code></em> (or any name you like) inside the plugin root folder. Create two new files named <code>class-responsive-slider-activator.php</code> and <code>class-responsive-slider-deactivator.php</code><br />\nNow, in <em>class-responsive-slider-activator.php</em> create a class -</p>\n<pre><code>class Responsive_Slider_Activator {\n\n public static function activate() {\n //do your codes to execute upon activation\n\n }\n}\n</code></pre>\n<p>and in <em>class-responsive-slider-deactivator.php</em> create another class-</p>\n<pre><code>class Responsive_Slider_Deactivator {\n\n public static function deactivate() {\n //do your codes to execute upon deactivation\n\n }\n}\n</code></pre>\n<p><strong>Step-2:</strong> In main plugin file create functions and register the two hooks -</p>\n<pre><code>// this code runs during plugin activation\nfunction activate_responsive_slider() { \n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-activator.php';\n\n Responsive_Slider_Activator::activate();\n}\n\nregister_activation_hook( __FILE__, 'activate_responsive_slider' );\n\n\n// this code runs during plugin deactivation\nfunction deactivate_responsive_slider() {\n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-deactivator.php';\n\n Responsive_Slider_Deactivator::activate();\n}\n\nregister_deactivation_hook( __FILE__, 'deactivate_responsive_slider' );\n</code></pre>\n<p>That's it.</p>\n<p>N.B. - As per your interest, I would like to denote that there are <em>some essential tasks</em> which can be accomplished through activation and deactivation hooks like:</p>\n<ol> \n <li> Validating other dependent plugin on activation. </li> \n <li> Creating custom database tables on activation to store data and removing tables on deactivation. </li> \n <li> Creating custom options for plugins in activation and reset in deactivation.</li> \n<li>Any other necessary task need to execute in activation. etc</li> \n</ol>\n \n" } ]
2017/06/03
[ "https://wordpress.stackexchange.com/questions/269017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119647/" ]
I need to know how to write function for registering `activation_hook` and `deactivation_hook` following **OOP fashion with best practices**. I know there are some tasks we can do inside plugin activation/deactivation which is really essential in some cases like to create professional plugins. Thanks.
It can be demonstrated like this way: **Step-1:** Create a folder named *`includes`* (or any name you like) inside the plugin root folder. Create two new files named `class-responsive-slider-activator.php` and `class-responsive-slider-deactivator.php` Now, in *class-responsive-slider-activator.php* create a class - ``` class Responsive_Slider_Activator { public static function activate() { //do your codes to execute upon activation } } ``` and in *class-responsive-slider-deactivator.php* create another class- ``` class Responsive_Slider_Deactivator { public static function deactivate() { //do your codes to execute upon deactivation } } ``` **Step-2:** In main plugin file create functions and register the two hooks - ``` // this code runs during plugin activation function activate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-activator.php'; Responsive_Slider_Activator::activate(); } register_activation_hook( __FILE__, 'activate_responsive_slider' ); // this code runs during plugin deactivation function deactivate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-deactivator.php'; Responsive_Slider_Deactivator::activate(); } register_deactivation_hook( __FILE__, 'deactivate_responsive_slider' ); ``` That's it. N.B. - As per your interest, I would like to denote that there are *some essential tasks* which can be accomplished through activation and deactivation hooks like: 1. Validating other dependent plugin on activation. 2. Creating custom database tables on activation to store data and removing tables on deactivation. 3. Creating custom options for plugins in activation and reset in deactivation. 4. Any other necessary task need to execute in activation. etc
269,037
<p>I'm very new to WP theming and I know there are several types of functions to add Widget areas.</p> <p>The following one, for example, adds a widget area dedicated for menus:</p> <pre><code># functions.php (register a new widget area): function newMenuWidgetArea() { register_nav_menus( array ( 'my-custom-menu' =&gt; __('newMenu'), 'extra-menu' =&gt; __('newMenu') ) ); } add_action('init', 'newMenuWidgetArea'); # header.php (declare widgets in the new area to appear): &lt;?php wp_nav_menu(array ( 'theme_location' =&gt; 'newMenu', 'container_class' =&gt; 'newMenu') ); ?&gt; </code></pre> <h2>The problem:</h2> <p>I don't want to add custom menus manually for example, so I don't look for a functions that add menus and their widget areas manually.</p> <p>I wish to add menus from the GUI, hence I am looking forward to use a function that create global widget areas that can serve for any purpose, and then I will add into them anything I wish directly from the GUI (menu, text area, or whatever other widget).</p> <h2>The question:</h2> <p>What is the general function to add a general-purpose/multi-purpose Widget area?</p> <p>The one I have for now creates a menu. not a widget area in which I could place widgets.</p>
[ { "answer_id": 269023, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<p>Well there I got the below ways better-</p>\n\n<pre><code>// in the main plugin file\ndefine( 'PLUGIN_BASE_FILE', __FILE__ );\n\nclass MainClass {\n public static function init() {\n register_activation_hook( PLUGIN_BASE_FILE, array( 'MainClass', 'install' ) );\n }\n\n public static function install() {\n // Do what ever you like here.\n }\n}\n\nMainClass::init();\n</code></pre>\n\n<p>Another way would be defining a class and on instantiating the class through <code>__construct</code> method create a property with the value of <code>__FILE__</code>. The call the <code>register_activation_hook</code> in the init function. Like below-</p>\n\n<pre><code>class MainClass {\n\n public $file;\n\n public function __construct( $file ) {\n $this-&gt;file = $file;\n }\n\n public function init() {\n register_activation_hook( $this-&gt;file, array( $this, 'install' ) );\n }\n\n public function install() {\n // Do what ever you like here.\n }\n}\n\n// This part must have to be done in main plugin file.\n$class = new MainClass(__FILE__);\n$class-&gt;init();\n</code></pre>\n\n<blockquote>\n <p>But, this instantiation must be done in the plugin main file.</p>\n</blockquote>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 269035, "author": "perfectionist1", "author_id": 119194, "author_profile": "https://wordpress.stackexchange.com/users/119194", "pm_score": 3, "selected": true, "text": "<p>It can be demonstrated like this way:</p>\n<p><strong>Step-1:</strong> Create a folder named <em><code>includes</code></em> (or any name you like) inside the plugin root folder. Create two new files named <code>class-responsive-slider-activator.php</code> and <code>class-responsive-slider-deactivator.php</code><br />\nNow, in <em>class-responsive-slider-activator.php</em> create a class -</p>\n<pre><code>class Responsive_Slider_Activator {\n\n public static function activate() {\n //do your codes to execute upon activation\n\n }\n}\n</code></pre>\n<p>and in <em>class-responsive-slider-deactivator.php</em> create another class-</p>\n<pre><code>class Responsive_Slider_Deactivator {\n\n public static function deactivate() {\n //do your codes to execute upon deactivation\n\n }\n}\n</code></pre>\n<p><strong>Step-2:</strong> In main plugin file create functions and register the two hooks -</p>\n<pre><code>// this code runs during plugin activation\nfunction activate_responsive_slider() { \n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-activator.php';\n\n Responsive_Slider_Activator::activate();\n}\n\nregister_activation_hook( __FILE__, 'activate_responsive_slider' );\n\n\n// this code runs during plugin deactivation\nfunction deactivate_responsive_slider() {\n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-deactivator.php';\n\n Responsive_Slider_Deactivator::activate();\n}\n\nregister_deactivation_hook( __FILE__, 'deactivate_responsive_slider' );\n</code></pre>\n<p>That's it.</p>\n<p>N.B. - As per your interest, I would like to denote that there are <em>some essential tasks</em> which can be accomplished through activation and deactivation hooks like:</p>\n<ol> \n <li> Validating other dependent plugin on activation. </li> \n <li> Creating custom database tables on activation to store data and removing tables on deactivation. </li> \n <li> Creating custom options for plugins in activation and reset in deactivation.</li> \n<li>Any other necessary task need to execute in activation. etc</li> \n</ol>\n \n" } ]
2017/06/03
[ "https://wordpress.stackexchange.com/questions/269037", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121038/" ]
I'm very new to WP theming and I know there are several types of functions to add Widget areas. The following one, for example, adds a widget area dedicated for menus: ``` # functions.php (register a new widget area): function newMenuWidgetArea() { register_nav_menus( array ( 'my-custom-menu' => __('newMenu'), 'extra-menu' => __('newMenu') ) ); } add_action('init', 'newMenuWidgetArea'); # header.php (declare widgets in the new area to appear): <?php wp_nav_menu(array ( 'theme_location' => 'newMenu', 'container_class' => 'newMenu') ); ?> ``` The problem: ------------ I don't want to add custom menus manually for example, so I don't look for a functions that add menus and their widget areas manually. I wish to add menus from the GUI, hence I am looking forward to use a function that create global widget areas that can serve for any purpose, and then I will add into them anything I wish directly from the GUI (menu, text area, or whatever other widget). The question: ------------- What is the general function to add a general-purpose/multi-purpose Widget area? The one I have for now creates a menu. not a widget area in which I could place widgets.
It can be demonstrated like this way: **Step-1:** Create a folder named *`includes`* (or any name you like) inside the plugin root folder. Create two new files named `class-responsive-slider-activator.php` and `class-responsive-slider-deactivator.php` Now, in *class-responsive-slider-activator.php* create a class - ``` class Responsive_Slider_Activator { public static function activate() { //do your codes to execute upon activation } } ``` and in *class-responsive-slider-deactivator.php* create another class- ``` class Responsive_Slider_Deactivator { public static function deactivate() { //do your codes to execute upon deactivation } } ``` **Step-2:** In main plugin file create functions and register the two hooks - ``` // this code runs during plugin activation function activate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-activator.php'; Responsive_Slider_Activator::activate(); } register_activation_hook( __FILE__, 'activate_responsive_slider' ); // this code runs during plugin deactivation function deactivate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-deactivator.php'; Responsive_Slider_Deactivator::activate(); } register_deactivation_hook( __FILE__, 'deactivate_responsive_slider' ); ``` That's it. N.B. - As per your interest, I would like to denote that there are *some essential tasks* which can be accomplished through activation and deactivation hooks like: 1. Validating other dependent plugin on activation. 2. Creating custom database tables on activation to store data and removing tables on deactivation. 3. Creating custom options for plugins in activation and reset in deactivation. 4. Any other necessary task need to execute in activation. etc
269,061
<p>I've tried a few solutions I found online on this site and many others, but most issues are with theme users and not theme developers. There is a issue with my theme that I am building it is not setting Featured Image/Thumbnail in any type of template meaning pages, post, etc... I also can't remove ones that I preset manually!</p> <p>I also noticed if I click <code>Set Featured Image</code> before the WordPress post page <strong>before</strong> it has full time to load it loads like a low bandwith window showing the media library and that <strong>allows</strong> me to select/set the image! Image of low bandwith media library below: <a href="https://i.stack.imgur.com/imUlc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/imUlc.png" alt="enter image description here"></a></p> <p>What I tried:</p> <ul> <li>Removing Plugins</li> <li>Changing themes (which did allow me to set image)</li> <li>Looking in the themes PHP for errors and reviewed documents on WP official development guide</li> </ul> <p>But one thing I did notice is that on the media library when I go in to set a featured image there is this blank attachment that shows nothing no information. It only shows when setting featured image, does not show in the Media Library page. (See Image below)</p> <p><a href="https://i.stack.imgur.com/PNZuW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PNZuW.jpg" alt="enter image description here"></a></p> <p>I've added code that may be relevant to the issue:</p> <pre><code>if ( $post_type !== 'post' ) { register_post_type( $post_type, array( 'labels' =&gt; array( 'name' =&gt; __( ucfirst( $post_type ) ), 'singular_name' =&gt; __( $post_type ), ), 'supports' =&gt; array( 'title', 'thumbnail', 'editor', 'excerpt', 'author', 'comments', 'revisions', 'custom-fields'), 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'taxonomies' =&gt; array( 'category' ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; strtolower( $post_type ), ), ) ); </code></pre> <p>The error in the console shows: <code>load-scripts.php?c=1&amp;load[]=utils,jquery-core,jquery-migrate,plupload,quicktags&amp;ver=4.7.5:5 POST admin-ajax.php 403 (Forbidden)</code></p>
[ { "answer_id": 269372, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": -1, "selected": false, "text": "<p>Add below function to function.php</p>\n\n<pre>\nif (function_exists('add_theme_support')) { add_theme_support('post-thumbnails'); }\nset_post_thumbnail_size( 100, 100, true ); // Normal post thumbnails\n</pre>\n" }, { "answer_id": 270156, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 2, "selected": false, "text": "<p>You added your own answer in the comments section:</p>\n\n<blockquote>\n <p>There is only one total php warning/error: </p>\n</blockquote>\n\n<pre><code>wp-admin/admin-header.php:9 \n- Cannot modify header information \n- headers already sent by \n(output started at \n /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php:413‌​8) \ninclude('wp-admin/edit-form-advanced.php'), \nrequire_once('wp-admin/admin-header.php'), \nheader…\n</code></pre>\n\n<p>The other half of the errors (it's two different problems you are facing) can also be found in your comments <sup><strong>1)</strong></sup></p>\n\n<blockquote>\n <p>I also get 6x of these that come up but not sure if has anything to do with the theme. </p>\n</blockquote>\n\n<pre><code>Notice: wp_enqueue_style was called incorrectly. \nScripts and styles should not be registered or enqueued until the \nwp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. \nPlease see Debugging in WordPress for more information. \n(This message was added in version 3.3.0.) \nin /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php on line 4138\n</code></pre>\n\n<p>The first problem is an <em>error</em>, which was raised in your AJAX call. The reason you do not get to see the error directly is, that —and this is what defines AJAX, the <em>A</em> is for <em>asyncronous</em>— the error was not in your current request, but in a request <em>spawned</em> by your current request, which ran in its own process in the background. Meaning: You will have to inspect the AJAX callback, the functionality that was called, to find the actual error.</p>\n\n<p>Chrome has a nice set of debugging options available: </p>\n\n<ol>\n<li>You can replay that request without loading the whole page again, without repeating the process (e.g. opening a modal) and without bringing the request to a specific state. If you have a callback failing and are in local dev mode, simply change your AJAX endpoint handler, the callback script, hit <em>Replay XHR</em> and you will execute the callback with the changed code. Logical? Yes! Overseen? Yes, often.</li>\n<li>You can open any script that runs in the background, during an AJAX request, in a separate tab. That often makes error messages visible as they printed to the screen. Same here: Easy solution, but overseen by most devs.</li>\n</ol>\n\n<p>The second problem is a <a href=\"https://en.wikipedia.org/wiki/Race_condition\" rel=\"nofollow noreferrer\">race condition</a>, a <em>timing</em> issue. A good indicator for a race condition is using a <em>slow</em> connection, something that you can for e.g. set and test in the Chrome developer tools. When things go slow, it's easier to notice and watch when one script finishes its task earlier than another one that relies on the result. If the result is not available, it will fail. When WordPress tells you, that you enqueued a script too early, then for the reason that some script, shipped with core and noted as a dependency, is not yet ready. Another thing that is noted there is that you enqueued the script before the <em>Dependency API</em> is not yet ready to <em>accept</em> enqueuing a new script. This means that WP will not take and load and output your script, making WP fail at this point.</p>\n\n<p><a href=\"https://i.stack.imgur.com/I92Cd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I92Cd.png\" alt=\"enter image description here\"></a><a href=\"https://i.stack.imgur.com/BFCiB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BFCiB.png\" alt=\"enter image description here\"></a></p>\n\n<p><sup><strong>1)</strong></sup> Please, do <strong>not</strong> hide important information in comments. <strong>Always</strong> add them as edits to your question.</p>\n" } ]
2017/06/04
[ "https://wordpress.stackexchange.com/questions/269061", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94807/" ]
I've tried a few solutions I found online on this site and many others, but most issues are with theme users and not theme developers. There is a issue with my theme that I am building it is not setting Featured Image/Thumbnail in any type of template meaning pages, post, etc... I also can't remove ones that I preset manually! I also noticed if I click `Set Featured Image` before the WordPress post page **before** it has full time to load it loads like a low bandwith window showing the media library and that **allows** me to select/set the image! Image of low bandwith media library below: [![enter image description here](https://i.stack.imgur.com/imUlc.png)](https://i.stack.imgur.com/imUlc.png) What I tried: * Removing Plugins * Changing themes (which did allow me to set image) * Looking in the themes PHP for errors and reviewed documents on WP official development guide But one thing I did notice is that on the media library when I go in to set a featured image there is this blank attachment that shows nothing no information. It only shows when setting featured image, does not show in the Media Library page. (See Image below) [![enter image description here](https://i.stack.imgur.com/PNZuW.jpg)](https://i.stack.imgur.com/PNZuW.jpg) I've added code that may be relevant to the issue: ``` if ( $post_type !== 'post' ) { register_post_type( $post_type, array( 'labels' => array( 'name' => __( ucfirst( $post_type ) ), 'singular_name' => __( $post_type ), ), 'supports' => array( 'title', 'thumbnail', 'editor', 'excerpt', 'author', 'comments', 'revisions', 'custom-fields'), 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'taxonomies' => array( 'category' ), 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => strtolower( $post_type ), ), ) ); ``` The error in the console shows: `load-scripts.php?c=1&load[]=utils,jquery-core,jquery-migrate,plupload,quicktags&ver=4.7.5:5 POST admin-ajax.php 403 (Forbidden)`
You added your own answer in the comments section: > > There is only one total php warning/error: > > > ``` wp-admin/admin-header.php:9 - Cannot modify header information - headers already sent by (output started at /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php:413‌​8) include('wp-admin/edit-form-advanced.php'), require_once('wp-admin/admin-header.php'), header… ``` The other half of the errors (it's two different problems you are facing) can also be found in your comments **1)** > > I also get 6x of these that come up but not sure if has anything to do with the theme. > > > ``` Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php on line 4138 ``` The first problem is an *error*, which was raised in your AJAX call. The reason you do not get to see the error directly is, that —and this is what defines AJAX, the *A* is for *asyncronous*— the error was not in your current request, but in a request *spawned* by your current request, which ran in its own process in the background. Meaning: You will have to inspect the AJAX callback, the functionality that was called, to find the actual error. Chrome has a nice set of debugging options available: 1. You can replay that request without loading the whole page again, without repeating the process (e.g. opening a modal) and without bringing the request to a specific state. If you have a callback failing and are in local dev mode, simply change your AJAX endpoint handler, the callback script, hit *Replay XHR* and you will execute the callback with the changed code. Logical? Yes! Overseen? Yes, often. 2. You can open any script that runs in the background, during an AJAX request, in a separate tab. That often makes error messages visible as they printed to the screen. Same here: Easy solution, but overseen by most devs. The second problem is a [race condition](https://en.wikipedia.org/wiki/Race_condition), a *timing* issue. A good indicator for a race condition is using a *slow* connection, something that you can for e.g. set and test in the Chrome developer tools. When things go slow, it's easier to notice and watch when one script finishes its task earlier than another one that relies on the result. If the result is not available, it will fail. When WordPress tells you, that you enqueued a script too early, then for the reason that some script, shipped with core and noted as a dependency, is not yet ready. Another thing that is noted there is that you enqueued the script before the *Dependency API* is not yet ready to *accept* enqueuing a new script. This means that WP will not take and load and output your script, making WP fail at this point. [![enter image description here](https://i.stack.imgur.com/I92Cd.png)](https://i.stack.imgur.com/I92Cd.png)[![enter image description here](https://i.stack.imgur.com/BFCiB.png)](https://i.stack.imgur.com/BFCiB.png) **1)** Please, do **not** hide important information in comments. **Always** add them as edits to your question.
269,071
<p>I've got my HTML Custom Nav set up and it works fine for static template. I want to convert it into wordpress navigation menu. I am totally new to wordpress and i want help to convert html menu to wordpress.</p> <p>Here is the HTML code : </p> <pre><code>&lt;div id="cs-header-menu"&gt; &lt;div class="cs-container"&gt; &lt;!-- Main navigation --&gt; &lt;div class="cs-toggle-main-navigation"&gt;&lt;i class="fa fa-bars"&gt;&lt;/i&gt;&lt;/div&gt; &lt;nav id="cs-main-navigation" class="cs-clearfix"&gt; &lt;ul class="cs-main-navigation cs-clearfix"&gt; &lt;li class="current-menu-item"&gt;&lt;a href="#"&gt;&lt;span&gt;Homepages&lt;/span&gt;&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href="index-1.html"&gt;Homepage 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index-2.html"&gt;Homepage 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index-3.html"&gt;Homepage 3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index-4.html"&gt;Homepage 4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="blog_layout_1.html"&gt;Lifestyle&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="blog_layout_1.html"&gt;Beauty&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="blog_layout_1.html"&gt;Travel&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;!-- Search icon show --&gt; &lt;div id="cs-header-menu-search-button-show"&gt;&lt;i class="fa fa-search"&gt;&lt;/i&gt;&lt;/div&gt; &lt;!-- Search icon --&gt; &lt;div id="cs-header-menu-search-form"&gt; &lt;div id="cs-header-menu-search-button-hide"&gt;&lt;i class="fa fa-close"&gt;&lt;/i&gt;&lt;/div&gt; &lt;form&gt; &lt;input type="text" placeholder="Type and press enter..."&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I don't know how to use class and ids for div, nav, ul and li, and also for sub-menu items. Would anyone please help me with this. Thanks in advance.</p>
[ { "answer_id": 269372, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": -1, "selected": false, "text": "<p>Add below function to function.php</p>\n\n<pre>\nif (function_exists('add_theme_support')) { add_theme_support('post-thumbnails'); }\nset_post_thumbnail_size( 100, 100, true ); // Normal post thumbnails\n</pre>\n" }, { "answer_id": 270156, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 2, "selected": false, "text": "<p>You added your own answer in the comments section:</p>\n\n<blockquote>\n <p>There is only one total php warning/error: </p>\n</blockquote>\n\n<pre><code>wp-admin/admin-header.php:9 \n- Cannot modify header information \n- headers already sent by \n(output started at \n /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php:413‌​8) \ninclude('wp-admin/edit-form-advanced.php'), \nrequire_once('wp-admin/admin-header.php'), \nheader…\n</code></pre>\n\n<p>The other half of the errors (it's two different problems you are facing) can also be found in your comments <sup><strong>1)</strong></sup></p>\n\n<blockquote>\n <p>I also get 6x of these that come up but not sure if has anything to do with the theme. </p>\n</blockquote>\n\n<pre><code>Notice: wp_enqueue_style was called incorrectly. \nScripts and styles should not be registered or enqueued until the \nwp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. \nPlease see Debugging in WordPress for more information. \n(This message was added in version 3.3.0.) \nin /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php on line 4138\n</code></pre>\n\n<p>The first problem is an <em>error</em>, which was raised in your AJAX call. The reason you do not get to see the error directly is, that —and this is what defines AJAX, the <em>A</em> is for <em>asyncronous</em>— the error was not in your current request, but in a request <em>spawned</em> by your current request, which ran in its own process in the background. Meaning: You will have to inspect the AJAX callback, the functionality that was called, to find the actual error.</p>\n\n<p>Chrome has a nice set of debugging options available: </p>\n\n<ol>\n<li>You can replay that request without loading the whole page again, without repeating the process (e.g. opening a modal) and without bringing the request to a specific state. If you have a callback failing and are in local dev mode, simply change your AJAX endpoint handler, the callback script, hit <em>Replay XHR</em> and you will execute the callback with the changed code. Logical? Yes! Overseen? Yes, often.</li>\n<li>You can open any script that runs in the background, during an AJAX request, in a separate tab. That often makes error messages visible as they printed to the screen. Same here: Easy solution, but overseen by most devs.</li>\n</ol>\n\n<p>The second problem is a <a href=\"https://en.wikipedia.org/wiki/Race_condition\" rel=\"nofollow noreferrer\">race condition</a>, a <em>timing</em> issue. A good indicator for a race condition is using a <em>slow</em> connection, something that you can for e.g. set and test in the Chrome developer tools. When things go slow, it's easier to notice and watch when one script finishes its task earlier than another one that relies on the result. If the result is not available, it will fail. When WordPress tells you, that you enqueued a script too early, then for the reason that some script, shipped with core and noted as a dependency, is not yet ready. Another thing that is noted there is that you enqueued the script before the <em>Dependency API</em> is not yet ready to <em>accept</em> enqueuing a new script. This means that WP will not take and load and output your script, making WP fail at this point.</p>\n\n<p><a href=\"https://i.stack.imgur.com/I92Cd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I92Cd.png\" alt=\"enter image description here\"></a><a href=\"https://i.stack.imgur.com/BFCiB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BFCiB.png\" alt=\"enter image description here\"></a></p>\n\n<p><sup><strong>1)</strong></sup> Please, do <strong>not</strong> hide important information in comments. <strong>Always</strong> add them as edits to your question.</p>\n" } ]
2017/06/04
[ "https://wordpress.stackexchange.com/questions/269071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119438/" ]
I've got my HTML Custom Nav set up and it works fine for static template. I want to convert it into wordpress navigation menu. I am totally new to wordpress and i want help to convert html menu to wordpress. Here is the HTML code : ``` <div id="cs-header-menu"> <div class="cs-container"> <!-- Main navigation --> <div class="cs-toggle-main-navigation"><i class="fa fa-bars"></i></div> <nav id="cs-main-navigation" class="cs-clearfix"> <ul class="cs-main-navigation cs-clearfix"> <li class="current-menu-item"><a href="#"><span>Homepages</span></a> <ul class="sub-menu"> <li><a href="index-1.html">Homepage 1</a></li> <li><a href="index-2.html">Homepage 2</a></li> <li><a href="index-3.html">Homepage 3</a></li> <li><a href="index-4.html">Homepage 4</a></li> </ul> </li> <li><a href="blog_layout_1.html">Lifestyle</a></li> <li><a href="blog_layout_1.html">Beauty</a></li> <li><a href="blog_layout_1.html">Travel</a></li> </ul> </nav> <!-- Search icon show --> <div id="cs-header-menu-search-button-show"><i class="fa fa-search"></i></div> <!-- Search icon --> <div id="cs-header-menu-search-form"> <div id="cs-header-menu-search-button-hide"><i class="fa fa-close"></i></div> <form> <input type="text" placeholder="Type and press enter..."> </form> </div> </div> </div> </div> ``` I don't know how to use class and ids for div, nav, ul and li, and also for sub-menu items. Would anyone please help me with this. Thanks in advance.
You added your own answer in the comments section: > > There is only one total php warning/error: > > > ``` wp-admin/admin-header.php:9 - Cannot modify header information - headers already sent by (output started at /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php:413‌​8) include('wp-admin/edit-form-advanced.php'), require_once('wp-admin/admin-header.php'), header… ``` The other half of the errors (it's two different problems you are facing) can also be found in your comments **1)** > > I also get 6x of these that come up but not sure if has anything to do with the theme. > > > ``` Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php on line 4138 ``` The first problem is an *error*, which was raised in your AJAX call. The reason you do not get to see the error directly is, that —and this is what defines AJAX, the *A* is for *asyncronous*— the error was not in your current request, but in a request *spawned* by your current request, which ran in its own process in the background. Meaning: You will have to inspect the AJAX callback, the functionality that was called, to find the actual error. Chrome has a nice set of debugging options available: 1. You can replay that request without loading the whole page again, without repeating the process (e.g. opening a modal) and without bringing the request to a specific state. If you have a callback failing and are in local dev mode, simply change your AJAX endpoint handler, the callback script, hit *Replay XHR* and you will execute the callback with the changed code. Logical? Yes! Overseen? Yes, often. 2. You can open any script that runs in the background, during an AJAX request, in a separate tab. That often makes error messages visible as they printed to the screen. Same here: Easy solution, but overseen by most devs. The second problem is a [race condition](https://en.wikipedia.org/wiki/Race_condition), a *timing* issue. A good indicator for a race condition is using a *slow* connection, something that you can for e.g. set and test in the Chrome developer tools. When things go slow, it's easier to notice and watch when one script finishes its task earlier than another one that relies on the result. If the result is not available, it will fail. When WordPress tells you, that you enqueued a script too early, then for the reason that some script, shipped with core and noted as a dependency, is not yet ready. Another thing that is noted there is that you enqueued the script before the *Dependency API* is not yet ready to *accept* enqueuing a new script. This means that WP will not take and load and output your script, making WP fail at this point. [![enter image description here](https://i.stack.imgur.com/I92Cd.png)](https://i.stack.imgur.com/I92Cd.png)[![enter image description here](https://i.stack.imgur.com/BFCiB.png)](https://i.stack.imgur.com/BFCiB.png) **1)** Please, do **not** hide important information in comments. **Always** add them as edits to your question.
269,109
<p>I'm trying to add a dynamic attribute to an existing (3rd party) shortcode. The shortcode appears several times on the same page. When I do this (in my functions.php), I can get the first shortcode to output correctly but the others don't.</p> <pre class="lang-php prettyprint-override"><code>function testOne(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student1" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode1', 'testOne'); function testTwo(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student2" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode2', 'testTwo'); function testThree(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student3" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode3', 'testThree'); </code></pre> <p>So as you can see, each shortcode is pulling the slug of the page it resides on (that's what I'm trying to achieve anyway). They're using "and" logic, and in each case, the student is different.</p> <p>Why is only the first instance working? I wish I knew more about all this stuff!</p> <p>Thanks in advance folks, Mike</p>
[ { "answer_id": 269113, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 0, "selected": false, "text": "<p>I think you're just missing some single quotes to escape out to php:</p>\n\n<pre><code>function testOne(){\n return do_shortcode('[abc abc_tax_teacher=\"' . basename(get_permalink()) . '\"]');\n}\n</code></pre>\n\n<p>otherwise the value the abc shortcode function sees is literally <code>.basename(get_permalink()).</code></p>\n\n<p><code>get_permalink()</code> relies on the global <code>$post</code> to get the current post ID. If this doesn't output the expected permalink, it's likely because <code>$post</code> has been polluted by some other query. In that case you can try <code>get_permalink( get_queried_object_id() )</code> to explicitly supply the main query's post ID.</p>\n" }, { "answer_id": 269451, "author": "macmike78", "author_id": 121089, "author_profile": "https://wordpress.stackexchange.com/users/121089", "pm_score": 0, "selected": false, "text": "<p><code>get_permalink()</code> just wasn't cutting it. Here's what I ended up doing in case anyone tries to do the same thing someday...</p>\n\n<p><code>\n// Thank you Stack Exchange, Themify &amp; Tuts+ (a little piece of each of you is in here).\nfunction managercontacts_post_lists_sc( $atts, $content = null, $tag ) {\n$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );\n$slug = $current_page->post_name;\n extract( shortcode_atts( array(\n 'type' => 'contact',\n 'orderby' => 'menu_order',\n 'order' => 'asc',\n 'style' => 'list-post',\n 'logic' => 'and'\n ), $atts ) );\n $args = '';\n switch( $tag ) {\n case \"bearings\":\n $args = 'ptb_tax_vertical=\"bearings-sealing-products-power-transmission\"';\n break;\n case \"conveyor_belt\":\n $args = 'ptb_tax_vertical=\"conveyor-belt-hose-rigging-hydraulics-service\"';\n break;\n case \"electrical\":\n $args = 'ptb_tax_vertical=\"electrical-products\"';\n break;\n case \"engineered_products\":\n $args = 'ptb_tax_vertical=\"engineered-products-services\"';\n break;\n case \"not_specified\":\n $args = 'ptb_tax_vertical=\"not-specified\"';\n break;\n case \"specialty_valves\":\n $args = 'ptb_tax_vertical=\"specialty-valves-actuators-instrumentation-service\"';\n break;\n case \"welding\":\n $args = 'ptb_tax_vertical=\"welding-products-services\"';\n break;\n }\nreturn do_shortcode('[ptb type=\"'.$type.'\" orderby=\"'.$orderby.'\" order=\"'.$order.'\" style=\"'.$style.'\" logic=\"'.$logic.'\" '.$args.' ptb_tax_manager=\"'.$slug.'\"]');\n wp_reset_query();\n}\nadd_shortcode( 'bearings', 'managercontacts_post_lists_sc' );\nadd_shortcode( 'conveyor_belt', 'managercontacts_post_lists_sc' );\nadd_shortcode( 'electrical', 'managercontacts_post_lists_sc' );\nadd_shortcode( 'engineered_products', 'managercontacts_post_lists_sc' );\nadd_shortcode( 'not_specified', 'managercontacts_lists_sc' );\nadd_shortcode( 'specialty_valves', 'managercontacts_post_lists_sc' );\nadd_shortcode( 'welding', 'managercontacts_post_lists_sc' );\n</code></p>\n\n<p>Thanks everyone who chimed in!</p>\n" }, { "answer_id": 352602, "author": "tru.d", "author_id": 167464, "author_profile": "https://wordpress.stackexchange.com/users/167464", "pm_score": 2, "selected": false, "text": "<p>I think you are having syntax errors in the shortcode like missing single quotes.Please check the code properly.</p>\n" } ]
2017/06/04
[ "https://wordpress.stackexchange.com/questions/269109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121089/" ]
I'm trying to add a dynamic attribute to an existing (3rd party) shortcode. The shortcode appears several times on the same page. When I do this (in my functions.php), I can get the first shortcode to output correctly but the others don't. ```php function testOne(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student1" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode1', 'testOne'); function testTwo(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student2" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode2', 'testTwo'); function testThree(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student3" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode3', 'testThree'); ``` So as you can see, each shortcode is pulling the slug of the page it resides on (that's what I'm trying to achieve anyway). They're using "and" logic, and in each case, the student is different. Why is only the first instance working? I wish I knew more about all this stuff! Thanks in advance folks, Mike
I think you are having syntax errors in the shortcode like missing single quotes.Please check the code properly.
269,121
<p>I've been having some issues since Google requires an API code (which I already have) to display the map on the theme page, but the thing is I'm not sure where and how it should be enqueued.</p> <p>This is what it looks like on the code:</p> <pre><code>function sano_footer_scripts() { // wp_enqueue_script( 'jquery_1.11.2_min_js', get_template_directory_uri() . '/js/jquery-1.11.2.min.js','','', true); // wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;amp;sensor=false','','', true); // wp_enqueue_script( 'jquery_autosize_js', get_template_directory_uri() . '/js/jquery.autosize.js','','', true); // wp_enqueue_script( 'jquery_smooth_scroll_min_js', get_template_directory_uri() . '/js/jquery.smooth-scroll.min.js','','', true); // wp_enqueue_script( 'selectivizr_min_js', get_template_directory_uri() . '/js/selectivizr-min.js','','', true); // wp_enqueue_script( 'jquery_watermark_min_js', get_template_directory_uri() . '/js/jquery.watermark.min.js','','', true); // wp_enqueue_script( 'read_more_js', get_template_directory_uri() . '/js/read_more.js','','', true); // wp_enqueue_script( 'jquery_mixitup_min_js', get_template_directory_uri() . '/js/jquery.mixitup.min.js','','', true); // wp_enqueue_script( 'jquery_magnific_popup_min_js', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js','','', true); // wp_enqueue_script( 'jquery_animateNumber_min_js', get_template_directory_uri() . '/js/jquery.animateNumber.min.js','','', true); // wp_enqueue_script( 'select2_min_js', get_template_directory_uri() . '/js/select2.min.js','','', true); // wp_enqueue_script( 'owl_carousel_min_js', get_template_directory_uri() . '/js/owl.carousel.min.js','','', true); // wp_enqueue_script( 'parallax_plugin_min_js', get_template_directory_uri() . '/js/parallax-plugin.min.js','','', true); // wp_enqueue_script( 'jquery_nicescroll_min_js', get_template_directory_uri() . '/js/jquery.nicescroll.min.js','','', true); // wp_enqueue_script( 'jquery_inview_min_js', get_template_directory_uri() . '/js/jquery.inview.min.js','','', true); // wp_enqueue_script( 'jquery_validate_js', get_template_directory_uri() . '/js/jquery.validate.js','','', true); // wp_enqueue_script( 'jquery_hoverdir_js', get_template_directory_uri() . '/js/jquery.hoverdir.js','','', true); //wp_enqueue_script( 'map_default_js', get_template_directory_uri() . '/js/map-default.js','','', true); //wp_enqueue_script( 'responsiveslides_min_js', get_template_directory_uri() . '/js/responsiveslides.min.js','','', true); //wp_enqueue_script( 'jquery_ui_js', get_template_directory_uri() . '/js/jquery-ui.js','','', true); //wp_enqueue_script( 'init_js', get_template_directory_uri() . '/js/init.js','','', true); //wp_enqueue_script( 'respond_src_js', get_template_directory_uri() . '/js/respond.src.js','','', true); } //add_action( 'wp_enqueue_scripts', 'sano_footer_scripts' ); </code></pre> <p>Can anyone tell me where my API code should be?</p>
[ { "answer_id": 269122, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You are using <code>wp_enqueue_scripts()</code> in the proper way, however you are enqueuing everything in the footer, and re queuing jQuery (which is not a good practice, you could use <code>jquery-migrate</code> instead).</p>\n\n<p>But in response to your concern about the place to put this code, it really doesn't matter where in the <code>functions.php</code> you put this code. The scripts will be queued anyway. Although it is nicer to have such code in the first lines of <code>functions.php</code> for readability and ease of access.</p>\n\n<p>There's nothing wrong with your code that i can see, you just need to unquote them by removing the <code>//</code> before every line.</p>\n" }, { "answer_id": 269188, "author": "jdp", "author_id": 115910, "author_profile": "https://wordpress.stackexchange.com/users/115910", "pm_score": 2, "selected": false, "text": "<p>Your API key is URL encoded as a GET variable like so:</p>\n\n<pre><code>wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;key=yourKeyHere', '', '' );\n</code></pre>\n\n<p>I don't urlencode the handle. The function/class does that. So if you're having problems getting the script to load, don't urlencode the handle.</p>\n" } ]
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269121", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121097/" ]
I've been having some issues since Google requires an API code (which I already have) to display the map on the theme page, but the thing is I'm not sure where and how it should be enqueued. This is what it looks like on the code: ``` function sano_footer_scripts() { // wp_enqueue_script( 'jquery_1.11.2_min_js', get_template_directory_uri() . '/js/jquery-1.11.2.min.js','','', true); // wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false','','', true); // wp_enqueue_script( 'jquery_autosize_js', get_template_directory_uri() . '/js/jquery.autosize.js','','', true); // wp_enqueue_script( 'jquery_smooth_scroll_min_js', get_template_directory_uri() . '/js/jquery.smooth-scroll.min.js','','', true); // wp_enqueue_script( 'selectivizr_min_js', get_template_directory_uri() . '/js/selectivizr-min.js','','', true); // wp_enqueue_script( 'jquery_watermark_min_js', get_template_directory_uri() . '/js/jquery.watermark.min.js','','', true); // wp_enqueue_script( 'read_more_js', get_template_directory_uri() . '/js/read_more.js','','', true); // wp_enqueue_script( 'jquery_mixitup_min_js', get_template_directory_uri() . '/js/jquery.mixitup.min.js','','', true); // wp_enqueue_script( 'jquery_magnific_popup_min_js', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js','','', true); // wp_enqueue_script( 'jquery_animateNumber_min_js', get_template_directory_uri() . '/js/jquery.animateNumber.min.js','','', true); // wp_enqueue_script( 'select2_min_js', get_template_directory_uri() . '/js/select2.min.js','','', true); // wp_enqueue_script( 'owl_carousel_min_js', get_template_directory_uri() . '/js/owl.carousel.min.js','','', true); // wp_enqueue_script( 'parallax_plugin_min_js', get_template_directory_uri() . '/js/parallax-plugin.min.js','','', true); // wp_enqueue_script( 'jquery_nicescroll_min_js', get_template_directory_uri() . '/js/jquery.nicescroll.min.js','','', true); // wp_enqueue_script( 'jquery_inview_min_js', get_template_directory_uri() . '/js/jquery.inview.min.js','','', true); // wp_enqueue_script( 'jquery_validate_js', get_template_directory_uri() . '/js/jquery.validate.js','','', true); // wp_enqueue_script( 'jquery_hoverdir_js', get_template_directory_uri() . '/js/jquery.hoverdir.js','','', true); //wp_enqueue_script( 'map_default_js', get_template_directory_uri() . '/js/map-default.js','','', true); //wp_enqueue_script( 'responsiveslides_min_js', get_template_directory_uri() . '/js/responsiveslides.min.js','','', true); //wp_enqueue_script( 'jquery_ui_js', get_template_directory_uri() . '/js/jquery-ui.js','','', true); //wp_enqueue_script( 'init_js', get_template_directory_uri() . '/js/init.js','','', true); //wp_enqueue_script( 'respond_src_js', get_template_directory_uri() . '/js/respond.src.js','','', true); } //add_action( 'wp_enqueue_scripts', 'sano_footer_scripts' ); ``` Can anyone tell me where my API code should be?
Your API key is URL encoded as a GET variable like so: ``` wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=yourKeyHere', '', '' ); ``` I don't urlencode the handle. The function/class does that. So if you're having problems getting the script to load, don't urlencode the handle.
269,133
<p>I am finding a way to add <em>A</em> before the menu if we are on desktop and to add <em>B</em> if we are on mobile device.</p> <p>As such, this is are my functions for <em>A</em> and <em>B</em>:</p> <pre><code>add_action( 'wp_head', 'A_function' ); function A_function() { //add A } add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function() { //add B } </code></pre> <p>I know I need to put these hooks in functions file but I don't know the way to do it, I know we can use <code>wp_is_mobile()</code>.</p> <p>How can I achieve that?</p>
[ { "answer_id": 269122, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You are using <code>wp_enqueue_scripts()</code> in the proper way, however you are enqueuing everything in the footer, and re queuing jQuery (which is not a good practice, you could use <code>jquery-migrate</code> instead).</p>\n\n<p>But in response to your concern about the place to put this code, it really doesn't matter where in the <code>functions.php</code> you put this code. The scripts will be queued anyway. Although it is nicer to have such code in the first lines of <code>functions.php</code> for readability and ease of access.</p>\n\n<p>There's nothing wrong with your code that i can see, you just need to unquote them by removing the <code>//</code> before every line.</p>\n" }, { "answer_id": 269188, "author": "jdp", "author_id": 115910, "author_profile": "https://wordpress.stackexchange.com/users/115910", "pm_score": 2, "selected": false, "text": "<p>Your API key is URL encoded as a GET variable like so:</p>\n\n<pre><code>wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;key=yourKeyHere', '', '' );\n</code></pre>\n\n<p>I don't urlencode the handle. The function/class does that. So if you're having problems getting the script to load, don't urlencode the handle.</p>\n" } ]
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269133", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102551/" ]
I am finding a way to add *A* before the menu if we are on desktop and to add *B* if we are on mobile device. As such, this is are my functions for *A* and *B*: ``` add_action( 'wp_head', 'A_function' ); function A_function() { //add A } add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function() { //add B } ``` I know I need to put these hooks in functions file but I don't know the way to do it, I know we can use `wp_is_mobile()`. How can I achieve that?
Your API key is URL encoded as a GET variable like so: ``` wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=yourKeyHere', '', '' ); ``` I don't urlencode the handle. The function/class does that. So if you're having problems getting the script to load, don't urlencode the handle.
269,153
<p>I am aware that contributors cannot publish posts, and that by design WP will not show contributors in the author dropdown list (this has been discussed here: <a href="https://wordpress.stackexchange.com/questions/168665/contributors-missing-from-author-dropdown">Contributors missing from author dropdown</a>), however I am looking for a way to force listing contributors in the dropdown menu, when an author will create content to allow him/her to start creating content for a given contributor.</p> <p>Possible?</p>
[ { "answer_id": 269209, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Here's a solution that will remove the original author meta box and replace it with a similar, but customized version which includes users with the <code>contributor</code> role.</p>\n\n<p>The logic for adding/removing the author meta box is pulled directly from the core. The meta box display callback is also cloned from the core, but we use the <code>role__in</code> parameter of <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_users/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_users()</code></a> which lets us specify which roles we want to include within the dropdown.</p>\n\n<pre><code>/**\n * Removes the original author meta box and replaces it\n * with a customized version.\n */\nadd_action( 'add_meta_boxes', 'wpse_replace_post_author_meta_box' );\nfunction wpse_replace_post_author_meta_box() {\n $post_type = get_post_type();\n $post_type_object = get_post_type_object( $post_type );\n\n if ( post_type_supports( $post_type, 'author' ) ) {\n if ( is_super_admin() || current_user_can( $post_type_object-&gt;cap-&gt;edit_others_posts ) ) {\n remove_meta_box( 'authordiv', $post_type, 'core' );\n add_meta_box( 'authordiv', __( 'Author', 'text-domain' ), 'wpse_post_author_meta_box', null, 'normal' );\n }\n }\n}\n\n/**\n * Display form field with list of authors.\n * Modified version of post_author_meta_box().\n *\n * @global int $user_ID\n *\n * @param object $post\n */\nfunction wpse_post_author_meta_box( $post ) {\n global $user_ID;\n?&gt;\n&lt;label class=\"screen-reader-text\" for=\"post_author_override\"&gt;&lt;?php _e( 'Author', 'text-domain' ); ?&gt;&lt;/label&gt;\n&lt;?php\n wp_dropdown_users( array(\n 'role__in' =&gt; [ 'administrator', 'author', 'contributor' ], // Add desired roles here.\n 'name' =&gt; 'post_author_override',\n 'selected' =&gt; empty( $post-&gt;ID ) ? $user_ID : $post-&gt;post_author,\n 'include_selected' =&gt; true,\n 'show' =&gt; 'display_name_with_login',\n ) );\n}\n</code></pre>\n" }, { "answer_id": 303225, "author": "Mateusz Paulski", "author_id": 83472, "author_profile": "https://wordpress.stackexchange.com/users/83472", "pm_score": 3, "selected": false, "text": "<p>You can just use <code>wp_dropdown_users_args</code> filter instead of creating metabox</p>\n\n<pre><code>add_filter('wp_dropdown_users_args', 'display_administrators_and_subscribers_in_author_dropdown', 10, 2);\nfunction display_administrators_and_subscribers_in_author_dropdown($query_args, $r)\n{\n if (isset($r['name']) &amp;&amp; $r['name'] === 'post_author_override') {\n if (isset($query_args['who'])) {\n unset($query_args['who']);\n }\n $query_args['role__in'] = array('administrator', 'subscriber');\n }\n return $query_args;\n}\n</code></pre>\n" } ]
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1210/" ]
I am aware that contributors cannot publish posts, and that by design WP will not show contributors in the author dropdown list (this has been discussed here: [Contributors missing from author dropdown](https://wordpress.stackexchange.com/questions/168665/contributors-missing-from-author-dropdown)), however I am looking for a way to force listing contributors in the dropdown menu, when an author will create content to allow him/her to start creating content for a given contributor. Possible?
Here's a solution that will remove the original author meta box and replace it with a similar, but customized version which includes users with the `contributor` role. The logic for adding/removing the author meta box is pulled directly from the core. The meta box display callback is also cloned from the core, but we use the `role__in` parameter of [`wp_dropdown_users()`](https://developer.wordpress.org/reference/functions/wp_dropdown_users/) which lets us specify which roles we want to include within the dropdown. ``` /** * Removes the original author meta box and replaces it * with a customized version. */ add_action( 'add_meta_boxes', 'wpse_replace_post_author_meta_box' ); function wpse_replace_post_author_meta_box() { $post_type = get_post_type(); $post_type_object = get_post_type_object( $post_type ); if ( post_type_supports( $post_type, 'author' ) ) { if ( is_super_admin() || current_user_can( $post_type_object->cap->edit_others_posts ) ) { remove_meta_box( 'authordiv', $post_type, 'core' ); add_meta_box( 'authordiv', __( 'Author', 'text-domain' ), 'wpse_post_author_meta_box', null, 'normal' ); } } } /** * Display form field with list of authors. * Modified version of post_author_meta_box(). * * @global int $user_ID * * @param object $post */ function wpse_post_author_meta_box( $post ) { global $user_ID; ?> <label class="screen-reader-text" for="post_author_override"><?php _e( 'Author', 'text-domain' ); ?></label> <?php wp_dropdown_users( array( 'role__in' => [ 'administrator', 'author', 'contributor' ], // Add desired roles here. 'name' => 'post_author_override', 'selected' => empty( $post->ID ) ? $user_ID : $post->post_author, 'include_selected' => true, 'show' => 'display_name_with_login', ) ); } ```
269,160
<p>When using a 3rd party theme, some external dependancies are enqueued using the HTTP protocol, which is fine if you don't use SSL and if the child theme is allowing complete control over all of these elements, which in this case something is either being missed by myself or enqueued through another stylesheet - I've used grep via terminal to look for where this could be happening, without luck.</p> <p>Unfortunately, I have found in some cases logic goes right out of the window when these themes have been built, and can't be forced to HTTPS through theme code (bar editting the parent theme, which defeats the point).</p> <p>I had hoped there might be a way to force all (or be selective if need be) HTTP requests through HTAccess with something along the lines of:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^fonts.googleapis\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://fonts.googleapis.com/$1 [R,L] </code></pre> <p>This does not work - unless I'm doing something glaring obviously wrong?</p> <p>Has anyone encountered this before and found a solution?</p> <p>On a side note, I thought it was best practice to enqueue without any prefix like so:</p> <pre><code>//fonts.googleapis.com </code></pre> <p>Is that correct?</p>
[ { "answer_id": 269209, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Here's a solution that will remove the original author meta box and replace it with a similar, but customized version which includes users with the <code>contributor</code> role.</p>\n\n<p>The logic for adding/removing the author meta box is pulled directly from the core. The meta box display callback is also cloned from the core, but we use the <code>role__in</code> parameter of <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_users/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_users()</code></a> which lets us specify which roles we want to include within the dropdown.</p>\n\n<pre><code>/**\n * Removes the original author meta box and replaces it\n * with a customized version.\n */\nadd_action( 'add_meta_boxes', 'wpse_replace_post_author_meta_box' );\nfunction wpse_replace_post_author_meta_box() {\n $post_type = get_post_type();\n $post_type_object = get_post_type_object( $post_type );\n\n if ( post_type_supports( $post_type, 'author' ) ) {\n if ( is_super_admin() || current_user_can( $post_type_object-&gt;cap-&gt;edit_others_posts ) ) {\n remove_meta_box( 'authordiv', $post_type, 'core' );\n add_meta_box( 'authordiv', __( 'Author', 'text-domain' ), 'wpse_post_author_meta_box', null, 'normal' );\n }\n }\n}\n\n/**\n * Display form field with list of authors.\n * Modified version of post_author_meta_box().\n *\n * @global int $user_ID\n *\n * @param object $post\n */\nfunction wpse_post_author_meta_box( $post ) {\n global $user_ID;\n?&gt;\n&lt;label class=\"screen-reader-text\" for=\"post_author_override\"&gt;&lt;?php _e( 'Author', 'text-domain' ); ?&gt;&lt;/label&gt;\n&lt;?php\n wp_dropdown_users( array(\n 'role__in' =&gt; [ 'administrator', 'author', 'contributor' ], // Add desired roles here.\n 'name' =&gt; 'post_author_override',\n 'selected' =&gt; empty( $post-&gt;ID ) ? $user_ID : $post-&gt;post_author,\n 'include_selected' =&gt; true,\n 'show' =&gt; 'display_name_with_login',\n ) );\n}\n</code></pre>\n" }, { "answer_id": 303225, "author": "Mateusz Paulski", "author_id": 83472, "author_profile": "https://wordpress.stackexchange.com/users/83472", "pm_score": 3, "selected": false, "text": "<p>You can just use <code>wp_dropdown_users_args</code> filter instead of creating metabox</p>\n\n<pre><code>add_filter('wp_dropdown_users_args', 'display_administrators_and_subscribers_in_author_dropdown', 10, 2);\nfunction display_administrators_and_subscribers_in_author_dropdown($query_args, $r)\n{\n if (isset($r['name']) &amp;&amp; $r['name'] === 'post_author_override') {\n if (isset($query_args['who'])) {\n unset($query_args['who']);\n }\n $query_args['role__in'] = array('administrator', 'subscriber');\n }\n return $query_args;\n}\n</code></pre>\n" } ]
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52020/" ]
When using a 3rd party theme, some external dependancies are enqueued using the HTTP protocol, which is fine if you don't use SSL and if the child theme is allowing complete control over all of these elements, which in this case something is either being missed by myself or enqueued through another stylesheet - I've used grep via terminal to look for where this could be happening, without luck. Unfortunately, I have found in some cases logic goes right out of the window when these themes have been built, and can't be forced to HTTPS through theme code (bar editting the parent theme, which defeats the point). I had hoped there might be a way to force all (or be selective if need be) HTTP requests through HTAccess with something along the lines of: ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^fonts.googleapis\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://fonts.googleapis.com/$1 [R,L] ``` This does not work - unless I'm doing something glaring obviously wrong? Has anyone encountered this before and found a solution? On a side note, I thought it was best practice to enqueue without any prefix like so: ``` //fonts.googleapis.com ``` Is that correct?
Here's a solution that will remove the original author meta box and replace it with a similar, but customized version which includes users with the `contributor` role. The logic for adding/removing the author meta box is pulled directly from the core. The meta box display callback is also cloned from the core, but we use the `role__in` parameter of [`wp_dropdown_users()`](https://developer.wordpress.org/reference/functions/wp_dropdown_users/) which lets us specify which roles we want to include within the dropdown. ``` /** * Removes the original author meta box and replaces it * with a customized version. */ add_action( 'add_meta_boxes', 'wpse_replace_post_author_meta_box' ); function wpse_replace_post_author_meta_box() { $post_type = get_post_type(); $post_type_object = get_post_type_object( $post_type ); if ( post_type_supports( $post_type, 'author' ) ) { if ( is_super_admin() || current_user_can( $post_type_object->cap->edit_others_posts ) ) { remove_meta_box( 'authordiv', $post_type, 'core' ); add_meta_box( 'authordiv', __( 'Author', 'text-domain' ), 'wpse_post_author_meta_box', null, 'normal' ); } } } /** * Display form field with list of authors. * Modified version of post_author_meta_box(). * * @global int $user_ID * * @param object $post */ function wpse_post_author_meta_box( $post ) { global $user_ID; ?> <label class="screen-reader-text" for="post_author_override"><?php _e( 'Author', 'text-domain' ); ?></label> <?php wp_dropdown_users( array( 'role__in' => [ 'administrator', 'author', 'contributor' ], // Add desired roles here. 'name' => 'post_author_override', 'selected' => empty( $post->ID ) ? $user_ID : $post->post_author, 'include_selected' => true, 'show' => 'display_name_with_login', ) ); } ```
269,215
<p>I am trying to add this to functions.php. In my test lab on a different site it adds the test info information fine. But on the website I am trying to add it to nothing happens. The website is running a builder thrifty theme with the latest woocommerce. Any ideas? I'm basically just wanting to add a line of text on every product page that is like a disclaimer but can't.</p> <pre><code>add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description'); function print_something_below_short_description() { echo 'Test Info.'; } </code></pre>
[ { "answer_id": 269220, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>It's possible the theme or another plugin are using that hook with a later priority. Your <code>add_action</code> would have the default of 10; try giving it a 12 or a 20, etc. and see if the text shows up.</p>\n\n<p><code>add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description', 10);</code></p>\n\n<p>You can <a href=\"https://developer.wordpress.org/reference/functions/add_action/#parameters\" rel=\"nofollow noreferrer\">read about Priority with Action Hooks here</a>.</p>\n" }, { "answer_id": 319294, "author": "Asrsagar", "author_id": 129292, "author_profile": "https://wordpress.stackexchange.com/users/129292", "pm_score": 0, "selected": false, "text": "<p>Please try this code. Hope it will work now. </p>\n\n<pre><code>function action_woocommerce_before_add_to_cart_form( ) { \n echo 'Test Info.';\n}; \nadd_action( 'woocommerce_before_add_to_cart_form', 'action_woocommerce_before_add_to_cart_form', 10, 0 );\n</code></pre>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121164/" ]
I am trying to add this to functions.php. In my test lab on a different site it adds the test info information fine. But on the website I am trying to add it to nothing happens. The website is running a builder thrifty theme with the latest woocommerce. Any ideas? I'm basically just wanting to add a line of text on every product page that is like a disclaimer but can't. ``` add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description'); function print_something_below_short_description() { echo 'Test Info.'; } ```
It's possible the theme or another plugin are using that hook with a later priority. Your `add_action` would have the default of 10; try giving it a 12 or a 20, etc. and see if the text shows up. `add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description', 10);` You can [read about Priority with Action Hooks here](https://developer.wordpress.org/reference/functions/add_action/#parameters).
269,231
<p><a href="https://i.stack.imgur.com/XQVgH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQVgH.jpg" alt="enter image description here"></a> I am writing a query for inserting data in to database but when I am printing query at output it turns into "SHOW COLUMNS from tbl_name" query. I am writing below query . But it executes like shown in image</p> <pre><code>$table_name1 = $wpdb-&gt;prefix . 'fullcontact'; $sql1=$wpdb-&gt;insert( $table_name1, array( 'status' =&gt; $status, 'request_id' =&gt; $req_id, 'likelihood' =&gt; $likelihood, 'photos' =&gt; $photos, 'chats' =&gt; $chats, 'websites' =&gt; $websites, 'fullname' =&gt; $fullname, 'familyname' =&gt; $familyname, 'givenname' =&gt; $givenname, 'organisation' =&gt; $organisation, 'normalizedlocation' =&gt; $normalizedlocation, 'city' =&gt; $city, 'state' =&gt; $state, 'country' =&gt; $country, 'age' =&gt; $age, 'agerange' =&gt; $agerange, 'gender' =&gt; $gender, 'locationgeneral' =&gt; $locationgeneral, 'socialprofiles' =&gt; $socialprofiles, 'scores' =&gt; $scores, 'topics' =&gt; $topics ) ); //exit( var_dump( $wpdb-&gt;last_query ) ); $wpdb-&gt;show_errors(); $wpdb-&gt;print_error($sql1); </code></pre>
[ { "answer_id": 269251, "author": "Roger Bücker", "author_id": 121189, "author_profile": "https://wordpress.stackexchange.com/users/121189", "pm_score": 0, "selected": false, "text": "<p>Just had the same Problem, the fix was i tried to add varchar longer than the database field can hold. When changed the DB it workled again</p>\n" }, { "answer_id": 273995, "author": "Sumurai8", "author_id": 110951, "author_profile": "https://wordpress.stackexchange.com/users/110951", "pm_score": 2, "selected": false, "text": "<p>For anyone else finding this question. Wordpress seems to do a <code>SHOW FULL COLUMNS</code> query before executing the <code>INSERT</code> query. If it determines that the <code>INSERT</code> query would fail/store bad data, for example because the given data types would not fit in the column, it does not execute the insert query at all and return false.</p>\n\n<p>Check:</p>\n\n<ul>\n<li>Have you filled all fields that can not be null and do not have a default value</li>\n<li>Does the data type for every field match the data type in the database</li>\n<li>Does the data passed to the function violate any constraints? A string cannot be longer than the maximum length of the field you are trying to put it into. An integer field has a minimum and maximum value. Unsigned integers cannot contain negative values.</li>\n</ul>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269231", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121179/" ]
[![enter image description here](https://i.stack.imgur.com/XQVgH.jpg)](https://i.stack.imgur.com/XQVgH.jpg) I am writing a query for inserting data in to database but when I am printing query at output it turns into "SHOW COLUMNS from tbl\_name" query. I am writing below query . But it executes like shown in image ``` $table_name1 = $wpdb->prefix . 'fullcontact'; $sql1=$wpdb->insert( $table_name1, array( 'status' => $status, 'request_id' => $req_id, 'likelihood' => $likelihood, 'photos' => $photos, 'chats' => $chats, 'websites' => $websites, 'fullname' => $fullname, 'familyname' => $familyname, 'givenname' => $givenname, 'organisation' => $organisation, 'normalizedlocation' => $normalizedlocation, 'city' => $city, 'state' => $state, 'country' => $country, 'age' => $age, 'agerange' => $agerange, 'gender' => $gender, 'locationgeneral' => $locationgeneral, 'socialprofiles' => $socialprofiles, 'scores' => $scores, 'topics' => $topics ) ); //exit( var_dump( $wpdb->last_query ) ); $wpdb->show_errors(); $wpdb->print_error($sql1); ```
For anyone else finding this question. Wordpress seems to do a `SHOW FULL COLUMNS` query before executing the `INSERT` query. If it determines that the `INSERT` query would fail/store bad data, for example because the given data types would not fit in the column, it does not execute the insert query at all and return false. Check: * Have you filled all fields that can not be null and do not have a default value * Does the data type for every field match the data type in the database * Does the data passed to the function violate any constraints? A string cannot be longer than the maximum length of the field you are trying to put it into. An integer field has a minimum and maximum value. Unsigned integers cannot contain negative values.
269,254
<p>I have used bootstrap nav walker but it works good with just 1 and 2 level , 3 level is not supported correctly.</p> <p>I found one here <a href="http://www.dangtrinh.com/2015/05/multilevel-drop-down-menu-in-wordpress.html" rel="nofollow noreferrer">http://www.dangtrinh.com/2015/05/multilevel-drop-down-menu-in-wordpress.html</a></p> <p>but it is not that good . </p> <p>How can I make navigation like one in blazok theme on themeforest. </p>
[ { "answer_id": 269302, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 2, "selected": true, "text": "<p>Download <a href=\"https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8\" rel=\"nofollow noreferrer\">Bootstrap nav walker file</a>.Call this file to your functions.php. Then Put this code to dynamic your nav menu:</p>\n\n<pre><code> &lt;?php\n $args = array(\n 'theme_location' =&gt; 'primary',\n 'menu' =&gt; 'Main',\n 'container' =&gt; 'false',\n 'container_class' =&gt; '',\n 'container_id' =&gt; '',\n 'menu_class' =&gt; 'nav navbar-nav navbar-right',\n 'menu_id' =&gt; '',\n 'echo' =&gt; true,\n 'fallback_cb' =&gt; 'wp_page_menu',\n 'before' =&gt; '',\n 'after' =&gt; '',\n 'link_before' =&gt; '',\n 'link_after' =&gt; '',\n 'items_wrap' =&gt; '&lt;ul id=\"%1$s\" class=\"%2$s\"&gt;%3$s&lt;/ul&gt;',\n 'depth' =&gt; 5,\n 'walker' =&gt; new my_custom_walker_nav_menu()\n );\n\n wp_nav_menu ($args);\n ?&gt;\n</code></pre>\n\n<p>You can choose the value to the 'depth' key how many depth you need</p>\n" }, { "answer_id": 269305, "author": "Daniele Squalo", "author_id": 119611, "author_profile": "https://wordpress.stackexchange.com/users/119611", "pm_score": 0, "selected": false, "text": "<p>I myself have wrote <a href=\"https://wordpress.stackexchange.com/questions/268571/output-the-aria-labelledby-parameter-for-a-nav-menu-child/\">a class</a> that can achieve this result. In any case, you need to write a <code>Walker</code> class (more precisely your class should extend <code>Walker_Nav_Menu</code>) and override the methods you need to change. Finally, include it in functions.php, inside a check for existing <code>Walker_Nav_Menu</code>. In code:</p>\n\n<pre><code>if (class_exists('Walker_Nav_Menu')) {\n class Walker_Custom_Bootstrap_Nav_Menu extends Walker_Nav_Menu {\n //Override Walker Methods\n }\n}\n</code></pre>\n\n<p>Check more at <a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/\" rel=\"nofollow noreferrer\">the code reference</a>, or study the file <code>/wp-includes/class-walker-nav-menu.php</code> which is very well commented.</p>\n\n<p>I hope i'll be helpful for you.</p>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269254", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78103/" ]
I have used bootstrap nav walker but it works good with just 1 and 2 level , 3 level is not supported correctly. I found one here <http://www.dangtrinh.com/2015/05/multilevel-drop-down-menu-in-wordpress.html> but it is not that good . How can I make navigation like one in blazok theme on themeforest.
Download [Bootstrap nav walker file](https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8).Call this file to your functions.php. Then Put this code to dynamic your nav menu: ``` <?php $args = array( 'theme_location' => 'primary', 'menu' => 'Main', 'container' => 'false', 'container_class' => '', 'container_id' => '', 'menu_class' => 'nav navbar-nav navbar-right', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 5, 'walker' => new my_custom_walker_nav_menu() ); wp_nav_menu ($args); ?> ``` You can choose the value to the 'depth' key how many depth you need
269,267
<p>I am using a plugin called AddThis on a website at: <a href="http://minionsphotography.com/" rel="nofollow noreferrer">http://minionsphotography.com/</a>. With AddThis enabled I am getting some extra P tags in-between the header and the text on the page: <code>&lt;p&gt;&lt;!-- AddThis Sharing Buttons above --&gt;&lt;/p&gt;</code>, this adds a lot of extra space and shouldn't be there. *On the homepage it's the space between the Welcome header and the slideshow image.</p> <p>Is there a function or something out there that I could use to find and remove the html comment on the page to eliminate the extra space? I use a plugin called pSquirrel to detect and remove empty P tags, but it won't remove this one (I'm guessing because pSquirrel doesn't think it's empty because of the html comment).</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 269302, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 2, "selected": true, "text": "<p>Download <a href=\"https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8\" rel=\"nofollow noreferrer\">Bootstrap nav walker file</a>.Call this file to your functions.php. Then Put this code to dynamic your nav menu:</p>\n\n<pre><code> &lt;?php\n $args = array(\n 'theme_location' =&gt; 'primary',\n 'menu' =&gt; 'Main',\n 'container' =&gt; 'false',\n 'container_class' =&gt; '',\n 'container_id' =&gt; '',\n 'menu_class' =&gt; 'nav navbar-nav navbar-right',\n 'menu_id' =&gt; '',\n 'echo' =&gt; true,\n 'fallback_cb' =&gt; 'wp_page_menu',\n 'before' =&gt; '',\n 'after' =&gt; '',\n 'link_before' =&gt; '',\n 'link_after' =&gt; '',\n 'items_wrap' =&gt; '&lt;ul id=\"%1$s\" class=\"%2$s\"&gt;%3$s&lt;/ul&gt;',\n 'depth' =&gt; 5,\n 'walker' =&gt; new my_custom_walker_nav_menu()\n );\n\n wp_nav_menu ($args);\n ?&gt;\n</code></pre>\n\n<p>You can choose the value to the 'depth' key how many depth you need</p>\n" }, { "answer_id": 269305, "author": "Daniele Squalo", "author_id": 119611, "author_profile": "https://wordpress.stackexchange.com/users/119611", "pm_score": 0, "selected": false, "text": "<p>I myself have wrote <a href=\"https://wordpress.stackexchange.com/questions/268571/output-the-aria-labelledby-parameter-for-a-nav-menu-child/\">a class</a> that can achieve this result. In any case, you need to write a <code>Walker</code> class (more precisely your class should extend <code>Walker_Nav_Menu</code>) and override the methods you need to change. Finally, include it in functions.php, inside a check for existing <code>Walker_Nav_Menu</code>. In code:</p>\n\n<pre><code>if (class_exists('Walker_Nav_Menu')) {\n class Walker_Custom_Bootstrap_Nav_Menu extends Walker_Nav_Menu {\n //Override Walker Methods\n }\n}\n</code></pre>\n\n<p>Check more at <a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/\" rel=\"nofollow noreferrer\">the code reference</a>, or study the file <code>/wp-includes/class-walker-nav-menu.php</code> which is very well commented.</p>\n\n<p>I hope i'll be helpful for you.</p>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I am using a plugin called AddThis on a website at: <http://minionsphotography.com/>. With AddThis enabled I am getting some extra P tags in-between the header and the text on the page: `<p><!-- AddThis Sharing Buttons above --></p>`, this adds a lot of extra space and shouldn't be there. \*On the homepage it's the space between the Welcome header and the slideshow image. Is there a function or something out there that I could use to find and remove the html comment on the page to eliminate the extra space? I use a plugin called pSquirrel to detect and remove empty P tags, but it won't remove this one (I'm guessing because pSquirrel doesn't think it's empty because of the html comment). Thanks, Josh
Download [Bootstrap nav walker file](https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8).Call this file to your functions.php. Then Put this code to dynamic your nav menu: ``` <?php $args = array( 'theme_location' => 'primary', 'menu' => 'Main', 'container' => 'false', 'container_class' => '', 'container_id' => '', 'menu_class' => 'nav navbar-nav navbar-right', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 5, 'walker' => new my_custom_walker_nav_menu() ); wp_nav_menu ($args); ?> ``` You can choose the value to the 'depth' key how many depth you need
269,277
<p>I can't figure how to get the ID of the custom taxonomy I'm using to loop through the custom post type called "test_values". </p> <pre><code>function prefix_load_term_posts () { $term_slug = $_POST[ 'term' ]; $args = array ( 'post_type' =&gt; 'test_values', 'posts_per_page' =&gt; 1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'test_value_category', 'field' =&gt; 'slug', 'terms' =&gt; $term_slug , ), ), ); global $post; $myposts = get_posts( $args ); ob_start (); foreach( $myposts as $post ) : setup_postdata($post); ?&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>Anyone have any suggestions how to get this taxonomy ID within the loop? </p>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n\n<pre><code>$termID = [];\n$terms = get_the_terms($post-&gt;ID, 'taxonomy');\nforeach ($terms as $term) {\n $termID[] = $term-&gt;term_id;\n}\n</code></pre>\n\n<p>or <code>get_queried_object_id()</code> </p>\n" }, { "answer_id": 301331, "author": "Chris Gatherer", "author_id": 90088, "author_profile": "https://wordpress.stackexchange.com/users/90088", "pm_score": 1, "selected": false, "text": "<p>I found the answer, what I had was way to complicated. Here's what I ended up doing that worked:</p>\n\n<pre><code>&lt;?php $terms = get_the_terms( $post-&gt;ID, 'newsroom_post_category' ); \n foreach($terms as $term) {\n $termlinks = get_term_link($term);\n echo '&lt;p class=\"post-content--cat\"&gt;';\n echo '&lt;a href=\"' . $termlinks . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;'; \n echo '&lt;/p&gt;'; }?&gt;\n</code></pre>\n\n<p>This got all the Taxonomy terms attributed to the custom post.</p>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109345/" ]
I can't figure how to get the ID of the custom taxonomy I'm using to loop through the custom post type called "test\_values". ``` function prefix_load_term_posts () { $term_slug = $_POST[ 'term' ]; $args = array ( 'post_type' => 'test_values', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'test_value_category', 'field' => 'slug', 'terms' => $term_slug , ), ), ); global $post; $myposts = get_posts( $args ); ob_start (); foreach( $myposts as $post ) : setup_postdata($post); ?> <?php endforeach; ?> ``` Anyone have any suggestions how to get this taxonomy ID within the loop?
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,291
<p>i'm using (<a href="https://codex.wordpress.org/Javascript_Reference/wp.media" rel="nofollow noreferrer">media library</a>) in my theme on Frontend.</p> <p>It's possible load only attachment of current user logged? For example, my wp user id is 55 and load only my attachment and not others by different users?</p> <p>There isn't a documentation about how work js in WP...</p>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n\n<pre><code>$termID = [];\n$terms = get_the_terms($post-&gt;ID, 'taxonomy');\nforeach ($terms as $term) {\n $termID[] = $term-&gt;term_id;\n}\n</code></pre>\n\n<p>or <code>get_queried_object_id()</code> </p>\n" }, { "answer_id": 301331, "author": "Chris Gatherer", "author_id": 90088, "author_profile": "https://wordpress.stackexchange.com/users/90088", "pm_score": 1, "selected": false, "text": "<p>I found the answer, what I had was way to complicated. Here's what I ended up doing that worked:</p>\n\n<pre><code>&lt;?php $terms = get_the_terms( $post-&gt;ID, 'newsroom_post_category' ); \n foreach($terms as $term) {\n $termlinks = get_term_link($term);\n echo '&lt;p class=\"post-content--cat\"&gt;';\n echo '&lt;a href=\"' . $termlinks . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;'; \n echo '&lt;/p&gt;'; }?&gt;\n</code></pre>\n\n<p>This got all the Taxonomy terms attributed to the custom post.</p>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110442/" ]
i'm using ([media library](https://codex.wordpress.org/Javascript_Reference/wp.media)) in my theme on Frontend. It's possible load only attachment of current user logged? For example, my wp user id is 55 and load only my attachment and not others by different users? There isn't a documentation about how work js in WP...
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,308
<p>I want to add class to caption shortcode, pulled from custom attachment field. I add the field via:</p> <pre><code>function add_img_class( $form_fields, $post ) { $form_fields['img_class_field'] = array( 'label' =&gt; __( 'Image class', 'text-domain' ), 'input' =&gt; 'text', 'value' =&gt; get_post_meta( $post-&gt;ID, 'img_class_field', true ) ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'add_img_class', 10, 2 ); function save_img_class( $post, $attachment ) { if( isset( $attachment['img_class_field'] ) ) update_post_meta( $post['ID'], 'img_class_field', $attachment['img_class_field']); return $post; } add_filter( 'attachment_fields_to_save', 'save_img_class', 10, 2 ); </code></pre> <p>How do I dynamically add "class" attribute with the field value to caption shortcode now? </p> <pre><code>[caption ... class="img_class_field"]&lt;img src...&gt;[/caption] </code></pre>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n\n<pre><code>$termID = [];\n$terms = get_the_terms($post-&gt;ID, 'taxonomy');\nforeach ($terms as $term) {\n $termID[] = $term-&gt;term_id;\n}\n</code></pre>\n\n<p>or <code>get_queried_object_id()</code> </p>\n" }, { "answer_id": 301331, "author": "Chris Gatherer", "author_id": 90088, "author_profile": "https://wordpress.stackexchange.com/users/90088", "pm_score": 1, "selected": false, "text": "<p>I found the answer, what I had was way to complicated. Here's what I ended up doing that worked:</p>\n\n<pre><code>&lt;?php $terms = get_the_terms( $post-&gt;ID, 'newsroom_post_category' ); \n foreach($terms as $term) {\n $termlinks = get_term_link($term);\n echo '&lt;p class=\"post-content--cat\"&gt;';\n echo '&lt;a href=\"' . $termlinks . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;'; \n echo '&lt;/p&gt;'; }?&gt;\n</code></pre>\n\n<p>This got all the Taxonomy terms attributed to the custom post.</p>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I want to add class to caption shortcode, pulled from custom attachment field. I add the field via: ``` function add_img_class( $form_fields, $post ) { $form_fields['img_class_field'] = array( 'label' => __( 'Image class', 'text-domain' ), 'input' => 'text', 'value' => get_post_meta( $post->ID, 'img_class_field', true ) ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'add_img_class', 10, 2 ); function save_img_class( $post, $attachment ) { if( isset( $attachment['img_class_field'] ) ) update_post_meta( $post['ID'], 'img_class_field', $attachment['img_class_field']); return $post; } add_filter( 'attachment_fields_to_save', 'save_img_class', 10, 2 ); ``` How do I dynamically add "class" attribute with the field value to caption shortcode now? ``` [caption ... class="img_class_field"]<img src...>[/caption] ```
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,316
<pre><code>&lt;p&gt; &lt;?php the_author_meta('description'); ?&gt; &lt;a href="#"&gt; Read More &lt;/a&gt; &lt;/p&gt; </code></pre> <p>I just wanted to pull authors link here "#", but I tried many options such as →</p> <pre><code>get_the_author() the_author_link() the_author_posts_link() </code></pre> <p>All of them are pulling authors name also. Any solution that will help me pull Just the authors link?</p>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n\n<pre><code>$termID = [];\n$terms = get_the_terms($post-&gt;ID, 'taxonomy');\nforeach ($terms as $term) {\n $termID[] = $term-&gt;term_id;\n}\n</code></pre>\n\n<p>or <code>get_queried_object_id()</code> </p>\n" }, { "answer_id": 301331, "author": "Chris Gatherer", "author_id": 90088, "author_profile": "https://wordpress.stackexchange.com/users/90088", "pm_score": 1, "selected": false, "text": "<p>I found the answer, what I had was way to complicated. Here's what I ended up doing that worked:</p>\n\n<pre><code>&lt;?php $terms = get_the_terms( $post-&gt;ID, 'newsroom_post_category' ); \n foreach($terms as $term) {\n $termlinks = get_term_link($term);\n echo '&lt;p class=\"post-content--cat\"&gt;';\n echo '&lt;a href=\"' . $termlinks . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;'; \n echo '&lt;/p&gt;'; }?&gt;\n</code></pre>\n\n<p>This got all the Taxonomy terms attributed to the custom post.</p>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269316", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` <p> <?php the_author_meta('description'); ?> <a href="#"> Read More </a> </p> ``` I just wanted to pull authors link here "#", but I tried many options such as → ``` get_the_author() the_author_link() the_author_posts_link() ``` All of them are pulling authors name also. Any solution that will help me pull Just the authors link?
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,323
<p>Hoping someone can help.</p> <p>I am trying to change the "Notice of Email Change" text within the email you receive when updating an email address.</p> <p>Here is what I have so far</p> <pre><code>add_filter( 'password_change_email', 'red_change_password_mail_message', 10, 3 ); function red_change_password_mail_message( $pass_change_mail, $user, $userdata ) { $new_message_txt = __( 'Hi [first_name] [last_name], This notice confirms that your email was changed on IBEW Local 353. If you did not change your email, please contact the Site Administrator at [email protected] This email has been sent to [user_email] Regards, All at IBEW Local 353' ); $pass_change_mail[ 'message' ] = $new_message_txt; return $pass_change_mail; } </code></pre> <p>As you can see I want to personalize the email message with their first and last name. What would be the best way to do this and would anyone be able to provide me with a example to start me off please.</p>
[ { "answer_id": 269326, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You're already passing a <code>$user</code> object into your function, so you should be able to substitute in <code>$user-&gt;first_name</code> and <code>$user-&gt;last_name</code>.</p>\n\n<p>So just change <code>$new_message_txt</code> to:</p>\n\n<pre><code>$new_message_txt = __('Hi ' . $user-&gt;first_name ' . ' ' . $user-&gt;last_name . ',\n...(rest of your message)\n... ' . $pass_change_mail . '... end of your message');\n</code></pre>\n" }, { "answer_id": 269331, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>The filter to use to modify the e-mail sent to a user when they change their <em>e-mail</em> address is <code>email_change_email</code>. Note that this is different from <code>password_change_email</code> which you've used in your original code. That filter allows you to modify the e-mail sent to the user when their <em>password</em> is changed.</p>\n\n<p>These two filters work similarly but it's important to make a distinction between the two. Both filters appear in <code>wp-includes/user.php</code>. </p>\n\n<ul>\n<li><p>In the code below, we use the <code>email_change_email</code> to modify the message text. The new placeholders, <code>###FIRST_NAME###</code> and <code>###LAST_NAME###</code> have been added to the code (and docs) below.</p></li>\n<li><p>The standard placeholders wherever possible in the message text, instead of hardcoding the strings.</p></li>\n<li><p>Also, a text domain was added to the customized message text. It's always a good practice to add a text domain to strings that are passed to gettext functions ( <code>__()</code>, <code>_e()</code>, etc.).</p></li>\n</ul>\n\n<p></p>\n\n<pre><code>/**\n * Filters the contents of the email sent when the user's email is changed.\n *\n * @param array $email_change_email {\n * Used to build wp_mail().\n * @type string $to The intended recipients.\n * @type string $subject The subject of the email.\n * @type string $message The content of the email.\n * The following strings have a special meaning and will get replaced dynamically:\n * - ###USERNAME### The current user's username.\n * - ###FIRST_NAME### The current user's first name.\n * - ###LAST_NAME### The current user's last name.\n * - ###ADMIN_EMAIL### The admin email in case this was unexpected.\n * - ###EMAIL### The old email.\n * - ###SITENAME### The name of the site.\n * - ###SITEURL### The URL to the site.\n * @type string $headers Headers.\n * }\n * @param array $user The original user array.\n * @param array $userdata The updated user array.\n */\nadd_filter( 'email_change_email', 'red_email_change_email', 10, 3 );\nfunction red_email_change_email( $email_change_email, $user, $userdata ) {\n\n $new_message_txt = __( 'Hi ###FIRST_NAME### ###LAST_NAME###, \n\nThis notice confirms that your email was changed on ###SITENAME###.\n\nIf you did not change your email, please contact the Site Administrator at\n###ADMIN_EMAIL###\n\nThis email has been sent to ###EMAIL###\n\nRegards,\nAll at ###SITENAME###' );\n\n $email_change_email['message'] = $new_message_txt;\n\n $email_change_email['message'] = str_replace( '###FIRST_NAME###', $user['first_name'], $email_change_email['message'] );\n $email_change_email['message'] = str_replace( '###LAST_NAME###', $user['last_name'], $email_change_email['message'] );\n\n // Debugging helper. Uncomment to turn on.\n // update_option( 'wpse_debug_email_change_email_user', $user );\n\n return $email_change_email;\n}\n</code></pre>\n\n<h2>Debugging</h2>\n\n<p>I've verified that this code does output the first and last names of the user. This information is coming from the user meta table, but it's already set up for us via the <code>$user</code> array by the core. I've manually replaced any personal info with<code>**REMOVED**</code>.</p>\n\n<p>Example e-mail:</p>\n\n<blockquote>\n<pre><code>Hi Dave (first name) Romsey (last name),\n\nThis notice confirms that your email was changed on WP Theme Testing.\n\nIf you did not change your email, please contact the Site Administrator at\n**REMOVED**\n\nThis email has been sent to **REMOVED**\n\nRegards,\nAll at WP Theme Testing\n</code></pre>\n</blockquote>\n\n<p>Here's the contents of the <code>$user</code> array:</p>\n\n<blockquote>\n<pre><code>Array\n(\n [ID] =&gt; 1\n [user_login] =&gt; dave\n [user_pass] =&gt; **REMOVED**\n [user_nicename] =&gt; dave\n [user_email] =&gt; **REMOVED**\n [user_url] =&gt; http://example.com/\n [user_registered] =&gt; 2016-02-14 05:29:13\n [user_activation_key] =&gt; \n [user_status] =&gt; 0\n [display_name] =&gt; dave\n [first_name] =&gt; Dave (first name)\n [last_name] =&gt; Romsey (last name)\n [nickname] =&gt; dave\n [description] =&gt; This is the author’s test! &lt;a href=\\\"#\\\"&gt;test link&lt;/a&gt;\n [rich_editing] =&gt; true\n [comment_shortcuts] =&gt; false\n [admin_color] =&gt; fresh\n [use_ssl] =&gt; 0\n [show_admin_bar_front] =&gt; true\n [locale] =&gt; \n)\n</code></pre>\n</blockquote>\n\n<p>Here's a function that will display the <code>$user</code> array in the console of the admin area once the debugging line has been activated in the original code above.</p>\n\n<pre><code>/**\n * Debugging helper. Outputs $user array to console in admin area. \n * This data is saved via debugging line in red_email_change_email().\n */\nadd_action( 'admin_head', 'wpse_debug_option' );\nfunction wpse_debug_option() {\n $value = get_option( 'wpse_debug_email_change_email_user' );\n echo '&lt;script&gt;console.log( ' . json_encode( $value ) . ');&lt;/script&gt;';\n}\n</code></pre>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111895/" ]
Hoping someone can help. I am trying to change the "Notice of Email Change" text within the email you receive when updating an email address. Here is what I have so far ``` add_filter( 'password_change_email', 'red_change_password_mail_message', 10, 3 ); function red_change_password_mail_message( $pass_change_mail, $user, $userdata ) { $new_message_txt = __( 'Hi [first_name] [last_name], This notice confirms that your email was changed on IBEW Local 353. If you did not change your email, please contact the Site Administrator at [email protected] This email has been sent to [user_email] Regards, All at IBEW Local 353' ); $pass_change_mail[ 'message' ] = $new_message_txt; return $pass_change_mail; } ``` As you can see I want to personalize the email message with their first and last name. What would be the best way to do this and would anyone be able to provide me with a example to start me off please.
The filter to use to modify the e-mail sent to a user when they change their *e-mail* address is `email_change_email`. Note that this is different from `password_change_email` which you've used in your original code. That filter allows you to modify the e-mail sent to the user when their *password* is changed. These two filters work similarly but it's important to make a distinction between the two. Both filters appear in `wp-includes/user.php`. * In the code below, we use the `email_change_email` to modify the message text. The new placeholders, `###FIRST_NAME###` and `###LAST_NAME###` have been added to the code (and docs) below. * The standard placeholders wherever possible in the message text, instead of hardcoding the strings. * Also, a text domain was added to the customized message text. It's always a good practice to add a text domain to strings that are passed to gettext functions ( `__()`, `_e()`, etc.). ``` /** * Filters the contents of the email sent when the user's email is changed. * * @param array $email_change_email { * Used to build wp_mail(). * @type string $to The intended recipients. * @type string $subject The subject of the email. * @type string $message The content of the email. * The following strings have a special meaning and will get replaced dynamically: * - ###USERNAME### The current user's username. * - ###FIRST_NAME### The current user's first name. * - ###LAST_NAME### The current user's last name. * - ###ADMIN_EMAIL### The admin email in case this was unexpected. * - ###EMAIL### The old email. * - ###SITENAME### The name of the site. * - ###SITEURL### The URL to the site. * @type string $headers Headers. * } * @param array $user The original user array. * @param array $userdata The updated user array. */ add_filter( 'email_change_email', 'red_email_change_email', 10, 3 ); function red_email_change_email( $email_change_email, $user, $userdata ) { $new_message_txt = __( 'Hi ###FIRST_NAME### ###LAST_NAME###, This notice confirms that your email was changed on ###SITENAME###. If you did not change your email, please contact the Site Administrator at ###ADMIN_EMAIL### This email has been sent to ###EMAIL### Regards, All at ###SITENAME###' ); $email_change_email['message'] = $new_message_txt; $email_change_email['message'] = str_replace( '###FIRST_NAME###', $user['first_name'], $email_change_email['message'] ); $email_change_email['message'] = str_replace( '###LAST_NAME###', $user['last_name'], $email_change_email['message'] ); // Debugging helper. Uncomment to turn on. // update_option( 'wpse_debug_email_change_email_user', $user ); return $email_change_email; } ``` Debugging --------- I've verified that this code does output the first and last names of the user. This information is coming from the user meta table, but it's already set up for us via the `$user` array by the core. I've manually replaced any personal info with`**REMOVED**`. Example e-mail: > > > ``` > Hi Dave (first name) Romsey (last name), > > This notice confirms that your email was changed on WP Theme Testing. > > If you did not change your email, please contact the Site Administrator at > **REMOVED** > > This email has been sent to **REMOVED** > > Regards, > All at WP Theme Testing > > ``` > > Here's the contents of the `$user` array: > > > ``` > Array > ( > [ID] => 1 > [user_login] => dave > [user_pass] => **REMOVED** > [user_nicename] => dave > [user_email] => **REMOVED** > [user_url] => http://example.com/ > [user_registered] => 2016-02-14 05:29:13 > [user_activation_key] => > [user_status] => 0 > [display_name] => dave > [first_name] => Dave (first name) > [last_name] => Romsey (last name) > [nickname] => dave > [description] => This is the author’s test! <a href=\"#\">test link</a> > [rich_editing] => true > [comment_shortcuts] => false > [admin_color] => fresh > [use_ssl] => 0 > [show_admin_bar_front] => true > [locale] => > ) > > ``` > > Here's a function that will display the `$user` array in the console of the admin area once the debugging line has been activated in the original code above. ``` /** * Debugging helper. Outputs $user array to console in admin area. * This data is saved via debugging line in red_email_change_email(). */ add_action( 'admin_head', 'wpse_debug_option' ); function wpse_debug_option() { $value = get_option( 'wpse_debug_email_change_email_user' ); echo '<script>console.log( ' . json_encode( $value ) . ');</script>'; } ```
269,336
<p>I am trying to locate the correct file to edit my internal linking anchor tags i.e.<code>&lt;a href=</code></p> <p>Can anyone point me to to the correct file? When I view the source code I see about 50 of them but I am not able to locate them in any files for editing????</p> <p>I have looked in Header, Footer, Functions and many other hooks but could not locate the anchor tags???</p>
[ { "answer_id": 269326, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You're already passing a <code>$user</code> object into your function, so you should be able to substitute in <code>$user-&gt;first_name</code> and <code>$user-&gt;last_name</code>.</p>\n\n<p>So just change <code>$new_message_txt</code> to:</p>\n\n<pre><code>$new_message_txt = __('Hi ' . $user-&gt;first_name ' . ' ' . $user-&gt;last_name . ',\n...(rest of your message)\n... ' . $pass_change_mail . '... end of your message');\n</code></pre>\n" }, { "answer_id": 269331, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>The filter to use to modify the e-mail sent to a user when they change their <em>e-mail</em> address is <code>email_change_email</code>. Note that this is different from <code>password_change_email</code> which you've used in your original code. That filter allows you to modify the e-mail sent to the user when their <em>password</em> is changed.</p>\n\n<p>These two filters work similarly but it's important to make a distinction between the two. Both filters appear in <code>wp-includes/user.php</code>. </p>\n\n<ul>\n<li><p>In the code below, we use the <code>email_change_email</code> to modify the message text. The new placeholders, <code>###FIRST_NAME###</code> and <code>###LAST_NAME###</code> have been added to the code (and docs) below.</p></li>\n<li><p>The standard placeholders wherever possible in the message text, instead of hardcoding the strings.</p></li>\n<li><p>Also, a text domain was added to the customized message text. It's always a good practice to add a text domain to strings that are passed to gettext functions ( <code>__()</code>, <code>_e()</code>, etc.).</p></li>\n</ul>\n\n<p></p>\n\n<pre><code>/**\n * Filters the contents of the email sent when the user's email is changed.\n *\n * @param array $email_change_email {\n * Used to build wp_mail().\n * @type string $to The intended recipients.\n * @type string $subject The subject of the email.\n * @type string $message The content of the email.\n * The following strings have a special meaning and will get replaced dynamically:\n * - ###USERNAME### The current user's username.\n * - ###FIRST_NAME### The current user's first name.\n * - ###LAST_NAME### The current user's last name.\n * - ###ADMIN_EMAIL### The admin email in case this was unexpected.\n * - ###EMAIL### The old email.\n * - ###SITENAME### The name of the site.\n * - ###SITEURL### The URL to the site.\n * @type string $headers Headers.\n * }\n * @param array $user The original user array.\n * @param array $userdata The updated user array.\n */\nadd_filter( 'email_change_email', 'red_email_change_email', 10, 3 );\nfunction red_email_change_email( $email_change_email, $user, $userdata ) {\n\n $new_message_txt = __( 'Hi ###FIRST_NAME### ###LAST_NAME###, \n\nThis notice confirms that your email was changed on ###SITENAME###.\n\nIf you did not change your email, please contact the Site Administrator at\n###ADMIN_EMAIL###\n\nThis email has been sent to ###EMAIL###\n\nRegards,\nAll at ###SITENAME###' );\n\n $email_change_email['message'] = $new_message_txt;\n\n $email_change_email['message'] = str_replace( '###FIRST_NAME###', $user['first_name'], $email_change_email['message'] );\n $email_change_email['message'] = str_replace( '###LAST_NAME###', $user['last_name'], $email_change_email['message'] );\n\n // Debugging helper. Uncomment to turn on.\n // update_option( 'wpse_debug_email_change_email_user', $user );\n\n return $email_change_email;\n}\n</code></pre>\n\n<h2>Debugging</h2>\n\n<p>I've verified that this code does output the first and last names of the user. This information is coming from the user meta table, but it's already set up for us via the <code>$user</code> array by the core. I've manually replaced any personal info with<code>**REMOVED**</code>.</p>\n\n<p>Example e-mail:</p>\n\n<blockquote>\n<pre><code>Hi Dave (first name) Romsey (last name),\n\nThis notice confirms that your email was changed on WP Theme Testing.\n\nIf you did not change your email, please contact the Site Administrator at\n**REMOVED**\n\nThis email has been sent to **REMOVED**\n\nRegards,\nAll at WP Theme Testing\n</code></pre>\n</blockquote>\n\n<p>Here's the contents of the <code>$user</code> array:</p>\n\n<blockquote>\n<pre><code>Array\n(\n [ID] =&gt; 1\n [user_login] =&gt; dave\n [user_pass] =&gt; **REMOVED**\n [user_nicename] =&gt; dave\n [user_email] =&gt; **REMOVED**\n [user_url] =&gt; http://example.com/\n [user_registered] =&gt; 2016-02-14 05:29:13\n [user_activation_key] =&gt; \n [user_status] =&gt; 0\n [display_name] =&gt; dave\n [first_name] =&gt; Dave (first name)\n [last_name] =&gt; Romsey (last name)\n [nickname] =&gt; dave\n [description] =&gt; This is the author’s test! &lt;a href=\\\"#\\\"&gt;test link&lt;/a&gt;\n [rich_editing] =&gt; true\n [comment_shortcuts] =&gt; false\n [admin_color] =&gt; fresh\n [use_ssl] =&gt; 0\n [show_admin_bar_front] =&gt; true\n [locale] =&gt; \n)\n</code></pre>\n</blockquote>\n\n<p>Here's a function that will display the <code>$user</code> array in the console of the admin area once the debugging line has been activated in the original code above.</p>\n\n<pre><code>/**\n * Debugging helper. Outputs $user array to console in admin area. \n * This data is saved via debugging line in red_email_change_email().\n */\nadd_action( 'admin_head', 'wpse_debug_option' );\nfunction wpse_debug_option() {\n $value = get_option( 'wpse_debug_email_change_email_user' );\n echo '&lt;script&gt;console.log( ' . json_encode( $value ) . ');&lt;/script&gt;';\n}\n</code></pre>\n" } ]
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269336", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117358/" ]
I am trying to locate the correct file to edit my internal linking anchor tags i.e.`<a href=` Can anyone point me to to the correct file? When I view the source code I see about 50 of them but I am not able to locate them in any files for editing???? I have looked in Header, Footer, Functions and many other hooks but could not locate the anchor tags???
The filter to use to modify the e-mail sent to a user when they change their *e-mail* address is `email_change_email`. Note that this is different from `password_change_email` which you've used in your original code. That filter allows you to modify the e-mail sent to the user when their *password* is changed. These two filters work similarly but it's important to make a distinction between the two. Both filters appear in `wp-includes/user.php`. * In the code below, we use the `email_change_email` to modify the message text. The new placeholders, `###FIRST_NAME###` and `###LAST_NAME###` have been added to the code (and docs) below. * The standard placeholders wherever possible in the message text, instead of hardcoding the strings. * Also, a text domain was added to the customized message text. It's always a good practice to add a text domain to strings that are passed to gettext functions ( `__()`, `_e()`, etc.). ``` /** * Filters the contents of the email sent when the user's email is changed. * * @param array $email_change_email { * Used to build wp_mail(). * @type string $to The intended recipients. * @type string $subject The subject of the email. * @type string $message The content of the email. * The following strings have a special meaning and will get replaced dynamically: * - ###USERNAME### The current user's username. * - ###FIRST_NAME### The current user's first name. * - ###LAST_NAME### The current user's last name. * - ###ADMIN_EMAIL### The admin email in case this was unexpected. * - ###EMAIL### The old email. * - ###SITENAME### The name of the site. * - ###SITEURL### The URL to the site. * @type string $headers Headers. * } * @param array $user The original user array. * @param array $userdata The updated user array. */ add_filter( 'email_change_email', 'red_email_change_email', 10, 3 ); function red_email_change_email( $email_change_email, $user, $userdata ) { $new_message_txt = __( 'Hi ###FIRST_NAME### ###LAST_NAME###, This notice confirms that your email was changed on ###SITENAME###. If you did not change your email, please contact the Site Administrator at ###ADMIN_EMAIL### This email has been sent to ###EMAIL### Regards, All at ###SITENAME###' ); $email_change_email['message'] = $new_message_txt; $email_change_email['message'] = str_replace( '###FIRST_NAME###', $user['first_name'], $email_change_email['message'] ); $email_change_email['message'] = str_replace( '###LAST_NAME###', $user['last_name'], $email_change_email['message'] ); // Debugging helper. Uncomment to turn on. // update_option( 'wpse_debug_email_change_email_user', $user ); return $email_change_email; } ``` Debugging --------- I've verified that this code does output the first and last names of the user. This information is coming from the user meta table, but it's already set up for us via the `$user` array by the core. I've manually replaced any personal info with`**REMOVED**`. Example e-mail: > > > ``` > Hi Dave (first name) Romsey (last name), > > This notice confirms that your email was changed on WP Theme Testing. > > If you did not change your email, please contact the Site Administrator at > **REMOVED** > > This email has been sent to **REMOVED** > > Regards, > All at WP Theme Testing > > ``` > > Here's the contents of the `$user` array: > > > ``` > Array > ( > [ID] => 1 > [user_login] => dave > [user_pass] => **REMOVED** > [user_nicename] => dave > [user_email] => **REMOVED** > [user_url] => http://example.com/ > [user_registered] => 2016-02-14 05:29:13 > [user_activation_key] => > [user_status] => 0 > [display_name] => dave > [first_name] => Dave (first name) > [last_name] => Romsey (last name) > [nickname] => dave > [description] => This is the author’s test! <a href=\"#\">test link</a> > [rich_editing] => true > [comment_shortcuts] => false > [admin_color] => fresh > [use_ssl] => 0 > [show_admin_bar_front] => true > [locale] => > ) > > ``` > > Here's a function that will display the `$user` array in the console of the admin area once the debugging line has been activated in the original code above. ``` /** * Debugging helper. Outputs $user array to console in admin area. * This data is saved via debugging line in red_email_change_email(). */ add_action( 'admin_head', 'wpse_debug_option' ); function wpse_debug_option() { $value = get_option( 'wpse_debug_email_change_email_user' ); echo '<script>console.log( ' . json_encode( $value ) . ');</script>'; } ```
269,358
<p>This is my careers first WordPress theme: <a href="http://codepen.trafficopedia.com/site01/" rel="nofollow noreferrer">Click Here</a>.</p> <p>If you search anything than the design breaks. Search for example this string → The Authors Name </p> <p>I could not understand why only search results breaks the design, and I remember 2 weeks back I think all this was working fine?</p> <p>Please let me Know if you need code. i think the code is not required so initially I am not posting the code.</p> <p>This is the code in <code>searchform.php</code>:</p> <pre><code>&lt;form role="search" method="get" class="search-form" action="&lt;?php echo home_url( '/' ); ?&gt;"&gt; &lt;label&gt; &lt;span class="screen-reader-text"&gt;&lt;?php echo _x( '', 'label','simplisto' ) ?&gt;&lt;/span&gt; &lt;input type="search" class="search-field" placeholder="&lt;?php echo esc_attr_x( 'Search', 'placeholder','simplisto' ) ?&gt;" value="&lt;?php echo get_search_query() ?&gt;" name="s" title="&lt;?php echo esc_attr_x( 'Search for:', 'label','simplisto' ) ?&gt;" /&gt; &lt;/label&gt; &lt;input type="submit" class="search-submit" value="&lt;?php echo esc_attr_x( 'Search', 'submit button','simplisto' ) ?&gt;" /&gt; &lt;/form&gt; </code></pre> <p>Please let me know if some other code is needed.</p>
[ { "answer_id": 269361, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Check out the markup. On the search results page, the <code>&lt;body&gt;</code> element is assigned the classes <code>search</code> and <code>search-no-results</code>.</p>\n\n<pre><code>&lt;body class=\"search search-no-results\"&gt;\n</code></pre>\n\n<p>Looking at the CSS, the styles for <code>.search</code> are intended to be used for the search input. They are working for that, but they are also being applied to the body due to the use of a weak selector:</p>\n\n<pre><code>.search {\n border: 1px solid #CCCCCC;\n padding: 5px 7px;\n /*margin-left: 15px;*/\n width: 175px;\n -webkit-transition: all .5s ease;\n -moz-transition: all .5s ease;\n transition: all .5s ease;\n /*position: absolute;*/\n right: 0;\n /*float: right;*/\n}\n</code></pre>\n\n<p>That's no good. I'd update the selector to be more specific:</p>\n\n<pre><code>input.search {\n ...\n}\n</code></pre>\n" }, { "answer_id": 269472, "author": "Elsner Technologies", "author_id": 121104, "author_profile": "https://wordpress.stackexchange.com/users/121104", "pm_score": 0, "selected": false, "text": "<p>If you search anything and design breaks so you have to check your file\n\" template-parts/content-search.php \" if there where any desing or code error is left \nAnd as alternate you can add css in in style.css</p>\n\n<p>.search-form {\n position: relative;\n} </p>\n" } ]
2017/06/07
[ "https://wordpress.stackexchange.com/questions/269358", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
This is my careers first WordPress theme: [Click Here](http://codepen.trafficopedia.com/site01/). If you search anything than the design breaks. Search for example this string → The Authors Name I could not understand why only search results breaks the design, and I remember 2 weeks back I think all this was working fine? Please let me Know if you need code. i think the code is not required so initially I am not posting the code. This is the code in `searchform.php`: ``` <form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> <label> <span class="screen-reader-text"><?php echo _x( '', 'label','simplisto' ) ?></span> <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search', 'placeholder','simplisto' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label','simplisto' ) ?>" /> </label> <input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button','simplisto' ) ?>" /> </form> ``` Please let me know if some other code is needed.
Check out the markup. On the search results page, the `<body>` element is assigned the classes `search` and `search-no-results`. ``` <body class="search search-no-results"> ``` Looking at the CSS, the styles for `.search` are intended to be used for the search input. They are working for that, but they are also being applied to the body due to the use of a weak selector: ``` .search { border: 1px solid #CCCCCC; padding: 5px 7px; /*margin-left: 15px;*/ width: 175px; -webkit-transition: all .5s ease; -moz-transition: all .5s ease; transition: all .5s ease; /*position: absolute;*/ right: 0; /*float: right;*/ } ``` That's no good. I'd update the selector to be more specific: ``` input.search { ... } ```
269,416
<p>I need to get only the custom posts which have <code>meta_key</code> <code>landing_exported</code> as <code>meta_value</code> <code>NULL</code>.</p> <p>I know that exists at least 2 custom posts in my database, but my code print "nothing found".</p> <pre><code>$args = array( 'post_type' =&gt; LANDING__CUSTOM_POST, 'meta_query' =&gt; array( array( 'key' =&gt; 'landing_exported', 'value' =&gt; false, 'type' =&gt; 'BOOLEAN' ) ) ); // query $the_query = new WP_Query( $args ); if( $the_query-&gt;have_posts() ) { // do funny things } else { echo 'nothing found'; } </code></pre>
[ { "answer_id": 269422, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>I am not sure where are you getting that <code>BOOLEAN</code> type from. I don’t think it is a type supported by <code>WP_Query</code>.</p>\n\n<p>Since meta values are always <em>stored</em> as text anyway, it is hard to guess what precisely do you mean by the <code>NULL</code> value.</p>\n\n<p>You should examine what is the actual value in database, resulting from your code, and query accordingly. It might be something like <code>'NULL'</code> string, or it might be empty string, or it might be unset altogether.</p>\n" }, { "answer_id": 269444, "author": "Picard", "author_id": 118566, "author_profile": "https://wordpress.stackexchange.com/users/118566", "pm_score": 4, "selected": true, "text": "<p>I depends if you're looking for an empty value:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; LANDING__CUSTOM_POST,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'landing_exported',\n 'value' =&gt; '',\n 'compare' =&gt; '='\n )\n )\n);\n\n// query\n$the_query = new WP_Query( $args );\n</code></pre>\n\n<p>which searches for value like: <code>meta_value = ''</code></p>\n\n<p>or if you are looking for actually a <code>NULL</code> value which is more difficult (or I couldn't find an easier solution):</p>\n\n<pre><code>add_filter( 'posts_where', 'my_modify_the_posts_where' );\nfunction lets_modify_the_posts_where( $clause = '' ) {\n global $wpdb;\n\n $clause .= \" AND \" . $wpdb-&gt;prefix . \"postmeta.meta_value IS NULL\"\n return $clause;\n}\n\n$args = array(\n 'post_type' =&gt; LANDING__CUSTOM_POST,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'landing_exported',\n 'compare' =&gt; 'EXISTS'\n )\n )\n);\n\n// query\n$the_query = new WP_Query( $args );\n\nremove_filter('posts_where', 'my_modify_the_posts_where');\n</code></pre>\n\n<p>which searches for value like: <code>meta_value IS NULL</code></p>\n" }, { "answer_id": 308173, "author": "Annesley Newholm", "author_id": 146703, "author_profile": "https://wordpress.stackexchange.com/users/146703", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter( 'posts_where', 'cb2_posts_where_allow_NULL_meta_query' );\nfunction cb2_posts_where_allow_NULL_meta_query( $where ) {\n return preg_replace(\n \"/CAST\\(([a-z0-9_]+)\\.([a-z0-9_]+) AS SIGNED\\)\\s*IN\\s*\\(([^)]*)'NULL'/mi\",\n 'CAST(\\1.\\2 AS SIGNED) IN(\\3NULL',\n $where\n );\n}\n</code></pre>\n" } ]
2017/06/07
[ "https://wordpress.stackexchange.com/questions/269416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115372/" ]
I need to get only the custom posts which have `meta_key` `landing_exported` as `meta_value` `NULL`. I know that exists at least 2 custom posts in my database, but my code print "nothing found". ``` $args = array( 'post_type' => LANDING__CUSTOM_POST, 'meta_query' => array( array( 'key' => 'landing_exported', 'value' => false, 'type' => 'BOOLEAN' ) ) ); // query $the_query = new WP_Query( $args ); if( $the_query->have_posts() ) { // do funny things } else { echo 'nothing found'; } ```
I depends if you're looking for an empty value: ``` $args = array( 'post_type' => LANDING__CUSTOM_POST, 'meta_query' => array( array( 'key' => 'landing_exported', 'value' => '', 'compare' => '=' ) ) ); // query $the_query = new WP_Query( $args ); ``` which searches for value like: `meta_value = ''` or if you are looking for actually a `NULL` value which is more difficult (or I couldn't find an easier solution): ``` add_filter( 'posts_where', 'my_modify_the_posts_where' ); function lets_modify_the_posts_where( $clause = '' ) { global $wpdb; $clause .= " AND " . $wpdb->prefix . "postmeta.meta_value IS NULL" return $clause; } $args = array( 'post_type' => LANDING__CUSTOM_POST, 'meta_query' => array( array( 'key' => 'landing_exported', 'compare' => 'EXISTS' ) ) ); // query $the_query = new WP_Query( $args ); remove_filter('posts_where', 'my_modify_the_posts_where'); ``` which searches for value like: `meta_value IS NULL`
269,439
<p>I've been using the <code>document_title_parts</code> hook to change the page title for some front end pages. However, this doesn't seem to work for the login, register and password management pages.</p> <p>How can I change the wp-login.php page <code>&lt;title&gt;</code>?</p>
[ { "answer_id": 269446, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>It looks like it's not easily accessible as it's displayed as <sup><a href=\"https://github.com/WordPress/WordPress/blob/1d34043e8cd2eead37048bc8aed379d57ff32408/wp-login.php#L69\" rel=\"nofollow noreferrer\">src</a></sup>:</p>\n\n<pre><code>&lt;title&gt;&lt;?php echo get_bloginfo( 'name', 'display' ) . $separator . $title; ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>where the separator is:</p>\n\n<pre><code> $separator = is_rtl() ? ' &amp;rsaquo; ' : ' &amp;lsaquo; ';\n</code></pre>\n\n<p>and the <code>$title</code> part comes from:</p>\n\n<pre><code>login_header( $title = 'Some title' , ... );\n</code></pre>\n\n<p>But it looks like you've already checked this out, as I see you've filed a ticket <a href=\"https://core.trac.wordpress.org/ticket/40812\" rel=\"nofollow noreferrer\">#40812</a> for an extra filter to change the <em>separator</em>.</p>\n\n<p>A workaround that comes to mind, to change the <em>separator</em>, would be to use <em>output buffering</em> hacks to replace it. </p>\n" }, { "answer_id": 269448, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<h2>The problem</h2>\n\n<p>As @birgire pointed out, changing the title text on <code>wp-login.php</code> is not easily doable, since we don't have the various title altering filters like the front end offers.</p>\n\n<h2>A solution</h2>\n\n<p>However, we can detect if we're on <code>wp-login.php</code> and then determine which action the user is taking: logging in, registering, or resetting their password. </p>\n\n<p>The <code>&lt;title&gt;</code> tag on <code>wp-login.php</code> is made up of three parts:</p>\n\n<pre><code>&lt;title&gt;&lt;?php echo get_bloginfo( 'name', 'display' ) . $separator . $title; ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>We can alter the <code>get_bloginfo( 'name', 'display' )</code> and <code>$title</code> areas but unfortunately, <code>$separator</code> can not be changed with the technique outlined here.</p>\n\n<p>The <code>option_{option_name}</code> filter ( <code>option_blogname</code> in this case ) can be used to modify the <code>get_bloginfo( 'name', 'display' )</code> part of the title.</p>\n\n<p>The <code>$title</code>, is passed to <code>__()</code> which means that we can intercept it and change it using the <code>gettext</code> filter. </p>\n\n<p><code>$title</code> is assigned <code>__('Log In')</code>, <code>__('Registration Form')</code>, and <code>__('Lost Password')</code> on the log in, register, and lost password pages respectively.</p>\n\n<h2>The code</h2>\n\n<p>This code will wire up the appropriate filters on <code>wp-login.php</code> for both of the changeable parts of the title.</p>\n\n<pre><code>/**\n * Detect if we're on wp-login.php and wire up the appropriate filters\n * based on what action being taken by the user.\n * idea via https://wordpress.stackexchange.com/a/12865/2807\n */\nadd_action( 'init', 'wpse_login_register_password_title' );\nfunction wpse_login_register_password_title() {\n\n if ( isset( $GLOBALS['pagenow'] ) &amp;&amp; $GLOBALS['pagenow'] === 'wp-login.php' ) {\n\n // Registration\n if ( ! empty( $_REQUEST['action'] ) &amp;&amp; $_REQUEST['action'] === 'register' ) {\n add_filter( 'option_blogname', 'wpse_login_page_register_blogname', 10, 1 );\n add_filter( 'gettext', 'wpse_login_page_register_title', 10, 3 );\n }\n\n // Password\n else if ( ! empty( $_REQUEST['action'] ) &amp;&amp; $_REQUEST['action'] === 'lostpassword' ) {\n add_filter( 'option_blogname', 'wpse_login_page_password_blogname', 10, 1 );\n add_filter( 'gettext', 'wpse_login_page_password_title', 10, 3 );\n }\n\n // Log in\n else {\n add_filter( 'option_blogname', 'wpse_login_page_blogname', 10, 1 );\n add_filter( 'gettext', 'wpse_login_page_title', 10, 3 );\n }\n }\n}\n</code></pre>\n\n<p>Here are the filters that will modify the blogname portion of the title tag for each of the <code>wp-login.php</code> actions.</p>\n\n<pre><code>/**\n * Change get_bloginfo( 'name', 'display' ) portion of the &lt;title&gt;'s\n * text on the wp-login.php page.\n * Immediately remove the filters so that they only run once.\n */\nfunction wpse_login_page_blogname( $value ) {\n // Log in\n remove_filter( 'option_blogname', 'wpse_login_page_blogname', 10, 1 );\n return 'This is the changed blog name for the login page.';\n}\n\nfunction wpse_login_page_register_blogname( $value ) {\n // Register\n remove_filter( 'option_blogname', 'wpse_login_page_register_blogname', 10, 1 );\n return 'This is the changed blog name for the register page.';\n}\n\nfunction wpse_login_page_password_blogname( $value ) {\n // Reset password\n remove_filter( 'option_blogname', 'wpse_login_page_password_blogname', 10, 1 );\n return 'This is the changed blog name for the password reset page.';\n}\n</code></pre>\n\n<p>Finally, these are the filters that will modify the <code>$title</code> portion of the title tag for each of the <code>wp-login.php</code> actions.</p>\n\n<pre><code>/**\n * Translate the $title portion of the &lt;title&gt;'s text on the wp-login.php page.\n * Immediately remove the filters so that they only run once.\n *\n * @param string $translation Translated text.\n * @param string $text Text to translate.\n * @param string $domain Text domain. Unique identifier for retrieving translated strings.\n *\n * @return string\n */\nfunction wpse_login_page_title( $translation, $text, $domain ) {\n // Log in\n // The 'default' text domain is reserved for the WP core.\n if ( 'default' === $domain &amp;&amp; 'Log In' === $text ) {\n $translation = 'This is the changed \"Log In\" text.';\n remove_filter( 'gettext', 'wpse_login_page_title', 10, 3 );\n }\n return $translation;\n}\n\nfunction wpse_login_page_register_title( $translation, $text, $domain ) {\n // Register\n if ( 'default' === $domain &amp;&amp; 'Registration Form' === $text ) {\n $translation = 'This is the changed \"Registration Form\" text.';\n remove_filter( 'gettext', 'wpse_login_page_register_title', 10, 3 );\n }\n return $translation;\n}\n\nfunction wpse_login_page_password_title( $translation, $text, $domain ) {\n // Reset password\n if ( 'default' === $domain &amp;&amp; 'Lost Password' === $text ) {\n $translation = 'This is the changed \"Lost Password\" text.';\n remove_filter( 'gettext', 'wpse_login_page_password_title', 10, 3 );\n }\n return $translation;\n}\n</code></pre>\n" }, { "answer_id": 290723, "author": "chop62", "author_id": 109170, "author_profile": "https://wordpress.stackexchange.com/users/109170", "pm_score": 3, "selected": false, "text": "<p>You can use this code in your themes functions.php</p>\n\n<pre><code>function custom_login_title( $login_title ) {\nreturn str_replace(array( ' &amp;lsaquo;', ' &amp;#8212; WordPress'), array( ' &amp;bull;', ' what ever you want'),$login_title );\n}\nadd_filter( 'login_title', 'custom_login_title' );\n</code></pre>\n\n<p>This will change the login.php <code>&lt;title&gt;</code> to Log In &bull; Blog Name what every you want</p>\n\n<p>You can do the same for all admin pages but it would be <code>$admin_title</code> instead of <code>$login_title</code></p>\n" } ]
2017/06/07
[ "https://wordpress.stackexchange.com/questions/269439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
I've been using the `document_title_parts` hook to change the page title for some front end pages. However, this doesn't seem to work for the login, register and password management pages. How can I change the wp-login.php page `<title>`?
It looks like it's not easily accessible as it's displayed as [src](https://github.com/WordPress/WordPress/blob/1d34043e8cd2eead37048bc8aed379d57ff32408/wp-login.php#L69): ``` <title><?php echo get_bloginfo( 'name', 'display' ) . $separator . $title; ?></title> ``` where the separator is: ``` $separator = is_rtl() ? ' &rsaquo; ' : ' &lsaquo; '; ``` and the `$title` part comes from: ``` login_header( $title = 'Some title' , ... ); ``` But it looks like you've already checked this out, as I see you've filed a ticket [#40812](https://core.trac.wordpress.org/ticket/40812) for an extra filter to change the *separator*. A workaround that comes to mind, to change the *separator*, would be to use *output buffering* hacks to replace it.
269,468
<p>I am creating a child theme. I noticed my parent theme is adding some inline CSS in its functions.php:</p> <pre><code>wp_add_inline_style( 'persona-style-css', $custom_css ); </code></pre> <p>Since I cannot change some values there, is it possible to dequeue it? I have tried to dequeue it using <code>wp_dequeue_style ('persona-style-css')</code> but it didn't really help.</p> <p>Thanks in advance.</p>
[ { "answer_id": 269471, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>If <code>wp_add_inline_css</code> is fired within an action you can use <code>remove_action</code> with the same parameters.</p>\n\n<p>You also might use <code>wp_enqueue_scripts</code> action to dequeue any scripts or styles in a proper way. But, inline style are not included in the <code>$wp_styles</code> global, you can unset them with the action <code>print_styles_array</code>, you need to know the handle name to unset it.</p>\n\n<p>Hope it gives you some hints to make it works.</p>\n" }, { "answer_id": 300603, "author": "Marcio Dias", "author_id": 47306, "author_profile": "https://wordpress.stackexchange.com/users/47306", "pm_score": 1, "selected": false, "text": "<p>Try,</p>\n\n<pre><code>function wp_force_remove_style(){\n\nadd_filter( 'print_styles_array', function($styles) {\n\n #DEBUG: Show all registered styles\n //print_r($styles);\n //die();\n\n #Set styles to remove\n $styles_to_remove = array('persona-style-css');\n\n if(is_array($styles) AND count($styles) &gt; 0){\n\n foreach($styles AS $key =&gt; $code){\n\n if(in_array($code, $styles_to_remove)){\n\n unset($styles[$key]);\n\n }\n\n }\n\n }\n\n return $styles;\n\n }); \n\n}\n\nadd_action('wp_enqueue_scripts', 'wp_force_remove_style', 99);\n</code></pre>\n\n<p>I hope this helps!</p>\n" } ]
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269468", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90981/" ]
I am creating a child theme. I noticed my parent theme is adding some inline CSS in its functions.php: ``` wp_add_inline_style( 'persona-style-css', $custom_css ); ``` Since I cannot change some values there, is it possible to dequeue it? I have tried to dequeue it using `wp_dequeue_style ('persona-style-css')` but it didn't really help. Thanks in advance.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
269,486
<p>I have added following code in my theme functions.php </p> <pre><code>function my_loginlcustomization() { wp_register_style('custom_loginstyle', get_template_directory_uri() . '/login/login-styles.css', __FILE__); wp_enqueue_style('custom_loginstyle'); } add_action('login_head', 'my_loginlcustomization'); </code></pre> <p>Custom login page:</p> <pre><code>&lt;?php /* Template Name: Login */ ?&gt; &lt;!DOCTYPE html&gt; &lt;html &gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Login Form&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php wp_login_form(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But no effect on page.</p>
[ { "answer_id": 269471, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>If <code>wp_add_inline_css</code> is fired within an action you can use <code>remove_action</code> with the same parameters.</p>\n\n<p>You also might use <code>wp_enqueue_scripts</code> action to dequeue any scripts or styles in a proper way. But, inline style are not included in the <code>$wp_styles</code> global, you can unset them with the action <code>print_styles_array</code>, you need to know the handle name to unset it.</p>\n\n<p>Hope it gives you some hints to make it works.</p>\n" }, { "answer_id": 300603, "author": "Marcio Dias", "author_id": 47306, "author_profile": "https://wordpress.stackexchange.com/users/47306", "pm_score": 1, "selected": false, "text": "<p>Try,</p>\n\n<pre><code>function wp_force_remove_style(){\n\nadd_filter( 'print_styles_array', function($styles) {\n\n #DEBUG: Show all registered styles\n //print_r($styles);\n //die();\n\n #Set styles to remove\n $styles_to_remove = array('persona-style-css');\n\n if(is_array($styles) AND count($styles) &gt; 0){\n\n foreach($styles AS $key =&gt; $code){\n\n if(in_array($code, $styles_to_remove)){\n\n unset($styles[$key]);\n\n }\n\n }\n\n }\n\n return $styles;\n\n }); \n\n}\n\nadd_action('wp_enqueue_scripts', 'wp_force_remove_style', 99);\n</code></pre>\n\n<p>I hope this helps!</p>\n" } ]
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269486", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95126/" ]
I have added following code in my theme functions.php ``` function my_loginlcustomization() { wp_register_style('custom_loginstyle', get_template_directory_uri() . '/login/login-styles.css', __FILE__); wp_enqueue_style('custom_loginstyle'); } add_action('login_head', 'my_loginlcustomization'); ``` Custom login page: ``` <?php /* Template Name: Login */ ?> <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>Login Form</title> </head> <body> <?php wp_login_form(); ?> </body> </html> ``` But no effect on page.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
269,529
<p>After reading several posts regarding post category manipulation with a given time I wanted to create a plugin that would manipulate posts after a date. My original post reference is from six years ago: "<a href="https://wordpress.stackexchange.com/questions/7571/plugin-for-changing-a-posts-category-based-on-its-post-date">Plugin for changing a post's category based on it's post date?</a>" but I've referenced several posts regarding manipulation:</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/157253/i-need-to-bulk-update-all-wordpress-posts-on-a-scheduled-time">I need to bulk update all wordpress posts on a scheduled time</a></li> <li><a href="https://wordpress.stackexchange.com/questions/268239/how-can-i-hide-posts-that-are-over-2-years-old">How can I hide posts that are over 2 years old</a></li> </ul> <p>However it isn't removing the category and adding the new one:</p> <p><strong>Code:</strong></p> <pre><code>function check_if_cat_has_reached_time() { // test if term exists and if doesn't return $test_term1 = term_exists('Uncategorized', 'category'); if ($test_term1 !== 0 &amp;&amp; $test_term1 !== null) : // $default_cat = get_term_by('id', 'Uncategorized', 'category'); $default_cat = get_cat_ID('uncategorized'); else : return; endif; // test if term exists and if doesn't return $test_term2 = term_exists('failed', 'category'); if ($test_term2 !== 0 &amp;&amp; $test_term2 !== null) : $new_cat = get_cat_ID('failed'); else : return; endif; global $post; // the Post ID $the_ID = $post-&gt;ID; // Post creation time in epoch // $post_creation = get_the_time('U',$the_ID); // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time &gt;= $post_plus_two &amp;&amp; has_category($default_cat,$the_ID)) : wp_remove_object_terms($the_ID, $default_cat, 'category'); $update_post_cat = array( 'post_category' =&gt; array($new_cat), ); wp_insert_post($update_post_cat); endif; } add_action('save_post', 'check_if_cat_has_reached_time'); </code></pre> <p>Is there a reason why <code>wp_remove_object_terms()</code> doesn't work? I used this after reading <a href="https://wordpress.stackexchange.com/questions/135602/remove-specific-category-from-a-post">Remove specific category from a post</a>. </p> <p>So my questions are:</p> <ul> <li>Am I removing the category correctly?</li> <li>Am I updating the category correctly?</li> <li>Is there better hook for manipulating posts in a plugin?</li> <li>Would there be any performance issues if this was implemented on a site that had several thousand posts?</li> </ul> <hr> <p><strong>EDIT:</strong></p> <p>The below answer I've tried to implement in my theme's function.php but it still doesn't work. I'm using a default theme with <a href="http://wptest.io/" rel="nofollow noreferrer">WP Test</a>. Before the function I make sure to create the categories with:</p> <pre><code>function create_foo_category() { wp_insert_term( 'Foo', 'category', array( 'description' =&gt; 'This is the Foo', 'slug' =&gt; 'foo' ) ); } add_action('after_setup_theme', 'create_foo_category'); </code></pre> <p>then for <code>bar</code>:</p> <pre><code>function create_bar_category() { wp_insert_term( 'Bar', 'category', array( 'description' =&gt; 'This is the bar', 'slug' =&gt; 'bar' ) ); } add_action('after_setup_theme', 'create_bar_category'); </code></pre> <p>I tried to manipulate the provided answer with:</p> <pre><code>function check_if_cat_has_reached_time() { global $post; $the_ID = $post-&gt;ID; if (!wp_is_post_revision($the_ID)) { // unhook this function so it doesn't loop infinitely remove_action('save_post', 'check_if_cat_has_reached_time'); // test if term exists and if doesn't return $check_default_cat = term_exists('Foo', 'category'); if ($check_default_cat !== 0 &amp;&amp; $check_default_cat !== null) { $default_cat = get_cat_ID('foo'); } else { return; } // test if term exists and if doesn't return $check_new_cat = term_exists('Bar', 'category'); if ($check_new_cat !== 0 &amp;&amp; $check_new_cat !== null) { $new_cat = get_cat_ID('bar'); } else { return; } // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time &gt;= $post_plus_two &amp;&amp; has_category($default_cat,$the_ID)) { wp_remove_object_terms($the_ID, $default_cat, 'category'); $args = array( 'ID' =&gt; $the_ID, 'post_category' =&gt; array($new_cat), ); wp_update_post($args); } // re-hook this function add_action('save_post', 'check_if_cat_has_reached_time'); } } add_action('publish_post', 'check_if_cat_has_reached_time'); </code></pre> <hr> <p><strong>EDIT:</strong></p> <p>After talking to a few people I think it was somewhat unclear what the intended purpose of the above was for. I'm looking to modify the posts without actually going into them with something like an event daily. After discussing this issue further I was made aware of <a href="https://developer.wordpress.org/reference/functions/wp_schedule_event/" rel="nofollow noreferrer"><code>wp_schedule_event()</code></a> that I'm going to test out and edit. </p>
[ { "answer_id": 269471, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>If <code>wp_add_inline_css</code> is fired within an action you can use <code>remove_action</code> with the same parameters.</p>\n\n<p>You also might use <code>wp_enqueue_scripts</code> action to dequeue any scripts or styles in a proper way. But, inline style are not included in the <code>$wp_styles</code> global, you can unset them with the action <code>print_styles_array</code>, you need to know the handle name to unset it.</p>\n\n<p>Hope it gives you some hints to make it works.</p>\n" }, { "answer_id": 300603, "author": "Marcio Dias", "author_id": 47306, "author_profile": "https://wordpress.stackexchange.com/users/47306", "pm_score": 1, "selected": false, "text": "<p>Try,</p>\n\n<pre><code>function wp_force_remove_style(){\n\nadd_filter( 'print_styles_array', function($styles) {\n\n #DEBUG: Show all registered styles\n //print_r($styles);\n //die();\n\n #Set styles to remove\n $styles_to_remove = array('persona-style-css');\n\n if(is_array($styles) AND count($styles) &gt; 0){\n\n foreach($styles AS $key =&gt; $code){\n\n if(in_array($code, $styles_to_remove)){\n\n unset($styles[$key]);\n\n }\n\n }\n\n }\n\n return $styles;\n\n }); \n\n}\n\nadd_action('wp_enqueue_scripts', 'wp_force_remove_style', 99);\n</code></pre>\n\n<p>I hope this helps!</p>\n" } ]
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
After reading several posts regarding post category manipulation with a given time I wanted to create a plugin that would manipulate posts after a date. My original post reference is from six years ago: "[Plugin for changing a post's category based on it's post date?](https://wordpress.stackexchange.com/questions/7571/plugin-for-changing-a-posts-category-based-on-its-post-date)" but I've referenced several posts regarding manipulation: * [I need to bulk update all wordpress posts on a scheduled time](https://wordpress.stackexchange.com/questions/157253/i-need-to-bulk-update-all-wordpress-posts-on-a-scheduled-time) * [How can I hide posts that are over 2 years old](https://wordpress.stackexchange.com/questions/268239/how-can-i-hide-posts-that-are-over-2-years-old) However it isn't removing the category and adding the new one: **Code:** ``` function check_if_cat_has_reached_time() { // test if term exists and if doesn't return $test_term1 = term_exists('Uncategorized', 'category'); if ($test_term1 !== 0 && $test_term1 !== null) : // $default_cat = get_term_by('id', 'Uncategorized', 'category'); $default_cat = get_cat_ID('uncategorized'); else : return; endif; // test if term exists and if doesn't return $test_term2 = term_exists('failed', 'category'); if ($test_term2 !== 0 && $test_term2 !== null) : $new_cat = get_cat_ID('failed'); else : return; endif; global $post; // the Post ID $the_ID = $post->ID; // Post creation time in epoch // $post_creation = get_the_time('U',$the_ID); // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time >= $post_plus_two && has_category($default_cat,$the_ID)) : wp_remove_object_terms($the_ID, $default_cat, 'category'); $update_post_cat = array( 'post_category' => array($new_cat), ); wp_insert_post($update_post_cat); endif; } add_action('save_post', 'check_if_cat_has_reached_time'); ``` Is there a reason why `wp_remove_object_terms()` doesn't work? I used this after reading [Remove specific category from a post](https://wordpress.stackexchange.com/questions/135602/remove-specific-category-from-a-post). So my questions are: * Am I removing the category correctly? * Am I updating the category correctly? * Is there better hook for manipulating posts in a plugin? * Would there be any performance issues if this was implemented on a site that had several thousand posts? --- **EDIT:** The below answer I've tried to implement in my theme's function.php but it still doesn't work. I'm using a default theme with [WP Test](http://wptest.io/). Before the function I make sure to create the categories with: ``` function create_foo_category() { wp_insert_term( 'Foo', 'category', array( 'description' => 'This is the Foo', 'slug' => 'foo' ) ); } add_action('after_setup_theme', 'create_foo_category'); ``` then for `bar`: ``` function create_bar_category() { wp_insert_term( 'Bar', 'category', array( 'description' => 'This is the bar', 'slug' => 'bar' ) ); } add_action('after_setup_theme', 'create_bar_category'); ``` I tried to manipulate the provided answer with: ``` function check_if_cat_has_reached_time() { global $post; $the_ID = $post->ID; if (!wp_is_post_revision($the_ID)) { // unhook this function so it doesn't loop infinitely remove_action('save_post', 'check_if_cat_has_reached_time'); // test if term exists and if doesn't return $check_default_cat = term_exists('Foo', 'category'); if ($check_default_cat !== 0 && $check_default_cat !== null) { $default_cat = get_cat_ID('foo'); } else { return; } // test if term exists and if doesn't return $check_new_cat = term_exists('Bar', 'category'); if ($check_new_cat !== 0 && $check_new_cat !== null) { $new_cat = get_cat_ID('bar'); } else { return; } // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time >= $post_plus_two && has_category($default_cat,$the_ID)) { wp_remove_object_terms($the_ID, $default_cat, 'category'); $args = array( 'ID' => $the_ID, 'post_category' => array($new_cat), ); wp_update_post($args); } // re-hook this function add_action('save_post', 'check_if_cat_has_reached_time'); } } add_action('publish_post', 'check_if_cat_has_reached_time'); ``` --- **EDIT:** After talking to a few people I think it was somewhat unclear what the intended purpose of the above was for. I'm looking to modify the posts without actually going into them with something like an event daily. After discussing this issue further I was made aware of [`wp_schedule_event()`](https://developer.wordpress.org/reference/functions/wp_schedule_event/) that I'm going to test out and edit.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
269,570
<p>If you have like 20 text box widgets and you are using widget logic or something to selectively display them on various pages, it gets confusing what content is in each box IF you are not using the title box. they will all then just say "text."</p> <p>Would be nice if the text widgets had a descriptive field where you can enter a title that the system will not display, but users can identify what code or text is in a particular text widget. I hope this makes sense.</p> <p>is there a way to do this that I can't see?</p> <p>I know I can enter a title and then remove all titles with CSS, but I want to display some titles.</p> <p>I feel there is a way</p>
[ { "answer_id": 269577, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>It looks like the suggestion by @DaveRomsey will solve the problem. </p>\n\n<p>Another simple idea is from a <a href=\"https://wordpress.org/plugins/remove-widget-titles/\" rel=\"nofollow noreferrer\">plugin</a> by <a href=\"https://profiles.wordpress.org/stephencronin\" rel=\"nofollow noreferrer\">Stephen Cronin</a>, (<em>I'm not related to that plugin in any way.</em>) that uses the <code>widget_title</code> filter:</p>\n\n<pre><code>add_filter( 'widget_title', function( $title ) \n{\n return '!' === mb_substr ( $title, 0, 1 ) ? '' : $title;\n} );\n</code></pre>\n\n<p>where I've adjusted the code a little bit. </p>\n\n<p>It simply removes the widget's title if it starts with <code>!</code>. </p>\n\n<p>This is handy for e.g. Text Widgets containing ads where we don't want the widget's title to display on the front-end. This approach makes it easier to manage the widgets as we can still see their titles in the backend.</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 271652, "author": "Norman Bird", "author_id": 121412, "author_profile": "https://wordpress.stackexchange.com/users/121412", "pm_score": 0, "selected": false, "text": "<p>Solution was provided in comment by user. No way to select user. I asked them to post an answer, they are not, so</p>\n\n<blockquote>\n <p>This is an annoying problem. Plugin recommendations are off-topic here\n on WPSE, but while researching the issue I found something that looks\n perfect: wordpress.org/plugins/widget-labels – Dave Romsey</p>\n</blockquote>\n" } ]
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269570", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121412/" ]
If you have like 20 text box widgets and you are using widget logic or something to selectively display them on various pages, it gets confusing what content is in each box IF you are not using the title box. they will all then just say "text." Would be nice if the text widgets had a descriptive field where you can enter a title that the system will not display, but users can identify what code or text is in a particular text widget. I hope this makes sense. is there a way to do this that I can't see? I know I can enter a title and then remove all titles with CSS, but I want to display some titles. I feel there is a way
It looks like the suggestion by @DaveRomsey will solve the problem. Another simple idea is from a [plugin](https://wordpress.org/plugins/remove-widget-titles/) by [Stephen Cronin](https://profiles.wordpress.org/stephencronin), (*I'm not related to that plugin in any way.*) that uses the `widget_title` filter: ``` add_filter( 'widget_title', function( $title ) { return '!' === mb_substr ( $title, 0, 1 ) ? '' : $title; } ); ``` where I've adjusted the code a little bit. It simply removes the widget's title if it starts with `!`. This is handy for e.g. Text Widgets containing ads where we don't want the widget's title to display on the front-end. This approach makes it easier to manage the widgets as we can still see their titles in the backend. Hope it helps!
269,579
<p>I have a post that contain images, let's say image with id 19, 12, 10. I attach image 19 first, 12 below the first and 10 as the last, and I need to retrieve them. I </p> <pre><code>$post_images = get_children( array( 'post_parent' =&gt; $id, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', )); </code></pre> <p>But i receive them sorted by id (10,12,19), how i get them with the order as i needed</p>
[ { "answer_id": 269580, "author": "Jared Cobb", "author_id": 6737, "author_profile": "https://wordpress.stackexchange.com/users/6737", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_children\" rel=\"nofollow noreferrer\">The documentation for <code>get_children</code></a> isn't great (at the time of this answer), however <code>get_children</code> is simply a wrapper for <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a>. This means that <code>orderby</code> and <code>order</code> are valid arguments for your query.</p>\n\n<p>When you ask, \"<em>how i get them with the order as i needed</em>\", is the property you wish to order them by a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">valid <code>orderby</code> value</a>? If so, your function call might look like this:</p>\n\n<pre><code>$post_images = get_children( array(\n 'post_parent' =&gt; $id,\n 'post_status' =&gt; 'inherit',\n 'post_type' =&gt; 'attachment',\n 'post_mime_type' =&gt; 'image',\n 'orderby' =&gt; 'title'\n 'order' =&gt; 'ASC',\n));\n</code></pre>\n" }, { "answer_id": 269582, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>If I'm understood, you want to get the attachment by the same order that you uploaded them. You can sort them by date, in this case:</p>\n\n<pre><code>$args = array(\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC',\n 'post_type' =&gt; 'attachment',\n 'post_mime_type' =&gt; 'image',\n 'post_parent' =&gt; $id,\n 'post_status' =&gt; 'inherit',\n);\n$posts = get_posts( $args ); \n</code></pre>\n\n<p>This will sort your attachments by their date, which would most likely be what you are looking for.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121420/" ]
I have a post that contain images, let's say image with id 19, 12, 10. I attach image 19 first, 12 below the first and 10 as the last, and I need to retrieve them. I ``` $post_images = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', )); ``` But i receive them sorted by id (10,12,19), how i get them with the order as i needed
[The documentation for `get_children`](https://codex.wordpress.org/Function_Reference/get_children) isn't great (at the time of this answer), however `get_children` is simply a wrapper for [`get_posts()`](https://codex.wordpress.org/Template_Tags/get_posts). This means that `orderby` and `order` are valid arguments for your query. When you ask, "*how i get them with the order as i needed*", is the property you wish to order them by a [valid `orderby` value](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters)? If so, your function call might look like this: ``` $post_images = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'title' 'order' => 'ASC', )); ```
269,606
<p>I have a custom div (holder for extra settings) which I need to load some specific controls from a specific section in there. I can get the controls in JavaScript but I can't generate the necessary HTML as WordPress do in sections.</p> <pre><code>wp.customize.section( 'custom_div_1' ).controls(); </code></pre> <p>It gives an array of controls but how to generate the HTML like <strong>Site title</strong> or <strong>Tagline</strong> controls in default WordPress section.</p> <p>This custom div will toggle by the left button <strong>Open extra settings</strong>.</p> <p>Screenshot for easier understanding:<a href="https://i.stack.imgur.com/scfZA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/scfZA.jpg" alt="screenshot"></a></p> <p>Any help is appreciated.</p>
[ { "answer_id": 269601, "author": "hilaryk", "author_id": 121431, "author_profile": "https://wordpress.stackexchange.com/users/121431", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/qt38l.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qt38l.jpg\" alt=\"Here is the img from my screenshot \"></a></p>\n\n<p>I still can't resolve the issue. I'm so troubled right now....</p>\n" }, { "answer_id": 269602, "author": "Jiten Gaikwad", "author_id": 120716, "author_profile": "https://wordpress.stackexchange.com/users/120716", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/Tp9QG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Tp9QG.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Here is how it looks like at my end. I have checked it in chrome, mozilla and IE as well. It look fine in all browsers.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269606", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24688/" ]
I have a custom div (holder for extra settings) which I need to load some specific controls from a specific section in there. I can get the controls in JavaScript but I can't generate the necessary HTML as WordPress do in sections. ``` wp.customize.section( 'custom_div_1' ).controls(); ``` It gives an array of controls but how to generate the HTML like **Site title** or **Tagline** controls in default WordPress section. This custom div will toggle by the left button **Open extra settings**. Screenshot for easier understanding:[![screenshot](https://i.stack.imgur.com/scfZA.jpg)](https://i.stack.imgur.com/scfZA.jpg) Any help is appreciated.
[![enter image description here](https://i.stack.imgur.com/Tp9QG.jpg)](https://i.stack.imgur.com/Tp9QG.jpg) Here is how it looks like at my end. I have checked it in chrome, mozilla and IE as well. It look fine in all browsers.
269,612
<p>I need to show the various content of a post in a modal overlay.</p> <p>How do I call Wordpress through AJAX from the front end (directly from a .js file), using the classic jQuery method?</p> <pre><code>$.ajax({ 'url' : ? data : { 'id' : 247 &lt;-- post ID } ... }); </code></pre> <p>This is NOT a PHP file, so no:</p> <p><code>admin_url('admin-ajax.php?action=my_action&amp;post_id='.$post-&gt;ID.'&amp;nonce='.$nonce);</code></p> <p>Or?</p>
[ { "answer_id": 269623, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>You can output your javascript via <code>wp_add_inline_script()</code>. This way you can set the post's id and AJAX URL before outputting the code:</p>\n\n<pre><code>wp_add_inline_script('my-js', '\n jQuery.ajax({\n \\'url\\' : '.admin_url('admin-ajax.php?action=my_action').'\n data : {\n \\'id\\' : '.get_the_ID().'\n }\n });');\n</code></pre>\n\n<p>Note that you need to hook to an existing js file to be able to add inline script, so <code>my-js</code> must be a valid enqueued script.</p>\n" }, { "answer_id": 269638, "author": "Sam", "author_id": 120374, "author_profile": "https://wordpress.stackexchange.com/users/120374", "pm_score": 1, "selected": false, "text": "<p>Add this in your functions.php file:</p>\n\n<pre><code>function my_action() {\n $the_post_id = $_POST['id'];\n\n $output = json_encode( get_post( $the_post_id ) );\n header('Content-Type: application/json');\n echo $output;\n wp_die();\n}\nadd_action('wp_ajax_my_action', 'my_action');\nadd_action('wp_ajax_nopriv_my_action', 'my_action');\n</code></pre>\n\n<p>Enqueue the scripts:</p>\n\n<pre><code>function add_scripts() {\n wp_enqueue_script( 'app', get_template_directory_uri() . '/assets/js/build.min.js', array(), '1.0.0', true );\n\n wp_localize_script( 'app', 'my_ajax_object', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) );\n}\nadd_action( 'wp_enqueue_scripts', 'add_scripts' );\n</code></pre>\n\n<p>The AJAX call from your js file:</p>\n\n<pre><code>$.ajax({\n url : my_ajax_object.ajaxurl,\n type: 'POST',\n data : {\n 'action' : 'my_action',\n 'id' : 214 // And whatever else you need to pass on ...\n }\n}).done(function ( response ) {\n\n}).fail(function ( err ) {\n\n});\n</code></pre>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120374/" ]
I need to show the various content of a post in a modal overlay. How do I call Wordpress through AJAX from the front end (directly from a .js file), using the classic jQuery method? ``` $.ajax({ 'url' : ? data : { 'id' : 247 <-- post ID } ... }); ``` This is NOT a PHP file, so no: `admin_url('admin-ajax.php?action=my_action&post_id='.$post->ID.'&nonce='.$nonce);` Or?
You can output your javascript via `wp_add_inline_script()`. This way you can set the post's id and AJAX URL before outputting the code: ``` wp_add_inline_script('my-js', ' jQuery.ajax({ \'url\' : '.admin_url('admin-ajax.php?action=my_action').' data : { \'id\' : '.get_the_ID().' } });'); ``` Note that you need to hook to an existing js file to be able to add inline script, so `my-js` must be a valid enqueued script.
269,625
<p>How can i put a youtube video on my post without show the default title from youtube?</p> <p>I tried to put this code in the theme´s functions, but not worked.</p> <pre><code>function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\"&gt;s]*)@", "src=$1$2&amp;showinfo=0&amp;rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); </code></pre> <p>Someone can help?</p> <p>Thanks</p>
[ { "answer_id": 269732, "author": "Bikash Waiba", "author_id": 121069, "author_profile": "https://wordpress.stackexchange.com/users/121069", "pm_score": -1, "selected": true, "text": "<p>Update: Try this one.. it works for youtube url in your post which is converted to iframe by wordpress. </p>\n\n<pre><code> function remove_youtube_controls($code){\n if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){\n $return = preg_replace(\"@src=(['\\\"])?([^'\\\"&gt;]*)@\", \"src=$1$2&amp;showinfo=0&amp;rel=0\", $code);\n return $return;\n }\n return $code;\n}\n\nadd_filter('embed_handler_html', 'remove_youtube_controls');\nadd_filter('embed_oembed_html', 'remove_youtube_controls');\n</code></pre>\n" }, { "answer_id": 269737, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": false, "text": "<p>This works, the OP code was odd and I've never seen that usage before or the other filter. Tested and works. This code removes Title on youtube but doesn't touch anything else since the parameters wouldn't be relevant on Vimeo for example.</p>\n\n<pre><code>function yourprefix_remove_title_youtube_oembed( $html, $url, $args ) {\n\n if( strpos( $url, 'youtu.be' ) !== false || strpos( $url, 'youtube.com' ) !== false ) :\n\n return str_replace( '?feature=oembed', '?feature=oembed&amp;amp;showinfo=0&amp;amp;rel=0', $html );\n\n else:\n\n return $html;\n\n endif;\n\n}\nadd_filter( 'embed_oembed_html', 'yourprefix_remove_title_youtube_oembed', 10, 3 );\n</code></pre>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269625", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116787/" ]
How can i put a youtube video on my post without show the default title from youtube? I tried to put this code in the theme´s functions, but not worked. ``` function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\">s]*)@", "src=$1$2&showinfo=0&rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); ``` Someone can help? Thanks
Update: Try this one.. it works for youtube url in your post which is converted to iframe by wordpress. ``` function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\">]*)@", "src=$1$2&showinfo=0&rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); ```
269,627
<p>I need to make WordPress call a specific REST endpoint when a new post is published, passing the most important post data via JSON.</p> <p>I found a plugin, HookPress, that apparently did just that by letting you configure webhooks for various events. Unfortunately it has not been updated in over 2 years and does not work with recent versions of Wordpress (>4.6).</p> <p>Is there any way I can achieve this?</p>
[ { "answer_id": 269633, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You can use a post status transition hook. In this case, it sounds like {status}_{post_type} may be the most fitting. Assuming you're talking about Posts:</p>\n\n<pre><code>&lt;?php\n/* Plugin Name: Publish to REST\nDescription: Whenever a Post is published, WP will call a REST endpoint.\n*/\nadd_action('publish_post', 'wpse_send_rest_data', 10, 2);\nfunction wpse_send_rest_data($ID, $post) {\n // Add your code to call the REST endpoint here.\n // The $post object is available so you can send post details.\n // Example: $post-&gt;post_title will give you the title.\n // $post-&gt;post_excerpt will give you an excerpt.\n // get_permalink($post) will give you the permalink.\n}\n?&gt;\n</code></pre>\n\n<p>In this case, any time a post of type \"Post\" transitions to \"Publish\" status (could be brand-new, or an update, or a scheduled post) your custom function will be executed. This type of code is probably most suited to a custom plugin, since presumably even if you change the theme at some point you'll still want to make your custom REST call.</p>\n" }, { "answer_id": 269691, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": true, "text": "<p>You don't have to write a new plugin. You can either add the code to your theme's <code>functions.php</code> file, or create a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"noreferrer\">child theme</a>. </p>\n\n<p>To wrap your data in a JSON format, you can use the <code>json_encode</code> function. Hook into the post when it's published, and send the data. In the following function, i will send the post's title, excerpt and featured image URL to the endpoint.</p>\n\n<pre><code>add_action('publish_post', 'call_the_endpoint',10,2);\nfunction call_the_endpoint($post_id, $post){\n // Define an empty array\n $data = array();\n // Store the title into the array\n $data['title'] = get_the_title();\n // If there is a post thumbnail, get the link\n if (has_post_thumbnail()) {\n $data['thumbnail'] = get_the_post_thumbnail_url( get_the_ID(),'thumbnail' );\n }\n // Get the excerpt and save it into the array\n $data['excerpt'] = get_the_excerpt();\n // Encode the data to be sent\n $json_data = json_encode($data);\n // Initiate the cURL\n $url = curl_init('YOUR API URL HERE');\n curl_setopt($url, CURLOPT_CUSTOMREQUEST, \"POST\");\n curl_setopt($url, CURLOPT_POSTFIELDS, $json_data);\n curl_setopt($url, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($url, CURLOPT_HTTPHEADER, array(\n 'Content-Type: application/json',\n 'Content-Length: ' . strlen($json_data))\n );\n // The results of our request, to use later if we want.\n $result = curl_exec($url);\n}\n</code></pre>\n\n<p>It would be possible to write an accurate answer if you could provide more information about your API and how you interact with it. However this was a simple example for you to know how to use the <code>publish_post</code> hook to achieve what you are looking for.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121459/" ]
I need to make WordPress call a specific REST endpoint when a new post is published, passing the most important post data via JSON. I found a plugin, HookPress, that apparently did just that by letting you configure webhooks for various events. Unfortunately it has not been updated in over 2 years and does not work with recent versions of Wordpress (>4.6). Is there any way I can achieve this?
You don't have to write a new plugin. You can either add the code to your theme's `functions.php` file, or create a [child theme](https://codex.wordpress.org/Child_Themes). To wrap your data in a JSON format, you can use the `json_encode` function. Hook into the post when it's published, and send the data. In the following function, i will send the post's title, excerpt and featured image URL to the endpoint. ``` add_action('publish_post', 'call_the_endpoint',10,2); function call_the_endpoint($post_id, $post){ // Define an empty array $data = array(); // Store the title into the array $data['title'] = get_the_title(); // If there is a post thumbnail, get the link if (has_post_thumbnail()) { $data['thumbnail'] = get_the_post_thumbnail_url( get_the_ID(),'thumbnail' ); } // Get the excerpt and save it into the array $data['excerpt'] = get_the_excerpt(); // Encode the data to be sent $json_data = json_encode($data); // Initiate the cURL $url = curl_init('YOUR API URL HERE'); curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($url, CURLOPT_POSTFIELDS, $json_data); curl_setopt($url, CURLOPT_RETURNTRANSFER, true); curl_setopt($url, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json_data)) ); // The results of our request, to use later if we want. $result = curl_exec($url); } ``` It would be possible to write an accurate answer if you could provide more information about your API and how you interact with it. However this was a simple example for you to know how to use the `publish_post` hook to achieve what you are looking for.
269,629
<p>I'm stuck right now. For my project, I have to create login not using WP user system but another system. </p> <p>Now, when with my system API login, I created some cookie but, obviously I didn't also create wp cookie for user logged in. So, I want to allow a user upload with media library of WP (<a href="https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/" rel="nofollow noreferrer">link of WP codex</a>) some files, but it doesn't work.</p> <p>I have also edited (temporary core wordpress change) admin-ajax.php for forcing it to create post attachment also in the case of user not logged in:</p> <pre><code>if ( is_user_logged_in() ) { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } else { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } </code></pre> <p>but async-upload.php responds with 302 and I don't know how to go forward.</p> <p><strong><em>UPDATE</em></strong>:<br> the problem is the same of this user: <a href="https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/" rel="nofollow noreferrer">click here</a></p> <p>I tried to use wp_ajax_my_action and wp_ajax_nopriv_myaction but nothing change. My need is allow to not logged user in WP to upload attachment, and assign this attachment with his ID author (for example, 12345), cause each user must see only yours media (i will use pre_get_posts and yet work). </p>
[ { "answer_id": 269640, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes.</p>\n\n<p>Second, you may want to peruse this <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">Codex page</a> on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in):</p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action' );\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action' );\n</code></pre>\n\n<p>The <code>my_action</code> function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX).</p>\n\n<p>Hope this starts you down the right path.</p>\n" }, { "answer_id": 365932, "author": "Farhan Ahmed", "author_id": 187484, "author_profile": "https://wordpress.stackexchange.com/users/187484", "pm_score": 0, "selected": false, "text": "<p>I was facing the same problem and finally got a solution.. As non login user don't have any role.. If we make a user role and assign a role to the every visitor we can solve the problem of uploading files as uploading file is a capability we can add to user role...</p>\n\n<p>I tried the following...</p>\n\n<pre><code>add_role( 'frontend_editor','Front-End Editor', array( 'upload_files' =&gt; true) );\n\nif ( is_user_logged_in() ) { \n $current_user = wp_get_current_user();\n $current_user-&gt;add_role('frontend_editor');\n}\n</code></pre>\n\n<p>put it function.php its work for me.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110442/" ]
I'm stuck right now. For my project, I have to create login not using WP user system but another system. Now, when with my system API login, I created some cookie but, obviously I didn't also create wp cookie for user logged in. So, I want to allow a user upload with media library of WP ([link of WP codex](https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/)) some files, but it doesn't work. I have also edited (temporary core wordpress change) admin-ajax.php for forcing it to create post attachment also in the case of user not logged in: ``` if ( is_user_logged_in() ) { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } else { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } ``` but async-upload.php responds with 302 and I don't know how to go forward. ***UPDATE***: the problem is the same of this user: [click here](https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/) I tried to use wp\_ajax\_my\_action and wp\_ajax\_nopriv\_myaction but nothing change. My need is allow to not logged user in WP to upload attachment, and assign this attachment with his ID author (for example, 12345), cause each user must see only yours media (i will use pre\_get\_posts and yet work).
First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes. Second, you may want to peruse this [Codex page](https://codex.wordpress.org/AJAX_in_Plugins) on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in): ``` add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); ``` The `my_action` function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX). Hope this starts you down the right path.
269,639
<p>I want to have one header page for the front page of the site and all other pages that follow by clicking "next" and a different header for all other pages, categories, articles, etc. on the site. Is there a way to do this within the header.php file or do I have to do something differently?</p> <p>I'm using a free theme for the backbone of the site and have implemented a child theme to create a unique header as well as add functions separately so that I don't lose changes when the parent theme is updated, so I have minimal space to maneuver in order to affect these changes.</p>
[ { "answer_id": 269640, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes.</p>\n\n<p>Second, you may want to peruse this <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">Codex page</a> on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in):</p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action' );\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action' );\n</code></pre>\n\n<p>The <code>my_action</code> function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX).</p>\n\n<p>Hope this starts you down the right path.</p>\n" }, { "answer_id": 365932, "author": "Farhan Ahmed", "author_id": 187484, "author_profile": "https://wordpress.stackexchange.com/users/187484", "pm_score": 0, "selected": false, "text": "<p>I was facing the same problem and finally got a solution.. As non login user don't have any role.. If we make a user role and assign a role to the every visitor we can solve the problem of uploading files as uploading file is a capability we can add to user role...</p>\n\n<p>I tried the following...</p>\n\n<pre><code>add_role( 'frontend_editor','Front-End Editor', array( 'upload_files' =&gt; true) );\n\nif ( is_user_logged_in() ) { \n $current_user = wp_get_current_user();\n $current_user-&gt;add_role('frontend_editor');\n}\n</code></pre>\n\n<p>put it function.php its work for me.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100669/" ]
I want to have one header page for the front page of the site and all other pages that follow by clicking "next" and a different header for all other pages, categories, articles, etc. on the site. Is there a way to do this within the header.php file or do I have to do something differently? I'm using a free theme for the backbone of the site and have implemented a child theme to create a unique header as well as add functions separately so that I don't lose changes when the parent theme is updated, so I have minimal space to maneuver in order to affect these changes.
First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes. Second, you may want to peruse this [Codex page](https://codex.wordpress.org/AJAX_in_Plugins) on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in): ``` add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); ``` The `my_action` function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX). Hope this starts you down the right path.
269,644
<p>I'm having a hard time figuring out why my repeatable fields javascript doesn't work. I'm using the following plugin: Rhyzz (repeatable-fields): <a href="http://www.rhyzz.com/repeatable-fields.html" rel="nofollow noreferrer">http://www.rhyzz.com/repeatable-fields.html</a>. I scraped the website and I see he ran the script inside html and also ran his javascript all on the same page. My website is a lot larger. I'm using Wordpress and I did the following to call the script in <code>functions.php</code>.</p> <pre><code> wp_enqueue_script( 'jquery', 'https://code.jquery.com/jquery-1.11.2.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-ui', 'https://code.jquery.com/ui/1.11.4/jquery-ui.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-repeatable', get_template_directory_uri() . '/js/repeatable.js', array( 'jquery', 'jquery-ui' ), '20120206', true ); </code></pre> <p>I also have about another 10 scripts. The files are all in the proper directories. I then have a particular page on my site (PHP) implementing the repeatable fields, but none of the buttons work. I don't have the following anywhere, and I don't know if it's necessary, but on Rhyzz's site he puts it in his HTML: </p> <pre><code>jQuery(function() { jQuery('.repeat').each(function() { jQuery(this).repeatable_fields(); }); }); </code></pre> <p>I'm very frustrated and don't know what to do. I also don't know if I'm enqueueing the script properly, as in if I should pass in jquery and jquery-ui into the array field. If anyone can help me with this please do so!</p> <p>Note: This is Rhyzz's GitHub with a tutorial on how to implement in HTML, <a href="https://github.com/Rhyzz/repeatable-fields" rel="nofollow noreferrer">https://github.com/Rhyzz/repeatable-fields</a>.</p>
[ { "answer_id": 269640, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes.</p>\n\n<p>Second, you may want to peruse this <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">Codex page</a> on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in):</p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action' );\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action' );\n</code></pre>\n\n<p>The <code>my_action</code> function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX).</p>\n\n<p>Hope this starts you down the right path.</p>\n" }, { "answer_id": 365932, "author": "Farhan Ahmed", "author_id": 187484, "author_profile": "https://wordpress.stackexchange.com/users/187484", "pm_score": 0, "selected": false, "text": "<p>I was facing the same problem and finally got a solution.. As non login user don't have any role.. If we make a user role and assign a role to the every visitor we can solve the problem of uploading files as uploading file is a capability we can add to user role...</p>\n\n<p>I tried the following...</p>\n\n<pre><code>add_role( 'frontend_editor','Front-End Editor', array( 'upload_files' =&gt; true) );\n\nif ( is_user_logged_in() ) { \n $current_user = wp_get_current_user();\n $current_user-&gt;add_role('frontend_editor');\n}\n</code></pre>\n\n<p>put it function.php its work for me.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121469/" ]
I'm having a hard time figuring out why my repeatable fields javascript doesn't work. I'm using the following plugin: Rhyzz (repeatable-fields): <http://www.rhyzz.com/repeatable-fields.html>. I scraped the website and I see he ran the script inside html and also ran his javascript all on the same page. My website is a lot larger. I'm using Wordpress and I did the following to call the script in `functions.php`. ``` wp_enqueue_script( 'jquery', 'https://code.jquery.com/jquery-1.11.2.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-ui', 'https://code.jquery.com/ui/1.11.4/jquery-ui.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-repeatable', get_template_directory_uri() . '/js/repeatable.js', array( 'jquery', 'jquery-ui' ), '20120206', true ); ``` I also have about another 10 scripts. The files are all in the proper directories. I then have a particular page on my site (PHP) implementing the repeatable fields, but none of the buttons work. I don't have the following anywhere, and I don't know if it's necessary, but on Rhyzz's site he puts it in his HTML: ``` jQuery(function() { jQuery('.repeat').each(function() { jQuery(this).repeatable_fields(); }); }); ``` I'm very frustrated and don't know what to do. I also don't know if I'm enqueueing the script properly, as in if I should pass in jquery and jquery-ui into the array field. If anyone can help me with this please do so! Note: This is Rhyzz's GitHub with a tutorial on how to implement in HTML, <https://github.com/Rhyzz/repeatable-fields>.
First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes. Second, you may want to peruse this [Codex page](https://codex.wordpress.org/AJAX_in_Plugins) on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in): ``` add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); ``` The `my_action` function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX). Hope this starts you down the right path.
269,645
<p>I am using this code below to specify a post template for a specific category in my functions.php file.</p> <pre><code>function get_custom_cat_template($single_template) { global $post; if ( in_category( 'ms-conversations' )) { $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ; </code></pre> <p>The code technically works, however I need to specify about 20 categories for that same post template.</p> <p>When I copy and paste the code again and again I get this fatal error because I am declaring it twice, but I do not know how to include all of the categories I need.</p> <pre><code>Fatal error: Cannot redeclare get_custom_cat_template() (previously declared in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php:152) in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php on line 174 </code></pre> <p>Here is a list of all the categories I need for that post template.</p> <p>ms-conversations, artist-of-the-month, exercise, hiking-for-multiple-sclerosis, msaa, caregiving-msaa, updates, ms-resources, ms-tips-msaa, recipe-of-the-month, stories-to-inspire, well-being, guest-bloggers, ms-publications, videos, multiplesclerosis-net, sharkfest, surveys, swim-for-ms, the-motivator</p> <p>When I try to use commas or &amp; signs to separate the categories I get further errors, how do I declare multiple categories for this chunk of code?</p> <p>Thank you.</p>
[ { "answer_id": 269647, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You don't need multiple functions. Use an <code>array</code> with <code>in_category</code> to pass multiple slugs:</p>\n\n<pre><code>if( in_category( array( 'ms-conversations', 'artist-of-the-month' ) ) ){\n // do something\n}\n</code></pre>\n" }, { "answer_id": 269650, "author": "Gina DiSanto", "author_id": 78325, "author_profile": "https://wordpress.stackexchange.com/users/78325", "pm_score": 1, "selected": true, "text": "<p>This is my final code.</p>\n\n<pre><code>function get_custom_cat_template($single_template) {\n global $post;\n\n if( in_category( array( 'ms-conversations', 'artist-of-the-month', 'exercise', 'hiking-for-multiple-sclerosis', 'msaa', 'caregiving-msaa', 'updates', 'ms-resources', 'ms-tips-msaa', 'recipe-of-the-month', 'stories-to-inspire', 'well-being', 'guest-bloggers', 'ms-publications', 'videos', 'multiplesclerosis-net', 'sharkfest', 'surveys', 'swim-for-ms', 'the-motivator' ) ) ){\n $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php';\n\n }\n return $single_template;\n\n}\n\nadd_filter( \"single_template\", \"get_custom_cat_template\" ) ; \n</code></pre>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269645", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78325/" ]
I am using this code below to specify a post template for a specific category in my functions.php file. ``` function get_custom_cat_template($single_template) { global $post; if ( in_category( 'ms-conversations' )) { $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ; ``` The code technically works, however I need to specify about 20 categories for that same post template. When I copy and paste the code again and again I get this fatal error because I am declaring it twice, but I do not know how to include all of the categories I need. ``` Fatal error: Cannot redeclare get_custom_cat_template() (previously declared in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php:152) in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php on line 174 ``` Here is a list of all the categories I need for that post template. ms-conversations, artist-of-the-month, exercise, hiking-for-multiple-sclerosis, msaa, caregiving-msaa, updates, ms-resources, ms-tips-msaa, recipe-of-the-month, stories-to-inspire, well-being, guest-bloggers, ms-publications, videos, multiplesclerosis-net, sharkfest, surveys, swim-for-ms, the-motivator When I try to use commas or & signs to separate the categories I get further errors, how do I declare multiple categories for this chunk of code? Thank you.
This is my final code. ``` function get_custom_cat_template($single_template) { global $post; if( in_category( array( 'ms-conversations', 'artist-of-the-month', 'exercise', 'hiking-for-multiple-sclerosis', 'msaa', 'caregiving-msaa', 'updates', 'ms-resources', 'ms-tips-msaa', 'recipe-of-the-month', 'stories-to-inspire', 'well-being', 'guest-bloggers', 'ms-publications', 'videos', 'multiplesclerosis-net', 'sharkfest', 'surveys', 'swim-for-ms', 'the-motivator' ) ) ){ $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ; ```
269,656
<p>How can I retrieve the values ​​passed to the shortcode using only one parameter?</p> <p>Example:</p> <pre><code>[related type="2,3,4,5,6"] </code></pre> <p>Is it possible to do that?</p>
[ { "answer_id": 269657, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 1, "selected": false, "text": "<p>You can pass a JSON object in a short code:</p>\n\n<pre><code>[related values='{\"a\":\"foo\",\"b\":\"bar\"}']\n</code></pre>\n\n<p>Then you can retrieve passed attributes using <code>json_decode</code></p>\n\n<pre><code>public static function myshortcode( $atts, $content = null ) {\n extract( shortcode_atts( array(\n \"values\" = \"\",\n ), $atts ) );\n\n $values = json_decode( $values, true );\n\n // Your Shortcode Functionality here\n\n}\n</code></pre>\n" }, { "answer_id": 269660, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>The solution below will parse the comma separated values passed to the shortcode's <code>type</code> parameter. We'll also strip out any whitespace surrounding the values which is a usability improvement (see example 2 after the code below).</p>\n\n<pre><code>add_shortcode( 'related', 'wpse_related' );\nfunction wpse_related( $atts, $content = '' ) {\n // User provided values are stored in $atts.\n // Default values are passed to shortcode_atts() below.\n // Merged values are stored in the $a array.\n $a = shortcode_atts( [\n 'type' =&gt; false,\n ], $atts );\n\n $output = '';\n\n if ( $a['type'] ) {\n // Parse type into an array. Whitespace will be stripped.\n $a['type'] = array_map( 'trim', str_getcsv( $a['type'], ',' ) );\n }\n\n // Debugging: Display the type parameter as a formatted array.\n $output .= '&lt;pre&gt;' . print_r( $a['type'], true ) . '&lt;/pre&gt;';\n\n return $output;\n}\n</code></pre>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><code>[related type=\"2,3,4,5,6\"]\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>Array\n(\n [0] =&gt; 2\n [1] =&gt; 3\n [2] =&gt; 4\n [3] =&gt; 5\n [4] =&gt; 6\n)\n</code></pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><code>[related type=\"8, 6, 7,5,30, 9\"]\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>Array\n(\n [0] =&gt; 8\n [1] =&gt; 6\n [2] =&gt; 7\n [3] =&gt; 5\n [4] =&gt; 30\n [5] =&gt; 9\n)\n</code></pre>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269656", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121477/" ]
How can I retrieve the values ​​passed to the shortcode using only one parameter? Example: ``` [related type="2,3,4,5,6"] ``` Is it possible to do that?
The solution below will parse the comma separated values passed to the shortcode's `type` parameter. We'll also strip out any whitespace surrounding the values which is a usability improvement (see example 2 after the code below). ``` add_shortcode( 'related', 'wpse_related' ); function wpse_related( $atts, $content = '' ) { // User provided values are stored in $atts. // Default values are passed to shortcode_atts() below. // Merged values are stored in the $a array. $a = shortcode_atts( [ 'type' => false, ], $atts ); $output = ''; if ( $a['type'] ) { // Parse type into an array. Whitespace will be stripped. $a['type'] = array_map( 'trim', str_getcsv( $a['type'], ',' ) ); } // Debugging: Display the type parameter as a formatted array. $output .= '<pre>' . print_r( $a['type'], true ) . '</pre>'; return $output; } ``` **Example 1:** ``` [related type="2,3,4,5,6"] ``` **Output:** ``` Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 ) ``` **Example 2:** ``` [related type="8, 6, 7,5,30, 9"] ``` **Output:** ``` Array ( [0] => 8 [1] => 6 [2] => 7 [3] => 5 [4] => 30 [5] => 9 ) ```
269,676
<p>I would like to update a post on every new comment, so that the <code>Last Modified Date</code> is always up to date on the sitemap.</p> <p>How can i do this?</p> <p>Thanks.</p>
[ { "answer_id": 269686, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>That may change the order of posts on your main page, depending on your theme. </p>\n\n<p>There are ways to display the links to the pages with recent comments. </p>\n\n<p>But, you will need to have your theme (child theme, hopefully, since you don't want to change theme code) add code which uses a hook on comment save. For instance, you could use the <code>wp_insert_comment()</code> hook, as described in this link: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_comment\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_comment</a> </p>\n\n<p>There are other hooks that can be used during a comment save, depending on when you want things to happen.</p>\n" }, { "answer_id": 269694, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>From what i understand, you want to change the post's modification time whenever a comment is left on your post. For this, you need to hook into the <code>wp_insert_comment</code> hook and update the post's date manually:</p>\n\n<pre><code>add_action('wp_insert_comment','update_post_time',99,2);\nfunction update_post_time($comment_id, $comment_object) {\n // Get the post's ID\n $post_id = $comment_object-&gt;comment_post_ID;\n // Double check for post's ID, since this value is mandatory in wp_update_post()\n if ($post_id) {\n // Get the current time\n $time = current_time('mysql');\n // Form an array of data to be updated\n $post_data = array(\n 'ID' =&gt; $post_id, \n 'post_modified' =&gt; $time, \n 'post_modified_gmt' =&gt; get_gmt_from_date( $time )\n );\n // Update the post\n wp_update_post( $post_data );\n }\n}\n</code></pre>\n\n<p>Note that this will create a revision for the post each time a comment is created.</p>\n\n<p>If your sitemap plugin uses the <code>post_date</code> instead of <code>post_modified</code>, you can use this instead:</p>\n\n<pre><code>$post_data = array(\n 'ID' =&gt; $post_id, \n 'post_date' =&gt; $time, \n 'post_date_gmt' =&gt; get_gmt_from_date( $time )\n);\n</code></pre>\n\n<p>However, this might cause problems, and mess post's order in archives and homepage, since it changes the post's <strong>creation</strong> date, not modification date.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269676", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117210/" ]
I would like to update a post on every new comment, so that the `Last Modified Date` is always up to date on the sitemap. How can i do this? Thanks.
From what i understand, you want to change the post's modification time whenever a comment is left on your post. For this, you need to hook into the `wp_insert_comment` hook and update the post's date manually: ``` add_action('wp_insert_comment','update_post_time',99,2); function update_post_time($comment_id, $comment_object) { // Get the post's ID $post_id = $comment_object->comment_post_ID; // Double check for post's ID, since this value is mandatory in wp_update_post() if ($post_id) { // Get the current time $time = current_time('mysql'); // Form an array of data to be updated $post_data = array( 'ID' => $post_id, 'post_modified' => $time, 'post_modified_gmt' => get_gmt_from_date( $time ) ); // Update the post wp_update_post( $post_data ); } } ``` Note that this will create a revision for the post each time a comment is created. If your sitemap plugin uses the `post_date` instead of `post_modified`, you can use this instead: ``` $post_data = array( 'ID' => $post_id, 'post_date' => $time, 'post_date_gmt' => get_gmt_from_date( $time ) ); ``` However, this might cause problems, and mess post's order in archives and homepage, since it changes the post's **creation** date, not modification date.
269,679
<p>I'm in trouble with Bootstrap and Wordpress.</p> <p>I want to get Taxonomy list to expand (show custom posts from Taxonomy). But it is hard!!!!</p> <p>Its basically a custom sidebar</p> <p>My code:</p> <pre><code>&lt;h3&gt; Portfólio &lt;/h3&gt; &lt;?php $catprod = get_terms( array( 'taxonomy' =&gt; 'categoria-produto', 'order' =&gt; 'DESC' )); // Todas as categorias $args = array( 'post_type' =&gt; 'produto' ); $prodtype = new WP_Query($args); ?&gt; &lt;div class="panel-group"&gt; &lt;div class="panel-heading"&gt; &lt;?php foreach( $catprod as $cat ) { ?&gt; &lt;h3 class="panel-title"&gt; &lt;a data-toggle="collapse" href="#&lt;?php echo $cat-&gt;slug ?&gt;" class="accordion-toggle" data-parent="#accordion"&gt; &lt;?php echo $cat-&gt;name ?&gt; &lt;/a&gt; &lt;/h3&gt; &lt;div id="&lt;?php echo $cat-&gt;slug ?&gt;" class="panel-collapse collapse in"&gt; &lt;div class="panel-body"&gt; &lt;?php foreach( $prodtype as $prod ) { ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt; &lt;?php the_field('titulo') ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 269686, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>That may change the order of posts on your main page, depending on your theme. </p>\n\n<p>There are ways to display the links to the pages with recent comments. </p>\n\n<p>But, you will need to have your theme (child theme, hopefully, since you don't want to change theme code) add code which uses a hook on comment save. For instance, you could use the <code>wp_insert_comment()</code> hook, as described in this link: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_comment\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_comment</a> </p>\n\n<p>There are other hooks that can be used during a comment save, depending on when you want things to happen.</p>\n" }, { "answer_id": 269694, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>From what i understand, you want to change the post's modification time whenever a comment is left on your post. For this, you need to hook into the <code>wp_insert_comment</code> hook and update the post's date manually:</p>\n\n<pre><code>add_action('wp_insert_comment','update_post_time',99,2);\nfunction update_post_time($comment_id, $comment_object) {\n // Get the post's ID\n $post_id = $comment_object-&gt;comment_post_ID;\n // Double check for post's ID, since this value is mandatory in wp_update_post()\n if ($post_id) {\n // Get the current time\n $time = current_time('mysql');\n // Form an array of data to be updated\n $post_data = array(\n 'ID' =&gt; $post_id, \n 'post_modified' =&gt; $time, \n 'post_modified_gmt' =&gt; get_gmt_from_date( $time )\n );\n // Update the post\n wp_update_post( $post_data );\n }\n}\n</code></pre>\n\n<p>Note that this will create a revision for the post each time a comment is created.</p>\n\n<p>If your sitemap plugin uses the <code>post_date</code> instead of <code>post_modified</code>, you can use this instead:</p>\n\n<pre><code>$post_data = array(\n 'ID' =&gt; $post_id, \n 'post_date' =&gt; $time, \n 'post_date_gmt' =&gt; get_gmt_from_date( $time )\n);\n</code></pre>\n\n<p>However, this might cause problems, and mess post's order in archives and homepage, since it changes the post's <strong>creation</strong> date, not modification date.</p>\n" } ]
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269679", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121494/" ]
I'm in trouble with Bootstrap and Wordpress. I want to get Taxonomy list to expand (show custom posts from Taxonomy). But it is hard!!!! Its basically a custom sidebar My code: ``` <h3> Portfólio </h3> <?php $catprod = get_terms( array( 'taxonomy' => 'categoria-produto', 'order' => 'DESC' )); // Todas as categorias $args = array( 'post_type' => 'produto' ); $prodtype = new WP_Query($args); ?> <div class="panel-group"> <div class="panel-heading"> <?php foreach( $catprod as $cat ) { ?> <h3 class="panel-title"> <a data-toggle="collapse" href="#<?php echo $cat->slug ?>" class="accordion-toggle" data-parent="#accordion"> <?php echo $cat->name ?> </a> </h3> <div id="<?php echo $cat->slug ?>" class="panel-collapse collapse in"> <div class="panel-body"> <?php foreach( $prodtype as $prod ) { ?> <li> <a href="<?php the_permalink() ?>"> <?php the_field('titulo') ?> </a> </li> <?php } ?> </div> </div> <?php } ?> </div> </div> ```
From what i understand, you want to change the post's modification time whenever a comment is left on your post. For this, you need to hook into the `wp_insert_comment` hook and update the post's date manually: ``` add_action('wp_insert_comment','update_post_time',99,2); function update_post_time($comment_id, $comment_object) { // Get the post's ID $post_id = $comment_object->comment_post_ID; // Double check for post's ID, since this value is mandatory in wp_update_post() if ($post_id) { // Get the current time $time = current_time('mysql'); // Form an array of data to be updated $post_data = array( 'ID' => $post_id, 'post_modified' => $time, 'post_modified_gmt' => get_gmt_from_date( $time ) ); // Update the post wp_update_post( $post_data ); } } ``` Note that this will create a revision for the post each time a comment is created. If your sitemap plugin uses the `post_date` instead of `post_modified`, you can use this instead: ``` $post_data = array( 'ID' => $post_id, 'post_date' => $time, 'post_date_gmt' => get_gmt_from_date( $time ) ); ``` However, this might cause problems, and mess post's order in archives and homepage, since it changes the post's **creation** date, not modification date.
269,699
<p>I wanted to know if i can change the way i display views count in WordPress.</p> <p>Example: 1000 views = 1k - 10000 views = 10k</p> <p>I'm counting and viewing post views by using this code:</p> <pre><code>// Count views function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); } else { $count++; update_post_meta($postID, $count_key, $count); } } // Show views function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } return $count.' Views'; } // Show views in WP-Admin add_filter('manage_posts_columns', 'posts_column_views'); add_action('manage_posts_custom_column', 'posts_custom_column_views', 5, 2); function posts_column_views($defaults) { $defaults['post_views'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views') { echo getPostViews(get_the_ID()); } } </code></pre>
[ { "answer_id": 269700, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return it:</p>\n\n<pre><code>function getPostViews($postID) {\n $count_key = 'post_views_count';\n $count = get_post_meta($postID, $count_key, true);\n if($count=='') {\n delete_post_meta($postID, $count_key);\n add_post_meta($postID, $count_key, '0');\n return \"0 View\";\n }\n if ($count &gt; 1000) {\n return round ( $count / 1000 ,1 ).'K Views';\n } else {\n return $count.' Views';\n }\n}\n</code></pre>\n" }, { "answer_id": 300879, "author": "jrxpress", "author_id": 119061, "author_profile": "https://wordpress.stackexchange.com/users/119061", "pm_score": 0, "selected": false, "text": "<p>I uses this function for a while and works great for my needs:</p>\n\n<pre><code>/**\n * Shorten long numbers to K/M/B (Thousand, Million and Billion)\n *\n * @param int $number The number to shorten.\n * @param int $decimals Precision of the number of decimal places.\n * @param string $suffix A string displays as the number suffix.\n */\nif(!function_exists('short_number')) {\nfunction short_number($n, $decimals = 2, $suffix = '') {\n if(!$suffix)\n $suffix = 'K,M,B';\n $suffix = explode(',', $suffix);\n\n if ($n &lt; 1000) { // any number less than a Thousand\n $shorted = number_format($n);\n } elseif ($n &lt; 1000000) { // any number less than a million\n $shorted = number_format($n/1000, $decimals).$suffix[0];\n } elseif ($n &lt; 1000000000) { // any number less than a billion\n $shorted = number_format($n/1000000, $decimals).$suffix[1];\n } else { // at least a billion\n $shorted = number_format($n/1000000000, $decimals).$suffix[2];\n }\n\n return $shorted;\n}\n}\n</code></pre>\n\n<p>now you just call the function like this example:</p>\n\n<pre><code>$views = getPostViews($postID); \n$views = short_number($views);\nreturn $views;\n</code></pre>\n\n<p>I hope it helps anyone else in need :D</p>\n" } ]
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117100/" ]
I wanted to know if i can change the way i display views count in WordPress. Example: 1000 views = 1k - 10000 views = 10k I'm counting and viewing post views by using this code: ``` // Count views function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); } else { $count++; update_post_meta($postID, $count_key, $count); } } // Show views function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } return $count.' Views'; } // Show views in WP-Admin add_filter('manage_posts_columns', 'posts_column_views'); add_action('manage_posts_custom_column', 'posts_custom_column_views', 5, 2); function posts_column_views($defaults) { $defaults['post_views'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views') { echo getPostViews(get_the_ID()); } } ```
Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return it: ``` function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } if ($count > 1000) { return round ( $count / 1000 ,1 ).'K Views'; } else { return $count.' Views'; } } ```
269,708
<p>I have used thumbnail like this in my wordpress theme's one template →</p> <pre><code>&lt;?php the_post_thumbnail( 'medium' ); ?&gt; </code></pre> <p>In the browser it is rendering like this →</p> <pre><code>&lt;img width="300" height="220" src="http://example.com/image-300x220.jpg" class="attachment-medium size-medium wp-post-image" alt="" srcset=" http://example.com/image-300x220.jpg 300w, http://example.com/image.jpg 640w" sizes="(max-width: 300px) 100vw, 300px" &gt; </code></pre> <p>My first question is how to put height = auto is there any function that can help us to achieve this? such as <code>responsive-img</code></p> <p>In short, I am asking should I control the width through the CSS or WordPress gives some function to do this?</p>
[ { "answer_id": 269700, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return it:</p>\n\n<pre><code>function getPostViews($postID) {\n $count_key = 'post_views_count';\n $count = get_post_meta($postID, $count_key, true);\n if($count=='') {\n delete_post_meta($postID, $count_key);\n add_post_meta($postID, $count_key, '0');\n return \"0 View\";\n }\n if ($count &gt; 1000) {\n return round ( $count / 1000 ,1 ).'K Views';\n } else {\n return $count.' Views';\n }\n}\n</code></pre>\n" }, { "answer_id": 300879, "author": "jrxpress", "author_id": 119061, "author_profile": "https://wordpress.stackexchange.com/users/119061", "pm_score": 0, "selected": false, "text": "<p>I uses this function for a while and works great for my needs:</p>\n\n<pre><code>/**\n * Shorten long numbers to K/M/B (Thousand, Million and Billion)\n *\n * @param int $number The number to shorten.\n * @param int $decimals Precision of the number of decimal places.\n * @param string $suffix A string displays as the number suffix.\n */\nif(!function_exists('short_number')) {\nfunction short_number($n, $decimals = 2, $suffix = '') {\n if(!$suffix)\n $suffix = 'K,M,B';\n $suffix = explode(',', $suffix);\n\n if ($n &lt; 1000) { // any number less than a Thousand\n $shorted = number_format($n);\n } elseif ($n &lt; 1000000) { // any number less than a million\n $shorted = number_format($n/1000, $decimals).$suffix[0];\n } elseif ($n &lt; 1000000000) { // any number less than a billion\n $shorted = number_format($n/1000000, $decimals).$suffix[1];\n } else { // at least a billion\n $shorted = number_format($n/1000000000, $decimals).$suffix[2];\n }\n\n return $shorted;\n}\n}\n</code></pre>\n\n<p>now you just call the function like this example:</p>\n\n<pre><code>$views = getPostViews($postID); \n$views = short_number($views);\nreturn $views;\n</code></pre>\n\n<p>I hope it helps anyone else in need :D</p>\n" } ]
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I have used thumbnail like this in my wordpress theme's one template → ``` <?php the_post_thumbnail( 'medium' ); ?> ``` In the browser it is rendering like this → ``` <img width="300" height="220" src="http://example.com/image-300x220.jpg" class="attachment-medium size-medium wp-post-image" alt="" srcset=" http://example.com/image-300x220.jpg 300w, http://example.com/image.jpg 640w" sizes="(max-width: 300px) 100vw, 300px" > ``` My first question is how to put height = auto is there any function that can help us to achieve this? such as `responsive-img` In short, I am asking should I control the width through the CSS or WordPress gives some function to do this?
Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return it: ``` function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } if ($count > 1000) { return round ( $count / 1000 ,1 ).'K Views'; } else { return $count.' Views'; } } ```
269,719
<p>Can the new 4.8 widget visual editor in the default text widget be unhooked or removed and the widget restored to the pre-4.8 editor style?</p> <p>I don't need or want the visual editor in widgets; I use them for plain text and html and don't need other users adding anything other than plain text.</p> <p>I did learn how to <em>remove</em> the new video, audio and image widgets in <code>functions.php</code> as I don't need them:</p> <pre><code>// Unregister default WP Widgets function unregister_default_wp_widgets() { unregister_widget('WP_Widget_Media_Audio' ); unregister_widget('WP_Widget_Media_Image'); unregister_widget( 'WP_Widget_Media_Video' ); } add_action('widgets_init', 'unregister_default_wp_widgets', 1); </code></pre> <p>But I also want to remove the visual editor tab from the default text widget.</p> <p><strong>Edit:</strong> I can use the PHP Code Widget <a href="https://wordpress.org/plugins/php-code-widget/" rel="noreferrer">https://wordpress.org/plugins/php-code-widget/</a> which does not have the visual editor, and though I don't usually need <code>php</code> execution, it is useful. But this adds the "break things" vector for users who might play with <code>php</code>.</p>
[ { "answer_id": 269724, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>The answer is mostly no. The \"enhanced\" text widget was designed to work like the post editor as much as possible, including autop which might break whatever HTML that can not stand the conversion of lines into paragraphs.</p>\n\n<p>Several people have released plugins to restore the former functionality, but 4.8.1 will also include an \"code\" widget that can be used to add unaltered HTML. The problem is that there is no, and unlikely to be a plain upgrade path. Best advice right now if you use the html widget is to skip 4.8 and wait for 4.8.1 and allocate some time in advance to migrate the widgets.</p>\n\n<p>If you are just looking to hide the \"visual\" tab, you are most like also out of luck best to open a ticket at trac to add such possibility, specifically for the widget without impact on the post editor (4.8.1 plan right now is to use the same setting for both)</p>\n" }, { "answer_id": 269822, "author": "Reyno", "author_id": 121588, "author_profile": "https://wordpress.stackexchange.com/users/121588", "pm_score": 1, "selected": false, "text": "<p>I am not sure you can remove the visual tab from the widget. It is however possible te remove the wpautop filter.</p>\n\n<p>If you add <code>remove_filter('widget_text_content', 'wpautop');</code> to your functions.php it should stop wordpress from adding the <code>&lt;p&gt;</code>, <code>&lt;br/&gt;</code>, <code>&amp;nbsp;</code> tags to your text widget output.</p>\n\n<p>This way, you can write all the html you want in your text editor without wordpress messing it up.</p>\n" }, { "answer_id": 270279, "author": "Alan Fuller", "author_id": 121883, "author_profile": "https://wordpress.stackexchange.com/users/121883", "pm_score": 0, "selected": false, "text": "<p>I wrote this plugin to handle the issues of upgrading to 4.8.</p>\n\n<p><a href=\"https://wordpress.org/plugins/add-paragraphs-option-to-text-widget/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/add-paragraphs-option-to-text-widget/</a></p>\n" } ]
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101490/" ]
Can the new 4.8 widget visual editor in the default text widget be unhooked or removed and the widget restored to the pre-4.8 editor style? I don't need or want the visual editor in widgets; I use them for plain text and html and don't need other users adding anything other than plain text. I did learn how to *remove* the new video, audio and image widgets in `functions.php` as I don't need them: ``` // Unregister default WP Widgets function unregister_default_wp_widgets() { unregister_widget('WP_Widget_Media_Audio' ); unregister_widget('WP_Widget_Media_Image'); unregister_widget( 'WP_Widget_Media_Video' ); } add_action('widgets_init', 'unregister_default_wp_widgets', 1); ``` But I also want to remove the visual editor tab from the default text widget. **Edit:** I can use the PHP Code Widget <https://wordpress.org/plugins/php-code-widget/> which does not have the visual editor, and though I don't usually need `php` execution, it is useful. But this adds the "break things" vector for users who might play with `php`.
The answer is mostly no. The "enhanced" text widget was designed to work like the post editor as much as possible, including autop which might break whatever HTML that can not stand the conversion of lines into paragraphs. Several people have released plugins to restore the former functionality, but 4.8.1 will also include an "code" widget that can be used to add unaltered HTML. The problem is that there is no, and unlikely to be a plain upgrade path. Best advice right now if you use the html widget is to skip 4.8 and wait for 4.8.1 and allocate some time in advance to migrate the widgets. If you are just looking to hide the "visual" tab, you are most like also out of luck best to open a ticket at trac to add such possibility, specifically for the widget without impact on the post editor (4.8.1 plan right now is to use the same setting for both)
269,736
<p>I was able to add the file last modified time as version to css and js files. As you can see I have to repeatly adding <code>filemtime(get_theme_file_path('...'))</code> every time when a new link is added.</p> <pre><code>function _enqueue_scripts() { wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css'))); wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js'))); } add_action('wp_enqueue_scripts', '_enqueue_scripts'); </code></pre> <p>Is there a way to use a custom filter or so for it rather than manually add that line every time?</p> <p>Similar to the below function (for removing version numbers), but I'd like to add version numbers. </p> <pre><code>function _remove_script_version($src) { return $src ? esc_url(remove_query_arg('ver', $src)) : false; } add_filter('style_loader_src', '_remove_script_version', 15, 1); add_filter('script_loader_src', '_remove_script_version', 15, 1); </code></pre>
[ { "answer_id": 269740, "author": "inarilo", "author_id": 17923, "author_profile": "https://wordpress.stackexchange.com/users/17923", "pm_score": 4, "selected": true, "text": "<p>You could use <a href=\"http://developer.wordpress.org/reference/functions/add_query_arg\" rel=\"noreferrer\">add_query_arg()</a> but then you'd have to parse the uri everytime, I'd rather create a wrapper function for wp_enqueue_script/style:</p>\n\n<pre><code>function my_enqueuer($my_handle, $relpath, $type='script', $my_deps=array()) {\n $uri = get_theme_file_uri($relpath);\n $vsn = filemtime(get_theme_file_path($relpath));\n if($type == 'script') wp_enqueue_script($my_handle, $uri, $my_deps, $vsn);\n else if($type == 'style') wp_enqueue_style($my_handle, $uri, $my_deps, $vsn); \n}\n</code></pre>\n\n<p>Add this in your functions file and then in place of e.g.</p>\n\n<pre><code>wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js')));\n</code></pre>\n\n<p>call:</p>\n\n<pre><code>my_enqueuer('_base', '/assets/js/base.js');\n</code></pre>\n\n<p>and in place of e.g.</p>\n\n<pre><code>wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css')));\n</code></pre>\n\n<p>call:</p>\n\n<pre><code>my_enqueuer('_base', '/assets/css/base.css', 'style');\n</code></pre>\n\n<p>You can pass the dependency array as the last argument when needed. For scripts, if you pass the dependency array, you will have to pass the third parameter 'script' as well, even though I've set it as the default value.</p>\n" }, { "answer_id": 293493, "author": "Mr. HK", "author_id": 110110, "author_profile": "https://wordpress.stackexchange.com/users/110110", "pm_score": 2, "selected": false, "text": "<p>I used to use YYYYMMDD as my version number for enqueued files, which was reasonably good, but caused issues when it changed more than once in a day and still meant having to remember to update the version number when changes were made to the file. An example of an enqueue might have looked like this:</p>\n\n<pre><code>&lt;?php wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/css/styles.css', array(), '20150731' ); ?&gt;\n</code></pre>\n\n<p>My revised approach starts by creating a variable for the path of the CSS/JS file and then using filemtime in the version number instead of YYYYMMDD:</p>\n\n<pre><code>&lt;?php\n$themecsspath = get_stylesheet_directory() . '/css/styles.css';\nwp_enqueue_style(\n 'child-theme',\n get_stylesheet_directory_uri() . '/css/styles.css',\n array(),\n filemtime( $themecsspath )\n);\n?&gt;\n</code></pre>\n\n<p>Now, instead of my enqueued files containing the WordPress version number, like this:</p>\n\n<pre><code>&lt;link rel='stylesheet' id='child-theme-css' href='http://example.com/wp-content/themes/child/css/styles.css?ver=4.3.1' type='text/css' media='all' /&gt;\n</code></pre>\n\n<p>They look like this:</p>\n\n<pre><code>&lt;link rel='stylesheet' id='child-theme-css' href='http://example.com/wp-content/themes/child/css/styles.css?ver=1447781986' type='text/css' media='all' /&gt;\n</code></pre>\n" }, { "answer_id": 294553, "author": "CGodo", "author_id": 114314, "author_profile": "https://wordpress.stackexchange.com/users/114314", "pm_score": 2, "selected": false, "text": "<p>If for some reason somebody needs it, these hooks will put modified time versions on all Wordpress scripts and styles, except for those loaded from PHP. </p>\n\n<p>The reason it uses WP_Scripts and WP_Styles singletons is because those instances already have calculated the base_url.</p>\n\n<pre><code>/**\n * Replaces query version in registered scripts or styles with file modified time\n * @param string $src Source url\n * @param string $baseUrl Site base url\n * @return string\n */\nfunction put_modified_time_version($src, $baseUrl)\n{\n // Only work with objects from baseUrl\n if ($src &amp;&amp; strpos($src, $baseUrl) === 0) {\n // Remove any version\n $newSrc = remove_query_arg('ver', $src);\n // Get path after base_url\n $path = substr($newSrc, strlen($baseUrl));\n $path = wp_parse_url($path, PHP_URL_PATH);\n // Apply modified time version if exists\n if ($mtime = @filemtime(untrailingslashit(ABSPATH) . $path)) {\n $src = add_query_arg('ver', $mtime, $newSrc);\n }\n }\n return $src;\n}\n\n/**\n * Filters style sources to put file modified time as query string\n * @param $src\n * @return string\n */\nfunction modified_time_version_style($src) {\n // base_url from WP_Versions is already in memory\n return ($src) ? put_modified_time_version($src, wp_styles()-&gt;base_url) : $src;\n}\n\n/**\n * Filters script sources to put file modified time as query string\n * @param $src\n * @return string\n */\nfunction modified_time_version_script($src) {\n // base_url from WP_Styles is already in memory\n return ($src) ? put_modified_time_version($src, wp_scripts()-&gt;base_url) : $src;\n}\n\nadd_filter('style_loader_src', 'modified_time_version_style', 15, 1);\nadd_filter('script_loader_src', 'modified_time_version_script', 15, 1);\n</code></pre>\n" }, { "answer_id": 346024, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 2, "selected": false, "text": "<p>This answer was adapted from <a href=\"https://wordpress.stackexchange.com/a/294553/9579\"><code>@CGodo's solution</code></a>.</p>\n\n<p>I was getting Fatal Errors with the original code. I've tested this code and it does what I believe the original answer was intended to do.</p>\n\n<pre><code>/**\n * Replaces query version in registered scripts or styles with file modified time\n *\n * @param $src\n *\n * @return string\n */\nfunction add_modified_time( $src ) {\n\n $clean_src = remove_query_arg( 'ver', $src );\n $path = wp_parse_url( $src, PHP_URL_PATH );\n\n if ( $modified_time = @filemtime( untrailingslashit( ABSPATH ) . $path ) ) {\n $src = add_query_arg( 'ver', $modified_time, $clean_src );\n } else {\n $src = add_query_arg( 'ver', time(), $clean_src );\n }\n\n return $src;\n\n}\n\nadd_filter( 'style_loader_src', 'add_modified_time', 99999999, 1 );\nadd_filter( 'script_loader_src', 'add_modified_time', 99999999, 1 );\n</code></pre>\n" }, { "answer_id": 391682, "author": "user1030151", "author_id": 208781, "author_profile": "https://wordpress.stackexchange.com/users/208781", "pm_score": 0, "selected": false, "text": "<p>I just wrote two methods for my plugin class, that makes it super easy to register/enqueue scripts and styles. And of course, as desired, the last modification time is always added as version parameter. Maybe this will help someone </p>\n<p>How to use them:</p>\n<pre><code>/**\n * For these examples we assume that your plugin assets are located in\n * wp-content/plugins/my-plugin/path/to/assets/\n */\n\n// add your style\n$this-&gt;registerAsset('path/to/assets/your-style.css');\n\n// add your script works exactly the same\n$this-&gt;registerAsset('path/to/assets/your-script.js');\n\n// add script with dependency\n$this-&gt;registerAsset('path/to/assets/script-with-dependencies.js', [\n 'jquery'\n]);\n\n// add script with internal dependency\n$this-&gt;registerAsset('path/to/assets/script-with-dependencies.js', [\n 'jquery',\n $this-&gt;getAssetHandle('path/to/assets/your-script.js')\n]);\n\n// for internal dependencies you can also pass the path of the dependency directly\n$this-&gt;registerAsset('path/to/assets/script-with-dependencies.js', [\n 'jquery',\n 'path/to/assets/your-script.js'\n]);\n</code></pre>\n<p>There are a few more options, but just check out the documentation about the methods in the source code you need:</p>\n<pre><code>class myPlugin\n{\n public function __construct()\n {\n }\n \n /**\n * Registers and enqueues a script or style\n * \n * @param STRING $path The path of the file you want to register or enqueue (relative to your plugin folder).\n * @param ARRAY $dependencies The dependencies as you know from wp_enqueue_script, but allows also paths of other assets that were registered with this method.\n * @param BOOLEAN $enqueue If FALSE it will only be registered, otherwise it will also be enqueued.\n * @param STRING|NULL $type Type of the asset. Allowed types are 'script' and 'style'. If it is NULL, the type is automatically detected from the file extension.\n * @param STRING $media To define 'media' when adding CSS (Ignored for JS assets - JS assets always get TRUE for the in_footer parameter as this is usually the recommended way)\n * \n * @return BOOLEAN|NULL When $enqueue is TRUE, the return value is always NULL. Otherwise TRUE on success, FALSE on failure.\n */\n public function registerAsset($path, $dependencies = [], $enqueue = true, $type = null, $media = 'all')\n {\n $path = '/' . ltrim($path, '/');\n $pluginDirName = explode(DIRECTORY_SEPARATOR, ltrim(str_replace(realpath(WP_PLUGIN_DIR), '', realpath(__FILE__)), DIRECTORY_SEPARATOR), 2)[0];\n $pluginDir = realpath(WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $pluginDirName);\n\n if ($type === null) {\n $extensions = ['js' =&gt; 'script', 'css' =&gt; 'style'];\n $extension = pathinfo($path, PATHINFO_EXTENSION);\n $type = isset($extensions[$extension]) ? $extensions[$extension] : null;\n }\n if (!in_array($type, ['script', 'style']) || !file_exists($pluginDir . $path)) {\n return;\n }\n\n foreach ($dependencies as $index =&gt; $dependency) {\n if (preg_match('/\\.(js|css)$/', $dependency) &amp;&amp; file_exists($pluginDir . DIRECTORY_SEPARATOR . ltrim($dependency, '\\\\/'))) {\n $dependencies[$index] = $this-&gt;getAssetHandle($dependency);\n }\n }\n\n $func = 'wp_' . ($enqueue ? 'enqueue' : 'register') . '_' . $type;\n return $func($this-&gt;getAssetHandle($path), plugins_url($pluginDirName . $path), $dependencies, filemtime($pluginDir . $path), $type === 'script' ? true : $media);\n }\n\n /**\n * Gets the handle of an asset that registerAsset() uses automatically\n * \n * @param STRING $path The path that you used with registerAsset()\n * \n * @return STRING The handle name of the asset\n */\n public function getAssetHandle($path)\n {\n $pluginDirName = explode(DIRECTORY_SEPARATOR, ltrim(str_replace(realpath(WP_PLUGIN_DIR), '', realpath(__FILE__)), DIRECTORY_SEPARATOR), 2)[0];\n return preg_replace('/[^a-zA-Z0-9]+/', '-', $pluginDirName . '-' . $path);\n }\n}\n</code></pre>\n" } ]
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9508/" ]
I was able to add the file last modified time as version to css and js files. As you can see I have to repeatly adding `filemtime(get_theme_file_path('...'))` every time when a new link is added. ``` function _enqueue_scripts() { wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css'))); wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js'))); } add_action('wp_enqueue_scripts', '_enqueue_scripts'); ``` Is there a way to use a custom filter or so for it rather than manually add that line every time? Similar to the below function (for removing version numbers), but I'd like to add version numbers. ``` function _remove_script_version($src) { return $src ? esc_url(remove_query_arg('ver', $src)) : false; } add_filter('style_loader_src', '_remove_script_version', 15, 1); add_filter('script_loader_src', '_remove_script_version', 15, 1); ```
You could use [add\_query\_arg()](http://developer.wordpress.org/reference/functions/add_query_arg) but then you'd have to parse the uri everytime, I'd rather create a wrapper function for wp\_enqueue\_script/style: ``` function my_enqueuer($my_handle, $relpath, $type='script', $my_deps=array()) { $uri = get_theme_file_uri($relpath); $vsn = filemtime(get_theme_file_path($relpath)); if($type == 'script') wp_enqueue_script($my_handle, $uri, $my_deps, $vsn); else if($type == 'style') wp_enqueue_style($my_handle, $uri, $my_deps, $vsn); } ``` Add this in your functions file and then in place of e.g. ``` wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js'))); ``` call: ``` my_enqueuer('_base', '/assets/js/base.js'); ``` and in place of e.g. ``` wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css'))); ``` call: ``` my_enqueuer('_base', '/assets/css/base.css', 'style'); ``` You can pass the dependency array as the last argument when needed. For scripts, if you pass the dependency array, you will have to pass the third parameter 'script' as well, even though I've set it as the default value.
269,794
<p><a href="https://i.stack.imgur.com/RIKPa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RIKPa.jpg" alt="Can You plz guide me"></a> how to create the logic that makes those posts sortable either by the first letter of title or numbers?</p> <p>I want when I click on a "letter" the posts must get updated with the given first letter I want when I click on a "letter" the posts must get updated with the given first letter</p> <p>If you want to check the original page: <a href="https://neverquit.000webhostapp.com/library" rel="nofollow noreferrer">https://neverquit.000webhostapp.com/library</a></p>
[ { "answer_id": 296408, "author": "Alex Sancho", "author_id": 2536, "author_profile": "https://wordpress.stackexchange.com/users/2536", "pm_score": 4, "selected": true, "text": "<p>I think there's a better approach, just create a custom taxonomy that holds the alphanumeric terms, then assign each post to the correct term.</p>\n\n<p>You can use the save post action to auto assign posts to correct term on post save:</p>\n\n<pre><code>function save_index( $post_id ) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n $slug = 'post';\n $letter = '';\n\n // only run for posts\n if ( isset( $_POST['post_type'] ) &amp;&amp; ( $slug != $_POST['post_type'] ) ) {\n return;\n }\n\n // Check user capabilities\n if ( ! current_user_can( 'edit_post', $post_id ) ) {\n return;\n }\n\n $taxonomy = 'index'; // our custom taxonomy\n\n if ( isset( $_POST['post_type'] ) ) {\n\n // Get the title of the post\n $title = strtolower( $_POST['post_title'] );\n\n // The next few lines remove A, An, or The from the start of the title\n $splitTitle = explode( ' ', $title );\n $blacklist = [ 'an ', 'a ', 'the ' ];\n $splitTitle[0] = str_replace( $blacklist, '', strtolower( $splitTitle[0] ) );\n $title = implode( ' ', $splitTitle );\n\n // Get the first letter of the title\n $letter = substr( $title, 0, 1 );\n\n // Set to 0-9 if it's a number\n if ( is_numeric( $letter ) ) {\n $letter = '0-9';\n }\n\n // set term as first letter of post title, lower case\n wp_set_post_terms( $post_id, $letter, $taxonomy );\n }\n}\n\nadd_action( 'save_post', 'save_index' );\n</code></pre>\n" }, { "answer_id": 297072, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 1, "selected": false, "text": "<p>This is a little short and not much detail. I have plans to come back to this in more detail at some point.</p>\n\n<p>However, in the short run, this solution should do exactly what you need. You'll need to expand on it obviously, but it does the basics.</p>\n\n<p>This example assumes the Post Type is <code>mbe-members</code> and the rewrite slug of the Post Type is <code>/member/</code>.</p>\n\n<h2>Step 1) Add the Custom Rewrite Rule and Query Variable</h2>\n\n<pre><code>add_action( 'init', function () {\n\n add_rewrite_tag( '%member-filter%', 'members/filter/([a-zA-Z0-9-]{1,3})', 'post_type=mbe-members&amp;filter=' );\n add_permastruct( 'member-filter', '%member-filter%', array( 'with_front' =&gt; false ) );\n\n} );\n</code></pre>\n\n<p>You need to make sure that this is performed before your Post Type has been registered.</p>\n\n<p>You'll also need to make sure you flush your rewrite rules.</p>\n\n<p><strong>Note:</strong> For extreme simplicity for now, the remainder of the tasks would be completed in your Post Type Archive theme template file. (I'll make this part better in the future)</p>\n\n<h2>Step 2) Determine What Needs to be Filtered</h2>\n\n<pre><code>$filter = get_query_var( 'filter' );\n$filter_start = null;\n$filter_end = null;\n\nif ( strpos( $filter, '-' ) !== false ) {\n\n if ( $pieces = explode( '-', $filter ) ) {\n\n if ( isset( $pieces[0] ) ) {\n $filter_start = $pieces[0];\n }\n\n if ( isset( $pieces[1] ) ) {\n $filter_end = $pieces[1];\n }\n\n }\n\n} else {\n $filter_start = substr( $filter, 0, 1 );\n}\n</code></pre>\n\n<p>This filtering also allows a range of letters or numbers. </p>\n\n<p>A/K/A -- You can specify: <code>/members/filter/a</code> or <code>/members/filter/a-z/</code></p>\n\n<h2>Step 3) Query Post IDs for Filtered Matches</h2>\n\n<pre><code>global $wpdb;\n\n$post_ids = array();\n\nif ( ! is_null( $filter_start ) &amp;&amp; ! is_null( $filter_end ) ) {\n\n $range = range( $filter_start, $filter_end );\n\n foreach ( $range as $value ) {\n\n $query_args = array(\n 'SELECT' =&gt; 'ID',\n 'FROM' =&gt; $wpdb-&gt;posts,\n 'WHERE' =&gt; 'post_title'\n );\n\n if ( $query = $wpdb-&gt;get_results( $wpdb-&gt;prepare( \"\n SELECT {$query_args['SELECT']}\n FROM {$query_args['FROM']}\n WHERE {$query_args['WHERE']}\n LIKE %s\n AND post_type = %s\n \", \"{$value}%\", 'mbe-members' ) ) ) {\n\n foreach ( $query as $result ) {\n\n if ( ! in_array( $result-&gt;ID, $post_ids ) ) {\n $post_ids[] = $result-&gt;ID;\n }\n\n }\n\n }\n\n }\n\n} else {\n\n if ( ! is_null( $filter_start ) ) {\n\n $value = $filter_start;\n\n $query_args = array(\n 'SELECT' =&gt; 'ID',\n 'FROM' =&gt; $wpdb-&gt;posts,\n 'WHERE' =&gt; 'post_title',\n );\n\n if ( is_numeric( $value ) ) {\n $query_args['LIKE'] = '%d';\n } else {\n $query_args['LIKE'] = '%s';\n }\n\n if ( $query = $wpdb-&gt;get_results( $wpdb-&gt;prepare( \"\n SELECT {$query_args['SELECT']}\n FROM {$query_args['FROM']}\n WHERE {$query_args['WHERE']}\n LIKE {$query_args['LIKE']}\n AND post_type = %s\n \", \"{$value}%\", \"mbe-members\" ) ) ) {\n\n foreach ( $query as $result ) {\n\n if ( ! in_array( $result-&gt;ID, $post_ids ) ) {\n $post_ids[] = $result-&gt;ID;\n }\n\n }\n\n }\n\n }\n\n}\n</code></pre>\n\n<h2>Step 4) Query the Post Objects and Output the Display</h2>\n\n<pre><code>$content = '';\n\nif ( ! empty( $post_ids ) ) {\n\n $query = new \\WP_Query( array(\n 'post_type' =&gt; 'mbe-members',\n 'posts_per_page' =&gt; absint( get_option( 'posts_per_page' ) ),\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'post_title',\n 'order' =&gt; 'ASC',\n 'update_post_meta_cache' =&gt; false,\n 'update_post_term_cache' =&gt; false,\n 'suppress_filters' =&gt; true,\n 'post__in' =&gt; $post_ids\n ) );\n\n if ( $query-&gt;have_posts() ) {\n\n foreach ( $query-&gt;posts as $post ) {\n $content .= $post-&gt;post_title . '&lt;br /&gt;';\n }\n\n }\n\n}\n\necho '&lt;div&gt;' . PHP_EOL;\n\necho '&lt;ul class=\"nav nav-tabs\" role=\"tablist\"&gt;' . PHP_EOL;\n\n$class = '';\n\nif ( $filter == '0-9' ) {\n $class = 'active';\n}\n\necho '&lt;li role=\"presentation\" class=\"' . $class . '\"&gt;&lt;a href=\"' . site_url( '/member/filter/0-9/' ) . '\" aria-controls=\"0-9\" role=\"tab\"&gt;0-9&lt;/a&gt;&lt;/li&gt;' . PHP_EOL;\n\nforeach ( range( 'a', 'z' ) as $letter ) {\n\n $class = '';\n\n if ( $letter == $filter_start ) {\n $class = 'active';\n }\n\n echo '&lt;li role=\"presentation\" class=\"' . $class . '\"&gt;&lt;a href=\"' . site_url( '/member/filter/' . $letter . '/' ) . '\" aria-controls=\"' . $letter . '\" role=\"tab\"&gt;' . $letter . '&lt;/a&gt;&lt;/li&gt;' . PHP_EOL;\n\n}\n\necho '&lt;/ul&gt;' . PHP_EOL;\n\necho '&lt;div class=\"tab-content\"&gt;' . PHP_EOL;\n\n$class = '';\n\nif ( $filter == '0-9' ) {\n $class = 'active';\n}\n\necho '&lt;div role=\"tabpanel\" class=\"tab-pane ' . $class . '\" id=\"0-9\"&gt;' . PHP_EOL;\n\nif ( $filter == '0-9' ) {\n echo $content;\n}\n\necho '&lt;/div&gt;' . PHP_EOL;\n\nforeach ( range( 'a', 'z' ) as $letter ) {\n\n $class = '';\n\n if ( $letter == $filter_start ) {\n $class = 'active';\n }\n\n echo '&lt;div role=\"tabpanel\" class=\"tab-pane ' . $class . '\" id=\"' . $letter . '\"&gt;' . PHP_EOL;\n\n if ( $letter == $filter_start ) {\n echo $content;\n }\n\n echo '&lt;/div&gt;' . PHP_EOL;\n\n}\n\necho '&lt;/div&gt;' . PHP_EOL;\n\necho '&lt;/div&gt;' . PHP_EOL;\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Like I said, this was a very quick answer. Which does indeed answer your question. It's very rough and simple, but it does what you need. I'll try to improve this answer to be a bit more of an elegant solution.</p>\n" } ]
2017/06/11
[ "https://wordpress.stackexchange.com/questions/269794", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116722/" ]
[![Can You plz guide me](https://i.stack.imgur.com/RIKPa.jpg)](https://i.stack.imgur.com/RIKPa.jpg) how to create the logic that makes those posts sortable either by the first letter of title or numbers? I want when I click on a "letter" the posts must get updated with the given first letter I want when I click on a "letter" the posts must get updated with the given first letter If you want to check the original page: <https://neverquit.000webhostapp.com/library>
I think there's a better approach, just create a custom taxonomy that holds the alphanumeric terms, then assign each post to the correct term. You can use the save post action to auto assign posts to correct term on post save: ``` function save_index( $post_id ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } $slug = 'post'; $letter = ''; // only run for posts if ( isset( $_POST['post_type'] ) && ( $slug != $_POST['post_type'] ) ) { return; } // Check user capabilities if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } $taxonomy = 'index'; // our custom taxonomy if ( isset( $_POST['post_type'] ) ) { // Get the title of the post $title = strtolower( $_POST['post_title'] ); // The next few lines remove A, An, or The from the start of the title $splitTitle = explode( ' ', $title ); $blacklist = [ 'an ', 'a ', 'the ' ]; $splitTitle[0] = str_replace( $blacklist, '', strtolower( $splitTitle[0] ) ); $title = implode( ' ', $splitTitle ); // Get the first letter of the title $letter = substr( $title, 0, 1 ); // Set to 0-9 if it's a number if ( is_numeric( $letter ) ) { $letter = '0-9'; } // set term as first letter of post title, lower case wp_set_post_terms( $post_id, $letter, $taxonomy ); } } add_action( 'save_post', 'save_index' ); ```
269,798
<p>I freshly installed a WordPress site and I configured it behind a reverse proxy with site URL - <code>http://example.com/hello</code></p> <h2>Problem</h2> <p>I can reach the admin dashboard page, however I cannot go further as the link becomes <code>http://example.com/wp-admin</code> instead of <code>http://example.com/hello/wp-admin</code>. How could I get rid of this weird behaviour?</p> <h2>Details that might help...</h2> <ol> <li>I am quite sure that the WordPress Address (URL) and Site Address (URL) are configured as <code>http://example.com/hello</code>, I even checked the database table <code>wp_options</code>.</li> <li>When it arrives the admin dashboard page with correct CSS, the browser will show the correct link for half seconds and suddenly change to the wrong one. I even checked the network log in my Chrome and Firefox, the requested URL is <code>http://example.com/hello/wp-admin</code>.</li> <li><p>I have tried to configure the <code>.htaccess</code> as well, but no luck.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /hello RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /hello/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre></li> </ol>
[ { "answer_id": 269801, "author": "Victor Wong", "author_id": 121572, "author_profile": "https://wordpress.stackexchange.com/users/121572", "pm_score": 2, "selected": false, "text": "<p>Eventually, I found the reason of this weird behaviour.</p>\n\n<p>It is caused by the JavaScript embedded in <code>wp_admin_canonical_url()</code> (<a href=\"https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/</a>)</p>\n\n<p>The URL is determined by this piece of code</p>\n\n<pre><code>$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']\n</code></pre>\n\n<p>where the latter one returns <code>wp-admin</code> instead of <code>hello/wp-admin</code>.</p>\n\n<p>By manipulating the value in <code>$_SERVER['REQUEST_URI']</code>, I can successfully get the correct behaviour in admin dashboard. But I still hope for an elegant solution without touching WordPress code.</p>\n" }, { "answer_id": 325259, "author": "Chad", "author_id": 158761, "author_profile": "https://wordpress.stackexchange.com/users/158761", "pm_score": -1, "selected": false, "text": "<p>Victor is 100%, so save the next person (maybe even myself) work digging further:</p>\n\n<ul>\n<li>the function wp_admin_canonical_url is in the ./wp-admin/includes/misc.php file </li>\n<li><p>Change </p>\n\n<p>$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] </p></li>\n</ul>\n\n<p>to be</p>\n\n<pre><code>$_SERVER['HTTP_HOST'] . '/news/. $_SERVER['REQUEST_URI']\n</code></pre>\n\n<p>Where /news can be anything you have as a path in front of the wp-admin folder. </p>\n" }, { "answer_id": 325268, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter('set_url_scheme', 'hacky_uri_fix', 10, 2);\nfunction hacky_uri_fix($url, $scheme) {\n if ( $url === {{BAD ADMIN URL}} ) {\n $url = {{CORRECT ADMIN URL}}\n }\n return $url\n}\n</code></pre>\n\n<p>should work, just replace the bad URL you are trying to avoid with the correct one. I'm sure there's a better solution to this out there but I'm not super familiar with subfolder installs and this should work without touching core code.</p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269798", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121572/" ]
I freshly installed a WordPress site and I configured it behind a reverse proxy with site URL - `http://example.com/hello` Problem ------- I can reach the admin dashboard page, however I cannot go further as the link becomes `http://example.com/wp-admin` instead of `http://example.com/hello/wp-admin`. How could I get rid of this weird behaviour? Details that might help... -------------------------- 1. I am quite sure that the WordPress Address (URL) and Site Address (URL) are configured as `http://example.com/hello`, I even checked the database table `wp_options`. 2. When it arrives the admin dashboard page with correct CSS, the browser will show the correct link for half seconds and suddenly change to the wrong one. I even checked the network log in my Chrome and Firefox, the requested URL is `http://example.com/hello/wp-admin`. 3. I have tried to configure the `.htaccess` as well, but no luck. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /hello RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /hello/index.php [L] </IfModule> # END WordPress ```
Eventually, I found the reason of this weird behaviour. It is caused by the JavaScript embedded in `wp_admin_canonical_url()` (<https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/>) The URL is determined by this piece of code ``` $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ``` where the latter one returns `wp-admin` instead of `hello/wp-admin`. By manipulating the value in `$_SERVER['REQUEST_URI']`, I can successfully get the correct behaviour in admin dashboard. But I still hope for an elegant solution without touching WordPress code.
269,836
<p>I have a WordPress site, which has a list of playlists, which are essentially custom post types.</p> <p>There is a screenshot below. I want to extend this so it also includes <code>playlist_id</code> as an option of input. </p> <p>Currently you see it just has Image, Portfolio Title, Categories and Date.</p> <p>Can anyone advise which file/files I should be looking at to include this new header?</p> <p>I have searched the entire project for Portolio Title but for some reason it cannot be found.</p> <p>It is important to note the <code>post_id</code> and <code>playlist_id</code> are the same thing. The <code>playlist_id</code> will actually come from spotify, and i want to be able to insert this to correspond with a playlist.</p> <p><a href="https://i.stack.imgur.com/kz47A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kz47A.png" alt="enter image description here"></a></p>
[ { "answer_id": 269801, "author": "Victor Wong", "author_id": 121572, "author_profile": "https://wordpress.stackexchange.com/users/121572", "pm_score": 2, "selected": false, "text": "<p>Eventually, I found the reason of this weird behaviour.</p>\n\n<p>It is caused by the JavaScript embedded in <code>wp_admin_canonical_url()</code> (<a href=\"https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/</a>)</p>\n\n<p>The URL is determined by this piece of code</p>\n\n<pre><code>$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']\n</code></pre>\n\n<p>where the latter one returns <code>wp-admin</code> instead of <code>hello/wp-admin</code>.</p>\n\n<p>By manipulating the value in <code>$_SERVER['REQUEST_URI']</code>, I can successfully get the correct behaviour in admin dashboard. But I still hope for an elegant solution without touching WordPress code.</p>\n" }, { "answer_id": 325259, "author": "Chad", "author_id": 158761, "author_profile": "https://wordpress.stackexchange.com/users/158761", "pm_score": -1, "selected": false, "text": "<p>Victor is 100%, so save the next person (maybe even myself) work digging further:</p>\n\n<ul>\n<li>the function wp_admin_canonical_url is in the ./wp-admin/includes/misc.php file </li>\n<li><p>Change </p>\n\n<p>$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] </p></li>\n</ul>\n\n<p>to be</p>\n\n<pre><code>$_SERVER['HTTP_HOST'] . '/news/. $_SERVER['REQUEST_URI']\n</code></pre>\n\n<p>Where /news can be anything you have as a path in front of the wp-admin folder. </p>\n" }, { "answer_id": 325268, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter('set_url_scheme', 'hacky_uri_fix', 10, 2);\nfunction hacky_uri_fix($url, $scheme) {\n if ( $url === {{BAD ADMIN URL}} ) {\n $url = {{CORRECT ADMIN URL}}\n }\n return $url\n}\n</code></pre>\n\n<p>should work, just replace the bad URL you are trying to avoid with the correct one. I'm sure there's a better solution to this out there but I'm not super familiar with subfolder installs and this should work without touching core code.</p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121592/" ]
I have a WordPress site, which has a list of playlists, which are essentially custom post types. There is a screenshot below. I want to extend this so it also includes `playlist_id` as an option of input. Currently you see it just has Image, Portfolio Title, Categories and Date. Can anyone advise which file/files I should be looking at to include this new header? I have searched the entire project for Portolio Title but for some reason it cannot be found. It is important to note the `post_id` and `playlist_id` are the same thing. The `playlist_id` will actually come from spotify, and i want to be able to insert this to correspond with a playlist. [![enter image description here](https://i.stack.imgur.com/kz47A.png)](https://i.stack.imgur.com/kz47A.png)
Eventually, I found the reason of this weird behaviour. It is caused by the JavaScript embedded in `wp_admin_canonical_url()` (<https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/>) The URL is determined by this piece of code ``` $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ``` where the latter one returns `wp-admin` instead of `hello/wp-admin`. By manipulating the value in `$_SERVER['REQUEST_URI']`, I can successfully get the correct behaviour in admin dashboard. But I still hope for an elegant solution without touching WordPress code.
269,853
<p>With WP 4.8 extending the widgets API, the simple text widget is using TinyMCE. The advantage is that TinyMCE scripts are already enqueued in Ajax requests.</p> <p>However, for a client, I need a widget which has <strong>multiple editors</strong> inside it. This widget is not only used on the Widgets' Page but also within the Plugin <strong><em>Page builder by SiteOrigin</em></strong>.</p> <p><em>With the new WordPress the following works in the widget form() function:</em></p> <pre><code>public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?&gt;&lt;div class="cis_editor_bwrap" &lt;?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?&gt;&gt;&lt;?php wp_editor(cisI8Extract($instance, 'text', $suf), 'text'.$suf ); ?&gt;&lt;/div&gt;&lt;?php } $this-&gt;containerInputHTML($instance); $this-&gt;linkWrapperInputHTML($instance); } </code></pre> <p>However, it only works as long as I have only one widget as the IDs will be duplicated as soon as a second widget is created. I need either a random number or the widget ID (note: the str_replace is needed as wp_editor does not accept the minus sign in ids).</p> <p><em>The following unfortunatly fails:</em></p> <pre><code>public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?&gt;&lt;div class="cis_editor_bwrap" &lt;?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?&gt;&gt;&lt;?php wp_editor(cisI8Extract($instance, 'text', $suf), str_replace("-","_",$this-&gt;get_field_id('text'.$suf)) ); ?&gt;&lt;/div&gt;&lt;?php } } </code></pre> <p>Somehow WordPress does not correctly instantiate TinyMCE if a random number or the widget ID are within the editor ID. Error message is like this: </p> <pre><code>wp-tinymce.php?c=1&amp;ver=4603-20170530:15 Uncaught TypeError: Cannot read property 'onpageload' of undefined at h (wp-tinymce.php?c=1&amp;ver=4603-20170530:15) at m (wp-tinymce.php?c=1&amp;ver=4603-20170530:15) at h.l.bind (wp-tinymce.php?c=1&amp;ver=4603-20170530:3) at o.bind (wp-tinymce.php?c=1&amp;ver=4603-20170530:5) at Object.init (wp-tinymce.php?c=1&amp;ver=4603-20170530:15) at e (editor.min.js?ver=4.8:1) at HTMLDocument.&lt;anonymous&gt; (editor.min.js?ver=4.8:1) at a (wp-tinymce.php?c=1&amp;ver=4603-20170530:3) at HTMLDocument.p (wp-tinymce.php?c=1&amp;ver=4603-20170530:3) </code></pre> <p>This is the HTML outputted by wp_editor if using possibility two:</p> <pre><code>&lt;div class="wp-core-ui wp-editor-wrap html-active" id="wp-widget_ciseditor_c27_text-wrap"&gt; &lt;link href="http://localhost/hiedler/wp-includes/css/dashicons.min.css?ver=4.8" id="dashicons-css" media="all" rel="stylesheet" type="text/css"&gt; &lt;link href="http://localhost/hiedler/wp-includes/css/editor.min.css?ver=4.8" id="editor-buttons-css" media="all" rel="stylesheet" type="text/css"&gt; &lt;div class="wp-editor-tools hide-if-no-js" id="wp-widget_ciseditor_c27_text-editor-tools"&gt; &lt;div class="wp-media-buttons" id="wp-widget_ciseditor_c27_text-media-buttons"&gt; &lt;button class="button insert-media add_media" data-editor="widget_ciseditor_c27_text" id="insert-media-button" type="button"&gt;&lt;span class="wp-media-buttons-icon"&gt;&lt;/span&gt; Dateien hinzufügen&lt;/button&gt; &lt;/div&gt; &lt;div class="wp-editor-tabs"&gt; &lt;button class="wp-switch-editor switch-tmce" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-tmce" type="button"&gt;Visuell&lt;/button&gt; &lt;button class="wp-switch-editor switch-html" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-html" type="button"&gt;Text&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="wp-editor-container" id="wp-widget_ciseditor_c27_text-editor-container"&gt; &lt;div class="quicktags-toolbar" id="qt_widget_ciseditor_c27_text_toolbar"&gt;&lt;/div&gt; &lt;textarea class="wp-editor-area" cols="40" id="widget_ciseditor_c27_text" name="widget_ciseditor_c27_text" rows="20"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>So my question is how can I solve this?</p> <p>I have the two ideas:</p> <ol> <li><p>Register the dynamic editor ID after widget creation/load and make it work. HOW?</p></li> <li><p>Do not use wp_editor() at all but use textareas and apply TinyMCE to them dynamically. Problems: File Upload will be missing. How to apply TinyMCE scripts on every new widget/widget load?</p></li> </ol> <p>Tried a lot of things so far but no luck.</p>
[ { "answer_id": 270853, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly the ID supplied to <code>wp_editor</code> needs to already exist. </p>\n\n<p>Perhaps it does for you elsewhere in your code, but it doesn't look like it from what I can see? I think it would need to be specified like this:</p>\n\n<pre><code>public function form( $instance ) {\n // ...\n foreach(cisI8Suffixes(true) as $suf) {\n $id = str_replace(\"-\",\"_\",$this-&gt;get_field_id('text'.$suf));\n ?&gt;&lt;div class=\"cis_editor_bwrap\" id=\"&lt;?php echo $id; ?&gt;\" &lt;?php echo (CIS_I8_ENABLE) ? 'data-cislan=\"'.cisLanFromSuf($suf).'\"': \"\"; ?&gt;&gt;&lt;?php\n wp_editor(cisI8Extract($instance, 'text', $suf), $id);\n ?&gt;&lt;/div&gt;&lt;?php\n }\n}\n</code></pre>\n" }, { "answer_id": 273103, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": false, "text": "<p>It's hard to say without seeing <em>all</em> the code.</p>\n\n<p>Yes if you don't refer to the instance - then it won't really be a unique ID. Something like this would work - you would just reference the class property $id:</p>\n\n<pre><code> for ( $i = 0; $i &lt;= count( $suffixes ); $i++) {\n wp_editor( 'your content', \"{$this-&gt;id}_$i\" );\n }\n</code></pre>\n\n<p>The js in core for the text widget create a random ID for the editor instances before it handles the instantiation, so you could translate that over to PHP if you wanted to follow that:</p>\n\n<pre><code> $el = 'el' . preg_replace( '/\\D/', '', ( rand()/getrandmax() ) ) . '_';\n</code></pre>\n\n<p>Since your developing locally - you should turn on SCRIPT_DEBUG in your wp-config.php: define( 'SCRIPT_DEBUG', true ); to help you troubleshoot your issues with javascript. Doing so would make that error from minified files be a little more meaningful. The error is being caused by switchEditor method in editor.min.js. There's special handling of the tinymce text widget in the customizer - and it's not just as simple as calling wp_editor - though it could probably be done. You could try enabling the wp_skip_init process and adding your own initialization code perhaps:</p>\n\n<pre><code> add_filter( 'wp_editor_settings', 'ciseditor_wp_editor_settings', 5, 2 );\n function ciseditor_wp_editor_settings( $settings, $id ) {\n // look for your prefixed id and return the id associated with it.\n if ( $ed = strstr( $id, 'foo_widget' ) ) {\n $settings['tinymce'] = array(\n 'wp_skip_init' =&gt; true,\n 'wp_autoresize_on' =&gt; false, // turn off the auto resize height of editor.\n );\n $settings['editor_height'] = 300; // set the height\n }\n return $settings;\n }\n</code></pre>\n\n<p>I'm pretty sure that won't be the way to go though. I would recommend looking at wp-admin/js/text-widgets.js to see the handling of how core is implementing the text widget and the switch editor functionality - along with properly handling the data for the customizer. You should also reference wp-includes/widgets/class-wp-widget-text.php since you're essentially wanting to make the same thing that already exists.</p>\n\n<p>Generally having that error in tinymce means that the instance isn't being removed and added back properly - so it makes sense that WordPress' switchEditor in this context is throwing errors for you. There's a lot of documentation in the text-widgets.js about how tinymce and dynamic DOM components will interact that have to be accounted for or you'll end up with issues.</p>\n\n<p>One quick solution might just be to disable quicktags for your editor instances, which could be done in the wp_editor_settings filter or you can also pass it in the settings array when you're making the editors, ie:</p>\n\n<pre><code>wp_editor( 'your content', \"{$this-&gt;id}_$i\", array( 'quicktags' =&gt; false ) );\n</code></pre>\n\n<p>I did dynamically create tinymce instances on a project once in wordpress, and I just remember looking at the editor code in core to see what arguments and scripts they included to get everything working, so that's always an option too. If you go that route - most of the things translate over 1:1 in terms of the php abstraction to js for the params. I think for the add media button I ended up creating my own thing, but there is the action 'media_buttons' so you should be able to just add that where it needs to be displayed.</p>\n\n<p>Also consider why it is that you need multiple editors in one widget. Another way to handle this would be to remove the instances in an accordion style within the widget itself, and rebuild them as accordions are expanded so only one widget is displayed at a time. I think ultimately though - having one editor in a widget suits most use cases, and gives the end user flexibility to move content where they find it most fitting for their own use.</p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
With WP 4.8 extending the widgets API, the simple text widget is using TinyMCE. The advantage is that TinyMCE scripts are already enqueued in Ajax requests. However, for a client, I need a widget which has **multiple editors** inside it. This widget is not only used on the Widgets' Page but also within the Plugin ***Page builder by SiteOrigin***. *With the new WordPress the following works in the widget form() function:* ``` public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?><div class="cis_editor_bwrap" <?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?>><?php wp_editor(cisI8Extract($instance, 'text', $suf), 'text'.$suf ); ?></div><?php } $this->containerInputHTML($instance); $this->linkWrapperInputHTML($instance); } ``` However, it only works as long as I have only one widget as the IDs will be duplicated as soon as a second widget is created. I need either a random number or the widget ID (note: the str\_replace is needed as wp\_editor does not accept the minus sign in ids). *The following unfortunatly fails:* ``` public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?><div class="cis_editor_bwrap" <?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?>><?php wp_editor(cisI8Extract($instance, 'text', $suf), str_replace("-","_",$this->get_field_id('text'.$suf)) ); ?></div><?php } } ``` Somehow WordPress does not correctly instantiate TinyMCE if a random number or the widget ID are within the editor ID. Error message is like this: ``` wp-tinymce.php?c=1&ver=4603-20170530:15 Uncaught TypeError: Cannot read property 'onpageload' of undefined at h (wp-tinymce.php?c=1&ver=4603-20170530:15) at m (wp-tinymce.php?c=1&ver=4603-20170530:15) at h.l.bind (wp-tinymce.php?c=1&ver=4603-20170530:3) at o.bind (wp-tinymce.php?c=1&ver=4603-20170530:5) at Object.init (wp-tinymce.php?c=1&ver=4603-20170530:15) at e (editor.min.js?ver=4.8:1) at HTMLDocument.<anonymous> (editor.min.js?ver=4.8:1) at a (wp-tinymce.php?c=1&ver=4603-20170530:3) at HTMLDocument.p (wp-tinymce.php?c=1&ver=4603-20170530:3) ``` This is the HTML outputted by wp\_editor if using possibility two: ``` <div class="wp-core-ui wp-editor-wrap html-active" id="wp-widget_ciseditor_c27_text-wrap"> <link href="http://localhost/hiedler/wp-includes/css/dashicons.min.css?ver=4.8" id="dashicons-css" media="all" rel="stylesheet" type="text/css"> <link href="http://localhost/hiedler/wp-includes/css/editor.min.css?ver=4.8" id="editor-buttons-css" media="all" rel="stylesheet" type="text/css"> <div class="wp-editor-tools hide-if-no-js" id="wp-widget_ciseditor_c27_text-editor-tools"> <div class="wp-media-buttons" id="wp-widget_ciseditor_c27_text-media-buttons"> <button class="button insert-media add_media" data-editor="widget_ciseditor_c27_text" id="insert-media-button" type="button"><span class="wp-media-buttons-icon"></span> Dateien hinzufügen</button> </div> <div class="wp-editor-tabs"> <button class="wp-switch-editor switch-tmce" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-tmce" type="button">Visuell</button> <button class="wp-switch-editor switch-html" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-html" type="button">Text</button> </div> </div> <div class="wp-editor-container" id="wp-widget_ciseditor_c27_text-editor-container"> <div class="quicktags-toolbar" id="qt_widget_ciseditor_c27_text_toolbar"></div> <textarea class="wp-editor-area" cols="40" id="widget_ciseditor_c27_text" name="widget_ciseditor_c27_text" rows="20"></textarea> </div> </div> ``` So my question is how can I solve this? I have the two ideas: 1. Register the dynamic editor ID after widget creation/load and make it work. HOW? 2. Do not use wp\_editor() at all but use textareas and apply TinyMCE to them dynamically. Problems: File Upload will be missing. How to apply TinyMCE scripts on every new widget/widget load? Tried a lot of things so far but no luck.
It's hard to say without seeing *all* the code. Yes if you don't refer to the instance - then it won't really be a unique ID. Something like this would work - you would just reference the class property $id: ``` for ( $i = 0; $i <= count( $suffixes ); $i++) { wp_editor( 'your content', "{$this->id}_$i" ); } ``` The js in core for the text widget create a random ID for the editor instances before it handles the instantiation, so you could translate that over to PHP if you wanted to follow that: ``` $el = 'el' . preg_replace( '/\D/', '', ( rand()/getrandmax() ) ) . '_'; ``` Since your developing locally - you should turn on SCRIPT\_DEBUG in your wp-config.php: define( 'SCRIPT\_DEBUG', true ); to help you troubleshoot your issues with javascript. Doing so would make that error from minified files be a little more meaningful. The error is being caused by switchEditor method in editor.min.js. There's special handling of the tinymce text widget in the customizer - and it's not just as simple as calling wp\_editor - though it could probably be done. You could try enabling the wp\_skip\_init process and adding your own initialization code perhaps: ``` add_filter( 'wp_editor_settings', 'ciseditor_wp_editor_settings', 5, 2 ); function ciseditor_wp_editor_settings( $settings, $id ) { // look for your prefixed id and return the id associated with it. if ( $ed = strstr( $id, 'foo_widget' ) ) { $settings['tinymce'] = array( 'wp_skip_init' => true, 'wp_autoresize_on' => false, // turn off the auto resize height of editor. ); $settings['editor_height'] = 300; // set the height } return $settings; } ``` I'm pretty sure that won't be the way to go though. I would recommend looking at wp-admin/js/text-widgets.js to see the handling of how core is implementing the text widget and the switch editor functionality - along with properly handling the data for the customizer. You should also reference wp-includes/widgets/class-wp-widget-text.php since you're essentially wanting to make the same thing that already exists. Generally having that error in tinymce means that the instance isn't being removed and added back properly - so it makes sense that WordPress' switchEditor in this context is throwing errors for you. There's a lot of documentation in the text-widgets.js about how tinymce and dynamic DOM components will interact that have to be accounted for or you'll end up with issues. One quick solution might just be to disable quicktags for your editor instances, which could be done in the wp\_editor\_settings filter or you can also pass it in the settings array when you're making the editors, ie: ``` wp_editor( 'your content', "{$this->id}_$i", array( 'quicktags' => false ) ); ``` I did dynamically create tinymce instances on a project once in wordpress, and I just remember looking at the editor code in core to see what arguments and scripts they included to get everything working, so that's always an option too. If you go that route - most of the things translate over 1:1 in terms of the php abstraction to js for the params. I think for the add media button I ended up creating my own thing, but there is the action 'media\_buttons' so you should be able to just add that where it needs to be displayed. Also consider why it is that you need multiple editors in one widget. Another way to handle this would be to remove the instances in an accordion style within the widget itself, and rebuild them as accordions are expanded so only one widget is displayed at a time. I think ultimately though - having one editor in a widget suits most use cases, and gives the end user flexibility to move content where they find it most fitting for their own use.
269,856
<p>I need to add custom item to WooCommerce My Account navigation. I can add the item with no problem. Since it is a link to user's profile I use the following code:</p> <pre><code>&lt;?php global $switched; switch_to_blog(2); ?&gt; &lt;a href=”&lt;?php echo bp_loggedin_user_domain(); ?&gt;”&gt;Profile&lt;/a&gt; &lt;?php restore_current_blog(); //switched back to main site ?&gt; </code></pre> <p>First I switch to BuddyPress which handles users (multisite newtork). Then I use bp_loggedin_user_domain to get user profile url.</p> <p>But the actual output of the link is incorrect, I get: www.domain.com/my-account/"www.subdomain.domain.com/members/profile/"</p> <p>I know that My Account page treats all links as child pages with WooCommerce endpoints, but is there a way to get the external url there? Without WooCommerce's default domain.com/my-account/ prefix</p>
[ { "answer_id": 270853, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly the ID supplied to <code>wp_editor</code> needs to already exist. </p>\n\n<p>Perhaps it does for you elsewhere in your code, but it doesn't look like it from what I can see? I think it would need to be specified like this:</p>\n\n<pre><code>public function form( $instance ) {\n // ...\n foreach(cisI8Suffixes(true) as $suf) {\n $id = str_replace(\"-\",\"_\",$this-&gt;get_field_id('text'.$suf));\n ?&gt;&lt;div class=\"cis_editor_bwrap\" id=\"&lt;?php echo $id; ?&gt;\" &lt;?php echo (CIS_I8_ENABLE) ? 'data-cislan=\"'.cisLanFromSuf($suf).'\"': \"\"; ?&gt;&gt;&lt;?php\n wp_editor(cisI8Extract($instance, 'text', $suf), $id);\n ?&gt;&lt;/div&gt;&lt;?php\n }\n}\n</code></pre>\n" }, { "answer_id": 273103, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": false, "text": "<p>It's hard to say without seeing <em>all</em> the code.</p>\n\n<p>Yes if you don't refer to the instance - then it won't really be a unique ID. Something like this would work - you would just reference the class property $id:</p>\n\n<pre><code> for ( $i = 0; $i &lt;= count( $suffixes ); $i++) {\n wp_editor( 'your content', \"{$this-&gt;id}_$i\" );\n }\n</code></pre>\n\n<p>The js in core for the text widget create a random ID for the editor instances before it handles the instantiation, so you could translate that over to PHP if you wanted to follow that:</p>\n\n<pre><code> $el = 'el' . preg_replace( '/\\D/', '', ( rand()/getrandmax() ) ) . '_';\n</code></pre>\n\n<p>Since your developing locally - you should turn on SCRIPT_DEBUG in your wp-config.php: define( 'SCRIPT_DEBUG', true ); to help you troubleshoot your issues with javascript. Doing so would make that error from minified files be a little more meaningful. The error is being caused by switchEditor method in editor.min.js. There's special handling of the tinymce text widget in the customizer - and it's not just as simple as calling wp_editor - though it could probably be done. You could try enabling the wp_skip_init process and adding your own initialization code perhaps:</p>\n\n<pre><code> add_filter( 'wp_editor_settings', 'ciseditor_wp_editor_settings', 5, 2 );\n function ciseditor_wp_editor_settings( $settings, $id ) {\n // look for your prefixed id and return the id associated with it.\n if ( $ed = strstr( $id, 'foo_widget' ) ) {\n $settings['tinymce'] = array(\n 'wp_skip_init' =&gt; true,\n 'wp_autoresize_on' =&gt; false, // turn off the auto resize height of editor.\n );\n $settings['editor_height'] = 300; // set the height\n }\n return $settings;\n }\n</code></pre>\n\n<p>I'm pretty sure that won't be the way to go though. I would recommend looking at wp-admin/js/text-widgets.js to see the handling of how core is implementing the text widget and the switch editor functionality - along with properly handling the data for the customizer. You should also reference wp-includes/widgets/class-wp-widget-text.php since you're essentially wanting to make the same thing that already exists.</p>\n\n<p>Generally having that error in tinymce means that the instance isn't being removed and added back properly - so it makes sense that WordPress' switchEditor in this context is throwing errors for you. There's a lot of documentation in the text-widgets.js about how tinymce and dynamic DOM components will interact that have to be accounted for or you'll end up with issues.</p>\n\n<p>One quick solution might just be to disable quicktags for your editor instances, which could be done in the wp_editor_settings filter or you can also pass it in the settings array when you're making the editors, ie:</p>\n\n<pre><code>wp_editor( 'your content', \"{$this-&gt;id}_$i\", array( 'quicktags' =&gt; false ) );\n</code></pre>\n\n<p>I did dynamically create tinymce instances on a project once in wordpress, and I just remember looking at the editor code in core to see what arguments and scripts they included to get everything working, so that's always an option too. If you go that route - most of the things translate over 1:1 in terms of the php abstraction to js for the params. I think for the add media button I ended up creating my own thing, but there is the action 'media_buttons' so you should be able to just add that where it needs to be displayed.</p>\n\n<p>Also consider why it is that you need multiple editors in one widget. Another way to handle this would be to remove the instances in an accordion style within the widget itself, and rebuild them as accordions are expanded so only one widget is displayed at a time. I think ultimately though - having one editor in a widget suits most use cases, and gives the end user flexibility to move content where they find it most fitting for their own use.</p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269856", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93413/" ]
I need to add custom item to WooCommerce My Account navigation. I can add the item with no problem. Since it is a link to user's profile I use the following code: ``` <?php global $switched; switch_to_blog(2); ?> <a href=”<?php echo bp_loggedin_user_domain(); ?>”>Profile</a> <?php restore_current_blog(); //switched back to main site ?> ``` First I switch to BuddyPress which handles users (multisite newtork). Then I use bp\_loggedin\_user\_domain to get user profile url. But the actual output of the link is incorrect, I get: www.domain.com/my-account/"www.subdomain.domain.com/members/profile/" I know that My Account page treats all links as child pages with WooCommerce endpoints, but is there a way to get the external url there? Without WooCommerce's default domain.com/my-account/ prefix
It's hard to say without seeing *all* the code. Yes if you don't refer to the instance - then it won't really be a unique ID. Something like this would work - you would just reference the class property $id: ``` for ( $i = 0; $i <= count( $suffixes ); $i++) { wp_editor( 'your content', "{$this->id}_$i" ); } ``` The js in core for the text widget create a random ID for the editor instances before it handles the instantiation, so you could translate that over to PHP if you wanted to follow that: ``` $el = 'el' . preg_replace( '/\D/', '', ( rand()/getrandmax() ) ) . '_'; ``` Since your developing locally - you should turn on SCRIPT\_DEBUG in your wp-config.php: define( 'SCRIPT\_DEBUG', true ); to help you troubleshoot your issues with javascript. Doing so would make that error from minified files be a little more meaningful. The error is being caused by switchEditor method in editor.min.js. There's special handling of the tinymce text widget in the customizer - and it's not just as simple as calling wp\_editor - though it could probably be done. You could try enabling the wp\_skip\_init process and adding your own initialization code perhaps: ``` add_filter( 'wp_editor_settings', 'ciseditor_wp_editor_settings', 5, 2 ); function ciseditor_wp_editor_settings( $settings, $id ) { // look for your prefixed id and return the id associated with it. if ( $ed = strstr( $id, 'foo_widget' ) ) { $settings['tinymce'] = array( 'wp_skip_init' => true, 'wp_autoresize_on' => false, // turn off the auto resize height of editor. ); $settings['editor_height'] = 300; // set the height } return $settings; } ``` I'm pretty sure that won't be the way to go though. I would recommend looking at wp-admin/js/text-widgets.js to see the handling of how core is implementing the text widget and the switch editor functionality - along with properly handling the data for the customizer. You should also reference wp-includes/widgets/class-wp-widget-text.php since you're essentially wanting to make the same thing that already exists. Generally having that error in tinymce means that the instance isn't being removed and added back properly - so it makes sense that WordPress' switchEditor in this context is throwing errors for you. There's a lot of documentation in the text-widgets.js about how tinymce and dynamic DOM components will interact that have to be accounted for or you'll end up with issues. One quick solution might just be to disable quicktags for your editor instances, which could be done in the wp\_editor\_settings filter or you can also pass it in the settings array when you're making the editors, ie: ``` wp_editor( 'your content', "{$this->id}_$i", array( 'quicktags' => false ) ); ``` I did dynamically create tinymce instances on a project once in wordpress, and I just remember looking at the editor code in core to see what arguments and scripts they included to get everything working, so that's always an option too. If you go that route - most of the things translate over 1:1 in terms of the php abstraction to js for the params. I think for the add media button I ended up creating my own thing, but there is the action 'media\_buttons' so you should be able to just add that where it needs to be displayed. Also consider why it is that you need multiple editors in one widget. Another way to handle this would be to remove the instances in an accordion style within the widget itself, and rebuild them as accordions are expanded so only one widget is displayed at a time. I think ultimately though - having one editor in a widget suits most use cases, and gives the end user flexibility to move content where they find it most fitting for their own use.
269,862
<p>How to set custom title of custom page template?</p> <p>I try use <code>wp_title</code> filter but it's not working.</p>
[ { "answer_id": 269864, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You can do a conditional and check if you are on a custom post type page, and then update the title:</p>\n\n<pre><code>function my_wp_title( $title, $sep ) {\n if (is_single('post-tyle')){\n // Update the title here, for example : $title .= $title . $post-&gt;post_title;\n }\n return $title;\n}\nadd_filter( 'wp_title', 'my_wp_title', 10, 2 );\n</code></pre>\n\n<p>However, your theme must support <code>wp_title</code>. For doing so, add this in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n" }, { "answer_id": 320290, "author": "Rajesh Pundeer", "author_id": 154766, "author_profile": "https://wordpress.stackexchange.com/users/154766", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/questions/62415/changing-document-title-only-on-a-custom-page-template/62417?newreg=9e9601805cd5461e9ab988dc3e605854\">Reference</a></p>\n\n<p>Got success by adding this code to <code>your-page-template.php</code> file before <code>get_header()</code> function: </p>\n\n<pre><code>function my_page_title() {\n return 'Your value is '; // add dynamic content to this title (if needed)\n}\nadd_action( 'pre_get_document_title', 'my_page_title' );\n</code></pre>\n" }, { "answer_id": 338510, "author": "Fanky", "author_id": 89973, "author_profile": "https://wordpress.stackexchange.com/users/89973", "pm_score": -1, "selected": false, "text": "<p>There are times when you cannot do this from functions.php (you don't have the data you want to output yet). For these cases:</p>\n\n<p>make a new copied header file <code>header-mycustom.php</code> and load it in your template</p>\n\n<pre><code>global $newtitle;\n$newtitle=\"New Title\";\nget_header(\"mycustom\");\n</code></pre>\n\n<p>in the <code>header-mycustom.php</code> replace <code>wp_head</code> with the following:</p>\n\n<pre><code>&lt;?php \nob_start();\nwp_head();\n$output = ob_get_contents();\nob_end_clean();\nglobal $newtitle;\n$output=preg_replace(\"/&lt;title&gt;(.+)&lt;\\/title&gt;/\",\"&lt;title&gt;$newtitle&lt;/title&gt;\",$output);\necho $output; \n?&gt;\n</code></pre>\n\n<p>(This is the first time I feel I have to hack WP for such common task.)</p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117356/" ]
How to set custom title of custom page template? I try use `wp_title` filter but it's not working.
[Reference](https://wordpress.stackexchange.com/questions/62415/changing-document-title-only-on-a-custom-page-template/62417?newreg=9e9601805cd5461e9ab988dc3e605854) Got success by adding this code to `your-page-template.php` file before `get_header()` function: ``` function my_page_title() { return 'Your value is '; // add dynamic content to this title (if needed) } add_action( 'pre_get_document_title', 'my_page_title' ); ```
269,868
<p>I migrated my WordPress site to a new host and new URL. I've done all the typical search and replace in mysql and the site works great.</p> <p>However, the links of my images are all missing <code>.co.uk</code>, thus not working.</p> <p><a href="https://i.stack.imgur.com/T9Rmn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T9Rmn.jpg" alt="Image below"></a></p> <p>The odd thing is, all the image URLs are correct in the source code of blogs. But in my media library, they are all missing .co.uk.</p> <p>How do I add .co.uk back into my media library URLs?</p>
[ { "answer_id": 269881, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 3, "selected": false, "text": "<p>As mentioned in the comments under your question, some data in the WordPress database is serialized and therefore not possible to change with a simple find and replace.</p>\n<p>You should read through the <a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\">Moving WordPress</a> section of the codex. Specifically the <a href=\"https://codex.wordpress.org/Moving_WordPress#Changing_Your_Domain_Name_and_URLs\" rel=\"nofollow noreferrer\">Changing Your Domain Name and URLs</a> portion. I usually use a plugin or a command line tool depending on what's available to me.</p>\n<h3>Plugin:</h3>\n<p><a href=\"https://wordpress.org/plugins/better-search-replace/#description\" rel=\"nofollow noreferrer\">Better Search Replace</a> is a useful plugin recommended in the entry above. There are other plugins that will do the same things but this is my preference. Some features that I enjoy are:</p>\n<ul>\n<li>Support for serialized data.</li>\n<li>The ability to select single or multiple tables.</li>\n<li>A &quot;dry run&quot; feature to test and verify your changes before actually performing them.</li>\n<li>Very few server requirements (all you <em>need</em> is a WP instance.)</li>\n</ul>\n<hr/>\n<h3>CLI Tool:</h3>\n<p>Another option that handles serialized data is the <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">WP-CLI's search-replace tool</a>. This option is used from the command line via something like SSH and requires the wp-cli to be installed on the server. You can <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">take a look at the docs</a> for all available options and examples but the basic usage is:</p>\n<pre><code># Search for old domain name and replace it with a new one\n$ wp search-replace 'http://old.example.dev' 'http://new.example.com'\n</code></pre>\n" }, { "answer_id": 269938, "author": "s.poole", "author_id": 81862, "author_profile": "https://wordpress.stackexchange.com/users/81862", "pm_score": 0, "selected": false, "text": "<p>My 'home' option_name in wp_options table was missing the .co.uk. Silly mistake! Next time, I'll try the migration plugins you helped out with.</p>\n" }, { "answer_id": 365911, "author": "Elizabeth", "author_id": 187470, "author_profile": "https://wordpress.stackexchange.com/users/187470", "pm_score": 0, "selected": false, "text": "<p>Came to look this up - try this plugin as well as Velvet Blues Update URL - neither worked. Then I realized, why on earth am I not just updating this via MySQL? </p>\n\n<p>First, update your wp_posts table. Then your SQL looks like this:</p>\n\n<pre><code> UPDATE `wp_posts` SET post_content = REPLACE(post_content, 'oldurl', 'newurl') WHERE post_content like \"%oldurl%\"\n</code></pre>\n" }, { "answer_id": 365912, "author": "made2popular", "author_id": 173347, "author_profile": "https://wordpress.stackexchange.com/users/173347", "pm_score": 0, "selected": false, "text": "<p>You should use WP all in one migration plugin to migrate the website. <a href=\"https://wordpress.org/plugins/all-in-one-wp-migration/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/all-in-one-wp-migration/</a></p>\n" }, { "answer_id": 365915, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 1, "selected": false, "text": "<p>This is a pretty common problem, so I think it deserves a thorough answer that covers the situation most are probably Googling when they find this.</p>\n\n<h3>For Montrealist's Specific Issue</h3>\n\n<p>For the specific question, it looks like @montrealist improperly ran a database find/replace process at some point. I see the URL for the media is:</p>\n\n<p><code>http://www.cosworth-europe/sam/wp-content/...</code></p>\n\n<p>I'm guessing that this should be:</p>\n\n<p><code>http://www.cosworth-europe.co.uk/sam/wp-content/...</code></p>\n\n<p>At some point, you lost the host TLD, so that's the first thing that would be worth looking at here. You could re-run a find and replace with something like this:</p>\n\n<ul>\n<li><strong>Find:</strong> <code>//www.cosworth-europe/</code> </li>\n<li><strong>Replace:</strong> <code>//www.cosworth-europe.co.uk/</code> </li>\n</ul>\n\n<p>This should correct the specific issue I see here, assuming that my assumptions are correct here.</p>\n\n<h3>For Those Googling Similar Issues</h3>\n\n<p>WordPress stores many references to URL's inside of its database. There's no single source config for a site's host, so you'll need to run a database find and replace the process to fix this. Depending on where those images are used, you may need to make sure that serialized strings are properly replaced as well.</p>\n\n<p>For most cases, I'd recommend this as the best fix:</p>\n\n<ol>\n<li>Install the <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better Search Replace</a> plugin</li>\n<li>Find and replace your domain excluding the protocol, so find <code>//www.olddomain.com</code> with <code>//www.newdomain.com</code></li>\n<li>Test and confirm that there are no issues, then uninstall and remove the plugin</li>\n</ol>\n\n<p>I don't typically recommend plugins as solutions, I code most everything minimally myself but for this specific case, I'd personally use the <em>WP Migrate DB Pro</em> plugin for this and other database related transfers. The <em>Better Search and Replace</em> plugin is developed by the same company, Delicious Brains, and it provides the exact same find and replace process. It's a great option for thoroughly solving this problem.</p>\n\n<p>If you do encounter issues, and you're unable to login to WordPress you can (S)FTP into your installs directory and set or update the following constants in your <code>wp-config.php</code> file:</p>\n\n<pre><code>define( 'WP_HOME', 'https://www.example.com' );\ndefine( 'WP_SITEURL', 'https://www.example.com' );\n</code></pre>\n\n<p>This should only be done temporarily though, once you correct the issue in the database it's best to remove this from your <code>wp-config.php</code> file afterward.</p>\n\n<p><a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">Changing The Site URL</a></p>\n" }, { "answer_id": 399102, "author": "sudhan", "author_id": 215745, "author_profile": "https://wordpress.stackexchange.com/users/215745", "pm_score": 0, "selected": false, "text": "<p>Change Uploading Files location in WordPress dashboard <strong>Dashboard &gt; Settings &gt; Media &gt; Uploading Files.</strong></p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81862/" ]
I migrated my WordPress site to a new host and new URL. I've done all the typical search and replace in mysql and the site works great. However, the links of my images are all missing `.co.uk`, thus not working. [![Image below](https://i.stack.imgur.com/T9Rmn.jpg)](https://i.stack.imgur.com/T9Rmn.jpg) The odd thing is, all the image URLs are correct in the source code of blogs. But in my media library, they are all missing .co.uk. How do I add .co.uk back into my media library URLs?
As mentioned in the comments under your question, some data in the WordPress database is serialized and therefore not possible to change with a simple find and replace. You should read through the [Moving WordPress](https://codex.wordpress.org/Moving_WordPress) section of the codex. Specifically the [Changing Your Domain Name and URLs](https://codex.wordpress.org/Moving_WordPress#Changing_Your_Domain_Name_and_URLs) portion. I usually use a plugin or a command line tool depending on what's available to me. ### Plugin: [Better Search Replace](https://wordpress.org/plugins/better-search-replace/#description) is a useful plugin recommended in the entry above. There are other plugins that will do the same things but this is my preference. Some features that I enjoy are: * Support for serialized data. * The ability to select single or multiple tables. * A "dry run" feature to test and verify your changes before actually performing them. * Very few server requirements (all you *need* is a WP instance.) --- ### CLI Tool: Another option that handles serialized data is the [WP-CLI's search-replace tool](https://developer.wordpress.org/cli/commands/search-replace/). This option is used from the command line via something like SSH and requires the wp-cli to be installed on the server. You can [take a look at the docs](https://developer.wordpress.org/cli/commands/search-replace/) for all available options and examples but the basic usage is: ``` # Search for old domain name and replace it with a new one $ wp search-replace 'http://old.example.dev' 'http://new.example.com' ```
269,878
<p>I'm struggling with WordPress Multisite page creation when newly site created. I found some hooks to achieve this but the hook is not responding. Some of the resources I found on stack and other sites are <a href="https://stackoverflow.com/questions/40014419/wordpress-multisite-default-page-for-newly-created-site">https://stackoverflow.com/questions/40014419/wordpress-multisite-default-page-for-newly-created-site</a> and <a href="http://www.wpbeginner.com/wp-tutorials/how-to-add-remove-default-pages-in-wordpress-multisite/" rel="nofollow noreferrer">http://www.wpbeginner.com/wp-tutorials/how-to-add-remove-default-pages-in-wordpress-multisite/</a></p> <p>The hook mentioned in these resources not working in my multisite setup.</p> <pre><code>add_action('wpmu_new_blog', 'wpb_create_my_pages', 10, 2); function wpb_create_my_pages($blog_id, $user_id){ switch_to_blog($blog_id); // create new page $page_id = wp_insert_post(array( 'post_title' =&gt; 'About', 'post_name' =&gt; 'about', 'post_content' =&gt; 'This is an about page. Feel free to edit or delete this page.', 'post_status' =&gt; 'publish', 'post_author' =&gt; $user_id, // or "1" (super-admin?) 'post_type' =&gt; 'page', 'menu_order' =&gt; 1, 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', )); // Find and delete the WP default 'Sample Page' $defaultPage = get_page_by_title( 'Sample Page' ); wp_delete_post( $defaultPage-&gt;ID ); restore_current_blog(); } </code></pre> <p>I'm adding this code in my child theme functions.php file. Any suggestion to fix this issue.</p>
[ { "answer_id": 269888, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 3, "selected": true, "text": "<p>The code you provided works great on my multisite. I am putting it in a network activated plugin though. Try the same.</p>\n" }, { "answer_id": 400363, "author": "Lautaro Ayosa", "author_id": 216972, "author_profile": "https://wordpress.stackexchange.com/users/216972", "pm_score": 1, "selected": false, "text": "<p>The &quot;wpmu_new_blog&quot; hook has been deprecated! Instead you should use the &quot;wp_initialize_site&quot; hook. For some reason Per Søderlind recomended using a priority higher than 100 in <a href=\"https://developer.wordpress.org/reference/hooks/wp_insert_site/\" rel=\"nofollow noreferrer\">this post</a>.</p>\n<p>The rest is pretty much the same. The only change that has been made (also taking advice from the post that Per Søderlind did) was to change the $blog_id to $new_site-&gt;blog_id. It didn't worked for me using only $blog_id.</p>\n<p>Also, important detail. I've this piece of code as an mu-plugin.</p>\n<pre><code>add_action('wp_initialize_site', 'wpb_create_my_pages', 910, 1);\n\nfunction wpb_create_my_pages(WP_Site $new_site){\n switch_to_blog($new_site-&gt;blog_id);\n\n// create new page\n $page_id = wp_insert_post(array(\n 'post_title' =&gt; 'About',\n 'post_name' =&gt; 'about',\n 'post_content' =&gt; 'Page content goes in here',\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_type' =&gt; 'page',\n 'menu_order' =&gt; 1,\n 'comment_status' =&gt; 'closed',\n 'ping_status' =&gt; 'closed',\n )); \n\n// Find and delete the WP default 'Sample Page'\n$defaultPage = get_page_by_title( 'Sample Page' );\nwp_delete_post( $defaultPage-&gt;ID );\n\n restore_current_blog();\n}\n</code></pre>\n<p>Hope this works!</p>\n" } ]
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60914/" ]
I'm struggling with WordPress Multisite page creation when newly site created. I found some hooks to achieve this but the hook is not responding. Some of the resources I found on stack and other sites are <https://stackoverflow.com/questions/40014419/wordpress-multisite-default-page-for-newly-created-site> and <http://www.wpbeginner.com/wp-tutorials/how-to-add-remove-default-pages-in-wordpress-multisite/> The hook mentioned in these resources not working in my multisite setup. ``` add_action('wpmu_new_blog', 'wpb_create_my_pages', 10, 2); function wpb_create_my_pages($blog_id, $user_id){ switch_to_blog($blog_id); // create new page $page_id = wp_insert_post(array( 'post_title' => 'About', 'post_name' => 'about', 'post_content' => 'This is an about page. Feel free to edit or delete this page.', 'post_status' => 'publish', 'post_author' => $user_id, // or "1" (super-admin?) 'post_type' => 'page', 'menu_order' => 1, 'comment_status' => 'closed', 'ping_status' => 'closed', )); // Find and delete the WP default 'Sample Page' $defaultPage = get_page_by_title( 'Sample Page' ); wp_delete_post( $defaultPage->ID ); restore_current_blog(); } ``` I'm adding this code in my child theme functions.php file. Any suggestion to fix this issue.
The code you provided works great on my multisite. I am putting it in a network activated plugin though. Try the same.
269,934
<p>I'm using <em>Knowall</em> theme for WordPress. I've developed a child theme with the following code placed in my <code>style.css</code> file in my child theme's folder:</p> <pre><code>/* Theme Name: KnowAll Child Theme Theme URI: help.mysite.com Description: Help site Author: myurl.com Template: knowall Version: 1.0 */ @import url("../knowall/css/style.css"); </code></pre> <p>This works (child theme is shown in WordPress) but created the following broken link:</p> <pre><code>http://help.mysite.com/wp-content/themes/knowall-child/css/style.css?ver=4.8 </code></pre> <p>So it looks like it's trying to locate the core Knowall style.css from within the child theme rather than the parent folder.</p> <p>I've 'fixed' this by importing the parent style.css directly into the child theme folder. I've also had to do the same for the 'img' folder. </p> <p>How can I re-target these assets so it finds them in the parent theme? I don't want to have to re-import assets to the child theme every time I update Wordpress...</p>
[ { "answer_id": 269961, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>There is most likely some issues about using <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a>.</p>\n\n<p>According to WordPress Code reference:</p>\n\n<blockquote>\n <p><code>get_template_directory_uri()</code> function returns the URL to the root theme. If a child theme is\n used and you want to return the URL to the current child theme, use\n <code>get_stylesheet_directory_uri()</code> instead.</p>\n</blockquote>\n\n<p>Also, it is <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">noted</a> that importing the parent CSS file is not a good practice anymore:</p>\n\n<blockquote>\n <p>Note that the previous method was to import the parent theme\n stylesheet using @import: this is no longer best practice, as it\n increases the amount of time it takes style sheets to load. The\n correct method of enqueuing the parent theme stylesheet is to add a\n <code>wp_enqueue_scripts</code> action and use <code>wp_enqueue_style()</code> in your child\n theme's functions.php.</p>\n</blockquote>\n\n<p>So, what you have to do is to enqueue the style by using the following code in your child theme's functions.php file:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' );\nfunction my_child_theme_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n\n}\n</code></pre>\n\n<p>And then enqueue your own CSS files if there is any.</p>\n" }, { "answer_id": 269962, "author": "Markus Hirsch", "author_id": 109453, "author_profile": "https://wordpress.stackexchange.com/users/109453", "pm_score": 0, "selected": false, "text": "<p>I think so I understand you wrong or you don´t know 100% for what you use a child-theme. </p>\n\n<blockquote>\n <p>A child theme is a theme that inherits the functionality and styling of another theme, called the parent theme. Child themes are the recommended way of modifying an existing theme.</p>\n</blockquote>\n\n<p><a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a></p>\n\n<p>You don´t need to import the parent style in your child.\nIn style.css you include your own coded css.</p>\n\n<p>Your folder structur are: wp-content/theme/knowall-child/css/style.css\nand in css/style.css is your custom css code.</p>\n\n<p>Switch your style.css to:</p>\n\n<pre><code>/*\nTheme Name: KnowAll Child Theme\nTheme URI: help.mysite.com\nDescription: Help site\nAuthor: myurl.com\nTemplate: knowall\nVersion: 1.0\n*/\n@import \"css/style.css\";\n</code></pre>\n\n<p>That should solve your prob.</p>\n" }, { "answer_id": 269963, "author": "Vivek Tamrakar", "author_id": 96956, "author_profile": "https://wordpress.stackexchange.com/users/96956", "pm_score": 0, "selected": false, "text": "<p><strong>Write this code in you functions.php</strong></p>\n\n<blockquote>\n <p>add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' ); function\n my_child_theme_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );</p>\n \n <p>}</p>\n</blockquote>\n" }, { "answer_id": 269968, "author": "Hlsg", "author_id": 121682, "author_profile": "https://wordpress.stackexchange.com/users/121682", "pm_score": 0, "selected": false, "text": "<p>Jack Johansson is on point.\nHowever, since you don't seem very in the know with this stuff, <a href=\"http://wordpress.org/plugins/one-click-child-theme/\" rel=\"nofollow noreferrer\">One-Click Child Theme</a> can automate the process of creating child themes and follows best practices.</p>\n" } ]
2017/06/13
[ "https://wordpress.stackexchange.com/questions/269934", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121660/" ]
I'm using *Knowall* theme for WordPress. I've developed a child theme with the following code placed in my `style.css` file in my child theme's folder: ``` /* Theme Name: KnowAll Child Theme Theme URI: help.mysite.com Description: Help site Author: myurl.com Template: knowall Version: 1.0 */ @import url("../knowall/css/style.css"); ``` This works (child theme is shown in WordPress) but created the following broken link: ``` http://help.mysite.com/wp-content/themes/knowall-child/css/style.css?ver=4.8 ``` So it looks like it's trying to locate the core Knowall style.css from within the child theme rather than the parent folder. I've 'fixed' this by importing the parent style.css directly into the child theme folder. I've also had to do the same for the 'img' folder. How can I re-target these assets so it finds them in the parent theme? I don't want to have to re-import assets to the child theme every time I update Wordpress...
There is most likely some issues about using [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) or [`get_stylesheet_directory_uri()`](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri). According to WordPress Code reference: > > `get_template_directory_uri()` function returns the URL to the root theme. If a child theme is > used and you want to return the URL to the current child theme, use > `get_stylesheet_directory_uri()` instead. > > > Also, it is [noted](https://codex.wordpress.org/Child_Themes) that importing the parent CSS file is not a good practice anymore: > > Note that the previous method was to import the parent theme > stylesheet using @import: this is no longer best practice, as it > increases the amount of time it takes style sheets to load. The > correct method of enqueuing the parent theme stylesheet is to add a > `wp_enqueue_scripts` action and use `wp_enqueue_style()` in your child > theme's functions.php. > > > So, what you have to do is to enqueue the style by using the following code in your child theme's functions.php file: ``` add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' ); function my_child_theme_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ``` And then enqueue your own CSS files if there is any.
269,970
<p>I'have this structure:</p> <ul> <li><strong>News</strong> (CPT. A page showing all news) </li> <li><strong>Works</strong> (CPT. A page showing all works)</li> </ul> <p>Then, inside a single page of <strong>works</strong> I want to show the news related to this work:</p> <ul> <li>Single work <ul> <li>title</li> <li>content</li> <li>news related to this single work</li> </ul></li> </ul> <p>How can I make a relation between a single post in <strong>News</strong> and single post in <strong>Works</strong>?</p> <p>AFAIK, I can create a category term with same name of each single work, by hand, and then to assign that term to News single post. But there is high risk of typos and a lot of work in the content editor. Is it possible to get a more automated method?</p> <p>Thank you.</p>
[ { "answer_id": 269961, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>There is most likely some issues about using <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a>.</p>\n\n<p>According to WordPress Code reference:</p>\n\n<blockquote>\n <p><code>get_template_directory_uri()</code> function returns the URL to the root theme. If a child theme is\n used and you want to return the URL to the current child theme, use\n <code>get_stylesheet_directory_uri()</code> instead.</p>\n</blockquote>\n\n<p>Also, it is <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">noted</a> that importing the parent CSS file is not a good practice anymore:</p>\n\n<blockquote>\n <p>Note that the previous method was to import the parent theme\n stylesheet using @import: this is no longer best practice, as it\n increases the amount of time it takes style sheets to load. The\n correct method of enqueuing the parent theme stylesheet is to add a\n <code>wp_enqueue_scripts</code> action and use <code>wp_enqueue_style()</code> in your child\n theme's functions.php.</p>\n</blockquote>\n\n<p>So, what you have to do is to enqueue the style by using the following code in your child theme's functions.php file:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' );\nfunction my_child_theme_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n\n}\n</code></pre>\n\n<p>And then enqueue your own CSS files if there is any.</p>\n" }, { "answer_id": 269962, "author": "Markus Hirsch", "author_id": 109453, "author_profile": "https://wordpress.stackexchange.com/users/109453", "pm_score": 0, "selected": false, "text": "<p>I think so I understand you wrong or you don´t know 100% for what you use a child-theme. </p>\n\n<blockquote>\n <p>A child theme is a theme that inherits the functionality and styling of another theme, called the parent theme. Child themes are the recommended way of modifying an existing theme.</p>\n</blockquote>\n\n<p><a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a></p>\n\n<p>You don´t need to import the parent style in your child.\nIn style.css you include your own coded css.</p>\n\n<p>Your folder structur are: wp-content/theme/knowall-child/css/style.css\nand in css/style.css is your custom css code.</p>\n\n<p>Switch your style.css to:</p>\n\n<pre><code>/*\nTheme Name: KnowAll Child Theme\nTheme URI: help.mysite.com\nDescription: Help site\nAuthor: myurl.com\nTemplate: knowall\nVersion: 1.0\n*/\n@import \"css/style.css\";\n</code></pre>\n\n<p>That should solve your prob.</p>\n" }, { "answer_id": 269963, "author": "Vivek Tamrakar", "author_id": 96956, "author_profile": "https://wordpress.stackexchange.com/users/96956", "pm_score": 0, "selected": false, "text": "<p><strong>Write this code in you functions.php</strong></p>\n\n<blockquote>\n <p>add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' ); function\n my_child_theme_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );</p>\n \n <p>}</p>\n</blockquote>\n" }, { "answer_id": 269968, "author": "Hlsg", "author_id": 121682, "author_profile": "https://wordpress.stackexchange.com/users/121682", "pm_score": 0, "selected": false, "text": "<p>Jack Johansson is on point.\nHowever, since you don't seem very in the know with this stuff, <a href=\"http://wordpress.org/plugins/one-click-child-theme/\" rel=\"nofollow noreferrer\">One-Click Child Theme</a> can automate the process of creating child themes and follows best practices.</p>\n" } ]
2017/06/13
[ "https://wordpress.stackexchange.com/questions/269970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77722/" ]
I'have this structure: * **News** (CPT. A page showing all news) * **Works** (CPT. A page showing all works) Then, inside a single page of **works** I want to show the news related to this work: * Single work + title + content + news related to this single work How can I make a relation between a single post in **News** and single post in **Works**? AFAIK, I can create a category term with same name of each single work, by hand, and then to assign that term to News single post. But there is high risk of typos and a lot of work in the content editor. Is it possible to get a more automated method? Thank you.
There is most likely some issues about using [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) or [`get_stylesheet_directory_uri()`](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri). According to WordPress Code reference: > > `get_template_directory_uri()` function returns the URL to the root theme. If a child theme is > used and you want to return the URL to the current child theme, use > `get_stylesheet_directory_uri()` instead. > > > Also, it is [noted](https://codex.wordpress.org/Child_Themes) that importing the parent CSS file is not a good practice anymore: > > Note that the previous method was to import the parent theme > stylesheet using @import: this is no longer best practice, as it > increases the amount of time it takes style sheets to load. The > correct method of enqueuing the parent theme stylesheet is to add a > `wp_enqueue_scripts` action and use `wp_enqueue_style()` in your child > theme's functions.php. > > > So, what you have to do is to enqueue the style by using the following code in your child theme's functions.php file: ``` add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' ); function my_child_theme_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ``` And then enqueue your own CSS files if there is any.
270,005
<p>I have a custom endpoint defined like so:</p> <pre><code> add_action( 'rest_api_init', function () { register_rest_route( 'menc/v1', '/crosscat/(?P&lt;dept&gt;[\w-]+)/(?P&lt;cat&gt;[\w-]+)', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'dept_cat_api', 'args' =&gt; array( 'dept' =&gt; array( 'sanitize_callback' =&gt; function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'cat' =&gt; array( 'sanitize_callback' =&gt; function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'per_page' =&gt; array( 'default' =&gt; 10, 'sanitize_callback' =&gt; 'absint', ), 'page' =&gt; array( 'default' =&gt; 1, 'sanitize_callback' =&gt; 'absint', ), 'orderby' =&gt; array( 'default' =&gt; 'date', 'sanitize_callback' =&gt; 'sanitize_text_field', ), 'order' =&gt; array( 'default' =&gt; 'desc', 'sanitize_callback' =&gt; 'sanitize_text_field', ), ), ) ); } ); function dept_cat_api( $request ) { $args = array( 'post_type' =&gt; 'post', 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'crosspost', 'field' =&gt; 'slug', 'terms' =&gt; array( $request['dept'] ), ), array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; array( $request['cat'] ), ), ), 'per_page' =&gt; $request['per_page'], 'page' =&gt; $request['page'], 'orderby' =&gt; $request['orderby'], 'order' =&gt; $request['order'] ); $posts = get_posts( $args ); if ( empty( $posts ) ) return new WP_Error( 'no_posts', 'Invalid term(s)', array( 'status' =&gt; 404 ) ); $controller = new WP_REST_Posts_Controller('post'); foreach ( $posts as $post ) { $response = $controller-&gt;prepare_item_for_response( $post, $request ); $data[] = $controller-&gt;prepare_response_for_collection( $response ); } // return results return new WP_REST_Response($data, 200); } </code></pre> <p>Remotely I'm having a problem. When I call the route everything seems fine with the content, however both <code>X-WP-TotalPages</code> and <code>X-WP-Total</code> return empty responses. </p> <pre><code> object(Requests_Utility_CaseInsensitiveDictionary)#991 (1) { ["data":protected]=&gt; array(20) { ["server"]=&gt; string(5) "nginx" ["date"]=&gt; string(29) "Wed, 14 Jun 2017 14:07:51 GMT" ["content-type"]=&gt; string(31) "application/json; charset=UTF-8" ["content-length"]=&gt; string(6) "104787" ["expires"]=&gt; string(29) "Thu, 19 Nov 1981 08:52:00 GMT" ["pragma"]=&gt; string(8) "no-cache" ["x-robots-tag"]=&gt; string(7) "noindex" ["link"]=&gt; string(65) "; rel="https://api.w.org/"" ["x-content-type-options"]=&gt; string(7) "nosniff" ["access-control-expose-headers"]=&gt; string(27) "X-WP-Total, X-WP-TotalPages" ["access-control-allow-headers"]=&gt; string(27) "Authorization, Content-Type" ["allow"]=&gt; string(3) "GET" ["x-cacheable"]=&gt; string(5) "SHORT" ["vary"]=&gt; string(22) "Accept-Encoding,Cookie" ["cache-control"]=&gt; string(28) "max-age=600, must-revalidate" ["accept-ranges"]=&gt; string(5) "bytes" ["x-cache"]=&gt; string(6) "HIT: 1" ["x-pass-why"]=&gt; string(0) "" ["x-cache-group"]=&gt; string(6) "normal" ["x-type"]=&gt; string(7) "default" } } </code></pre> <p>Ideally I need both populated, but I could make do with one. I assumed WordPress calculated/populated these via the controller. Do I have to populate them manually? Have I done something incorrectly? Am I experiencing a bug?</p>
[ { "answer_id": 270128, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>I had a quick look and here's how the headers are set in the <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_posts_controller/get_items/\" rel=\"noreferrer\"><code>WP_REST_Posts_Controller::get_items()</code></a> method:</p>\n\n<pre><code>$response = rest_ensure_response( $posts );\n// ...\n$response-&gt;header( 'X-WP-Total', (int) $total_posts );\n$response-&gt;header( 'X-WP-TotalPages', (int) $max_pages );\n// ...\nreturn $response;\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>$total_posts = $posts_query-&gt;found_posts;\n</code></pre>\n\n<p>and we could use as @jshwlkr <a href=\"https://wordpress.stackexchange.com/users/98703/jshwlkr\">suggested</a>:</p>\n\n<pre><code>$max_pages = $posts_query-&gt;max_num_pages;\n</code></pre>\n\n<p>You could emulate that for your custom endpoint, by using <code>WP_Query</code> instead of <code>get_posts()</code>. </p>\n\n<p>Thanks to @DenisUyeda for <a href=\"https://wordpress.stackexchange.com/questions/270005/custom-endpoint-and-x-wp-totalpages-headers/270128#comment416579_270128\">correcting the typo</a>.</p>\n" }, { "answer_id": 385512, "author": "suprio", "author_id": 203733, "author_profile": "https://wordpress.stackexchange.com/users/203733", "pm_score": 1, "selected": false, "text": "<p>Based on the answer above, I used this code, It works for me.</p>\n<pre><code>$query = new WP_Query(array());\n\n$posts = $query-&gt;get_posts();\n\n$total_posts = $query-&gt;found_posts;\n$max_pages = $query-&gt;max_num_pages;\n$returned = new WP_REST_Response($posts, 200);\n$returned-&gt;header( 'X-WP-Total', $total_posts );\n$returned-&gt;header( 'X-WP-TotalPages', $max_pages );\nreturn $returned;\n</code></pre>\n" }, { "answer_id": 405735, "author": "Tribes Chain", "author_id": 222188, "author_profile": "https://wordpress.stackexchange.com/users/222188", "pm_score": 0, "selected": false, "text": "<pre><code>\n$posts = $query-&gt;get_posts();\n\n$total_posts = $query-&gt;found_posts;\n$max_pages = $query-&gt;max_num_pages;\n$returned = new WP_REST_Response($posts, 200);\n$returned-&gt;header( 'X-WP-Total', $total_posts );\n$returned-&gt;header( 'X-WP-TotalPages', $max_pages );\nreturn $returned;\n</code></pre>\n<p>Where should I put it ? In rest-api.php ?</p>\n" } ]
2017/06/13
[ "https://wordpress.stackexchange.com/questions/270005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98703/" ]
I have a custom endpoint defined like so: ``` add_action( 'rest_api_init', function () { register_rest_route( 'menc/v1', '/crosscat/(?P<dept>[\w-]+)/(?P<cat>[\w-]+)', array( 'methods' => 'GET', 'callback' => 'dept_cat_api', 'args' => array( 'dept' => array( 'sanitize_callback' => function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'cat' => array( 'sanitize_callback' => function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'per_page' => array( 'default' => 10, 'sanitize_callback' => 'absint', ), 'page' => array( 'default' => 1, 'sanitize_callback' => 'absint', ), 'orderby' => array( 'default' => 'date', 'sanitize_callback' => 'sanitize_text_field', ), 'order' => array( 'default' => 'desc', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } ); function dept_cat_api( $request ) { $args = array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'crosspost', 'field' => 'slug', 'terms' => array( $request['dept'] ), ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( $request['cat'] ), ), ), 'per_page' => $request['per_page'], 'page' => $request['page'], 'orderby' => $request['orderby'], 'order' => $request['order'] ); $posts = get_posts( $args ); if ( empty( $posts ) ) return new WP_Error( 'no_posts', 'Invalid term(s)', array( 'status' => 404 ) ); $controller = new WP_REST_Posts_Controller('post'); foreach ( $posts as $post ) { $response = $controller->prepare_item_for_response( $post, $request ); $data[] = $controller->prepare_response_for_collection( $response ); } // return results return new WP_REST_Response($data, 200); } ``` Remotely I'm having a problem. When I call the route everything seems fine with the content, however both `X-WP-TotalPages` and `X-WP-Total` return empty responses. ``` object(Requests_Utility_CaseInsensitiveDictionary)#991 (1) { ["data":protected]=> array(20) { ["server"]=> string(5) "nginx" ["date"]=> string(29) "Wed, 14 Jun 2017 14:07:51 GMT" ["content-type"]=> string(31) "application/json; charset=UTF-8" ["content-length"]=> string(6) "104787" ["expires"]=> string(29) "Thu, 19 Nov 1981 08:52:00 GMT" ["pragma"]=> string(8) "no-cache" ["x-robots-tag"]=> string(7) "noindex" ["link"]=> string(65) "; rel="https://api.w.org/"" ["x-content-type-options"]=> string(7) "nosniff" ["access-control-expose-headers"]=> string(27) "X-WP-Total, X-WP-TotalPages" ["access-control-allow-headers"]=> string(27) "Authorization, Content-Type" ["allow"]=> string(3) "GET" ["x-cacheable"]=> string(5) "SHORT" ["vary"]=> string(22) "Accept-Encoding,Cookie" ["cache-control"]=> string(28) "max-age=600, must-revalidate" ["accept-ranges"]=> string(5) "bytes" ["x-cache"]=> string(6) "HIT: 1" ["x-pass-why"]=> string(0) "" ["x-cache-group"]=> string(6) "normal" ["x-type"]=> string(7) "default" } } ``` Ideally I need both populated, but I could make do with one. I assumed WordPress calculated/populated these via the controller. Do I have to populate them manually? Have I done something incorrectly? Am I experiencing a bug?
I had a quick look and here's how the headers are set in the [`WP_REST_Posts_Controller::get_items()`](https://developer.wordpress.org/reference/classes/wp_rest_posts_controller/get_items/) method: ``` $response = rest_ensure_response( $posts ); // ... $response->header( 'X-WP-Total', (int) $total_posts ); $response->header( 'X-WP-TotalPages', (int) $max_pages ); // ... return $response; ``` where: ``` $total_posts = $posts_query->found_posts; ``` and we could use as @jshwlkr [suggested](https://wordpress.stackexchange.com/users/98703/jshwlkr): ``` $max_pages = $posts_query->max_num_pages; ``` You could emulate that for your custom endpoint, by using `WP_Query` instead of `get_posts()`. Thanks to @DenisUyeda for [correcting the typo](https://wordpress.stackexchange.com/questions/270005/custom-endpoint-and-x-wp-totalpages-headers/270128#comment416579_270128).
270,008
<p>I've read a couple of things about the wp.media object and have successfully initialised in the state that I can find to upload images. But for the plug-in that I am building I need to have the same layout as when I click my attachment in de media grid gallery.</p> <p>For now this is my "simple" code that opens the default wp.media object</p> <pre><code>// Create a new media frame frame = wp.media({ title: 'Select or Upload Media Of Your Chosen Persuasion', button: { text: 'Use this media' }, multiple: false // Set to true to allow multiple files to be selected }); // Finally, open the modal on click frame.open(); </code></pre> <p>What I need is the exact same result as you follow the url down below:</p> <pre><code>http://wordpress.dev/wp-admin/upload.php?item=10 </code></pre> <p>Where you need to replace wordpress.dev with your own WP installation en item=10 to any attachment ID you actually have.</p> <p>It should look like the following screenshot:</p> <p><a href="https://i.stack.imgur.com/BBtzU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBtzU.jpg" alt="Screenshot of edit attachment"></a></p> <p>Is there anyone we has an answer or can send me into the right direction?</p>
[ { "answer_id": 278838, "author": "user63350", "author_id": 83763, "author_profile": "https://wordpress.stackexchange.com/users/83763", "pm_score": 2, "selected": false, "text": "<p>Unfortunately the logic of the attachment details isn't made to be used standalone - it requires the grid that opens it. You can however use the <code>get_media_item( attachment_id )</code> method to receive the HTML of the form for modifying images: <a href=\"https://developer.wordpress.org/reference/functions/get_media_item/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_media_item/</a></p>\n" }, { "answer_id": 278839, "author": "user63350", "author_id": 83763, "author_profile": "https://wordpress.stackexchange.com/users/83763", "pm_score": 2, "selected": false, "text": "<p><strong>Long answer</strong>:\nPeeking into wp-includes/js/media-models.js, I see this:</p>\n\n<pre><code>if ( 'select' === attributes.frame &amp;&amp; MediaFrame.Select ) {\n frame = new MediaFrame.Select( attributes );\n} else if ( 'post' === attributes.frame &amp;&amp; MediaFrame.Post ) {\n frame = new MediaFrame.Post( attributes );\n} else if ( 'manage' === attributes.frame &amp;&amp; MediaFrame.Manage ) {\n frame = new MediaFrame.Manage( attributes );\n} else if ( 'image' === attributes.frame &amp;&amp; MediaFrame.ImageDetails ) {\n frame = new MediaFrame.ImageDetails( attributes );\n} else if ( 'audio' === attributes.frame &amp;&amp; MediaFrame.AudioDetails ) {\n frame = new MediaFrame.AudioDetails( attributes );\n} else if ( 'video' === attributes.frame &amp;&amp; MediaFrame.VideoDetails ) {\n frame = new MediaFrame.VideoDetails( attributes );\n} else if ( 'edit-attachments' === attributes.frame &amp;&amp; MediaFrame.EditAttachments ) {\n frame = new MediaFrame.EditAttachments( attributes );\n}\n</code></pre>\n\n<p>So one is lead to believe you could do this:</p>\n\n<pre><code>var frame = wp.media.frames.frame = wp.media({\n title: 'Select Image',\n button: { text: 'Select' },\nmultiple: false,\nframe: 'edit-attachments',\ncontroller: {\n gridRouter: {}\n}\n});\nframe.open();\n</code></pre>\n\n<p>But it won't work.\nThe first trouble you meet is that some script is required. This can be dealt with like this:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function() {\n wp_enqueue_media();\n wp_enqueue_script( 'media-grid' );\n wp_enqueue_script( 'media' );\n});\n</code></pre>\n\n<p>But still no cigar.</p>\n\n<p>The problem can be found in wp-includes/js/media-grid.js:</p>\n\n<pre><code>EditAttachments = MediaFrame.extend({\ninitialize: function() {\n this.controller = this.options.controller;\n this.gridRouter = this.controller.gridRouter;\n</code></pre>\n\n<p>This shows that EditAttachments requires a controller provided in the options, and this controller must have property \"gridRouter\". So something like this:</p>\n\n<pre><code>var frame = wp.media.frames.frame = wp.media({\n frame: 'edit-attachments',\n controller: {\n gridRouter: {}\n }\n});\n</code></pre>\n\n<p>But this won't work, because you need a valid gridRouter.</p>\n\n<p>This is all related to the underlying grid.</p>\n\n<p>To learn more about the wp.media, I can recommend this plugin:\n<a href=\"https://github.com/ericandrewlewis/wp-media-javascript-guide\" rel=\"nofollow noreferrer\">https://github.com/ericandrewlewis/wp-media-javascript-guide</a></p>\n\n<p>And of course, there is this page:\n<a href=\"https://codex.wordpress.org/Javascript_Reference/wp.media\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Javascript_Reference/wp.media</a></p>\n\n<p>Related questions:</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/189727/open-the-attachment-details-modal\">Open the attachment details modal</a></li>\n<li><a href=\"https://stackoverflow.com/questions/41098126/wordpress-open-edit-attachment-modal-with-wp-media/\">https://stackoverflow.com/questions/41098126/wordpress-open-edit-attachment-modal-with-wp-media/</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/236817/open-media-frame-and-select-an-attachment\">Open media frame and select an attachment</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/181000/get-attachment-image-info-in-js\">Get attachment/image info in JS</a></li>\n</ul>\n" } ]
2017/06/13
[ "https://wordpress.stackexchange.com/questions/270008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58001/" ]
I've read a couple of things about the wp.media object and have successfully initialised in the state that I can find to upload images. But for the plug-in that I am building I need to have the same layout as when I click my attachment in de media grid gallery. For now this is my "simple" code that opens the default wp.media object ``` // Create a new media frame frame = wp.media({ title: 'Select or Upload Media Of Your Chosen Persuasion', button: { text: 'Use this media' }, multiple: false // Set to true to allow multiple files to be selected }); // Finally, open the modal on click frame.open(); ``` What I need is the exact same result as you follow the url down below: ``` http://wordpress.dev/wp-admin/upload.php?item=10 ``` Where you need to replace wordpress.dev with your own WP installation en item=10 to any attachment ID you actually have. It should look like the following screenshot: [![Screenshot of edit attachment](https://i.stack.imgur.com/BBtzU.jpg)](https://i.stack.imgur.com/BBtzU.jpg) Is there anyone we has an answer or can send me into the right direction?
Unfortunately the logic of the attachment details isn't made to be used standalone - it requires the grid that opens it. You can however use the `get_media_item( attachment_id )` method to receive the HTML of the form for modifying images: <https://developer.wordpress.org/reference/functions/get_media_item/>
270,010
<p>Running NGINX, Wordpress 4.75 after upgrading from a way older version of Wordpress, our images are being served locally and I would like to change that to our CDN. </p> <p>In the past images that were uploaded to the blog were uploaded directly to our CDN using a plugin ( I think Offload S3 Lite ). </p> <p>My goal is that I want post images, thumbnail etc URL to be served from our CDN and not local. </p> <p>For example I have: <a href="https://test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg" rel="nofollow noreferrer">https://test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg</a></p> <p>Needs to point to: <a href="https://cdn.test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg" rel="nofollow noreferrer">https://cdn.test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg</a></p> <p>Before the wordpress site (was not updated for a while) was uploading images directly to the CDN (AWS S3 -> Cloudfront) now that we upgraded to 4.75 the images that get served are pointing to local url instead of our CDN url. </p> <p>images are served through the functions like: the_post_thumbnail()</p> <p>Which I believe uses wp_get_attachment_image under the hood. If I can included a function in my functions.php to rewrite image urls that could work too.</p> <p>So how can I get the image urls to point to our CDN and instead of local url?</p> <p>Thanks for your help!</p>
[ { "answer_id": 270052, "author": "Morgan Estes", "author_id": 26317, "author_profile": "https://wordpress.stackexchange.com/users/26317", "pm_score": 0, "selected": false, "text": "<p>You probably want to use the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_thumb_url/\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_thumb_url</code></a> filter to rewrite the images that are attached to a post (like featured images or ones added via media manager.) </p>\n\n<p>If there are other images in the content (like if someone copied and pasted HTML with an image tag) you can filter <code>the_content</code> and use RegEx to replace those URLs, but that's hopefully not going to be something you run into very much.</p>\n" }, { "answer_id": 345208, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": 1, "selected": false, "text": "<p>Since the major adoption of <strong>Responsive Images</strong> and the addition of new <code>srcset</code> attribute to the <code>&lt;img&gt;</code> element. WordPress has to evolve too. WordPress 4.4 added the responsive images feature. </p>\n\n<p>If you inspect the <code>src</code> attribute it might point to the CDN, however, you still need to consider the <code>srcset</code> attribute which might still be using the local version of the images.</p>\n\n<p>First, we need to provide the algorithm for changing the local URL to the CDN version. The algorithm I use adheres your test case above; i.e. <a href=\"https://test.com/\" rel=\"nofollow noreferrer\">https://test.com/</a> to <a href=\"https://cdn.test.com/\" rel=\"nofollow noreferrer\">https://cdn.test.com/</a></p>\n\n<h3>Add these to <code>functions.php</code></h3>\n\n<pre><code>// Add .cdn after http:// or https://\nfunction to_cdn($src) {\n $dslash_pos = strpos($src, '//') + 2;\n\n $src_pre = substr($src, 0, $dslash_pos); // http:// or https://\n $src_post = substr($src, $dslash_pos); // The rest after http:// or https://\n\n return $src_pre . 'cdn.' . $src_post;\n}\n</code></pre>\n\n<p>Then we need to change the <code>src</code> attribute of the image using the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">wp_get_attachment_image_src</a> filter.</p>\n\n<pre><code>function test_get_attachment_image_src($image, $attachment_id, $size, $icon) {\n if(!is_admin()) {\n if(!image) {\n return false;\n }\n\n if(is_array($image)) {\n $src = to_cdn($image[0]); // To CDN\n $width = $image[1];\n $height = $image[2];\n\n return [$src, $width, $height, true];\n\n } else {\n return false;\n }\n }\n\n return $image;\n\n}\nadd_filter('wp_get_attachment_image_src', 'test_get_attachment_image_src', 10, 4);\n</code></pre>\n\n<p>Next is for the <code>srcset</code> attribute this time using <a href=\"https://developer.wordpress.org/reference/hooks/wp_calculate_image_srcset/\" rel=\"nofollow noreferrer\">wp_calculate_image_srcset</a> filter.</p>\n\n<pre><code>function test_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) {\n if(!is_admin()) {\n $images = [];\n\n foreach($sources as $source) {\n $src = to_cdn($source['url']); // To CDN\n $images[] = [\n 'url' =&gt; $src,\n 'descriptor' =&gt; $source['descriptor'],\n 'value' =&gt; $source['value']\n ];\n }\n\n return $images;\n }\n\n return $sources;\n}\nadd_filter('wp_calculate_image_srcset', 'test_calculate_image_srcset', 10, 5);\n</code></pre>\n" } ]
2017/06/13
[ "https://wordpress.stackexchange.com/questions/270010", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51263/" ]
Running NGINX, Wordpress 4.75 after upgrading from a way older version of Wordpress, our images are being served locally and I would like to change that to our CDN. In the past images that were uploaded to the blog were uploaded directly to our CDN using a plugin ( I think Offload S3 Lite ). My goal is that I want post images, thumbnail etc URL to be served from our CDN and not local. For example I have: <https://test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg> Needs to point to: <https://cdn.test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg> Before the wordpress site (was not updated for a while) was uploading images directly to the CDN (AWS S3 -> Cloudfront) now that we upgraded to 4.75 the images that get served are pointing to local url instead of our CDN url. images are served through the functions like: the\_post\_thumbnail() Which I believe uses wp\_get\_attachment\_image under the hood. If I can included a function in my functions.php to rewrite image urls that could work too. So how can I get the image urls to point to our CDN and instead of local url? Thanks for your help!
Since the major adoption of **Responsive Images** and the addition of new `srcset` attribute to the `<img>` element. WordPress has to evolve too. WordPress 4.4 added the responsive images feature. If you inspect the `src` attribute it might point to the CDN, however, you still need to consider the `srcset` attribute which might still be using the local version of the images. First, we need to provide the algorithm for changing the local URL to the CDN version. The algorithm I use adheres your test case above; i.e. <https://test.com/> to <https://cdn.test.com/> ### Add these to `functions.php` ``` // Add .cdn after http:// or https:// function to_cdn($src) { $dslash_pos = strpos($src, '//') + 2; $src_pre = substr($src, 0, $dslash_pos); // http:// or https:// $src_post = substr($src, $dslash_pos); // The rest after http:// or https:// return $src_pre . 'cdn.' . $src_post; } ``` Then we need to change the `src` attribute of the image using the [wp\_get\_attachment\_image\_src](https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_src/) filter. ``` function test_get_attachment_image_src($image, $attachment_id, $size, $icon) { if(!is_admin()) { if(!image) { return false; } if(is_array($image)) { $src = to_cdn($image[0]); // To CDN $width = $image[1]; $height = $image[2]; return [$src, $width, $height, true]; } else { return false; } } return $image; } add_filter('wp_get_attachment_image_src', 'test_get_attachment_image_src', 10, 4); ``` Next is for the `srcset` attribute this time using [wp\_calculate\_image\_srcset](https://developer.wordpress.org/reference/hooks/wp_calculate_image_srcset/) filter. ``` function test_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) { if(!is_admin()) { $images = []; foreach($sources as $source) { $src = to_cdn($source['url']); // To CDN $images[] = [ 'url' => $src, 'descriptor' => $source['descriptor'], 'value' => $source['value'] ]; } return $images; } return $sources; } add_filter('wp_calculate_image_srcset', 'test_calculate_image_srcset', 10, 5); ```
270,111
<p>I have a new client who has recently had her site migrated to 1and1.com, and since the migration, none of her images will load, along with other assets.</p> <p>In the Media Library, the path to all of the images display as simply /u/, instead of /wp-content/uploads/:</p> <p><a href="https://i.stack.imgur.com/1B45y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1B45y.png" alt="enter image description here"></a></p> <p>Likewise for the styles.css, instead of looking for it in the /wp-content/themes/ directory, it's looking in a non-existent /t/ directory.</p> <p>This has to be intentional. Where would a change like this be made? I've looked in all of the usual places – wp-config.php, functions.php files, etc. – and found nothing.</p> <p>I've also tried Replace Image, with no success.</p> <p>Also, what would be the purpose of this?</p> <p>Thanks in advance!</p> <p>UPDATE: </p> <p>I found this in the htaccess library, but it doesn't appear to be functioning properly – the images aren't displaying – if that provides a clue:</p> <pre><code>### ### Rewrites /u/anything to /wp-content/uploads/anything if file anything exists there ### RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/wp-content/uploads/$1 -f RewriteRule ^u/(.+)$ /wp-content/uploads/$1 [L,NS,S=500] </code></pre>
[ { "answer_id": 270035, "author": "Pisuke Soramame", "author_id": 120818, "author_profile": "https://wordpress.stackexchange.com/users/120818", "pm_score": 1, "selected": false, "text": "<p>One possible solution is to add a metadata field to your post indicating the status (i.e. completed, for sale or for rent). Then in your template file you call get_post_meta and show the content depending on the status. An added bonus of this approach is that you’ll be able to generate post listings based on the status.</p>\n\n<p>To add the metadata with plugins you could use Advanced Custom Fields to add a field “status” to your posts. If you want to do so programmatically, I can recommend an <a href=\"https://www.youtube.com/watch?v=y3SvtpOk4UI&amp;list=PLIjMj0-5C8TI7Jwell1rTvv5XXyrbKDcy&amp;index=9\" rel=\"nofollow noreferrer\">excellent video tutorial by Bobby</a>.</p>\n\n<p>Another solution, quite less elegant though, would be to use post formats (search the codex for post formats). In that case you would not need to add a custom metadata field. Note that wordpress does not allow to generate custom post formats, so you’ll have to map three of the nine predefined to the three possible statuses of your properties. A good <a href=\"https://www.youtube.com/watch?v=ut5b0gSpV1w&amp;t=834s\" rel=\"nofollow noreferrer\">video tutorial by Alessandro</a> shows how to deal with post formats.\nBy adopting this approach, you need to manually set the post format in your dashboard so the right template is rendered (e.g. aside => completed, gallery => for sale and link => for rent).</p>\n" }, { "answer_id": 270185, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>For example, let's say that Property is the post type. We would like\n to display several different views (completed (built), for sale, and\n for rent.)</p>\n</blockquote>\n\n<p>Sure. Just make <em>Completed</em>, <em>For Sale</em>, and <em>For Rent</em> <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">taxonomies</a> for the <em>Property</em> post type. \nLook into <a href=\"https://developer.wordpress.org/reference/classes/wp_rewrite/generate_rewrite_rules/\" rel=\"nofollow noreferrer\">WP_Rewrite</a> class, too, and you can get greater control over url permalink structure.</p>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16909/" ]
I have a new client who has recently had her site migrated to 1and1.com, and since the migration, none of her images will load, along with other assets. In the Media Library, the path to all of the images display as simply /u/, instead of /wp-content/uploads/: [![enter image description here](https://i.stack.imgur.com/1B45y.png)](https://i.stack.imgur.com/1B45y.png) Likewise for the styles.css, instead of looking for it in the /wp-content/themes/ directory, it's looking in a non-existent /t/ directory. This has to be intentional. Where would a change like this be made? I've looked in all of the usual places – wp-config.php, functions.php files, etc. – and found nothing. I've also tried Replace Image, with no success. Also, what would be the purpose of this? Thanks in advance! UPDATE: I found this in the htaccess library, but it doesn't appear to be functioning properly – the images aren't displaying – if that provides a clue: ``` ### ### Rewrites /u/anything to /wp-content/uploads/anything if file anything exists there ### RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/wp-content/uploads/$1 -f RewriteRule ^u/(.+)$ /wp-content/uploads/$1 [L,NS,S=500] ```
> > For example, let's say that Property is the post type. We would like > to display several different views (completed (built), for sale, and > for rent.) > > > Sure. Just make *Completed*, *For Sale*, and *For Rent* [taxonomies](https://codex.wordpress.org/Taxonomies) for the *Property* post type. Look into [WP\_Rewrite](https://developer.wordpress.org/reference/classes/wp_rewrite/generate_rewrite_rules/) class, too, and you can get greater control over url permalink structure.
270,126
<p>The plugin <strong><em>search and filter</em></strong>, doesn't retrieve <code>author_meta</code>. So i need to add <code>post_meta</code> from <code>author_meta</code>. Is it possible?</p> <h2>EDIT</h2> <p>I create user_meta in this way:</p> <pre><code> function custom_user_profile_fields($user){ $previous_value = ''; if( is_object($user) &amp;&amp; isset($user-&gt;ID) ) { $previous_value = get_user_meta( $user-&gt;ID, 'company', true ); } ?&gt; &lt;h3&gt;Extra profile information&lt;/h3&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="company"&gt;Company Name&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="text" class="regular-text" name="company" value="&lt;?php echo esc_attr( $previous_value ); ?&gt;" id="company" /&gt;&lt;br /&gt; &lt;span class="description"&gt;Where are you?&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php } add_action( 'show_user_profile', 'custom_user_profile_fields' ); add_action( 'edit_user_profile', 'custom_user_profile_fields' ); add_action( "user_new_form", "custom_user_profile_fields" ); function save_custom_user_profile_fields($user_id){ if(!current_user_can('manage_options')) return false; # save my custom field if( isset($_POST['company']) ) { update_user_meta( $user_id, 'company', sanitize_text_field( $_POST['company'] ) ); } else { //Delete the company field if $_POST['company'] is not set delete_user_meta( $user_id, 'company', $meta_value ); } } add_action('user_register', 'save_custom_user_profile_fields'); add_action( 'personal_options_update', 'save_custom_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_custom_user_profile_fields' ); </code></pre> <p>Now i need to set 'company' as a post_meta.</p> <h2>EDIT</h2> <p>I have added in functions.php your code, and i set every three minutes WP Cron but i didn't found MySql table 'genere' in postmeta. I have changed 'company', now is 'genere', but it's the same.</p> <pre><code>function add_cron_recurrence_interval( $schedules ) { $schedules['every_three_minutes'] = array( 'interval' =&gt; 180, 'display' =&gt; __( 'Every 3 Minutes', 'textdomain' ) ); return $schedules; } add_filter( 'cron_schedules', 'add_cron_recurrence_interval' ); function author_company_post_sync() { global $wpdb; $posts= $wpdb-&gt;get_results("SELECT ID,post_author FROM ".$wpdb- &gt;prefix."posts"); foreach ($posts as $post) { $company = get_user_meta($post-&gt;post_author, 'genere', true); update_user_meta($post-&gt;ID, 'genere', $company); } } // schedule with WP Cron to run sync callback once daily... if (!wp_next_scheduled('author_company_post_sync')) { wp_schedule_event( time(), 'every_three_minutes', 'author_company_post_sync'); } </code></pre> <h2>EDIT</h2> <p>Here the solution: <a href="https://wordpress.stackexchange.com/questions/273198/user-meta-to-post">User meta to post</a></p>
[ { "answer_id": 270035, "author": "Pisuke Soramame", "author_id": 120818, "author_profile": "https://wordpress.stackexchange.com/users/120818", "pm_score": 1, "selected": false, "text": "<p>One possible solution is to add a metadata field to your post indicating the status (i.e. completed, for sale or for rent). Then in your template file you call get_post_meta and show the content depending on the status. An added bonus of this approach is that you’ll be able to generate post listings based on the status.</p>\n\n<p>To add the metadata with plugins you could use Advanced Custom Fields to add a field “status” to your posts. If you want to do so programmatically, I can recommend an <a href=\"https://www.youtube.com/watch?v=y3SvtpOk4UI&amp;list=PLIjMj0-5C8TI7Jwell1rTvv5XXyrbKDcy&amp;index=9\" rel=\"nofollow noreferrer\">excellent video tutorial by Bobby</a>.</p>\n\n<p>Another solution, quite less elegant though, would be to use post formats (search the codex for post formats). In that case you would not need to add a custom metadata field. Note that wordpress does not allow to generate custom post formats, so you’ll have to map three of the nine predefined to the three possible statuses of your properties. A good <a href=\"https://www.youtube.com/watch?v=ut5b0gSpV1w&amp;t=834s\" rel=\"nofollow noreferrer\">video tutorial by Alessandro</a> shows how to deal with post formats.\nBy adopting this approach, you need to manually set the post format in your dashboard so the right template is rendered (e.g. aside => completed, gallery => for sale and link => for rent).</p>\n" }, { "answer_id": 270185, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>For example, let's say that Property is the post type. We would like\n to display several different views (completed (built), for sale, and\n for rent.)</p>\n</blockquote>\n\n<p>Sure. Just make <em>Completed</em>, <em>For Sale</em>, and <em>For Rent</em> <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">taxonomies</a> for the <em>Property</em> post type. \nLook into <a href=\"https://developer.wordpress.org/reference/classes/wp_rewrite/generate_rewrite_rules/\" rel=\"nofollow noreferrer\">WP_Rewrite</a> class, too, and you can get greater control over url permalink structure.</p>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121790/" ]
The plugin ***search and filter***, doesn't retrieve `author_meta`. So i need to add `post_meta` from `author_meta`. Is it possible? EDIT ---- I create user\_meta in this way: ``` function custom_user_profile_fields($user){ $previous_value = ''; if( is_object($user) && isset($user->ID) ) { $previous_value = get_user_meta( $user->ID, 'company', true ); } ?> <h3>Extra profile information</h3> <table class="form-table"> <tr> <th><label for="company">Company Name</label></th> <td> <input type="text" class="regular-text" name="company" value="<?php echo esc_attr( $previous_value ); ?>" id="company" /><br /> <span class="description">Where are you?</span> </td> </tr> </table> <?php } add_action( 'show_user_profile', 'custom_user_profile_fields' ); add_action( 'edit_user_profile', 'custom_user_profile_fields' ); add_action( "user_new_form", "custom_user_profile_fields" ); function save_custom_user_profile_fields($user_id){ if(!current_user_can('manage_options')) return false; # save my custom field if( isset($_POST['company']) ) { update_user_meta( $user_id, 'company', sanitize_text_field( $_POST['company'] ) ); } else { //Delete the company field if $_POST['company'] is not set delete_user_meta( $user_id, 'company', $meta_value ); } } add_action('user_register', 'save_custom_user_profile_fields'); add_action( 'personal_options_update', 'save_custom_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_custom_user_profile_fields' ); ``` Now i need to set 'company' as a post\_meta. EDIT ---- I have added in functions.php your code, and i set every three minutes WP Cron but i didn't found MySql table 'genere' in postmeta. I have changed 'company', now is 'genere', but it's the same. ``` function add_cron_recurrence_interval( $schedules ) { $schedules['every_three_minutes'] = array( 'interval' => 180, 'display' => __( 'Every 3 Minutes', 'textdomain' ) ); return $schedules; } add_filter( 'cron_schedules', 'add_cron_recurrence_interval' ); function author_company_post_sync() { global $wpdb; $posts= $wpdb->get_results("SELECT ID,post_author FROM ".$wpdb- >prefix."posts"); foreach ($posts as $post) { $company = get_user_meta($post->post_author, 'genere', true); update_user_meta($post->ID, 'genere', $company); } } // schedule with WP Cron to run sync callback once daily... if (!wp_next_scheduled('author_company_post_sync')) { wp_schedule_event( time(), 'every_three_minutes', 'author_company_post_sync'); } ``` EDIT ---- Here the solution: [User meta to post](https://wordpress.stackexchange.com/questions/273198/user-meta-to-post)
> > For example, let's say that Property is the post type. We would like > to display several different views (completed (built), for sale, and > for rent.) > > > Sure. Just make *Completed*, *For Sale*, and *For Rent* [taxonomies](https://codex.wordpress.org/Taxonomies) for the *Property* post type. Look into [WP\_Rewrite](https://developer.wordpress.org/reference/classes/wp_rewrite/generate_rewrite_rules/) class, too, and you can get greater control over url permalink structure.
270,129
<p>I am trying to setup rewrite rules for a custom homepage because we are planning on using full-screen slides and using a javascript pushstate to update the url instead of using formal WordPress pages. We decided using GET variables would be easiest in order to allow linking to a certain slide on the homepage, but it's not nice looking so I wanted to use rewrite rules in order to make everything slick and SEO friendly.</p> <p>Here's a few examples of what we are trying to do ("slide" is not a page/post in WP):</p> <pre><code>Nice URL: example.com/slide/something/ Ugly URL: example.com/?slide=something Nice URL: example.com/slide/videos/ Ugly URL: example.com/?slide=videos </code></pre> <p>Now, we have <em>no</em> problem with the ugly URLs, but my rewrite rule for this just isn't working. I have gone through several questions/answers on this but none of the accepted answers have been working. Here's what I have in functions.php:</p> <pre><code>add_action('init', 'add_rewrite_rules'); function add_rewrite_rules() { flush_rewrite_rules(); add_rewrite_rule( '^slide/([^/]*)/?$', 'index.php?slide=$matches[1]', 'top' ); } </code></pre> <p>I'm flushing rewrite rules while I try to get this working; I realize I shouldn't have this in there, being called on every refresh if this was a production site.</p> <p>If I try to go to example.com/slide/something/ I am <em>redirected</em> to the homepage.</p>
[ { "answer_id": 270131, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>Two problems I see- rewrite rules need to set query vars that will result in a successful main query. Setting just a custom var like <code>slide</code> doesn't parse to anything WordPress can load. Additionally, <code>slide</code> needs to be <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars\" rel=\"nofollow noreferrer\">added to the recognized query vars</a> for it to get parsed within a rule.</p>\n\n<p>So, what would a rule look like that would load the front page posts in the main query? That's a good question- the posts page is a special case, the absence of any other query vars. I haven't found a way to do that with a rule, though it may exist.</p>\n\n<p>An easier way to do this is with a rewrite endpoint:</p>\n\n<pre><code>function wpd_slide_endpoint(){\n add_rewrite_endpoint( 'slide', EP_ROOT );\n}\nadd_action( 'init', 'wpd_slide_endpoint' );\n</code></pre>\n\n<p>Keep in mind that if you have code accessing values via <code>$_GET</code>, this still won't work, because WordPress doesn't put query vars there when rules are parsed. You can change the code to use <code>get_query_var</code>, or just assign it before the code tries to access it:</p>\n\n<pre><code>$_GET['slide'] = get_query_var('slide');\n</code></pre>\n" }, { "answer_id": 270132, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>@Milo was two minutes faster, therefor I will just add to his answer, that using a CPT for slides might be the simplest way to get pretty urls for the slides, and in addition it will be much easier to SEO the slides.</p>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270129", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100538/" ]
I am trying to setup rewrite rules for a custom homepage because we are planning on using full-screen slides and using a javascript pushstate to update the url instead of using formal WordPress pages. We decided using GET variables would be easiest in order to allow linking to a certain slide on the homepage, but it's not nice looking so I wanted to use rewrite rules in order to make everything slick and SEO friendly. Here's a few examples of what we are trying to do ("slide" is not a page/post in WP): ``` Nice URL: example.com/slide/something/ Ugly URL: example.com/?slide=something Nice URL: example.com/slide/videos/ Ugly URL: example.com/?slide=videos ``` Now, we have *no* problem with the ugly URLs, but my rewrite rule for this just isn't working. I have gone through several questions/answers on this but none of the accepted answers have been working. Here's what I have in functions.php: ``` add_action('init', 'add_rewrite_rules'); function add_rewrite_rules() { flush_rewrite_rules(); add_rewrite_rule( '^slide/([^/]*)/?$', 'index.php?slide=$matches[1]', 'top' ); } ``` I'm flushing rewrite rules while I try to get this working; I realize I shouldn't have this in there, being called on every refresh if this was a production site. If I try to go to example.com/slide/something/ I am *redirected* to the homepage.
Two problems I see- rewrite rules need to set query vars that will result in a successful main query. Setting just a custom var like `slide` doesn't parse to anything WordPress can load. Additionally, `slide` needs to be [added to the recognized query vars](https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars) for it to get parsed within a rule. So, what would a rule look like that would load the front page posts in the main query? That's a good question- the posts page is a special case, the absence of any other query vars. I haven't found a way to do that with a rule, though it may exist. An easier way to do this is with a rewrite endpoint: ``` function wpd_slide_endpoint(){ add_rewrite_endpoint( 'slide', EP_ROOT ); } add_action( 'init', 'wpd_slide_endpoint' ); ``` Keep in mind that if you have code accessing values via `$_GET`, this still won't work, because WordPress doesn't put query vars there when rules are parsed. You can change the code to use `get_query_var`, or just assign it before the code tries to access it: ``` $_GET['slide'] = get_query_var('slide'); ```
270,141
<p>Inside a WordPress loop, I'd like to conditionally check to see if the post has a title, in order to provide necessary wrapping HTML. If the post does not have a title, I don't want any of the wrapping HTML to appear.</p>
[ { "answer_id": 270142, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>While you're in The Loop you can check against the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\">WP_Post Object</a> like so:</p>\n\n<pre><code>&lt;?php while( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php if( ! empty( $post-&gt;post_title ) ) : ?&gt;\n\n &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;\n\n &lt;?php endif; ?&gt;\n\n&lt;?php endwhile; ?&gt;\n</code></pre>\n" }, { "answer_id": 270144, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>While checking <code>$post-&gt;post_title</code>, as in Howdy_McGee's answer, is probably safe in most cases, there may be some instances where a title is being modified by <code>the_title</code> filter. In that case, you have to get the title via the API to determine if it's really empty.</p>\n\n<pre><code>$title = trim( get_the_title() );\n\nif( ! empty( $title ) ){\n echo 'there is a title';\n} else {\n echo 'empty title';\n}\n</code></pre>\n" }, { "answer_id": 270148, "author": "Daren Zammit", "author_id": 121801, "author_profile": "https://wordpress.stackexchange.com/users/121801", "pm_score": 2, "selected": false, "text": "<p>You can add the before and after html tags to <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\">the_title()</a> function.\nIf the post_title is empty, nothing will be outputted.</p>\n\n<pre><code>the_title('&lt;h1&gt;', '&lt;/h1&gt;');\n</code></pre>\n" }, { "answer_id": 270150, "author": "fwho", "author_id": 82807, "author_profile": "https://wordpress.stackexchange.com/users/82807", "pm_score": 1, "selected": false, "text": "<p>To expand <a href=\"https://wordpress.stackexchange.com/users/4771/milo\">@Milo</a>'s answer.</p>\n\n<pre><code>echo $title = ( ! empty( trim( get_the_title())) ? \"there is a title\" : \"empty title\";\n</code></pre>\n\n<p>or</p>\n\n<pre><code>echo $title = ( ! empty( trim( get_the_title())) ?: \"empty title\";\n</code></pre>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270141", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121798/" ]
Inside a WordPress loop, I'd like to conditionally check to see if the post has a title, in order to provide necessary wrapping HTML. If the post does not have a title, I don't want any of the wrapping HTML to appear.
While you're in The Loop you can check against the [WP\_Post Object](https://codex.wordpress.org/Class_Reference/WP_Post) like so: ``` <?php while( have_posts() ) : the_post(); ?> <?php if( ! empty( $post->post_title ) ) : ?> <h1><?php the_title(); ?></h1> <?php endif; ?> <?php endwhile; ?> ```
270,158
<p>Sorry for this, but I really combed everything there is on the subject and cannot come to the solution, although it is probably super-simple:</p> <p>I have a front-page.php set as the static front page of the WordPress site. In it there is a link that I'd like to link to the home.php or index.php.</p> <p>How do I write the url? </p> <pre><code>&lt;a href='&lt;?php echo esc_url( home_url()); ?&gt;' title='&lt;?php echo esc_attr( get_bloginfo( 'title' ) ); ?&gt;' rel='home'&gt; </code></pre> <p>What do i write instead of <em>home_url()</em> , which lands me of course on the front-page.php ? </p> <p>Thank you very much for your help!</p>
[ { "answer_id": 270159, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>There really should be a simpler way to do it but you kind of need to know that WordPress stores both the Front Page ID and Blog Page ID in the options table. So, to get the URL of the blog you need to use both <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\"><code>get_permalink()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_option/\" rel=\"nofollow noreferrer\"><code>get_option()</code></a> in conjunction.</p>\n\n<pre><code>&lt;a href='&lt;?php echo esc_url( get_permalink( get_option( 'page_for_posts' ) ) ); ?&gt;' title='&lt;?php echo esc_attr( get_bloginfo( 'title' ) ); ?&gt;' rel='home'&gt;Blog Page&lt;/a&gt;\n</code></pre>\n\n<p>The above will grab <code>page_for_posts</code> value from the options table which holds the Page ID of the blog which needs to be set in <code>Settings -&gt; Readings</code>. By passing an ID to <code>get_permalink()</code> it will return the string URL that we need for the page.</p>\n" }, { "answer_id": 270241, "author": "furby", "author_id": 121586, "author_profile": "https://wordpress.stackexchange.com/users/121586", "pm_score": 0, "selected": false, "text": "<p>Well, to close this question, first of all - thank you, @Howdy_McGee!\nYou were on the right track, and the solution that works is</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo get_permalink( get_option( 'page_for_posts' ) ); ?&gt;\"&gt;Blog Page&lt;/a&gt;\n</code></pre>\n\n<p>The <code>esc_url</code> is not doing the job here. I'm not that apt of a developer to know why, though I'd love to. \nThank you again! </p>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121586/" ]
Sorry for this, but I really combed everything there is on the subject and cannot come to the solution, although it is probably super-simple: I have a front-page.php set as the static front page of the WordPress site. In it there is a link that I'd like to link to the home.php or index.php. How do I write the url? ``` <a href='<?php echo esc_url( home_url()); ?>' title='<?php echo esc_attr( get_bloginfo( 'title' ) ); ?>' rel='home'> ``` What do i write instead of *home\_url()* , which lands me of course on the front-page.php ? Thank you very much for your help!
There really should be a simpler way to do it but you kind of need to know that WordPress stores both the Front Page ID and Blog Page ID in the options table. So, to get the URL of the blog you need to use both [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) and [`get_option()`](https://developer.wordpress.org/reference/functions/get_option/) in conjunction. ``` <a href='<?php echo esc_url( get_permalink( get_option( 'page_for_posts' ) ) ); ?>' title='<?php echo esc_attr( get_bloginfo( 'title' ) ); ?>' rel='home'>Blog Page</a> ``` The above will grab `page_for_posts` value from the options table which holds the Page ID of the blog which needs to be set in `Settings -> Readings`. By passing an ID to `get_permalink()` it will return the string URL that we need for the page.
270,166
<p>In <code>category-about.php</code> I have</p> <pre><code>&lt;?php /** * The template for displaying the posts in the About category * */ ?&gt; &lt;!-- category-about.php --&gt; &lt;?php get_header(); ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'post', 'category_name' =&gt; 'about', ); ?&gt; &lt;?php // How to put this part in get_template_part ? $cat_name = $args['category_name']; $query = new WP_Query( $args ); if($query-&gt;have_posts()) : ?&gt; &lt;section id="&lt;?php echo $cat_name ?&gt;-section"&gt; &lt;h1 class="&lt;?php echo $cat_name ?&gt;-section-title"&gt; &lt;strong&gt;&lt;?php echo ucfirst($cat_name) ?&gt; Section&lt;/strong&gt; &lt;/h1&gt;&lt;?php while($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; &lt;strong&gt;&lt;?php the_title(); ?&gt;&lt;/strong&gt; &lt;div &lt;?php post_class() ?&gt; &gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/section&gt; &lt;?php endif; wp_reset_query(); // end get_template_part ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>How can I have the variables from <code>category-about.php</code> in the template file <code>posts-loop.php</code>?</p> <p>Looking at <a href="http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459" rel="nofollow noreferrer">this comment</a> and <a href="https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part">this answer</a> I have trouble putting it all together.</p> <p>I would like to understand this better instead of using any of the helper functions provided in the answers. I understand that the correct way would be using <code>set_query_var</code> and <code>get_query_var</code> however I require a bit of assistance with that.</p> <p>Instead of writing the core loop code for each category I like to just define the <code>$args</code> in the category template and then make use of that in the template file. Any help is much appreciated.</p>
[ { "answer_id": 270168, "author": "lowtechsun", "author_id": 77054, "author_profile": "https://wordpress.stackexchange.com/users/77054", "pm_score": 3, "selected": false, "text": "<p>In <code>category-about.php</code> I have</p>\n\n<pre><code>&lt;?php\n/**\n * The template for displaying the posts in the About category\n *\n */\n?&gt;\n&lt;!-- category-about.php --&gt;\n&lt;?php get_header(); ?&gt;\n\n&lt;?php\n $args = array(\n 'post_type' =&gt; 'post',\n 'category_name' =&gt; 'about',\n ); ?&gt;\n\n &lt;?php \n // important bit\n set_query_var( 'query_category', $args );\n\n get_template_part('template-parts/posts', 'loop');\n ?&gt; \n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>and in template file <code>posts-loops.php</code> I now have</p>\n\n<pre><code>&lt;!-- posts-loop.php --&gt;\n &lt;?php\n // important bit\n $args = get_query_var('query_category');\n\n $cat_name = $args['category_name'];\n $query = new WP_Query( $args );\n if($query-&gt;have_posts()) : ?&gt;\n &lt;section id=\"&lt;?php echo $cat_name ?&gt;-section\"&gt;\n &lt;h1 class=\"&lt;?php echo $cat_name ?&gt;-section-title\"&gt;\n &lt;strong&gt;&lt;?php echo ucfirst($cat_name) ?&gt; Section&lt;/strong&gt;\n &lt;/h1&gt;&lt;?php\n while($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt;\n &lt;strong&gt;&lt;?php the_title(); ?&gt;&lt;/strong&gt;\n &lt;div &lt;?php post_class() ?&gt; &gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt; &lt;?php\n endwhile; ?&gt;\n &lt;/section&gt; &lt;?php\n endif;\n wp_reset_query();\n</code></pre>\n\n<p>and it works. </p>\n\n<p>Reference:<br>\n<a href=\"http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459\" rel=\"noreferrer\">http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459</a>\n<a href=\"https://wordpress.stackexchange.com/a/176807/77054\">https://wordpress.stackexchange.com/a/176807/77054</a></p>\n" }, { "answer_id": 326416, "author": "Tahi Reu", "author_id": 148666, "author_profile": "https://wordpress.stackexchange.com/users/148666", "pm_score": 0, "selected": false, "text": "<p><strong>First way</strong>:</p>\n\n<p><em>Template in which template part is included:</em> </p>\n\n<pre><code>$value_to_sent = true;\nset_query_var( 'my_var', $value_to_sent );\n</code></pre>\n\n<p><em>Included template part:</em></p>\n\n<pre><code>$get_my_var = get_query_var('my_var');\nif ($get_my_var == true) {\n...\n}\n</code></pre>\n\n<p><br /></p>\n\n<p><strong>Second way:</strong> </p>\n\n<p><em>Template in which template part is included:</em> </p>\n\n<pre><code>global $my_var;\n$my_var= true;\n</code></pre>\n\n<p><em>Included template part:</em></p>\n\n<pre><code>global $my_var;\nif ($my_var == true) {\n...\n}\n</code></pre>\n\n<p><br />\nI would rather go with the first way.</p>\n" }, { "answer_id": 372952, "author": "Ankit", "author_id": 51280, "author_profile": "https://wordpress.stackexchange.com/users/51280", "pm_score": 1, "selected": false, "text": "<p>WordPress <strong>5.5</strong> allows passing <code>$args</code> to <code>get_template_part</code>. Apart from this function there are sets of template function which can now accept arguments.</p>\n<pre><code>get_header\nget_footer\nget_sidebar\nget_template_part_{$slug}\nget_template_part\n</code></pre>\n<p>Please refer more details at: <a href=\"https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/</a></p>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270166", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77054/" ]
In `category-about.php` I have ``` <?php /** * The template for displaying the posts in the About category * */ ?> <!-- category-about.php --> <?php get_header(); ?> <?php $args = array( 'post_type' => 'post', 'category_name' => 'about', ); ?> <?php // How to put this part in get_template_part ? $cat_name = $args['category_name']; $query = new WP_Query( $args ); if($query->have_posts()) : ?> <section id="<?php echo $cat_name ?>-section"> <h1 class="<?php echo $cat_name ?>-section-title"> <strong><?php echo ucfirst($cat_name) ?> Section</strong> </h1><?php while($query->have_posts()) : $query->the_post(); ?> <strong><?php the_title(); ?></strong> <div <?php post_class() ?> > <?php the_content(); ?> </div> <?php endwhile; ?> </section> <?php endif; wp_reset_query(); // end get_template_part ?> <?php get_footer(); ?> ``` How can I have the variables from `category-about.php` in the template file `posts-loop.php`? Looking at [this comment](http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459) and [this answer](https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part) I have trouble putting it all together. I would like to understand this better instead of using any of the helper functions provided in the answers. I understand that the correct way would be using `set_query_var` and `get_query_var` however I require a bit of assistance with that. Instead of writing the core loop code for each category I like to just define the `$args` in the category template and then make use of that in the template file. Any help is much appreciated.
In `category-about.php` I have ``` <?php /** * The template for displaying the posts in the About category * */ ?> <!-- category-about.php --> <?php get_header(); ?> <?php $args = array( 'post_type' => 'post', 'category_name' => 'about', ); ?> <?php // important bit set_query_var( 'query_category', $args ); get_template_part('template-parts/posts', 'loop'); ?> <?php get_footer(); ?> ``` and in template file `posts-loops.php` I now have ``` <!-- posts-loop.php --> <?php // important bit $args = get_query_var('query_category'); $cat_name = $args['category_name']; $query = new WP_Query( $args ); if($query->have_posts()) : ?> <section id="<?php echo $cat_name ?>-section"> <h1 class="<?php echo $cat_name ?>-section-title"> <strong><?php echo ucfirst($cat_name) ?> Section</strong> </h1><?php while($query->have_posts()) : $query->the_post(); ?> <strong><?php the_title(); ?></strong> <div <?php post_class() ?> > <?php the_content(); ?> </div> <?php endwhile; ?> </section> <?php endif; wp_reset_query(); ``` and it works. Reference: <http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459> <https://wordpress.stackexchange.com/a/176807/77054>
270,167
<p>I am trying to show a weblink to my WordPress users only if they are logged in. If they are logged out they will see text that says they need to "Login to View"</p> <p>My Original Code</p> <pre><code>&lt;a href="&lt;?php echo get_post_meta($post_id, 'external_link', true); ?&gt;"&gt;View Website&lt;/a&gt; </code></pre> <p>My Altered Code</p> <pre><code> &lt;a href="&lt;?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?&gt;"&gt;View Website&lt;/a&gt; </code></pre> <p>When a user is logged in, it's doing what it's supposed to but when they are logged out the url is broken. Can someone post an example of the format that it should be done?</p>
[ { "answer_id": 270169, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here's what you need:</p>\n\n<pre><code>&lt;?php\nif ( is_user_logged_in() ) {\n echo '&lt;a href=\"'.get_post_meta($post_id, 'external_link', true).'\"&gt;View Website&lt;/a&gt;';\n} else {\n echo '&lt;a href=\"'.wp_login_url(get_permalink()).'\"&gt;Login to view Website&lt;/a&gt;;\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 270171, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>The code you posted:</p>\n\n<pre><code> &lt;a href=\"&lt;?php\n if ( is_user_logged_in() ) {\n echo get_post_meta($post_id, 'external_link', true);\n } \n else {\n echo 'Login to View';\n }\n ?&gt;\n \"&gt;View Website&lt;/a&gt;\n</code></pre>\n\n<p>Is going to echo \"Login to View\" as the <code>href</code> attribute.</p>\n\n<p>You need something more like:</p>\n\n<pre><code> &lt;a href=\"&lt;?php\n if ( is_user_logged_in() ) {\n echo get_post_meta($post_id, 'external_link', true);\n } \n else {\n echo wp_login_url( get_permalink() );\n}\n?&gt;\"&gt;View Website&lt;/a&gt;\n</code></pre>\n\n<p>That of course won't be changing the text, just the <code>href</code>. So maybe do the conditional a step earlier (I added an arbitrary <code>&lt;span&gt;</code> for context):</p>\n\n<pre><code>&lt;span&gt; \n&lt;?php \nif ( is_user_logged_in() ) {\n $href = esc_url( get_post_meta($post_id, 'external_link', true ) );\n $text = 'View Website'; \n}\nelse {\n $href = wp_login_url( get_permalink() );\n $text = 'Login to View';\n}\n?&gt;\n&lt;a href=\"&lt;?php echo $href; ?&gt;\" &gt;&lt;?php echo $text; ?&gt;&lt;/a&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>Since you're pulling the url from the db, I wrapped it in <a href=\"https://codex.wordpress.org/Data_Validation#URLs\" rel=\"nofollow noreferrer\"> esc_url() for sanitization</a>.</p>\n" } ]
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270167", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121812/" ]
I am trying to show a weblink to my WordPress users only if they are logged in. If they are logged out they will see text that says they need to "Login to View" My Original Code ``` <a href="<?php echo get_post_meta($post_id, 'external_link', true); ?>">View Website</a> ``` My Altered Code ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?>">View Website</a> ``` When a user is logged in, it's doing what it's supposed to but when they are logged out the url is broken. Can someone post an example of the format that it should be done?
The code you posted: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?> ">View Website</a> ``` Is going to echo "Login to View" as the `href` attribute. You need something more like: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo wp_login_url( get_permalink() ); } ?>">View Website</a> ``` That of course won't be changing the text, just the `href`. So maybe do the conditional a step earlier (I added an arbitrary `<span>` for context): ``` <span> <?php if ( is_user_logged_in() ) { $href = esc_url( get_post_meta($post_id, 'external_link', true ) ); $text = 'View Website'; } else { $href = wp_login_url( get_permalink() ); $text = 'Login to View'; } ?> <a href="<?php echo $href; ?>" ><?php echo $text; ?></a> </span> ``` Since you're pulling the url from the db, I wrapped it in [esc\_url() for sanitization](https://codex.wordpress.org/Data_Validation#URLs).
270,176
<p>Basically as the title says I want to get list of categories and subcategories and then posts(with links to them) for those categories/subcategories.</p> <p>This is the structure I'm trying to achieve:</p> <ul> <li>Category 1</li> <ul> <li>Subcategory 1 within category 1</li> <ul> <li>Post 1 within subcategory 1</li> <li>Post 2 within subcategory 1</li> <li>Post 3 within subcategory 1</li> </ul> <li>Subcategory 2 within category 1</li> <ul> <li>Post 1 within subcategory 2</li> <li>Post 2 within subcategory 2</li> <li>Post 3 within subcategory 2</li> </ul> <li>Subcategory 3 within category 1</li> <ul> <li>Post 1 within subcategory 3</li> <li>Post 2 within subcategory 3</li> <li>Post 3 within subcategory 3</li> </ul> <li>Posts that have no subcategory</li> <ul> <li>Post 1 with no subcategory</li> <li>Post 1 with no subcategory</li> </ul> </ul> <li>Category 2</li> <ul> <li>Subcategory 1 within category 2</li> <ul> <li>Post 1 within subcategory 1</li> <li>Post 2 within subcategory 1</li> <li>Post 3 within subcategory 1</li> </ul> <li>Subcategory 2 within category 2</li> <ul> <li>Post 1 within subcategory 2</li> <li>Post 2 within subcategory 2</li> <li>Post 3 within subcategory 2</li> </ul> <li>Subcategory 3 within category 2</li> <ul> <li>Post 1 within subcategory 2</li> <li>Post 2 within subcategory 2</li> <li>Post 3 within subcategory 2</li> </ul> <li>Posts that have no subcategory</li> <ul> <li>Post 1 with no subcategory</li> <li>Post 1 with no subcategory</li> </ul> </ul> </ul> <p>Now so far after after reading everything I could found on the subject I have the following code:</p> <pre><code>&lt;ul&gt; &lt;?php $get_parent_cats = array( 'parent' =&gt; '0' //get top level categories only ); $all_categories = get_categories( $get_parent_cats );//get parent categories foreach( $all_categories as $single_category ){ //for each category, get the ID $catID = $single_category-&gt;cat_ID; echo '&lt;li&gt;&lt;a href=" ' . get_category_link( $catID ) . ' "&gt;' . $single_category-&gt;name . '&lt;/a&gt;'; //category name &amp; link $get_children_cats = array( 'child_of' =&gt; $catID //get children of this parent using the catID variable from earlier ); $child_cats = get_categories( $get_children_cats );//get children of parent category echo '&lt;ul class="children"&gt;'; foreach( $child_cats as $child_cat ){ //for each child category, get the ID $childID = $child_cat-&gt;cat_ID; //for each child category, give us the link and name echo '&lt;a href=" ' . get_category_link( $childID ) . ' "&gt;' . $child_cat-&gt;name . '&lt;/a&gt;'; } echo '&lt;/ul&gt;&lt;/li&gt;'; } //end of categories logic ?&gt; &lt;/ul&gt; </code></pre> <p>Now this code shows categories and subcategories well but I need to somehow loop through my posts and show them withing categories/subcategories. I have also tried to use fallowing code: </p> <pre><code> &lt;?php // get all the categories from the database $cats = get_categories(); // loop through the categries foreach ($cats as $cat) { // setup the cateogory ID $cat_id= $cat-&gt;term_id; // Make a header for the cateogry echo "&lt;h2&gt;".$cat-&gt;name."&lt;/h2&gt;"; // create a custom wordpress query query_posts("cat=$cat_id&amp;posts_per_page=100"); // start the wordpress loop! if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;?php // create our link now that the post is setup ?&gt; &lt;a href="&lt;?php the_permalink();?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php echo '&lt;hr/&gt;'; ?&gt; &lt;?php endwhile; endif; // done our wordpress loop. Will start again for each category ?&gt; &lt;?php } // done the foreach statement ?&gt; &lt;/div&gt;&lt;!-- #content --&gt; &lt;/div&gt;&lt;!-- #container --&gt; </code></pre> <p>This code shows all categories and posts within particular category, but the structure is not the one I want. I have been trying to combine these two snippets of code for two days, but nothing I try gives me the result I want. I am inexperienced with Wordpress and I could really use help with this.</p>
[ { "answer_id": 270169, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here's what you need:</p>\n\n<pre><code>&lt;?php\nif ( is_user_logged_in() ) {\n echo '&lt;a href=\"'.get_post_meta($post_id, 'external_link', true).'\"&gt;View Website&lt;/a&gt;';\n} else {\n echo '&lt;a href=\"'.wp_login_url(get_permalink()).'\"&gt;Login to view Website&lt;/a&gt;;\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 270171, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>The code you posted:</p>\n\n<pre><code> &lt;a href=\"&lt;?php\n if ( is_user_logged_in() ) {\n echo get_post_meta($post_id, 'external_link', true);\n } \n else {\n echo 'Login to View';\n }\n ?&gt;\n \"&gt;View Website&lt;/a&gt;\n</code></pre>\n\n<p>Is going to echo \"Login to View\" as the <code>href</code> attribute.</p>\n\n<p>You need something more like:</p>\n\n<pre><code> &lt;a href=\"&lt;?php\n if ( is_user_logged_in() ) {\n echo get_post_meta($post_id, 'external_link', true);\n } \n else {\n echo wp_login_url( get_permalink() );\n}\n?&gt;\"&gt;View Website&lt;/a&gt;\n</code></pre>\n\n<p>That of course won't be changing the text, just the <code>href</code>. So maybe do the conditional a step earlier (I added an arbitrary <code>&lt;span&gt;</code> for context):</p>\n\n<pre><code>&lt;span&gt; \n&lt;?php \nif ( is_user_logged_in() ) {\n $href = esc_url( get_post_meta($post_id, 'external_link', true ) );\n $text = 'View Website'; \n}\nelse {\n $href = wp_login_url( get_permalink() );\n $text = 'Login to View';\n}\n?&gt;\n&lt;a href=\"&lt;?php echo $href; ?&gt;\" &gt;&lt;?php echo $text; ?&gt;&lt;/a&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>Since you're pulling the url from the db, I wrapped it in <a href=\"https://codex.wordpress.org/Data_Validation#URLs\" rel=\"nofollow noreferrer\"> esc_url() for sanitization</a>.</p>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119868/" ]
Basically as the title says I want to get list of categories and subcategories and then posts(with links to them) for those categories/subcategories. This is the structure I'm trying to achieve: * Category 1 + Subcategory 1 within category 1 - Post 1 within subcategory 1 - Post 2 within subcategory 1 - Post 3 within subcategory 1 + Subcategory 2 within category 1 - Post 1 within subcategory 2 - Post 2 within subcategory 2 - Post 3 within subcategory 2 + Subcategory 3 within category 1 - Post 1 within subcategory 3 - Post 2 within subcategory 3 - Post 3 within subcategory 3 + Posts that have no subcategory - Post 1 with no subcategory - Post 1 with no subcategory * Category 2 + Subcategory 1 within category 2 - Post 1 within subcategory 1 - Post 2 within subcategory 1 - Post 3 within subcategory 1 + Subcategory 2 within category 2 - Post 1 within subcategory 2 - Post 2 within subcategory 2 - Post 3 within subcategory 2 + Subcategory 3 within category 2 - Post 1 within subcategory 2 - Post 2 within subcategory 2 - Post 3 within subcategory 2 + Posts that have no subcategory - Post 1 with no subcategory - Post 1 with no subcategory Now so far after after reading everything I could found on the subject I have the following code: ``` <ul> <?php $get_parent_cats = array( 'parent' => '0' //get top level categories only ); $all_categories = get_categories( $get_parent_cats );//get parent categories foreach( $all_categories as $single_category ){ //for each category, get the ID $catID = $single_category->cat_ID; echo '<li><a href=" ' . get_category_link( $catID ) . ' ">' . $single_category->name . '</a>'; //category name & link $get_children_cats = array( 'child_of' => $catID //get children of this parent using the catID variable from earlier ); $child_cats = get_categories( $get_children_cats );//get children of parent category echo '<ul class="children">'; foreach( $child_cats as $child_cat ){ //for each child category, get the ID $childID = $child_cat->cat_ID; //for each child category, give us the link and name echo '<a href=" ' . get_category_link( $childID ) . ' ">' . $child_cat->name . '</a>'; } echo '</ul></li>'; } //end of categories logic ?> </ul> ``` Now this code shows categories and subcategories well but I need to somehow loop through my posts and show them withing categories/subcategories. I have also tried to use fallowing code: ``` <?php // get all the categories from the database $cats = get_categories(); // loop through the categries foreach ($cats as $cat) { // setup the cateogory ID $cat_id= $cat->term_id; // Make a header for the cateogry echo "<h2>".$cat->name."</h2>"; // create a custom wordpress query query_posts("cat=$cat_id&posts_per_page=100"); // start the wordpress loop! if (have_posts()) : while (have_posts()) : the_post(); ?> <?php // create our link now that the post is setup ?> <a href="<?php the_permalink();?>"><?php the_title(); ?></a> <?php echo '<hr/>'; ?> <?php endwhile; endif; // done our wordpress loop. Will start again for each category ?> <?php } // done the foreach statement ?> </div><!-- #content --> </div><!-- #container --> ``` This code shows all categories and posts within particular category, but the structure is not the one I want. I have been trying to combine these two snippets of code for two days, but nothing I try gives me the result I want. I am inexperienced with Wordpress and I could really use help with this.
The code you posted: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?> ">View Website</a> ``` Is going to echo "Login to View" as the `href` attribute. You need something more like: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo wp_login_url( get_permalink() ); } ?>">View Website</a> ``` That of course won't be changing the text, just the `href`. So maybe do the conditional a step earlier (I added an arbitrary `<span>` for context): ``` <span> <?php if ( is_user_logged_in() ) { $href = esc_url( get_post_meta($post_id, 'external_link', true ) ); $text = 'View Website'; } else { $href = wp_login_url( get_permalink() ); $text = 'Login to View'; } ?> <a href="<?php echo $href; ?>" ><?php echo $text; ?></a> </span> ``` Since you're pulling the url from the db, I wrapped it in [esc\_url() for sanitization](https://codex.wordpress.org/Data_Validation#URLs).
270,187
<p>I've created a shortcode that should be showing an image depending on the day of the week.</p> <pre><code> function custom_shortcode() { return '&lt;img src="/wp-content/themes/coworker/images/daily-social-image-' . the_weekday() . '.gif" width="100%" /&gt;'; } add_shortcode( 'weekday', 'custom_shortcode' ); </code></pre> <p>The issue being that the function <code>the_weekday()</code> is not working - the rest of the code appears to be working correctly.</p>
[ { "answer_id": 270169, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here's what you need:</p>\n\n<pre><code>&lt;?php\nif ( is_user_logged_in() ) {\n echo '&lt;a href=\"'.get_post_meta($post_id, 'external_link', true).'\"&gt;View Website&lt;/a&gt;';\n} else {\n echo '&lt;a href=\"'.wp_login_url(get_permalink()).'\"&gt;Login to view Website&lt;/a&gt;;\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 270171, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>The code you posted:</p>\n\n<pre><code> &lt;a href=\"&lt;?php\n if ( is_user_logged_in() ) {\n echo get_post_meta($post_id, 'external_link', true);\n } \n else {\n echo 'Login to View';\n }\n ?&gt;\n \"&gt;View Website&lt;/a&gt;\n</code></pre>\n\n<p>Is going to echo \"Login to View\" as the <code>href</code> attribute.</p>\n\n<p>You need something more like:</p>\n\n<pre><code> &lt;a href=\"&lt;?php\n if ( is_user_logged_in() ) {\n echo get_post_meta($post_id, 'external_link', true);\n } \n else {\n echo wp_login_url( get_permalink() );\n}\n?&gt;\"&gt;View Website&lt;/a&gt;\n</code></pre>\n\n<p>That of course won't be changing the text, just the <code>href</code>. So maybe do the conditional a step earlier (I added an arbitrary <code>&lt;span&gt;</code> for context):</p>\n\n<pre><code>&lt;span&gt; \n&lt;?php \nif ( is_user_logged_in() ) {\n $href = esc_url( get_post_meta($post_id, 'external_link', true ) );\n $text = 'View Website'; \n}\nelse {\n $href = wp_login_url( get_permalink() );\n $text = 'Login to View';\n}\n?&gt;\n&lt;a href=\"&lt;?php echo $href; ?&gt;\" &gt;&lt;?php echo $text; ?&gt;&lt;/a&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>Since you're pulling the url from the db, I wrapped it in <a href=\"https://codex.wordpress.org/Data_Validation#URLs\" rel=\"nofollow noreferrer\"> esc_url() for sanitization</a>.</p>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270187", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100731/" ]
I've created a shortcode that should be showing an image depending on the day of the week. ``` function custom_shortcode() { return '<img src="/wp-content/themes/coworker/images/daily-social-image-' . the_weekday() . '.gif" width="100%" />'; } add_shortcode( 'weekday', 'custom_shortcode' ); ``` The issue being that the function `the_weekday()` is not working - the rest of the code appears to be working correctly.
The code you posted: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?> ">View Website</a> ``` Is going to echo "Login to View" as the `href` attribute. You need something more like: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo wp_login_url( get_permalink() ); } ?>">View Website</a> ``` That of course won't be changing the text, just the `href`. So maybe do the conditional a step earlier (I added an arbitrary `<span>` for context): ``` <span> <?php if ( is_user_logged_in() ) { $href = esc_url( get_post_meta($post_id, 'external_link', true ) ); $text = 'View Website'; } else { $href = wp_login_url( get_permalink() ); $text = 'Login to View'; } ?> <a href="<?php echo $href; ?>" ><?php echo $text; ?></a> </span> ``` Since you're pulling the url from the db, I wrapped it in [esc\_url() for sanitization](https://codex.wordpress.org/Data_Validation#URLs).
270,209
<p>There is a plugin that uses a class; and create an object like this:</p> <pre><code>class WC_Disability_VAT_Exemption { public function __construct() { add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } public function exemption_field() { //some code here } } /** * Return instance of WC_Disability_VAT_Exemption. * * @since 1.3.3 * * @return WC_Disability_VAT_Exemption */ function wc_dve() { static $instance; if ( ! isset( $instance ) ) { $instance = new WC_Disability_VAT_Exemption(); } return $instance; } wc_dve(); </code></pre> <p>I want to extend the class because I want to use this method to remove an action:</p> <pre><code>class WC_Disability_VAT_Exemption_Extend extends WC_Disability_VAT_Exemption { function __construct() { $this-&gt;unregister_parent_hook(); add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } function unregister_parent_hook() { global $instance; remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) ); } function exemption_field() { //---some code here } } </code></pre> <p>But <code>global $instance</code> doesn't get the class object. It returns <em>null</em>. So how can I get <code>$instance</code> object in the extended class?</p>
[ { "answer_id": 270212, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>Well, you used <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\"><code>static</code></a> key word inside the first function. The keyword <code>static</code> will not make the variable <code>global</code>. It'll make sure that the variable exists only in that local function scope, but it does not lose its value when program execution leaves this scope.</p>\n\n<p>So if you try to access in the second function the <code>global $my_class;</code> it'll obviously return <code>null</code>. Cause <strong><em>PHP</em></strong> will treat the <code>global $my_class;</code> in the second function as a new global variable just declared.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 270363, "author": "Nick P.", "author_id": 57671, "author_profile": "https://wordpress.stackexchange.com/users/57671", "pm_score": 2, "selected": false, "text": "<p>Woocommerce support sent me the solution of my problem:</p>\n\n<pre><code>function unregister_parent_hook() {\n if ( function_exists( 'wc_dve' ) ) {\n $instance = wc_dve();\n remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) );\n }\n }\n</code></pre>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57671/" ]
There is a plugin that uses a class; and create an object like this: ``` class WC_Disability_VAT_Exemption { public function __construct() { add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } public function exemption_field() { //some code here } } /** * Return instance of WC_Disability_VAT_Exemption. * * @since 1.3.3 * * @return WC_Disability_VAT_Exemption */ function wc_dve() { static $instance; if ( ! isset( $instance ) ) { $instance = new WC_Disability_VAT_Exemption(); } return $instance; } wc_dve(); ``` I want to extend the class because I want to use this method to remove an action: ``` class WC_Disability_VAT_Exemption_Extend extends WC_Disability_VAT_Exemption { function __construct() { $this->unregister_parent_hook(); add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } function unregister_parent_hook() { global $instance; remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) ); } function exemption_field() { //---some code here } } ``` But `global $instance` doesn't get the class object. It returns *null*. So how can I get `$instance` object in the extended class?
Woocommerce support sent me the solution of my problem: ``` function unregister_parent_hook() { if ( function_exists( 'wc_dve' ) ) { $instance = wc_dve(); remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) ); } } ```
270,218
<p>I am stuck in a situation where the requirement is to create a custom email template for a particular product category, so that when any user buy product from that category he/she get that customised order email. Please help if anyone have any idea about how this can be achieved. Thanks in advance.</p>
[ { "answer_id": 270256, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Whatever plugin you're using for ecommerce, there should be an email hook available to customize the emails.</p>\n\n<p>For example, WooCommerce provides 9 different hooks in its \"new order\" email. Here's a <a href=\"https://businessbloomer.com/woocommerce-visual-hook-guide-emails/\" rel=\"nofollow noreferrer\">visual reference</a>.</p>\n\n<p>Add a function that runs on the desired hook, and you can add conditional content. You'll have to find a way to identify \"any product from a particular category\" - pull order details, loop through the products, and if any of them is from that category, trigger your conditional content.</p>\n\n<p>Further related reading: <a href=\"https://tommcfarlin.com/customizing-woocommerce-emails-hooks/\" rel=\"nofollow noreferrer\">https://tommcfarlin.com/customizing-woocommerce-emails-hooks/</a></p>\n" }, { "answer_id": 320078, "author": "Brad Holmes", "author_id": 133516, "author_profile": "https://wordpress.stackexchange.com/users/133516", "pm_score": 2, "selected": false, "text": "<p>Firstly extend WC_Email class to define the email header, subject, email template for content</p>\n\n<p>secondly, add custom email class to the default WooCommerce email classes using woocommerce_email_classes filter, with trigger that calls terms </p>\n\n<pre><code>if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) )\n</code></pre>\n\n<p>lastly, Create an email template to be used to generate email content for your custom email.</p>\n\n<p>this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. </p>\n\n<p><a href=\"https://cloudredux.com/adding-sending-custom-woocommerce-email/\" rel=\"nofollow noreferrer\">https://cloudredux.com/adding-sending-custom-woocommerce-email/</a></p>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121842/" ]
I am stuck in a situation where the requirement is to create a custom email template for a particular product category, so that when any user buy product from that category he/she get that customised order email. Please help if anyone have any idea about how this can be achieved. Thanks in advance.
Firstly extend WC\_Email class to define the email header, subject, email template for content secondly, add custom email class to the default WooCommerce email classes using woocommerce\_email\_classes filter, with trigger that calls terms ``` if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) ) ``` lastly, Create an email template to be used to generate email content for your custom email. this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. <https://cloudredux.com/adding-sending-custom-woocommerce-email/>
270,229
<p>I am working with underscores me trying to build a template by my own.</p> <p>I have build a homepage template and also a single-post file for the custom post types.</p> <p>What I am trying to get its to display in the homepage a kind of gallery with the featured images from each custom post type with title and tags.</p> <p>Have tried different ways, i guessed it would be something with <code>wp_get_archives</code> but still didn't get it. </p> <p>If you have some suggestions would be awesome.</p> <p>Thanks!</p>
[ { "answer_id": 270256, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Whatever plugin you're using for ecommerce, there should be an email hook available to customize the emails.</p>\n\n<p>For example, WooCommerce provides 9 different hooks in its \"new order\" email. Here's a <a href=\"https://businessbloomer.com/woocommerce-visual-hook-guide-emails/\" rel=\"nofollow noreferrer\">visual reference</a>.</p>\n\n<p>Add a function that runs on the desired hook, and you can add conditional content. You'll have to find a way to identify \"any product from a particular category\" - pull order details, loop through the products, and if any of them is from that category, trigger your conditional content.</p>\n\n<p>Further related reading: <a href=\"https://tommcfarlin.com/customizing-woocommerce-emails-hooks/\" rel=\"nofollow noreferrer\">https://tommcfarlin.com/customizing-woocommerce-emails-hooks/</a></p>\n" }, { "answer_id": 320078, "author": "Brad Holmes", "author_id": 133516, "author_profile": "https://wordpress.stackexchange.com/users/133516", "pm_score": 2, "selected": false, "text": "<p>Firstly extend WC_Email class to define the email header, subject, email template for content</p>\n\n<p>secondly, add custom email class to the default WooCommerce email classes using woocommerce_email_classes filter, with trigger that calls terms </p>\n\n<pre><code>if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) )\n</code></pre>\n\n<p>lastly, Create an email template to be used to generate email content for your custom email.</p>\n\n<p>this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. </p>\n\n<p><a href=\"https://cloudredux.com/adding-sending-custom-woocommerce-email/\" rel=\"nofollow noreferrer\">https://cloudredux.com/adding-sending-custom-woocommerce-email/</a></p>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270229", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120964/" ]
I am working with underscores me trying to build a template by my own. I have build a homepage template and also a single-post file for the custom post types. What I am trying to get its to display in the homepage a kind of gallery with the featured images from each custom post type with title and tags. Have tried different ways, i guessed it would be something with `wp_get_archives` but still didn't get it. If you have some suggestions would be awesome. Thanks!
Firstly extend WC\_Email class to define the email header, subject, email template for content secondly, add custom email class to the default WooCommerce email classes using woocommerce\_email\_classes filter, with trigger that calls terms ``` if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) ) ``` lastly, Create an email template to be used to generate email content for your custom email. this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. <https://cloudredux.com/adding-sending-custom-woocommerce-email/>
270,235
<p>I'm trying to make booking - plugin with form on WordPress-admin site, where I can add new event in calendar (made with JavaScript). I have to submit form with all data and insert data to MySQL Database.</p> <p>My <strong>ajax.js</strong> file:</p> <pre><code>function ajaxSubmit(e){ var nazwa_szkolenia = document.getElementById(&quot;nazwa_szkolenia&quot;).value; var Data_szkolenia = document.getElementById(&quot;Data_szkolenia&quot;).value; var Godzina = document.getElementById(&quot;Godzina&quot;).value; var Max_pacjent = document.getElementById(&quot;Max_pacjent&quot;).value; // Returns successful data submission message when the entered information is stored in database. var dataString = 'nazwa_szkolenia1=' + nazwa_szkolenia + '&amp;Data_szkolenia1=' + Data_szkolenia + '&amp;Godzina1=' + Godzina + '&amp;Max_pacjent1=' + Max_pacjent; if (nazwa_szkolenia == '' || Data_szkolenia == '' || Max_pacjent == '') { alert(&quot;fill all fields&quot;); } else { // prevent the default action. e.preventDefault(); var myform= jQuery(this).serialize(); jQuery.ajax({ type:&quot;POST&quot;, // Get the admin ajax url which we have passed through wp_localize_script(). url: ajax_object.ajax_url, action: &quot;submitAjaxForm&quot;, data: dataString, error: function(jqXHR, textStatus, errorThrown){ console.error(&quot;The following error occurred: &quot; + textStatus, errorThrown); }, success:function(data){ alert(&quot;process OK&quot;); } }); } return false; } </code></pre> <p><strong>arcode-functions.php</strong>:</p> <pre><code>&lt;?php add_action('init', 'registerFormAction'); function registerFormAction(){ add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback'); add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback'); } function submitAjaxForm_callback(){ global $wpdb; $nazwa_szkolenia2 = $_POST['nazwa_szkolenia1']; $Data_szkolenia2 = $_POST['Data_szkolenia1']; $Godzina2 = $_POST['Godzina1']; $Max_pacjent2 = $_POST['Max_pacjent1']; $wpdb-&gt;insert( $wpdb-&gt;modul_terminarz, array( 'proba' =&gt; $nazwa_szkolenia2, 'id' =&gt; '10', 'data_szkolenia' =&gt; $Data_szkolenia2, 'typ_szkolenia' =&gt; '1', 'ile_miejsc' =&gt; $Max_pacjent2, 'pelne' =&gt; '1', 'Ile_miejsc_akt' =&gt; '4' ) ); wp_die(); } ?&gt; </code></pre> <p>I've added <code>admin-ajax.php</code> with <code>wp_localize_script</code> function. The form button is made with JavaScript:</p> <pre><code>var Input_Form_Send = document.createElement('input'); Input_Form_Send.value = 'Utwórz'; Input_Form_Send.type = 'submit'; Input_Form_Send.className = 'input-form-send'; Input_Form_Send.onclick = ajaxSubmit; </code></pre> <p>When I fill all fields from form, click on the button, then comes alert &quot;process ok&quot;, but on the Database comes nothing new... <em>nazwa_szkolenia</em>, <em>Data_szkolenia</em>, <em>Godzina</em>, <em>Max_pacjent</em> -those are the names of the form fields.</p> <p>Maybe you know what I've made wrong?</p>
[ { "answer_id": 270256, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Whatever plugin you're using for ecommerce, there should be an email hook available to customize the emails.</p>\n\n<p>For example, WooCommerce provides 9 different hooks in its \"new order\" email. Here's a <a href=\"https://businessbloomer.com/woocommerce-visual-hook-guide-emails/\" rel=\"nofollow noreferrer\">visual reference</a>.</p>\n\n<p>Add a function that runs on the desired hook, and you can add conditional content. You'll have to find a way to identify \"any product from a particular category\" - pull order details, loop through the products, and if any of them is from that category, trigger your conditional content.</p>\n\n<p>Further related reading: <a href=\"https://tommcfarlin.com/customizing-woocommerce-emails-hooks/\" rel=\"nofollow noreferrer\">https://tommcfarlin.com/customizing-woocommerce-emails-hooks/</a></p>\n" }, { "answer_id": 320078, "author": "Brad Holmes", "author_id": 133516, "author_profile": "https://wordpress.stackexchange.com/users/133516", "pm_score": 2, "selected": false, "text": "<p>Firstly extend WC_Email class to define the email header, subject, email template for content</p>\n\n<p>secondly, add custom email class to the default WooCommerce email classes using woocommerce_email_classes filter, with trigger that calls terms </p>\n\n<pre><code>if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) )\n</code></pre>\n\n<p>lastly, Create an email template to be used to generate email content for your custom email.</p>\n\n<p>this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. </p>\n\n<p><a href=\"https://cloudredux.com/adding-sending-custom-woocommerce-email/\" rel=\"nofollow noreferrer\">https://cloudredux.com/adding-sending-custom-woocommerce-email/</a></p>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121854/" ]
I'm trying to make booking - plugin with form on WordPress-admin site, where I can add new event in calendar (made with JavaScript). I have to submit form with all data and insert data to MySQL Database. My **ajax.js** file: ``` function ajaxSubmit(e){ var nazwa_szkolenia = document.getElementById("nazwa_szkolenia").value; var Data_szkolenia = document.getElementById("Data_szkolenia").value; var Godzina = document.getElementById("Godzina").value; var Max_pacjent = document.getElementById("Max_pacjent").value; // Returns successful data submission message when the entered information is stored in database. var dataString = 'nazwa_szkolenia1=' + nazwa_szkolenia + '&Data_szkolenia1=' + Data_szkolenia + '&Godzina1=' + Godzina + '&Max_pacjent1=' + Max_pacjent; if (nazwa_szkolenia == '' || Data_szkolenia == '' || Max_pacjent == '') { alert("fill all fields"); } else { // prevent the default action. e.preventDefault(); var myform= jQuery(this).serialize(); jQuery.ajax({ type:"POST", // Get the admin ajax url which we have passed through wp_localize_script(). url: ajax_object.ajax_url, action: "submitAjaxForm", data: dataString, error: function(jqXHR, textStatus, errorThrown){ console.error("The following error occurred: " + textStatus, errorThrown); }, success:function(data){ alert("process OK"); } }); } return false; } ``` **arcode-functions.php**: ``` <?php add_action('init', 'registerFormAction'); function registerFormAction(){ add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback'); add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback'); } function submitAjaxForm_callback(){ global $wpdb; $nazwa_szkolenia2 = $_POST['nazwa_szkolenia1']; $Data_szkolenia2 = $_POST['Data_szkolenia1']; $Godzina2 = $_POST['Godzina1']; $Max_pacjent2 = $_POST['Max_pacjent1']; $wpdb->insert( $wpdb->modul_terminarz, array( 'proba' => $nazwa_szkolenia2, 'id' => '10', 'data_szkolenia' => $Data_szkolenia2, 'typ_szkolenia' => '1', 'ile_miejsc' => $Max_pacjent2, 'pelne' => '1', 'Ile_miejsc_akt' => '4' ) ); wp_die(); } ?> ``` I've added `admin-ajax.php` with `wp_localize_script` function. The form button is made with JavaScript: ``` var Input_Form_Send = document.createElement('input'); Input_Form_Send.value = 'Utwórz'; Input_Form_Send.type = 'submit'; Input_Form_Send.className = 'input-form-send'; Input_Form_Send.onclick = ajaxSubmit; ``` When I fill all fields from form, click on the button, then comes alert "process ok", but on the Database comes nothing new... *nazwa\_szkolenia*, *Data\_szkolenia*, *Godzina*, *Max\_pacjent* -those are the names of the form fields. Maybe you know what I've made wrong?
Firstly extend WC\_Email class to define the email header, subject, email template for content secondly, add custom email class to the default WooCommerce email classes using woocommerce\_email\_classes filter, with trigger that calls terms ``` if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) ) ``` lastly, Create an email template to be used to generate email content for your custom email. this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. <https://cloudredux.com/adding-sending-custom-woocommerce-email/>
270,253
<p>I display a wp_editor on the front-end and everything was going fine until a recent WP update.</p> <p>Now, the "insert/edit link" is not working due to a Javascript error:</p> <pre><code>Uncaught TypeError: Cannot set property 'tempHide' of undefined </code></pre> <p>This error only appears on front-end. The back-end is going fine.</p> <p>I've looked for it on StackExchange and Google. Maybe I'm not using the right keywords, but I don't find anyone with the same problem...</p> <p>Has anyone an idea?</p>
[ { "answer_id": 270269, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I suspect a theme error. Try a different theme (like the standard ones - Twenty-whatevers).</p>\n" }, { "answer_id": 276354, "author": "Emilien Schneider", "author_id": 121184, "author_profile": "https://wordpress.stackexchange.com/users/121184", "pm_score": 2, "selected": true, "text": "<p>I found it at last!</p>\n\n<p>Using the browser debugger, I found that there was a \"editor.wp\" which was undefined (in the complete version of the js file).\nThen I understood that the \"wordpress\" plugin was not used in the editor.</p>\n\n<p>When calling the function wp_editor, I was setting a list of plugin : paste, wplink, textcolor.\nIt was working until a specific WordPress update.</p>\n\n<p>I just had to add the \"wordpress\" plugin in the list, and now it's working.</p>\n" } ]
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121184/" ]
I display a wp\_editor on the front-end and everything was going fine until a recent WP update. Now, the "insert/edit link" is not working due to a Javascript error: ``` Uncaught TypeError: Cannot set property 'tempHide' of undefined ``` This error only appears on front-end. The back-end is going fine. I've looked for it on StackExchange and Google. Maybe I'm not using the right keywords, but I don't find anyone with the same problem... Has anyone an idea?
I found it at last! Using the browser debugger, I found that there was a "editor.wp" which was undefined (in the complete version of the js file). Then I understood that the "wordpress" plugin was not used in the editor. When calling the function wp\_editor, I was setting a list of plugin : paste, wplink, textcolor. It was working until a specific WordPress update. I just had to add the "wordpress" plugin in the list, and now it's working.