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
183,250
<p><a href="http://www.winnebagoparts.com/specials/top-100-products/" rel="nofollow">This page</a> is created using a recent posts shortcode included with my theme. It is not displaying paragraph breaks that I've added in the editor and I'd like it to. How can I get the shortcode to display the paragraph breaks?</p> <p>This is the code that compiles the list of recent posts:</p> <pre><code>if (!function_exists('mo_get_thumbnail_post_list')) { function mo_get_thumbnail_post_list($args) { /* Set the default arguments. */ $defaults = array( 'loop' =&gt; null, 'image_size' =&gt; 'small', 'style' =&gt; null, 'show_meta' =&gt; false, 'excerpt_count' =&gt; 120, 'hide_thumbnail' =&gt; false ); /* Merge the input arguments and the defaults. */ $args = wp_parse_args($args, $defaults); /* Extract the array to allow easy use of variables. */ extract($args); if ($loop-&gt;have_posts()): $css_class = $image_size . '-size'; $image_size = mo_get_post_image_size($image_size); $style = ($style ? ' ' . $style : ''); $output = '&lt;ul class="post-list' . $style . ' ' . $css_class . '"&gt;'; $hide_thumbnail = mo_to_boolean($hide_thumbnail); $show_meta = mo_to_boolean($show_meta); while ($loop-&gt;have_posts()) : $loop-&gt;the_post(); $output .= '&lt;li&gt;'; $thumbnail_exists = false; $output .= "\n" . '&lt;div class="' . join(' ', get_post_class()) . '"&gt;' . "\n"; // Removed id="post-'.get_the_ID() to help avoid duplicate IDs validation error in the page if (!$hide_thumbnail) { $thumbnail_url = mo_get_thumbnail(array('image_size' =&gt; $image_size)); if (!empty($thumbnail_url)) { $thumbnail_exists = true; $output .= $thumbnail_url; } } $output .= "\n" . '&lt;div class="entry-text-wrap ' . ($thumbnail_exists ? '' : 'nothumbnail') . '"&gt;'; $output .= "\n" . the_title('&lt;div class="entry-title"&gt;&lt;h2&gt;&lt;a title="' . the_title_attribute('echo=0') . '" rel="bookmark"&gt;', '&lt;/a&gt;&lt;/h2&gt;&lt;/div&gt;', false); if ($show_meta) { $output .= '&lt;div class="byline"&gt;' . mo_entry_published() . mo_entry_comments_number() . '&lt;/div&gt;'; } if ($excerpt_count != 0) { $output .= "\n" . '&lt;div class="entry-summary"&gt;'; $output .= get_the_content(); $output .= "\n" . '&lt;/div&gt;&lt;!-- entry-summary --&gt;'; } $output .= "\n" . '&lt;/div&gt;&lt;!-- entry-text-wrap --&gt;'; $output .= "\n" . '&lt;/div&gt;&lt;!-- .hentry --&gt;'; $output .= '&lt;/li&gt;'; endwhile; $output .= '&lt;/ul&gt;'; endif; wp_reset_postdata(); return $output; } } </code></pre> <p>I've contacted the theme creator about this and they haven't been too helpful with the matter.</p>
[ { "answer_id": 183500, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p><code>get_the_content()</code> returns unfiltered content, and using a shortcode you cannot use <code>the_content()</code> to return filtered content as you cannot echo inside a shortcode. Your best option here will be is to applying <code>the_content</code> filters to <code>get_the_content()</code>, something like:</p>\n\n<pre><code>apply_filters( 'the_content', get_the_content() );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Exact usage, replace </p>\n\n<pre><code>$output .= get_the_content();\n</code></pre>\n\n<p>with</p>\n\n<pre><code>$output .= apply_filters( 'the_content', get_the_content() );\n</code></pre>\n" }, { "answer_id": 183501, "author": "T.rev", "author_id": 43424, "author_profile": "https://wordpress.stackexchange.com/users/43424", "pm_score": 0, "selected": false, "text": "<p>Found a solution <a href=\"http://www.web-templates.nu/2008/08/31/get_the_content-with-formatting/\" rel=\"nofollow\">here</a>: </p>\n\n<pre><code>function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {\n$content = get_the_content($more_link_text, $stripteaser, $more_file);\n$content = apply_filters('the_content', $content);\n$content = str_replace(']]&gt;', ']]&amp;gt;', $content);\nreturn $content;\n}\n</code></pre>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43424/" ]
[This page](http://www.winnebagoparts.com/specials/top-100-products/) is created using a recent posts shortcode included with my theme. It is not displaying paragraph breaks that I've added in the editor and I'd like it to. How can I get the shortcode to display the paragraph breaks? This is the code that compiles the list of recent posts: ``` if (!function_exists('mo_get_thumbnail_post_list')) { function mo_get_thumbnail_post_list($args) { /* Set the default arguments. */ $defaults = array( 'loop' => null, 'image_size' => 'small', 'style' => null, 'show_meta' => false, 'excerpt_count' => 120, 'hide_thumbnail' => false ); /* Merge the input arguments and the defaults. */ $args = wp_parse_args($args, $defaults); /* Extract the array to allow easy use of variables. */ extract($args); if ($loop->have_posts()): $css_class = $image_size . '-size'; $image_size = mo_get_post_image_size($image_size); $style = ($style ? ' ' . $style : ''); $output = '<ul class="post-list' . $style . ' ' . $css_class . '">'; $hide_thumbnail = mo_to_boolean($hide_thumbnail); $show_meta = mo_to_boolean($show_meta); while ($loop->have_posts()) : $loop->the_post(); $output .= '<li>'; $thumbnail_exists = false; $output .= "\n" . '<div class="' . join(' ', get_post_class()) . '">' . "\n"; // Removed id="post-'.get_the_ID() to help avoid duplicate IDs validation error in the page if (!$hide_thumbnail) { $thumbnail_url = mo_get_thumbnail(array('image_size' => $image_size)); if (!empty($thumbnail_url)) { $thumbnail_exists = true; $output .= $thumbnail_url; } } $output .= "\n" . '<div class="entry-text-wrap ' . ($thumbnail_exists ? '' : 'nothumbnail') . '">'; $output .= "\n" . the_title('<div class="entry-title"><h2><a title="' . the_title_attribute('echo=0') . '" rel="bookmark">', '</a></h2></div>', false); if ($show_meta) { $output .= '<div class="byline">' . mo_entry_published() . mo_entry_comments_number() . '</div>'; } if ($excerpt_count != 0) { $output .= "\n" . '<div class="entry-summary">'; $output .= get_the_content(); $output .= "\n" . '</div><!-- entry-summary -->'; } $output .= "\n" . '</div><!-- entry-text-wrap -->'; $output .= "\n" . '</div><!-- .hentry -->'; $output .= '</li>'; endwhile; $output .= '</ul>'; endif; wp_reset_postdata(); return $output; } } ``` I've contacted the theme creator about this and they haven't been too helpful with the matter.
`get_the_content()` returns unfiltered content, and using a shortcode you cannot use `the_content()` to return filtered content as you cannot echo inside a shortcode. Your best option here will be is to applying `the_content` filters to `get_the_content()`, something like: ``` apply_filters( 'the_content', get_the_content() ); ``` EDIT ---- Exact usage, replace ``` $output .= get_the_content(); ``` with ``` $output .= apply_filters( 'the_content', get_the_content() ); ```
183,278
<p>I have a custom theme that I use for many client sites. I regularly update the theme and need a way to have the sites notified when there is an update to the theme.</p> <p>I tried using <a href="https://github.com/UCF/Theme-Updater" rel="nofollow">https://github.com/UCF/Theme-Updater</a> but since it is no longer supported and hasn't been updated I can not get it to work with WP 4.1.1.</p> <p>I get the notification of the update in WP, but the update will not load. I get an error every time.</p> <p>Is there another way to update custom themes?</p>
[ { "answer_id": 183285, "author": "Frankie Jarrett", "author_id": 10993, "author_profile": "https://wordpress.stackexchange.com/users/10993", "pm_score": 0, "selected": false, "text": "<p>If you are looking for a simple solution that you don't have to worry about coding yourself I would recommend you check out <a href=\"http://wp-updates.com/\" rel=\"nofollow\">wp-updates.com</a>.</p>\n\n<p>I think it's free to signup for an account, it works for both custom themes and custom plugins, and they claim you can integrate the service with just <em>2 lines</em> of code.</p>\n\n<blockquote>\n <p>Provide automatic updates for your premium WordPress themes and plugins with 2 lines of code.</p>\n</blockquote>\n\n<p>It's made by the team at <a href=\"http://dev7studios.com/\" rel=\"nofollow\">Dev7studios</a>, who are a respected group in the premium WordPress plugin space.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 219474, "author": "Dionoh", "author_id": 44597, "author_profile": "https://wordpress.stackexchange.com/users/44597", "pm_score": 2, "selected": false, "text": "<p>Here is a full documentation for how to do this:\n<a href=\"https://github.com/afragen/github-updater\" rel=\"nofollow\">Github updater - Documentation</a></p>\n\n<p><strong>Upload in wordpress</strong></p>\n\n<p>Download the latest tagged archive (choose the \"<a href=\"https://github.com/afragen/github-updater/archive/develop.zip\" rel=\"nofollow\"><strong>zip</strong></a>\" option).</p>\n\n<p>Unzip the archive, rename the folder correctly to <strong><em>github-updater</em></strong>, then <strong><em>re-zip</em></strong> the file.</p>\n\n<p>Go to the Plugins -> Add New screen and click the Upload tab.</p>\n\n<p>Upload the zipped archive directly.</p>\n\n<p>Go to the Plugins screen and click Activate. </p>\n\n<p>[<strong>Description</strong>]</p>\n\n<p>This plugin was designed to simply update any GitHub hosted WordPress\n plugin or theme. Your plugin or theme must contain a header in the\n style.css header or in the plugin's header denoting the location on\n GitHub. The format is as follows.</p>\n\n<p><code>GitHub Plugin URI: afragen/github-updater</code></p>\n\n<p><code>GitHub Plugin URI: https://github.com/afragen/github-updater</code></p>\n\n<p>or</p>\n\n<p><code>GitHub Theme URI: afragen/test-child</code></p>\n\n<p><code>GitHub Theme URI: https://github.com/afragen/test-child</code></p>\n\n<p>...where the above URI leads to the <strong>owner/repository</strong> of your theme or\n plugin. The URI may be in the format <code>https://github.com/&lt;owner&gt;/&lt;repo&gt;</code>\n or the short format <code>&lt;owner&gt;/&lt;repo&gt;</code>. You do not need both. Only one\n Plugin or Theme URI is required. <strong>You must not</strong> include any extensions\n like <code>.git</code>.</p>\n\n<p><strong>[Usage]</strong></p>\n\n<p><strong>Plugins</strong></p>\n\n<p>There must be a <code>GitHub Plugin URI</code>, <code>Bitbucket Plugin URI</code>, or <code>GitLab Plugin URI</code> declaration in the plugin's header.</p>\n\n<pre><code>/*\nPlugin Name: GitHub Updater\nPlugin URI: https://github.com/afragen/github-updater\nDescription: A plugin to automatically update GitHub, Bitbucket or GitLab hosted plugins and themes. It also allows for remote installation of plugins or themes into WordPress.\nVersion: 1.0.0\nAuthor: Andy Fragen\nLicense: GNU General Public License v2\nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html\nDomain Path: /languages\nText Domain: github-updater\nGitHub Plugin URI: https://github.com/afragen/github-updater\nGitHub Branch: master\n*/\n</code></pre>\n\n<p><strong>Themes</strong></p>\n\n<p>There must be a <code>GitHub Theme URI</code>, <code>Bitbucket Theme URI</code>, or <code>GitLab Theme URI</code> declaration in the <code>style.css</code> file. When initially adding a theme, the directory <strong>must</strong> be identical to the repo name.</p>\n\n<pre><code>/*\nTheme Name: Test\nTheme URI: http://thefragens.net/\nVersion: 0.1.0\nDescription: Child theme of TwentyTwelve.\nAuthor: Andy Fragen\nTemplate: twentytwelve\nTemplate Version: 1.0.0\nGitHub Theme URI: https://github.com/afragen/test-child\nGitHub Branch: master\n*/\n</code></pre>\n\n<p>Hope this helps.</p>\n\n<p>Please let me know</p>\n" } ]
2015/04/04
[ "https://wordpress.stackexchange.com/questions/183278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70162/" ]
I have a custom theme that I use for many client sites. I regularly update the theme and need a way to have the sites notified when there is an update to the theme. I tried using <https://github.com/UCF/Theme-Updater> but since it is no longer supported and hasn't been updated I can not get it to work with WP 4.1.1. I get the notification of the update in WP, but the update will not load. I get an error every time. Is there another way to update custom themes?
Here is a full documentation for how to do this: [Github updater - Documentation](https://github.com/afragen/github-updater) **Upload in wordpress** Download the latest tagged archive (choose the "[**zip**](https://github.com/afragen/github-updater/archive/develop.zip)" option). Unzip the archive, rename the folder correctly to ***github-updater***, then ***re-zip*** the file. Go to the Plugins -> Add New screen and click the Upload tab. Upload the zipped archive directly. Go to the Plugins screen and click Activate. [**Description**] This plugin was designed to simply update any GitHub hosted WordPress plugin or theme. Your plugin or theme must contain a header in the style.css header or in the plugin's header denoting the location on GitHub. The format is as follows. `GitHub Plugin URI: afragen/github-updater` `GitHub Plugin URI: https://github.com/afragen/github-updater` or `GitHub Theme URI: afragen/test-child` `GitHub Theme URI: https://github.com/afragen/test-child` ...where the above URI leads to the **owner/repository** of your theme or plugin. The URI may be in the format `https://github.com/<owner>/<repo>` or the short format `<owner>/<repo>`. You do not need both. Only one Plugin or Theme URI is required. **You must not** include any extensions like `.git`. **[Usage]** **Plugins** There must be a `GitHub Plugin URI`, `Bitbucket Plugin URI`, or `GitLab Plugin URI` declaration in the plugin's header. ``` /* Plugin Name: GitHub Updater Plugin URI: https://github.com/afragen/github-updater Description: A plugin to automatically update GitHub, Bitbucket or GitLab hosted plugins and themes. It also allows for remote installation of plugins or themes into WordPress. Version: 1.0.0 Author: Andy Fragen License: GNU General Public License v2 License URI: http://www.gnu.org/licenses/gpl-2.0.html Domain Path: /languages Text Domain: github-updater GitHub Plugin URI: https://github.com/afragen/github-updater GitHub Branch: master */ ``` **Themes** There must be a `GitHub Theme URI`, `Bitbucket Theme URI`, or `GitLab Theme URI` declaration in the `style.css` file. When initially adding a theme, the directory **must** be identical to the repo name. ``` /* Theme Name: Test Theme URI: http://thefragens.net/ Version: 0.1.0 Description: Child theme of TwentyTwelve. Author: Andy Fragen Template: twentytwelve Template Version: 1.0.0 GitHub Theme URI: https://github.com/afragen/test-child GitHub Branch: master */ ``` Hope this helps. Please let me know
183,283
<p>I want to specify an alternative image that will be displayed when oEmbed fails.</p> <p>The specific use case is to offer an alternative when China (or other countries) block YouTube. We know the YouTube content won't be available there, but want to provide an alternate image in that case.</p> <p>Can the oEmbed error code be made accessible for this purpose?</p>
[ { "answer_id": 191740, "author": "codecowboy", "author_id": 500, "author_profile": "https://wordpress.stackexchange.com/users/500", "pm_score": 0, "selected": false, "text": "<p>One approach might be to make another request using oEmbed on the server side via a proxy which is based in China.</p>\n\n<p>This way you would know ahead of time if the call to the resource on the client is going to fail. Early on in the page request you can ascertain where the client's IP is located geographically, make a server-side call via a proxy to the resource e.g youtube and then leverage the oEmbed error you'll presumably get. </p>\n\n<p>You could take a look at <a href=\"https://wonderproxy.com/\" rel=\"nofollow\">Wonderproxy</a> for achieving this (I am not affiliated with them but hear good things)</p>\n" }, { "answer_id": 195284, "author": "Daron Spence", "author_id": 31283, "author_profile": "https://wordpress.stackexchange.com/users/31283", "pm_score": 1, "selected": false, "text": "<p>I think the best thing to do in this case is to wrap your oEmbed content with a <code>div</code> before they are rendered and then show an alternate image with the CSS <code>background-image</code> property. If the video loads, then the oEmbed content will cover the background image.</p>\n\n<p>You can add the wrapper using the <code>embed_oembed_html</code> filter.</p>\n\n<pre><code>add_filter('embed_oembed_html', 'your_function_here');\n</code></pre>\n\n<p>If you're worried about loading in extra elements, then you can do a client side check with JS to see if the oEmbed loaded, and if not, load a background image into the wrapper.</p>\n\n<p>You could get a lot more complicated by adding in custom fields for each video, but that's essentially the gist of it.</p>\n" } ]
2015/04/05
[ "https://wordpress.stackexchange.com/questions/183283", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31322/" ]
I want to specify an alternative image that will be displayed when oEmbed fails. The specific use case is to offer an alternative when China (or other countries) block YouTube. We know the YouTube content won't be available there, but want to provide an alternate image in that case. Can the oEmbed error code be made accessible for this purpose?
I think the best thing to do in this case is to wrap your oEmbed content with a `div` before they are rendered and then show an alternate image with the CSS `background-image` property. If the video loads, then the oEmbed content will cover the background image. You can add the wrapper using the `embed_oembed_html` filter. ``` add_filter('embed_oembed_html', 'your_function_here'); ``` If you're worried about loading in extra elements, then you can do a client side check with JS to see if the oEmbed loaded, and if not, load a background image into the wrapper. You could get a lot more complicated by adding in custom fields for each video, but that's essentially the gist of it.
183,292
<p>I'm using <code>wp_dropdown_categories()</code> for populating <code>&lt;select&gt;</code> field with custom taxonomy terms.</p> <p>If the code is like below:</p> <pre><code>&lt;?php $args = array( 'show_option_none' =&gt; __( 'Select one', 'text-domain' ), 'taxonomy' =&gt; 'my_tax', 'id' =&gt; 'tax-type', 'echo' =&gt; 1, ); wp_dropdown_categories( $args ); </code></pre> <p>It's working just fine. I can make the field mandatory with jQuery:</p> <pre><code>$('#tax-type option:first').val(null); $('#tax-type').attr('required', true); </code></pre> <p>It's working too. But, I want to make the field mandatory without JavaScripts. I tried adding the following by making the <code>'echo'</code> to <code>0</code>:</p> <pre><code>$new = array(); $new['required'] = true; $mrg = array_merge($args, $new); var_dump($mrg); //outputs 'required'=&gt;1 $dd = wp_dropdown_categories( $mrg ); echo $dd; </code></pre> <p>I can also understand why it's not working. But is there a way I can achieve that without JavaScripts? Any filter? Please don't just say:</p> <blockquote> <p><em>copy from the core and make your new one with that option.</em></p> </blockquote> <p>And my second question is: Why the none_option's value is <code>-1</code>? Why not it's a <code>''</code> (null)?</p>
[ { "answer_id": 183298, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 1, "selected": false, "text": "<p>There's a filter - <code>wp_dropdown_cats</code> (not documented anywhere as far as I know.)</p>\n\n<p>It gives you two parameters, the HTML string and an array of the arguments supplied to <code>wp_dropdown_categories</code>, and you need to return the new HTML.</p>\n" }, { "answer_id": 183299, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 1, "selected": false, "text": "<p>If you have a look into the function in <em>wp-includes/category-template.php</em> you will see, there is no option for 'required' build in. So we have to choose another way since <code>$args['required']</code> doesn't work - as you know.</p>\n\n<p>We find the filter <code>'wp_dropdown_cats'</code>, which provides us with the output just before the function returns this output. So we could work with this filter and alter\n<code>\"&lt;select \"</code> to <code>\"&lt;select required \"</code>:</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required' );\nfunction wp_dropdown_categories_required( $output ){\n return preg_replace( \n '^' . preg_quote( '&lt;select ' ) . '^', \n '&lt;select required ', \n $output \n );\n}\n</code></pre>\n\n<p>Regarding your second question:</p>\n\n<blockquote>\n <p>Why the none_option's value is -1? Why not it's a '' (null)?</p>\n</blockquote>\n\n<p>This is the standard value, which the function adds to the \"none\"-option. You can change this value with $args['option_none_value']. So for example:</p>\n\n<pre><code>$args = array(\n 'show_option_none' =&gt; 'test',\n 'option_none_value' =&gt; 'x'\n);\nwp_dropdown_categories( $args );\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/wp_dropdown_categories\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_dropdown_categories</a></p>\n\n<p>If you want to add the \"required\"-Attribute just to a specific select-field, you could add yourself a 'required'-Attribute, which you check in the filter:</p>\n\n<pre><code> function show_pages(){\n $args = array(\n 'show_option_none' =&gt; 'test',\n 'option_none_value' =&gt; 'x',\n 'required' =&gt; true\n );\n wp_dropdown_categories( $args );\n }\n\n add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required', 10, 2 );\n function wp_dropdown_categories_required( $output, $args ){\n if( ! isset( $args['required'] ) || $args['required'] != true )\n return $output;\n\n return preg_replace( \n '^' . preg_quote( '&lt;select ' ) . '^', \n '&lt;select required ', \n $output \n );\n }\n</code></pre>\n\n<p>All the best.</p>\n" }, { "answer_id": 183302, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>If you want to apply the <code>required</code> attribute every time you use <code>wp_categories_dropdown</code>, use <code>wp_dropdown_cats</code> filter as suggested in other answers:</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required' );\nfunction wp_dropdown_categories_required( $output ){\n return preg_replace( \n '^' . preg_quote( '&lt;select ' ) . '^', \n '&lt;select required ', \n $output \n );\n}\n</code></pre>\n\n<p>If you want to apply the <code>required</code> attribute only in especific situations, you can use <code>wp_dropdown_categories</code> with <code>echo</code> argument set to <code>false</code>, introduce the <code>required</code> attribute in the returned string and then <code>echo</code>:</p>\n\n<pre><code>$args = array(\n 'show_option_none' =&gt; __( 'Select one', 'text-domain' ),\n 'taxonomy' =&gt; 'my_tax',\n 'id' =&gt; 'tax-type',\n 'echo' =&gt; false,\n);\n\n$cat_dropdown = wp_dropdown_categories( $args );\n\n$cat_dropdown = preg_replace( \n '^' . preg_quote( '&lt;select ' ) . '^', \n '&lt;select required ', \n $cat_dropdown\n );\n\necho $cat_dropdown;\n</code></pre>\n\n<p>Or maybe better, apply the filter combined with a custom <code>required</code> attribute:</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required', 10, 2 );\nfunction wp_dropdown_categories_required( $output, $args ){\n\n if( isset( $args['required'] ) &amp;&amp; $args['required'] ) {\n\n $output = preg_replace( \n '^' . preg_quote( '&lt;select ' ) . '^', \n '&lt;select required ', \n $output \n );\n\n }\n\n return $output;\n\n}\n</code></pre>\n\n<p>And then use <code>wp_dropdown_categories</code> like this:</p>\n\n<pre><code>$args = array(\n 'show_option_none' =&gt; __( 'Select one', 'text-domain' ),\n 'taxonomy' =&gt; 'my_tax',\n 'id' =&gt; 'tax-type',\n 'required' =&gt; true,\n);\n\nwp_dropdown_categories( $args );\n</code></pre>\n\n<p>About the second question, you should know that there is a \"one question per thread\" rule. Remember that for future questions. Than being said, <code>-1</code> is the default value for <code>option_none_value</code> argument. This argument was not documented (now it is, I've added it to <a href=\"http://codex.wordpress.org/Function_Reference/wp_dropdown_categories#Arguments\" rel=\"noreferrer\">codex</a>). You can override it as follow:</p>\n\n<pre><code>$args = array(\n 'show_option_none' =&gt; __( 'Select one', 'text-domain' ),\n 'option_none_value' =&gt; NULL,\n 'taxonomy' =&gt; 'my_tax',\n 'id' =&gt; 'tax-type',\n 'echo' =&gt; false\n);\n</code></pre>\n\n<p>PD: I'm not sure if <code>NULL</code> is a valid value for a <code>option</code> in a <code>select</code> element. Also, note that <code>''</code> (empty string) is not the same that <code>NULL</code>. An empty string is a string data type with zero length; <code>NULL</code> is not any date type and has not data properties, it is nothing.</p>\n" }, { "answer_id": 236695, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 2, "selected": false, "text": "<h1>Update: WordPress 4.6</h1>\n<p>As from WordPress 4.6 we can add a 'required' attribute directly to <a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a>.</p>\n<pre><code>&lt;?php\n$args = array(\n 'show_option_none' =&gt; __( 'Select one', 'text-domain' ),\n 'taxonomy' =&gt; 'my_tax',\n 'id' =&gt; 'tax-type',\n 'echo' =&gt; 1,\n 'required' =&gt; true\n);\nwp_dropdown_categories( $args );\n</code></pre>\n<p><strong>Source:</strong> <a href=\"https://core.trac.wordpress.org/ticket/31909\" rel=\"nofollow noreferrer\">Core Tract Ticket</a></p>\n" } ]
2015/04/05
[ "https://wordpress.stackexchange.com/questions/183292", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I'm using `wp_dropdown_categories()` for populating `<select>` field with custom taxonomy terms. If the code is like below: ``` <?php $args = array( 'show_option_none' => __( 'Select one', 'text-domain' ), 'taxonomy' => 'my_tax', 'id' => 'tax-type', 'echo' => 1, ); wp_dropdown_categories( $args ); ``` It's working just fine. I can make the field mandatory with jQuery: ``` $('#tax-type option:first').val(null); $('#tax-type').attr('required', true); ``` It's working too. But, I want to make the field mandatory without JavaScripts. I tried adding the following by making the `'echo'` to `0`: ``` $new = array(); $new['required'] = true; $mrg = array_merge($args, $new); var_dump($mrg); //outputs 'required'=>1 $dd = wp_dropdown_categories( $mrg ); echo $dd; ``` I can also understand why it's not working. But is there a way I can achieve that without JavaScripts? Any filter? Please don't just say: > > *copy from the core and make your new one with that option.* > > > And my second question is: Why the none\_option's value is `-1`? Why not it's a `''` (null)?
If you want to apply the `required` attribute every time you use `wp_categories_dropdown`, use `wp_dropdown_cats` filter as suggested in other answers: ``` add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required' ); function wp_dropdown_categories_required( $output ){ return preg_replace( '^' . preg_quote( '<select ' ) . '^', '<select required ', $output ); } ``` If you want to apply the `required` attribute only in especific situations, you can use `wp_dropdown_categories` with `echo` argument set to `false`, introduce the `required` attribute in the returned string and then `echo`: ``` $args = array( 'show_option_none' => __( 'Select one', 'text-domain' ), 'taxonomy' => 'my_tax', 'id' => 'tax-type', 'echo' => false, ); $cat_dropdown = wp_dropdown_categories( $args ); $cat_dropdown = preg_replace( '^' . preg_quote( '<select ' ) . '^', '<select required ', $cat_dropdown ); echo $cat_dropdown; ``` Or maybe better, apply the filter combined with a custom `required` attribute: ``` add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required', 10, 2 ); function wp_dropdown_categories_required( $output, $args ){ if( isset( $args['required'] ) && $args['required'] ) { $output = preg_replace( '^' . preg_quote( '<select ' ) . '^', '<select required ', $output ); } return $output; } ``` And then use `wp_dropdown_categories` like this: ``` $args = array( 'show_option_none' => __( 'Select one', 'text-domain' ), 'taxonomy' => 'my_tax', 'id' => 'tax-type', 'required' => true, ); wp_dropdown_categories( $args ); ``` About the second question, you should know that there is a "one question per thread" rule. Remember that for future questions. Than being said, `-1` is the default value for `option_none_value` argument. This argument was not documented (now it is, I've added it to [codex](http://codex.wordpress.org/Function_Reference/wp_dropdown_categories#Arguments)). You can override it as follow: ``` $args = array( 'show_option_none' => __( 'Select one', 'text-domain' ), 'option_none_value' => NULL, 'taxonomy' => 'my_tax', 'id' => 'tax-type', 'echo' => false ); ``` PD: I'm not sure if `NULL` is a valid value for a `option` in a `select` element. Also, note that `''` (empty string) is not the same that `NULL`. An empty string is a string data type with zero length; `NULL` is not any date type and has not data properties, it is nothing.
183,376
<p>I have a wordpress plugin where i included this (with some changes)</p> <pre><code>$fep_files = array( 'first' =&gt; 'first.php', 'second' =&gt; 'second.php' ); $fep_files = apply_filters('include_files', $fep_files ); foreach ( $fep_files as $fep_file ) require_once ( $fep_file ); unset ( $fep_files ); </code></pre> <p>Now i added in my theme's function.php</p> <pre><code>function fep_remove ( $fep_files ) { if ( isset ( $fep_files['first'] ) ) { unset ( $fep_files['first'] ); } //die($fep_files); //to check it fires return $fep_files; } add_filter( 'include_files', 'fep_remove' ); </code></pre> <p>It should remove first.php but it does not. i am wrong some where, but where? Is there any better way to include files where user can include/exclude any files if needed?</p>
[ { "answer_id": 183413, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": true, "text": "<p>Your plugin code is going to run before the theme code and hence will run before anything is added to the hook. You will need to the code that processes the file inclusion to some other hook that runs after all of the plugins load, like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\"><code>after_setup_theme</code></a> </p>\n\n<p>This should help: <a href=\"https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence\">Is there a flowchart for wordpress loading sequence?</a></p>\n" }, { "answer_id": 215651, "author": "nobilis", "author_id": 78597, "author_profile": "https://wordpress.stackexchange.com/users/78597", "pm_score": -1, "selected": false, "text": "<p>The previous answer was great as far as the order, but I could not figure out how to make the filter/hook work with those intructions.</p>\n\n<p>My solution was creating a custom plugin containing the filter on it, making sure that it alphabetically comes before the plugin that contains the filter I want to add.</p>\n\n<p>In other words, put the code in <code>plugings/a-custom-plugin.php</code> starting the file with </p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: My Custom Plugin\n*/\n</code></pre>\n" }, { "answer_id": 380182, "author": "Jer", "author_id": 199258, "author_profile": "https://wordpress.stackexchange.com/users/199258", "pm_score": 2, "selected": false, "text": "<p>I think there needs to be an update to some of the answers on here. (Just for when I, or others, come upon this page in the future looking for an answer).</p>\n<p>Plugin ordering seems to depend on the type of Wordpress installation you are working with. If you are working with a Multisite installation, then plugins are indeed processed in the order in which they are activated.</p>\n<p>However, in a single wordpress installation, they are activated alphabetically. So, if you are running into an issue where you need to update an initialization filter or action for another plugin, your best bet is to name your plugin something that begins with an underscore.</p>\n<p>For example: _my_custom_plugin/my_custom_plugin.php</p>\n<p>For reference. please see 704-713 in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/plugin.php\" rel=\"nofollow noreferrer\">wp-admin/includes/plugin.php</a></p>\n" } ]
2015/04/06
[ "https://wordpress.stackexchange.com/questions/183376", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70211/" ]
I have a wordpress plugin where i included this (with some changes) ``` $fep_files = array( 'first' => 'first.php', 'second' => 'second.php' ); $fep_files = apply_filters('include_files', $fep_files ); foreach ( $fep_files as $fep_file ) require_once ( $fep_file ); unset ( $fep_files ); ``` Now i added in my theme's function.php ``` function fep_remove ( $fep_files ) { if ( isset ( $fep_files['first'] ) ) { unset ( $fep_files['first'] ); } //die($fep_files); //to check it fires return $fep_files; } add_filter( 'include_files', 'fep_remove' ); ``` It should remove first.php but it does not. i am wrong some where, but where? Is there any better way to include files where user can include/exclude any files if needed?
Your plugin code is going to run before the theme code and hence will run before anything is added to the hook. You will need to the code that processes the file inclusion to some other hook that runs after all of the plugins load, like [`after_setup_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme) This should help: [Is there a flowchart for wordpress loading sequence?](https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence)
183,429
<p>I've got 20+ hours into this and could really use some help. Here is what I am trying to do.. For each record, add post meta. If the post meta already exists, update each field in the array. Just like it would be with adding and updating a single custom field, except this one is repeatable based off of each record.</p> <p>I know how to add post meta for each record. That's the simple part, it's adding it for each record and then updating it without adding any more before/after the update that I'm having a hard time with. Just for the sake of writing it out, here is just adding the repeating fields based off of each record.</p> <pre><code>foreach ($response-&gt;records as $record) { $sales = 'ten'; update_repeating_meta('assigned-sales', $sales); } </code></pre> <p>The function:</p> <pre><code>function update_repeating_meta($key, $value){ add_post_meta($this-&gt;current_post_id, $key, $value); } </code></pre> <p>That all works fine. Here is what I have so far for adding each one and then updating, that's not working:</p> <pre><code>foreach ($response-&gt;records as $record) { $sales = 'ten'; update_repeating_meta('assigned-sales', $sales); } </code></pre> <p>New function:</p> <pre><code>function update_repeating_meta($key, $value){ $post_meta = get_post_meta($this-&gt;current_post_id, $key); if(!empty($post_meta)){ foreach($post_meta as $key =&gt; $value) { update_post_meta($this-&gt;current_post_id, $key, $value); } } elseif(empty($post_meta)){ add_post_meta($this-&gt;current_post_id, $key, $value); } } </code></pre> <p>This code neither adds nor updates any of the results. Plus, I don't think it has support for updating the correct key/values in the post meta array after the meta data is added. I'm still trying my best to make it work and learn more about it. Sorry in advance if any of this doesn't make sense.</p> <p>I'd really appreciate the help if anyone has any ideas.</p>
[ { "answer_id": 183413, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": true, "text": "<p>Your plugin code is going to run before the theme code and hence will run before anything is added to the hook. You will need to the code that processes the file inclusion to some other hook that runs after all of the plugins load, like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\"><code>after_setup_theme</code></a> </p>\n\n<p>This should help: <a href=\"https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence\">Is there a flowchart for wordpress loading sequence?</a></p>\n" }, { "answer_id": 215651, "author": "nobilis", "author_id": 78597, "author_profile": "https://wordpress.stackexchange.com/users/78597", "pm_score": -1, "selected": false, "text": "<p>The previous answer was great as far as the order, but I could not figure out how to make the filter/hook work with those intructions.</p>\n\n<p>My solution was creating a custom plugin containing the filter on it, making sure that it alphabetically comes before the plugin that contains the filter I want to add.</p>\n\n<p>In other words, put the code in <code>plugings/a-custom-plugin.php</code> starting the file with </p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: My Custom Plugin\n*/\n</code></pre>\n" }, { "answer_id": 380182, "author": "Jer", "author_id": 199258, "author_profile": "https://wordpress.stackexchange.com/users/199258", "pm_score": 2, "selected": false, "text": "<p>I think there needs to be an update to some of the answers on here. (Just for when I, or others, come upon this page in the future looking for an answer).</p>\n<p>Plugin ordering seems to depend on the type of Wordpress installation you are working with. If you are working with a Multisite installation, then plugins are indeed processed in the order in which they are activated.</p>\n<p>However, in a single wordpress installation, they are activated alphabetically. So, if you are running into an issue where you need to update an initialization filter or action for another plugin, your best bet is to name your plugin something that begins with an underscore.</p>\n<p>For example: _my_custom_plugin/my_custom_plugin.php</p>\n<p>For reference. please see 704-713 in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/plugin.php\" rel=\"nofollow noreferrer\">wp-admin/includes/plugin.php</a></p>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64444/" ]
I've got 20+ hours into this and could really use some help. Here is what I am trying to do.. For each record, add post meta. If the post meta already exists, update each field in the array. Just like it would be with adding and updating a single custom field, except this one is repeatable based off of each record. I know how to add post meta for each record. That's the simple part, it's adding it for each record and then updating it without adding any more before/after the update that I'm having a hard time with. Just for the sake of writing it out, here is just adding the repeating fields based off of each record. ``` foreach ($response->records as $record) { $sales = 'ten'; update_repeating_meta('assigned-sales', $sales); } ``` The function: ``` function update_repeating_meta($key, $value){ add_post_meta($this->current_post_id, $key, $value); } ``` That all works fine. Here is what I have so far for adding each one and then updating, that's not working: ``` foreach ($response->records as $record) { $sales = 'ten'; update_repeating_meta('assigned-sales', $sales); } ``` New function: ``` function update_repeating_meta($key, $value){ $post_meta = get_post_meta($this->current_post_id, $key); if(!empty($post_meta)){ foreach($post_meta as $key => $value) { update_post_meta($this->current_post_id, $key, $value); } } elseif(empty($post_meta)){ add_post_meta($this->current_post_id, $key, $value); } } ``` This code neither adds nor updates any of the results. Plus, I don't think it has support for updating the correct key/values in the post meta array after the meta data is added. I'm still trying my best to make it work and learn more about it. Sorry in advance if any of this doesn't make sense. I'd really appreciate the help if anyone has any ideas.
Your plugin code is going to run before the theme code and hence will run before anything is added to the hook. You will need to the code that processes the file inclusion to some other hook that runs after all of the plugins load, like [`after_setup_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme) This should help: [Is there a flowchart for wordpress loading sequence?](https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence)
183,441
<p>I'm really stuck on the WP_Rewrite functionality...</p> <h2>What I have</h2> <p>I have a plugin that's rendered using a shortcode and is displaying full-site content. E.g.:</p> <pre><code>//?p=2 (maps to domain.tld/myplugin/) [my-plugin] </code></pre> <p>This plugin basically is a directory of some list-content. </p> <h2>What I want</h2> <p>Basically I want to achieve nice urls for the categorisation of the list content displayed by the plugin. E.g.:</p> <pre><code>domain.tld/myplugin/?filter=someFilter // works but is ugly domain.tld/myplugin/someFilter // is what I want </code></pre> <h2>What I tried</h2> <p>So I've tried the approach using <code>add_rewrite_rule</code> as well as modifying:</p> <pre><code>global $wp_rewrite $customRules = [ "myplugin/([^/]+)/?" =&gt; "?p=2&amp;filter=$matches[1]" // try 1.1 "myplugin/([^/]+)/?" =&gt; "/myplugin/filter=$matches[1]" // try 2.1 ]; $wp_rewrite-&gt;rules = $customRules + $wp_rewrite-&gt;rules; // try 1 $wp_rewrite-&gt;extra_rules_top = $customRules + $wp_rewrite-&gt;extra_rules_top // try 2 </code></pre> <p>However none of my rewrites work. The best I can achieve is to simply get redirected to <code>/myplugin/</code> without any parameter added to the page. This, I assume, is due to Wordpress matching <code>?p=2</code> to <code>/myplugin/</code> as defined within the permalink structure of the page. So my guess is that parameters simply are stripped from the rule.</p> <h1>So my question:</h1> <p>How can I achieve what I want? Do I really have to write the rewrite-rules hard into the .htaccess?</p> <h2>The 50% solution</h2> <p>So after reading <a href="http://blog.pmg.co/a-mostly-complete-guide-to-the-wordpress-rewrite-api/" rel="nofollow">this awesome article</a> I was able to get at least something working. Ultimately I'm able to achieve</p> <pre><code>domain.tld/myplugin/filter/someFilter a syntax like "param/value" </code></pre> <p>This is done by <code>add_rewrite_endpoint()</code> and adding the filter to the <code>query_vars</code>. For now this thing is what I do but ultimately I'd really like to get it down to:</p> <pre><code>domain.tld/myplugin/someFilter </code></pre> <p>So help will still be much appreciated ;)</p> <h1>Update 1st solution by @websupporter</h1> <p>Tried the approach given by a user here and it still doesn't work. I deactivated all plugins and it still doesn't work.</p> <p>The only thing that could interfere at this point as far as I know is the <code>.htaccess</code> but to me this one looks pretty standard as well..</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 183927, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>This approach should work for you:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Rewrite Shortcode\n **/\n\n add_shortcode( 'myplugin', 'mp_shortcode' );\n function mp_shortcode(){\n return '&lt;p&gt;Filter: ' . get_query_var( 'filter' ) . '&lt;/p&gt;';\n }\n\n add_action( 'init', 'mp_rewrite' );\n function mp_rewrite(){\n $post_id = 2;\n add_rewrite_rule( 'myplugin/([^/]+)/?$', 'index.php?p=' . $post_id . '&amp;filter=$matches[1]', 'top' );\n add_rewrite_tag( '%filter%', '([^/]+)' );\n }\n?&gt;\n</code></pre>\n\n<p>I developed it quickly as a small plugin, so I was able to test it myself. While you work with the global <code>$wp_rewrite</code> I thought it might be better to use the functions, which are documented in the Codex. Basically just, because I know them better :) So I can't exaktly tell, what you did wrong, but I can tell, what I do differently.</p>\n\n<p>You're approach:</p>\n\n<pre><code>\"myplugin/([^/]+)/?\" =&gt; \"?p=2&amp;filter=$matches[1]\n</code></pre>\n\n<p>I've explicitly told WordPress to use the <em>index.php</em> as it is also done in the documents. And I use <code>add_rewrite_tag()</code> to generate a new query variable, which I can read with <code>get_query_var()</code> in my shortcode.</p>\n\n<p><strong>Attention: Flush the Rules!</strong>\nWhen you use these functions, you have to go to Settings > Permalinks and click the \"update\"-button. If you don't do this, the new rules won't be active. You could also use <code>flush_rewrite_rules()</code> during the activation of the plugin. An example on how to do this is given in the Codex.</p>\n\n<p>Docs:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">https://codex.wordpress.org/Rewrite_API/add_rewrite_rule</a> </li>\n<li><a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_tag\" rel=\"nofollow\">https://codex.wordpress.org/Rewrite_API/add_rewrite_tag</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/flush_rewrite_rules</a></li>\n</ul>\n" }, { "answer_id": 184173, "author": "gyo", "author_id": 16929, "author_profile": "https://wordpress.stackexchange.com/users/16929", "pm_score": 1, "selected": false, "text": "<p>I would use the <code>add_rewrite_rule()</code> function, please note that the code is untested but it should work depending on your specific use. If you also need to set a <strong>post_id</strong>, just add it to the <code>index.php?p=X...</code> string.</p>\n\n<pre><code>function myplugin_filter_add_rewrite_rules()\n{\n // Allow for /myplugin/filter/someFilter\n add_rewrite_rule('myplugin/filter/([^/]+)/?$',\n 'index.php?filter=$matches[1]',\n 'top');\n\n // Optionally keep pagination /myplugin/filter/someFilter/page/2\n add_rewrite_rule('myplugin/filter/([^/]+)/page/([0-9]+)?$',\n 'index.php?filter=$matches[1]&amp;paged=$matches[2]',\n 'top');\n}\n\nadd_filter('init', 'myplugin_filter_add_rewrite_rules');\n</code></pre>\n\n<p>As already stated, don't forget to flush the rules by visiting <strong>Settings > Permalinks</strong> or use <code>flush_rewrite_rules()</code> in the plugin activation (don't execute it at every page load).</p>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183441", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13711/" ]
I'm really stuck on the WP\_Rewrite functionality... What I have ----------- I have a plugin that's rendered using a shortcode and is displaying full-site content. E.g.: ``` //?p=2 (maps to domain.tld/myplugin/) [my-plugin] ``` This plugin basically is a directory of some list-content. What I want ----------- Basically I want to achieve nice urls for the categorisation of the list content displayed by the plugin. E.g.: ``` domain.tld/myplugin/?filter=someFilter // works but is ugly domain.tld/myplugin/someFilter // is what I want ``` What I tried ------------ So I've tried the approach using `add_rewrite_rule` as well as modifying: ``` global $wp_rewrite $customRules = [ "myplugin/([^/]+)/?" => "?p=2&filter=$matches[1]" // try 1.1 "myplugin/([^/]+)/?" => "/myplugin/filter=$matches[1]" // try 2.1 ]; $wp_rewrite->rules = $customRules + $wp_rewrite->rules; // try 1 $wp_rewrite->extra_rules_top = $customRules + $wp_rewrite->extra_rules_top // try 2 ``` However none of my rewrites work. The best I can achieve is to simply get redirected to `/myplugin/` without any parameter added to the page. This, I assume, is due to Wordpress matching `?p=2` to `/myplugin/` as defined within the permalink structure of the page. So my guess is that parameters simply are stripped from the rule. So my question: =============== How can I achieve what I want? Do I really have to write the rewrite-rules hard into the .htaccess? The 50% solution ---------------- So after reading [this awesome article](http://blog.pmg.co/a-mostly-complete-guide-to-the-wordpress-rewrite-api/) I was able to get at least something working. Ultimately I'm able to achieve ``` domain.tld/myplugin/filter/someFilter a syntax like "param/value" ``` This is done by `add_rewrite_endpoint()` and adding the filter to the `query_vars`. For now this thing is what I do but ultimately I'd really like to get it down to: ``` domain.tld/myplugin/someFilter ``` So help will still be much appreciated ;) Update 1st solution by @websupporter ==================================== Tried the approach given by a user here and it still doesn't work. I deactivated all plugins and it still doesn't work. The only thing that could interfere at this point as far as I know is the `.htaccess` but to me this one looks pretty standard as well.. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ```
This approach should work for you: ``` <?php /** * Plugin Name: Rewrite Shortcode **/ add_shortcode( 'myplugin', 'mp_shortcode' ); function mp_shortcode(){ return '<p>Filter: ' . get_query_var( 'filter' ) . '</p>'; } add_action( 'init', 'mp_rewrite' ); function mp_rewrite(){ $post_id = 2; add_rewrite_rule( 'myplugin/([^/]+)/?$', 'index.php?p=' . $post_id . '&filter=$matches[1]', 'top' ); add_rewrite_tag( '%filter%', '([^/]+)' ); } ?> ``` I developed it quickly as a small plugin, so I was able to test it myself. While you work with the global `$wp_rewrite` I thought it might be better to use the functions, which are documented in the Codex. Basically just, because I know them better :) So I can't exaktly tell, what you did wrong, but I can tell, what I do differently. You're approach: ``` "myplugin/([^/]+)/?" => "?p=2&filter=$matches[1] ``` I've explicitly told WordPress to use the *index.php* as it is also done in the documents. And I use `add_rewrite_tag()` to generate a new query variable, which I can read with `get_query_var()` in my shortcode. **Attention: Flush the Rules!** When you use these functions, you have to go to Settings > Permalinks and click the "update"-button. If you don't do this, the new rules won't be active. You could also use `flush_rewrite_rules()` during the activation of the plugin. An example on how to do this is given in the Codex. Docs: * <https://codex.wordpress.org/Rewrite_API/add_rewrite_rule> * <https://codex.wordpress.org/Rewrite_API/add_rewrite_tag> * <https://codex.wordpress.org/Function_Reference/flush_rewrite_rules>
183,455
<p>I created CPT called "Basics", then added the following code to functions.php</p> <pre><code>add_theme_support('post-thumbnails'); add_image_size('large_thumb', 900, 500, true); add_image_size('small_thumb', 250, 250, true); </code></pre> <p>Featured Image Option only appear default post type, and not appeared in CPT(Basics) </p>
[ { "answer_id": 183457, "author": "Bhavik Patel", "author_id": 26471, "author_profile": "https://wordpress.stackexchange.com/users/26471", "pm_score": 1, "selected": false, "text": "<p>Please Use this For custom post type after register_post_type </p>\n\n<p><code>add_theme_support( 'post-thumbnails', array( 'post', 'movie' ) );</code> // Posts and Movies</p>\n\n<p>OR </p>\n\n<pre><code>$args = array(\n 'labels' =&gt; 'Basics',\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'Basics' ),\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'Basics', $args );\n}\n</code></pre>\n\n<p>Full Code Here </p>\n\n<pre>\nfunction custom_theme_setup() {\nadd_theme_support( 'post-thumbnails' );\n}\nadd_action( 'after_setup_theme', 'custom_theme_setup' );\n\n\nadd_action( 'init', 'codex_basic_init' );\nfunction codex_basic_init() {\n $args = array(\n 'labels' => 'Basics',\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'basics' ),\n 'capability_type' => 'post',\n 'has_archive' => true,\n 'hierarchical' => false,\n 'menu_position' => null,\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'basics', $args );} \n</pre>\n" }, { "answer_id": 279668, "author": "Nikhil Gowda", "author_id": 127651, "author_profile": "https://wordpress.stackexchange.com/users/127651", "pm_score": 2, "selected": false, "text": "<p>use this code to create a custom post type, \nmainly you need to include this line: </p>\n\n<pre><code>'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', ), \n\"\n</code></pre>\n\n<p>full code to create:</p>\n\n<pre><code>// Register Custom Post Type\nfunction custom_post_type() {\n\n $labels = array(\n 'name' =&gt; _x( 'Post Types', 'Post Type General Name', 'text_domain' ),\n 'singular_name' =&gt; _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' =&gt; __( 'Post Types', 'text_domain' ),\n 'name_admin_bar' =&gt; __( 'Post Type', 'text_domain' ),\n 'archives' =&gt; __( 'Item Archives', 'text_domain' ),\n 'attributes' =&gt; __( 'Item Attributes', 'text_domain' ),\n 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ),\n 'all_items' =&gt; __( 'All Items', 'text_domain' ),\n 'add_new_item' =&gt; __( 'Add New Item', 'text_domain' ),\n 'add_new' =&gt; __( 'Add New', 'text_domain' ),\n 'new_item' =&gt; __( 'New Item', 'text_domain' ),\n 'edit_item' =&gt; __( 'Edit Item', 'text_domain' ),\n 'update_item' =&gt; __( 'Update Item', 'text_domain' ),\n 'view_item' =&gt; __( 'View Item', 'text_domain' ),\n 'view_items' =&gt; __( 'View Items', 'text_domain' ),\n 'search_items' =&gt; __( 'Search Item', 'text_domain' ),\n 'not_found' =&gt; __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ),\n 'featured_image' =&gt; __( 'Featured Image', 'text_domain' ),\n 'set_featured_image' =&gt; __( 'Set featured image', 'text_domain' ),\n 'remove_featured_image' =&gt; __( 'Remove featured image', 'text_domain' ),\n 'use_featured_image' =&gt; __( 'Use as featured image', 'text_domain' ),\n 'insert_into_item' =&gt; __( 'Insert into item', 'text_domain' ),\n 'uploaded_to_this_item' =&gt; __( 'Uploaded to this item', 'text_domain' ),\n 'items_list' =&gt; __( 'Items list', 'text_domain' ),\n 'items_list_navigation' =&gt; __( 'Items list navigation', 'text_domain' ),\n 'filter_items_list' =&gt; __( 'Filter items list', 'text_domain' ),\n );\n $args = array(\n 'label' =&gt; __( 'Post Type', 'text_domain' ),\n 'description' =&gt; __( 'Post Type Description', 'text_domain' ),\n 'labels' =&gt; $labels,\n 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', ),\n 'taxonomies' =&gt; array( 'category', 'post_tag' ),\n 'hierarchical' =&gt; false,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'menu_position' =&gt; 5,\n 'show_in_admin_bar' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'can_export' =&gt; true,\n 'has_archive' =&gt; true, \n 'exclude_from_search' =&gt; false,\n 'publicly_queryable' =&gt; true,\n 'capability_type' =&gt; 'page',\n );\n register_post_type( 'post_type', $args );\n\n}\nadd_action( 'init', 'custom_post_type', 0 );\n</code></pre>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64198/" ]
I created CPT called "Basics", then added the following code to functions.php ``` add_theme_support('post-thumbnails'); add_image_size('large_thumb', 900, 500, true); add_image_size('small_thumb', 250, 250, true); ``` Featured Image Option only appear default post type, and not appeared in CPT(Basics)
use this code to create a custom post type, mainly you need to include this line: ``` 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ), " ``` full code to create: ``` // Register Custom Post Type function custom_post_type() { $labels = array( 'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ), 'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ), 'menu_name' => __( 'Post Types', 'text_domain' ), 'name_admin_bar' => __( 'Post Type', 'text_domain' ), 'archives' => __( 'Item Archives', 'text_domain' ), 'attributes' => __( 'Item Attributes', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'add_new' => __( 'Add New', 'text_domain' ), 'new_item' => __( 'New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'view_item' => __( 'View Item', 'text_domain' ), 'view_items' => __( 'View Items', 'text_domain' ), 'search_items' => __( 'Search Item', 'text_domain' ), 'not_found' => __( 'Not found', 'text_domain' ), 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ), 'featured_image' => __( 'Featured Image', 'text_domain' ), 'set_featured_image' => __( 'Set featured image', 'text_domain' ), 'remove_featured_image' => __( 'Remove featured image', 'text_domain' ), 'use_featured_image' => __( 'Use as featured image', 'text_domain' ), 'insert_into_item' => __( 'Insert into item', 'text_domain' ), 'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ), 'items_list' => __( 'Items list', 'text_domain' ), 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ), 'filter_items_list' => __( 'Filter items list', 'text_domain' ), ); $args = array( 'label' => __( 'Post Type', 'text_domain' ), 'description' => __( 'Post Type Description', 'text_domain' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ), 'taxonomies' => array( 'category', 'post_tag' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'post_type', $args ); } add_action( 'init', 'custom_post_type', 0 ); ```
183,461
<p>I'm trying to send jQuery data via AJAX to a WordPress template file. I've tried several different techniques and solutions based on other questions posted that pertain to this topic, with no success. I can successfully pass data from the functions.php file to my promotions.php template file. </p> <p>However, I cannot get the data from my JavaScript file (ajax-javascript.js) file to the functions.php file. When the page loads, my $_POST variable is empty and my console.log message from my ajax-javascript.js file reads <strong>'Server response from the AJAX URL 0'</strong>. To me, a response code of '0' means there is something wrong with my wp_ajax hooks but I cannot figure out what. Is there something wrong with the hooks or is it something else that I'm over-looking? </p> <p>Here is my latest attempt:</p> <p><strong>ajax-javascript.js</strong></p> <pre><code>jQuery(document).ready(function($) { var numberOfPromos = 4; var data = { numberOfPromos: numberOfPromos }; $.post('/wp-admin/admin-ajax.php', data, function(response) { console.log('Server response from the AJAX URL ' + response); }); }); </code></pre> <p><strong>functions.php</strong></p> <pre><code>add_action( 'wp_enqueue_scripts', 'add_ajax_javascript_file' ); function add_ajax_javascript_file() { wp_localize_script( 'ajax_for_frontend', 'ajax_for_frontend', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'ajax_custom_script', get_stylesheet_directory_uri() . '/js/ajax-javascript.js', array('jquery') ); } add_action( 'wp_ajax_nopriv_get_number_of_promos', 'get_number_of_promos' ); add_action( 'wp_ajax_get_number_of_promos', 'get_number_of_promos' ); function get_number_of_promos() { echo $_POST['numberOfPromos']; die(); } </code></pre> <p><strong>promotions.php</strong> - where I call my function in my Wordpress template file</p> <pre><code>&lt;div&gt;&lt;?php echo $get_number_of_promos(); ?&gt;&lt;/div&gt; </code></pre>
[ { "answer_id": 183457, "author": "Bhavik Patel", "author_id": 26471, "author_profile": "https://wordpress.stackexchange.com/users/26471", "pm_score": 1, "selected": false, "text": "<p>Please Use this For custom post type after register_post_type </p>\n\n<p><code>add_theme_support( 'post-thumbnails', array( 'post', 'movie' ) );</code> // Posts and Movies</p>\n\n<p>OR </p>\n\n<pre><code>$args = array(\n 'labels' =&gt; 'Basics',\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'Basics' ),\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'Basics', $args );\n}\n</code></pre>\n\n<p>Full Code Here </p>\n\n<pre>\nfunction custom_theme_setup() {\nadd_theme_support( 'post-thumbnails' );\n}\nadd_action( 'after_setup_theme', 'custom_theme_setup' );\n\n\nadd_action( 'init', 'codex_basic_init' );\nfunction codex_basic_init() {\n $args = array(\n 'labels' => 'Basics',\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'basics' ),\n 'capability_type' => 'post',\n 'has_archive' => true,\n 'hierarchical' => false,\n 'menu_position' => null,\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'basics', $args );} \n</pre>\n" }, { "answer_id": 279668, "author": "Nikhil Gowda", "author_id": 127651, "author_profile": "https://wordpress.stackexchange.com/users/127651", "pm_score": 2, "selected": false, "text": "<p>use this code to create a custom post type, \nmainly you need to include this line: </p>\n\n<pre><code>'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', ), \n\"\n</code></pre>\n\n<p>full code to create:</p>\n\n<pre><code>// Register Custom Post Type\nfunction custom_post_type() {\n\n $labels = array(\n 'name' =&gt; _x( 'Post Types', 'Post Type General Name', 'text_domain' ),\n 'singular_name' =&gt; _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' =&gt; __( 'Post Types', 'text_domain' ),\n 'name_admin_bar' =&gt; __( 'Post Type', 'text_domain' ),\n 'archives' =&gt; __( 'Item Archives', 'text_domain' ),\n 'attributes' =&gt; __( 'Item Attributes', 'text_domain' ),\n 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ),\n 'all_items' =&gt; __( 'All Items', 'text_domain' ),\n 'add_new_item' =&gt; __( 'Add New Item', 'text_domain' ),\n 'add_new' =&gt; __( 'Add New', 'text_domain' ),\n 'new_item' =&gt; __( 'New Item', 'text_domain' ),\n 'edit_item' =&gt; __( 'Edit Item', 'text_domain' ),\n 'update_item' =&gt; __( 'Update Item', 'text_domain' ),\n 'view_item' =&gt; __( 'View Item', 'text_domain' ),\n 'view_items' =&gt; __( 'View Items', 'text_domain' ),\n 'search_items' =&gt; __( 'Search Item', 'text_domain' ),\n 'not_found' =&gt; __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ),\n 'featured_image' =&gt; __( 'Featured Image', 'text_domain' ),\n 'set_featured_image' =&gt; __( 'Set featured image', 'text_domain' ),\n 'remove_featured_image' =&gt; __( 'Remove featured image', 'text_domain' ),\n 'use_featured_image' =&gt; __( 'Use as featured image', 'text_domain' ),\n 'insert_into_item' =&gt; __( 'Insert into item', 'text_domain' ),\n 'uploaded_to_this_item' =&gt; __( 'Uploaded to this item', 'text_domain' ),\n 'items_list' =&gt; __( 'Items list', 'text_domain' ),\n 'items_list_navigation' =&gt; __( 'Items list navigation', 'text_domain' ),\n 'filter_items_list' =&gt; __( 'Filter items list', 'text_domain' ),\n );\n $args = array(\n 'label' =&gt; __( 'Post Type', 'text_domain' ),\n 'description' =&gt; __( 'Post Type Description', 'text_domain' ),\n 'labels' =&gt; $labels,\n 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', ),\n 'taxonomies' =&gt; array( 'category', 'post_tag' ),\n 'hierarchical' =&gt; false,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'menu_position' =&gt; 5,\n 'show_in_admin_bar' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'can_export' =&gt; true,\n 'has_archive' =&gt; true, \n 'exclude_from_search' =&gt; false,\n 'publicly_queryable' =&gt; true,\n 'capability_type' =&gt; 'page',\n );\n register_post_type( 'post_type', $args );\n\n}\nadd_action( 'init', 'custom_post_type', 0 );\n</code></pre>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183461", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70271/" ]
I'm trying to send jQuery data via AJAX to a WordPress template file. I've tried several different techniques and solutions based on other questions posted that pertain to this topic, with no success. I can successfully pass data from the functions.php file to my promotions.php template file. However, I cannot get the data from my JavaScript file (ajax-javascript.js) file to the functions.php file. When the page loads, my $\_POST variable is empty and my console.log message from my ajax-javascript.js file reads **'Server response from the AJAX URL 0'**. To me, a response code of '0' means there is something wrong with my wp\_ajax hooks but I cannot figure out what. Is there something wrong with the hooks or is it something else that I'm over-looking? Here is my latest attempt: **ajax-javascript.js** ``` jQuery(document).ready(function($) { var numberOfPromos = 4; var data = { numberOfPromos: numberOfPromos }; $.post('/wp-admin/admin-ajax.php', data, function(response) { console.log('Server response from the AJAX URL ' + response); }); }); ``` **functions.php** ``` add_action( 'wp_enqueue_scripts', 'add_ajax_javascript_file' ); function add_ajax_javascript_file() { wp_localize_script( 'ajax_for_frontend', 'ajax_for_frontend', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'ajax_custom_script', get_stylesheet_directory_uri() . '/js/ajax-javascript.js', array('jquery') ); } add_action( 'wp_ajax_nopriv_get_number_of_promos', 'get_number_of_promos' ); add_action( 'wp_ajax_get_number_of_promos', 'get_number_of_promos' ); function get_number_of_promos() { echo $_POST['numberOfPromos']; die(); } ``` **promotions.php** - where I call my function in my Wordpress template file ``` <div><?php echo $get_number_of_promos(); ?></div> ```
use this code to create a custom post type, mainly you need to include this line: ``` 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ), " ``` full code to create: ``` // Register Custom Post Type function custom_post_type() { $labels = array( 'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ), 'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ), 'menu_name' => __( 'Post Types', 'text_domain' ), 'name_admin_bar' => __( 'Post Type', 'text_domain' ), 'archives' => __( 'Item Archives', 'text_domain' ), 'attributes' => __( 'Item Attributes', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'add_new' => __( 'Add New', 'text_domain' ), 'new_item' => __( 'New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'view_item' => __( 'View Item', 'text_domain' ), 'view_items' => __( 'View Items', 'text_domain' ), 'search_items' => __( 'Search Item', 'text_domain' ), 'not_found' => __( 'Not found', 'text_domain' ), 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ), 'featured_image' => __( 'Featured Image', 'text_domain' ), 'set_featured_image' => __( 'Set featured image', 'text_domain' ), 'remove_featured_image' => __( 'Remove featured image', 'text_domain' ), 'use_featured_image' => __( 'Use as featured image', 'text_domain' ), 'insert_into_item' => __( 'Insert into item', 'text_domain' ), 'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ), 'items_list' => __( 'Items list', 'text_domain' ), 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ), 'filter_items_list' => __( 'Filter items list', 'text_domain' ), ); $args = array( 'label' => __( 'Post Type', 'text_domain' ), 'description' => __( 'Post Type Description', 'text_domain' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ), 'taxonomies' => array( 'category', 'post_tag' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'post_type', $args ); } add_action( 'init', 'custom_post_type', 0 ); ```
183,463
<p>As part of a much broader problem I'm trying to tackle, I am wondering if I can automatically create a taxonomy term with the same name as a new post of a specific CPT.</p> <p>The idea would be as follows. I'd have a cartoon-series CPT. When I create a new cartoon series post, a taxonomy term for the cartoon-series taxonomy would be created with the same name as this new post. Along with that top-level term, two sub-terms would be created: "Episodes" and "Special Features"</p> <p>So, for each new cartoon series post I create, I'd get a total of three terms added. One with the same name as the post and two under that, that would always be the same for all cartoon series.</p> <p>A few potential problems I foresee right away:<br> Can I have terms in a taxonomy that are exactly the same? Like Episodes appearing multiple times as sub-terms.<br> Can a taxonomy have the same name as a CPT? Ideally, both would be named cartoon-series. The slugs for the sub-terms would need to be the same as I'd be displaying them in the url. </p> <pre><code>GOOD domain/cartoon-series/&lt;series-name1&gt;/episodes/&lt;episode-name&gt; GOOD domain/cartoon-series/&lt;series-name2&gt;/episodes/&lt;episode-name&gt; BAD domain/cartoon-series/&lt;series-name2&gt;/episodes-1/&lt;episode-name&gt; </code></pre> <p>"episodes" would need to be the same slug even though they are not the same term. I'm not sure if this is possible even if they are under different top-level terms.</p> <p>All of this is in effort to solve this problem: <a href="https://wordpress.stackexchange.com/questions/183415/need-help-with-complex-custom-post-type-setup">Need help with complex custom post type setup</a></p> <p>I'm all ears if you have any other ideas!</p> <p>Thanks! Matt</p>
[ { "answer_id": 183457, "author": "Bhavik Patel", "author_id": 26471, "author_profile": "https://wordpress.stackexchange.com/users/26471", "pm_score": 1, "selected": false, "text": "<p>Please Use this For custom post type after register_post_type </p>\n\n<p><code>add_theme_support( 'post-thumbnails', array( 'post', 'movie' ) );</code> // Posts and Movies</p>\n\n<p>OR </p>\n\n<pre><code>$args = array(\n 'labels' =&gt; 'Basics',\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'Basics' ),\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'Basics', $args );\n}\n</code></pre>\n\n<p>Full Code Here </p>\n\n<pre>\nfunction custom_theme_setup() {\nadd_theme_support( 'post-thumbnails' );\n}\nadd_action( 'after_setup_theme', 'custom_theme_setup' );\n\n\nadd_action( 'init', 'codex_basic_init' );\nfunction codex_basic_init() {\n $args = array(\n 'labels' => 'Basics',\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'basics' ),\n 'capability_type' => 'post',\n 'has_archive' => true,\n 'hierarchical' => false,\n 'menu_position' => null,\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'basics', $args );} \n</pre>\n" }, { "answer_id": 279668, "author": "Nikhil Gowda", "author_id": 127651, "author_profile": "https://wordpress.stackexchange.com/users/127651", "pm_score": 2, "selected": false, "text": "<p>use this code to create a custom post type, \nmainly you need to include this line: </p>\n\n<pre><code>'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', ), \n\"\n</code></pre>\n\n<p>full code to create:</p>\n\n<pre><code>// Register Custom Post Type\nfunction custom_post_type() {\n\n $labels = array(\n 'name' =&gt; _x( 'Post Types', 'Post Type General Name', 'text_domain' ),\n 'singular_name' =&gt; _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' =&gt; __( 'Post Types', 'text_domain' ),\n 'name_admin_bar' =&gt; __( 'Post Type', 'text_domain' ),\n 'archives' =&gt; __( 'Item Archives', 'text_domain' ),\n 'attributes' =&gt; __( 'Item Attributes', 'text_domain' ),\n 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ),\n 'all_items' =&gt; __( 'All Items', 'text_domain' ),\n 'add_new_item' =&gt; __( 'Add New Item', 'text_domain' ),\n 'add_new' =&gt; __( 'Add New', 'text_domain' ),\n 'new_item' =&gt; __( 'New Item', 'text_domain' ),\n 'edit_item' =&gt; __( 'Edit Item', 'text_domain' ),\n 'update_item' =&gt; __( 'Update Item', 'text_domain' ),\n 'view_item' =&gt; __( 'View Item', 'text_domain' ),\n 'view_items' =&gt; __( 'View Items', 'text_domain' ),\n 'search_items' =&gt; __( 'Search Item', 'text_domain' ),\n 'not_found' =&gt; __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ),\n 'featured_image' =&gt; __( 'Featured Image', 'text_domain' ),\n 'set_featured_image' =&gt; __( 'Set featured image', 'text_domain' ),\n 'remove_featured_image' =&gt; __( 'Remove featured image', 'text_domain' ),\n 'use_featured_image' =&gt; __( 'Use as featured image', 'text_domain' ),\n 'insert_into_item' =&gt; __( 'Insert into item', 'text_domain' ),\n 'uploaded_to_this_item' =&gt; __( 'Uploaded to this item', 'text_domain' ),\n 'items_list' =&gt; __( 'Items list', 'text_domain' ),\n 'items_list_navigation' =&gt; __( 'Items list navigation', 'text_domain' ),\n 'filter_items_list' =&gt; __( 'Filter items list', 'text_domain' ),\n );\n $args = array(\n 'label' =&gt; __( 'Post Type', 'text_domain' ),\n 'description' =&gt; __( 'Post Type Description', 'text_domain' ),\n 'labels' =&gt; $labels,\n 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', ),\n 'taxonomies' =&gt; array( 'category', 'post_tag' ),\n 'hierarchical' =&gt; false,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'menu_position' =&gt; 5,\n 'show_in_admin_bar' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'can_export' =&gt; true,\n 'has_archive' =&gt; true, \n 'exclude_from_search' =&gt; false,\n 'publicly_queryable' =&gt; true,\n 'capability_type' =&gt; 'page',\n );\n register_post_type( 'post_type', $args );\n\n}\nadd_action( 'init', 'custom_post_type', 0 );\n</code></pre>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183463", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68905/" ]
As part of a much broader problem I'm trying to tackle, I am wondering if I can automatically create a taxonomy term with the same name as a new post of a specific CPT. The idea would be as follows. I'd have a cartoon-series CPT. When I create a new cartoon series post, a taxonomy term for the cartoon-series taxonomy would be created with the same name as this new post. Along with that top-level term, two sub-terms would be created: "Episodes" and "Special Features" So, for each new cartoon series post I create, I'd get a total of three terms added. One with the same name as the post and two under that, that would always be the same for all cartoon series. A few potential problems I foresee right away: Can I have terms in a taxonomy that are exactly the same? Like Episodes appearing multiple times as sub-terms. Can a taxonomy have the same name as a CPT? Ideally, both would be named cartoon-series. The slugs for the sub-terms would need to be the same as I'd be displaying them in the url. ``` GOOD domain/cartoon-series/<series-name1>/episodes/<episode-name> GOOD domain/cartoon-series/<series-name2>/episodes/<episode-name> BAD domain/cartoon-series/<series-name2>/episodes-1/<episode-name> ``` "episodes" would need to be the same slug even though they are not the same term. I'm not sure if this is possible even if they are under different top-level terms. All of this is in effort to solve this problem: [Need help with complex custom post type setup](https://wordpress.stackexchange.com/questions/183415/need-help-with-complex-custom-post-type-setup) I'm all ears if you have any other ideas! Thanks! Matt
use this code to create a custom post type, mainly you need to include this line: ``` 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ), " ``` full code to create: ``` // Register Custom Post Type function custom_post_type() { $labels = array( 'name' => _x( 'Post Types', 'Post Type General Name', 'text_domain' ), 'singular_name' => _x( 'Post Type', 'Post Type Singular Name', 'text_domain' ), 'menu_name' => __( 'Post Types', 'text_domain' ), 'name_admin_bar' => __( 'Post Type', 'text_domain' ), 'archives' => __( 'Item Archives', 'text_domain' ), 'attributes' => __( 'Item Attributes', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'add_new' => __( 'Add New', 'text_domain' ), 'new_item' => __( 'New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'view_item' => __( 'View Item', 'text_domain' ), 'view_items' => __( 'View Items', 'text_domain' ), 'search_items' => __( 'Search Item', 'text_domain' ), 'not_found' => __( 'Not found', 'text_domain' ), 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ), 'featured_image' => __( 'Featured Image', 'text_domain' ), 'set_featured_image' => __( 'Set featured image', 'text_domain' ), 'remove_featured_image' => __( 'Remove featured image', 'text_domain' ), 'use_featured_image' => __( 'Use as featured image', 'text_domain' ), 'insert_into_item' => __( 'Insert into item', 'text_domain' ), 'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ), 'items_list' => __( 'Items list', 'text_domain' ), 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ), 'filter_items_list' => __( 'Filter items list', 'text_domain' ), ); $args = array( 'label' => __( 'Post Type', 'text_domain' ), 'description' => __( 'Post Type Description', 'text_domain' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', ), 'taxonomies' => array( 'category', 'post_tag' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', ); register_post_type( 'post_type', $args ); } add_action( 'init', 'custom_post_type', 0 ); ```
183,475
<p>In my little age with WordPress, I've seen WordPress itself and its friendly plugins are using PHP <code>serialize()</code> in storing data into db in many cases. But in a recent search I found a serious community support for the <code>json_encode()</code> over the <code>serialize()</code>.</p> <ul> <li><a href="https://stackoverflow.com/a/804089/1743124">A test that proves <code>json_encode()</code> is better than <code>serialize()</code> - StackOverflow</a></li> <li><a href="https://stackoverflow.com/a/804053/1743124">Reasons why <code>json_encode()</code> can be used and why not - StackOverflow</a></li> </ul> <p>And I personally tested an associative array with both of 'em, that shows:</p> <ul> <li><code>serialize()</code> stores 342 chars</li> <li><code>json_encode()</code> stores 285 chars</li> </ul> <h3>Why I'm asking this?</h3> <p>I'm on a project while I'm going to store repeating meta fields to a post. Where:</p> <ul> <li>Data would be basically in English, but sometimes can be Bengali</li> <li>Data would be associative array, 3 level deep (I hope I understood <em>levels</em> correctly):</li> </ul> <pre><code>array( 1 =&gt; array( 'key'=&gt;'value', 'key2'=&gt;'value' ), 2 =&gt; array( 'key'=&gt;'value', 'key2'=&gt;'value' ) ) </code></pre> <p>I've checked the <code>postmeta</code> table's <code>meta_value</code> field it's a <code>longtext</code>, <a href="https://stackoverflow.com/a/4294527/1743124">that means</a> a length of 4,294,967,295 chars (4GB).</p> <p>So I need a robust solution into storing things.</p>
[ { "answer_id": 183478, "author": "Ramy Deeb", "author_id": 15117, "author_profile": "https://wordpress.stackexchange.com/users/15117", "pm_score": 5, "selected": true, "text": "<p>I think, not 100% sure that this was the real reason the WP developers took this approach, but common sense tells me that serialize preserves the variable types and have a mini built in error detection, and json stores only string values <code>{ key : value }</code>, so when you go back to PHP you will have to guess the format, or make a parser for it. This will force you to have two different ways to handle your data: previous, to storing the data as json and after decoding the json it will come back as a totally different object.</p>\n\n<p>This is the main reason the difference in size, PHP is storing not only an array; it is storing how many elements were in the array when it was serialized, their types, and their values.</p>\n\n<p>You are not storing only key value pairs on the database but you may also be storing an object with different variable types.</p>\n" }, { "answer_id": 183480, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>I am tempted to close this as \"subject to opinion\" but I think there are a couple of good answers to the question. I am going to go with \"history\".</p>\n\n<p>1) <code>json_encode</code> is relatively new in PHP core.</p>\n\n<blockquote>\n <p>json_encode</p>\n \n <p>(PHP 5 >= 5.2.0, PECL json >= 1.2.0) json_encode — Returns the JSON\n representation of a value</p>\n \n <p><a href=\"http://php.net/manual/en/function.json-encode.php\" rel=\"nofollow\">http://php.net/manual/en/function.json-encode.php</a></p>\n</blockquote>\n\n<p><code>json_encode</code> would not have been reliable in WordPress' early days. It was only rolled into \"core\" PHP in 5.2, though it was available as a PECL extension long before that.</p>\n\n<p>Second, if you feed an object such as a <code>WP_Query</code> object into <code>json_encode</code> you get a <code>stdClass</code> object on <code>json_decode</code>. <code>serialize</code>/<code>unserialize</code> will preserve the object.</p>\n" }, { "answer_id": 183482, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>JSON encoding was introduced in PHP 5.2, WordPress is way older, and it was born (and designed for) PHP 4.</p>\n\n<p>Data serialization is a pervasive thing in WordPress, so moving from PHP serialization to JSON encoding would mean a huge backward compatibility problem, and if I know WordPress a little, that will never happen.</p>\n\n<p>That said, if you think that JSON encoding is better for you than PHP serialization, just use it.</p>\n\n<p>If you pass a string (that is the JSON-encoded version of your data) to post meta functions WordPress will not touch it, but then you need to remember to JSON-decode data on retrieval.</p>\n\n<p>If DB storage size is very important for you, that it probably worth the additional work, otherwise just let WordPress use what it uses and don't care about it.</p>\n\n<p>Maybe, you can evaluate if it is the case of custom tables to save your data.</p>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183475", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
In my little age with WordPress, I've seen WordPress itself and its friendly plugins are using PHP `serialize()` in storing data into db in many cases. But in a recent search I found a serious community support for the `json_encode()` over the `serialize()`. * [A test that proves `json_encode()` is better than `serialize()` - StackOverflow](https://stackoverflow.com/a/804089/1743124) * [Reasons why `json_encode()` can be used and why not - StackOverflow](https://stackoverflow.com/a/804053/1743124) And I personally tested an associative array with both of 'em, that shows: * `serialize()` stores 342 chars * `json_encode()` stores 285 chars ### Why I'm asking this? I'm on a project while I'm going to store repeating meta fields to a post. Where: * Data would be basically in English, but sometimes can be Bengali * Data would be associative array, 3 level deep (I hope I understood *levels* correctly): ``` array( 1 => array( 'key'=>'value', 'key2'=>'value' ), 2 => array( 'key'=>'value', 'key2'=>'value' ) ) ``` I've checked the `postmeta` table's `meta_value` field it's a `longtext`, [that means](https://stackoverflow.com/a/4294527/1743124) a length of 4,294,967,295 chars (4GB). So I need a robust solution into storing things.
I think, not 100% sure that this was the real reason the WP developers took this approach, but common sense tells me that serialize preserves the variable types and have a mini built in error detection, and json stores only string values `{ key : value }`, so when you go back to PHP you will have to guess the format, or make a parser for it. This will force you to have two different ways to handle your data: previous, to storing the data as json and after decoding the json it will come back as a totally different object. This is the main reason the difference in size, PHP is storing not only an array; it is storing how many elements were in the array when it was serialized, their types, and their values. You are not storing only key value pairs on the database but you may also be storing an object with different variable types.
183,489
<p>On a blog, i'm using the following to display the post authors avatars:</p> <pre><code>&lt;a href="&lt;?php echo get_author_posts_url(get_the_author_meta( 'ID' )); ?&gt;" style="color:#ffffff;"&gt;&lt;?php echo get_avatar( get_the_author_meta( 'ID' )); ?&gt;&lt;/a&gt; </code></pre> <p>But some posts have more than one author, and this only displays one avatar, how can I get this to display both authors avatars?</p> <p>Thanks</p>
[ { "answer_id": 183491, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 0, "selected": false, "text": "<p>The obvious answer is to use <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow\"><code>get_avatar()</code></a> twice using different author IDs. As you must be aware given your code above (assuming that is your code and not code cribbed from elsewhere), the first parameter of that function accepts an author ID or the associated author email address. </p>\n\n<p>However, you don't explain how you have associated multiple authors to the post so an answer beyond the rather trivial answer just given is not possible. If you can expand the question, I can expand the answer.</p>\n" }, { "answer_id": 183495, "author": "Adrian", "author_id": 34820, "author_profile": "https://wordpress.stackexchange.com/users/34820", "pm_score": 2, "selected": true, "text": "<p>Here we go, found a nice thread which gave some answers and developed this which works a treat:</p>\n\n<pre><code>if ( class_exists( 'coauthors_plus' ) ) {\n $co_authors = get_coauthors();\n foreach ( $co_authors as $key =&gt; $co_author ) {\n $co_author_classes = array(\n 'co-author-wrap',\n 'co-author-number-' . ( $key + 1 ),\n );\n echo '&lt;div class=\"' . implode( ' ', $co_author_classes ) . '\"&gt;&lt;a href=\"' . get_author_posts_url($co_author-&gt;ID) . '\" style=\"color:#ffffff;\"&gt;';\n echo userphoto_thumbnail( $co_author );\n echo '&lt;/a&gt;&lt;/div&gt;';\n }\n} \n</code></pre>\n" }, { "answer_id": 412298, "author": "user1062954", "author_id": 227725, "author_profile": "https://wordpress.stackexchange.com/users/227725", "pm_score": 0, "selected": false, "text": "<p>Use</p>\n<pre class=\"lang-php prettyprint-override\"><code>coauthors_get_avatar( $coauthor, $width, null, null, array('class' =&gt; 'rounded-full'))\n</code></pre>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183489", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34820/" ]
On a blog, i'm using the following to display the post authors avatars: ``` <a href="<?php echo get_author_posts_url(get_the_author_meta( 'ID' )); ?>" style="color:#ffffff;"><?php echo get_avatar( get_the_author_meta( 'ID' )); ?></a> ``` But some posts have more than one author, and this only displays one avatar, how can I get this to display both authors avatars? Thanks
Here we go, found a nice thread which gave some answers and developed this which works a treat: ``` if ( class_exists( 'coauthors_plus' ) ) { $co_authors = get_coauthors(); foreach ( $co_authors as $key => $co_author ) { $co_author_classes = array( 'co-author-wrap', 'co-author-number-' . ( $key + 1 ), ); echo '<div class="' . implode( ' ', $co_author_classes ) . '"><a href="' . get_author_posts_url($co_author->ID) . '" style="color:#ffffff;">'; echo userphoto_thumbnail( $co_author ); echo '</a></div>'; } } ```
183,502
<p>I'm trying to allow "author" users to embed in posts. I (the administrator) can iframe, embed, etc...., but authors can not. </p> <p>Can someone show me to give authors 'just' the ability to embed and iframe in posts?</p>
[ { "answer_id": 183504, "author": "Olivier", "author_id": 23275, "author_profile": "https://wordpress.stackexchange.com/users/23275", "pm_score": 4, "selected": true, "text": "<p>The capability you are after is called <code>unfiltered_html</code>. Some options:</p>\n\n<ol>\n<li><p>Modify <strong>author</strong> capabilities in your theme <code>functions.php</code>. This is saved in the DB, so you can access a page, make sure it works then remove it from your <code>functions.php</code> file. A better option would be to run it on theme activation. See <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"noreferrer\">this page on WP Codex</a> for options: </p>\n\n<pre><code>function add_theme_caps() {\n // gets the author role\n $role = get_role( 'author' );\n\n // This only works, because it accesses the class instance.\n // would allow the author to edit others' posts for current theme only\n $role-&gt;add_cap( 'unfiltered_html' ); \n}\nadd_action( 'admin_init', 'add_theme_caps');\n</code></pre></li>\n<li><p>Use a plugin that allows you to modify it using a UI, like <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"noreferrer\">User Role Editor</a>.</p></li>\n</ol>\n" }, { "answer_id": 183535, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>This is a bad idea and you might as well just give those users \"higher\" roles as with the \"unfiltered_html\" permission it is not very hard to duplicate the admin authorization cookies and take control of the site.</p>\n\n<p>What you should do is to teach them to use the built-in functionality of <a href=\"https://codex.wordpress.org/Embeds\" rel=\"nofollow\">oEmbed</a>, which should be enough to embed content from many sites in a simple way, by just putting the url of the content on a line of its own, but if that is not good enough, then you need to write shortcodes that will do the actual embed into the content.</p>\n" } ]
2015/04/07
[ "https://wordpress.stackexchange.com/questions/183502", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64181/" ]
I'm trying to allow "author" users to embed in posts. I (the administrator) can iframe, embed, etc...., but authors can not. Can someone show me to give authors 'just' the ability to embed and iframe in posts?
The capability you are after is called `unfiltered_html`. Some options: 1. Modify **author** capabilities in your theme `functions.php`. This is saved in the DB, so you can access a page, make sure it works then remove it from your `functions.php` file. A better option would be to run it on theme activation. See [this page on WP Codex](https://codex.wordpress.org/Function_Reference/add_cap) for options: ``` function add_theme_caps() { // gets the author role $role = get_role( 'author' ); // This only works, because it accesses the class instance. // would allow the author to edit others' posts for current theme only $role->add_cap( 'unfiltered_html' ); } add_action( 'admin_init', 'add_theme_caps'); ``` 2. Use a plugin that allows you to modify it using a UI, like [User Role Editor](https://wordpress.org/plugins/user-role-editor/).
183,517
<p>I'm just looking to make sure my home page and pages display my featured image if set, and other wise if not set show blog-banner.jpg. So that's what I thought I had however now my 404 error page doesn't have a banner image. Any advice on correcting this if statement?</p> <pre><code>/** Add the featured image section */ add_action( 'genesis_before_header', 'minimum_featured_image' ); function minimum_featured_image() { global $post; $post-&gt;ID; if ( is_home() ) { echo '&lt;div id="featured-image-home"&gt;'; echo get_the_post_thumbnail($thumbnail-&gt;ID, 'header'); echo '&lt;/div&gt;'; } if ( is_singular( array( 'post' ) ) &amp;&amp; ( !has_post_thumbnail( $post-&gt;ID ) ) ){ echo '&lt;div id="featured-image-home"&gt;&lt;img src="'. get_stylesheet_directory_uri() . '/images/blog-banner.jpg" /&gt;&lt;/div&gt;'; return; } if ( is_singular( array( 'post', 'page' ) ) &amp;&amp; has_post_thumbnail( $post-&gt;ID ) ){ echo '&lt;div id="featured-image"&gt;'; echo get_the_post_thumbnail($thumbnail-&gt;ID, 'header'); echo '&lt;/div&gt;'; } } </code></pre>
[ { "answer_id": 183504, "author": "Olivier", "author_id": 23275, "author_profile": "https://wordpress.stackexchange.com/users/23275", "pm_score": 4, "selected": true, "text": "<p>The capability you are after is called <code>unfiltered_html</code>. Some options:</p>\n\n<ol>\n<li><p>Modify <strong>author</strong> capabilities in your theme <code>functions.php</code>. This is saved in the DB, so you can access a page, make sure it works then remove it from your <code>functions.php</code> file. A better option would be to run it on theme activation. See <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"noreferrer\">this page on WP Codex</a> for options: </p>\n\n<pre><code>function add_theme_caps() {\n // gets the author role\n $role = get_role( 'author' );\n\n // This only works, because it accesses the class instance.\n // would allow the author to edit others' posts for current theme only\n $role-&gt;add_cap( 'unfiltered_html' ); \n}\nadd_action( 'admin_init', 'add_theme_caps');\n</code></pre></li>\n<li><p>Use a plugin that allows you to modify it using a UI, like <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"noreferrer\">User Role Editor</a>.</p></li>\n</ol>\n" }, { "answer_id": 183535, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>This is a bad idea and you might as well just give those users \"higher\" roles as with the \"unfiltered_html\" permission it is not very hard to duplicate the admin authorization cookies and take control of the site.</p>\n\n<p>What you should do is to teach them to use the built-in functionality of <a href=\"https://codex.wordpress.org/Embeds\" rel=\"nofollow\">oEmbed</a>, which should be enough to embed content from many sites in a simple way, by just putting the url of the content on a line of its own, but if that is not good enough, then you need to write shortcodes that will do the actual embed into the content.</p>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25108/" ]
I'm just looking to make sure my home page and pages display my featured image if set, and other wise if not set show blog-banner.jpg. So that's what I thought I had however now my 404 error page doesn't have a banner image. Any advice on correcting this if statement? ``` /** Add the featured image section */ add_action( 'genesis_before_header', 'minimum_featured_image' ); function minimum_featured_image() { global $post; $post->ID; if ( is_home() ) { echo '<div id="featured-image-home">'; echo get_the_post_thumbnail($thumbnail->ID, 'header'); echo '</div>'; } if ( is_singular( array( 'post' ) ) && ( !has_post_thumbnail( $post->ID ) ) ){ echo '<div id="featured-image-home"><img src="'. get_stylesheet_directory_uri() . '/images/blog-banner.jpg" /></div>'; return; } if ( is_singular( array( 'post', 'page' ) ) && has_post_thumbnail( $post->ID ) ){ echo '<div id="featured-image">'; echo get_the_post_thumbnail($thumbnail->ID, 'header'); echo '</div>'; } } ```
The capability you are after is called `unfiltered_html`. Some options: 1. Modify **author** capabilities in your theme `functions.php`. This is saved in the DB, so you can access a page, make sure it works then remove it from your `functions.php` file. A better option would be to run it on theme activation. See [this page on WP Codex](https://codex.wordpress.org/Function_Reference/add_cap) for options: ``` function add_theme_caps() { // gets the author role $role = get_role( 'author' ); // This only works, because it accesses the class instance. // would allow the author to edit others' posts for current theme only $role->add_cap( 'unfiltered_html' ); } add_action( 'admin_init', 'add_theme_caps'); ``` 2. Use a plugin that allows you to modify it using a UI, like [User Role Editor](https://wordpress.org/plugins/user-role-editor/).
183,520
<p>I have a question today. I am looking for a solution to make sticky post available on my website. But, i just got it work on homepage with the code below.</p> <pre><code>function wpb_latest_sticky() { /* Get all sticky posts */ $sticky = get_option( 'sticky_posts' ); /* Sort the stickies with the newest ones at the top */ rsort( $sticky ); /* Get the 5 newest stickies (change 5 for a different number) */ $sticky = array_slice( $sticky, 0, 5 ); /* Query sticky posts */ $the_query = new WP_Query( array( 'post__in' =&gt; $sticky, 'ignore_sticky_posts' =&gt; 1 ) ); // The Loop if ( $the_query-&gt;have_posts() ) { $return .= '&lt;ul&gt;'; while ( $the_query-&gt;have_posts() ) { $the_query-&gt;the_post(); $return .= '&lt;li&gt;&lt;a href="' .get_permalink(). '" title="' . get_the_title() . '"&gt;' . get_the_title() . '&lt;/a&gt;&lt;br /&gt;' . get_the_excerpt(). '&lt;/li&gt;'; } $return .= '&lt;/ul&gt;'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); return $return; } add_shortcode('latest_stickies', 'wpb_latest_sticky'); </code></pre> <p>I was thinking to make the sticky post to be displayed on search, tag, and category as well. </p> <p>Any solution? Thanks! </p>
[ { "answer_id": 183620, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>This same exact question was asked earlier this week or over the weekend, and it had me thinking. Here is the idea that I came up with.</p>\n\n<p>If you look at the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/query.php#L3580\" rel=\"nofollow\">source code</a> of the <code>WP_Query</code> class, you will see that sticky posts is only added to the first page of the home page. There is also no filter supplied to change this behavior in order to set the required templates according to your liking. </p>\n\n<p>There are many ways to display sticky posts on other templates through widgets, custom queries, shortcodes (which I will not recommend due to the fact that using <code>do_shortcode()</code> is slower that using the function itself) or custom functions where you need to display them. I have opted to go with using <code>the_posts</code> filter and <code>pre_get_posts</code> action. </p>\n\n<h2>HERE'S HOW:</h2>\n\n<ul>\n<li><p>Get the post ID's saved as sticky posts with <code>get_option( 'sticky_posts' )</code></p></li>\n<li><p>Remove this posts from the main query with <code>pre_get_posts</code>. As stickies are included on the home page, we will exclude the home page. We will also exclude normal pages</p></li>\n<li><p>Inside a custom function, run a custom query with <code>get_posts</code> to get the posts set as sticky posts. </p></li>\n<li><p>Merge the returned array of sticky posts with the current returned posts of the main query with <code>array_merge</code></p></li>\n<li><p>Hook this custom function to <code>the_posts</code> filter</p></li>\n</ul>\n\n<p>Here is the code: (<em>Requires PHP 5.4+</em>)</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin()\n &amp;&amp; $q-&gt;is_main_query()\n &amp;&amp; !$q-&gt;is_home()\n &amp;&amp; !$q-&gt;is_page()\n ) {\n\n $q-&gt;set( 'post__not_in', get_option( 'sticky_posts' ) );\n\n if ( !$q-&gt;is_paged() ) {\n add_filter( 'the_posts', function ( $posts )\n {\n $stickies = get_posts( ['post__in' =&gt; get_option( 'sticky_posts' ), 'nopaging' =&gt; true] );\n\n $posts = array_merge( $stickies, $posts );\n\n return $posts;\n\n }, 10, 2);\n }\n\n }\n});\n</code></pre>\n" }, { "answer_id": 228180, "author": "mll", "author_id": 94898, "author_profile": "https://wordpress.stackexchange.com/users/94898", "pm_score": 2, "selected": false, "text": "<p>Pieter's answer does work, but it displays <em>all</em> sticky posts even on pages when we want to display filtered posts (to a given category for instance).</p>\n\n<p>The following works for me. Adding this to functions.php only displays stickies within the subset of filtered posts :</p>\n\n<pre><code>add_filter('the_posts', 'bump_sticky_posts_to_top');\nfunction bump_sticky_posts_to_top($posts) {\n $stickies = array();\n foreach($posts as $i =&gt; $post) {\n if(is_sticky($post-&gt;ID)) {\n $stickies[] = $post;\n unset($posts[$i]);\n }\n }\n return array_merge($stickies, $posts);\n</code></pre>\n\n<p>(Credits : <a href=\"http://pastebin.com/Y5jVrKg4\" rel=\"nofollow\">http://pastebin.com/Y5jVrKg4</a>, with a slight change to prevent a <em>Warning: array_merge() [function.array-merge]: Argument #1 is not an array on line 9</em> error)</p>\n\n<p>However, there is a big flaw. It will not promote a sticky post on top if this sticky post in not to be present in the current page.</p>\n\n<p>A system that would set the .sticky CSS class to the sticky posts would also be nice.</p>\n" }, { "answer_id": 233242, "author": "RedNails", "author_id": 78129, "author_profile": "https://wordpress.stackexchange.com/users/78129", "pm_score": 1, "selected": false, "text": "<p>I needed some modifications(original see Pieters answer) to get it to work just on category pages. This solution will display all sticky posts of the current category (and child categories), but not on search, tag and single pages:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q ) {\n if ( !is_admin()\n &amp;&amp; $q-&gt;is_main_query()\n &amp;&amp; !$q-&gt;is_home()\n &amp;&amp; !$q-&gt;is_tag()\n &amp;&amp; !$q-&gt;is_search()\n &amp;&amp; !$q-&gt;is_page()\n &amp;&amp; !$q-&gt;is_single()\n ) {\n\n function is_existing_cat($q_catName) {\n $existingCats = get_categories();\n $isExistingCat = false;\n\n foreach ($existingCats as $cat) {\n if ($cat-&gt;name == $q_catName) {\n $isExistingCat = true;\n }\n }\n\n return $isExistingCat;\n }\n\n if ($q-&gt;is_category() &amp;&amp; !$q-&gt;is_paged() &amp;&amp; is_existing_cat($q-&gt;query['category_name'])) {\n\n $q-&gt;set( 'post__not_in', get_option( 'sticky_posts' ) );\n\n add_filter( 'the_posts', function ( $posts ) {\n $catName = get_category(get_query_var('cat'))-&gt;name;\n $catID = get_cat_ID($catName);\n\n if ( !empty(get_option( 'sticky_posts' )) ) {\n $stickies = get_posts( [\n 'category' =&gt; $catID,\n 'post__in' =&gt; get_option( 'sticky_posts' )\n ] );\n\n $posts = array_merge( $stickies, $posts );\n }\n\n return $posts;\n\n }, 10, 2);\n }\n }\n});\n</code></pre>\n\n<p>I added a function to check if the category is an existing category because I run into the issue that I was directed to the category.php instead of the expected 404.php.\nLinks like <code>/existing-cat/not-existing-post</code> worked but links like <code>/not-existing-post-or-page-or-cat</code> didn't.</p>\n\n<p>If you need a css class on that post you add this code to the PHP part of the template that displays the content of the post (in twentysixteen for example: template-parts/content.php)</p>\n\n<pre><code>&lt;?php\nif (is_sticky()) {\n $stickyClass = 'sticky';\n} else {\n $stickyClass = '';\n}\n?&gt;\n</code></pre>\n\n<p>Than you add this class to the css classes of the post <code>post_class($stickyClass);</code> (this function will add the class attribute to the HTML element with a few classes and your added class). You may find this function already located at the article:</p>\n\n<pre><code>&lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class($stickyClass); ?&gt;&gt;\n ...\n&lt;/article&gt;&lt;!-- #post-## --&gt;\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23036/" ]
I have a question today. I am looking for a solution to make sticky post available on my website. But, i just got it work on homepage with the code below. ``` function wpb_latest_sticky() { /* Get all sticky posts */ $sticky = get_option( 'sticky_posts' ); /* Sort the stickies with the newest ones at the top */ rsort( $sticky ); /* Get the 5 newest stickies (change 5 for a different number) */ $sticky = array_slice( $sticky, 0, 5 ); /* Query sticky posts */ $the_query = new WP_Query( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) ); // The Loop if ( $the_query->have_posts() ) { $return .= '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); $return .= '<li><a href="' .get_permalink(). '" title="' . get_the_title() . '">' . get_the_title() . '</a><br />' . get_the_excerpt(). '</li>'; } $return .= '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); return $return; } add_shortcode('latest_stickies', 'wpb_latest_sticky'); ``` I was thinking to make the sticky post to be displayed on search, tag, and category as well. Any solution? Thanks!
This same exact question was asked earlier this week or over the weekend, and it had me thinking. Here is the idea that I came up with. If you look at the [source code](https://github.com/WordPress/WordPress/blob/master/wp-includes/query.php#L3580) of the `WP_Query` class, you will see that sticky posts is only added to the first page of the home page. There is also no filter supplied to change this behavior in order to set the required templates according to your liking. There are many ways to display sticky posts on other templates through widgets, custom queries, shortcodes (which I will not recommend due to the fact that using `do_shortcode()` is slower that using the function itself) or custom functions where you need to display them. I have opted to go with using `the_posts` filter and `pre_get_posts` action. HERE'S HOW: ----------- * Get the post ID's saved as sticky posts with `get_option( 'sticky_posts' )` * Remove this posts from the main query with `pre_get_posts`. As stickies are included on the home page, we will exclude the home page. We will also exclude normal pages * Inside a custom function, run a custom query with `get_posts` to get the posts set as sticky posts. * Merge the returned array of sticky posts with the current returned posts of the main query with `array_merge` * Hook this custom function to `the_posts` filter Here is the code: (*Requires PHP 5.4+*) ``` add_action( 'pre_get_posts', function ( $q ) { if ( !is_admin() && $q->is_main_query() && !$q->is_home() && !$q->is_page() ) { $q->set( 'post__not_in', get_option( 'sticky_posts' ) ); if ( !$q->is_paged() ) { add_filter( 'the_posts', function ( $posts ) { $stickies = get_posts( ['post__in' => get_option( 'sticky_posts' ), 'nopaging' => true] ); $posts = array_merge( $stickies, $posts ); return $posts; }, 10, 2); } } }); ```
183,548
<p>When publishing a custom post type, I'm trying to override the custom permalink based on code rather than what the user types into the input box. I can confirm my action is firing correctly, but I'm suspecting it's being triggered before the update event, so the user's value then overrides mine.</p> <pre><code>add_action('publish_course-variation', 'update_course_variation_permalink', 10, 3); function update_course_variation_permalink($course_variation_id){ $cv_meta = get_post_meta($course_variation_id); $desired_permalink_value = "my/custom/permalink"; if( isset($cv_meta['custom_permalink']) ){ //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){ update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); $results = "UPDATED"; }else{ $results = "UNTOUCHED/ALREADY SET CORRECTLY"; } }else{ //DOESNT HAVE PERMALINK = ADD add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); $results = "NEW CUSTOM PERMALINK CREATED"; } }//end function </code></pre> <p>How do I make my action happen after the post is updated? Or disable the permalink from being updated by hitting 'publish'? </p> <p>Thanks</p>
[ { "answer_id": 183551, "author": "Web Dev", "author_id": 69449, "author_profile": "https://wordpress.stackexchange.com/users/69449", "pm_score": -1, "selected": false, "text": "<p>You could just do a <code>display:none</code> on the css selector for the slug so they never see it.</p>\n" }, { "answer_id": 183555, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>The <code>publish_{post-type}</code> action is triggered only when the post change from any post status (not published) to published; for example, if the post is already published and you edit it, the <code>publish_{post-type}</code> action is not triggered. I think you need to hook your function to <code>save_post_{post_type}</code> action, which is triggered every time a post is saved, not matter the status:</p>\n\n<pre><code>add_action('save_post_course-variation', 'update_course_variation_permalink', 10, 3);\n\nfunction update_course_variation_permalink($course_variation_id){\n\n $cv_meta = get_post_meta($course_variation_id);\n $desired_permalink_value = \"my/custom/permalink\";\n\n if( isset($cv_meta['custom_permalink']) ){\n //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED\n if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){\n update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); \n $results = \"UPDATED\";\n }else{\n $results = \"UNTOUCHED/ALREADY SET CORRECTLY\";\n }\n }else{\n //DOESNT HAVE PERMALINK = ADD\n add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); \n $results = \"NEW CUSTOM PERMALINK CREATED\";\n }\n\n}//end function\n</code></pre>\n\n<p><strong>Note</strong>: storing data in <code>custom_permalink</code> meta field doens't affect to the permalink. Not sure how you are handling the post permalink. I just answered your question about how to trigger the function when a post is updated. If you want to truly override permalink (not a meta field), you could use this (based on this <a href=\"https://wordpress.stackexchange.com/a/128831/37428\">answer</a>):</p>\n\n<pre><code>add_filter('wp_insert_post_data', 'wpse_wp_insert_post_data', 10, 2);\nfunction wpse_wp_insert_post_data($data, $post_attr) {\n\n $desired_permalink_value = \"my/custom/permalink\";\n\n if( ( isset( $data['post_name'] ) &amp;&amp; $data['post_name'] != $desired_permalink_value ) || empty( $data['post_name'] ) ) {\n $data['post_name'] = $desired_permalink_value;\n }\n\n return $data;\n}\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183548", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69831/" ]
When publishing a custom post type, I'm trying to override the custom permalink based on code rather than what the user types into the input box. I can confirm my action is firing correctly, but I'm suspecting it's being triggered before the update event, so the user's value then overrides mine. ``` add_action('publish_course-variation', 'update_course_variation_permalink', 10, 3); function update_course_variation_permalink($course_variation_id){ $cv_meta = get_post_meta($course_variation_id); $desired_permalink_value = "my/custom/permalink"; if( isset($cv_meta['custom_permalink']) ){ //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){ update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); $results = "UPDATED"; }else{ $results = "UNTOUCHED/ALREADY SET CORRECTLY"; } }else{ //DOESNT HAVE PERMALINK = ADD add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); $results = "NEW CUSTOM PERMALINK CREATED"; } }//end function ``` How do I make my action happen after the post is updated? Or disable the permalink from being updated by hitting 'publish'? Thanks
The `publish_{post-type}` action is triggered only when the post change from any post status (not published) to published; for example, if the post is already published and you edit it, the `publish_{post-type}` action is not triggered. I think you need to hook your function to `save_post_{post_type}` action, which is triggered every time a post is saved, not matter the status: ``` add_action('save_post_course-variation', 'update_course_variation_permalink', 10, 3); function update_course_variation_permalink($course_variation_id){ $cv_meta = get_post_meta($course_variation_id); $desired_permalink_value = "my/custom/permalink"; if( isset($cv_meta['custom_permalink']) ){ //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){ update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); $results = "UPDATED"; }else{ $results = "UNTOUCHED/ALREADY SET CORRECTLY"; } }else{ //DOESNT HAVE PERMALINK = ADD add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); $results = "NEW CUSTOM PERMALINK CREATED"; } }//end function ``` **Note**: storing data in `custom_permalink` meta field doens't affect to the permalink. Not sure how you are handling the post permalink. I just answered your question about how to trigger the function when a post is updated. If you want to truly override permalink (not a meta field), you could use this (based on this [answer](https://wordpress.stackexchange.com/a/128831/37428)): ``` add_filter('wp_insert_post_data', 'wpse_wp_insert_post_data', 10, 2); function wpse_wp_insert_post_data($data, $post_attr) { $desired_permalink_value = "my/custom/permalink"; if( ( isset( $data['post_name'] ) && $data['post_name'] != $desired_permalink_value ) || empty( $data['post_name'] ) ) { $data['post_name'] = $desired_permalink_value; } return $data; } ```
183,553
<p>I would have thought a simple question but I can't find a function to do this in the WordPress API. </p> <p>I just want to revert to one previous revision as soon as a user updates a post. This would allow admins/editors to review the latest non live revision whilst the old one gives the appearance of staying live. The editor/admin would then switch the post to the newest revision when they are happy with it.</p>
[ { "answer_id": 183551, "author": "Web Dev", "author_id": 69449, "author_profile": "https://wordpress.stackexchange.com/users/69449", "pm_score": -1, "selected": false, "text": "<p>You could just do a <code>display:none</code> on the css selector for the slug so they never see it.</p>\n" }, { "answer_id": 183555, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>The <code>publish_{post-type}</code> action is triggered only when the post change from any post status (not published) to published; for example, if the post is already published and you edit it, the <code>publish_{post-type}</code> action is not triggered. I think you need to hook your function to <code>save_post_{post_type}</code> action, which is triggered every time a post is saved, not matter the status:</p>\n\n<pre><code>add_action('save_post_course-variation', 'update_course_variation_permalink', 10, 3);\n\nfunction update_course_variation_permalink($course_variation_id){\n\n $cv_meta = get_post_meta($course_variation_id);\n $desired_permalink_value = \"my/custom/permalink\";\n\n if( isset($cv_meta['custom_permalink']) ){\n //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED\n if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){\n update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); \n $results = \"UPDATED\";\n }else{\n $results = \"UNTOUCHED/ALREADY SET CORRECTLY\";\n }\n }else{\n //DOESNT HAVE PERMALINK = ADD\n add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); \n $results = \"NEW CUSTOM PERMALINK CREATED\";\n }\n\n}//end function\n</code></pre>\n\n<p><strong>Note</strong>: storing data in <code>custom_permalink</code> meta field doens't affect to the permalink. Not sure how you are handling the post permalink. I just answered your question about how to trigger the function when a post is updated. If you want to truly override permalink (not a meta field), you could use this (based on this <a href=\"https://wordpress.stackexchange.com/a/128831/37428\">answer</a>):</p>\n\n<pre><code>add_filter('wp_insert_post_data', 'wpse_wp_insert_post_data', 10, 2);\nfunction wpse_wp_insert_post_data($data, $post_attr) {\n\n $desired_permalink_value = \"my/custom/permalink\";\n\n if( ( isset( $data['post_name'] ) &amp;&amp; $data['post_name'] != $desired_permalink_value ) || empty( $data['post_name'] ) ) {\n $data['post_name'] = $desired_permalink_value;\n }\n\n return $data;\n}\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28543/" ]
I would have thought a simple question but I can't find a function to do this in the WordPress API. I just want to revert to one previous revision as soon as a user updates a post. This would allow admins/editors to review the latest non live revision whilst the old one gives the appearance of staying live. The editor/admin would then switch the post to the newest revision when they are happy with it.
The `publish_{post-type}` action is triggered only when the post change from any post status (not published) to published; for example, if the post is already published and you edit it, the `publish_{post-type}` action is not triggered. I think you need to hook your function to `save_post_{post_type}` action, which is triggered every time a post is saved, not matter the status: ``` add_action('save_post_course-variation', 'update_course_variation_permalink', 10, 3); function update_course_variation_permalink($course_variation_id){ $cv_meta = get_post_meta($course_variation_id); $desired_permalink_value = "my/custom/permalink"; if( isset($cv_meta['custom_permalink']) ){ //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){ update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); $results = "UPDATED"; }else{ $results = "UNTOUCHED/ALREADY SET CORRECTLY"; } }else{ //DOESNT HAVE PERMALINK = ADD add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); $results = "NEW CUSTOM PERMALINK CREATED"; } }//end function ``` **Note**: storing data in `custom_permalink` meta field doens't affect to the permalink. Not sure how you are handling the post permalink. I just answered your question about how to trigger the function when a post is updated. If you want to truly override permalink (not a meta field), you could use this (based on this [answer](https://wordpress.stackexchange.com/a/128831/37428)): ``` add_filter('wp_insert_post_data', 'wpse_wp_insert_post_data', 10, 2); function wpse_wp_insert_post_data($data, $post_attr) { $desired_permalink_value = "my/custom/permalink"; if( ( isset( $data['post_name'] ) && $data['post_name'] != $desired_permalink_value ) || empty( $data['post_name'] ) ) { $data['post_name'] = $desired_permalink_value; } return $data; } ```
183,554
<p>I install fresh installation of wordpress in my server sub-folder call <code>blog</code>.</p> <p>So in the beginning I access the site <code>mydomain/blog</code> and it works perfectly. </p> <p>But when I changed the <code>permalinks</code> settings to <code>Post name</code> option in the <code>settings</code>, all urls giving me 403 - forbidden error including frot-end.</p> <p>And then I realize it is because of <code>.htaccess</code> file inside the <code>/blog</code> folder as bellow.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>It was automatically create after I change the <code>permalinks</code> settings. When I rename the <code>.htaccess</code> file to another name homepage is accessible and not others.</p> <p>Does anybody have an idea to what should I do in order to get the things back in action.</p> <p>Thanks in advance.</p>
[ { "answer_id": 183551, "author": "Web Dev", "author_id": 69449, "author_profile": "https://wordpress.stackexchange.com/users/69449", "pm_score": -1, "selected": false, "text": "<p>You could just do a <code>display:none</code> on the css selector for the slug so they never see it.</p>\n" }, { "answer_id": 183555, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>The <code>publish_{post-type}</code> action is triggered only when the post change from any post status (not published) to published; for example, if the post is already published and you edit it, the <code>publish_{post-type}</code> action is not triggered. I think you need to hook your function to <code>save_post_{post_type}</code> action, which is triggered every time a post is saved, not matter the status:</p>\n\n<pre><code>add_action('save_post_course-variation', 'update_course_variation_permalink', 10, 3);\n\nfunction update_course_variation_permalink($course_variation_id){\n\n $cv_meta = get_post_meta($course_variation_id);\n $desired_permalink_value = \"my/custom/permalink\";\n\n if( isset($cv_meta['custom_permalink']) ){\n //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED\n if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){\n update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); \n $results = \"UPDATED\";\n }else{\n $results = \"UNTOUCHED/ALREADY SET CORRECTLY\";\n }\n }else{\n //DOESNT HAVE PERMALINK = ADD\n add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); \n $results = \"NEW CUSTOM PERMALINK CREATED\";\n }\n\n}//end function\n</code></pre>\n\n<p><strong>Note</strong>: storing data in <code>custom_permalink</code> meta field doens't affect to the permalink. Not sure how you are handling the post permalink. I just answered your question about how to trigger the function when a post is updated. If you want to truly override permalink (not a meta field), you could use this (based on this <a href=\"https://wordpress.stackexchange.com/a/128831/37428\">answer</a>):</p>\n\n<pre><code>add_filter('wp_insert_post_data', 'wpse_wp_insert_post_data', 10, 2);\nfunction wpse_wp_insert_post_data($data, $post_attr) {\n\n $desired_permalink_value = \"my/custom/permalink\";\n\n if( ( isset( $data['post_name'] ) &amp;&amp; $data['post_name'] != $desired_permalink_value ) || empty( $data['post_name'] ) ) {\n $data['post_name'] = $desired_permalink_value;\n }\n\n return $data;\n}\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
I install fresh installation of wordpress in my server sub-folder call `blog`. So in the beginning I access the site `mydomain/blog` and it works perfectly. But when I changed the `permalinks` settings to `Post name` option in the `settings`, all urls giving me 403 - forbidden error including frot-end. And then I realize it is because of `.htaccess` file inside the `/blog` folder as bellow. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule> # END WordPress ``` It was automatically create after I change the `permalinks` settings. When I rename the `.htaccess` file to another name homepage is accessible and not others. Does anybody have an idea to what should I do in order to get the things back in action. Thanks in advance.
The `publish_{post-type}` action is triggered only when the post change from any post status (not published) to published; for example, if the post is already published and you edit it, the `publish_{post-type}` action is not triggered. I think you need to hook your function to `save_post_{post_type}` action, which is triggered every time a post is saved, not matter the status: ``` add_action('save_post_course-variation', 'update_course_variation_permalink', 10, 3); function update_course_variation_permalink($course_variation_id){ $cv_meta = get_post_meta($course_variation_id); $desired_permalink_value = "my/custom/permalink"; if( isset($cv_meta['custom_permalink']) ){ //HAS PERMALINK = CHECK AND UPDATE IF REQUIRED if( get_post_meta($course_variation_id, 'custom_permalink', true) != $desired_permalink_value ){ update_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value); $results = "UPDATED"; }else{ $results = "UNTOUCHED/ALREADY SET CORRECTLY"; } }else{ //DOESNT HAVE PERMALINK = ADD add_post_meta($course_variation_id, 'custom_permalink', $desired_permalink_value, true); $results = "NEW CUSTOM PERMALINK CREATED"; } }//end function ``` **Note**: storing data in `custom_permalink` meta field doens't affect to the permalink. Not sure how you are handling the post permalink. I just answered your question about how to trigger the function when a post is updated. If you want to truly override permalink (not a meta field), you could use this (based on this [answer](https://wordpress.stackexchange.com/a/128831/37428)): ``` add_filter('wp_insert_post_data', 'wpse_wp_insert_post_data', 10, 2); function wpse_wp_insert_post_data($data, $post_attr) { $desired_permalink_value = "my/custom/permalink"; if( ( isset( $data['post_name'] ) && $data['post_name'] != $desired_permalink_value ) || empty( $data['post_name'] ) ) { $data['post_name'] = $desired_permalink_value; } return $data; } ```
183,576
<p>I've tinkered with WordPress a little, but I'm far from an expert, so apologies in advance if this is a duplicate question.</p> <p>I've built a simple WordPress theme based around Bootstrap, and I can successfully display posts using <code>the_content()</code>, while filling in the sidebar using <code>get_sidebar()</code>.</p> <p>My question is whether it's possible to tag a specific section of a post, and have that section handled differently than the rest of <code>the_content()</code>. Here's an example:</p> <p><img src="https://i.stack.imgur.com/rdUXu.png" alt="enter image description here"></p> <p>Here's some pseudo-code:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;div class="row"&gt; &lt;div class="col-md-12"&gt; &lt;!--tag one image within the post, to appear across all 12 columns--&gt; &lt;/div&gt; &lt;/div&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;div class="row"&gt; &lt;div class="col-md-8"&gt; &lt;!--the rest of the post, minus the tagged image, goes here--&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;?php get_sidebar(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;&lt;?php _e('Sorry, no posts matched your criteria.'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>In this case I'd like to tag (or otherwise identify) one image from the post, and have that appear in the <em>col-md-12</em> div, with the rest of the post going into the <em>col-md-8</em> div.</p> <p>I've read about <code>the_excerpt()</code> but I don't believe that will work here. </p>
[ { "answer_id": 183596, "author": "dynamicad", "author_id": 70281, "author_profile": "https://wordpress.stackexchange.com/users/70281", "pm_score": 1, "selected": false, "text": "<p>You could try using <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow\">advanced custom fields plugin</a>. You can add an image field to the page under the content area, and then just output that custom field wherever you want it on the page using the following where field_name is the name of the field you create. You would then just wrap the code in whatever CSS you wanted. </p>\n\n<pre><code>&lt;p&gt;&lt;?php the_field('field_name'); ?&gt;&lt;/p&gt;\n</code></pre>\n\n<p>You could also just simply consider using the featured image. </p>\n" }, { "answer_id": 183617, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>You can make use of <a href=\"https://codex.wordpress.org/Post_Thumbnails\" rel=\"nofollow\">featured images</a> as suggested by @gmazzap in comments. This featured image will not be included in post content. However, if you already have your images included in post content, then you need to strip the post content down in two parts, as you've said in your question.</p>\n\n<p>I have two functions, one that returns all the images (or any html tag content) from the content and one function that returns the text without the desired tag/images. Both of these functions uses <a href=\"http://php.net/manual/en/class.domdocument.php\" rel=\"nofollow\"><code>DOMDocument</code></a></p>\n\n<p>The first function <code>get_content_without_tag()</code> returns the content which has been stripped from images. There are two parameters</p>\n\n<ul>\n<li><p><code>$html</code> -> The text with images to be stripped, in this case, use <code>apply_filters( 'the_content', get_the_content() )</code> to use the post content</p></li>\n<li><p><code>$tag</code> -> The name of the tag to strip out, in this case, 'a' as <code>a</code> tags hold images</p></li>\n</ul>\n\n<p>Here is the function</p>\n\n<pre><code>function get_content_without_tag( $html, $tag )\n{\n $dom = new DOMDocument;\n $dom-&gt;loadHTML( $html );\n\n $dom_x_path = new DOMXPath( $dom );\n while ($node = $dom_x_path-&gt;query( '//' . $tag )-&gt;item(0)) {\n $node-&gt;parentNode-&gt;removeChild( $node );\n }\n return $dom-&gt;saveHTML();\n}\n</code></pre>\n\n<p>You would then use this in place of <code>the_content()</code> where you would need to display text only, stripping out the complete <code>&lt;a/&gt;</code> tag in which the images are as follows</p>\n\n<pre><code>echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' )\n</code></pre>\n\n<p>The second function, <code>get_tag_without_text()</code> returns the content between the desired tag, in your case, images. The parameters are exactly the same as the first function. Here is the function</p>\n\n<pre><code>function get_tag_without_text( $html, $tag )\n{\n $document = new DOMDocument();\n $document-&gt;loadHTML( $html ); \n\n $tags = [];\n $elements = $document-&gt;getElementsByTagName( $tag );\n if ( $elements ) {\n foreach ( $elements as $element ) {\n $tags[] = $document-&gt;saveHtml($element);\n } \n } \n return $tags;\n}\n</code></pre>\n\n<p>This function returns an array of images should you use <code>a</code> tags, so, to display the first image, use the function as follow:</p>\n\n<pre><code>$image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' );\necho $image[0];\n</code></pre>\n\n<p>Just one final tip on your code, move your call the side bar outside your loop. It should go just above the call to the footer</p>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70325/" ]
I've tinkered with WordPress a little, but I'm far from an expert, so apologies in advance if this is a duplicate question. I've built a simple WordPress theme based around Bootstrap, and I can successfully display posts using `the_content()`, while filling in the sidebar using `get_sidebar()`. My question is whether it's possible to tag a specific section of a post, and have that section handled differently than the rest of `the_content()`. Here's an example: ![enter image description here](https://i.stack.imgur.com/rdUXu.png) Here's some pseudo-code: ``` <?php get_header(); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="row"> <div class="col-md-12"> <!--tag one image within the post, to appear across all 12 columns--> </div> </div> <h1><?php the_title(); ?></h1> <div class="row"> <div class="col-md-8"> <!--the rest of the post, minus the tagged image, goes here--> <?php the_content(); ?> </div> <div class="col-md-4"> <?php get_sidebar(); ?> </div> </div> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> <?php get_footer(); ?> ``` In this case I'd like to tag (or otherwise identify) one image from the post, and have that appear in the *col-md-12* div, with the rest of the post going into the *col-md-8* div. I've read about `the_excerpt()` but I don't believe that will work here.
You can make use of [featured images](https://codex.wordpress.org/Post_Thumbnails) as suggested by @gmazzap in comments. This featured image will not be included in post content. However, if you already have your images included in post content, then you need to strip the post content down in two parts, as you've said in your question. I have two functions, one that returns all the images (or any html tag content) from the content and one function that returns the text without the desired tag/images. Both of these functions uses [`DOMDocument`](http://php.net/manual/en/class.domdocument.php) The first function `get_content_without_tag()` returns the content which has been stripped from images. There are two parameters * `$html` -> The text with images to be stripped, in this case, use `apply_filters( 'the_content', get_the_content() )` to use the post content * `$tag` -> The name of the tag to strip out, in this case, 'a' as `a` tags hold images Here is the function ``` function get_content_without_tag( $html, $tag ) { $dom = new DOMDocument; $dom->loadHTML( $html ); $dom_x_path = new DOMXPath( $dom ); while ($node = $dom_x_path->query( '//' . $tag )->item(0)) { $node->parentNode->removeChild( $node ); } return $dom->saveHTML(); } ``` You would then use this in place of `the_content()` where you would need to display text only, stripping out the complete `<a/>` tag in which the images are as follows ``` echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' ) ``` The second function, `get_tag_without_text()` returns the content between the desired tag, in your case, images. The parameters are exactly the same as the first function. Here is the function ``` function get_tag_without_text( $html, $tag ) { $document = new DOMDocument(); $document->loadHTML( $html ); $tags = []; $elements = $document->getElementsByTagName( $tag ); if ( $elements ) { foreach ( $elements as $element ) { $tags[] = $document->saveHtml($element); } } return $tags; } ``` This function returns an array of images should you use `a` tags, so, to display the first image, use the function as follow: ``` $image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' ); echo $image[0]; ``` Just one final tip on your code, move your call the side bar outside your loop. It should go just above the call to the footer
183,582
<p>I have this site that uses the <code>&lt;!--nextpage--&gt;</code> tag in posts for pagination purposes. I want to disable pagination, but without deleting the tags for the database (maybe they'll want to use them again in the future). </p> <p>Tried removing <code>wp_link_pages();</code> from the template, but then it would only show the first page's content without the links - I don't know if that's how it should work or something wrong. </p> <p>How can I make it that wordpress simply ignores <code>&lt;!--nextpage--&gt;</code> and display the full post at once?</p>
[ { "answer_id": 183587, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You can try to use the <code>the_post</code> filter, to override the content pagination, that takes place within the <code>setup_postdata()</code> function ( <em>PHP 5.4+</em> ):</p>\n\n<pre><code>/**\n * Ignore the &lt;!--nextpage--&gt; for content pagination.\n * \n * @see http://wordpress.stackexchange.com/a/183587/26350\n */\n\nadd_action( 'the_post', function( $post )\n{\n if ( false !== strpos( $post-&gt;post_content, '&lt;!--nextpage--&gt;' ) ) \n {\n // Reset the global $pages:\n $GLOBALS['pages'] = [ $post-&gt;post_content ];\n\n // Reset the global $numpages:\n $GLOBALS['numpages'] = 0;\n\n // Reset the global $multipage:\n $GLOBALS['multipage'] = false;\n }\n\n}, 99 );\n</code></pre>\n\n<p>to ignore the <code>&lt;!--nextpage--&gt;</code> feature. </p>\n\n<p>The global <code>$pages</code> variable contains the paginated content:</p>\n\n<pre><code>$pages = explode('&lt;!--nextpage--&gt;', $content);\n</code></pre>\n\n<p>so that's why we need to restore it to:</p>\n\n<pre><code>$pages = array( $post-&gt;post_content );\n</code></pre>\n\n<p>We actually don't need to restore the <code>$numpages</code> variable, but we do it as part of the house cleaning. If we only restored <code>$pages</code> and <code>$numpages=0</code> then we would get: </p>\n\n<pre><code>&lt;div class=\"page-links\"&gt;Pages:&lt;/div&gt; \n</code></pre>\n\n<p>The <code>wp_link_pages()</code> function <a href=\"https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/post-template.php#L779\" rel=\"nofollow\">checks</a> if the global <code>$multipage</code> is true to display the content pagination output. So that's the variable to set to false to remove the whole output. We could also use the <code>wp_link_pages</code> filter to remove it.</p>\n" }, { "answer_id": 254790, "author": "SatuWeb", "author_id": 102634, "author_profile": "https://wordpress.stackexchange.com/users/102634", "pm_score": 0, "selected": false, "text": "<p>Try to put <code>&lt;?php $GLOBALS['multipage'] = false; ?&gt;</code> in your loop.\nif doesn't show paginator in mobile: </p>\n\n<pre><code>wp_is_mobile()\n$GLOBALS['multipage'] = false;\n</code></pre>\n\n<p>I hope it is helpful for you</p>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70333/" ]
I have this site that uses the `<!--nextpage-->` tag in posts for pagination purposes. I want to disable pagination, but without deleting the tags for the database (maybe they'll want to use them again in the future). Tried removing `wp_link_pages();` from the template, but then it would only show the first page's content without the links - I don't know if that's how it should work or something wrong. How can I make it that wordpress simply ignores `<!--nextpage-->` and display the full post at once?
You can try to use the `the_post` filter, to override the content pagination, that takes place within the `setup_postdata()` function ( *PHP 5.4+* ): ``` /** * Ignore the <!--nextpage--> for content pagination. * * @see http://wordpress.stackexchange.com/a/183587/26350 */ add_action( 'the_post', function( $post ) { if ( false !== strpos( $post->post_content, '<!--nextpage-->' ) ) { // Reset the global $pages: $GLOBALS['pages'] = [ $post->post_content ]; // Reset the global $numpages: $GLOBALS['numpages'] = 0; // Reset the global $multipage: $GLOBALS['multipage'] = false; } }, 99 ); ``` to ignore the `<!--nextpage-->` feature. The global `$pages` variable contains the paginated content: ``` $pages = explode('<!--nextpage-->', $content); ``` so that's why we need to restore it to: ``` $pages = array( $post->post_content ); ``` We actually don't need to restore the `$numpages` variable, but we do it as part of the house cleaning. If we only restored `$pages` and `$numpages=0` then we would get: ``` <div class="page-links">Pages:</div> ``` The `wp_link_pages()` function [checks](https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/post-template.php#L779) if the global `$multipage` is true to display the content pagination output. So that's the variable to set to false to remove the whole output. We could also use the `wp_link_pages` filter to remove it.
183,598
<p>On one of my pages I changed the slug to form a different URL. E.g.</p> <p>Old: <a href="http://example.com/old-slug" rel="noreferrer">http://example.com/old-slug</a></p> <p>New: <a href="http://example.com/new-slug" rel="noreferrer">http://example.com/new-slug</a></p> <p>WordPress has done it's thing of redirecting <a href="http://example.com/old-slug" rel="noreferrer">http://example.com/old-slug</a> to <a href="http://example.com/new-slug" rel="noreferrer">http://example.com/new-slug</a>.</p> <p>I'd like to remove this behaviour as a plugin I am using makes use of the slug in question and the redirect overrides its behaviour.</p> <p>I checked <a href="https://wordpress.stackexchange.com/questions/33361/does-wordpress-keep-track-of-a-posts-url-history-and-provide-automatic-redirect">this question</a>, and checked my <code>wp_postmeta</code> table for instances of <code>_wp_old_slug</code> but nothing is returned. My server is Nginx so shouldn't be affected by .htaccess files.</p> <p>Is there anything else I can do to remove this redirect?</p>
[ { "answer_id": 183603, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 3, "selected": false, "text": "<p>This (in your <code>functions.php</code>) will turn it off (but see also the comment I've left):</p>\n\n<pre><code>remove_action('template_redirect', 'wp_old_slug_redirect');\n</code></pre>\n\n<p>It seems odd that your <code>wp_postmeta</code> table wouldn't have any <code>_wp_old_slug</code> keys - the bit of code that does that is in <code>wp-includes/query.php</code> (wp_old_slug_redirect()) - you could add an exit or debug statement there to check if it's being called.</p>\n\n<p>Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink <em>/foobar</em>, then <em>/foo</em> will redirect to it.</p>\n" }, { "answer_id": 191283, "author": "Kęstutis", "author_id": 68821, "author_profile": "https://wordpress.stackexchange.com/users/68821", "pm_score": 1, "selected": false, "text": "<p>What helped for was permalinks reset. just go to <code>Settings -&gt; Permalinks</code>, pick default, hit <code>Save Changes</code>. Then pick your structure and hit <code>Save Changes</code> again. </p>\n" }, { "answer_id": 254865, "author": "Faiyaz Alam", "author_id": 85769, "author_profile": "https://wordpress.stackexchange.com/users/85769", "pm_score": 2, "selected": false, "text": "<p>this worked for me:</p>\n\n<pre><code> remove_filter('template_redirect', 'redirect_canonical'); \n</code></pre>\n\n<p>source: <a href=\"http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/\" rel=\"nofollow noreferrer\">http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/</a></p>\n" }, { "answer_id": 258572, "author": "Lithin", "author_id": 114553, "author_profile": "https://wordpress.stackexchange.com/users/114553", "pm_score": 1, "selected": false, "text": "<p>To manually remove automatic redirects after slug change, just delete the corresponding rows from the \"wp-redirection-items\" from the database using phpMyAdmin.</p>\n\n<p>This is the best and simplest way which allows you to remove redirects for specific posts. More details can be found here <a href=\"http://couponnexus.com/remove-wordpress-redirects-changing-slug/\" rel=\"nofollow noreferrer\">http://couponnexus.com/remove-wordpress-redirects-changing-slug/</a></p>\n" }, { "answer_id": 323253, "author": "Avinash Singh", "author_id": 157210, "author_profile": "https://wordpress.stackexchange.com/users/157210", "pm_score": 0, "selected": false, "text": "<p>Every WordPress post has its own slug, which is automatically generated by your post’s title. If you decide to change the post slug later, WordPress will remember the old one and redirect it to the new one. It’s possible to prevent old post slug redirection in WordPress by adding removing a couple of actions from your WordPress core with a small snippet.</p>\n\n<p>Just add following code to your current theme’s <strong>functions.php</strong> file to prevent WordPress from redirecting old post slugs to new ones:</p>\n\n<pre><code>remove_action( 'template_redirect', 'wp_old_slug_redirect'); \nremove_action( 'post_updated', 'wp_check_for_changed_slugs', 12, 3 );\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23620/" ]
On one of my pages I changed the slug to form a different URL. E.g. Old: <http://example.com/old-slug> New: <http://example.com/new-slug> WordPress has done it's thing of redirecting <http://example.com/old-slug> to <http://example.com/new-slug>. I'd like to remove this behaviour as a plugin I am using makes use of the slug in question and the redirect overrides its behaviour. I checked [this question](https://wordpress.stackexchange.com/questions/33361/does-wordpress-keep-track-of-a-posts-url-history-and-provide-automatic-redirect), and checked my `wp_postmeta` table for instances of `_wp_old_slug` but nothing is returned. My server is Nginx so shouldn't be affected by .htaccess files. Is there anything else I can do to remove this redirect?
This (in your `functions.php`) will turn it off (but see also the comment I've left): ``` remove_action('template_redirect', 'wp_old_slug_redirect'); ``` It seems odd that your `wp_postmeta` table wouldn't have any `_wp_old_slug` keys - the bit of code that does that is in `wp-includes/query.php` (wp\_old\_slug\_redirect()) - you could add an exit or debug statement there to check if it's being called. Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink */foobar*, then */foo* will redirect to it.
183,604
<p>I have a WordPress site that uses custom post types. However, the custom post types are not being recognized by google. It's like the custom post type is a box full of our original content that google can't see inside of it seems. What can I do to change this?</p>
[ { "answer_id": 183603, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 3, "selected": false, "text": "<p>This (in your <code>functions.php</code>) will turn it off (but see also the comment I've left):</p>\n\n<pre><code>remove_action('template_redirect', 'wp_old_slug_redirect');\n</code></pre>\n\n<p>It seems odd that your <code>wp_postmeta</code> table wouldn't have any <code>_wp_old_slug</code> keys - the bit of code that does that is in <code>wp-includes/query.php</code> (wp_old_slug_redirect()) - you could add an exit or debug statement there to check if it's being called.</p>\n\n<p>Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink <em>/foobar</em>, then <em>/foo</em> will redirect to it.</p>\n" }, { "answer_id": 191283, "author": "Kęstutis", "author_id": 68821, "author_profile": "https://wordpress.stackexchange.com/users/68821", "pm_score": 1, "selected": false, "text": "<p>What helped for was permalinks reset. just go to <code>Settings -&gt; Permalinks</code>, pick default, hit <code>Save Changes</code>. Then pick your structure and hit <code>Save Changes</code> again. </p>\n" }, { "answer_id": 254865, "author": "Faiyaz Alam", "author_id": 85769, "author_profile": "https://wordpress.stackexchange.com/users/85769", "pm_score": 2, "selected": false, "text": "<p>this worked for me:</p>\n\n<pre><code> remove_filter('template_redirect', 'redirect_canonical'); \n</code></pre>\n\n<p>source: <a href=\"http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/\" rel=\"nofollow noreferrer\">http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/</a></p>\n" }, { "answer_id": 258572, "author": "Lithin", "author_id": 114553, "author_profile": "https://wordpress.stackexchange.com/users/114553", "pm_score": 1, "selected": false, "text": "<p>To manually remove automatic redirects after slug change, just delete the corresponding rows from the \"wp-redirection-items\" from the database using phpMyAdmin.</p>\n\n<p>This is the best and simplest way which allows you to remove redirects for specific posts. More details can be found here <a href=\"http://couponnexus.com/remove-wordpress-redirects-changing-slug/\" rel=\"nofollow noreferrer\">http://couponnexus.com/remove-wordpress-redirects-changing-slug/</a></p>\n" }, { "answer_id": 323253, "author": "Avinash Singh", "author_id": 157210, "author_profile": "https://wordpress.stackexchange.com/users/157210", "pm_score": 0, "selected": false, "text": "<p>Every WordPress post has its own slug, which is automatically generated by your post’s title. If you decide to change the post slug later, WordPress will remember the old one and redirect it to the new one. It’s possible to prevent old post slug redirection in WordPress by adding removing a couple of actions from your WordPress core with a small snippet.</p>\n\n<p>Just add following code to your current theme’s <strong>functions.php</strong> file to prevent WordPress from redirecting old post slugs to new ones:</p>\n\n<pre><code>remove_action( 'template_redirect', 'wp_old_slug_redirect'); \nremove_action( 'post_updated', 'wp_check_for_changed_slugs', 12, 3 );\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183604", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70345/" ]
I have a WordPress site that uses custom post types. However, the custom post types are not being recognized by google. It's like the custom post type is a box full of our original content that google can't see inside of it seems. What can I do to change this?
This (in your `functions.php`) will turn it off (but see also the comment I've left): ``` remove_action('template_redirect', 'wp_old_slug_redirect'); ``` It seems odd that your `wp_postmeta` table wouldn't have any `_wp_old_slug` keys - the bit of code that does that is in `wp-includes/query.php` (wp\_old\_slug\_redirect()) - you could add an exit or debug statement there to check if it's being called. Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink */foobar*, then */foo* will redirect to it.
183,614
<p>I'm running through a normal loop on one of my templates, and it displays a list of upcoming events with dates. I'd like the events that have passed to stay active, but not appear in my list of posts. </p> <p>As it currently stands, I select a date for the event (custom field), compare that to the current date via PHP date function, and then if its passed, "continue" so we skip the loop. This is great, except my posts per page suffers from this. I'm not using a <code>WP_Query</code> loop, this is an archive template. </p> <p>Code looks something like this:</p> <pre><code>if( have_posts() ) : while( have_posts() ) : the_post(); // Post specific fields $date = get_post_meta( get_the_ID(), 'Date', true ); $time = get_post_meta( get_the_ID(), 'Time', true ); $cat = wp_get_object_terms(get_the_ID(), 'event-type'); $todaysDate = date('n\/d\/Y'); if( $date &lt; $todaysDate ){ continue; } </code></pre> <p>Any ideas on how I can accomplish this another way?</p>
[ { "answer_id": 183603, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 3, "selected": false, "text": "<p>This (in your <code>functions.php</code>) will turn it off (but see also the comment I've left):</p>\n\n<pre><code>remove_action('template_redirect', 'wp_old_slug_redirect');\n</code></pre>\n\n<p>It seems odd that your <code>wp_postmeta</code> table wouldn't have any <code>_wp_old_slug</code> keys - the bit of code that does that is in <code>wp-includes/query.php</code> (wp_old_slug_redirect()) - you could add an exit or debug statement there to check if it's being called.</p>\n\n<p>Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink <em>/foobar</em>, then <em>/foo</em> will redirect to it.</p>\n" }, { "answer_id": 191283, "author": "Kęstutis", "author_id": 68821, "author_profile": "https://wordpress.stackexchange.com/users/68821", "pm_score": 1, "selected": false, "text": "<p>What helped for was permalinks reset. just go to <code>Settings -&gt; Permalinks</code>, pick default, hit <code>Save Changes</code>. Then pick your structure and hit <code>Save Changes</code> again. </p>\n" }, { "answer_id": 254865, "author": "Faiyaz Alam", "author_id": 85769, "author_profile": "https://wordpress.stackexchange.com/users/85769", "pm_score": 2, "selected": false, "text": "<p>this worked for me:</p>\n\n<pre><code> remove_filter('template_redirect', 'redirect_canonical'); \n</code></pre>\n\n<p>source: <a href=\"http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/\" rel=\"nofollow noreferrer\">http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/</a></p>\n" }, { "answer_id": 258572, "author": "Lithin", "author_id": 114553, "author_profile": "https://wordpress.stackexchange.com/users/114553", "pm_score": 1, "selected": false, "text": "<p>To manually remove automatic redirects after slug change, just delete the corresponding rows from the \"wp-redirection-items\" from the database using phpMyAdmin.</p>\n\n<p>This is the best and simplest way which allows you to remove redirects for specific posts. More details can be found here <a href=\"http://couponnexus.com/remove-wordpress-redirects-changing-slug/\" rel=\"nofollow noreferrer\">http://couponnexus.com/remove-wordpress-redirects-changing-slug/</a></p>\n" }, { "answer_id": 323253, "author": "Avinash Singh", "author_id": 157210, "author_profile": "https://wordpress.stackexchange.com/users/157210", "pm_score": 0, "selected": false, "text": "<p>Every WordPress post has its own slug, which is automatically generated by your post’s title. If you decide to change the post slug later, WordPress will remember the old one and redirect it to the new one. It’s possible to prevent old post slug redirection in WordPress by adding removing a couple of actions from your WordPress core with a small snippet.</p>\n\n<p>Just add following code to your current theme’s <strong>functions.php</strong> file to prevent WordPress from redirecting old post slugs to new ones:</p>\n\n<pre><code>remove_action( 'template_redirect', 'wp_old_slug_redirect'); \nremove_action( 'post_updated', 'wp_check_for_changed_slugs', 12, 3 );\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183614", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55073/" ]
I'm running through a normal loop on one of my templates, and it displays a list of upcoming events with dates. I'd like the events that have passed to stay active, but not appear in my list of posts. As it currently stands, I select a date for the event (custom field), compare that to the current date via PHP date function, and then if its passed, "continue" so we skip the loop. This is great, except my posts per page suffers from this. I'm not using a `WP_Query` loop, this is an archive template. Code looks something like this: ``` if( have_posts() ) : while( have_posts() ) : the_post(); // Post specific fields $date = get_post_meta( get_the_ID(), 'Date', true ); $time = get_post_meta( get_the_ID(), 'Time', true ); $cat = wp_get_object_terms(get_the_ID(), 'event-type'); $todaysDate = date('n\/d\/Y'); if( $date < $todaysDate ){ continue; } ``` Any ideas on how I can accomplish this another way?
This (in your `functions.php`) will turn it off (but see also the comment I've left): ``` remove_action('template_redirect', 'wp_old_slug_redirect'); ``` It seems odd that your `wp_postmeta` table wouldn't have any `_wp_old_slug` keys - the bit of code that does that is in `wp-includes/query.php` (wp\_old\_slug\_redirect()) - you could add an exit or debug statement there to check if it's being called. Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink */foobar*, then */foo* will redirect to it.
183,615
<p>Space is being added to a sidebar in a WordPress theme I have created. The space isn't being added via my own style sheet, but I think I have isolated it to this from my code editor:</p> <pre><code> ul, menu, dir { display: block; list-style-type: disc; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px; -webkit-padding-start: 40px; } </code></pre> <p>I've attached a couple of pictures showing the site as it appears normally, and with the code editor's highlighting of the space.</p> <p>The weird thing is that the "-webkit-margin-*" styles are locked in my code inspector so I cannot edit them. Trying to add the same values to my theme's style sheet with the 1em margins swapped for zeroes doesn't seem to have any effect.</p> <p>Has anyone dealt with this before? </p> <p><img src="https://i.stack.imgur.com/H9Pid.png" alt="Sidebar"></p> <p><img src="https://i.stack.imgur.com/7IqMh.png" alt="Sidebar with space highlighted"></p> <p><strong>EDIT</strong></p> <p>As discussed in the comments, the problem wasn't with padding/margins but with a header tag which contained nothing but a single space (hence the following items started on a newline, which looked a lot like 1em padding).</p> <p>The header tag is generated by the register_sideber() function in widgets.php:</p> <pre><code> function register_sidebar($args = array()) { global $wp_registered_sidebars; $i = count($wp_registered_sidebars) + 1; $defaults = array( 'name' =&gt; sprintf(__('Sidebar %d'), $i ), 'id' =&gt; "sidebar-$i", 'description' =&gt; '', 'class' =&gt; '', 'before_widget' =&gt; '&lt;li id="%1$s" class="widget %2$s"&gt;', 'after_widget' =&gt; "&lt;/li&gt;\n", 'before_title' =&gt; '&lt;h2 class="widgettitle"&gt;', 'after_title' =&gt; "&lt;/h2&gt;\n", ); </code></pre>
[ { "answer_id": 183603, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 3, "selected": false, "text": "<p>This (in your <code>functions.php</code>) will turn it off (but see also the comment I've left):</p>\n\n<pre><code>remove_action('template_redirect', 'wp_old_slug_redirect');\n</code></pre>\n\n<p>It seems odd that your <code>wp_postmeta</code> table wouldn't have any <code>_wp_old_slug</code> keys - the bit of code that does that is in <code>wp-includes/query.php</code> (wp_old_slug_redirect()) - you could add an exit or debug statement there to check if it's being called.</p>\n\n<p>Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink <em>/foobar</em>, then <em>/foo</em> will redirect to it.</p>\n" }, { "answer_id": 191283, "author": "Kęstutis", "author_id": 68821, "author_profile": "https://wordpress.stackexchange.com/users/68821", "pm_score": 1, "selected": false, "text": "<p>What helped for was permalinks reset. just go to <code>Settings -&gt; Permalinks</code>, pick default, hit <code>Save Changes</code>. Then pick your structure and hit <code>Save Changes</code> again. </p>\n" }, { "answer_id": 254865, "author": "Faiyaz Alam", "author_id": 85769, "author_profile": "https://wordpress.stackexchange.com/users/85769", "pm_score": 2, "selected": false, "text": "<p>this worked for me:</p>\n\n<pre><code> remove_filter('template_redirect', 'redirect_canonical'); \n</code></pre>\n\n<p>source: <a href=\"http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/\" rel=\"nofollow noreferrer\">http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/</a></p>\n" }, { "answer_id": 258572, "author": "Lithin", "author_id": 114553, "author_profile": "https://wordpress.stackexchange.com/users/114553", "pm_score": 1, "selected": false, "text": "<p>To manually remove automatic redirects after slug change, just delete the corresponding rows from the \"wp-redirection-items\" from the database using phpMyAdmin.</p>\n\n<p>This is the best and simplest way which allows you to remove redirects for specific posts. More details can be found here <a href=\"http://couponnexus.com/remove-wordpress-redirects-changing-slug/\" rel=\"nofollow noreferrer\">http://couponnexus.com/remove-wordpress-redirects-changing-slug/</a></p>\n" }, { "answer_id": 323253, "author": "Avinash Singh", "author_id": 157210, "author_profile": "https://wordpress.stackexchange.com/users/157210", "pm_score": 0, "selected": false, "text": "<p>Every WordPress post has its own slug, which is automatically generated by your post’s title. If you decide to change the post slug later, WordPress will remember the old one and redirect it to the new one. It’s possible to prevent old post slug redirection in WordPress by adding removing a couple of actions from your WordPress core with a small snippet.</p>\n\n<p>Just add following code to your current theme’s <strong>functions.php</strong> file to prevent WordPress from redirecting old post slugs to new ones:</p>\n\n<pre><code>remove_action( 'template_redirect', 'wp_old_slug_redirect'); \nremove_action( 'post_updated', 'wp_check_for_changed_slugs', 12, 3 );\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70347/" ]
Space is being added to a sidebar in a WordPress theme I have created. The space isn't being added via my own style sheet, but I think I have isolated it to this from my code editor: ``` ul, menu, dir { display: block; list-style-type: disc; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px; -webkit-padding-start: 40px; } ``` I've attached a couple of pictures showing the site as it appears normally, and with the code editor's highlighting of the space. The weird thing is that the "-webkit-margin-\*" styles are locked in my code inspector so I cannot edit them. Trying to add the same values to my theme's style sheet with the 1em margins swapped for zeroes doesn't seem to have any effect. Has anyone dealt with this before? ![Sidebar](https://i.stack.imgur.com/H9Pid.png) ![Sidebar with space highlighted](https://i.stack.imgur.com/7IqMh.png) **EDIT** As discussed in the comments, the problem wasn't with padding/margins but with a header tag which contained nothing but a single space (hence the following items started on a newline, which looked a lot like 1em padding). The header tag is generated by the register\_sideber() function in widgets.php: ``` function register_sidebar($args = array()) { global $wp_registered_sidebars; $i = count($wp_registered_sidebars) + 1; $defaults = array( 'name' => sprintf(__('Sidebar %d'), $i ), 'id' => "sidebar-$i", 'description' => '', 'class' => '', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => "</li>\n", 'before_title' => '<h2 class="widgettitle">', 'after_title' => "</h2>\n", ); ```
This (in your `functions.php`) will turn it off (but see also the comment I've left): ``` remove_action('template_redirect', 'wp_old_slug_redirect'); ``` It seems odd that your `wp_postmeta` table wouldn't have any `_wp_old_slug` keys - the bit of code that does that is in `wp-includes/query.php` (wp\_old\_slug\_redirect()) - you could add an exit or debug statement there to check if it's being called. Also, remember that if WordPress can't find a permalink, it looks for posts with a matching beginning, e.g. if you had a post with permalink */foobar*, then */foo* will redirect to it.
183,652
<p>I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories.</p> <p>So far, I have the client-side code that works when not calling a WP function (this code is in a theme page):</p> <pre><code>jQuery('#cat-location-main').change(function () { var optionSelected = jQuery(this).find('option:selected'); var valueSelected = optionSelected.val(); var textSelected = optionSelected.text(); console.log(valueSelected); jQuery.ajax({ type: 'POST', url: ajaxurl, data: { action: 'myajax-get-subcat', category: valueSelected, // send the nonce along with the request categoryNonce: '&lt;?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?&gt;' }, success: function(data, textStatus, jjqXHR) { console.log(data); }, dataType: 'json' }); }); </code></pre> <p>And I have this in the functions.php:</p> <pre><code>add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat'); function myajax_get_subcat() { $nonce = $_POST['categoryNonce']; $main_category = $_POST['category']; if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce')) die ( 'Busted!'); if(function_exists('wp_dropdown_categories')==true) { echo 'true'; } else { echo 'false'; } wp_dropdown_categories('taxonomy=category&amp;selected=1&amp;echo=1&amp;orderby=NAME&amp;order=ASC&amp;hide_empty=0&amp;hide_empty=0&amp;hierarchical=1&amp;depth=1&amp;id=cat-location-secondary&amp;child_of='.$main_category); exit; } </code></pre> <p>Now I get a "true" on the client side when commenting <strong>wp_dropdown_categories</strong> line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup).</p> <p>Also, not working even if I add <code>require_once(__DIR__.'/../../../wp-load.php');</code> but it works if I use GET in browser (for the functions.php). Any help would be greatly appreciated!</p>
[ { "answer_id": 183657, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Your problem is probably because you do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't.</p>\n\n<p>your code at the ajax handler should be something like</p>\n\n<pre><code>$catshtml = wp_dropdown_categories(.....echo=0);\n$ret = array('data' =&gt; $catshtml);\nwp_send_json($ret);\ndie();\n</code></pre>\n\n<p>on the browser side you need to look for the content of the data attribute of the json element you receive from the server.</p>\n\n<p>Debugging tip: always look at what is actually transmitted as a response in the browser developer tools section first before starting to rely on the consol log.</p>\n" }, { "answer_id": 183659, "author": "strattonn", "author_id": 56917, "author_profile": "https://wordpress.stackexchange.com/users/56917", "pm_score": 0, "selected": false, "text": "<p>When I seemingly get nothing from an Ajax call I run Fiddler and examine the return when it comes to the request.</p>\n\n<p>The other day an Ajax call was failing inexplicably. Upon examining the return I saw another programmer was dumping an array into the output before I received my response. I never would have guessed that because the JavaScript never hit the breakpoint I set.</p>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70361/" ]
I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories. So far, I have the client-side code that works when not calling a WP function (this code is in a theme page): ``` jQuery('#cat-location-main').change(function () { var optionSelected = jQuery(this).find('option:selected'); var valueSelected = optionSelected.val(); var textSelected = optionSelected.text(); console.log(valueSelected); jQuery.ajax({ type: 'POST', url: ajaxurl, data: { action: 'myajax-get-subcat', category: valueSelected, // send the nonce along with the request categoryNonce: '<?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?>' }, success: function(data, textStatus, jjqXHR) { console.log(data); }, dataType: 'json' }); }); ``` And I have this in the functions.php: ``` add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat'); function myajax_get_subcat() { $nonce = $_POST['categoryNonce']; $main_category = $_POST['category']; if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce')) die ( 'Busted!'); if(function_exists('wp_dropdown_categories')==true) { echo 'true'; } else { echo 'false'; } wp_dropdown_categories('taxonomy=category&selected=1&echo=1&orderby=NAME&order=ASC&hide_empty=0&hide_empty=0&hierarchical=1&depth=1&id=cat-location-secondary&child_of='.$main_category); exit; } ``` Now I get a "true" on the client side when commenting **wp\_dropdown\_categories** line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup). Also, not working even if I add `require_once(__DIR__.'/../../../wp-load.php');` but it works if I use GET in browser (for the functions.php). Any help would be greatly appreciated!
Your problem is probably because you do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't. your code at the ajax handler should be something like ``` $catshtml = wp_dropdown_categories(.....echo=0); $ret = array('data' => $catshtml); wp_send_json($ret); die(); ``` on the browser side you need to look for the content of the data attribute of the json element you receive from the server. Debugging tip: always look at what is actually transmitted as a response in the browser developer tools section first before starting to rely on the consol log.
183,669
<h2>Use Case</h2> <p>I've been experimenting with Chrome's Dev Tools Workspace features. It includes the ability to edit a file directly in Dev Tools and have the saved stylesheet refresh itself (or even compile and then refresh!).</p> <p>However, as documented in the <a href="https://stackoverflow.com/questions/20886807/chromes-auto-reload-generated-css-not-reloading-page-when-sass-recompiles-css">StackOverflow question "Chrome's “Auto-Reload Generated CSS” not reloading page when SASS recompiles CSS"</a>, URL parameters on the stylesheet URL prevent Chrome from noticing the change.</p> <h2>Desired Outcome</h2> <p>That means that <strong>only during development</strong>, I wanted to remove the <code>?ver=X.X.X</code> from the normal stylesheet <code>&lt;link&gt;</code> output by <code>wp_enqueue_style()</code>. In other words, I wanted the default <code>href</code>:</p> <pre><code>http://localhost/mysite/wp-includes/style.css?ver=4.1.1 </code></pre> <p>to instead be this:</p> <pre><code>http://localhost/mysite/wp-includes/style.css </code></pre>
[ { "answer_id": 183670, "author": "mrwweb", "author_id": 9844, "author_profile": "https://wordpress.stackexchange.com/users/9844", "pm_score": 5, "selected": true, "text": "<h2>Default <code>wp_enqueue_[style/script]()</code> behavior</h2>\n\n<p>The <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style#Parameters\" rel=\"noreferrer\">default value for the <code>$version</code> argument</a> of <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"noreferrer\"><code>wp_enqueue_style()</code></a> is <code>false</code>. However, that default just means that the stylesheets are given the <em>WordPress version</em> instead.</p>\n\n<h2>Solution</h2>\n\n<p>Thanks to <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"noreferrer\">\"Remove version from WordPress enqueued CSS and JS\"</a>, I learned the undocumented fact that passing in <code>null</code> as a version will remove the version altogether!</p>\n\n<h2>Example</h2>\n\n<pre><code>wp_enqueue_style( 'wpse-styles', get_template_directory_uri() . '/style.css', array(), null );\n</code></pre>\n\n<h2>Caveat Reminder</h2>\n\n<p>It's worth pointing out, as noted in the question, that this should probably only be done during development (as in the specific usecase). The version parameter helps with caching (and not caching) for site visitors and so probably should be left alone in 99% of cases.</p>\n" }, { "answer_id": 195663, "author": "Ricardo Andres", "author_id": 70093, "author_profile": "https://wordpress.stackexchange.com/users/70093", "pm_score": 3, "selected": false, "text": "<p>Thank you for your post, mrwweb. </p>\n\n<p>I found another solution to this, by creating a very simple plugin you can deactive when the site is no longer under development. </p>\n\n<pre><code>&lt;?php\n\n/*\nPlugin name: Strip WP Version in Stylesheets/Scripts\n*/\n\nfunction switch_stylesheet_src( $src, $handle ) {\n\n $src = remove_query_arg( 'ver', $src );\n return $src;\n}\nadd_filter( 'style_loader_src', 'switch_stylesheet_src', 10, 2 );\n\n?&gt;\n</code></pre>\n\n<p>I spent a couple minutes trying to find this solution. Thought I might share another option here instead of creating a new Question/Answer.</p>\n" }, { "answer_id": 375437, "author": "Solariane", "author_id": 195179, "author_profile": "https://wordpress.stackexchange.com/users/195179", "pm_score": 0, "selected": false, "text": "<p>building on the suggestion of <strong>@ricardo-andres</strong>, a code applicable anytime, most notably for resources on CDN ( like jquery ) - we get rid of this query tag on resources having a version included in their names</p>\n<pre><code>function clean_src( $src, $handle ) {\n if (preg_match('_\\d[^\\?/]*\\?_', $src))\n $src = remove_query_arg( 'ver', $src );\n return $src;\n}\nadd_filter( 'style_loader_src', 'clean_src', 10, 2 );\nadd_filter( 'script_loader_src', 'clean_src', 10, 2 );\n\n</code></pre>\n" } ]
2015/04/08
[ "https://wordpress.stackexchange.com/questions/183669", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9844/" ]
Use Case -------- I've been experimenting with Chrome's Dev Tools Workspace features. It includes the ability to edit a file directly in Dev Tools and have the saved stylesheet refresh itself (or even compile and then refresh!). However, as documented in the [StackOverflow question "Chrome's “Auto-Reload Generated CSS” not reloading page when SASS recompiles CSS"](https://stackoverflow.com/questions/20886807/chromes-auto-reload-generated-css-not-reloading-page-when-sass-recompiles-css), URL parameters on the stylesheet URL prevent Chrome from noticing the change. Desired Outcome --------------- That means that **only during development**, I wanted to remove the `?ver=X.X.X` from the normal stylesheet `<link>` output by `wp_enqueue_style()`. In other words, I wanted the default `href`: ``` http://localhost/mysite/wp-includes/style.css?ver=4.1.1 ``` to instead be this: ``` http://localhost/mysite/wp-includes/style.css ```
Default `wp_enqueue_[style/script]()` behavior ---------------------------------------------- The [default value for the `$version` argument](https://codex.wordpress.org/Function_Reference/wp_enqueue_style#Parameters) of [`wp_enqueue_style()`](https://codex.wordpress.org/Function_Reference/wp_enqueue_style) is `false`. However, that default just means that the stylesheets are given the *WordPress version* instead. Solution -------- Thanks to ["Remove version from WordPress enqueued CSS and JS"](https://codex.wordpress.org/Function_Reference/wp_enqueue_style), I learned the undocumented fact that passing in `null` as a version will remove the version altogether! Example ------- ``` wp_enqueue_style( 'wpse-styles', get_template_directory_uri() . '/style.css', array(), null ); ``` Caveat Reminder --------------- It's worth pointing out, as noted in the question, that this should probably only be done during development (as in the specific usecase). The version parameter helps with caching (and not caching) for site visitors and so probably should be left alone in 99% of cases.
183,699
<p>I have a wordpress site (lets call it site1) and another site with oauth2 (site2).</p> <p>When a new user is created, a record is created in both site1 and site2 databases with the same email as username, the typed password hashed in site2 database and a dummy (e.g. "pass") password for site1 database. Then login action authenticates with site2 database using a RESTfull API. If authentication is successful, I want to programmatically log the user in to site1 (wordpress), if not, an error object should be injected to site1.</p> <p>My question is which wordpress filter is more suitable for this, wp_authenticate_user or wp_authenticate and where should wp_signon fit in?</p>
[ { "answer_id": 183670, "author": "mrwweb", "author_id": 9844, "author_profile": "https://wordpress.stackexchange.com/users/9844", "pm_score": 5, "selected": true, "text": "<h2>Default <code>wp_enqueue_[style/script]()</code> behavior</h2>\n\n<p>The <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style#Parameters\" rel=\"noreferrer\">default value for the <code>$version</code> argument</a> of <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"noreferrer\"><code>wp_enqueue_style()</code></a> is <code>false</code>. However, that default just means that the stylesheets are given the <em>WordPress version</em> instead.</p>\n\n<h2>Solution</h2>\n\n<p>Thanks to <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"noreferrer\">\"Remove version from WordPress enqueued CSS and JS\"</a>, I learned the undocumented fact that passing in <code>null</code> as a version will remove the version altogether!</p>\n\n<h2>Example</h2>\n\n<pre><code>wp_enqueue_style( 'wpse-styles', get_template_directory_uri() . '/style.css', array(), null );\n</code></pre>\n\n<h2>Caveat Reminder</h2>\n\n<p>It's worth pointing out, as noted in the question, that this should probably only be done during development (as in the specific usecase). The version parameter helps with caching (and not caching) for site visitors and so probably should be left alone in 99% of cases.</p>\n" }, { "answer_id": 195663, "author": "Ricardo Andres", "author_id": 70093, "author_profile": "https://wordpress.stackexchange.com/users/70093", "pm_score": 3, "selected": false, "text": "<p>Thank you for your post, mrwweb. </p>\n\n<p>I found another solution to this, by creating a very simple plugin you can deactive when the site is no longer under development. </p>\n\n<pre><code>&lt;?php\n\n/*\nPlugin name: Strip WP Version in Stylesheets/Scripts\n*/\n\nfunction switch_stylesheet_src( $src, $handle ) {\n\n $src = remove_query_arg( 'ver', $src );\n return $src;\n}\nadd_filter( 'style_loader_src', 'switch_stylesheet_src', 10, 2 );\n\n?&gt;\n</code></pre>\n\n<p>I spent a couple minutes trying to find this solution. Thought I might share another option here instead of creating a new Question/Answer.</p>\n" }, { "answer_id": 375437, "author": "Solariane", "author_id": 195179, "author_profile": "https://wordpress.stackexchange.com/users/195179", "pm_score": 0, "selected": false, "text": "<p>building on the suggestion of <strong>@ricardo-andres</strong>, a code applicable anytime, most notably for resources on CDN ( like jquery ) - we get rid of this query tag on resources having a version included in their names</p>\n<pre><code>function clean_src( $src, $handle ) {\n if (preg_match('_\\d[^\\?/]*\\?_', $src))\n $src = remove_query_arg( 'ver', $src );\n return $src;\n}\nadd_filter( 'style_loader_src', 'clean_src', 10, 2 );\nadd_filter( 'script_loader_src', 'clean_src', 10, 2 );\n\n</code></pre>\n" } ]
2015/04/09
[ "https://wordpress.stackexchange.com/questions/183699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70391/" ]
I have a wordpress site (lets call it site1) and another site with oauth2 (site2). When a new user is created, a record is created in both site1 and site2 databases with the same email as username, the typed password hashed in site2 database and a dummy (e.g. "pass") password for site1 database. Then login action authenticates with site2 database using a RESTfull API. If authentication is successful, I want to programmatically log the user in to site1 (wordpress), if not, an error object should be injected to site1. My question is which wordpress filter is more suitable for this, wp\_authenticate\_user or wp\_authenticate and where should wp\_signon fit in?
Default `wp_enqueue_[style/script]()` behavior ---------------------------------------------- The [default value for the `$version` argument](https://codex.wordpress.org/Function_Reference/wp_enqueue_style#Parameters) of [`wp_enqueue_style()`](https://codex.wordpress.org/Function_Reference/wp_enqueue_style) is `false`. However, that default just means that the stylesheets are given the *WordPress version* instead. Solution -------- Thanks to ["Remove version from WordPress enqueued CSS and JS"](https://codex.wordpress.org/Function_Reference/wp_enqueue_style), I learned the undocumented fact that passing in `null` as a version will remove the version altogether! Example ------- ``` wp_enqueue_style( 'wpse-styles', get_template_directory_uri() . '/style.css', array(), null ); ``` Caveat Reminder --------------- It's worth pointing out, as noted in the question, that this should probably only be done during development (as in the specific usecase). The version parameter helps with caching (and not caching) for site visitors and so probably should be left alone in 99% of cases.
183,708
<p>I am using a page hierarchy and I want to show the title of the 2nd parents The structure is something like</p> <p>Main Page</p> <p>Main Page > Second page</p> <p>Main Page > Second page > Third page</p> <p>Main Page > Second page > Third page > Fourth page</p> <p>I want to show the Second page title in the Fouth page.</p> <p>How can i do this? Any help would be appreciated....</p>
[ { "answer_id": 183709, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 0, "selected": false, "text": "<p>The function you are looking for is <a href=\"https://codex.wordpress.org/Function_Reference/get_post_ancestors\" rel=\"nofollow noreferrer\"><code>get_post_ancestors()</code></a></p>\n<p>According to the documentation it returns an array of the ancestor page IDs</p>\n" }, { "answer_id": 183718, "author": "Shazzad", "author_id": 42967, "author_profile": "https://wordpress.stackexchange.com/users/42967", "pm_score": 2, "selected": false, "text": "<p>get_post_ancestors() returns all of the ancestors hierarchically. As you only want to display the 2nd level post title on 4th post page, you can do something like -</p>\n\n<pre><code>global $post;\n\n$parents = get_post_ancestors( get_the_ID() );\n\nif( count($parents) == 4 ){\n\n // ancestor1 = 1st parent, ancestor2 = second.\n echo get_the_title($parents['1']); // index starts from 0, 1 = 2nd item\n}\n</code></pre>\n" } ]
2015/04/09
[ "https://wordpress.stackexchange.com/questions/183708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70400/" ]
I am using a page hierarchy and I want to show the title of the 2nd parents The structure is something like Main Page Main Page > Second page Main Page > Second page > Third page Main Page > Second page > Third page > Fourth page I want to show the Second page title in the Fouth page. How can i do this? Any help would be appreciated....
get\_post\_ancestors() returns all of the ancestors hierarchically. As you only want to display the 2nd level post title on 4th post page, you can do something like - ``` global $post; $parents = get_post_ancestors( get_the_ID() ); if( count($parents) == 4 ){ // ancestor1 = 1st parent, ancestor2 = second. echo get_the_title($parents['1']); // index starts from 0, 1 = 2nd item } ```
183,720
<p>I'm having some issues sharing the user sessions across two installs. </p> <p>(a) site on <a href="http://stolenmx.com" rel="nofollow">http://stolenmx.com</a> (b) site on <a href="http://arcade.stolenmx.com" rel="nofollow">http://arcade.stolenmx.com</a></p> <p>I have installed B in the same database as A and I have defined the user and user_meta tables so I am sharing user data and users etc but I can't seem to bridge the sessions. </p> <p>I have tried using cookies a few different ways but nothing works. </p> <p>This is what I'm using in (b) wp-config at the moment with no effect, </p> <pre><code>define('COOKIE_DOMAIN', 'www.stolenmx.com'); define('COOKIEPATH', '/'); </code></pre> <p>does anyone know how to get this working? </p> <p>I'm actually using UserPro on site (a) to manage registration and login and I have wp-login.php disabled. Could this be why cookie isn't working cause UserPro saves the cookie elsewhere or just simply doesn't use one? </p>
[ { "answer_id": 183750, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": false, "text": "<p>You also need to define a matching <code>COOKIEHASH</code> for both sites - a random 32 bit string will do.</p>\n\n<p>By default, <code>COOKIEHASH</code> is an MD5 hash of the site URL, and is used to generate the default names for all authentication-related cookies. Hence why, at the moment, your cross-domain login isn't working (the names of the cookies aren't consistent, as <code>COOKIEHASH</code> will be different for each site).</p>\n\n<p>See <a href=\"http://wpseek.com/function/wp_cookie_constants/\" rel=\"noreferrer\"><code>wp_cookie_constants()</code></a> for more information.</p>\n\n<p>So to recap, your <code>wp-config.php</code> for both sites should look like:</p>\n\n<pre><code>define( 'COOKIE_DOMAIN', '.stolenmx.com' ); // Dot prefix\ndefine( 'COOKIEPATH', '/' );\ndefine( 'COOKIEHASH', md5( 'stolenmx.com' ) );\n\ndefine( 'CUSTOM_USER_TABLE', 'wp_users' );\ndefine( 'CUSTOM_USER_META_TABLE', 'wp_usermeta' );\n</code></pre>\n" }, { "answer_id": 254190, "author": "TEKFused", "author_id": 111892, "author_profile": "https://wordpress.stackexchange.com/users/111892", "pm_score": 1, "selected": false, "text": "<p>In addition to TheDeadMedic's answer, both sites must share the same keys and salts in the wp-config.php files (I replaced the string with four zeros):</p>\n\n<pre><code>define('AUTH_KEY', '0000');\ndefine('SECURE_AUTH_KEY', '0000');\ndefine('LOGGED_IN_KEY', '0000');\ndefine('NONCE_KEY', '0000');\ndefine('AUTH_SALT', '0000');\ndefine('SECURE_AUTH_SALT', '0000');\ndefine('LOGGED_IN_SALT', '0000');\ndefine('NONCE_SALT', '0000');\n</code></pre>\n\n<p>I created a blog post about this which has more details: <a href=\"https://www.tekfused.com/wordpress/sharing-login-cookies-among-wordpress-installs/\" rel=\"nofollow noreferrer\">https://www.tekfused.com/wordpress/sharing-login-cookies-among-wordpress-installs/</a></p>\n" } ]
2015/04/09
[ "https://wordpress.stackexchange.com/questions/183720", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70406/" ]
I'm having some issues sharing the user sessions across two installs. (a) site on <http://stolenmx.com> (b) site on <http://arcade.stolenmx.com> I have installed B in the same database as A and I have defined the user and user\_meta tables so I am sharing user data and users etc but I can't seem to bridge the sessions. I have tried using cookies a few different ways but nothing works. This is what I'm using in (b) wp-config at the moment with no effect, ``` define('COOKIE_DOMAIN', 'www.stolenmx.com'); define('COOKIEPATH', '/'); ``` does anyone know how to get this working? I'm actually using UserPro on site (a) to manage registration and login and I have wp-login.php disabled. Could this be why cookie isn't working cause UserPro saves the cookie elsewhere or just simply doesn't use one?
You also need to define a matching `COOKIEHASH` for both sites - a random 32 bit string will do. By default, `COOKIEHASH` is an MD5 hash of the site URL, and is used to generate the default names for all authentication-related cookies. Hence why, at the moment, your cross-domain login isn't working (the names of the cookies aren't consistent, as `COOKIEHASH` will be different for each site). See [`wp_cookie_constants()`](http://wpseek.com/function/wp_cookie_constants/) for more information. So to recap, your `wp-config.php` for both sites should look like: ``` define( 'COOKIE_DOMAIN', '.stolenmx.com' ); // Dot prefix define( 'COOKIEPATH', '/' ); define( 'COOKIEHASH', md5( 'stolenmx.com' ) ); define( 'CUSTOM_USER_TABLE', 'wp_users' ); define( 'CUSTOM_USER_META_TABLE', 'wp_usermeta' ); ```
183,752
<p>It's easy enough to find help with admin_notices which:</p> <ul> <li>show permanently in the admin screen</li> <li>only show when a particular kind of page is shown</li> <li>show until the user dismisses it</li> </ul> <p>But I can't find help with creating a message which shows until the user leaves that particular page. ie. <em>exactly</em> what WordPress shows routinely with its <code>Post updated. View post.</code> message.</p> <p><img src="https://i.stack.imgur.com/ryQCA.jpg" alt="enter image description here"></p> <p>You only see that message up until you decide to move on, you don't see it again, and you don't have to actively dismiss it.</p> <p>Here's what we've got so far (this creates a permanent message, obviously this is far from the unobtrusive message we're looking for):</p> <pre><code>function my_admin_notice() { ?&gt; &lt;div class="updated"&gt; &lt;p&gt;&lt;?php _e( 'Updated!', 'my-text-domain' ); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } add_action( 'admin_notices', 'my_admin_notice' ); </code></pre>
[ { "answer_id": 183775, "author": "Mike", "author_id": 69112, "author_profile": "https://wordpress.stackexchange.com/users/69112", "pm_score": 0, "selected": false, "text": "<p>Not entirely sure I understand what you are doing but would it be feasible to add an option (add_option) during the CPT post publish and then check for the existance of that option and if there, display the notice. Within the function you have to display the notice, you could also remove the option to stop it showing again.</p>\n\n<p>Alternatively add user meta and remove it when the notice is displayed - best option if you are only targeting a single user</p>\n" }, { "answer_id": 184941, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>This answer assumes you want to do this on a post edit screen.</p>\n\n<h2>Explanation:</h2>\n\n<p>Basically, you need some conditions:</p>\n\n<ol>\n<li><p>To address a specific admin screen:</p>\n\n<ul>\n<li>Used for this: <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow noreferrer\"><code>get_current_screen()</code></a> function</li>\n</ul></li>\n<li><p>To only show the message until the specific page has been left: </p>\n\n<ul>\n<li>Used for this: <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\"><code>add_query_arg()</code></a> function </li>\n<li>And: <a href=\"https://developer.wordpress.org/reference/hooks/redirect_post_location/\" rel=\"nofollow noreferrer\"><code>redirect_post_location</code></a> hook </li>\n</ul></li>\n</ol>\n\n<p>Additionally - of course - usage of the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices\" rel=\"nofollow noreferrer\"><code>admin_notices</code></a> hook. And - for below example - the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>save_post</code></a> hook.</p>\n\n<h2>Example:</h2>\n\n<pre><code>function wpse183752_the_admin_notice() {\n // get screen information\n $screen = get_current_screen();\n // screen condition \n // TODO: change to the screen you want to address\n if ( $screen-&gt;id != 'post' ) {\n return;\n }\n // query variable condition\n if ( ! isset( $_GET[ 'the_message' ] ) || $_GET[ 'the_message' ] != 'show' ) {\n return;\n }\n ?&gt;\n &lt;div class=\"updated\"&gt;\n &lt;p&gt;\n &lt;?php _e( 'The Message', 'the-text-domain' ); ?&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n}\nadd_action( 'admin_notices', 'wpse183752_the_admin_notice' );\n\nfunction wpse183752_the_message( $old_query_string ) {\n // add the new query variable\n $new_query_string = add_query_arg( 'the_message', 'show', $old_query_string );\n // return the new query string\n return $new_query_string;\n}\n\nfunction wpse183752_set_message_variable() {\n // usage of wpse183752_the_message() callback with redirect_post_location\n // to setup the query variable on a hook, here save_post\n add_filter( 'redirect_post_location', 'wpse183752_the_message' );\n}\n// TODO: change to the hook you need\nadd_action( 'save_post', 'wpse183752_set_message_variable' );\n</code></pre>\n\n<h2>Note:</h2>\n\n<p>Above example is pretty much a generic one. It addresses the post edit screen of the built-in post type post. You have to change some things to make it work for you, see the ToDo's in above example. As you <a href=\"https://wordpress.stackexchange.com/questions/183752/how-to-make-an-admin-notices-message-that-disappears-once-the-user-leaves-that-p#comment268253_183752\">said yourself</a> you probably want to address <code>publish_mycpt</code>, which is a <code>{status}_{post_type}</code> type of hook, see <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Codex: Post Status Transitions</a> for more information.</p>\n" }, { "answer_id": 184943, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 3, "selected": false, "text": "<p>The short answer is: <strong>Use Query Strings.</strong></p>\n\n<p>If you notice in the address bar immediately after you publish a Post... You will see something similar to this: <code>domain.com/wp-admin/post.php?post=4935&amp;action=edit&amp;message=6</code></p>\n\n<p><strong>There's a few different Query Variables:</strong></p>\n\n<ol>\n<li><code>post</code> contains the ID of the Post being edited.</li>\n<li><code>action</code> is saying we're currently \"editing\" the Post.</li>\n<li><code>message</code> refers to what Admin Notice should be displayed depending on what was done to the Post.</li>\n</ol>\n\n<p>Look <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Example\">here</a> for an example on seeing the default Post Type messages and how to customize the messages (a/k/a Admin notices) specifically for your Custom Post Type.</p>\n\n<p>The above example is relative to a Custom Post Type and WordPress handles all the conditionals for you. All you have to do is customize the messages.</p>\n\n<p>If you wanted to do this on a custom settings page for your plugin for example. You would need to take several steps to accomplish the same thing.</p>\n\n<p><strong>In a nut shell:</strong></p>\n\n<p>Send the user to your custom settings page WITH an extra Query Variable appended to the URL.</p>\n\n<p>Hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices\"><code>admin_notices</code></a>. </p>\n\n<p>Inside the callback function you specify for the <code>admin_notices</code> hook, have an array of messages, where they array key will match the value of your Query Variable and the array value will be the appropriate message.</p>\n\n<p>Check to see if your Query Variable is present. (Be sure to check that the user is specifically on your plugin's setting page using: <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\"><code>get_current_screen();</code></a> - otherwise you'll be checking globally across every admin page.)</p>\n\n<p>Perform additional conditional checks for the different possible values of your Query Variable and display the appropriate Admin Notice depending on the value of your Query Variable.</p>\n\n<p><strong>So basically:</strong></p>\n\n<ul>\n<li>Check if the user is on your plugin's settings page.</li>\n<li>Check if your Query Variable is present.</li>\n<li>Check if the value of your Query Variable matches that of something\nexpected.</li>\n<li>Select appropriate message depending on the expected value matched\nfrom your Query Variable with an array key in your messages array.</li>\n<li>Display Admin Notice with message matched from messages array key.</li>\n</ul>\n" } ]
2015/04/09
[ "https://wordpress.stackexchange.com/questions/183752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/875/" ]
It's easy enough to find help with admin\_notices which: * show permanently in the admin screen * only show when a particular kind of page is shown * show until the user dismisses it But I can't find help with creating a message which shows until the user leaves that particular page. ie. *exactly* what WordPress shows routinely with its `Post updated. View post.` message. ![enter image description here](https://i.stack.imgur.com/ryQCA.jpg) You only see that message up until you decide to move on, you don't see it again, and you don't have to actively dismiss it. Here's what we've got so far (this creates a permanent message, obviously this is far from the unobtrusive message we're looking for): ``` function my_admin_notice() { ?> <div class="updated"> <p><?php _e( 'Updated!', 'my-text-domain' ); ?></p> </div> <?php } add_action( 'admin_notices', 'my_admin_notice' ); ```
The short answer is: **Use Query Strings.** If you notice in the address bar immediately after you publish a Post... You will see something similar to this: `domain.com/wp-admin/post.php?post=4935&action=edit&message=6` **There's a few different Query Variables:** 1. `post` contains the ID of the Post being edited. 2. `action` is saying we're currently "editing" the Post. 3. `message` refers to what Admin Notice should be displayed depending on what was done to the Post. Look [here](https://codex.wordpress.org/Function_Reference/register_post_type#Example) for an example on seeing the default Post Type messages and how to customize the messages (a/k/a Admin notices) specifically for your Custom Post Type. The above example is relative to a Custom Post Type and WordPress handles all the conditionals for you. All you have to do is customize the messages. If you wanted to do this on a custom settings page for your plugin for example. You would need to take several steps to accomplish the same thing. **In a nut shell:** Send the user to your custom settings page WITH an extra Query Variable appended to the URL. Hook into [`admin_notices`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices). Inside the callback function you specify for the `admin_notices` hook, have an array of messages, where they array key will match the value of your Query Variable and the array value will be the appropriate message. Check to see if your Query Variable is present. (Be sure to check that the user is specifically on your plugin's setting page using: [`get_current_screen();`](https://codex.wordpress.org/Function_Reference/get_current_screen) - otherwise you'll be checking globally across every admin page.) Perform additional conditional checks for the different possible values of your Query Variable and display the appropriate Admin Notice depending on the value of your Query Variable. **So basically:** * Check if the user is on your plugin's settings page. * Check if your Query Variable is present. * Check if the value of your Query Variable matches that of something expected. * Select appropriate message depending on the expected value matched from your Query Variable with an array key in your messages array. * Display Admin Notice with message matched from messages array key.
183,828
<p>I try to remove metaboxes from non-admin for posts, pages, and add products page (WooCommerce), and this my code:</p> <pre><code>// ciusART Remove Metaboxes add_action('admin_head', 'remove_metaboxes_for_non_admin'); function remove_metaboxes_for_non_admin(){ if (!is_admin()){ // only remove for non admins remove_meta_box('wpseo_meta', 'post', 'advanced'); remove_meta_box('wpseo_meta', 'page', 'advanced'); remove_meta_box('wpseo_meta', 'products', 'advanced'); remove_meta_box('acf_acf_extended-footer', 'post', 'advanced'); remove_meta_box('acf_acf_extended-footer', 'page', 'advanced'); remove_meta_box('acf_acf_extended-footer', 'products', 'advanced'); remove_meta_box('acf_acf_layout-settings', 'post', 'advanced'); remove_meta_box('acf_acf_layout-settings', 'page', 'advanced'); remove_meta_box('acf_acf_layout-settings', 'products', 'advanced'); remove_meta_box('acf_acf_product-settings', 'post', 'advanced'); remove_meta_box('acf_acf_product-settings', 'page', 'advanced'); remove_meta_box('acf_acf_product-settings', 'products', 'advanced'); remove_meta_box('acf_acf_sidebar', 'post', 'advanced'); remove_meta_box('acf_acf_sidebar', 'page', 'advanced'); remove_meta_box('acf_acf_sidebar', 'products', 'advanced'); remove_meta_box('acf_acf_size-guide', 'post', 'advanced'); remove_meta_box('acf_acf_size-guide', 'page', 'advanced'); remove_meta_box('acf_acf_size-guide', 'products', 'advanced'); remove_meta_box('acf_acf_header-image-background', 'post', 'advanced'); remove_meta_box('acf_acf_header-image-background', 'page', 'advanced'); remove_meta_box('acf_acf_header-image-background', 'products', 'advanced'); remove_meta_box('acf_acf_footer-image-background', 'post', 'advanced'); remove_meta_box('acf_acf_footer-image-background', 'page', 'advanced'); remove_meta_box('acf_acf_footer-image-background', 'products', 'advanced'); remove_meta_box('acf_acf_extended-footer-image-background', 'post', 'advanced'); remove_meta_box('acf_acf_extended-footer-image-background', 'page', 'advanced'); remove_meta_box('acf_acf_extended-footer-image-background', 'products', 'advanced'); // continue adding as necessary } } </code></pre> <p>But this code not work, can you help me...</p> <p>Thanks...</p>
[ { "answer_id": 183829, "author": "GastroGeek", "author_id": 70445, "author_profile": "https://wordpress.stackexchange.com/users/70445", "pm_score": 1, "selected": false, "text": "<p>I don't think this will ever fire....</p>\n\n<p>Is_admin() detects admin UI not admin priveleges... Try:</p>\n\n<pre><code>if (is_admin()) : \nfunction my_remove_meta_boxes() { \nif( !current_user_can('manage_options') ) { \n remove_meta_box(...);\n}}\nadd_action( 'admin_menu', 'my_remove_meta_boxes' );\nendif;\n</code></pre>\n" }, { "answer_id": 183830, "author": "Bhavik Patel", "author_id": 26471, "author_profile": "https://wordpress.stackexchange.com/users/26471", "pm_score": 0, "selected": false, "text": "<p>Please Change !is_admin() current user is administrator , is_admin() not check user but they check admin panel area </p>\n\n<p>please change in your code </p>\n\n<pre> add_action('admin_head', 'remove_metaboxes_for_non_admin');\nfunction remove_metaboxes_for_non_admin(){\n global $current_user;\n if ($current_user->role[0]!='administrator')\n {\n remove_meta_box('wpseo_meta', 'post', 'advanced');\n remove_meta_box('wpseo_meta', 'page', 'advanced');\n remove_meta_box('wpseo_meta', 'products', 'advanced');\n remove_meta_box('acf_acf_extended-footer', 'post', 'advanced');\n remove_meta_box('acf_acf_extended-footer', 'page', 'advanced');\n remove_meta_box('acf_acf_extended-footer', 'products', 'advanced');\n remove_meta_box('acf_acf_layout-settings', 'post', 'advanced');\n remove_meta_box('acf_acf_layout-settings', 'page', 'advanced');\n remove_meta_box('acf_acf_layout-settings', 'products', 'advanced');\n remove_meta_box('acf_acf_product-settings', 'post', 'advanced');\n remove_meta_box('acf_acf_product-settings', 'page', 'advanced');\n remove_meta_box('acf_acf_product-settings', 'products', 'advanced');\n remove_meta_box('acf_acf_sidebar', 'post', 'advanced');\n remove_meta_box('acf_acf_sidebar', 'page', 'advanced');\n remove_meta_box('acf_acf_sidebar', 'products', 'advanced');\n remove_meta_box('acf_acf_size-guide', 'post', 'advanced');\n remove_meta_box('acf_acf_size-guide', 'page', 'advanced');\n remove_meta_box('acf_acf_size-guide', 'products', 'advanced');\n remove_meta_box('acf_acf_header-image-background', 'post', 'advanced');\n remove_meta_box('acf_acf_header-image-background', 'page', 'advanced');\n remove_meta_box('acf_acf_header-image-background', 'products', 'advanced');\n remove_meta_box('acf_acf_footer-image-background', 'post', 'advanced');\n remove_meta_box('acf_acf_footer-image-background', 'page', 'advanced');\n remove_meta_box('acf_acf_footer-image-background', 'products', 'advanced');\n remove_meta_box('acf_acf_extended-footer-image-background', 'post', 'advanced');\n remove_meta_box('acf_acf_extended-footer-image-background', 'page', 'advanced');\n remove_meta_box('acf_acf_extended-footer-image-background', 'products', 'advanced');\n // continue adding as necessary\n }\n}\n</pre>\n" } ]
2015/04/10
[ "https://wordpress.stackexchange.com/questions/183828", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68053/" ]
I try to remove metaboxes from non-admin for posts, pages, and add products page (WooCommerce), and this my code: ``` // ciusART Remove Metaboxes add_action('admin_head', 'remove_metaboxes_for_non_admin'); function remove_metaboxes_for_non_admin(){ if (!is_admin()){ // only remove for non admins remove_meta_box('wpseo_meta', 'post', 'advanced'); remove_meta_box('wpseo_meta', 'page', 'advanced'); remove_meta_box('wpseo_meta', 'products', 'advanced'); remove_meta_box('acf_acf_extended-footer', 'post', 'advanced'); remove_meta_box('acf_acf_extended-footer', 'page', 'advanced'); remove_meta_box('acf_acf_extended-footer', 'products', 'advanced'); remove_meta_box('acf_acf_layout-settings', 'post', 'advanced'); remove_meta_box('acf_acf_layout-settings', 'page', 'advanced'); remove_meta_box('acf_acf_layout-settings', 'products', 'advanced'); remove_meta_box('acf_acf_product-settings', 'post', 'advanced'); remove_meta_box('acf_acf_product-settings', 'page', 'advanced'); remove_meta_box('acf_acf_product-settings', 'products', 'advanced'); remove_meta_box('acf_acf_sidebar', 'post', 'advanced'); remove_meta_box('acf_acf_sidebar', 'page', 'advanced'); remove_meta_box('acf_acf_sidebar', 'products', 'advanced'); remove_meta_box('acf_acf_size-guide', 'post', 'advanced'); remove_meta_box('acf_acf_size-guide', 'page', 'advanced'); remove_meta_box('acf_acf_size-guide', 'products', 'advanced'); remove_meta_box('acf_acf_header-image-background', 'post', 'advanced'); remove_meta_box('acf_acf_header-image-background', 'page', 'advanced'); remove_meta_box('acf_acf_header-image-background', 'products', 'advanced'); remove_meta_box('acf_acf_footer-image-background', 'post', 'advanced'); remove_meta_box('acf_acf_footer-image-background', 'page', 'advanced'); remove_meta_box('acf_acf_footer-image-background', 'products', 'advanced'); remove_meta_box('acf_acf_extended-footer-image-background', 'post', 'advanced'); remove_meta_box('acf_acf_extended-footer-image-background', 'page', 'advanced'); remove_meta_box('acf_acf_extended-footer-image-background', 'products', 'advanced'); // continue adding as necessary } } ``` But this code not work, can you help me... Thanks...
I don't think this will ever fire.... Is\_admin() detects admin UI not admin priveleges... Try: ``` if (is_admin()) : function my_remove_meta_boxes() { if( !current_user_can('manage_options') ) { remove_meta_box(...); }} add_action( 'admin_menu', 'my_remove_meta_boxes' ); endif; ```
183,898
<p>How to make below code safe from sql injection ... I am working in wordpress. global $wpdb;</p> <pre><code> if($wpdb-&gt;insert( 'votes', array( 'votes' =&gt; $votes, 'competition' =&gt; $competition, 'uid' =&gt; $uid ) ) == false) wp_die('Database Insertion failed'); else echo 'Database insertion successful&lt;p /&gt;'; </code></pre>
[ { "answer_id": 183899, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p><code>wpdb::insert</code> already protects against SQL injection, it's a wrapper for <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks\" rel=\"nofollow\"><code>wpdb::prepare</code></a></p>\n\n<p>For <code>insert()</code>, you can pass a third \"formats\" argument for extra sanitization:</p>\n\n<pre><code>$wpdb-&gt;insert(\n 'votes',\n array(\n 'votes' =&gt; $votes,\n 'competition' =&gt; $competition,\n 'uid' =&gt; $uid\n ),\n array(\n '%s', // $votes will be parsed as a string\n '%s', // $competition will be parsed as a string\n '%d', // $uid will be parsed as an integer\n )\n);\n</code></pre>\n" }, { "answer_id": 183900, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>The insert method of <code>$wpdb</code> already scapes the data taking care of SQL injection. What you should worry about is about data sanitization and validation.</p>\n\n<p>For exmpla:</p>\n\n<p><strong>Sanitization</strong></p>\n\n<p>What type of data do you accept in <code>$votes</code>? A integer value? If so, be sure <code>$votes</code> contains a integer value. You cuold do it, for exmaple, using <a href=\"http://php.net/manual/es/function.intval.php\" rel=\"nofollow\"><code>intval</code> function</a> from PHP. This is sanitization.</p>\n\n<pre><code>$votes = intval( $votes );\n</code></pre>\n\n<p>What type of data do you accept in <code>$competition</code>? Any string with no HTML, tabs or line breaks, ? If so, be sure <code>$competition</code> contains a string value, strip HTML tags and remove tabs and line break; you could do it, for exmaple, using <a href=\"https://codex.wordpress.org/Function_Reference/sanitize_text_field\" rel=\"nofollow\"><code>sanitize_text_field</code> function</a> from WordPress. This is also sanitization.</p>\n\n<pre><code>$competition = sanitize_text_field( $competition );\n</code></pre>\n\n<p><strong>Data validation</strong></p>\n\n<p>What value do you accept in <code>$votes</code>? From 0 to 100, including both? If so, you could check the value of <code>$votes</code>:</p>\n\n<pre><code>if( $votes &gt;= 0 &amp;&amp; $votes &lt;= 100 ) {\n\n // Value is correct\n\n} else {\n\n // Value is not correct. Maybe abort the process?\n\n}\n</code></pre>\n\n<p>Do you have a list of valid competitions? Check the value of <code>$competition</code> against it:</p>\n\n<pre><code>$valid_competitions = array( 'competition1', 'competition2', 'competition3' );\n\nif( in_array( $competition, $valid_competitions ) ) {\n\n // Value is correct\n\n} else {\n\n // Value is not correct. Maybe abort the process?\n\n}\n</code></pre>\n\n<p>Do the same process with <code>$uid</code>.</p>\n\n<p>Once you have santize and validate your variables, you are ready to pass them to <code>$wpdb-&gt;insert</code> method like this (with the third parameter performs a basic sanitization, you can avoid previous sanitization if this is enough for your situation):</p>\n\n<pre><code>$wpdb-&gt;insert(\n 'votes',\n array(\n 'votes' =&gt; $votes,\n 'competition' =&gt; $competition,\n 'uid' =&gt; $uid\n ),\n array(\n '%d', // integer data type for $votes\n '%s', // string data type for $competition\n '%d', // integer data type for $uid\n )\n);\n</code></pre>\n" } ]
2015/04/11
[ "https://wordpress.stackexchange.com/questions/183898", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67938/" ]
How to make below code safe from sql injection ... I am working in wordpress. global $wpdb; ``` if($wpdb->insert( 'votes', array( 'votes' => $votes, 'competition' => $competition, 'uid' => $uid ) ) == false) wp_die('Database Insertion failed'); else echo 'Database insertion successful<p />'; ```
The insert method of `$wpdb` already scapes the data taking care of SQL injection. What you should worry about is about data sanitization and validation. For exmpla: **Sanitization** What type of data do you accept in `$votes`? A integer value? If so, be sure `$votes` contains a integer value. You cuold do it, for exmaple, using [`intval` function](http://php.net/manual/es/function.intval.php) from PHP. This is sanitization. ``` $votes = intval( $votes ); ``` What type of data do you accept in `$competition`? Any string with no HTML, tabs or line breaks, ? If so, be sure `$competition` contains a string value, strip HTML tags and remove tabs and line break; you could do it, for exmaple, using [`sanitize_text_field` function](https://codex.wordpress.org/Function_Reference/sanitize_text_field) from WordPress. This is also sanitization. ``` $competition = sanitize_text_field( $competition ); ``` **Data validation** What value do you accept in `$votes`? From 0 to 100, including both? If so, you could check the value of `$votes`: ``` if( $votes >= 0 && $votes <= 100 ) { // Value is correct } else { // Value is not correct. Maybe abort the process? } ``` Do you have a list of valid competitions? Check the value of `$competition` against it: ``` $valid_competitions = array( 'competition1', 'competition2', 'competition3' ); if( in_array( $competition, $valid_competitions ) ) { // Value is correct } else { // Value is not correct. Maybe abort the process? } ``` Do the same process with `$uid`. Once you have santize and validate your variables, you are ready to pass them to `$wpdb->insert` method like this (with the third parameter performs a basic sanitization, you can avoid previous sanitization if this is enough for your situation): ``` $wpdb->insert( 'votes', array( 'votes' => $votes, 'competition' => $competition, 'uid' => $uid ), array( '%d', // integer data type for $votes '%s', // string data type for $competition '%d', // integer data type for $uid ) ); ```
183,903
<p>This is about running code on wordpress . The given code runs properly outside wordpress but when I put it on theme functions file it does not do anything. </p> <pre><code>ob_start(); require('dynamic-css.php'); $content = ob_get_contents(); ob_end_clean(); $f = fopen("custom.css", "w"); fwrite($f, $content); fclose($f); </code></pre> <p>I think I have to put this inside custom function and add hook then. </p>
[ { "answer_id": 183899, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p><code>wpdb::insert</code> already protects against SQL injection, it's a wrapper for <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks\" rel=\"nofollow\"><code>wpdb::prepare</code></a></p>\n\n<p>For <code>insert()</code>, you can pass a third \"formats\" argument for extra sanitization:</p>\n\n<pre><code>$wpdb-&gt;insert(\n 'votes',\n array(\n 'votes' =&gt; $votes,\n 'competition' =&gt; $competition,\n 'uid' =&gt; $uid\n ),\n array(\n '%s', // $votes will be parsed as a string\n '%s', // $competition will be parsed as a string\n '%d', // $uid will be parsed as an integer\n )\n);\n</code></pre>\n" }, { "answer_id": 183900, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>The insert method of <code>$wpdb</code> already scapes the data taking care of SQL injection. What you should worry about is about data sanitization and validation.</p>\n\n<p>For exmpla:</p>\n\n<p><strong>Sanitization</strong></p>\n\n<p>What type of data do you accept in <code>$votes</code>? A integer value? If so, be sure <code>$votes</code> contains a integer value. You cuold do it, for exmaple, using <a href=\"http://php.net/manual/es/function.intval.php\" rel=\"nofollow\"><code>intval</code> function</a> from PHP. This is sanitization.</p>\n\n<pre><code>$votes = intval( $votes );\n</code></pre>\n\n<p>What type of data do you accept in <code>$competition</code>? Any string with no HTML, tabs or line breaks, ? If so, be sure <code>$competition</code> contains a string value, strip HTML tags and remove tabs and line break; you could do it, for exmaple, using <a href=\"https://codex.wordpress.org/Function_Reference/sanitize_text_field\" rel=\"nofollow\"><code>sanitize_text_field</code> function</a> from WordPress. This is also sanitization.</p>\n\n<pre><code>$competition = sanitize_text_field( $competition );\n</code></pre>\n\n<p><strong>Data validation</strong></p>\n\n<p>What value do you accept in <code>$votes</code>? From 0 to 100, including both? If so, you could check the value of <code>$votes</code>:</p>\n\n<pre><code>if( $votes &gt;= 0 &amp;&amp; $votes &lt;= 100 ) {\n\n // Value is correct\n\n} else {\n\n // Value is not correct. Maybe abort the process?\n\n}\n</code></pre>\n\n<p>Do you have a list of valid competitions? Check the value of <code>$competition</code> against it:</p>\n\n<pre><code>$valid_competitions = array( 'competition1', 'competition2', 'competition3' );\n\nif( in_array( $competition, $valid_competitions ) ) {\n\n // Value is correct\n\n} else {\n\n // Value is not correct. Maybe abort the process?\n\n}\n</code></pre>\n\n<p>Do the same process with <code>$uid</code>.</p>\n\n<p>Once you have santize and validate your variables, you are ready to pass them to <code>$wpdb-&gt;insert</code> method like this (with the third parameter performs a basic sanitization, you can avoid previous sanitization if this is enough for your situation):</p>\n\n<pre><code>$wpdb-&gt;insert(\n 'votes',\n array(\n 'votes' =&gt; $votes,\n 'competition' =&gt; $competition,\n 'uid' =&gt; $uid\n ),\n array(\n '%d', // integer data type for $votes\n '%s', // string data type for $competition\n '%d', // integer data type for $uid\n )\n);\n</code></pre>\n" } ]
2015/04/11
[ "https://wordpress.stackexchange.com/questions/183903", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30937/" ]
This is about running code on wordpress . The given code runs properly outside wordpress but when I put it on theme functions file it does not do anything. ``` ob_start(); require('dynamic-css.php'); $content = ob_get_contents(); ob_end_clean(); $f = fopen("custom.css", "w"); fwrite($f, $content); fclose($f); ``` I think I have to put this inside custom function and add hook then.
The insert method of `$wpdb` already scapes the data taking care of SQL injection. What you should worry about is about data sanitization and validation. For exmpla: **Sanitization** What type of data do you accept in `$votes`? A integer value? If so, be sure `$votes` contains a integer value. You cuold do it, for exmaple, using [`intval` function](http://php.net/manual/es/function.intval.php) from PHP. This is sanitization. ``` $votes = intval( $votes ); ``` What type of data do you accept in `$competition`? Any string with no HTML, tabs or line breaks, ? If so, be sure `$competition` contains a string value, strip HTML tags and remove tabs and line break; you could do it, for exmaple, using [`sanitize_text_field` function](https://codex.wordpress.org/Function_Reference/sanitize_text_field) from WordPress. This is also sanitization. ``` $competition = sanitize_text_field( $competition ); ``` **Data validation** What value do you accept in `$votes`? From 0 to 100, including both? If so, you could check the value of `$votes`: ``` if( $votes >= 0 && $votes <= 100 ) { // Value is correct } else { // Value is not correct. Maybe abort the process? } ``` Do you have a list of valid competitions? Check the value of `$competition` against it: ``` $valid_competitions = array( 'competition1', 'competition2', 'competition3' ); if( in_array( $competition, $valid_competitions ) ) { // Value is correct } else { // Value is not correct. Maybe abort the process? } ``` Do the same process with `$uid`. Once you have santize and validate your variables, you are ready to pass them to `$wpdb->insert` method like this (with the third parameter performs a basic sanitization, you can avoid previous sanitization if this is enough for your situation): ``` $wpdb->insert( 'votes', array( 'votes' => $votes, 'competition' => $competition, 'uid' => $uid ), array( '%d', // integer data type for $votes '%s', // string data type for $competition '%d', // integer data type for $uid ) ); ```
183,914
<p>Each of these bits of code work separately in category.php, but when I use both together, the first one is ignored. Can someone tell me how to combine them into a single piece of code, or at least make them play nicely together?</p> <pre><code>&lt;?php if (is_category()) { $posts = query_posts( $query_string . '&amp;orderby=title&amp;order=asc&amp;posts_per_page=18' ); } ?&gt; &lt;?php $current_cat = intval( get_query_var('cat') ); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args=array( 'category__and' =&gt; array($current_cat), 'paged' =&gt; $paged, 'post_type' =&gt; 'post', 'caller_get_posts'=&gt; 1 ); query_posts($args); ?&gt; </code></pre>
[ { "answer_id": 183899, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p><code>wpdb::insert</code> already protects against SQL injection, it's a wrapper for <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks\" rel=\"nofollow\"><code>wpdb::prepare</code></a></p>\n\n<p>For <code>insert()</code>, you can pass a third \"formats\" argument for extra sanitization:</p>\n\n<pre><code>$wpdb-&gt;insert(\n 'votes',\n array(\n 'votes' =&gt; $votes,\n 'competition' =&gt; $competition,\n 'uid' =&gt; $uid\n ),\n array(\n '%s', // $votes will be parsed as a string\n '%s', // $competition will be parsed as a string\n '%d', // $uid will be parsed as an integer\n )\n);\n</code></pre>\n" }, { "answer_id": 183900, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>The insert method of <code>$wpdb</code> already scapes the data taking care of SQL injection. What you should worry about is about data sanitization and validation.</p>\n\n<p>For exmpla:</p>\n\n<p><strong>Sanitization</strong></p>\n\n<p>What type of data do you accept in <code>$votes</code>? A integer value? If so, be sure <code>$votes</code> contains a integer value. You cuold do it, for exmaple, using <a href=\"http://php.net/manual/es/function.intval.php\" rel=\"nofollow\"><code>intval</code> function</a> from PHP. This is sanitization.</p>\n\n<pre><code>$votes = intval( $votes );\n</code></pre>\n\n<p>What type of data do you accept in <code>$competition</code>? Any string with no HTML, tabs or line breaks, ? If so, be sure <code>$competition</code> contains a string value, strip HTML tags and remove tabs and line break; you could do it, for exmaple, using <a href=\"https://codex.wordpress.org/Function_Reference/sanitize_text_field\" rel=\"nofollow\"><code>sanitize_text_field</code> function</a> from WordPress. This is also sanitization.</p>\n\n<pre><code>$competition = sanitize_text_field( $competition );\n</code></pre>\n\n<p><strong>Data validation</strong></p>\n\n<p>What value do you accept in <code>$votes</code>? From 0 to 100, including both? If so, you could check the value of <code>$votes</code>:</p>\n\n<pre><code>if( $votes &gt;= 0 &amp;&amp; $votes &lt;= 100 ) {\n\n // Value is correct\n\n} else {\n\n // Value is not correct. Maybe abort the process?\n\n}\n</code></pre>\n\n<p>Do you have a list of valid competitions? Check the value of <code>$competition</code> against it:</p>\n\n<pre><code>$valid_competitions = array( 'competition1', 'competition2', 'competition3' );\n\nif( in_array( $competition, $valid_competitions ) ) {\n\n // Value is correct\n\n} else {\n\n // Value is not correct. Maybe abort the process?\n\n}\n</code></pre>\n\n<p>Do the same process with <code>$uid</code>.</p>\n\n<p>Once you have santize and validate your variables, you are ready to pass them to <code>$wpdb-&gt;insert</code> method like this (with the third parameter performs a basic sanitization, you can avoid previous sanitization if this is enough for your situation):</p>\n\n<pre><code>$wpdb-&gt;insert(\n 'votes',\n array(\n 'votes' =&gt; $votes,\n 'competition' =&gt; $competition,\n 'uid' =&gt; $uid\n ),\n array(\n '%d', // integer data type for $votes\n '%s', // string data type for $competition\n '%d', // integer data type for $uid\n )\n);\n</code></pre>\n" } ]
2015/04/11
[ "https://wordpress.stackexchange.com/questions/183914", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/53989/" ]
Each of these bits of code work separately in category.php, but when I use both together, the first one is ignored. Can someone tell me how to combine them into a single piece of code, or at least make them play nicely together? ``` <?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc&posts_per_page=18' ); } ?> <?php $current_cat = intval( get_query_var('cat') ); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args=array( 'category__and' => array($current_cat), 'paged' => $paged, 'post_type' => 'post', 'caller_get_posts'=> 1 ); query_posts($args); ?> ```
The insert method of `$wpdb` already scapes the data taking care of SQL injection. What you should worry about is about data sanitization and validation. For exmpla: **Sanitization** What type of data do you accept in `$votes`? A integer value? If so, be sure `$votes` contains a integer value. You cuold do it, for exmaple, using [`intval` function](http://php.net/manual/es/function.intval.php) from PHP. This is sanitization. ``` $votes = intval( $votes ); ``` What type of data do you accept in `$competition`? Any string with no HTML, tabs or line breaks, ? If so, be sure `$competition` contains a string value, strip HTML tags and remove tabs and line break; you could do it, for exmaple, using [`sanitize_text_field` function](https://codex.wordpress.org/Function_Reference/sanitize_text_field) from WordPress. This is also sanitization. ``` $competition = sanitize_text_field( $competition ); ``` **Data validation** What value do you accept in `$votes`? From 0 to 100, including both? If so, you could check the value of `$votes`: ``` if( $votes >= 0 && $votes <= 100 ) { // Value is correct } else { // Value is not correct. Maybe abort the process? } ``` Do you have a list of valid competitions? Check the value of `$competition` against it: ``` $valid_competitions = array( 'competition1', 'competition2', 'competition3' ); if( in_array( $competition, $valid_competitions ) ) { // Value is correct } else { // Value is not correct. Maybe abort the process? } ``` Do the same process with `$uid`. Once you have santize and validate your variables, you are ready to pass them to `$wpdb->insert` method like this (with the third parameter performs a basic sanitization, you can avoid previous sanitization if this is enough for your situation): ``` $wpdb->insert( 'votes', array( 'votes' => $votes, 'competition' => $competition, 'uid' => $uid ), array( '%d', // integer data type for $votes '%s', // string data type for $competition '%d', // integer data type for $uid ) ); ```
183,921
<p>When having this:</p> <pre><code>$tag_list = get_the_tag_list( '', ', ' ); </code></pre> <p>I substituted the meta print:</p> <pre><code>printf( $tag_list, $category:list, etc ); </code></pre> <p>by this:</p> <pre><code>$printArray_tag_list = explode(', ', $tag_list); echo $category_list."/".$printArray_tag_list[0].','.$printArray_tag_list[1]; </code></pre> <p>to print only the first two tags from the list (the first tags inserted in the post editor). Only then I realized that they are alphabetically ordered and those are not the tags I want to print.</p> <p>Is there a way to print selected tags? Maybe selecting them in the custom fields?</p>
[ { "answer_id": 183922, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>By <code>get_the_tags()</code> you receive an array of tags attached to the current post. So you could do the following:</p>\n\n<pre><code>$tags = get_the_tags();\n$tag_ids_to_print = array( 1, 2, 3 ); //List of Tag IDs which you want to be printed\n\n$print_tags = array();\nif( is_array( $tags ) ){\n foreach( $tags as $tag ){\n if( in_array( $tag-&gt;term_id, $tag_ids_to_print ) )\n $print_tags[] = $tag;\n }\n}\n\n$tag_list = '';\nif( count( $print_tags ) &gt; 0 ){\n //Execute only, when tags found\n $i = 0;\n foreach( $print_tags as $tag ){\n if( $i == 1 ) $tag_list .= ', ';\n $tag_list .= '&lt;a href=\"' . get_tag_link( $tag-&gt;term_id ) . '\"&gt;' . $tag-&gt;name . '&lt;/a&gt;';\n $i = 1;\n }\n}\n</code></pre>\n\n<p>Docs:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_the_tags\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_the_tags</a></p>\n" }, { "answer_id": 183929, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<h2>Custom Field Tag filter:</h2>\n\n<p>You can try the following code snippet to filter tags from a custom field:</p>\n\n<pre><code>/**\n * Support the 'include_tags' custom field (comma seperated tag slugs) \n * to filter out those tags to display.\n *\n * @see http://wordpress.stackexchange.com/a/183929/26350\n */\n\n! is_admin() &amp;&amp; add_filter( 'get_the_terms', function( $terms, $post_id, $taxonomy )\n{\n if( 'post_tag' === $taxonomy \n &amp;&amp; ! empty( $terms ) \n &amp;&amp; $include = get_post_meta( $post_id, 'include_tags', true ) \n ){ \n // We only want lower case and trimmed strings from the custom meta field:\n $include_tags = array_map( 'trim', array_map( 'strtolower', explode( ',', $include ) ) );\n\n // Let's filter out the terms to display:\n if( ! empty( $include_tags ) )\n $terms = array_filter( $terms, function( $t ) use ( $include_tags ) { \n return in_array( $t-&gt;slug, $include_tags );\n });\n }\n return $terms;\n}, 10, 3 );\n</code></pre>\n\n<p>For example if you use <code>the_tags()</code> in your template and have the following tags in a given post:</p>\n\n<p><img src=\"https://i.stack.imgur.com/18DY2.jpg\" alt=\"tags\"></p>\n\n<p>then you can add the custom field <code>include_tags</code> with a comma seperated list of tags you want to filter out:</p>\n\n<p><img src=\"https://i.stack.imgur.com/FqQEG.jpg\" alt=\"cf\"></p>\n\n<p>Then it will show like this on your front end:</p>\n\n<p><img src=\"https://i.stack.imgur.com/yPp08.jpg\" alt=\"display\"></p>\n\n<p>Similarly we could support <code>exclude_tags</code> filtering with:</p>\n\n<pre><code>return ! in_array( $t-&gt;slug, $include_tags );\n</code></pre>\n\n<p>instead.</p>\n" } ]
2015/04/11
[ "https://wordpress.stackexchange.com/questions/183921", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66195/" ]
When having this: ``` $tag_list = get_the_tag_list( '', ', ' ); ``` I substituted the meta print: ``` printf( $tag_list, $category:list, etc ); ``` by this: ``` $printArray_tag_list = explode(', ', $tag_list); echo $category_list."/".$printArray_tag_list[0].','.$printArray_tag_list[1]; ``` to print only the first two tags from the list (the first tags inserted in the post editor). Only then I realized that they are alphabetically ordered and those are not the tags I want to print. Is there a way to print selected tags? Maybe selecting them in the custom fields?
By `get_the_tags()` you receive an array of tags attached to the current post. So you could do the following: ``` $tags = get_the_tags(); $tag_ids_to_print = array( 1, 2, 3 ); //List of Tag IDs which you want to be printed $print_tags = array(); if( is_array( $tags ) ){ foreach( $tags as $tag ){ if( in_array( $tag->term_id, $tag_ids_to_print ) ) $print_tags[] = $tag; } } $tag_list = ''; if( count( $print_tags ) > 0 ){ //Execute only, when tags found $i = 0; foreach( $print_tags as $tag ){ if( $i == 1 ) $tag_list .= ', '; $tag_list .= '<a href="' . get_tag_link( $tag->term_id ) . '">' . $tag->name . '</a>'; $i = 1; } } ``` Docs: <https://codex.wordpress.org/Function_Reference/get_the_tags>
183,971
<p>I'm storing CPT <code>products</code>' post IDs into CPT <code>companies</code>' post meta (meta_key = <code>prefix_products</code>). As a company can have multiple products, so I'm storing them into a PHP serialized array value.</p> <pre><code>s:48:"a:3:{i:0;s:3:"334";i:1;s:3:"333";i:2;s:3:"331";}"; </code></pre> <p>Where 334, 333, 331 are three post_ids of post type <code>products</code>.</p> <p>I need to get the post_id of the CPT <code>companies</code> where the product id (post_id of CTP <code>products</code>) is equal to 331 (dynamic - can be any value). It should compare with meta_value of the meta_key <code>prefix_products</code>.</p> <p>I can get post_id using a meta_value, but I'm stuck where the data is stored as serialized. :(</p> <p>What I did so far, can't get to the solution:</p> <pre><code>function get_company_of_the_product( $product_id ) { global $project_prefix; $prod_meta_key = $project_prefix .'products'; $companies = get_posts( array( 'post_type' =&gt; 'companies', 'post_status' =&gt; 'publish', 'meta_key' =&gt; $prod_meta_key ) ); $products_array = array(); foreach ( $companies as $company ) { $products = get_post_meta( $company-&gt;ID, $prod_meta_key, true ); $products_array[$company-&gt;ID] = unserialize( $products ); //if( in_array( $product_id, $products_array ) ) return $company-&gt;ID; //I know it's wrong } var_dump($products_array); } </code></pre> <p>Is this the way, or am I missing something seriously easy? How can I solve the riddle?</p>
[ { "answer_id": 183992, "author": "Erez.info", "author_id": 70538, "author_profile": "https://wordpress.stackexchange.com/users/70538", "pm_score": 1, "selected": false, "text": "<p>It's not possible, you have to store that value separately, and then you'll be able to use it. </p>\n" }, { "answer_id": 183996, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 2, "selected": true, "text": "<p>I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play.</p>\n\n<p>So, the <code>'prefix_products'</code> meta key is always an array of products. Now you need all companies, which sell a product with a certain ID.</p>\n\n<p>This should do the trick:</p>\n\n<pre><code>function get_all_companies_selling( $product_id ){\n global $wpdb;\n $sql = \"select post_id from \" . $wpdb-&gt;prefix . \"postmeta where\n meta_key = 'prefix_products' &amp;&amp;\n meta_value like '%%%s%%'\";\n\n $product_id = 's:' . strlen( $product_id ) . ':\"' . (int) $product_id . '\";';\n $sql = $wpdb-&gt;prepare( $sql, $product_id );\n $res = $wpdb-&gt;get_results( $sql );\n\n return $res;\n}\n\nget_all_companies_selling( 331 );\n</code></pre>\n" }, { "answer_id": 302780, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": 0, "selected": false, "text": "<p>This is very possible though possibly slow. It's essentially a reverse relationship search and is common with Advanced Custom Fields or any other custom field used for relationships. </p>\n\n<p>The following will get not just the IDs, it returns an array of posts object via WP_Query.</p>\n\n<pre><code>$some_product_id = '123';\n$args= array(\n 'post_type' =&gt; 'companies', // only search postmeta of these cpts\n 'posts_per_page' =&gt; 5, // limit or not depending on your use\n 'orderby' =&gt; 'date', // use whatever order you like\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'prefix_products', // name of custom field\n 'value' =&gt; '\"' . $some_product_id . '\"', // matches exactly \"123\" not just 123.\n 'compare' =&gt; 'LIKE'\n )\n);\n\n$the_related_companies = new WP_Query( $args );\n\nif( $the_related_companies-&gt;have_posts() ) :\n &lt;div class=\"container\"&gt;\n while( $the_related_companies-&gt;have_posts() ) :\n [do stuff with your posts]\n endwhile;\n &lt;/div&gt;\nendif;\n</code></pre>\n\n<p>(Excuse my PHP, I've been working in Blade a lot and it's hard to go back)</p>\n" } ]
2015/04/12
[ "https://wordpress.stackexchange.com/questions/183971", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I'm storing CPT `products`' post IDs into CPT `companies`' post meta (meta\_key = `prefix_products`). As a company can have multiple products, so I'm storing them into a PHP serialized array value. ``` s:48:"a:3:{i:0;s:3:"334";i:1;s:3:"333";i:2;s:3:"331";}"; ``` Where 334, 333, 331 are three post\_ids of post type `products`. I need to get the post\_id of the CPT `companies` where the product id (post\_id of CTP `products`) is equal to 331 (dynamic - can be any value). It should compare with meta\_value of the meta\_key `prefix_products`. I can get post\_id using a meta\_value, but I'm stuck where the data is stored as serialized. :( What I did so far, can't get to the solution: ``` function get_company_of_the_product( $product_id ) { global $project_prefix; $prod_meta_key = $project_prefix .'products'; $companies = get_posts( array( 'post_type' => 'companies', 'post_status' => 'publish', 'meta_key' => $prod_meta_key ) ); $products_array = array(); foreach ( $companies as $company ) { $products = get_post_meta( $company->ID, $prod_meta_key, true ); $products_array[$company->ID] = unserialize( $products ); //if( in_array( $product_id, $products_array ) ) return $company->ID; //I know it's wrong } var_dump($products_array); } ``` Is this the way, or am I missing something seriously easy? How can I solve the riddle?
I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play. So, the `'prefix_products'` meta key is always an array of products. Now you need all companies, which sell a product with a certain ID. This should do the trick: ``` function get_all_companies_selling( $product_id ){ global $wpdb; $sql = "select post_id from " . $wpdb->prefix . "postmeta where meta_key = 'prefix_products' && meta_value like '%%%s%%'"; $product_id = 's:' . strlen( $product_id ) . ':"' . (int) $product_id . '";'; $sql = $wpdb->prepare( $sql, $product_id ); $res = $wpdb->get_results( $sql ); return $res; } get_all_companies_selling( 331 ); ```
184,002
<p>Weird Problem: I registered two menus (theme-positions) and then added two different menus to each (in Wordpress Admin), but it always shows same menu in both positions:</p> <p>sidebar.php</p> <pre><code>&lt;?php wp_nav_menu( array( 'menu_name' =&gt; 'Header Menu', 'theme-location' =&gt; 'header-menu', ) ); ?&gt; &lt;div id="menu-content" class="back-canvas"&gt; &lt;div class="inner-menu-content"&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php wp_nav_menu( array( 'menu_name' =&gt; 'Footer Menu', 'theme-location' =&gt; 'footer-menu' ) ); ?&gt; </code></pre> <p>functions.php</p> <pre><code>add_action( 'init', 'bc_init' ); function bc_init() { add_editor_style( get_stylesheet_directory_uri() . '/css/editor-style.css' ); load_theme_textdomain( 'bc_leimcke', get_template_directory() . '/lang' ); register_nav_menus( array( 'header-menu' =&gt; 'Header Menu', 'footer-menu' =&gt; 'Footer Menu' ) ); } </code></pre> <p><strong>has anyone had the same problem? any hints?</strong></p>
[ { "answer_id": 183992, "author": "Erez.info", "author_id": 70538, "author_profile": "https://wordpress.stackexchange.com/users/70538", "pm_score": 1, "selected": false, "text": "<p>It's not possible, you have to store that value separately, and then you'll be able to use it. </p>\n" }, { "answer_id": 183996, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 2, "selected": true, "text": "<p>I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play.</p>\n\n<p>So, the <code>'prefix_products'</code> meta key is always an array of products. Now you need all companies, which sell a product with a certain ID.</p>\n\n<p>This should do the trick:</p>\n\n<pre><code>function get_all_companies_selling( $product_id ){\n global $wpdb;\n $sql = \"select post_id from \" . $wpdb-&gt;prefix . \"postmeta where\n meta_key = 'prefix_products' &amp;&amp;\n meta_value like '%%%s%%'\";\n\n $product_id = 's:' . strlen( $product_id ) . ':\"' . (int) $product_id . '\";';\n $sql = $wpdb-&gt;prepare( $sql, $product_id );\n $res = $wpdb-&gt;get_results( $sql );\n\n return $res;\n}\n\nget_all_companies_selling( 331 );\n</code></pre>\n" }, { "answer_id": 302780, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": 0, "selected": false, "text": "<p>This is very possible though possibly slow. It's essentially a reverse relationship search and is common with Advanced Custom Fields or any other custom field used for relationships. </p>\n\n<p>The following will get not just the IDs, it returns an array of posts object via WP_Query.</p>\n\n<pre><code>$some_product_id = '123';\n$args= array(\n 'post_type' =&gt; 'companies', // only search postmeta of these cpts\n 'posts_per_page' =&gt; 5, // limit or not depending on your use\n 'orderby' =&gt; 'date', // use whatever order you like\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'prefix_products', // name of custom field\n 'value' =&gt; '\"' . $some_product_id . '\"', // matches exactly \"123\" not just 123.\n 'compare' =&gt; 'LIKE'\n )\n);\n\n$the_related_companies = new WP_Query( $args );\n\nif( $the_related_companies-&gt;have_posts() ) :\n &lt;div class=\"container\"&gt;\n while( $the_related_companies-&gt;have_posts() ) :\n [do stuff with your posts]\n endwhile;\n &lt;/div&gt;\nendif;\n</code></pre>\n\n<p>(Excuse my PHP, I've been working in Blade a lot and it's hard to go back)</p>\n" } ]
2015/04/12
[ "https://wordpress.stackexchange.com/questions/184002", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70544/" ]
Weird Problem: I registered two menus (theme-positions) and then added two different menus to each (in Wordpress Admin), but it always shows same menu in both positions: sidebar.php ``` <?php wp_nav_menu( array( 'menu_name' => 'Header Menu', 'theme-location' => 'header-menu', ) ); ?> <div id="menu-content" class="back-canvas"> <div class="inner-menu-content"> </div> </div> <?php wp_nav_menu( array( 'menu_name' => 'Footer Menu', 'theme-location' => 'footer-menu' ) ); ?> ``` functions.php ``` add_action( 'init', 'bc_init' ); function bc_init() { add_editor_style( get_stylesheet_directory_uri() . '/css/editor-style.css' ); load_theme_textdomain( 'bc_leimcke', get_template_directory() . '/lang' ); register_nav_menus( array( 'header-menu' => 'Header Menu', 'footer-menu' => 'Footer Menu' ) ); } ``` **has anyone had the same problem? any hints?**
I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play. So, the `'prefix_products'` meta key is always an array of products. Now you need all companies, which sell a product with a certain ID. This should do the trick: ``` function get_all_companies_selling( $product_id ){ global $wpdb; $sql = "select post_id from " . $wpdb->prefix . "postmeta where meta_key = 'prefix_products' && meta_value like '%%%s%%'"; $product_id = 's:' . strlen( $product_id ) . ':"' . (int) $product_id . '";'; $sql = $wpdb->prepare( $sql, $product_id ); $res = $wpdb->get_results( $sql ); return $res; } get_all_companies_selling( 331 ); ```
184,009
<p>I want to make custom url and handle it from my plugin </p> <p>Ex:- </p> <pre><code>domain.com/myplugin=endpoint&amp;id=num&amp;.. </code></pre> <p>i want to return just json data not template </p> <p>Thanks</p>
[ { "answer_id": 183992, "author": "Erez.info", "author_id": 70538, "author_profile": "https://wordpress.stackexchange.com/users/70538", "pm_score": 1, "selected": false, "text": "<p>It's not possible, you have to store that value separately, and then you'll be able to use it. </p>\n" }, { "answer_id": 183996, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 2, "selected": true, "text": "<p>I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play.</p>\n\n<p>So, the <code>'prefix_products'</code> meta key is always an array of products. Now you need all companies, which sell a product with a certain ID.</p>\n\n<p>This should do the trick:</p>\n\n<pre><code>function get_all_companies_selling( $product_id ){\n global $wpdb;\n $sql = \"select post_id from \" . $wpdb-&gt;prefix . \"postmeta where\n meta_key = 'prefix_products' &amp;&amp;\n meta_value like '%%%s%%'\";\n\n $product_id = 's:' . strlen( $product_id ) . ':\"' . (int) $product_id . '\";';\n $sql = $wpdb-&gt;prepare( $sql, $product_id );\n $res = $wpdb-&gt;get_results( $sql );\n\n return $res;\n}\n\nget_all_companies_selling( 331 );\n</code></pre>\n" }, { "answer_id": 302780, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": 0, "selected": false, "text": "<p>This is very possible though possibly slow. It's essentially a reverse relationship search and is common with Advanced Custom Fields or any other custom field used for relationships. </p>\n\n<p>The following will get not just the IDs, it returns an array of posts object via WP_Query.</p>\n\n<pre><code>$some_product_id = '123';\n$args= array(\n 'post_type' =&gt; 'companies', // only search postmeta of these cpts\n 'posts_per_page' =&gt; 5, // limit or not depending on your use\n 'orderby' =&gt; 'date', // use whatever order you like\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'prefix_products', // name of custom field\n 'value' =&gt; '\"' . $some_product_id . '\"', // matches exactly \"123\" not just 123.\n 'compare' =&gt; 'LIKE'\n )\n);\n\n$the_related_companies = new WP_Query( $args );\n\nif( $the_related_companies-&gt;have_posts() ) :\n &lt;div class=\"container\"&gt;\n while( $the_related_companies-&gt;have_posts() ) :\n [do stuff with your posts]\n endwhile;\n &lt;/div&gt;\nendif;\n</code></pre>\n\n<p>(Excuse my PHP, I've been working in Blade a lot and it's hard to go back)</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65428/" ]
I want to make custom url and handle it from my plugin Ex:- ``` domain.com/myplugin=endpoint&id=num&.. ``` i want to return just json data not template Thanks
I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play. So, the `'prefix_products'` meta key is always an array of products. Now you need all companies, which sell a product with a certain ID. This should do the trick: ``` function get_all_companies_selling( $product_id ){ global $wpdb; $sql = "select post_id from " . $wpdb->prefix . "postmeta where meta_key = 'prefix_products' && meta_value like '%%%s%%'"; $product_id = 's:' . strlen( $product_id ) . ':"' . (int) $product_id . '";'; $sql = $wpdb->prepare( $sql, $product_id ); $res = $wpdb->get_results( $sql ); return $res; } get_all_companies_selling( 331 ); ```
184,014
<p>I am using this code to auto create a page when I activate my plugin..</p> <pre><code>function insert_page(){ // Create post object $my_post = array( 'post_title' =&gt; 'My post', 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_author' =&gt; get_current_user_id(), 'post_type' =&gt; 'page', ); // Insert the post into the database wp_insert_post( $my_post, '' ); } add_action('init', 'insert_page'); </code></pre> <p>The issue now is whenever it loads the admin page it creates also a new page.. is there any way that it only auto create 1 page? when the plugin activate only it then create only 1 page?</p> <p>also I have on my mind that when it created at <code>wp_insert_post( $my_post, '' )</code> how can I get the post/page ID? so that I an determine if the page were already exist or not...</p>
[ { "answer_id": 183992, "author": "Erez.info", "author_id": 70538, "author_profile": "https://wordpress.stackexchange.com/users/70538", "pm_score": 1, "selected": false, "text": "<p>It's not possible, you have to store that value separately, and then you'll be able to use it. </p>\n" }, { "answer_id": 183996, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 2, "selected": true, "text": "<p>I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play.</p>\n\n<p>So, the <code>'prefix_products'</code> meta key is always an array of products. Now you need all companies, which sell a product with a certain ID.</p>\n\n<p>This should do the trick:</p>\n\n<pre><code>function get_all_companies_selling( $product_id ){\n global $wpdb;\n $sql = \"select post_id from \" . $wpdb-&gt;prefix . \"postmeta where\n meta_key = 'prefix_products' &amp;&amp;\n meta_value like '%%%s%%'\";\n\n $product_id = 's:' . strlen( $product_id ) . ':\"' . (int) $product_id . '\";';\n $sql = $wpdb-&gt;prepare( $sql, $product_id );\n $res = $wpdb-&gt;get_results( $sql );\n\n return $res;\n}\n\nget_all_companies_selling( 331 );\n</code></pre>\n" }, { "answer_id": 302780, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": 0, "selected": false, "text": "<p>This is very possible though possibly slow. It's essentially a reverse relationship search and is common with Advanced Custom Fields or any other custom field used for relationships. </p>\n\n<p>The following will get not just the IDs, it returns an array of posts object via WP_Query.</p>\n\n<pre><code>$some_product_id = '123';\n$args= array(\n 'post_type' =&gt; 'companies', // only search postmeta of these cpts\n 'posts_per_page' =&gt; 5, // limit or not depending on your use\n 'orderby' =&gt; 'date', // use whatever order you like\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'prefix_products', // name of custom field\n 'value' =&gt; '\"' . $some_product_id . '\"', // matches exactly \"123\" not just 123.\n 'compare' =&gt; 'LIKE'\n )\n);\n\n$the_related_companies = new WP_Query( $args );\n\nif( $the_related_companies-&gt;have_posts() ) :\n &lt;div class=\"container\"&gt;\n while( $the_related_companies-&gt;have_posts() ) :\n [do stuff with your posts]\n endwhile;\n &lt;/div&gt;\nendif;\n</code></pre>\n\n<p>(Excuse my PHP, I've been working in Blade a lot and it's hard to go back)</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184014", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68933/" ]
I am using this code to auto create a page when I activate my plugin.. ``` function insert_page(){ // Create post object $my_post = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => get_current_user_id(), 'post_type' => 'page', ); // Insert the post into the database wp_insert_post( $my_post, '' ); } add_action('init', 'insert_page'); ``` The issue now is whenever it loads the admin page it creates also a new page.. is there any way that it only auto create 1 page? when the plugin activate only it then create only 1 page? also I have on my mind that when it created at `wp_insert_post( $my_post, '' )` how can I get the post/page ID? so that I an determine if the page were already exist or not...
I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play. So, the `'prefix_products'` meta key is always an array of products. Now you need all companies, which sell a product with a certain ID. This should do the trick: ``` function get_all_companies_selling( $product_id ){ global $wpdb; $sql = "select post_id from " . $wpdb->prefix . "postmeta where meta_key = 'prefix_products' && meta_value like '%%%s%%'"; $product_id = 's:' . strlen( $product_id ) . ':"' . (int) $product_id . '";'; $sql = $wpdb->prepare( $sql, $product_id ); $res = $wpdb->get_results( $sql ); return $res; } get_all_companies_selling( 331 ); ```
184,027
<p>The method <code>OpenMods</code> that you see below, is supposed to take an array generated by an <code>fgetcsv</code> function, and put it into an HTML table. <code>__construct</code> is supposed to, as is typically the case, define the attributes for the class, and <code>shortcode</code> is supposed to take two attributes from the shortcode, and if mods comes back, it is supposed to call another function in the class.</p> <p><code>OpenMods</code> did function when it was outside of a class, without the class attribute calls, so I'm fairly certain that isn't the source of my problem. My problem most likely lies within <code>__construct</code> and <code>shortcode</code>; However please don't overlook OpenMods as it may contain errors that are contributing to the problem, I'm just giving my estimation which isn't worth much since I'm having to ask to for help. </p> <p>This is an example of the shortcode I'm trying to make work:</p> <pre><code>[priceguide file=’test.csv’ type=’mods’] </code></pre> <hr> <pre><code>class CsvImporter { private $parse_header; private $header; private $delimiter; private $length; //-------------------------------------------------------------------- function __construct($parse_header=false, $delimiter="\t", $length=8000) { add_shortcode( 'priceguide', array( $this, 'shortcode' ) ); $this-&gt;parse_header = $parse_header; $this-&gt;delimiter = $delimiter; $this-&gt;length = $length; } //-------------------------------------------------------------------- public function shortcode($atts) { $attributes = extract( shortcode_atts( array( 'file' =&gt; '', 'type' =&gt; '', ), $atts )); if ($attributes['mods']) { $this-&gt;OpenMods($attributes['file']); } } //-------------------------------------------------------------------- function OpenMods($file) { ob_start(); $fp = fopen(plugin_dir_path( __FILE__ ) . $file , "r" ); if ($this-&gt;parse_header) { $header = fgetcsv($fp, $this-&gt;length, $this-&gt;delimiter); } // table header and search html echo('&lt;input type="text" class="search" id="search" placeholder="Search"&gt;'); echo('&lt;br&gt;'); echo('&lt;table id="table"&gt; &lt;tr class="hidden"&gt; &lt;th&gt;&lt;b&gt; Name&lt;/b&gt; &lt;/th&gt; &lt;th&gt;&lt;b&gt; Cheese&lt;/b&gt; &lt;/th&gt; &lt;th&gt;&lt;b&gt; Price&lt;/b&gt; &lt;/th&gt; &lt;th&gt;&lt;b&gt;Vote&lt;/b&gt; &lt;/th&gt; &lt;/tr&gt; &lt;tbody&gt;'); // integer for drop down/price submit $a = 1; // set values for table data while ($header !== FALSE) { $name = $header[0]; $quanid = $header[2]; $table = $header[3]; unset($header[2]); unset($header[3]); $cssId = 'row-'.$a; $a++; //generate HTML echo('&lt;tr&gt;'); foreach ($header as $index=&gt;$val) { echo('&lt;td&gt;'); echo htmlentities($val, ENT_QUOTES); echo('&lt;/td&gt;'); } // query to get item prices $sql = "SELECT ItemID, Price FROM {$table} WHERE ItemID = %d GROUP BY Price ORDER BY COUNT(*) DESC LIMIT 1"; global $wpdb; $results = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $sql, $quanid)); // put the results in the table echo('&lt;td&gt;'); print_r($results); echo('&lt;/td&gt;'); // HTML for hidden row/price submission echo('&lt;td&gt; &lt;button class="toggler" data-prod-cat="' . $cssId . '"&gt;Vote&lt;/button&gt; &lt;/td&gt;'); echo('&lt;/tr&gt;'); echo('&lt;tr class="cat' . $cssId . ' hidden" style="display:none"&gt;'); echo('&lt;td colspan="4" style="white-space: nowrap"&gt;Enter ' . $name . ' Price: &lt;form action="" name="form' . $quanid . '" method="post"&gt;&lt;input type="text" id="' . $quanid . '" maxlength="4" name="' . $quanid . '" value="price_input" class="input" /&gt; &lt;button id="submit" name="submit" class="submit" type="submit" value="Submit"&gt;Submit&lt;/button&gt;&lt;/form&gt; &lt;?php ?&gt; &lt;/td&gt; &lt;/tr&gt;'); wp_nonce_field('price_input'); } echo("&lt;/table&gt;"); fclose($fp); return ob_get_clean(); } } </code></pre>
[ { "answer_id": 184033, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>First, you have to initiate the class, something like:</p>\n\n<pre><code>add_action( 'init', function() {\n\n $CsvImporter = new CsvImporter;\n\n} );\n</code></pre>\n\n<p>Also, you are using <code>extract()</code> wrong; <code>extract()</code> won't build <code>$attributes</code> as an array. Anyway, <code>extract()</code> is not recommended any more and you should avoid using it. Also, note taht <code>if ($attributes['mods'])</code> should be <code>if ($attributes['type'] == 'mods')</code> as <code>mods</code> is not a valid index in <code>$attributes</code> array but the value of <code>type</code> index. Additionally you need to <code>return</code> a value int he shortcode callback.</p>\n\n<p>I've tested this shortcode <code>[priceguide file=\"test.csv\" type=\"mods\"]</code> and it is working with the code bellow (note also that I've change <code>’</code> character in the shortcode, not sure if <code>’</code> is a valid value delimiter).</p>\n\n<pre><code>add_action( 'init', function() {\n\n $CsvImporter = new CsvImporter;\n\n} );\n\nclass CsvImporter { \n private $parse_header;\n private $header;\n private $delimiter;\n private $length;\n\n function __construct($parse_header=false, $delimiter=\"\\t\", $length=8000) {\n add_shortcode( 'priceguide', array( $this, 'shortcode' ) );\n $this-&gt;parse_header = $parse_header;\n $this-&gt;delimiter = $delimiter;\n $this-&gt;length = $length;\n }\n\n public function shortcode($atts) {\n $attributes = shortcode_atts( array(\n 'file' =&gt; '',\n 'type' =&gt; '',\n ), $atts );\n\n if ( $attributes['type'] == \"mods\" ) {\n return $this-&gt;OpenMods($attributes['file']);\n }\n }\n\n function OpenMods($file) {\n return \"test\";\n }\n}\n</code></pre>\n\n<p>PD: While developing you should have <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow\"><code>WP_DEBUG</code></a> set to on and display errors set to on also; this way you would had seen a warning message saying that <code>$attributes['mods']</code> is not set.</p>\n" }, { "answer_id": 184034, "author": "Jon Limitless", "author_id": 27883, "author_profile": "https://wordpress.stackexchange.com/users/27883", "pm_score": -1, "selected": false, "text": "<p>You may always need to check initation for the class to be called which seems to be your problem. In your case you can always simply call the class when included like below:</p>\n\n<pre><code>$csvImporter = new CsvImporter($parse_header, $delimiter, $length);\n</code></pre>\n\n<p>Or if you adding the class into the WordPress init hook such as a plugin format.</p>\n\n<pre><code>add_action('init', array($this, 'CsvImporter'));\n</code></pre>\n\n<p>Also note that if the class already exists you may want to do a simply check using the function function_exists to see if it is already being called. </p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184027", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65738/" ]
The method `OpenMods` that you see below, is supposed to take an array generated by an `fgetcsv` function, and put it into an HTML table. `__construct` is supposed to, as is typically the case, define the attributes for the class, and `shortcode` is supposed to take two attributes from the shortcode, and if mods comes back, it is supposed to call another function in the class. `OpenMods` did function when it was outside of a class, without the class attribute calls, so I'm fairly certain that isn't the source of my problem. My problem most likely lies within `__construct` and `shortcode`; However please don't overlook OpenMods as it may contain errors that are contributing to the problem, I'm just giving my estimation which isn't worth much since I'm having to ask to for help. This is an example of the shortcode I'm trying to make work: ``` [priceguide file=’test.csv’ type=’mods’] ``` --- ``` class CsvImporter { private $parse_header; private $header; private $delimiter; private $length; //-------------------------------------------------------------------- function __construct($parse_header=false, $delimiter="\t", $length=8000) { add_shortcode( 'priceguide', array( $this, 'shortcode' ) ); $this->parse_header = $parse_header; $this->delimiter = $delimiter; $this->length = $length; } //-------------------------------------------------------------------- public function shortcode($atts) { $attributes = extract( shortcode_atts( array( 'file' => '', 'type' => '', ), $atts )); if ($attributes['mods']) { $this->OpenMods($attributes['file']); } } //-------------------------------------------------------------------- function OpenMods($file) { ob_start(); $fp = fopen(plugin_dir_path( __FILE__ ) . $file , "r" ); if ($this->parse_header) { $header = fgetcsv($fp, $this->length, $this->delimiter); } // table header and search html echo('<input type="text" class="search" id="search" placeholder="Search">'); echo('<br>'); echo('<table id="table"> <tr class="hidden"> <th><b> Name</b> </th> <th><b> Cheese</b> </th> <th><b> Price</b> </th> <th><b>Vote</b> </th> </tr> <tbody>'); // integer for drop down/price submit $a = 1; // set values for table data while ($header !== FALSE) { $name = $header[0]; $quanid = $header[2]; $table = $header[3]; unset($header[2]); unset($header[3]); $cssId = 'row-'.$a; $a++; //generate HTML echo('<tr>'); foreach ($header as $index=>$val) { echo('<td>'); echo htmlentities($val, ENT_QUOTES); echo('</td>'); } // query to get item prices $sql = "SELECT ItemID, Price FROM {$table} WHERE ItemID = %d GROUP BY Price ORDER BY COUNT(*) DESC LIMIT 1"; global $wpdb; $results = $wpdb->get_var( $wpdb->prepare( $sql, $quanid)); // put the results in the table echo('<td>'); print_r($results); echo('</td>'); // HTML for hidden row/price submission echo('<td> <button class="toggler" data-prod-cat="' . $cssId . '">Vote</button> </td>'); echo('</tr>'); echo('<tr class="cat' . $cssId . ' hidden" style="display:none">'); echo('<td colspan="4" style="white-space: nowrap">Enter ' . $name . ' Price: <form action="" name="form' . $quanid . '" method="post"><input type="text" id="' . $quanid . '" maxlength="4" name="' . $quanid . '" value="price_input" class="input" /> <button id="submit" name="submit" class="submit" type="submit" value="Submit">Submit</button></form> <?php ?> </td> </tr>'); wp_nonce_field('price_input'); } echo("</table>"); fclose($fp); return ob_get_clean(); } } ```
First, you have to initiate the class, something like: ``` add_action( 'init', function() { $CsvImporter = new CsvImporter; } ); ``` Also, you are using `extract()` wrong; `extract()` won't build `$attributes` as an array. Anyway, `extract()` is not recommended any more and you should avoid using it. Also, note taht `if ($attributes['mods'])` should be `if ($attributes['type'] == 'mods')` as `mods` is not a valid index in `$attributes` array but the value of `type` index. Additionally you need to `return` a value int he shortcode callback. I've tested this shortcode `[priceguide file="test.csv" type="mods"]` and it is working with the code bellow (note also that I've change `’` character in the shortcode, not sure if `’` is a valid value delimiter). ``` add_action( 'init', function() { $CsvImporter = new CsvImporter; } ); class CsvImporter { private $parse_header; private $header; private $delimiter; private $length; function __construct($parse_header=false, $delimiter="\t", $length=8000) { add_shortcode( 'priceguide', array( $this, 'shortcode' ) ); $this->parse_header = $parse_header; $this->delimiter = $delimiter; $this->length = $length; } public function shortcode($atts) { $attributes = shortcode_atts( array( 'file' => '', 'type' => '', ), $atts ); if ( $attributes['type'] == "mods" ) { return $this->OpenMods($attributes['file']); } } function OpenMods($file) { return "test"; } } ``` PD: While developing you should have [`WP_DEBUG`](https://codex.wordpress.org/WP_DEBUG) set to on and display errors set to on also; this way you would had seen a warning message saying that `$attributes['mods']` is not set.
184,028
<p>I want to check if there are sidebars rendered on the front end and if so output some body classes so I can style the page differently. I tried using <em>is_active_sidebar</em> but that just returns true if the sidebar contains some widget (is active) - I want to check if it exists on the page. How can I do this?</p> <p>My code looks like this:</p> <p>In my single.php</p> <pre><code>&lt;?php get_sidebar(); ?&gt; </code></pre> <p>In my sidebar.php</p> <pre><code>if ( ! is_active_sidebar() ) { // Add something here perhaps? return; } ?&gt; &lt;div class="sidebar widget-area" role="complementary"&gt; &lt;?php dynamic_sidebar(); ?&gt; &lt;/div&gt;&lt;!-- #secondary --&gt; </code></pre>
[ { "answer_id": 184033, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>First, you have to initiate the class, something like:</p>\n\n<pre><code>add_action( 'init', function() {\n\n $CsvImporter = new CsvImporter;\n\n} );\n</code></pre>\n\n<p>Also, you are using <code>extract()</code> wrong; <code>extract()</code> won't build <code>$attributes</code> as an array. Anyway, <code>extract()</code> is not recommended any more and you should avoid using it. Also, note taht <code>if ($attributes['mods'])</code> should be <code>if ($attributes['type'] == 'mods')</code> as <code>mods</code> is not a valid index in <code>$attributes</code> array but the value of <code>type</code> index. Additionally you need to <code>return</code> a value int he shortcode callback.</p>\n\n<p>I've tested this shortcode <code>[priceguide file=\"test.csv\" type=\"mods\"]</code> and it is working with the code bellow (note also that I've change <code>’</code> character in the shortcode, not sure if <code>’</code> is a valid value delimiter).</p>\n\n<pre><code>add_action( 'init', function() {\n\n $CsvImporter = new CsvImporter;\n\n} );\n\nclass CsvImporter { \n private $parse_header;\n private $header;\n private $delimiter;\n private $length;\n\n function __construct($parse_header=false, $delimiter=\"\\t\", $length=8000) {\n add_shortcode( 'priceguide', array( $this, 'shortcode' ) );\n $this-&gt;parse_header = $parse_header;\n $this-&gt;delimiter = $delimiter;\n $this-&gt;length = $length;\n }\n\n public function shortcode($atts) {\n $attributes = shortcode_atts( array(\n 'file' =&gt; '',\n 'type' =&gt; '',\n ), $atts );\n\n if ( $attributes['type'] == \"mods\" ) {\n return $this-&gt;OpenMods($attributes['file']);\n }\n }\n\n function OpenMods($file) {\n return \"test\";\n }\n}\n</code></pre>\n\n<p>PD: While developing you should have <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow\"><code>WP_DEBUG</code></a> set to on and display errors set to on also; this way you would had seen a warning message saying that <code>$attributes['mods']</code> is not set.</p>\n" }, { "answer_id": 184034, "author": "Jon Limitless", "author_id": 27883, "author_profile": "https://wordpress.stackexchange.com/users/27883", "pm_score": -1, "selected": false, "text": "<p>You may always need to check initation for the class to be called which seems to be your problem. In your case you can always simply call the class when included like below:</p>\n\n<pre><code>$csvImporter = new CsvImporter($parse_header, $delimiter, $length);\n</code></pre>\n\n<p>Or if you adding the class into the WordPress init hook such as a plugin format.</p>\n\n<pre><code>add_action('init', array($this, 'CsvImporter'));\n</code></pre>\n\n<p>Also note that if the class already exists you may want to do a simply check using the function function_exists to see if it is already being called. </p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184028", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5079/" ]
I want to check if there are sidebars rendered on the front end and if so output some body classes so I can style the page differently. I tried using *is\_active\_sidebar* but that just returns true if the sidebar contains some widget (is active) - I want to check if it exists on the page. How can I do this? My code looks like this: In my single.php ``` <?php get_sidebar(); ?> ``` In my sidebar.php ``` if ( ! is_active_sidebar() ) { // Add something here perhaps? return; } ?> <div class="sidebar widget-area" role="complementary"> <?php dynamic_sidebar(); ?> </div><!-- #secondary --> ```
First, you have to initiate the class, something like: ``` add_action( 'init', function() { $CsvImporter = new CsvImporter; } ); ``` Also, you are using `extract()` wrong; `extract()` won't build `$attributes` as an array. Anyway, `extract()` is not recommended any more and you should avoid using it. Also, note taht `if ($attributes['mods'])` should be `if ($attributes['type'] == 'mods')` as `mods` is not a valid index in `$attributes` array but the value of `type` index. Additionally you need to `return` a value int he shortcode callback. I've tested this shortcode `[priceguide file="test.csv" type="mods"]` and it is working with the code bellow (note also that I've change `’` character in the shortcode, not sure if `’` is a valid value delimiter). ``` add_action( 'init', function() { $CsvImporter = new CsvImporter; } ); class CsvImporter { private $parse_header; private $header; private $delimiter; private $length; function __construct($parse_header=false, $delimiter="\t", $length=8000) { add_shortcode( 'priceguide', array( $this, 'shortcode' ) ); $this->parse_header = $parse_header; $this->delimiter = $delimiter; $this->length = $length; } public function shortcode($atts) { $attributes = shortcode_atts( array( 'file' => '', 'type' => '', ), $atts ); if ( $attributes['type'] == "mods" ) { return $this->OpenMods($attributes['file']); } } function OpenMods($file) { return "test"; } } ``` PD: While developing you should have [`WP_DEBUG`](https://codex.wordpress.org/WP_DEBUG) set to on and display errors set to on also; this way you would had seen a warning message saying that `$attributes['mods']` is not set.
184,038
<p>Which function should be used to move post from trash to published pages? <br/> i.e. is there <strong><code>wp_undelete_post</code></strong> or something like?</p>
[ { "answer_id": 184040, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>There is not <code>wp_undelete_post</code> but you have other choices:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_untrash_post/\" rel=\"nofollow\"><code>wp_untrash_post()</code></a>: when post is trashed, the previous status is stored in <code>_wp_trash_meta_status</code> meta field. <code>wp_untrash_post()</code> restore trashed posts to previous status whatever it was; for example, private, inherit, publish. I've not tested it but it should work with <a href=\"https://developer.wordpress.org/reference/functions/register_post_status/\" rel=\"nofollow\">a custom post status as well</a>.</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_publish_post/\" rel=\"nofollow\"><code>wp_publish_post()</code></a>: if you want to move from trash to publish status.</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow\"><code>wp_update_post()</code></a>: to move from trash to any other status.</li>\n</ul>\n\n<p>For example, for a given post ID (of any post type, including pages):</p>\n\n<pre><code>if( get_post_status( $post_ID ) == \"trash\" ) {\n wp_update_post( array(\n 'ID' =&gt; $post_ID,\n 'post_status' =&gt; 'publish'\n )\n );\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>if( get_post_status( $post_ID ) == \"trash\" ) {\n wp_publish_post( $post_ID );\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>if( get_post_status( $post_ID ) == \"trash\" ) {\n wp_untrash_post( $post_ID );\n}\n</code></pre>\n" }, { "answer_id": 184043, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": -1, "selected": false, "text": "<p>the solution so far was:</p>\n\n<pre><code>$page =get_page_by_path('my-slug', OBJECT, 'page');\nif($page &amp;&amp; 'trash'==$page-&gt;post_status) { wp_update_post(array('ID'=&gt;$page-&gt;ID,'post_status'=&gt;'publish')); }\n</code></pre>\n" }, { "answer_id": 231675, "author": "Zank", "author_id": 97912, "author_profile": "https://wordpress.stackexchange.com/users/97912", "pm_score": 1, "selected": false, "text": "<p>It might be old but it showed up when I was looking for similar problem.\nSince WP 2.9.0 there is function called: <a href=\"https://developer.wordpress.org/reference/functions/wp_untrash_post/\" rel=\"nofollow\">wp_untrash_post(int $post_id)</a></p>\n\n<p>In my case it worked like a charm.</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
Which function should be used to move post from trash to published pages? i.e. is there **`wp_undelete_post`** or something like?
There is not `wp_undelete_post` but you have other choices: * [`wp_untrash_post()`](https://developer.wordpress.org/reference/functions/wp_untrash_post/): when post is trashed, the previous status is stored in `_wp_trash_meta_status` meta field. `wp_untrash_post()` restore trashed posts to previous status whatever it was; for example, private, inherit, publish. I've not tested it but it should work with [a custom post status as well](https://developer.wordpress.org/reference/functions/register_post_status/). * [`wp_publish_post()`](https://developer.wordpress.org/reference/functions/wp_publish_post/): if you want to move from trash to publish status. * [`wp_update_post()`](https://developer.wordpress.org/reference/functions/wp_update_post/): to move from trash to any other status. For example, for a given post ID (of any post type, including pages): ``` if( get_post_status( $post_ID ) == "trash" ) { wp_update_post( array( 'ID' => $post_ID, 'post_status' => 'publish' ) ); } ``` or: ``` if( get_post_status( $post_ID ) == "trash" ) { wp_publish_post( $post_ID ); } ``` or: ``` if( get_post_status( $post_ID ) == "trash" ) { wp_untrash_post( $post_ID ); } ```
184,050
<p>I need a little help with what I believe would be PHP.</p> <p><a href="http://www.domain.com/author/" rel="nofollow">http://www.domain.com/author/</a><strong>username</strong>/achievements/</p> <p>Depending on the username of the person logged in, I would like to create a URL that redirects a user to the aforementioned page. To do this, <strong>username</strong> needs to be replaced with their logged in username.</p> <p>Is there an easy way to do this?</p>
[ { "answer_id": 184040, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>There is not <code>wp_undelete_post</code> but you have other choices:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_untrash_post/\" rel=\"nofollow\"><code>wp_untrash_post()</code></a>: when post is trashed, the previous status is stored in <code>_wp_trash_meta_status</code> meta field. <code>wp_untrash_post()</code> restore trashed posts to previous status whatever it was; for example, private, inherit, publish. I've not tested it but it should work with <a href=\"https://developer.wordpress.org/reference/functions/register_post_status/\" rel=\"nofollow\">a custom post status as well</a>.</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_publish_post/\" rel=\"nofollow\"><code>wp_publish_post()</code></a>: if you want to move from trash to publish status.</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow\"><code>wp_update_post()</code></a>: to move from trash to any other status.</li>\n</ul>\n\n<p>For example, for a given post ID (of any post type, including pages):</p>\n\n<pre><code>if( get_post_status( $post_ID ) == \"trash\" ) {\n wp_update_post( array(\n 'ID' =&gt; $post_ID,\n 'post_status' =&gt; 'publish'\n )\n );\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>if( get_post_status( $post_ID ) == \"trash\" ) {\n wp_publish_post( $post_ID );\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>if( get_post_status( $post_ID ) == \"trash\" ) {\n wp_untrash_post( $post_ID );\n}\n</code></pre>\n" }, { "answer_id": 184043, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": -1, "selected": false, "text": "<p>the solution so far was:</p>\n\n<pre><code>$page =get_page_by_path('my-slug', OBJECT, 'page');\nif($page &amp;&amp; 'trash'==$page-&gt;post_status) { wp_update_post(array('ID'=&gt;$page-&gt;ID,'post_status'=&gt;'publish')); }\n</code></pre>\n" }, { "answer_id": 231675, "author": "Zank", "author_id": 97912, "author_profile": "https://wordpress.stackexchange.com/users/97912", "pm_score": 1, "selected": false, "text": "<p>It might be old but it showed up when I was looking for similar problem.\nSince WP 2.9.0 there is function called: <a href=\"https://developer.wordpress.org/reference/functions/wp_untrash_post/\" rel=\"nofollow\">wp_untrash_post(int $post_id)</a></p>\n\n<p>In my case it worked like a charm.</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184050", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70566/" ]
I need a little help with what I believe would be PHP. <http://www.domain.com/author/>**username**/achievements/ Depending on the username of the person logged in, I would like to create a URL that redirects a user to the aforementioned page. To do this, **username** needs to be replaced with their logged in username. Is there an easy way to do this?
There is not `wp_undelete_post` but you have other choices: * [`wp_untrash_post()`](https://developer.wordpress.org/reference/functions/wp_untrash_post/): when post is trashed, the previous status is stored in `_wp_trash_meta_status` meta field. `wp_untrash_post()` restore trashed posts to previous status whatever it was; for example, private, inherit, publish. I've not tested it but it should work with [a custom post status as well](https://developer.wordpress.org/reference/functions/register_post_status/). * [`wp_publish_post()`](https://developer.wordpress.org/reference/functions/wp_publish_post/): if you want to move from trash to publish status. * [`wp_update_post()`](https://developer.wordpress.org/reference/functions/wp_update_post/): to move from trash to any other status. For example, for a given post ID (of any post type, including pages): ``` if( get_post_status( $post_ID ) == "trash" ) { wp_update_post( array( 'ID' => $post_ID, 'post_status' => 'publish' ) ); } ``` or: ``` if( get_post_status( $post_ID ) == "trash" ) { wp_publish_post( $post_ID ); } ``` or: ``` if( get_post_status( $post_ID ) == "trash" ) { wp_untrash_post( $post_ID ); } ```
184,093
<p>I am working through the documentation on wp-api.org/ and trying to get my head around this awesome plugin, but I have a question that I can't find the answer to anywhere, so thought I'd ask...it's probably quite simple, but hey ho..</p> <p>Whilst exploring the json data my install is spitting out (by going to localhost/wordpress/wp-json/), the routes seem to be different to every example in the documentation on wp-api.org. </p> <p>Instead of the routes to the posts being </p> <pre><code>/wp-json/posts </code></pre> <p>my route is </p> <pre><code>/wp-json/wp/posts </code></pre> <p>and so on for pages etc. I was wondering what causes this change, and how you would go about removing the</p> <pre><code>/wp/ </code></pre> <p>/wp-json/posts from the route</p>
[ { "answer_id": 184079, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": true, "text": "<p>There is a <code>template_redirect</code> hooks which is perfectly suitable for task like this.</p>\n\n<ol>\n<li>Hook into <code>template_redirect</code></li>\n<li>Check your context (<code>is_single()</code>, etc)</li>\n<li>Redirect with <code>wp_safe_redirect()</code> (if it's inside a site)</li>\n<li><code>die()</code> to prevent execution from proceeding</li>\n</ol>\n" }, { "answer_id": 184098, "author": "Mattaton", "author_id": 68905, "author_profile": "https://wordpress.stackexchange.com/users/68905", "pm_score": 2, "selected": false, "text": "<p>Thanks to Rarst for the tip.<br>\nHere is the code I came up with to accomplish redirects for two similar taxonomy/post type set ups.<br>\nThis basically does what I indicated in the OP. If I hit a single post with a top-level term assigned to it, the url will go from<br>\n<code>domain/series/post/</code><br>\nto<br>\n<code>domain/series/</code> </p>\n\n<p>It simply strips the post's slug from the end of the url.</p>\n\n<p>Obviously, the CPTs, taxonomies and rewrites have to be set up properly to work with this. </p>\n\n<p>I added the <code>$type</code> parameter to the <code>theme_perform_redirect()</code> function so that I can add functionality to it later for other types of redirects.</p>\n\n<pre><code>function theme_perform_redirect($post, $taxonomy, $type) {\n if ($type == 'top-level') {\n $top_level_terms = get_top_level_term_ids( $taxonomy );\n $post_terms = wp_get_post_terms( $post-&gt;ID, $taxonomy );\n if ( in_array($post_terms[0]-&gt;term_id, $top_level_terms)) {\n // This is the main/top post, redirect it to the archive\n $to_strip = $post-&gt;post_name;\n $permalink = get_permalink( $post-&gt;ID );\n $go_here = str_replace($to_strip.\"/\", \"\", $permalink);\n wp_redirect( $go_here );\n exit();\n }\n }\n}\n\nfunction theme_redirects() {\n global $post;\n if ( is_single() ) {\n if (is_singular( 'cartoon-series' )) {\n heman_perform_redirect($post, 'cartoon-features', 'top-level');\n } else if (is_singular( 'movies' )) {\n heman_perform_redirect($post, 'movie-features', 'top-level');\n }\n }\n}\nadd_action( 'template_redirect', 'theme_redirects' );\n</code></pre>\n\n<p>Note that <code>get_top_level_term_ids()</code> is my own function. It just grabs all the terms with a parent of 0....just in a neater package. :-)</p>\n\n<p>Thanks!</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50090/" ]
I am working through the documentation on wp-api.org/ and trying to get my head around this awesome plugin, but I have a question that I can't find the answer to anywhere, so thought I'd ask...it's probably quite simple, but hey ho.. Whilst exploring the json data my install is spitting out (by going to localhost/wordpress/wp-json/), the routes seem to be different to every example in the documentation on wp-api.org. Instead of the routes to the posts being ``` /wp-json/posts ``` my route is ``` /wp-json/wp/posts ``` and so on for pages etc. I was wondering what causes this change, and how you would go about removing the ``` /wp/ ``` /wp-json/posts from the route
There is a `template_redirect` hooks which is perfectly suitable for task like this. 1. Hook into `template_redirect` 2. Check your context (`is_single()`, etc) 3. Redirect with `wp_safe_redirect()` (if it's inside a site) 4. `die()` to prevent execution from proceeding
184,104
<p>Update: As with so many mysteries, the cause turned out to be extremely stupid. I had the file saved in a different theme's directory. Thanks to @a4jp.com</p> <p>I'm building a theme using underscores. I've created a template file and added a template header at the top.</p> <pre><code>&lt;?php /** * Template Name: Featured **/ get_header(); ?&gt; </code></pre> <p>I'm not getting a Template drop down under Page Attributes in the page editor, so I'm not sure if there's a problem with my formatting or something else.</p> <p>I did try switching themes. The drop down appears in the other theme, but when I switch back to my custom theme, it's still missing.</p>
[ { "answer_id": 184108, "author": "a4jp.com", "author_id": 70586, "author_profile": "https://wordpress.stackexchange.com/users/70586", "pm_score": 4, "selected": true, "text": "<p>Maybe this will help.</p>\n\n<pre><code>&lt;?php \n/*\nTemplate Name: Featured\n*/\nget_header(); ?&gt;\n</code></pre>\n\n<p>Regular code here...</p>\n\n<pre><code>&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>If one theme works you could try replacing the files in the broken theme and test which file or files are broken. But first save the old files in a separate folder as a backup. Then you would know which file or files are broken pretty quickly.</p>\n" }, { "answer_id": 184109, "author": "TheGentleman", "author_id": 68563, "author_profile": "https://wordpress.stackexchange.com/users/68563", "pm_score": 2, "selected": false, "text": "<p>If you're not seeing the dropdown at all you might need to reload your theme. Try switching to another theme and then switching back.</p>\n" }, { "answer_id": 224004, "author": "P_95", "author_id": 92548, "author_profile": "https://wordpress.stackexchange.com/users/92548", "pm_score": 1, "selected": false, "text": "<p>This has happened two times for me. At the first time I changed the encoding of the file (header.php I think) to <em>UTF-8 without BOM</em> and all <strong>templates</strong> disappeared. Changed it back to regular utf-8.</p>\n\n<p>At the second time I somehow edited/renamed the index.php (/themes/<em>theme_name</em>/index.php). Just had to create an empty index.php and now everything seems to be ok.</p>\n\n<p>I hope this helps someone else.\n[WP 4.4.2]</p>\n" }, { "answer_id": 289429, "author": "Vipul Tank", "author_id": 132364, "author_profile": "https://wordpress.stackexchange.com/users/132364", "pm_score": 2, "selected": false, "text": "<p>By default Wordpress theme directory have not any template page then template page dropdown is invisible so follow the below instruction.</p>\n\n<p>For display template page dropdown in wordpress admin page you need to create one template page in your theme directory code is below</p>\n\n<pre><code>&lt;?php \n/*\nTemplate Name: template home \n*/\n?&gt;\n</code></pre>\n\n<p>By creating this template file in your theme directory you can see template dropdonw is visible in admin page.</p>\n" }, { "answer_id": 293304, "author": "Barry Poore", "author_id": 136332, "author_profile": "https://wordpress.stackexchange.com/users/136332", "pm_score": 1, "selected": false, "text": "<p>I had this same issue today, not sure if its relevant but for me the fix was, go to the edit page section, expand screen options, page attributes was not ticked, ticked it and the template dropdown came back.</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184104", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70344/" ]
Update: As with so many mysteries, the cause turned out to be extremely stupid. I had the file saved in a different theme's directory. Thanks to @a4jp.com I'm building a theme using underscores. I've created a template file and added a template header at the top. ``` <?php /** * Template Name: Featured **/ get_header(); ?> ``` I'm not getting a Template drop down under Page Attributes in the page editor, so I'm not sure if there's a problem with my formatting or something else. I did try switching themes. The drop down appears in the other theme, but when I switch back to my custom theme, it's still missing.
Maybe this will help. ``` <?php /* Template Name: Featured */ get_header(); ?> ``` Regular code here... ``` <?php get_footer(); ?> ``` If one theme works you could try replacing the files in the broken theme and test which file or files are broken. But first save the old files in a separate folder as a backup. Then you would know which file or files are broken pretty quickly.
184,122
<p>I'm having an issue inserting a wrapper div into my php index file that we're using for the front page of the site. </p> <p>Right now it looks like this: <img src="https://i.stack.imgur.com/4vxyz.png" alt="Ugly!"></p> <p>And it needs to look like this: <img src="https://i.stack.imgur.com/QBZ7z.png" alt="Much better!"></p> <p>I'm aware this is a CSS issue, and the fix I can think of is to insert a wrapper div around those 6 divs on the home page, But I don't know where to put the code, which is here:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php global $woo_options; ?&gt; &lt;?php if ( $woo_options['woo_featured_disable'] &lt;&gt; "true" ) include( TEMPLATEPATH . '/includes/featured.php'); ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'infobox', 'order' =&gt; 'DESC', // DESC for newer first. 'orderby' =&gt; 'date', 'posts_per_page' =&gt; 6 // For a 3x2 grid. ); $latest = new WP_Query( $args ); // You now have an object you can use in 'The Loop'. if ( $latest-&gt;have_posts() ) { while ($latest-&gt;have_posts()) : $latest-&gt;the_post(); ?&gt; &lt;div class="bskhp_t"&gt; &lt;a href="&lt;?php echo get_post_meta($post-&gt;ID, 'mini_readmore', true); ?&gt;"&gt; &lt;img src="&lt;?php echo get_post_meta($post-&gt;ID, 'mini', true); ?&gt;" alt="" class="home-icon"&gt; &lt;/a&gt; &lt;div class="bskhp_f"&gt; &lt;a href="&lt;?php echo get_post_meta($post-&gt;ID, 'mini_readmore', true); ?&gt;"&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;/a&gt; &lt;p class="mini-p"&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'mini_excerpt', true); ?&gt;&lt;/p&gt; &lt;a href="&lt;?php echo get_post_meta($post-&gt;ID, 'mini_readmore', true); ?&gt;"&gt; &lt;span&gt;Read more&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; } $v = array(); $upload_dir = wp_upload_dir(); $v[] = "&lt;div class=\"bskhp_vpv\"&gt;&lt;a href='https://www.youtube.com/watch?v=x6HQ4MFqMg0' target='_blank' style='color:#445567;font-family:arial;font-size:12px;font-weight:500'&gt;&lt;img style='padding:4px;border:1px solid #000000; width:180px; height:90px' src='".$upload_dir["baseurl"]."/2015/04/video-capture-1.png' width='180' height='90' vwidth='180' vheight='90' /&gt;&lt;div style='color:#000000;font-family:arial;font-size:12px; padding:4px 0'&gt;Mental Health, Homelessness, and Stability in Housing.&lt;/div&gt;&lt;p style='width:200px'&gt;&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;"; $v[] = "&lt;div class=\"bskhp_vpv\"&gt;&lt;a href='https://www.youtube.com/watch?v=gnMt4_7Xc9M' target='_blank' style='color:#445567;font-family:arial;font-size:12px;font-weight:500'&gt;&lt;img style='padding:4px;border:1px solid #000000; width:180px; height:90px' src='".$upload_dir["baseurl"]."/2015/04/video-capture-2.png' width='180' height='90' vwidth='180' vheight='90' /&gt;&lt;div style='color:#000000;font-family:arial;font-size:12px; padding:4px 0'&gt;2014 Key to Hope luncheon keynote address by Charles Gibson&lt;/div&gt;&lt;p style='width:200px'&gt;&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;"; $v[] = "&lt;div class=\"bskhp_vpv\"&gt;&lt;a href='https://www.youtube.com/watch?v=GKCJTTJq4KM' target='_blank' style='color:#445567;font-family:arial;font-size:12px;font-weight:500'&gt;&lt;img style='padding:4px;border:1px solid #000000; width:180px; height:90px' src='".$upload_dir["baseurl"]."/2015/04/video-capture-3.png' width='180' height='90' vwidth='180' vheight='90' /&gt;&lt;div style='color:#000000;font-family:arial;font-size:12px; padding:4px 0'&gt;Plymouth Housing Group 2013 Documentary&lt;/div&gt;&lt;p style='width:200px'&gt;&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;"; $p = array(); $p[] = "&lt;div&gt;&lt;a href='https://www.plymouthhousing.org/about-us/publications/'&gt;&lt;img src='".$upload_dir["baseurl"]."/2015/04/publications-1.png' height='254' width='190' /&gt;&lt;div class=\"bskhp_pcap\"&gt;ANNUAL REPORTS&lt;/div&gt;&lt;/div&gt;"; $p[] = "&lt;div&gt;&lt;a href='https://www.plymouthhousing.org/about-us/publications/'&gt;&lt;img src='".$upload_dir["baseurl"]."/2015/04/publications-2.png' height='254' width='190' /&gt;&lt;div class=\"bskhp_pcap\"&gt;FACT SHEET &amp;amp; MAPS&lt;/div&gt;&lt;/div&gt;"; $p[] = "&lt;div&gt;&lt;a href='https://www.plymouthhousing.org/about-us/publications/'&gt;&lt;img src='".$upload_dir["baseurl"]."/2015/04/publications-3.png' height='254' width='190' /&gt;&lt;div class=\"bskhp_pcap\"&gt;NEWSLETTER&lt;/div&gt;&lt;/div&gt;"; $mv = array(); $mv[] = "&lt;h3 class='bskhp_h3'&gt;Our Vision&lt;/h3&gt;Housing is just the beginning...the first step to building hope and transforming lives. We envision a day when every person has a home and a better quality of life.&lt;p class=\"bskhp_rm\"&gt;&lt;a href='https://www.plymouthhousing.org/about-us/mission-history/'&gt;READ MORE&lt;/a&gt;&lt;/p&gt;"; $mv[] = "&lt;h3 class='bskhp_h3'&gt;Our Mission&lt;/h3&gt;Plymouth Housing Group works to eliminate homelessness and address its causes by preserving, developing and operating safe, quality, supportive housing and by providing homeless adults with opportunities to stabilize and improve their lives.&lt;p class=\"bskhp_rm\"&gt;&lt;a href='https://www.plymouthhousing.org/about-us/mission-history/'&gt;READ MORE&lt;/a&gt;&lt;/p&gt;"; ?&gt; </code></pre> <p>Someone else graciously helped me with this code earlier, but it's been a long day and my head is pounding :) Does anyone know an easy fix?</p>
[ { "answer_id": 184108, "author": "a4jp.com", "author_id": 70586, "author_profile": "https://wordpress.stackexchange.com/users/70586", "pm_score": 4, "selected": true, "text": "<p>Maybe this will help.</p>\n\n<pre><code>&lt;?php \n/*\nTemplate Name: Featured\n*/\nget_header(); ?&gt;\n</code></pre>\n\n<p>Regular code here...</p>\n\n<pre><code>&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>If one theme works you could try replacing the files in the broken theme and test which file or files are broken. But first save the old files in a separate folder as a backup. Then you would know which file or files are broken pretty quickly.</p>\n" }, { "answer_id": 184109, "author": "TheGentleman", "author_id": 68563, "author_profile": "https://wordpress.stackexchange.com/users/68563", "pm_score": 2, "selected": false, "text": "<p>If you're not seeing the dropdown at all you might need to reload your theme. Try switching to another theme and then switching back.</p>\n" }, { "answer_id": 224004, "author": "P_95", "author_id": 92548, "author_profile": "https://wordpress.stackexchange.com/users/92548", "pm_score": 1, "selected": false, "text": "<p>This has happened two times for me. At the first time I changed the encoding of the file (header.php I think) to <em>UTF-8 without BOM</em> and all <strong>templates</strong> disappeared. Changed it back to regular utf-8.</p>\n\n<p>At the second time I somehow edited/renamed the index.php (/themes/<em>theme_name</em>/index.php). Just had to create an empty index.php and now everything seems to be ok.</p>\n\n<p>I hope this helps someone else.\n[WP 4.4.2]</p>\n" }, { "answer_id": 289429, "author": "Vipul Tank", "author_id": 132364, "author_profile": "https://wordpress.stackexchange.com/users/132364", "pm_score": 2, "selected": false, "text": "<p>By default Wordpress theme directory have not any template page then template page dropdown is invisible so follow the below instruction.</p>\n\n<p>For display template page dropdown in wordpress admin page you need to create one template page in your theme directory code is below</p>\n\n<pre><code>&lt;?php \n/*\nTemplate Name: template home \n*/\n?&gt;\n</code></pre>\n\n<p>By creating this template file in your theme directory you can see template dropdonw is visible in admin page.</p>\n" }, { "answer_id": 293304, "author": "Barry Poore", "author_id": 136332, "author_profile": "https://wordpress.stackexchange.com/users/136332", "pm_score": 1, "selected": false, "text": "<p>I had this same issue today, not sure if its relevant but for me the fix was, go to the edit page section, expand screen options, page attributes was not ticked, ticked it and the template dropdown came back.</p>\n" } ]
2015/04/13
[ "https://wordpress.stackexchange.com/questions/184122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70547/" ]
I'm having an issue inserting a wrapper div into my php index file that we're using for the front page of the site. Right now it looks like this: ![Ugly!](https://i.stack.imgur.com/4vxyz.png) And it needs to look like this: ![Much better!](https://i.stack.imgur.com/QBZ7z.png) I'm aware this is a CSS issue, and the fix I can think of is to insert a wrapper div around those 6 divs on the home page, But I don't know where to put the code, which is here: ``` <?php get_header(); ?> <?php global $woo_options; ?> <?php if ( $woo_options['woo_featured_disable'] <> "true" ) include( TEMPLATEPATH . '/includes/featured.php'); ?> <?php $args = array( 'post_type' => 'infobox', 'order' => 'DESC', // DESC for newer first. 'orderby' => 'date', 'posts_per_page' => 6 // For a 3x2 grid. ); $latest = new WP_Query( $args ); // You now have an object you can use in 'The Loop'. if ( $latest->have_posts() ) { while ($latest->have_posts()) : $latest->the_post(); ?> <div class="bskhp_t"> <a href="<?php echo get_post_meta($post->ID, 'mini_readmore', true); ?>"> <img src="<?php echo get_post_meta($post->ID, 'mini', true); ?>" alt="" class="home-icon"> </a> <div class="bskhp_f"> <a href="<?php echo get_post_meta($post->ID, 'mini_readmore', true); ?>"> <h3><?php the_title(); ?></h3> </a> <p class="mini-p"><?php echo get_post_meta($post->ID, 'mini_excerpt', true); ?></p> <a href="<?php echo get_post_meta($post->ID, 'mini_readmore', true); ?>"> <span>Read more</span> </a> </div> </div> <?php endwhile; } $v = array(); $upload_dir = wp_upload_dir(); $v[] = "<div class=\"bskhp_vpv\"><a href='https://www.youtube.com/watch?v=x6HQ4MFqMg0' target='_blank' style='color:#445567;font-family:arial;font-size:12px;font-weight:500'><img style='padding:4px;border:1px solid #000000; width:180px; height:90px' src='".$upload_dir["baseurl"]."/2015/04/video-capture-1.png' width='180' height='90' vwidth='180' vheight='90' /><div style='color:#000000;font-family:arial;font-size:12px; padding:4px 0'>Mental Health, Homelessness, and Stability in Housing.</div><p style='width:200px'></p></a></div>"; $v[] = "<div class=\"bskhp_vpv\"><a href='https://www.youtube.com/watch?v=gnMt4_7Xc9M' target='_blank' style='color:#445567;font-family:arial;font-size:12px;font-weight:500'><img style='padding:4px;border:1px solid #000000; width:180px; height:90px' src='".$upload_dir["baseurl"]."/2015/04/video-capture-2.png' width='180' height='90' vwidth='180' vheight='90' /><div style='color:#000000;font-family:arial;font-size:12px; padding:4px 0'>2014 Key to Hope luncheon keynote address by Charles Gibson</div><p style='width:200px'></p></a></div>"; $v[] = "<div class=\"bskhp_vpv\"><a href='https://www.youtube.com/watch?v=GKCJTTJq4KM' target='_blank' style='color:#445567;font-family:arial;font-size:12px;font-weight:500'><img style='padding:4px;border:1px solid #000000; width:180px; height:90px' src='".$upload_dir["baseurl"]."/2015/04/video-capture-3.png' width='180' height='90' vwidth='180' vheight='90' /><div style='color:#000000;font-family:arial;font-size:12px; padding:4px 0'>Plymouth Housing Group 2013 Documentary</div><p style='width:200px'></p></a></div>"; $p = array(); $p[] = "<div><a href='https://www.plymouthhousing.org/about-us/publications/'><img src='".$upload_dir["baseurl"]."/2015/04/publications-1.png' height='254' width='190' /><div class=\"bskhp_pcap\">ANNUAL REPORTS</div></div>"; $p[] = "<div><a href='https://www.plymouthhousing.org/about-us/publications/'><img src='".$upload_dir["baseurl"]."/2015/04/publications-2.png' height='254' width='190' /><div class=\"bskhp_pcap\">FACT SHEET &amp; MAPS</div></div>"; $p[] = "<div><a href='https://www.plymouthhousing.org/about-us/publications/'><img src='".$upload_dir["baseurl"]."/2015/04/publications-3.png' height='254' width='190' /><div class=\"bskhp_pcap\">NEWSLETTER</div></div>"; $mv = array(); $mv[] = "<h3 class='bskhp_h3'>Our Vision</h3>Housing is just the beginning...the first step to building hope and transforming lives. We envision a day when every person has a home and a better quality of life.<p class=\"bskhp_rm\"><a href='https://www.plymouthhousing.org/about-us/mission-history/'>READ MORE</a></p>"; $mv[] = "<h3 class='bskhp_h3'>Our Mission</h3>Plymouth Housing Group works to eliminate homelessness and address its causes by preserving, developing and operating safe, quality, supportive housing and by providing homeless adults with opportunities to stabilize and improve their lives.<p class=\"bskhp_rm\"><a href='https://www.plymouthhousing.org/about-us/mission-history/'>READ MORE</a></p>"; ?> ``` Someone else graciously helped me with this code earlier, but it's been a long day and my head is pounding :) Does anyone know an easy fix?
Maybe this will help. ``` <?php /* Template Name: Featured */ get_header(); ?> ``` Regular code here... ``` <?php get_footer(); ?> ``` If one theme works you could try replacing the files in the broken theme and test which file or files are broken. But first save the old files in a separate folder as a backup. Then you would know which file or files are broken pretty quickly.
184,163
<p>I'm looking for a way to prevent the default behaviour (when you have a static page set as the site homepage or 'frontpage' (in <code>settings&gt;reading&gt;front page displays</code> );</p> <p>I want the <code>domain.com/</code> page to point here (as it does), but if I made a page <code>home</code>, which would otherwise live at <code>domain.com/home</code> Wordpress automatically redirects to <code>domain.com</code>, and so there's no way of visiting and staying on <code>domain.com/home</code>.</p> <p>Does anyone have a clue how/where to do this? I've tried investigating php <code>$_SERVER</code> variables and attempting to alter rewrite rules, but I don't find a rule therein that matches this situation reliably. (There is one rule to a page with the <code>home</code> page <code>id</code>, but then I cannot target this reliably (and I think it's actually routing <code>domain.com/</code> -> <code>domain.com/home</code>.)</p> <p>To reiterate (and perhaps clarify), how does one make the wordpress 'frontpage' available at the domain root (as is default and working), but also at the page's default permalink also...</p>
[ { "answer_id": 184170, "author": "Bysander", "author_id": 47618, "author_profile": "https://wordpress.stackexchange.com/users/47618", "pm_score": 0, "selected": false, "text": "<p>If i have understood you correctly you just need your <code>domain.com/home</code> to display your homepage too? Just create this in a folder called <code>home</code> in the same folder as your <code>/wp-content</code> etc </p>\n\n<p>Name it index.php</p>\n\n<pre><code>?php\n header(\"Location: http://domain.com\");\n exit();\n?&gt;\n</code></pre>\n" }, { "answer_id": 184179, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>The redirect is thanks to <a href=\"http://codex.wordpress.org/Function_Reference/redirect_canonical\"><code>redirect_canonical()</code></a> - we can simply swoop in with a filter and disable it for the front page:</p>\n\n<pre><code>function wpse_184163_disable_canonical_front_page( $redirect ) {\n if ( is_page() &amp;&amp; $front_page = get_option( 'page_on_front' ) ) {\n if ( is_page( $front_page ) )\n $redirect = false;\n }\n\n return $redirect;\n}\n\nadd_filter( 'redirect_canonical', 'wpse_184163_disable_canonical_front_page' );\n</code></pre>\n\n<p>Now you can access the front page at the root <strong>and</strong> by it's slug, no redirect.</p>\n" } ]
2015/04/14
[ "https://wordpress.stackexchange.com/questions/184163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6353/" ]
I'm looking for a way to prevent the default behaviour (when you have a static page set as the site homepage or 'frontpage' (in `settings>reading>front page displays` ); I want the `domain.com/` page to point here (as it does), but if I made a page `home`, which would otherwise live at `domain.com/home` Wordpress automatically redirects to `domain.com`, and so there's no way of visiting and staying on `domain.com/home`. Does anyone have a clue how/where to do this? I've tried investigating php `$_SERVER` variables and attempting to alter rewrite rules, but I don't find a rule therein that matches this situation reliably. (There is one rule to a page with the `home` page `id`, but then I cannot target this reliably (and I think it's actually routing `domain.com/` -> `domain.com/home`.) To reiterate (and perhaps clarify), how does one make the wordpress 'frontpage' available at the domain root (as is default and working), but also at the page's default permalink also...
The redirect is thanks to [`redirect_canonical()`](http://codex.wordpress.org/Function_Reference/redirect_canonical) - we can simply swoop in with a filter and disable it for the front page: ``` function wpse_184163_disable_canonical_front_page( $redirect ) { if ( is_page() && $front_page = get_option( 'page_on_front' ) ) { if ( is_page( $front_page ) ) $redirect = false; } return $redirect; } add_filter( 'redirect_canonical', 'wpse_184163_disable_canonical_front_page' ); ``` Now you can access the front page at the root **and** by it's slug, no redirect.
184,168
<p>I need my users to be able to upload files to the media library and therefore need to somehow automatically set the user role to something other than the default "subscriber" when they register. </p> <p>I know in Settings > General you can set the ‘New User Default Role’, however if I change this to a role that allows user uploads this gives access to the main media library. If they could upload to their own media library that would be great but I don’t want everyone seeing everyone elses files in the media library.</p> <p>I am using Buddypress but can't find any documentation on this and so have installed the Members Plugin to see if this would help but I am still struggling to find out exactly how this would be implemented. </p> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 184170, "author": "Bysander", "author_id": 47618, "author_profile": "https://wordpress.stackexchange.com/users/47618", "pm_score": 0, "selected": false, "text": "<p>If i have understood you correctly you just need your <code>domain.com/home</code> to display your homepage too? Just create this in a folder called <code>home</code> in the same folder as your <code>/wp-content</code> etc </p>\n\n<p>Name it index.php</p>\n\n<pre><code>?php\n header(\"Location: http://domain.com\");\n exit();\n?&gt;\n</code></pre>\n" }, { "answer_id": 184179, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>The redirect is thanks to <a href=\"http://codex.wordpress.org/Function_Reference/redirect_canonical\"><code>redirect_canonical()</code></a> - we can simply swoop in with a filter and disable it for the front page:</p>\n\n<pre><code>function wpse_184163_disable_canonical_front_page( $redirect ) {\n if ( is_page() &amp;&amp; $front_page = get_option( 'page_on_front' ) ) {\n if ( is_page( $front_page ) )\n $redirect = false;\n }\n\n return $redirect;\n}\n\nadd_filter( 'redirect_canonical', 'wpse_184163_disable_canonical_front_page' );\n</code></pre>\n\n<p>Now you can access the front page at the root <strong>and</strong> by it's slug, no redirect.</p>\n" } ]
2015/04/14
[ "https://wordpress.stackexchange.com/questions/184168", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66275/" ]
I need my users to be able to upload files to the media library and therefore need to somehow automatically set the user role to something other than the default "subscriber" when they register. I know in Settings > General you can set the ‘New User Default Role’, however if I change this to a role that allows user uploads this gives access to the main media library. If they could upload to their own media library that would be great but I don’t want everyone seeing everyone elses files in the media library. I am using Buddypress but can't find any documentation on this and so have installed the Members Plugin to see if this would help but I am still struggling to find out exactly how this would be implemented. Any help would be greatly appreciated.
The redirect is thanks to [`redirect_canonical()`](http://codex.wordpress.org/Function_Reference/redirect_canonical) - we can simply swoop in with a filter and disable it for the front page: ``` function wpse_184163_disable_canonical_front_page( $redirect ) { if ( is_page() && $front_page = get_option( 'page_on_front' ) ) { if ( is_page( $front_page ) ) $redirect = false; } return $redirect; } add_filter( 'redirect_canonical', 'wpse_184163_disable_canonical_front_page' ); ``` Now you can access the front page at the root **and** by it's slug, no redirect.
184,211
<p>I want to reduce the font size of the text inside the table so I can fit in more columns. Is there a hook I can use or do I need to modify wordpress/woocommerce's core? In that case, which css or template file do i need to change?<img src="https://i.stack.imgur.com/TFAU3.png" alt="woocommerce-products-listing-page"> </p>
[ { "answer_id": 184254, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>admin_print_styles</code> hook to output custom CSS - in this case I've used the suffix <code>-edit.php</code> (which is the unique hook for the posts table screen). I also check the current post type is <code>product</code>, otherwise the CSS would output for pages, posts etc.</p>\n\n<pre><code>function wpse_184211_edit_products_style() {\n if ( get_current_screen()-&gt;post_type === 'product' ) {\n ?&gt;\n\n&lt;style&gt;\n .column-purpose {\n font-size: 10px;\n }\n&lt;/style&gt;\n\n&lt;?php\n }\n}\n\nadd_action( 'admin_print_styles-edit.php', 'wpse_184211_edit_products_style' );\n</code></pre>\n\n<p>The CSS is an example - just inspect/check out the source code of the page and you'll see which class names/selectors you need to use.</p>\n" }, { "answer_id": 184389, "author": "Bainternet", "author_id": 2487, "author_profile": "https://wordpress.stackexchange.com/users/2487", "pm_score": 1, "selected": false, "text": "<p>Another option would be to use the <code>current_screen</code> hook</p>\n\n<pre><code>add_action( 'current_screen', 'my_admin_listing_custom_styles' );\nfunction my_admin_listing_custom_styles() {\n $current_screen = get_current_screen();\n if( 'edit' == $current_screen-&gt;base &amp;&amp; 'product' == $current_screen-&gt;post_type) {\n // Run some code, only on the admin products listing page for e.x add css style\n ?&gt;\n &lt;style type=\"text/css\"&gt;\n a.row-title {font-size: 18px !important;}\n &lt;/style&gt;\n &lt;?php\n }\n}\n</code></pre>\n" }, { "answer_id": 285863, "author": "Stathis", "author_id": 131480, "author_profile": "https://wordpress.stackexchange.com/users/131480", "pm_score": -1, "selected": false, "text": "<p>You can customize the price font, price size, price color, with the Woo Product Price Styler plugin, the link is <a href=\"https://codecanyon.net/item/woo-product-price-styler/15730651\" rel=\"nofollow noreferrer\">https://codecanyon.net/item/woo-product-price-styler/15730651</a></p>\n" }, { "answer_id": 285867, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 0, "selected": false, "text": "<p>You can add an custom CSS sheet to your admin and style things however you like.</p>\n\n<ol>\n<li><p>Create a new CSS document in your theme folder called <code>admin-style.css</code> and add your rules there. For example:</p>\n\n<pre><code>.wp-list-table .row-title,\n.wp-list-table th,\n.wp-list-table td,\n.row-actions {\n font-size: 11px !important;\n}\n</code></pre></li>\n<li><p>Add the following code to your <code>functions.php</code> file:</p>\n\n<pre><code>function load_custom_wp_admin_style() {\n wp_register_style( 'custom_wp_admin_css', get_stylesheet_directory_uri() . '/admin-style.css', false, '1.0.0' );\n wp_enqueue_style( 'custom_wp_admin_css' );\n}\nadd_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );\n</code></pre></li>\n</ol>\n\n<p>This avoids modifying the core, is child theme friendly, and allows you to easily modify other styles inside the admin as needed.</p>\n" } ]
2015/04/14
[ "https://wordpress.stackexchange.com/questions/184211", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58172/" ]
I want to reduce the font size of the text inside the table so I can fit in more columns. Is there a hook I can use or do I need to modify wordpress/woocommerce's core? In that case, which css or template file do i need to change?![woocommerce-products-listing-page](https://i.stack.imgur.com/TFAU3.png)
Another option would be to use the `current_screen` hook ``` add_action( 'current_screen', 'my_admin_listing_custom_styles' ); function my_admin_listing_custom_styles() { $current_screen = get_current_screen(); if( 'edit' == $current_screen->base && 'product' == $current_screen->post_type) { // Run some code, only on the admin products listing page for e.x add css style ?> <style type="text/css"> a.row-title {font-size: 18px !important;} </style> <?php } } ```
184,235
<p>I have a variable in header.php, such as:</p> <pre><code>$page_extra_title = get_post_meta($this_page-&gt;ID, "_theme_extra_title", true); </code></pre> <p>Once I do:</p> <pre><code>var_dump($page_extra_title); </code></pre> <p>I always get <code>NULL</code> outside of header.php (var_dump works properly in header.php only). I've been pasting the same variable everywhere I need it (page.php, post.php, footer.php etc.), but it's madness and makes everything almost impossible to maintain.</p> <p>I'm wondering what's the best way of passing a variable through all the files in my theme? I guess using functions.php along with "get_post_meta" might not be the best idea? :)</p>
[ { "answer_id": 184239, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 4, "selected": true, "text": "<h2>Basic separated data structures</h2>\n\n<p>To pass around data, you normally utilize a <em>Model</em> (that's the \"M\" in \"MVC\"). Let's look at a very simple interface for data. <em>Interfaces</em> are just used as \"Recipes\" for our building blocks:</p>\n\n<pre><code>namespace WeCodeMore\\Package\\Models;\ninterface ArgsInterface\n{\n public function getID();\n public function getLabel();\n}\n</code></pre>\n\n<p>Above is what we pass around: A common ID and a \"Label\".</p>\n\n<h2>Displaying data by combining atomic pieces</h2>\n\n<p>Next we need some <em>View</em> that negotiates between our Model and ... our template.</p>\n\n<pre><code>namespace WeCodeMore\\Package;\ninterface PackageViewInterface\n{\n /**\n * @param Models\\ArgsInterface $args\n * @return int|void\n */\n public function render( Models\\ArgsInterface $args );\n}\n</code></pre>\n\n<p>Basically that <em>Interface</em> says </p>\n\n<blockquote>\n <p>\"We can render something and a Model is mandatory for that task\"</p>\n</blockquote>\n\n<p>Finally we need to implement above and build the actual <em>View</em>. As you can see, the constructor tells that the mandatory thing for our view is a <em>Template</em> and that we can render it. For the sake of easy development we even check if the template file actually is present so we can make other developers lives (and ours as well) much easier and note that.</p>\n\n<p>In a second step in the render function we use a <em>Closure</em> to build the actual template wrapper and <code>bindTo()</code> the Model to the template.</p>\n\n<pre><code>namespace WeCodeMore\\Package;\n\nuse WeCodeMore\\Package\\Models\\ArgsInterface;\n\n/** @noinspection PhpInconsistentReturnPointsInspection */\nclass PackageView implements PackageViewInterface\n{\n /** @var string|\\WP_Error */\n private $template;\n /**\n * @param string $template\n */\n public function __construct( $template )\n {\n $this-&gt;template = ! file_exists( $template )\n ? new \\WP_Error( 'wcm-package', 'A package view needs a template' )\n : $template;\n }\n /**\n * @param Models\\ArgsInterface $args\n * @return int|void\n */\n public function render( Models\\ArgsInterface $args )\n {\n if ( is_wp_error( $this-&gt;template ) )\n return print $this-&gt;template-&gt;get_error_message();\n\n /** @var $callback \\Closure */\n $callback = function( $template )\n {\n extract( get_object_vars( $this ) );\n require $template;\n };\n call_user_func(\n $callback-&gt;bindTo( $args ),\n $this-&gt;template\n );\n }\n}\n</code></pre>\n\n<h2>Separating the View and Rendering</h2>\n\n<p>This means that we can use a very simple template like the following</p>\n\n<pre><code>&lt;!--suppress HtmlFormInputWithoutLabel --&gt;\n&lt;p&gt;&lt;?= $label ?&gt;&lt;/p&gt;\n</code></pre>\n\n<p>to render our content. Putting the pieces together we would get something around the following lines (in our Controller, Mediator, etc.):</p>\n\n<pre><code>namespace WeCodeMore\\Package;\n\n$view = new PackageView( plugin_dir_path( __FILE__ ).'tmpl/label.tmpl.php' );\n$view-&gt;render( new Models\\Args );\n</code></pre>\n\n<h2>What did we gain?</h2>\n\n<p>This way we can </p>\n\n<ol>\n<li>Easily exchange templates without changing the data structure</li>\n<li>Have easy to read tempaltes</li>\n<li>Avoid global scope</li>\n<li>Can Unit-Test</li>\n<li>Can exchange the Model/the data without harming other components</li>\n</ol>\n\n<h2>Combining OOP PHP with the WP API</h2>\n\n<p>Of course this is hardly possible by using basic theming functionality like <code>get_header()</code>, <code>get_footer()</code>, etc., right? Wrong. Just call your classes in whatever template or template part you would like. Render it, transform the data, do whatever you want. If you are really nice you even just add your own bunch of custom filters and have some negotiator to take care of what gets rendered by which controller on which route/conditional template load.</p>\n\n<h2>Conclusion?</h2>\n\n<p>You can work with stuff like above in WP without a problem and still stick to the basic API and reuse code and data without calling a single global or messing up and polluting the global name space.</p>\n" }, { "answer_id": 184249, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 2, "selected": false, "text": "<p>Although kaiser's answer is technically right, I doubt it's the best answer for you.</p>\n\n<p>If you're creating your own theme, then I think it is indeed the best way to set up some sort of framework using classes (and maybe namespaces and interfaces too, although that might be a little too much for a WP theme).</p>\n\n<p>On the other hand, if you are just extending / adjusting an existing theme and only need to pass one or a few variables, I think you should stick with <code>global</code>. Because <code>header.php</code> is included within a function, the variables you declare in that file are usable in that file only. With <code>global</code> you make them accessible in the whole WP project:</p>\n\n<p>In <code>header.php</code>:</p>\n\n<pre><code>global $page_extra_title;\n\n$page_extra_title = get_post_meta($this_page-&gt;ID, \"_theme_extra_title\", true);\n</code></pre>\n\n<p>In <code>single.php</code> (for example):</p>\n\n<pre><code>global $page_extra_title;\n\nvar_dump( $page_extra_title );\n</code></pre>\n" }, { "answer_id": 184251, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": false, "text": "<p>Simple answer, don't pass variables anywhere as it stinks of using global variables which is evil.</p>\n\n<p>From your example it seems like you are trying to do an early optimization, yet another evil ;)</p>\n\n<p>Use the wordpress API to get data which is stored in the DB and don't try to outsmart and optimize its usage as the API do more then just retrieving values and it activates filters and actions. By removing the API call you remove the ability of other developers to change the behavior of your code without modifying it.</p>\n" }, { "answer_id": 184295, "author": "pbd", "author_id": 18968, "author_profile": "https://wordpress.stackexchange.com/users/18968", "pm_score": 1, "selected": false, "text": "<p>An easy solution is to write a function to get the extra title. I use a static variable to keep the database calls to one only. Put this in your functions.php.</p>\n\n<pre><code>function get_extra_title($post_id) {\n static $title = null;\n if ($title === null) {\n $title = get_post_meta($post_id, \"_theme_extra_title\", true)\n }\n return $title;\n}\n</code></pre>\n\n<p>Outside header.php, call the function to get the value:</p>\n\n<pre><code>var_dump(get_extra_title($post-&gt;ID));\n</code></pre>\n" }, { "answer_id": 184302, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": false, "text": "<p>This is an alternative approach to <a href=\"https://wordpress.stackexchange.com/users/385/kaiser\">@kaiser</a> answer, that I found pretty fine (+1 from me) but requires additional work to be used with core WP functions and it's per-se low integrated with template hierarchy.</p>\n\n<p>The approach I want to share is based on a single class (it's a stripped-down version from something I'm working on) that takes care of render data for templates.</p>\n\n<p>It has some (IMO) interesting features:</p>\n\n<ul>\n<li>templates are standard WordPress template files (single.php, page.php) they get a bit of more <em>power</em></li>\n<li>existing templates just work, so you can integrate template from existent themes with no effort</li>\n<li>unlike <a href=\"https://wordpress.stackexchange.com/users/385/kaiser\">@kaiser</a> approach, in templates you access variables using <code>$this</code> keyword: this gives you the possibility to avoid notices in production in case of undefined variables</li>\n</ul>\n\n<h2>The <code>Engine</code> Class</h2>\n\n<pre><code>namespace GM\\Template;\n\nclass Engine\n{\n private $data;\n private $template;\n private $debug = false;\n\n /**\n * Bootstrap rendering process. Should be called on 'template_redirect'.\n */\n public static function init()\n {\n add_filter('template_include', new static(), 99, 1);\n }\n\n /**\n * Constructor. Sets debug properties.\n */\n public function __construct()\n {\n $this-&gt;debug =\n (! defined('WP_DEBUG') || WP_DEBUG)\n &amp;&amp; (! defined('WP_DEBUG_DISPLAY') || WP_DEBUG_DISPLAY);\n }\n\n /**\n * Render a template.\n * Data is set via filters (for main template) or passed to method for partials.\n * @param string $template template file path\n * @param array $data template data\n * @param bool $partial is the template a partial?\n * @return mixed|void\n */\n public function __invoke($template, array $data = array(), $partial = false)\n {\n if ($partial || $template) {\n $this-&gt;data = $partial\n ? $data\n : $this-&gt;provide(substr(basename($template), 0, -4));\n require $template;\n $partial or exit;\n }\n\n return $template;\n }\n\n /**\n * Render a partial.\n * Partial-specific data can be passed to method.\n * @param string $template template file path\n * @param array $data template data\n * @param bool $isolated when true partial has no access on parent template context\n */\n public function partial($partial, array $data = array(), $isolated = false)\n {\n do_action(\"get_template_part_{$partial}\", $partial, null);\n $file = locate_template(\"{$partial}.php\");\n if ($file) {\n $class = __CLASS__;\n $template = new $class();\n $template_data = $isolated ? $data : array_merge($this-&gt;data, $data);\n $template($file, $template_data, true);\n } elseif ($this-&gt;debug) {\n throw new \\RuntimeException(\"{$partial} is not a valid partial.\");\n }\n }\n\n /**\n * Used in templates to access data.\n * @param string $name\n * @return string\n */\n public function __get($name)\n {\n if (array_key_exists($name, $this-&gt;data)) {\n return $this-&gt;data[$name];\n }\n if ($this-&gt;debug) {\n throw new \\RuntimeException(\"{$name} is undefined.\");\n }\n\n return '';\n }\n\n /**\n * Provide data to templates using two filters hooks:\n * one generic and another query type specific.\n * @param string $type Template file name (without extension, e.g. \"single\")\n * @return array\n */\n private function provide($type)\n {\n $generic = apply_filters('gm_template_data', array(), $type);\n $specific = apply_filters(\"gm_template_data_{$type}\", array());\n\n return array_merge(\n is_array($generic) ? $generic : array(),\n is_array($specific) ? $specific : array()\n );\n }\n}\n</code></pre>\n\n<p>(Available as <a href=\"https://gist.github.com/Giuseppe-Mazzapica/fb058aa5f6b68ad6ab27\" rel=\"nofollow noreferrer\">Gist</a> here.)</p>\n\n<h2>How to use</h2>\n\n<p>Only thing needed is to call the <code>Engine::init()</code> method, probably on <code>'template_redirect'</code> hook. That can be done in theme <code>functions.php</code> or from a plugin.</p>\n\n<pre><code>require_once '/path/to/the/file/Engine.php';\nadd_action('template_redirect', array('GM\\Template\\Engine', 'init'), 99);\n</code></pre>\n\n<p>That's all.</p>\n\n<p>Your existing templates will work as expcted. But now you have the possibility to access custom template data.</p>\n\n<h2>Custom Template Data</h2>\n\n<p>To pass custom data to templates there are two filters:</p>\n\n<ul>\n<li><code>'gm_template_data'</code></li>\n<li><code>'gm_template_data_{$type}'</code></li>\n</ul>\n\n<p>The first one is fired for all templates, the second is template specific, in fact, the dymamic part <code>{$type}</code> is the basename of the template file without file extension.</p>\n\n<p>E.g. the filter <code>'gm_template_data_single'</code> can be used to pass data to the <code>single.php</code> template.</p>\n\n<p>The callbacks attached to these hooks <strong>have to return an array</strong>, where the keys are the variable names.</p>\n\n<p>For example, you can pass meta data as template data likes so:</p>\n\n<pre><code>add_filter('gm_template_data', function($data) {\n if (is_singular()) {\n $id = get_queried_object_id();\n $data['extra_title'] = get_post_meta($id, \"_theme_extra_title\", true);\n }\n\n return $data;\n};\n</code></pre>\n\n<p>And then, inside the template you can just use:</p>\n\n<pre><code>&lt;?= $this-&gt;extra_title ?&gt;\n</code></pre>\n\n<h2>Debug Mode</h2>\n\n<p>When both the constants <code>WP_DEBUG</code> and <code>WP_DEBUG_DISPLAY</code> are true, the class worksin debug mode. It means that if a variable is not defined an exception is thrown.</p>\n\n<p>When the class is not in debug mode (probably in production) accessing an undefined variable will output an empty string.</p>\n\n<h2>Data Models</h2>\n\n<p>A nice and maintenable way to organize your data is to use model classes.</p>\n\n<p>They can be very simple classes, that return data using same filters described above.\nThere is no particular interface to follow, they can be organized accordi to your preference.</p>\n\n<p>Belowe, there is just an example, but you are free to do in your own way.</p>\n\n<pre><code>class SeoModel\n{\n public function __invoke(array $data, $type = '')\n {\n switch ($type) {\n case 'front-page':\n case 'home':\n $data['seo_title'] = 'Welcome to my site';\n break;\n default:\n $data['seo_title'] = wp_title(' - ', false, 'right');\n break;\n }\n\n return $data;\n }\n}\n\nadd_filter('gm_template_data', new SeoModel(), 10, 2);\n</code></pre>\n\n<p>The <code>__invoke()</code> method (that runs when a class is used like a callback) returns a string to be used for the <code>&lt;title&gt;</code> tag of the template.</p>\n\n<p>Thanks to the fact that the second argument passed by <code>'gm_template_data'</code> is the template name, the method returns a custom title for home page.</p>\n\n<p>Having the code above, is then possible to use something like</p>\n\n<pre><code> &lt;title&gt;&lt;?= $this-&gt;seo_title ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>in the <code>&lt;head&gt;</code> section of the page.</p>\n\n<h2>Partials</h2>\n\n<p>WordPress has functions like <code>get_header()</code> or <code>get_template_part()</code> that can be used to load partials into main template.</p>\n\n<p>These functions, just like all the other WordPress functions, can be used in templates when using the <code>Engine</code> class.</p>\n\n<p>The only problem is that inside the partials loaded using the core WordPress functions is not possible to use the <em>advanced</em> feature of getting custom template data using <code>$this</code>.</p>\n\n<p>For this reason, the <code>Engine</code> class has a method <code>partial()</code> that allows to load a partial (in a fully child-theme compatible way) and still be able to use in partials the custom template data.</p>\n\n<p>The usage is pretty simple.</p>\n\n<p>Assuming there is a file named <code>partials/content.php</code> inside theme (or child theme) folder, it can be included using:</p>\n\n<pre><code>&lt;?php $this-&gt;partial('partials/content') ?&gt;\n</code></pre>\n\n<p>Inside that partial will be possible to access all parent theme data is the same way.</p>\n\n<p>Unlike WordPress functions, <code>Engine::partial()</code> method allows to pass specific data to partials, simply passing an array of data as second argument.</p>\n\n<pre><code>&lt;?php $this-&gt;partial('partials/content', array('greeting' =&gt; 'Welcome!')) ?&gt;\n</code></pre>\n\n<p>By default, partials have access to data available in parent theme and to data explicilty passed .</p>\n\n<p>If some variable explicitly passed to partial has the same name of a parent theme variable, then the variable explicitly passed wins.</p>\n\n<p>However, is also possible to include a partial in <em>isolated</em> mode, i.e. the partial has no access to parent theme data. To do that, just pass <code>true</code> as third argument to <code>partial()</code>:</p>\n\n<pre><code>&lt;?php $this-&gt;partial('partials/content', array('greeting' =&gt; 'Welcome!'), true) ?&gt;\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Even if pretty simple, <code>Engine</code> class is pretty complete, but surely can be further improved. E.g. there is no way to check if a variable is defined or not.</p>\n\n<p>Thanks to its 100% compatibility with WordPress features and template hierarchy you can integrate it with existing and third party code with no issue.</p>\n\n<p>However, note that is only partially tested, so is possible there are issues I have not discovered yet.</p>\n\n<p>The five points under <strong>\"What did we gain?\"</strong> in <a href=\"https://wordpress.stackexchange.com/users/385/kaiser\">@kaiser</a> <a href=\"https://wordpress.stackexchange.com/a/184239/35541\">answer</a>:</p>\n\n<ol>\n<li>Easily exchange templates without changing the data structure</li>\n<li>Have easy to read tempaltes</li>\n<li>Avoid global scope</li>\n<li>Can Unit-Test</li>\n<li>Can exchange the Model/the data without harming other components</li>\n</ol>\n\n<p>are all valid for my class as well.</p>\n" } ]
2015/04/14
[ "https://wordpress.stackexchange.com/questions/184235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1869/" ]
I have a variable in header.php, such as: ``` $page_extra_title = get_post_meta($this_page->ID, "_theme_extra_title", true); ``` Once I do: ``` var_dump($page_extra_title); ``` I always get `NULL` outside of header.php (var\_dump works properly in header.php only). I've been pasting the same variable everywhere I need it (page.php, post.php, footer.php etc.), but it's madness and makes everything almost impossible to maintain. I'm wondering what's the best way of passing a variable through all the files in my theme? I guess using functions.php along with "get\_post\_meta" might not be the best idea? :)
Basic separated data structures ------------------------------- To pass around data, you normally utilize a *Model* (that's the "M" in "MVC"). Let's look at a very simple interface for data. *Interfaces* are just used as "Recipes" for our building blocks: ``` namespace WeCodeMore\Package\Models; interface ArgsInterface { public function getID(); public function getLabel(); } ``` Above is what we pass around: A common ID and a "Label". Displaying data by combining atomic pieces ------------------------------------------ Next we need some *View* that negotiates between our Model and ... our template. ``` namespace WeCodeMore\Package; interface PackageViewInterface { /** * @param Models\ArgsInterface $args * @return int|void */ public function render( Models\ArgsInterface $args ); } ``` Basically that *Interface* says > > "We can render something and a Model is mandatory for that task" > > > Finally we need to implement above and build the actual *View*. As you can see, the constructor tells that the mandatory thing for our view is a *Template* and that we can render it. For the sake of easy development we even check if the template file actually is present so we can make other developers lives (and ours as well) much easier and note that. In a second step in the render function we use a *Closure* to build the actual template wrapper and `bindTo()` the Model to the template. ``` namespace WeCodeMore\Package; use WeCodeMore\Package\Models\ArgsInterface; /** @noinspection PhpInconsistentReturnPointsInspection */ class PackageView implements PackageViewInterface { /** @var string|\WP_Error */ private $template; /** * @param string $template */ public function __construct( $template ) { $this->template = ! file_exists( $template ) ? new \WP_Error( 'wcm-package', 'A package view needs a template' ) : $template; } /** * @param Models\ArgsInterface $args * @return int|void */ public function render( Models\ArgsInterface $args ) { if ( is_wp_error( $this->template ) ) return print $this->template->get_error_message(); /** @var $callback \Closure */ $callback = function( $template ) { extract( get_object_vars( $this ) ); require $template; }; call_user_func( $callback->bindTo( $args ), $this->template ); } } ``` Separating the View and Rendering --------------------------------- This means that we can use a very simple template like the following ``` <!--suppress HtmlFormInputWithoutLabel --> <p><?= $label ?></p> ``` to render our content. Putting the pieces together we would get something around the following lines (in our Controller, Mediator, etc.): ``` namespace WeCodeMore\Package; $view = new PackageView( plugin_dir_path( __FILE__ ).'tmpl/label.tmpl.php' ); $view->render( new Models\Args ); ``` What did we gain? ----------------- This way we can 1. Easily exchange templates without changing the data structure 2. Have easy to read tempaltes 3. Avoid global scope 4. Can Unit-Test 5. Can exchange the Model/the data without harming other components Combining OOP PHP with the WP API --------------------------------- Of course this is hardly possible by using basic theming functionality like `get_header()`, `get_footer()`, etc., right? Wrong. Just call your classes in whatever template or template part you would like. Render it, transform the data, do whatever you want. If you are really nice you even just add your own bunch of custom filters and have some negotiator to take care of what gets rendered by which controller on which route/conditional template load. Conclusion? ----------- You can work with stuff like above in WP without a problem and still stick to the basic API and reuse code and data without calling a single global or messing up and polluting the global name space.
184,258
<p>I've made a new template file for Wordpress constructing the elements of the page via PHP and Wordpress recognizes the template as such.</p> <p>Then I wanted to include a CSS file for said template (same folder) and went with the standard:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="style.css"&gt; </code></pre> <p>but for some reason the PHP file does not load the linked CSS settings. if I add</p> <pre><code>&lt;? include('style.css') ?&gt; </code></pre> <p>the content of it gets printed onto the page, meaning the php file can read it. So why doesn't it load the CSS settings?</p> <p>Thanks for any help</p>
[ { "answer_id": 184260, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": true, "text": "<p>CSS links are relative to the current request URI, not your PHP file. Use an absolute path like:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php bloginfo( 'template_url' ) ?&gt;/themesubfolder/style.css\" /&gt;\n</code></pre>\n" }, { "answer_id": 184262, "author": "Dking", "author_id": 70654, "author_profile": "https://wordpress.stackexchange.com/users/70654", "pm_score": 1, "selected": false, "text": "<p>Add below code to your functions.php</p>\n\n<pre><code> function add_script_and_style() {\n // for .css add \n wp_enqueue_style('my-style', get_template_directory_uri() . '/my_style.css');\n\n // for .js add\n wp_enqueue_script( 'my-js', get_template_directory_uri() .'/filename.js', false );\n }\n\n add_action( 'wp_enqueue_scripts', 'add_script_and_style' );\n</code></pre>\n\n<p>Extra Info: Wordpress standard way to do</p>\n\n<p>wp_enqueue_style function for .css file</p>\n\n<p>AND\nwp_enqueue_scripts function for .js script file.</p>\n\n<p>Thank you</p>\n" } ]
2015/04/15
[ "https://wordpress.stackexchange.com/questions/184258", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63130/" ]
I've made a new template file for Wordpress constructing the elements of the page via PHP and Wordpress recognizes the template as such. Then I wanted to include a CSS file for said template (same folder) and went with the standard: ``` <link rel="stylesheet" type="text/css" href="style.css"> ``` but for some reason the PHP file does not load the linked CSS settings. if I add ``` <? include('style.css') ?> ``` the content of it gets printed onto the page, meaning the php file can read it. So why doesn't it load the CSS settings? Thanks for any help
CSS links are relative to the current request URI, not your PHP file. Use an absolute path like: ``` <link rel="stylesheet" href="<?php bloginfo( 'template_url' ) ?>/themesubfolder/style.css" /> ```
184,271
<p>Hi guys wonder if there is something like a guide to use git to manage WP projects. I have always been a cowboy coder, and I need to make this shift to Git to become more standarized...how can I begin? at least i would love to have my theme in GIT to have a backup copy of it and be able to track the changes. Im the only person working on the project, but I need to prepare myself for future jobs so I want to test this GIT+WP.</p>
[ { "answer_id": 184260, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": true, "text": "<p>CSS links are relative to the current request URI, not your PHP file. Use an absolute path like:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php bloginfo( 'template_url' ) ?&gt;/themesubfolder/style.css\" /&gt;\n</code></pre>\n" }, { "answer_id": 184262, "author": "Dking", "author_id": 70654, "author_profile": "https://wordpress.stackexchange.com/users/70654", "pm_score": 1, "selected": false, "text": "<p>Add below code to your functions.php</p>\n\n<pre><code> function add_script_and_style() {\n // for .css add \n wp_enqueue_style('my-style', get_template_directory_uri() . '/my_style.css');\n\n // for .js add\n wp_enqueue_script( 'my-js', get_template_directory_uri() .'/filename.js', false );\n }\n\n add_action( 'wp_enqueue_scripts', 'add_script_and_style' );\n</code></pre>\n\n<p>Extra Info: Wordpress standard way to do</p>\n\n<p>wp_enqueue_style function for .css file</p>\n\n<p>AND\nwp_enqueue_scripts function for .js script file.</p>\n\n<p>Thank you</p>\n" } ]
2015/04/15
[ "https://wordpress.stackexchange.com/questions/184271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50943/" ]
Hi guys wonder if there is something like a guide to use git to manage WP projects. I have always been a cowboy coder, and I need to make this shift to Git to become more standarized...how can I begin? at least i would love to have my theme in GIT to have a backup copy of it and be able to track the changes. Im the only person working on the project, but I need to prepare myself for future jobs so I want to test this GIT+WP.
CSS links are relative to the current request URI, not your PHP file. Use an absolute path like: ``` <link rel="stylesheet" href="<?php bloginfo( 'template_url' ) ?>/themesubfolder/style.css" /> ```
184,310
<p>I've done a plugin where you can add shortcode like this: <code>[myplugin xx]</code> (where <code>xx</code> is a number which calls a specific content <code>xx</code>).</p> <p>I have to do a multilingual version of my plugin, so here's my trick: my client writes content <code>xx</code> for language #1 and content <code>yy</code> for language #2.</p> <p>Then, in an article, he would have to add something like: </p> <pre><code>[multilingualmyplugin #1 xx][multilingualmyplugin #2 yy] </code></pre> <p>and then I should just have to write a plugin that is called and change the content <em>before</em> Wordpress calls my first plugin to either <code>[myplugin xx]</code> or <code>[myplugin yy]</code> depending on the domain name. Then Wordpress would call the plugin.</p> <p>Is it possible and if so, where should I look?</p>
[ { "answer_id": 184260, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": true, "text": "<p>CSS links are relative to the current request URI, not your PHP file. Use an absolute path like:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php bloginfo( 'template_url' ) ?&gt;/themesubfolder/style.css\" /&gt;\n</code></pre>\n" }, { "answer_id": 184262, "author": "Dking", "author_id": 70654, "author_profile": "https://wordpress.stackexchange.com/users/70654", "pm_score": 1, "selected": false, "text": "<p>Add below code to your functions.php</p>\n\n<pre><code> function add_script_and_style() {\n // for .css add \n wp_enqueue_style('my-style', get_template_directory_uri() . '/my_style.css');\n\n // for .js add\n wp_enqueue_script( 'my-js', get_template_directory_uri() .'/filename.js', false );\n }\n\n add_action( 'wp_enqueue_scripts', 'add_script_and_style' );\n</code></pre>\n\n<p>Extra Info: Wordpress standard way to do</p>\n\n<p>wp_enqueue_style function for .css file</p>\n\n<p>AND\nwp_enqueue_scripts function for .js script file.</p>\n\n<p>Thank you</p>\n" } ]
2015/04/15
[ "https://wordpress.stackexchange.com/questions/184310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4347/" ]
I've done a plugin where you can add shortcode like this: `[myplugin xx]` (where `xx` is a number which calls a specific content `xx`). I have to do a multilingual version of my plugin, so here's my trick: my client writes content `xx` for language #1 and content `yy` for language #2. Then, in an article, he would have to add something like: ``` [multilingualmyplugin #1 xx][multilingualmyplugin #2 yy] ``` and then I should just have to write a plugin that is called and change the content *before* Wordpress calls my first plugin to either `[myplugin xx]` or `[myplugin yy]` depending on the domain name. Then Wordpress would call the plugin. Is it possible and if so, where should I look?
CSS links are relative to the current request URI, not your PHP file. Use an absolute path like: ``` <link rel="stylesheet" href="<?php bloginfo( 'template_url' ) ?>/themesubfolder/style.css" /> ```
184,317
<p>I am attempting to compare a username to a page template name. I found the following code:</p> <pre><code>get_post_meta( $post-&gt;ID, '_wp_page_template', true ); </code></pre> <p>But this isn't quite what I am looking for. This returns the filename of the page template, IE:</p> <pre><code>templates/page-products.php </code></pre> <p>What I am looking for is the actual template name defined in the page template here:</p> <pre><code>/* Template Name: products */ </code></pre> <p>Is this possible?</p>
[ { "answer_id": 184320, "author": "Ben Cole", "author_id": 32532, "author_profile": "https://wordpress.stackexchange.com/users/32532", "pm_score": 1, "selected": false, "text": "<p>One way to retrieve the name of the template as defined in the file could be like this:</p>\n\n<pre><code>function get_template_name () {\n // List all available template names for current theme\n $available_templates = wp_get_theme()-&gt;get_page_templates();\n\n // Get filename of page template we are on\n $template_filename = basename(get_page_template())\n\n // Return the template name for the currently active file\n return $available_templates[$template_filename];\n}\n</code></pre>\n\n<p>The function above will return whatever text is used for the name of the template. In the example below, it would return \"<strong>NAME OF TEMPLATE</strong>\":</p>\n\n<pre><code>/*\nTemplate Name: NAME OF TEMPLATE\n*/\n</code></pre>\n\n<p>More info about the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Theme\" rel=\"nofollow\">WP_Theme</a> object. </p>\n" }, { "answer_id": 184322, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": true, "text": "<p>An alternative to @Ben Cole that's less intensive (especially if you have several page templates), but not as awesome because it doesn't use the <code>WP_Theme</code> object ;)</p>\n\n<pre><code>function wpse_184317_get_template_name( $page_id = null ) {\n if ( ! $template = get_page_template_slug( $page_id ) )\n return;\n if ( ! $file = locate_template( $template ) )\n return;\n\n $data = get_file_data(\n $file,\n array(\n 'Name' =&gt; 'Template Name',\n )\n );\n\n return $data['Name'];\n}\n</code></pre>\n\n<p>And in use:</p>\n\n<pre><code>echo wpse_184317_get_template_name(); // Template name for current page\necho wpse_184317_get_template_name( 14 ); // Template name for page ID 14\n</code></pre>\n" } ]
2015/04/15
[ "https://wordpress.stackexchange.com/questions/184317", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13286/" ]
I am attempting to compare a username to a page template name. I found the following code: ``` get_post_meta( $post->ID, '_wp_page_template', true ); ``` But this isn't quite what I am looking for. This returns the filename of the page template, IE: ``` templates/page-products.php ``` What I am looking for is the actual template name defined in the page template here: ``` /* Template Name: products */ ``` Is this possible?
An alternative to @Ben Cole that's less intensive (especially if you have several page templates), but not as awesome because it doesn't use the `WP_Theme` object ;) ``` function wpse_184317_get_template_name( $page_id = null ) { if ( ! $template = get_page_template_slug( $page_id ) ) return; if ( ! $file = locate_template( $template ) ) return; $data = get_file_data( $file, array( 'Name' => 'Template Name', ) ); return $data['Name']; } ``` And in use: ``` echo wpse_184317_get_template_name(); // Template name for current page echo wpse_184317_get_template_name( 14 ); // Template name for page ID 14 ```
184,330
<p>I cannot login to dashboard after installing multisite - I have infinite redirect loop to login page.</p> <p>Here is what I have added to wp-config </p> <pre><code>/* Multisite */ define( 'WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'nazarserdyuk.com'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); </code></pre> <p>Here is what I have in .htaccess</p> <pre><code># BEGIN WPSuperCache # END WPSuperCache # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Help me please if you can</p>
[ { "answer_id": 184336, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 1, "selected": false, "text": "<p>If I'm not mistaken you have to set the cookie paths and domain, like it is explained here:</p>\n\n<ul>\n<li><a href=\"https://tommcfarlin.com/resolving-the-wordpress-multisite-redirect-loop/\" rel=\"nofollow\">Resolving The WordPress Multisite Redirect Loop</a></li>\n</ul>\n\n<p>by Tom McFarlin. In a nutshell:</p>\n\n<blockquote>\n <p>In your <code>wp-config.php</code> file, add the following lines of code:</p>\n</blockquote>\n\n<pre><code>define('ADMIN_COOKIE_PATH', '/');\ndefine('COOKIE_DOMAIN', '');\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', '');\n</code></pre>\n\n<blockquote>\n <p>And do so just before the line that reads:</p>\n</blockquote>\n\n<pre><code>/* That's all, stop editing! Happy blogging. */\n</code></pre>\n\n<blockquote>\n <p>Once done, the redirect issue should be resolved.</p>\n</blockquote>\n" }, { "answer_id": 362770, "author": "WD40", "author_id": 181431, "author_profile": "https://wordpress.stackexchange.com/users/181431", "pm_score": 0, "selected": false, "text": "<p>I had this same issue, and remembered something that was written on the WordPress.org support site:</p>\n<blockquote>\n<p>If you get an error about cookies being blocked when you try to log in to your network subsite (or log in fails with no error message), open your wp-config.php file and add this line after the other code you added to create the network:</p>\n<p><code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);</code></p>\n</blockquote>\n<p>Adding this to my wp-config.php fixed the issue.</p>\n" } ]
2015/04/15
[ "https://wordpress.stackexchange.com/questions/184330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70683/" ]
I cannot login to dashboard after installing multisite - I have infinite redirect loop to login page. Here is what I have added to wp-config ``` /* Multisite */ define( 'WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'nazarserdyuk.com'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); ``` Here is what I have in .htaccess ``` # BEGIN WPSuperCache # END WPSuperCache # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] </IfModule> # END WordPress ``` Help me please if you can
If I'm not mistaken you have to set the cookie paths and domain, like it is explained here: * [Resolving The WordPress Multisite Redirect Loop](https://tommcfarlin.com/resolving-the-wordpress-multisite-redirect-loop/) by Tom McFarlin. In a nutshell: > > In your `wp-config.php` file, add the following lines of code: > > > ``` define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); ``` > > And do so just before the line that reads: > > > ``` /* That's all, stop editing! Happy blogging. */ ``` > > Once done, the redirect issue should be resolved. > > >
184,384
<p><em>Caveat- I'm not a programmer, I'm a designer that has taught myself basic php/wordpress theming.</em></p> <p>This is a very specific question, I realize, but I'm hoping the experts can help me find some universal principle I've overlooked.</p> <p>I am using the plugin posts 2 posts to generate a relationship between the CPT "speakers" to wordpress users (Relevant <a href="https://github.com/scribu/wp-posts-to-posts/wiki/Posts-2-Users" rel="nofollow">plugin documentation</a>)</p> <p>I then want to show, on the single page for speakers, a link to all the blog posts by the related users. My problem is that get_author_posts_url returns a link to the correct related user, while get_the author gets some other, seemingly random user. All this within the same query!</p> <p>This is my code:</p> <pre><code>$users = get_users( array( 'connected_type' =&gt; 'authors_to_speakers', 'connected_items' =&gt; $post, ) ); if($users){ foreach ( $users as $spost ){ echo '&lt;div class="related-tour-item"&gt;&lt;a href="'; echo get_author_posts_url($spost-&gt;ID); echo '"&gt;All posts by'; echo get_the_author($spost-&gt;ID); echo '&lt;/a&gt;&lt;/div&gt;'; </code></pre> <p>}</p> <p>The output is a correct link to the right author archive page and then another (different) user's name</p> <p>Any clues?</p>
[ { "answer_id": 184335, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>WordPress essentially <em>completely ignores</em> native PHP date functionality, in favor of its own handling. That traditionally allowed it to manage related aspects (such as timezones and translation) with no regards for server configuration.</p>\n\n<p>My educated guess that it would be largely oblivious to such change. At most the cron tasks might fire in bulk and some forms might fail due to nonces (which are valid for many hours, so probability of less than an hour shift affecting them is low).</p>\n" }, { "answer_id": 184350, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 1, "selected": false, "text": "<p>If you haven't already done so, install the <code>ntp</code> package on your web server(s), it automatically syncs the time for you against multiple reference time servers (atomic clocks). Otherwise server clocks do tend to drift over time.</p>\n\n<p>Crucially, ntp also makes any adjustments gradually (in steps), so as to minimise the chance of confusing any automated processes on the server:</p>\n\n<blockquote>\n <p>ntpd's reaction will depend on the offset between the local clock and the reference time. For a tiny offset ntpd will adjust the local clock as usual; for small and larger offsets, ntpd will reject the reference time for a while. In the latter case the operation system's clock will continue with the last corrections effective while the new reference time is being rejected. After some time, small offsets (significantly less than a second) will be slewed (adjusted slowly), while larger offsets will cause the clock to be stepped (set anew). Huge offsets are rejected, and ntpd will terminate itself, believing something very strange must have happened.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://www.ntp.org/ntpfaq/NTP-s-algo.htm\" rel=\"nofollow\">http://www.ntp.org/ntpfaq/NTP-s-algo.htm</a></p>\n\n<p>Use <code>ntpq -p</code> to show the current status.</p>\n\n<p>As per @Rarst's answer, in WordPress, the cron jobs will just fire in bulk.</p>\n\n<p>If you schedule your posts for publication at a specific date/time, double check none are showing as \"missed\", but you wouldn't expect that with your example.</p>\n" } ]
2015/04/16
[ "https://wordpress.stackexchange.com/questions/184384", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59536/" ]
*Caveat- I'm not a programmer, I'm a designer that has taught myself basic php/wordpress theming.* This is a very specific question, I realize, but I'm hoping the experts can help me find some universal principle I've overlooked. I am using the plugin posts 2 posts to generate a relationship between the CPT "speakers" to wordpress users (Relevant [plugin documentation](https://github.com/scribu/wp-posts-to-posts/wiki/Posts-2-Users)) I then want to show, on the single page for speakers, a link to all the blog posts by the related users. My problem is that get\_author\_posts\_url returns a link to the correct related user, while get\_the author gets some other, seemingly random user. All this within the same query! This is my code: ``` $users = get_users( array( 'connected_type' => 'authors_to_speakers', 'connected_items' => $post, ) ); if($users){ foreach ( $users as $spost ){ echo '<div class="related-tour-item"><a href="'; echo get_author_posts_url($spost->ID); echo '">All posts by'; echo get_the_author($spost->ID); echo '</a></div>'; ``` } The output is a correct link to the right author archive page and then another (different) user's name Any clues?
WordPress essentially *completely ignores* native PHP date functionality, in favor of its own handling. That traditionally allowed it to manage related aspects (such as timezones and translation) with no regards for server configuration. My educated guess that it would be largely oblivious to such change. At most the cron tasks might fire in bulk and some forms might fail due to nonces (which are valid for many hours, so probability of less than an hour shift affecting them is low).
184,391
<p>I have been using WPML for the use of multilingual but I am having major issues with it and am tired of it.</p> <p>I have now set up two WordPress set ups on two different domains. What I need to do is create a button / way of having an if statement that will take the user to the exact page / post / product in the different language?</p> <p>For example</p> <p>I am on a post about cars in English the use will use the drop down to German and get the exact post but in German.</p> <p>Now I know I have written any code yet but I am just the in the process and wanted to ask here first to see if anyone could point me in the right direction. Could this be done in PHP or Javascript / jquery etc?</p> <p>Thanks for any help,</p> <p>Max.</p>
[ { "answer_id": 184392, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<p>When a user creates a new page/post/product on one site, use the <a href=\"https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost\" rel=\"nofollow\">XML-RPC API</a> to create a matching one on the other site. Make sure to save the ID of the original post under a meta key for the \"duplicate\" post, and then use the response ID from the API to save the \"duplicate\" ID under a meta key for the original.</p>\n\n<p>You'll now have a post on each site with a reference to the other by ID, which will be enough to generate the \"edit\" link:</p>\n\n<pre><code>http://otherdomain.com/wp-admin/post.php?post=[ID]&amp;action=edit\n</code></pre>\n\n<p>There are a few caveats worth bearing in mind - firstly, if a user deletes a post on one site, you lose the reference. It would be a good idea to hook onto the <code>delete_post</code> action and either:</p>\n\n<ol>\n<li>Prevent the user from doing so (\"this post is a translated version and cannot be deleted\")</li>\n<li>Use the XML-RPC API again to delete the reference from the other site.</li>\n</ol>\n\n<p>Also, post authors. If you're using a shared database with custom user tables (which is what I would recommend), you only have to ensure they have the same capabilities on both sites.</p>\n\n<p>However, if the users are also duplicates (separate installs), you'll need a similar cross-site reference (to know which author ID to use when creating the \"other\" post).</p>\n" }, { "answer_id": 184402, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Clients are clients, but I suggest that you challenge those requirements. In the end of the day, after you have finished your work, the client is left alone to admin the site. Since for SEO reason the slugs of the posts in english and german will be different there is no trivial translation from one to the other, this means that if not for every url then for every public object in wordpress you will need a setting that helps you find the url in the other language. Depending on the amount of content changes the site will have and since updating the info is done by human it is likely to result in errors over time (did the SEO expert that renamed the slug remembered to update the relevant info on the other site?). Using XML-RPC as @TheDeadMedic suggests will solve big part of the problem, but it is not very trivial to implement (and you still need human interface if there is a bug in the sync process).</p>\n\n<p>The realities of the internet is that most people are likely to get to the site in the language they search in, and therefor comfortable to use. For those rare few that get to the wrong one it should be enough to point to the general direction of the site in the other language.</p>\n" } ]
2015/04/16
[ "https://wordpress.stackexchange.com/questions/184391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69859/" ]
I have been using WPML for the use of multilingual but I am having major issues with it and am tired of it. I have now set up two WordPress set ups on two different domains. What I need to do is create a button / way of having an if statement that will take the user to the exact page / post / product in the different language? For example I am on a post about cars in English the use will use the drop down to German and get the exact post but in German. Now I know I have written any code yet but I am just the in the process and wanted to ask here first to see if anyone could point me in the right direction. Could this be done in PHP or Javascript / jquery etc? Thanks for any help, Max.
When a user creates a new page/post/product on one site, use the [XML-RPC API](https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost) to create a matching one on the other site. Make sure to save the ID of the original post under a meta key for the "duplicate" post, and then use the response ID from the API to save the "duplicate" ID under a meta key for the original. You'll now have a post on each site with a reference to the other by ID, which will be enough to generate the "edit" link: ``` http://otherdomain.com/wp-admin/post.php?post=[ID]&action=edit ``` There are a few caveats worth bearing in mind - firstly, if a user deletes a post on one site, you lose the reference. It would be a good idea to hook onto the `delete_post` action and either: 1. Prevent the user from doing so ("this post is a translated version and cannot be deleted") 2. Use the XML-RPC API again to delete the reference from the other site. Also, post authors. If you're using a shared database with custom user tables (which is what I would recommend), you only have to ensure they have the same capabilities on both sites. However, if the users are also duplicates (separate installs), you'll need a similar cross-site reference (to know which author ID to use when creating the "other" post).
184,429
<p>I have searched this forum for the possible solutions but I am not getting anything which works. Maybe I am doing it the wrong way.</p> <p>Here is the code that I have tried so far </p> <pre><code>$parent_categories = '' ; $sub_categories = ''; $subcat = ''; $args = array( 'number' =&gt; $number, 'orderby' =&gt; $orderby, 'order' =&gt; $order, 'hide_empty' =&gt; $hide_empty, 'include' =&gt; $ids, 'hierarchical'=&gt; true, 'parent' =&gt; 0 ); $product_categories = get_terms( 'product_cat', $args ); foreach ($product_categories as $cat) { //var_dump($cat); echo '&lt;br&gt;'; </code></pre> <blockquote> <p>if($cat->slug == 'essays') {</p> </blockquote> <pre><code> $args2 = array( 'number' =&gt; $number, 'orderby' =&gt; $orderby, 'order' =&gt; $order, 'hide_empty' =&gt; $hide_empty, 'include' =&gt; $ids, 'parent' =&gt; $cat-&gt;term_id, 'hierarchical'=&gt; true, ); $sub_categories = get_terms( 'product_cat', $args2 ); foreach ($sub_categories as $subcat) { $sub_categories = $sub_categories.$subcat-&gt;name.','; } $sub_categories = rtrim($sub_categories); } else $sub_categories= 'nomatch'; } </code></pre> <p>When i do <code>echo $sub_categories</code>.</p> <p>I get the output <code>no match</code>;</p> <p><strong>Debug results</strong></p> <p>I tried removing the if else conditions to see what is working and what is not.</p> <pre><code>$parent_categories = '' ; $sub_categories = ''; $subcat = ''; $args = array( 'number' =&gt; $number, 'orderby' =&gt; $orderby, 'order' =&gt; $order, 'hide_empty' =&gt; $hide_empty, 'include' =&gt; $ids, 'hierarchical'=&gt; true, 'parent' =&gt; 0 ); $product_categories = get_terms( 'product_cat', $args ); foreach ($product_categories as $cat) { //var_dump($cat); echo '&lt;br&gt;'; $args2 = array( 'number' =&gt; $number, 'orderby' =&gt; $orderby, 'order' =&gt; $order, 'hide_empty' =&gt; $hide_empty, 'include' =&gt; $ids, 'parent' =&gt; $cat-&gt;term_id, 'hierarchical'=&gt; true, ); $sub_categories = get_terms( 'product_cat', $args2 ); foreach ($sub_categories as $subcat) { $sub_categories = $sub_categories.$subcat-&gt;name.','; } $sub_categories = rtrim($sub_categories); </code></pre> <p>The code does retrieves the parent category and <strong>ALL</strong> the sub categories for <strong>ALL</strong> top level categories. Though I want the sub-categories for a particular parent category. I tried <code>parent=&gt;$cat-&gt;term_id</code> and <code>$cat-&gt;term_taxonomy_id</code>. Still the results were same. I tried hardcoding the parent's term_id but to no use. </p> <p>Okay, so my first task is to get the subcategories for a particular category!</p> <p>And my second question is that why the if condition( marked in orange) doesn't work well ? </p> <p>Please let me know what modification I have to make here !</p>
[ { "answer_id": 184421, "author": "Ricardo Andres", "author_id": 70093, "author_profile": "https://wordpress.stackexchange.com/users/70093", "pm_score": 1, "selected": true, "text": "<p>I do not currently have access to a multi-site, but as far as I remember: Each site in the multi-site install can have their own theme; same with the plugins. However, you can install themes in the main site profile and it will display as optional themes for all the other sites in the multi-site install.</p>\n\n<p>I am not sure I answered your question. Please elaborate and/or include screenshots if I missed.</p>\n" }, { "answer_id": 184471, "author": "user3193817", "author_id": 65641, "author_profile": "https://wordpress.stackexchange.com/users/65641", "pm_score": 1, "selected": false, "text": "<p>I can't vote up the answer above, but its right... two ways of enabling a theme - one in the network site and making it network activated - this then shows in the all of the sites under appearance as normal. The second is not to network activate and then it shows as you have described and you can enable. You still have to activate the theme as normal mind... </p>\n\n<p>Hope that helps. </p>\n\n<p>Thanks</p>\n" } ]
2015/04/16
[ "https://wordpress.stackexchange.com/questions/184429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70729/" ]
I have searched this forum for the possible solutions but I am not getting anything which works. Maybe I am doing it the wrong way. Here is the code that I have tried so far ``` $parent_categories = '' ; $sub_categories = ''; $subcat = ''; $args = array( 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids, 'hierarchical'=> true, 'parent' => 0 ); $product_categories = get_terms( 'product_cat', $args ); foreach ($product_categories as $cat) { //var_dump($cat); echo '<br>'; ``` > > if($cat->slug == 'essays') { > > > ``` $args2 = array( 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids, 'parent' => $cat->term_id, 'hierarchical'=> true, ); $sub_categories = get_terms( 'product_cat', $args2 ); foreach ($sub_categories as $subcat) { $sub_categories = $sub_categories.$subcat->name.','; } $sub_categories = rtrim($sub_categories); } else $sub_categories= 'nomatch'; } ``` When i do `echo $sub_categories`. I get the output `no match`; **Debug results** I tried removing the if else conditions to see what is working and what is not. ``` $parent_categories = '' ; $sub_categories = ''; $subcat = ''; $args = array( 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids, 'hierarchical'=> true, 'parent' => 0 ); $product_categories = get_terms( 'product_cat', $args ); foreach ($product_categories as $cat) { //var_dump($cat); echo '<br>'; $args2 = array( 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids, 'parent' => $cat->term_id, 'hierarchical'=> true, ); $sub_categories = get_terms( 'product_cat', $args2 ); foreach ($sub_categories as $subcat) { $sub_categories = $sub_categories.$subcat->name.','; } $sub_categories = rtrim($sub_categories); ``` The code does retrieves the parent category and **ALL** the sub categories for **ALL** top level categories. Though I want the sub-categories for a particular parent category. I tried `parent=>$cat->term_id` and `$cat->term_taxonomy_id`. Still the results were same. I tried hardcoding the parent's term\_id but to no use. Okay, so my first task is to get the subcategories for a particular category! And my second question is that why the if condition( marked in orange) doesn't work well ? Please let me know what modification I have to make here !
I do not currently have access to a multi-site, but as far as I remember: Each site in the multi-site install can have their own theme; same with the plugins. However, you can install themes in the main site profile and it will display as optional themes for all the other sites in the multi-site install. I am not sure I answered your question. Please elaborate and/or include screenshots if I missed.
184,446
<p>I'm a newbie at PHP and WordPress, so please be gentle!</p> <p>I'm building a plugin - following a few tutorials, getting it all working.</p> <p>My question is why is the function I want to call wrapped up in the <code>array($this, function)</code>? For example I have this constructor code inside my class</p> <pre><code> function __construct() { add_action( 'admin_init',array( $this, 'getStuffDone' ) ); } </code></pre> <p>The getStuffDone function gets fired OK - but why does it have to be in the format it is in?</p> <p>Any insight is much appreciated.</p>
[ { "answer_id": 184452, "author": "Loopo", "author_id": 40423, "author_profile": "https://wordpress.stackexchange.com/users/40423", "pm_score": 3, "selected": false, "text": "<p>the <em>add_action()</em> function definition looks like:</p>\n\n<pre><code> function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {\n return add_filter($tag, $function_to_add, $priority, $accepted_args);\n }\n</code></pre>\n\n<p>so according to that it looks like it expects (string,string,int,int)</p>\n\n<p>In a traditional php file the second parameter would simply be one of your function names.</p>\n\n<p>so you would have <code>add_action('admin_init','my_init_function')</code></p>\n\n<p>It looks like you're using a class to encapsulate your plugin. Other classes could have functions in them with the same name (<em>getStuffDone</em>).</p>\n\n<p>So your function is only known with reference to your class, that's why you have to specify your class <code>$this</code> as well as the function name.</p>\n\n<p>If you're trying to reference a function inside a class you have to use \n<a href=\"http://php.net/manual/en/language.types.callable.php#language.types.callable.passing\" rel=\"nofollow noreferrer\">array callable syntax</a></p>\n\n<p>See also <a href=\"https://codex.wordpress.org/Function_Reference/add_action\" rel=\"nofollow noreferrer\">codex.wordpress.org</a></p>\n" }, { "answer_id": 184456, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": false, "text": "<p>It's a <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"noreferrer\">PHP callback</a>. You need the syntax to keep a reference to the class instance.</p>\n\n<p>Put it this way - if you didn't have <code>$this</code>, how does the caller know that <code>getStuffDone</code> is a method of your class, and not just a regular PHP function? It doesn't.</p>\n\n<p>Using <code>array( $this, 'getStuffDone' )</code> says to PHP:</p>\n\n<blockquote>\n <p>Hey bro, you need to call the method <code>getStuffDone</code> on this instance of my class</p>\n</blockquote>\n" }, { "answer_id": 336497, "author": "farzad", "author_id": 166913, "author_profile": "https://wordpress.stackexchange.com/users/166913", "pm_score": 1, "selected": false, "text": "<p>See the documentation, under the \"<a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">User Contributed Notes</a>\":</p>\n\n<blockquote>\n <p>\"To use <code>add_action()</code> <strong>when your plugin or theme is built using\n classes</strong>, you need to use the array callable syntax. You would pass\n the function to <code>add_action()</code> as an array, with <code>$this</code> as the first\n element, then the name of the class method ...\"</p>\n</blockquote>\n" }, { "answer_id": 412341, "author": "brittle_spirit", "author_id": 223709, "author_profile": "https://wordpress.stackexchange.com/users/223709", "pm_score": 1, "selected": false, "text": "<p>For future readers this example demonstrates the reason for the syntax. Although possibly a bad practice since the class method is called inside the <code>add_test</code> function without initializing the referenced class.</p>\n<pre><code>function add_test( $reference ){\n $object_instance = $reference[0];\n $object_method = $reference[1];\n $to_return = $object_instance-&gt;$object_method();\n return $to_return;\n}\nclass test{\n public function add(){\n $a = $this-&gt;get_first();\n $b = add_test(array($this,'get_second'));\n return $a+$b;\n }\n \n public function get_first(){\n return 1;\n }\n \n public function get_second(){\n return 2;\n }\n}\n$test_instance = new test();\necho $test_instance-&gt;add();\n</code></pre>\n<p>We're simply storing the reference of the object where the method resides so the function <code>add_action</code> can successfully execute the method in question.</p>\n" } ]
2015/04/16
[ "https://wordpress.stackexchange.com/questions/184446", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70739/" ]
I'm a newbie at PHP and WordPress, so please be gentle! I'm building a plugin - following a few tutorials, getting it all working. My question is why is the function I want to call wrapped up in the `array($this, function)`? For example I have this constructor code inside my class ``` function __construct() { add_action( 'admin_init',array( $this, 'getStuffDone' ) ); } ``` The getStuffDone function gets fired OK - but why does it have to be in the format it is in? Any insight is much appreciated.
the *add\_action()* function definition looks like: ``` function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) { return add_filter($tag, $function_to_add, $priority, $accepted_args); } ``` so according to that it looks like it expects (string,string,int,int) In a traditional php file the second parameter would simply be one of your function names. so you would have `add_action('admin_init','my_init_function')` It looks like you're using a class to encapsulate your plugin. Other classes could have functions in them with the same name (*getStuffDone*). So your function is only known with reference to your class, that's why you have to specify your class `$this` as well as the function name. If you're trying to reference a function inside a class you have to use [array callable syntax](http://php.net/manual/en/language.types.callable.php#language.types.callable.passing) See also [codex.wordpress.org](https://codex.wordpress.org/Function_Reference/add_action)
184,449
<p>I am aiming to pagination <a href="https://codex.wordpress.org/Class_Reference/WP_Comment_Query">WP_Comment_Query()</a>. It appears this is either taboo or there is no viable information about it <a href="https://www.google.co.uk/search?q=%22WP_Comment_Query%22%20pagination">online</a>, not anything.</p> <p>Why? Is it possible? If so, <strong>how</strong>?</p>
[ { "answer_id": 184451, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 4, "selected": true, "text": "<p>Yes, it is possible, but it is a bit of a pain.</p>\n\n<p>Looking at the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Comment_Query\" rel=\"noreferrer\">codex page</a>, only arguments of note are <code>number</code> and <code>offset</code>.</p>\n\n<p>We need these two to create our paginated pages. </p>\n\n<p>First, we set the <code>$paged</code> parameter, which is the current page:</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n</code></pre>\n\n<p>Then number of comments to display:</p>\n\n<pre><code>$number = 3;\n</code></pre>\n\n<p>After that, calculate the offset (where the query begins pulling comments):</p>\n\n<pre><code>$offset = ( $paged - 1 ) * $number;\n</code></pre>\n\n<p>Let's place them all in the arguments variable:</p>\n\n<pre><code>// arguments to filter comments\n$args = array(\n 'number' =&gt; $number,\n 'offset' =&gt; $offset,\n 'paged' =&gt; $paged\n);\n</code></pre>\n\n<p>Now let's hit the query and loop through it:</p>\n\n<pre><code>// the query\n$the_query = new WP_Comment_Query;\n$comments = $the_query-&gt;query( $args );\n\n// Comment Loop\nif ( $comments ) {\n\n foreach ( $comments as $comment ) {\n echo '&lt;p&gt;' . $comment-&gt;comment_content . '&lt;/p&gt;&lt;br&gt;&lt;br&gt;';\n }\n\n} else {\n\n echo 'No comments found.';\n\n}\n</code></pre>\n\n<p>Excellent. Now we can test to add <code>/page/2</code> to the URL bar to check if it works, which it does.</p>\n\n<p>The only thing missing is adding pagination links, for example, the <code>next_posts_link()</code> function. </p>\n\n<p>The problem is that I have not found a way to get <code>max_num_pages</code>. The following would normally work in a simple WP_Query: </p>\n\n<pre><code>$the_query-&gt;max_num_pages\n</code></pre>\n\n<p>But it does not work here. Without knowing the maximum amount of pages, we cannot create our pagination links properly. Note that <code>count($comments)</code> will give us only the total amount of comments per page (<code>$number</code>). </p>\n\n<p>Personally, I fixed this by calculating the maximum pages by the custom query I was targetting. I wanted to get the total amount of comments by User ID. So I used that number like this:</p>\n\n<pre><code>$maximum_pages = $user_total_comments / $number;\n</code></pre>\n\n<p>This works in my case, but we definitely need a way to get <code>max_num_pages</code>. Hopefully, with this answer, it <strong>will inspire someone to solve the final bit</strong>. At least we have a lot more information about pagination with <code>wp_comment_query()</code> here than anywhere else.</p>\n\n<h2>Update</h2>\n\n<p>So the remaining problem was the lack of <code>max_num_pages</code>. One way to solve this is to <code>count()</code> the returned array of post and check if it matches with the <code>$number</code> (what you set in the <code>number</code> array key), see below:</p>\n\n<pre><code>$tot_returned_comments = count($comments);\n\nif ($number == $tot_returned_comments) {\n echo '&lt;a href=\"/comments/page/' . $nextpage . '\"&gt;Next&lt;/a&gt;';\n}\n</code></pre>\n\n<p>This works in all cases besides if the final page has the exact same amount of posts as you set in your <code>$number</code> variable. So, if you set <code>$number</code> to 15, and your final paginated page has 15 results, then it will display the next button. </p>\n\n<p>Now, if you do not care about performance, you could easily just run two queries. One where you do not limit the results and simply <code>count()</code> the results and use that count for the <code>max_num_pages</code> value. </p>\n\n<p>While this doesn't solve the lack of getting <code>max_num_pages</code>, it should be enough to get you on your feet with a fully working pagination for <code>wp_comments_query()</code>.</p>\n" }, { "answer_id": 200400, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 2, "selected": false, "text": "<p>The alternative way to handle this problem is to use paginate_links() with get_comments() (or any similar query). Specifically to get the equivalent of max_num_pages, you can use the built-in function wp_count_comments().</p>\n\n<p>So, to get your maximum number of pages, you'd first produce a count of all the comments you want. Presuming you don't want unapproved comments:</p>\n\n<pre><code>$all_comments = wp_count_comments();\n$all_comments_approved = $all_comments-&gt;approved;\n</code></pre>\n\n<p>It's a simple matter to divide $all_comments_approved by the number of comments per page. So, with a desired \"n\" comments per page:</p>\n\n<pre><code>//Adding one at the end as simple way of rounding up. \n\n$max_num_pages = intval( $all_comments_approved / $comments_per_page ) + 1; \n</code></pre>\n\n<p>(The value of $comments_per_page should be pre-set as > 0, and is also used in the main comment query - see below). </p>\n\n<p>The full pagination function will look something like the following, depending on other particulars. (For example: Sometimes the 'base' option will be made trickier by the presence of query variables in the URL. I had to use a preg_replace to get around that problem in one application.)</p>\n\n<pre><code>$current_page = max(1, get_query_var('paged'));\n\necho paginate_links(array(\n //check codex for how to work with get_pagenum_link and variations\n 'base' =&gt; get_pagenum_link(1) . '%_%',\n 'current' =&gt; $current_page,\n 'total' =&gt; $max_num_pages,\n 'prev_text' =&gt; __('&amp;laquo; Previous'),\n 'next_text' =&gt; __('Next &amp;raquo;'),\n 'end_size' =&gt; 2,\n 'mid-size' =&gt; 3\n));\n</code></pre>\n\n<p>...and the rest is formatting the output... and the main comment query. The latter will look like the following: Note that $comments_per_page is critical here both for the number of comments retrieved and for calculating the offset. Note also that the total size of the object retrieved is limited by the number (as well as by 'status').</p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$offset = ($paged - 1) * $comments_per_page;\n\n\n$comments = get_comments(array(\n'status' =&gt; 'approve',\n'number' =&gt; $comments_per_page,\n'offset' =&gt; $offset\n));\n</code></pre>\n" } ]
2015/04/16
[ "https://wordpress.stackexchange.com/questions/184449", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24875/" ]
I am aiming to pagination [WP\_Comment\_Query()](https://codex.wordpress.org/Class_Reference/WP_Comment_Query). It appears this is either taboo or there is no viable information about it [online](https://www.google.co.uk/search?q=%22WP_Comment_Query%22%20pagination), not anything. Why? Is it possible? If so, **how**?
Yes, it is possible, but it is a bit of a pain. Looking at the [codex page](https://codex.wordpress.org/Class_Reference/WP_Comment_Query), only arguments of note are `number` and `offset`. We need these two to create our paginated pages. First, we set the `$paged` parameter, which is the current page: ``` $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ``` Then number of comments to display: ``` $number = 3; ``` After that, calculate the offset (where the query begins pulling comments): ``` $offset = ( $paged - 1 ) * $number; ``` Let's place them all in the arguments variable: ``` // arguments to filter comments $args = array( 'number' => $number, 'offset' => $offset, 'paged' => $paged ); ``` Now let's hit the query and loop through it: ``` // the query $the_query = new WP_Comment_Query; $comments = $the_query->query( $args ); // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { echo '<p>' . $comment->comment_content . '</p><br><br>'; } } else { echo 'No comments found.'; } ``` Excellent. Now we can test to add `/page/2` to the URL bar to check if it works, which it does. The only thing missing is adding pagination links, for example, the `next_posts_link()` function. The problem is that I have not found a way to get `max_num_pages`. The following would normally work in a simple WP\_Query: ``` $the_query->max_num_pages ``` But it does not work here. Without knowing the maximum amount of pages, we cannot create our pagination links properly. Note that `count($comments)` will give us only the total amount of comments per page (`$number`). Personally, I fixed this by calculating the maximum pages by the custom query I was targetting. I wanted to get the total amount of comments by User ID. So I used that number like this: ``` $maximum_pages = $user_total_comments / $number; ``` This works in my case, but we definitely need a way to get `max_num_pages`. Hopefully, with this answer, it **will inspire someone to solve the final bit**. At least we have a lot more information about pagination with `wp_comment_query()` here than anywhere else. Update ------ So the remaining problem was the lack of `max_num_pages`. One way to solve this is to `count()` the returned array of post and check if it matches with the `$number` (what you set in the `number` array key), see below: ``` $tot_returned_comments = count($comments); if ($number == $tot_returned_comments) { echo '<a href="/comments/page/' . $nextpage . '">Next</a>'; } ``` This works in all cases besides if the final page has the exact same amount of posts as you set in your `$number` variable. So, if you set `$number` to 15, and your final paginated page has 15 results, then it will display the next button. Now, if you do not care about performance, you could easily just run two queries. One where you do not limit the results and simply `count()` the results and use that count for the `max_num_pages` value. While this doesn't solve the lack of getting `max_num_pages`, it should be enough to get you on your feet with a fully working pagination for `wp_comments_query()`.
184,458
<p>A client of mine wants to be able to choose between a dark and a light theme each time he publishes a post. What's the best way to change the color of a theme per post?</p> <p>I thought in creating a taxonomy called "template" and within that two options: "dark" and "light". However, I dont know yet how to change the whole theme depending on the taxonomy if I load the single post. And I cant think of a smarter way to do it in Archive pages.</p> <p>Is there a good approach to achieve this?</p>
[ { "answer_id": 184451, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 4, "selected": true, "text": "<p>Yes, it is possible, but it is a bit of a pain.</p>\n\n<p>Looking at the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Comment_Query\" rel=\"noreferrer\">codex page</a>, only arguments of note are <code>number</code> and <code>offset</code>.</p>\n\n<p>We need these two to create our paginated pages. </p>\n\n<p>First, we set the <code>$paged</code> parameter, which is the current page:</p>\n\n<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n</code></pre>\n\n<p>Then number of comments to display:</p>\n\n<pre><code>$number = 3;\n</code></pre>\n\n<p>After that, calculate the offset (where the query begins pulling comments):</p>\n\n<pre><code>$offset = ( $paged - 1 ) * $number;\n</code></pre>\n\n<p>Let's place them all in the arguments variable:</p>\n\n<pre><code>// arguments to filter comments\n$args = array(\n 'number' =&gt; $number,\n 'offset' =&gt; $offset,\n 'paged' =&gt; $paged\n);\n</code></pre>\n\n<p>Now let's hit the query and loop through it:</p>\n\n<pre><code>// the query\n$the_query = new WP_Comment_Query;\n$comments = $the_query-&gt;query( $args );\n\n// Comment Loop\nif ( $comments ) {\n\n foreach ( $comments as $comment ) {\n echo '&lt;p&gt;' . $comment-&gt;comment_content . '&lt;/p&gt;&lt;br&gt;&lt;br&gt;';\n }\n\n} else {\n\n echo 'No comments found.';\n\n}\n</code></pre>\n\n<p>Excellent. Now we can test to add <code>/page/2</code> to the URL bar to check if it works, which it does.</p>\n\n<p>The only thing missing is adding pagination links, for example, the <code>next_posts_link()</code> function. </p>\n\n<p>The problem is that I have not found a way to get <code>max_num_pages</code>. The following would normally work in a simple WP_Query: </p>\n\n<pre><code>$the_query-&gt;max_num_pages\n</code></pre>\n\n<p>But it does not work here. Without knowing the maximum amount of pages, we cannot create our pagination links properly. Note that <code>count($comments)</code> will give us only the total amount of comments per page (<code>$number</code>). </p>\n\n<p>Personally, I fixed this by calculating the maximum pages by the custom query I was targetting. I wanted to get the total amount of comments by User ID. So I used that number like this:</p>\n\n<pre><code>$maximum_pages = $user_total_comments / $number;\n</code></pre>\n\n<p>This works in my case, but we definitely need a way to get <code>max_num_pages</code>. Hopefully, with this answer, it <strong>will inspire someone to solve the final bit</strong>. At least we have a lot more information about pagination with <code>wp_comment_query()</code> here than anywhere else.</p>\n\n<h2>Update</h2>\n\n<p>So the remaining problem was the lack of <code>max_num_pages</code>. One way to solve this is to <code>count()</code> the returned array of post and check if it matches with the <code>$number</code> (what you set in the <code>number</code> array key), see below:</p>\n\n<pre><code>$tot_returned_comments = count($comments);\n\nif ($number == $tot_returned_comments) {\n echo '&lt;a href=\"/comments/page/' . $nextpage . '\"&gt;Next&lt;/a&gt;';\n}\n</code></pre>\n\n<p>This works in all cases besides if the final page has the exact same amount of posts as you set in your <code>$number</code> variable. So, if you set <code>$number</code> to 15, and your final paginated page has 15 results, then it will display the next button. </p>\n\n<p>Now, if you do not care about performance, you could easily just run two queries. One where you do not limit the results and simply <code>count()</code> the results and use that count for the <code>max_num_pages</code> value. </p>\n\n<p>While this doesn't solve the lack of getting <code>max_num_pages</code>, it should be enough to get you on your feet with a fully working pagination for <code>wp_comments_query()</code>.</p>\n" }, { "answer_id": 200400, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 2, "selected": false, "text": "<p>The alternative way to handle this problem is to use paginate_links() with get_comments() (or any similar query). Specifically to get the equivalent of max_num_pages, you can use the built-in function wp_count_comments().</p>\n\n<p>So, to get your maximum number of pages, you'd first produce a count of all the comments you want. Presuming you don't want unapproved comments:</p>\n\n<pre><code>$all_comments = wp_count_comments();\n$all_comments_approved = $all_comments-&gt;approved;\n</code></pre>\n\n<p>It's a simple matter to divide $all_comments_approved by the number of comments per page. So, with a desired \"n\" comments per page:</p>\n\n<pre><code>//Adding one at the end as simple way of rounding up. \n\n$max_num_pages = intval( $all_comments_approved / $comments_per_page ) + 1; \n</code></pre>\n\n<p>(The value of $comments_per_page should be pre-set as > 0, and is also used in the main comment query - see below). </p>\n\n<p>The full pagination function will look something like the following, depending on other particulars. (For example: Sometimes the 'base' option will be made trickier by the presence of query variables in the URL. I had to use a preg_replace to get around that problem in one application.)</p>\n\n<pre><code>$current_page = max(1, get_query_var('paged'));\n\necho paginate_links(array(\n //check codex for how to work with get_pagenum_link and variations\n 'base' =&gt; get_pagenum_link(1) . '%_%',\n 'current' =&gt; $current_page,\n 'total' =&gt; $max_num_pages,\n 'prev_text' =&gt; __('&amp;laquo; Previous'),\n 'next_text' =&gt; __('Next &amp;raquo;'),\n 'end_size' =&gt; 2,\n 'mid-size' =&gt; 3\n));\n</code></pre>\n\n<p>...and the rest is formatting the output... and the main comment query. The latter will look like the following: Note that $comments_per_page is critical here both for the number of comments retrieved and for calculating the offset. Note also that the total size of the object retrieved is limited by the number (as well as by 'status').</p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$offset = ($paged - 1) * $comments_per_page;\n\n\n$comments = get_comments(array(\n'status' =&gt; 'approve',\n'number' =&gt; $comments_per_page,\n'offset' =&gt; $offset\n));\n</code></pre>\n" } ]
2015/04/16
[ "https://wordpress.stackexchange.com/questions/184458", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47846/" ]
A client of mine wants to be able to choose between a dark and a light theme each time he publishes a post. What's the best way to change the color of a theme per post? I thought in creating a taxonomy called "template" and within that two options: "dark" and "light". However, I dont know yet how to change the whole theme depending on the taxonomy if I load the single post. And I cant think of a smarter way to do it in Archive pages. Is there a good approach to achieve this?
Yes, it is possible, but it is a bit of a pain. Looking at the [codex page](https://codex.wordpress.org/Class_Reference/WP_Comment_Query), only arguments of note are `number` and `offset`. We need these two to create our paginated pages. First, we set the `$paged` parameter, which is the current page: ``` $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ``` Then number of comments to display: ``` $number = 3; ``` After that, calculate the offset (where the query begins pulling comments): ``` $offset = ( $paged - 1 ) * $number; ``` Let's place them all in the arguments variable: ``` // arguments to filter comments $args = array( 'number' => $number, 'offset' => $offset, 'paged' => $paged ); ``` Now let's hit the query and loop through it: ``` // the query $the_query = new WP_Comment_Query; $comments = $the_query->query( $args ); // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { echo '<p>' . $comment->comment_content . '</p><br><br>'; } } else { echo 'No comments found.'; } ``` Excellent. Now we can test to add `/page/2` to the URL bar to check if it works, which it does. The only thing missing is adding pagination links, for example, the `next_posts_link()` function. The problem is that I have not found a way to get `max_num_pages`. The following would normally work in a simple WP\_Query: ``` $the_query->max_num_pages ``` But it does not work here. Without knowing the maximum amount of pages, we cannot create our pagination links properly. Note that `count($comments)` will give us only the total amount of comments per page (`$number`). Personally, I fixed this by calculating the maximum pages by the custom query I was targetting. I wanted to get the total amount of comments by User ID. So I used that number like this: ``` $maximum_pages = $user_total_comments / $number; ``` This works in my case, but we definitely need a way to get `max_num_pages`. Hopefully, with this answer, it **will inspire someone to solve the final bit**. At least we have a lot more information about pagination with `wp_comment_query()` here than anywhere else. Update ------ So the remaining problem was the lack of `max_num_pages`. One way to solve this is to `count()` the returned array of post and check if it matches with the `$number` (what you set in the `number` array key), see below: ``` $tot_returned_comments = count($comments); if ($number == $tot_returned_comments) { echo '<a href="/comments/page/' . $nextpage . '">Next</a>'; } ``` This works in all cases besides if the final page has the exact same amount of posts as you set in your `$number` variable. So, if you set `$number` to 15, and your final paginated page has 15 results, then it will display the next button. Now, if you do not care about performance, you could easily just run two queries. One where you do not limit the results and simply `count()` the results and use that count for the `max_num_pages` value. While this doesn't solve the lack of getting `max_num_pages`, it should be enough to get you on your feet with a fully working pagination for `wp_comments_query()`.
184,498
<p>I currently have this:</p> <pre><code> &lt;?php $terms = wp_get_post_terms( $post-&gt;ID, 'artist-genre'); foreach($terms as $term) : ?&gt; &lt;li&gt; &lt;?php echo $term-&gt;name; ?&gt; &lt;/li&gt; &lt;?php endforeach;?&gt; </code></pre> <p>Just to list out the name on a custom post type page called <code>artwork</code>.</p> <p>It's working, but I feel that doing a <code>foreach</code> loop for one thing is a little overkill.</p> <p>Is there any other way to do this differently without the use of a <code>foreach</code> or is that the best way?</p>
[ { "answer_id": 184502, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>What about <a href=\"https://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"nofollow\">using</a>:</p>\n\n<pre><code>echo get_the_term_list( $post-&gt;ID, 'artist-genre', '&lt;li&gt;', ',&lt;/li&gt;&lt;li&gt;', '&lt;/li&gt;' );\n</code></pre>\n\n<p>instead, to generate the HTML list?</p>\n\n<p>Or <a href=\"https://codex.wordpress.org/Function_Reference/the_terms\" rel=\"nofollow\">simply</a>:</p>\n\n<pre><code>the_terms( $post-&gt;ID, 'artist-genre', '&lt;li&gt;', ',&lt;/li&gt;&lt;li&gt;', '&lt;/li&gt;' );\n</code></pre>\n\n<p>that's a wrapper for <code>get_the_term_list()</code>.</p>\n\n<p>Also notice that you're missing the <code>is_wp_error()</code> check, in your code snippet, because <code>wp_get_post_terms()</code> can return the <code>WP_Error</code> object, for an unknown taxonomy. But the <code>the_terms</code> function takes care of that and returns <code>false</code> in that case.</p>\n" }, { "answer_id": 184506, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>If you are just after the term name in your code, you can add </p>\n\n<pre><code>array( 'fields' =&gt; 'names' )\n</code></pre>\n\n<p>Or for PHP 5.4+</p>\n\n<pre><code>['fields' =&gt; 'names']\n</code></pre>\n\n<p>as the third parameter to <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow\"><code>wp_get_post_terms</code></a>. This will just retrieve the names of the terms attached to the post. You can then get and display the first post term name with</p>\n\n<pre><code>echo $terms[0]];\n</code></pre>\n\n<p>As @birgire already mentioned, you will need to check if <code>$terms</code> does not return a error and that there are actually values returned. Failing to do this will lead to a bug when <code>$terms</code> return an error of return an empty list</p>\n" } ]
2015/04/17
[ "https://wordpress.stackexchange.com/questions/184498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16613/" ]
I currently have this: ``` <?php $terms = wp_get_post_terms( $post->ID, 'artist-genre'); foreach($terms as $term) : ?> <li> <?php echo $term->name; ?> </li> <?php endforeach;?> ``` Just to list out the name on a custom post type page called `artwork`. It's working, but I feel that doing a `foreach` loop for one thing is a little overkill. Is there any other way to do this differently without the use of a `foreach` or is that the best way?
What about [using](https://codex.wordpress.org/Function_Reference/get_the_term_list): ``` echo get_the_term_list( $post->ID, 'artist-genre', '<li>', ',</li><li>', '</li>' ); ``` instead, to generate the HTML list? Or [simply](https://codex.wordpress.org/Function_Reference/the_terms): ``` the_terms( $post->ID, 'artist-genre', '<li>', ',</li><li>', '</li>' ); ``` that's a wrapper for `get_the_term_list()`. Also notice that you're missing the `is_wp_error()` check, in your code snippet, because `wp_get_post_terms()` can return the `WP_Error` object, for an unknown taxonomy. But the `the_terms` function takes care of that and returns `false` in that case.
184,513
<p>I need to set different screen options(title,author,categories...) in post summary page for non admin users(editor,author..) which can not be altered by user him/her self.</p> <p>Example : <img src="https://i.stack.imgur.com/MzmD7.jpg" alt="enter image description here"></p> <p>This is the administrator view and I need to hide <code>View Count</code> &amp; <code>SEO</code> columns for non admin users.</p> <p>Does anybody have an idea, how to achieve this ?</p>
[ { "answer_id": 184527, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">capabilities API</a> to conditionally set screen options:</p>\n\n<pre><code>if ( current_user_can( 'manage_options' ) ) {\n // Administrator, add some options\n} else {\n // Other roles, do something different\n}\n</code></pre>\n" }, { "answer_id": 184538, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>I assume, you need something like editors can't see the category column or something like this.</p>\n\n<p>This snippet might help you:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 );\nfunction change_columns_for_user( $columns, $post_type ){\n if( 'post' != $post_type )\n return $columns;\n\n if( current_user_can( 'manage_options' ) )\n return $columns;\n else{\n //Remove Categories\n unset( $columns['categories'] );\n //Remove Tags\n unset( $columns['tags'] );\n //Remove Comments\n unset( $columns['comments'] );\n return $columns;\n }\n\n}\n</code></pre>\n\n<p>In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more.</p>\n\n<blockquote>\n <p>But It should not be able to change from the particular user login.</p>\n</blockquote>\n\n<p>If you still want to disable the options panel for some users, have a look into this snippet:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 );\nfunction remove_screen_settings( $show_screen, $class ){\n if( 'edit-post' != $class-&gt;id )\n return $show_screen;\n\n if( ! current_user_can( 'manage_options' ) )\n return false;\n else\n return true;\n}\n</code></pre>\n" }, { "answer_id": 184614, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": false, "text": "<p>I have accepted the @websupporter answer according to my question. </p>\n\n<p>However I would like add few codes to specific question I have faced earlier.</p>\n\n<p>I need to remove <code>Yoast SEO</code> plugin extra columns from the non admin users. In that specific case <code>Yoast SEO</code> provide the hook to disable the columns. So I used that as below.</p>\n\n<pre><code>/** Remove SEO columns when User is not admin**/\nfunction remove_page_analysis_for_non_admin(){\n if( current_user_can( 'manage_options' ) )\n return true;\n else{\n return false;\n }\n}\nadd_filter( 'wpseo_use_page_analysis', 'remove_page_analysis_for_non_admin', 10, 2 );\n</code></pre>\n\n<p>If anybody would interesting to remove it for all users, use following code</p>\n\n<pre><code>add_filter( 'wpseo_use_page_analysis', '__return_false' );\n</code></pre>\n" } ]
2015/04/17
[ "https://wordpress.stackexchange.com/questions/184513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
I need to set different screen options(title,author,categories...) in post summary page for non admin users(editor,author..) which can not be altered by user him/her self. Example : ![enter image description here](https://i.stack.imgur.com/MzmD7.jpg) This is the administrator view and I need to hide `View Count` & `SEO` columns for non admin users. Does anybody have an idea, how to achieve this ?
I assume, you need something like editors can't see the category column or something like this. This snippet might help you: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 ); function change_columns_for_user( $columns, $post_type ){ if( 'post' != $post_type ) return $columns; if( current_user_can( 'manage_options' ) ) return $columns; else{ //Remove Categories unset( $columns['categories'] ); //Remove Tags unset( $columns['tags'] ); //Remove Comments unset( $columns['comments'] ); return $columns; } } ``` In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more. > > But It should not be able to change from the particular user login. > > > If you still want to disable the options panel for some users, have a look into this snippet: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 ); function remove_screen_settings( $show_screen, $class ){ if( 'edit-post' != $class->id ) return $show_screen; if( ! current_user_can( 'manage_options' ) ) return false; else return true; } ```
184,519
<p>I am using the following code for submit custom post by users in a custom page. When i submit form i get this error:</p> <blockquote> <p>Fatal error: Call to a member function get_error_messages() on null in D:\Ampps\www\wordpress2\wp-content\themes\tours\includes\add_tour.func.php on line 85</p> </blockquote> <p>Line 85: </p> <blockquote> <p>...} elseif (count($reg_errors->get_error_messages()) &lt; 1) {...</p> </blockquote> <pre><code> &lt;?php $postTitleError = ''; if(isset($_POST['submitted']) &amp;&amp; isset($_POST['post_nonce_field']) &amp;&amp; wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) { validate_tour_data( $_POST['tourTitle'],$_POST['keywords'],$_POST['sourceTour'],$_POST['destinationTour'],$_POST['duration'],$_POST['tourContent'],$_POST['agancyservice'],$_POST['passports'],$_POST['transport'],$_POST['hotel_name'],$_POST['hotelRate'],$_POST['room1'],$_POST['room2'],$_POST['room3'],$_POST['room4'],$_POST['desc'] ); global $tourTitle,$keywords,$sourceTour,$destinationTour,$duration,$tourContent,$agancyservice,$passports,$transport,$hotel_name,$hotelRate,$room1,$room2,$room3,$room4,$desc; $tourTitle = sanitize_text_field($_POST['tourTitle']); $keywords = sanitize_text_field($_POST['keywords']); $sourceTour = sanitize_text_field($_POST['sourceTour']); $destinationTour = sanitize_text_field($_POST['destinationTour']); $duration = sanitize_text_field($_POST['duration']); $tourContent = sanitize_text_field($_POST['tourContent']); $agancyservice = sanitize_text_field($_POST['agancyservice']); $passports = sanitize_text_field($_POST['passports']); $transport = sanitize_text_field($_POST['transport']); $hotel_name = sanitize_text_field($_POST['hotel_name']); $hotelRate = sanitize_text_field($_POST['hotelRate']); $room1 = sanitize_text_field($_POST['room1']); $room2 = sanitize_text_field($_POST['room2']); $room3 = sanitize_text_field($_POST['room3']); $room4 = sanitize_text_field($_POST['room4']); $desc = sanitize_text_field($_POST['desc']); add_complete_tour(); } function validate_tour_data($tourTitle,$keywords,$sourceTour,$destinationTour,$duration,$tourContent,$agancyservice,$passports,$transport,$hotel_name,$hotelRate,$room1,$room2,$room3,$room4,$desc){ global $reg_errors; $reg_errors = new WP_Error; if (empty($tourTitle)) { $reg_errors-&gt;add('tourTitle', 'عنوان تور را وارد کنید.'); } if (empty($keywords)) { $reg_errors-&gt;add('keywords', 'حداقل یک کلمه کلیدی و حداکثر سه کلمه کلیدی وارد کنید.'); } if (empty($sourceTour)) { $reg_errors-&gt;add('sourceTour', 'مبدا و آغاز تور را وارد کنید.'); } if (empty($destinationTour)) { $reg_errors-&gt;add('destinationTour', 'مقصد تور را وارد کنید.'); } if (empty($duration)) { $reg_errors-&gt;add('duration', 'مدت اقامت را وارد کنید.'); } if (!is_numeric($duration)) { $reg_errors-&gt;add('duration', 'مدت اقامت فقط میتواند مقداری عددی باشد.'); } if (empty($tourContent)) { $reg_errors-&gt;add('tourContent', 'توضیح مختصری در مورد تور وارد کنید.'); } if (empty($agancyservice)) { $reg_errors-&gt;add('agancyservice', 'خدمات آژانس مسافرتی را وارد کنید.'); } if (empty($passports)) { $reg_errors-&gt;add('passports', 'مدارک مورد نیاز تور مسافرنی را وارد کنید.'); } if (empty($transport)) { $reg_errors-&gt;add('transport', 'نوع سفر را انتخاب کنید.'); } } function add_complete_tour(){ global $tourTitle,$keywords,$sourceTour,$destinationTour,$duration,$tourContent,$agancyservice,$passports,$transport,$hotel_name,$hotelRate,$room1,$room2,$room3,$room4,$desc; if (is_wp_error($reg_errors) &amp;&amp; count($reg_errors-&gt;get_error_messages()) &gt; 0) { echo '&lt;div class="alert alert-danger" role="alert" style="margin-top: 10px;font-size:15px;"&gt;'; foreach ($reg_errors-&gt;get_error_messages() as $error) { echo '&lt;strong&gt;خطا&lt;/strong&gt;:'; echo $error . '&lt;br/&gt;'; } echo '&lt;/div&gt;'; } elseif (count($reg_errors-&gt;get_error_messages()) &lt; 1) { $post_data = array( 'post_title' =&gt; $tourTitle, 'post_content' =&gt; $tourContent, 'post_status' =&gt; 'pending', 'post_author' =&gt; get_current_user_id(), ); // Insert the post into the database $post_id = wp_insert_post( $post_data ); echo '&lt;div class="alert alert-success" role="alert" style="margin-top: 10px;font-size:15px;"&gt;تور مسافرتی با موفقیت ثبت شد. پس از بررسی مدیریت و تایید منتشر خواهد شد.&lt;/div&gt;'; } } ?&gt; </code></pre>
[ { "answer_id": 184527, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">capabilities API</a> to conditionally set screen options:</p>\n\n<pre><code>if ( current_user_can( 'manage_options' ) ) {\n // Administrator, add some options\n} else {\n // Other roles, do something different\n}\n</code></pre>\n" }, { "answer_id": 184538, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>I assume, you need something like editors can't see the category column or something like this.</p>\n\n<p>This snippet might help you:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 );\nfunction change_columns_for_user( $columns, $post_type ){\n if( 'post' != $post_type )\n return $columns;\n\n if( current_user_can( 'manage_options' ) )\n return $columns;\n else{\n //Remove Categories\n unset( $columns['categories'] );\n //Remove Tags\n unset( $columns['tags'] );\n //Remove Comments\n unset( $columns['comments'] );\n return $columns;\n }\n\n}\n</code></pre>\n\n<p>In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more.</p>\n\n<blockquote>\n <p>But It should not be able to change from the particular user login.</p>\n</blockquote>\n\n<p>If you still want to disable the options panel for some users, have a look into this snippet:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 );\nfunction remove_screen_settings( $show_screen, $class ){\n if( 'edit-post' != $class-&gt;id )\n return $show_screen;\n\n if( ! current_user_can( 'manage_options' ) )\n return false;\n else\n return true;\n}\n</code></pre>\n" }, { "answer_id": 184614, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": false, "text": "<p>I have accepted the @websupporter answer according to my question. </p>\n\n<p>However I would like add few codes to specific question I have faced earlier.</p>\n\n<p>I need to remove <code>Yoast SEO</code> plugin extra columns from the non admin users. In that specific case <code>Yoast SEO</code> provide the hook to disable the columns. So I used that as below.</p>\n\n<pre><code>/** Remove SEO columns when User is not admin**/\nfunction remove_page_analysis_for_non_admin(){\n if( current_user_can( 'manage_options' ) )\n return true;\n else{\n return false;\n }\n}\nadd_filter( 'wpseo_use_page_analysis', 'remove_page_analysis_for_non_admin', 10, 2 );\n</code></pre>\n\n<p>If anybody would interesting to remove it for all users, use following code</p>\n\n<pre><code>add_filter( 'wpseo_use_page_analysis', '__return_false' );\n</code></pre>\n" } ]
2015/04/17
[ "https://wordpress.stackexchange.com/questions/184519", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63723/" ]
I am using the following code for submit custom post by users in a custom page. When i submit form i get this error: > > Fatal error: Call to a member function get\_error\_messages() on null in D:\Ampps\www\wordpress2\wp-content\themes\tours\includes\add\_tour.func.php on line 85 > > > Line 85: > > ...} elseif (count($reg\_errors->get\_error\_messages()) < 1) {... > > > ``` <?php $postTitleError = ''; if(isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) { validate_tour_data( $_POST['tourTitle'],$_POST['keywords'],$_POST['sourceTour'],$_POST['destinationTour'],$_POST['duration'],$_POST['tourContent'],$_POST['agancyservice'],$_POST['passports'],$_POST['transport'],$_POST['hotel_name'],$_POST['hotelRate'],$_POST['room1'],$_POST['room2'],$_POST['room3'],$_POST['room4'],$_POST['desc'] ); global $tourTitle,$keywords,$sourceTour,$destinationTour,$duration,$tourContent,$agancyservice,$passports,$transport,$hotel_name,$hotelRate,$room1,$room2,$room3,$room4,$desc; $tourTitle = sanitize_text_field($_POST['tourTitle']); $keywords = sanitize_text_field($_POST['keywords']); $sourceTour = sanitize_text_field($_POST['sourceTour']); $destinationTour = sanitize_text_field($_POST['destinationTour']); $duration = sanitize_text_field($_POST['duration']); $tourContent = sanitize_text_field($_POST['tourContent']); $agancyservice = sanitize_text_field($_POST['agancyservice']); $passports = sanitize_text_field($_POST['passports']); $transport = sanitize_text_field($_POST['transport']); $hotel_name = sanitize_text_field($_POST['hotel_name']); $hotelRate = sanitize_text_field($_POST['hotelRate']); $room1 = sanitize_text_field($_POST['room1']); $room2 = sanitize_text_field($_POST['room2']); $room3 = sanitize_text_field($_POST['room3']); $room4 = sanitize_text_field($_POST['room4']); $desc = sanitize_text_field($_POST['desc']); add_complete_tour(); } function validate_tour_data($tourTitle,$keywords,$sourceTour,$destinationTour,$duration,$tourContent,$agancyservice,$passports,$transport,$hotel_name,$hotelRate,$room1,$room2,$room3,$room4,$desc){ global $reg_errors; $reg_errors = new WP_Error; if (empty($tourTitle)) { $reg_errors->add('tourTitle', 'عنوان تور را وارد کنید.'); } if (empty($keywords)) { $reg_errors->add('keywords', 'حداقل یک کلمه کلیدی و حداکثر سه کلمه کلیدی وارد کنید.'); } if (empty($sourceTour)) { $reg_errors->add('sourceTour', 'مبدا و آغاز تور را وارد کنید.'); } if (empty($destinationTour)) { $reg_errors->add('destinationTour', 'مقصد تور را وارد کنید.'); } if (empty($duration)) { $reg_errors->add('duration', 'مدت اقامت را وارد کنید.'); } if (!is_numeric($duration)) { $reg_errors->add('duration', 'مدت اقامت فقط میتواند مقداری عددی باشد.'); } if (empty($tourContent)) { $reg_errors->add('tourContent', 'توضیح مختصری در مورد تور وارد کنید.'); } if (empty($agancyservice)) { $reg_errors->add('agancyservice', 'خدمات آژانس مسافرتی را وارد کنید.'); } if (empty($passports)) { $reg_errors->add('passports', 'مدارک مورد نیاز تور مسافرنی را وارد کنید.'); } if (empty($transport)) { $reg_errors->add('transport', 'نوع سفر را انتخاب کنید.'); } } function add_complete_tour(){ global $tourTitle,$keywords,$sourceTour,$destinationTour,$duration,$tourContent,$agancyservice,$passports,$transport,$hotel_name,$hotelRate,$room1,$room2,$room3,$room4,$desc; if (is_wp_error($reg_errors) && count($reg_errors->get_error_messages()) > 0) { echo '<div class="alert alert-danger" role="alert" style="margin-top: 10px;font-size:15px;">'; foreach ($reg_errors->get_error_messages() as $error) { echo '<strong>خطا</strong>:'; echo $error . '<br/>'; } echo '</div>'; } elseif (count($reg_errors->get_error_messages()) < 1) { $post_data = array( 'post_title' => $tourTitle, 'post_content' => $tourContent, 'post_status' => 'pending', 'post_author' => get_current_user_id(), ); // Insert the post into the database $post_id = wp_insert_post( $post_data ); echo '<div class="alert alert-success" role="alert" style="margin-top: 10px;font-size:15px;">تور مسافرتی با موفقیت ثبت شد. پس از بررسی مدیریت و تایید منتشر خواهد شد.</div>'; } } ?> ```
I assume, you need something like editors can't see the category column or something like this. This snippet might help you: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 ); function change_columns_for_user( $columns, $post_type ){ if( 'post' != $post_type ) return $columns; if( current_user_can( 'manage_options' ) ) return $columns; else{ //Remove Categories unset( $columns['categories'] ); //Remove Tags unset( $columns['tags'] ); //Remove Comments unset( $columns['comments'] ); return $columns; } } ``` In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more. > > But It should not be able to change from the particular user login. > > > If you still want to disable the options panel for some users, have a look into this snippet: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 ); function remove_screen_settings( $show_screen, $class ){ if( 'edit-post' != $class->id ) return $show_screen; if( ! current_user_can( 'manage_options' ) ) return false; else return true; } ```
184,557
<p>On attachment pages, I have a link back to the post/page where the file was uploaded. (This is not displayed for files that were directly added to the Media Library and that's fine.)</p> <p>For attachments added to posts and pages, the following code generates the link:</p> <pre><code>$post = get_post( get_the_ID() ); if ( $post-&gt;post_parent ) { echo '&lt;a href="' . get_permalink( $post-&gt;post_parent ) . '"&gt;' . get_the_title( $post-&gt;post_parent ) . '&lt;/a&gt;'; } </code></pre> <p>However, when I try viewing an attachment that was uploaded to a custom post type, it doesn't work.</p> <p>If I display a var_dump of $post, I get the following:</p> <pre><code>object(WP_Post)#398 (24) { ["ID"]=&gt; int(789) ["post_author"]=&gt; string(1) "1" ["post_date"]=&gt; string(19) "2015-04-17 13:32:39" ["post_date_gmt"]=&gt; string(19) "2015-04-17 13:32:39" ["post_content"]=&gt; string(0) "" ["post_title"]=&gt; string(5) "image" ["post_excerpt"]=&gt; string(0) "" ["post_status"]=&gt; string(7) "inherit" ["comment_status"]=&gt; string(4) "open" ["ping_status"]=&gt; string(4) "open" ["post_password"]=&gt; string(0) "" ["post_name"]=&gt; string(5) "image" ["to_ping"]=&gt; string(0) "" ["pinged"]=&gt; string(0) "" ["post_modified"]=&gt; string(19) "2015-04-17 13:32:39" ["post_modified_gmt"]=&gt; string(19) "2015-04-17 13:32:39" ["post_content_filtered"]=&gt; string(0) "" ["post_parent"]=&gt; int(0) ["guid"]=&gt; string(63) "wp-content/uploads/2015/04/image.jpg" ["menu_order"]=&gt; int(0) ["post_type"]=&gt; string(10) "attachment" ["post_mime_type"]=&gt; string(10) "image/jpeg" ["comment_count"]=&gt; string(1) "0" ["filter"]=&gt; string(3) "raw" } </code></pre> <p>The concerning part is <code>["post_parent"]=&gt; int(0)</code> implying that files attached to custom posts don't have a parent.</p> <p>Can anyone confirm this? Or could this be an error with that way I have setup the custom post type?</p> <p>I have tried both hierarchical and non-hierarchical types, and with and without 'page-attributes' supported.</p> <p>Thanks in advance for anyone's help,</p> <p>Adam</p>
[ { "answer_id": 184527, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">capabilities API</a> to conditionally set screen options:</p>\n\n<pre><code>if ( current_user_can( 'manage_options' ) ) {\n // Administrator, add some options\n} else {\n // Other roles, do something different\n}\n</code></pre>\n" }, { "answer_id": 184538, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>I assume, you need something like editors can't see the category column or something like this.</p>\n\n<p>This snippet might help you:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 );\nfunction change_columns_for_user( $columns, $post_type ){\n if( 'post' != $post_type )\n return $columns;\n\n if( current_user_can( 'manage_options' ) )\n return $columns;\n else{\n //Remove Categories\n unset( $columns['categories'] );\n //Remove Tags\n unset( $columns['tags'] );\n //Remove Comments\n unset( $columns['comments'] );\n return $columns;\n }\n\n}\n</code></pre>\n\n<p>In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more.</p>\n\n<blockquote>\n <p>But It should not be able to change from the particular user login.</p>\n</blockquote>\n\n<p>If you still want to disable the options panel for some users, have a look into this snippet:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 );\nfunction remove_screen_settings( $show_screen, $class ){\n if( 'edit-post' != $class-&gt;id )\n return $show_screen;\n\n if( ! current_user_can( 'manage_options' ) )\n return false;\n else\n return true;\n}\n</code></pre>\n" }, { "answer_id": 184614, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": false, "text": "<p>I have accepted the @websupporter answer according to my question. </p>\n\n<p>However I would like add few codes to specific question I have faced earlier.</p>\n\n<p>I need to remove <code>Yoast SEO</code> plugin extra columns from the non admin users. In that specific case <code>Yoast SEO</code> provide the hook to disable the columns. So I used that as below.</p>\n\n<pre><code>/** Remove SEO columns when User is not admin**/\nfunction remove_page_analysis_for_non_admin(){\n if( current_user_can( 'manage_options' ) )\n return true;\n else{\n return false;\n }\n}\nadd_filter( 'wpseo_use_page_analysis', 'remove_page_analysis_for_non_admin', 10, 2 );\n</code></pre>\n\n<p>If anybody would interesting to remove it for all users, use following code</p>\n\n<pre><code>add_filter( 'wpseo_use_page_analysis', '__return_false' );\n</code></pre>\n" } ]
2015/04/17
[ "https://wordpress.stackexchange.com/questions/184557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70779/" ]
On attachment pages, I have a link back to the post/page where the file was uploaded. (This is not displayed for files that were directly added to the Media Library and that's fine.) For attachments added to posts and pages, the following code generates the link: ``` $post = get_post( get_the_ID() ); if ( $post->post_parent ) { echo '<a href="' . get_permalink( $post->post_parent ) . '">' . get_the_title( $post->post_parent ) . '</a>'; } ``` However, when I try viewing an attachment that was uploaded to a custom post type, it doesn't work. If I display a var\_dump of $post, I get the following: ``` object(WP_Post)#398 (24) { ["ID"]=> int(789) ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2015-04-17 13:32:39" ["post_date_gmt"]=> string(19) "2015-04-17 13:32:39" ["post_content"]=> string(0) "" ["post_title"]=> string(5) "image" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "inherit" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(4) "open" ["post_password"]=> string(0) "" ["post_name"]=> string(5) "image" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2015-04-17 13:32:39" ["post_modified_gmt"]=> string(19) "2015-04-17 13:32:39" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(63) "wp-content/uploads/2015/04/image.jpg" ["menu_order"]=> int(0) ["post_type"]=> string(10) "attachment" ["post_mime_type"]=> string(10) "image/jpeg" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } ``` The concerning part is `["post_parent"]=> int(0)` implying that files attached to custom posts don't have a parent. Can anyone confirm this? Or could this be an error with that way I have setup the custom post type? I have tried both hierarchical and non-hierarchical types, and with and without 'page-attributes' supported. Thanks in advance for anyone's help, Adam
I assume, you need something like editors can't see the category column or something like this. This snippet might help you: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 ); function change_columns_for_user( $columns, $post_type ){ if( 'post' != $post_type ) return $columns; if( current_user_can( 'manage_options' ) ) return $columns; else{ //Remove Categories unset( $columns['categories'] ); //Remove Tags unset( $columns['tags'] ); //Remove Comments unset( $columns['comments'] ); return $columns; } } ``` In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more. > > But It should not be able to change from the particular user login. > > > If you still want to disable the options panel for some users, have a look into this snippet: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 ); function remove_screen_settings( $show_screen, $class ){ if( 'edit-post' != $class->id ) return $show_screen; if( ! current_user_can( 'manage_options' ) ) return false; else return true; } ```
184,574
<p>I have an old intranet site running on 3.6.2 and tried to manually upgrade it to 4.1.1. After moving the files over the site just "spins". I have manually upgraded our sites literally 100 times (connection directly to wp.org does not work so there is no way to do it auto) and have never had this come up. I ended up going up one version at a time - 3.7, 3.8, 3.9, 4.0, 4.1) and this worked but wondering why it didn't take before?</p> <p>Follow up question: Why can't wordpress recognize my version and then upgrade the DB appropriately?</p>
[ { "answer_id": 184527, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">capabilities API</a> to conditionally set screen options:</p>\n\n<pre><code>if ( current_user_can( 'manage_options' ) ) {\n // Administrator, add some options\n} else {\n // Other roles, do something different\n}\n</code></pre>\n" }, { "answer_id": 184538, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>I assume, you need something like editors can't see the category column or something like this.</p>\n\n<p>This snippet might help you:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 );\nfunction change_columns_for_user( $columns, $post_type ){\n if( 'post' != $post_type )\n return $columns;\n\n if( current_user_can( 'manage_options' ) )\n return $columns;\n else{\n //Remove Categories\n unset( $columns['categories'] );\n //Remove Tags\n unset( $columns['tags'] );\n //Remove Comments\n unset( $columns['comments'] );\n return $columns;\n }\n\n}\n</code></pre>\n\n<p>In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more.</p>\n\n<blockquote>\n <p>But It should not be able to change from the particular user login.</p>\n</blockquote>\n\n<p>If you still want to disable the options panel for some users, have a look into this snippet:</p>\n\n<pre><code>/** Remove \"Options\"-Panel, when User is not admin **/\nadd_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 );\nfunction remove_screen_settings( $show_screen, $class ){\n if( 'edit-post' != $class-&gt;id )\n return $show_screen;\n\n if( ! current_user_can( 'manage_options' ) )\n return false;\n else\n return true;\n}\n</code></pre>\n" }, { "answer_id": 184614, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": false, "text": "<p>I have accepted the @websupporter answer according to my question. </p>\n\n<p>However I would like add few codes to specific question I have faced earlier.</p>\n\n<p>I need to remove <code>Yoast SEO</code> plugin extra columns from the non admin users. In that specific case <code>Yoast SEO</code> provide the hook to disable the columns. So I used that as below.</p>\n\n<pre><code>/** Remove SEO columns when User is not admin**/\nfunction remove_page_analysis_for_non_admin(){\n if( current_user_can( 'manage_options' ) )\n return true;\n else{\n return false;\n }\n}\nadd_filter( 'wpseo_use_page_analysis', 'remove_page_analysis_for_non_admin', 10, 2 );\n</code></pre>\n\n<p>If anybody would interesting to remove it for all users, use following code</p>\n\n<pre><code>add_filter( 'wpseo_use_page_analysis', '__return_false' );\n</code></pre>\n" } ]
2015/04/17
[ "https://wordpress.stackexchange.com/questions/184574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32393/" ]
I have an old intranet site running on 3.6.2 and tried to manually upgrade it to 4.1.1. After moving the files over the site just "spins". I have manually upgraded our sites literally 100 times (connection directly to wp.org does not work so there is no way to do it auto) and have never had this come up. I ended up going up one version at a time - 3.7, 3.8, 3.9, 4.0, 4.1) and this worked but wondering why it didn't take before? Follow up question: Why can't wordpress recognize my version and then upgrade the DB appropriately?
I assume, you need something like editors can't see the category column or something like this. This snippet might help you: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'manage_posts_columns', 'change_columns_for_user', 10, 2 ); function change_columns_for_user( $columns, $post_type ){ if( 'post' != $post_type ) return $columns; if( current_user_can( 'manage_options' ) ) return $columns; else{ //Remove Categories unset( $columns['categories'] ); //Remove Tags unset( $columns['tags'] ); //Remove Comments unset( $columns['comments'] ); return $columns; } } ``` In this snippet we unset some columns if the user cant managa options. You know the options panel on the top: In this case, they wouldn't even show up in this panel no more. > > But It should not be able to change from the particular user login. > > > If you still want to disable the options panel for some users, have a look into this snippet: ``` /** Remove "Options"-Panel, when User is not admin **/ add_filter( 'screen_options_show_screen', 'remove_screen_settings', 10, 2 ); function remove_screen_settings( $show_screen, $class ){ if( 'edit-post' != $class->id ) return $show_screen; if( ! current_user_can( 'manage_options' ) ) return false; else return true; } ```
184,587
<p>I am using the <code>get_terms</code> function to order all the terms of a custom taxonomy alphabetically. My client however has now requested that one of the terms be put at the very end (therefore not in alphabetical order). Does anyone have any suggestions on how the best way to achieve this?</p>
[ { "answer_id": 184589, "author": "Stephen S.", "author_id": 5019, "author_profile": "https://wordpress.stackexchange.com/users/5019", "pm_score": 0, "selected": false, "text": "<p>There may be a better way of doing this, but you could probably just do two queries. Maybe something along these lines (untested):</p>\n\n<pre><code>$loner_term = X; //put whatever the id of the term you want at end\n$taxonomies = 'YOUR_TAXONOMY_NAME';\n)\n// get all of the alphabetical terms and exclude the one you need at the end\n$alpha_args = array(\n 'orderby' =&gt; 'name',\n 'exclude' =&gt; $loner_term\n);\n$alpha_terms = get_terms($taxonomies, $alpha_args);\n\n// only get the term you need to come at the end\n$na_args = array(\n 'include' =&gt; $loner_term\n);\n$na_terms = get_terms($taxonomies, $na_args);\n\necho '&lt;ul&gt;';\n// loop through the alphabetical terms\nforeach ($alpha_terms as $alpha_term) {\n echo '&lt;li&gt;'. $alpha_term-&gt;name.'&lt;/li&gt;';\n}\n// then loop through the loner term\nforeach ($na_terms as $na_term) {\n echo '&lt;li&gt;'. $na_term-&gt;name.'&lt;/li&gt;';\n} \necho '&lt;/ul&gt;';\n</code></pre>\n\n<p>EDITED to use get_terms properly!</p>\n" }, { "answer_id": 184590, "author": "Dmitry Mayorov", "author_id": 49499, "author_profile": "https://wordpress.stackexchange.com/users/49499", "pm_score": 0, "selected": false, "text": "<p>I stumbled across similar issue lately. If you are comfortable with using a plugin, you can install <a href=\"https://wordpress.org/plugins/custom-taxonomy-sort/\" rel=\"nofollow\">Custom Taxonomy Sort</a>. Even though it was not updated for over two years, it solved the problem for me. Basically, it allows you to sort terms manually from the dashboard.</p>\n" }, { "answer_id": 184608, "author": "Sammy Nordström", "author_id": 70758, "author_profile": "https://wordpress.stackexchange.com/users/70758", "pm_score": 0, "selected": false, "text": "<p>An idea that came to me is to add a term in your taxonomy called something like 'append' and then make the terms you want to be appended at the end of your terms list children of that term. Then it is only a matter of doing the appropriate term queries, ie get all terms with append as it's parent and then exclude them when quering for the rest. This way you maintain editorial control to this custom ordering thing and don't have to hardcode anything into your template.</p>\n" }, { "answer_id": 184611, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>This can be easily done with your own custom function. What you want to do here is, get your object from <code>get_terms()</code> which will hold your term objects, check if your unique key is set as a parameter and then according to that, remove that key/pair and add it to the back</p>\n\n<p>Now, lets put that into code: (<em>I have commented the code to make it easy to follow</em>)</p>\n\n<p>This is the pre PHP 5.5 version but still need at least PHP 5.4</p>\n\n<pre><code>function get_term_to_end( $taxonomy = '', $args = [] )\n{\n $terms = get_terms( $taxonomy, $args );\n\n /*\n * Return $terms if our new argument term_to_end is not set or empty\n */\n if ( !isset( $args['term_to_end'] ) || empty( $args['term_to_end'] ) ) \n return $terms;\n\n /*\n * If term_to_end is set and has a value, continue to process\n * Return $terms if a wp error is returned or if $terms is empty\n */\n if ( is_wp_error( $terms ) || empty( $terms ) )\n return $terms;\n /*\n * We have came this far, now we can finish this off\n */\n foreach ( $terms as $term ) {\n /*\n * Check the term ids against our new argument term_to_end\n */\n if ( $term-&gt;term_id == $args['term_to_end'] ) {\n $end[] = $term;\n } else {\n $terms_array[] = $term;\n }\n }\n /*\n * Merge the two arrays together, adding the term_to_end right at the back\n */\n $terms = array_merge( $terms_array, $end );\n\n /*\n * For uniformaty, type cast the resultant array to an object\n */\n return (object) $terms;\n}\n</code></pre>\n\n<p>If you are using PHP 5.5 +, you can use <code>array_search</code> and <code>array_column</code> and skip the <code>foreach</code> loop inside the function</p>\n\n<pre><code>function get_term_to_end( $taxonomy = '', $args = [] )\n{\n $terms = get_terms( $taxonomy, $args );\n\n /*\n * Return $terms if our new argument term_to_end is not set or empty\n */\n if ( !isset( $args['term_to_end'] ) || empty( $args['term_to_end'] ) ) \n return $terms;\n\n /*\n * If term_to_end is set and has a value, continue to process\n * Return $terms if a wp error is returned or if $terms is empty\n */\n if ( is_wp_error( $terms ) || empty( $terms ) )\n return $terms;\n\n /*\n * We have came this far, now we can finish this off\n *\n * We need to convert the multidimensional objects to a multidimensional array. Lets used\n * json_encode and json_decode. Now we can use \n * array_search to and array_column to determine the position of the term_to_end\n */\n $terms_array = json_decode( json_encode( $terms ), true );\n $end_term_position = array_search( $args['term_to_end'], array_column( $terms_array, 'term_id'));\n\n /*\n * First check if $end_term_position in not false (array_search returns false on failure), \n * if false, return $terms\n */\n if ( !$end_term_position )\n return $terms;\n\n /*\n * Get the key value pair for term_to_end, unset it from $terms and reset term_to_end pair at the back\n */\n $end_term_pair[] = $terms[$end_term_position];\n unset( $terms[$end_term_position] );\n $new_terms_array = array_merge( (array) $terms, $end_term_pair );\n\n /*\n * We are done!! Now we can just return $new_terms_array as an object\n */\n return (object) $new_terms_array;\n}\n</code></pre>\n\n<p>Example use case:</p>\n\n<p>Move term with id 15 belonging to the taxonomy <code>mytax</code> to the back of the term array. Keep the default odering by name</p>\n\n<pre><code>$terms = get_term_to_end( 'mytax', ['term_to_end' =&gt; 15] );\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>$args = [\n 'term_to_end' =&gt; 15\n];\n$terms = get_term_to_end( 'mytax, $args );\n</code></pre>\n\n<p>FEW NOTES ON THE ABOVE</p>\n\n<ul>\n<li><p>The code above is all untested and might be buggy. I have written this on a tablet.</p></li>\n<li><p>For older versions (pre PHP 5.4), use the first code block and simply change the new array syntax (<code>[]</code>) to the old syntax (<code>array()</code>)</p></li>\n<li><p>The new parameter, <code>term_to_end</code> uses the term to move to the end term's ID. You can modify this to work with either the term name or term slug, whatever suites your need. You can also modify this to work with all of these values</p></li>\n<li><p>The new function uses the exact same parameters as <code>get_terms()</code>. The only extra addition is the <code>term_to_end</code> parameter</p></li>\n<li><p>As <code>get_terms</code>, the new function returns a <code>WP_Error</code> object if a taxonomy does not exists and also returns an ampty array if no terms are found. Remember to check for these occurances in the same way you would with <code>get_terms</code></p></li>\n<li><p>If the <code>term_to_end</code> parameter is set, the <code>fields</code> parameter cannot be set to anything else than <code>all</code> (which is the default). Any other value will break the function. You can modify this very easily to work properly by building in some coditional checks and changing the <code>foreach</code> in the first code block or changing the use of <code>array_search</code> in the second code block</p></li>\n<li><p>You can very easily change the function to move a selected term to the front if needed. You can also adjust the function to accept multiple terms to move</p></li>\n<li><p>For any other info regarding the use of this function, please see <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\"><code>get_terms</code></a></p></li>\n</ul>\n\n<p>EDIT</p>\n\n<p>This code in now tested and working as expected.</p>\n" } ]
2015/04/17
[ "https://wordpress.stackexchange.com/questions/184587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23406/" ]
I am using the `get_terms` function to order all the terms of a custom taxonomy alphabetically. My client however has now requested that one of the terms be put at the very end (therefore not in alphabetical order). Does anyone have any suggestions on how the best way to achieve this?
This can be easily done with your own custom function. What you want to do here is, get your object from `get_terms()` which will hold your term objects, check if your unique key is set as a parameter and then according to that, remove that key/pair and add it to the back Now, lets put that into code: (*I have commented the code to make it easy to follow*) This is the pre PHP 5.5 version but still need at least PHP 5.4 ``` function get_term_to_end( $taxonomy = '', $args = [] ) { $terms = get_terms( $taxonomy, $args ); /* * Return $terms if our new argument term_to_end is not set or empty */ if ( !isset( $args['term_to_end'] ) || empty( $args['term_to_end'] ) ) return $terms; /* * If term_to_end is set and has a value, continue to process * Return $terms if a wp error is returned or if $terms is empty */ if ( is_wp_error( $terms ) || empty( $terms ) ) return $terms; /* * We have came this far, now we can finish this off */ foreach ( $terms as $term ) { /* * Check the term ids against our new argument term_to_end */ if ( $term->term_id == $args['term_to_end'] ) { $end[] = $term; } else { $terms_array[] = $term; } } /* * Merge the two arrays together, adding the term_to_end right at the back */ $terms = array_merge( $terms_array, $end ); /* * For uniformaty, type cast the resultant array to an object */ return (object) $terms; } ``` If you are using PHP 5.5 +, you can use `array_search` and `array_column` and skip the `foreach` loop inside the function ``` function get_term_to_end( $taxonomy = '', $args = [] ) { $terms = get_terms( $taxonomy, $args ); /* * Return $terms if our new argument term_to_end is not set or empty */ if ( !isset( $args['term_to_end'] ) || empty( $args['term_to_end'] ) ) return $terms; /* * If term_to_end is set and has a value, continue to process * Return $terms if a wp error is returned or if $terms is empty */ if ( is_wp_error( $terms ) || empty( $terms ) ) return $terms; /* * We have came this far, now we can finish this off * * We need to convert the multidimensional objects to a multidimensional array. Lets used * json_encode and json_decode. Now we can use * array_search to and array_column to determine the position of the term_to_end */ $terms_array = json_decode( json_encode( $terms ), true ); $end_term_position = array_search( $args['term_to_end'], array_column( $terms_array, 'term_id')); /* * First check if $end_term_position in not false (array_search returns false on failure), * if false, return $terms */ if ( !$end_term_position ) return $terms; /* * Get the key value pair for term_to_end, unset it from $terms and reset term_to_end pair at the back */ $end_term_pair[] = $terms[$end_term_position]; unset( $terms[$end_term_position] ); $new_terms_array = array_merge( (array) $terms, $end_term_pair ); /* * We are done!! Now we can just return $new_terms_array as an object */ return (object) $new_terms_array; } ``` Example use case: Move term with id 15 belonging to the taxonomy `mytax` to the back of the term array. Keep the default odering by name ``` $terms = get_term_to_end( 'mytax', ['term_to_end' => 15] ); ``` Or ``` $args = [ 'term_to_end' => 15 ]; $terms = get_term_to_end( 'mytax, $args ); ``` FEW NOTES ON THE ABOVE * The code above is all untested and might be buggy. I have written this on a tablet. * For older versions (pre PHP 5.4), use the first code block and simply change the new array syntax (`[]`) to the old syntax (`array()`) * The new parameter, `term_to_end` uses the term to move to the end term's ID. You can modify this to work with either the term name or term slug, whatever suites your need. You can also modify this to work with all of these values * The new function uses the exact same parameters as `get_terms()`. The only extra addition is the `term_to_end` parameter * As `get_terms`, the new function returns a `WP_Error` object if a taxonomy does not exists and also returns an ampty array if no terms are found. Remember to check for these occurances in the same way you would with `get_terms` * If the `term_to_end` parameter is set, the `fields` parameter cannot be set to anything else than `all` (which is the default). Any other value will break the function. You can modify this very easily to work properly by building in some coditional checks and changing the `foreach` in the first code block or changing the use of `array_search` in the second code block * You can very easily change the function to move a selected term to the front if needed. You can also adjust the function to accept multiple terms to move * For any other info regarding the use of this function, please see [`get_terms`](https://codex.wordpress.org/Function_Reference/get_terms) EDIT This code in now tested and working as expected.
184,600
<p>I see this subject comes up regularly but have not seen an answer to my specific requirement yet.</p> <p>I'm trying to use a WordPress page as a template and insert database-sourced content (about 20 or so fields of text, including image file names) based on an ID passed as a URL parameter (and index to my database). e.g. www.example.com/examplepage/?pid=123</p> <p>Before WordPress, I could do this in PHP easily by executing some code to get a database record and then writing out HTML interspersed with those fields.</p> <p>I have a plugin in WordPress that allows me to do some PHP code snippets on page, but that's in the page body and I believe the header has already been written out. The header has fields like title and meta desc that I'd like to be populated by dynamic content.</p> <p>I've seen plug-ins for CMS-like management of real estate listings, movies, etc. but my database handling is a but unusual so I have to take a custom build approach.</p> <p>I understand that I may need to do some work in the functions.php script for my theme in order to dig into WordPress' page rendering, but I'd like to be careful not to disturb general pages/posts on my site. It's just this one special page that will accept a parameters and load the appropriate content.</p> <p>Some advice on the steps I need to take would be most appreciated.</p>
[ { "answer_id": 184602, "author": "GastroGeek", "author_id": 70445, "author_profile": "https://wordpress.stackexchange.com/users/70445", "pm_score": 0, "selected": false, "text": "<p>I might be missing something but:</p>\n\n<p>If you only need the 'pid' for example and it is part of the URL then its fairly simple?</p>\n\n<p>In the page template 'examplepage' just do a:</p>\n\n<pre><code>$mypid = $_GET['pid'];\n</code></pre>\n\n<p>in there and then carry on with the SQL query based on that value and echo out a response.</p>\n\n<p>If you want something a little more ajax based then when the user lands on 'examplepage' take the 'pid' and add as a class or data attribute on an empty div. Say called: 'results-container'</p>\n\n<pre><code>&lt;?php $mypid = $_GET['pid']; ?&gt;\n&lt;div class\"results-container\" mypid=\"&lt;?php echo $mypid; ?&gt;\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>And then have a js script execute on document ready that reads the mypid attribute on that div and does a seperate fetch. This way the page can load and show a 'fetching' status and some preliminary content while the results load in.</p>\n\n<p>Hope that made sense.</p>\n\n<p>-Typed with fat fingers on a mobile phone! aaaaah.</p>\n" }, { "answer_id": 184606, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>As you are building a page template, you can insert in the content of that template whatever you want and use any PHP snippet you want. So, you can continue doing it as you was doing in PHP. For example, this could be your page template:</p>\n\n<pre><code>&lt;?php\n/*\nTemplate Name: My template\n*/\nget_header();\n\n?&gt;\n&lt;main&gt;\n\n &lt;?php\n\n if( isset( $_GET['pid'] ) ) {\n\n // Populate your dynamic content here\n\n }\n\n ?&gt;\n\n\n&lt;/main&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>But you are correct about title and meta tags of the document, they may be already set. Here you need to hook into <code>wp_title</code> filter and <code>wp_head</code> action, using <code>is_page_template</code> function to check if you are in the page template.</p>\n\n<p>For example, suppose that your page tempalte file name is something like <code>page-mytemplate.php</code> and it is located in the root of your theme:</p>\n\n<pre><code>add_filter( 'wp_title', function( $title, $sep ) {\n\n if( is_page_template( 'page-mytemplate.php' ) ) {\n\n // Modify the $title here\n $title = 'my new title';\n\n }\n\n return $title;\n\n}, 10, 2 );\n\nadd_action( 'wp_head', function() {\n\n if( is_page_template( 'page-mytemplate.php' ) ) {\n\n // Echo/print your meta tags here\n echo '&lt;meta name=....&gt;';\n\n }\n\n} );\n</code></pre>\n\n<p><strong>The problem</strong></p>\n\n<p>The are a big problem with <code>&lt;meta&gt;</code> tags. WordPress has not a standard way to manage <code>&lt;meta&gt;</code> tags of the docuemnt. If you use any plugin that add <code>&lt;meta&gt;</code> tags, you won't be able to override them unless the plugin offer a way to do it.</p>\n\n<p><strong>Reference</strong></p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title\" rel=\"nofollow\">wp_title filter</a></li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\">wp_head action</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/is_page_template\" rel=\"nofollow\">is_page_template() function</a></li>\n</ul>\n" }, { "answer_id": 339956, "author": "Debbie Kurth", "author_id": 119560, "author_profile": "https://wordpress.stackexchange.com/users/119560", "pm_score": 0, "selected": false, "text": "<p>I have done this myself just recently. This may be late to the party, but in the event other want to know how, these were my steps in a wordpress environment </p>\n\n<ol>\n<li><p>Create a function that read the URL parameter, such as:</p>\n\n<pre><code>function details_Page($atts)\n {\n global $wpdb; \n\n\n // Get the database record for this details\n $DatabaseId = $_GET['pid'];\n if(!is_numeric ($DatabaseId))\n {\n // GO TO MISSING PAGE. PAGE IS NOT VALID. \n header('Location: /missing-page/'); \n return;\n }\n\n GENERATE YOUR PAGE CODE HERE\n}\n</code></pre></li>\n</ol>\n\n<p>Now create a shortcode for this function or use it in your page template. Functionally speaking, this is another way to do a page template.</p>\n\n<pre><code> add_shortcode('DETAILS_PAGE', 'details_Page');\n</code></pre>\n\n<p>Now add the shortcode to the specifically defined page (or template).</p>\n\n<p>To change the header to match you data, making sure the add_action call is in the primary loop or functions.php. Otherwise you will have a race condition.</p>\n\n<pre><code> add_action( 'wp_head', 'MMD_listings_add_custom_meta', 10 );\n function add_custom_meta()\n {\n $slug = basename(get_permalink()); // I use for the particular page\n if( $slug == 'details')\n {\n $Name = $_GET[ 'Name' ];\n $Desc = $_GET[ 'Desc' ];\n $Logo = $_GET[ 'Logo' ];\n ?&gt; \n &lt;meta content=\"&lt;?php echo $Name; ?&gt;&gt;\"/&gt;\n &lt;meta content=\"&lt;?php echo $Desc; ?&gt;\"&gt;\n &lt;?PHP\n }\n }\n</code></pre>\n" } ]
2015/04/18
[ "https://wordpress.stackexchange.com/questions/184600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70803/" ]
I see this subject comes up regularly but have not seen an answer to my specific requirement yet. I'm trying to use a WordPress page as a template and insert database-sourced content (about 20 or so fields of text, including image file names) based on an ID passed as a URL parameter (and index to my database). e.g. www.example.com/examplepage/?pid=123 Before WordPress, I could do this in PHP easily by executing some code to get a database record and then writing out HTML interspersed with those fields. I have a plugin in WordPress that allows me to do some PHP code snippets on page, but that's in the page body and I believe the header has already been written out. The header has fields like title and meta desc that I'd like to be populated by dynamic content. I've seen plug-ins for CMS-like management of real estate listings, movies, etc. but my database handling is a but unusual so I have to take a custom build approach. I understand that I may need to do some work in the functions.php script for my theme in order to dig into WordPress' page rendering, but I'd like to be careful not to disturb general pages/posts on my site. It's just this one special page that will accept a parameters and load the appropriate content. Some advice on the steps I need to take would be most appreciated.
As you are building a page template, you can insert in the content of that template whatever you want and use any PHP snippet you want. So, you can continue doing it as you was doing in PHP. For example, this could be your page template: ``` <?php /* Template Name: My template */ get_header(); ?> <main> <?php if( isset( $_GET['pid'] ) ) { // Populate your dynamic content here } ?> </main> <?php get_footer(); ?> ``` But you are correct about title and meta tags of the document, they may be already set. Here you need to hook into `wp_title` filter and `wp_head` action, using `is_page_template` function to check if you are in the page template. For example, suppose that your page tempalte file name is something like `page-mytemplate.php` and it is located in the root of your theme: ``` add_filter( 'wp_title', function( $title, $sep ) { if( is_page_template( 'page-mytemplate.php' ) ) { // Modify the $title here $title = 'my new title'; } return $title; }, 10, 2 ); add_action( 'wp_head', function() { if( is_page_template( 'page-mytemplate.php' ) ) { // Echo/print your meta tags here echo '<meta name=....>'; } } ); ``` **The problem** The are a big problem with `<meta>` tags. WordPress has not a standard way to manage `<meta>` tags of the docuemnt. If you use any plugin that add `<meta>` tags, you won't be able to override them unless the plugin offer a way to do it. **Reference** * [wp\_title filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title) * [wp\_head action](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head) * [is\_page\_template() function](https://codex.wordpress.org/Function_Reference/is_page_template)
184,627
<p>first of all, im sorry for my poor english, when i upadte a post this code changes the post slug to a "profileid" costom field value.. </p> <pre><code>add_action('save_post', 'my_custom_slug'); function my_custom_slug($post_id) { //Check it's not an auto save routine if ( defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) return; //Perform permission checks! For example: if ( !current_user_can('edit_post', $post_id) ) return; //If calling wp_update_post, unhook this function so it doesn't loop infinitely remove_action('save_post', 'my_custom_slug'); //call wp_update_post update, which calls save_post again. E.g: wp_update_post(array('ID' =&gt; $post_id, 'post_name' =&gt;get_post_meta($post_id,'profileid',true))); // re-hook this function add_action('save_post', 'my_custom_slug'); } </code></pre> <p>it works fine, but how i can use this for only a specific custom post type? my custom post type is "masters".. i used this, but not works! anyone can help?</p> <pre><code>add_action('save_post', 'my_custom_slug'); function my_custom_slug($post_id) { $slug = 'masters'; // If this isn't a 'masters' post, don't update it. if ( $slug != $post-&gt;post_type ) return $post_id; //Check it's not an auto save routine if ( defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) return; //Perform permission checks! For example: if ( !current_user_can('edit_post', $post_id) ) return; //If calling wp_update_post, unhook this function so it doesn't loop infinitely remove_action('save_post', 'my_custom_slug'); //call wp_update_post update, which calls save_post again. E.g: wp_update_post(array('ID' =&gt; $post_id, 'post_name' =&gt;get_post_meta($post_id,'profileid',true))); // re-hook this function add_action('save_post', 'my_custom_slug'); } </code></pre>
[ { "answer_id": 184602, "author": "GastroGeek", "author_id": 70445, "author_profile": "https://wordpress.stackexchange.com/users/70445", "pm_score": 0, "selected": false, "text": "<p>I might be missing something but:</p>\n\n<p>If you only need the 'pid' for example and it is part of the URL then its fairly simple?</p>\n\n<p>In the page template 'examplepage' just do a:</p>\n\n<pre><code>$mypid = $_GET['pid'];\n</code></pre>\n\n<p>in there and then carry on with the SQL query based on that value and echo out a response.</p>\n\n<p>If you want something a little more ajax based then when the user lands on 'examplepage' take the 'pid' and add as a class or data attribute on an empty div. Say called: 'results-container'</p>\n\n<pre><code>&lt;?php $mypid = $_GET['pid']; ?&gt;\n&lt;div class\"results-container\" mypid=\"&lt;?php echo $mypid; ?&gt;\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>And then have a js script execute on document ready that reads the mypid attribute on that div and does a seperate fetch. This way the page can load and show a 'fetching' status and some preliminary content while the results load in.</p>\n\n<p>Hope that made sense.</p>\n\n<p>-Typed with fat fingers on a mobile phone! aaaaah.</p>\n" }, { "answer_id": 184606, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>As you are building a page template, you can insert in the content of that template whatever you want and use any PHP snippet you want. So, you can continue doing it as you was doing in PHP. For example, this could be your page template:</p>\n\n<pre><code>&lt;?php\n/*\nTemplate Name: My template\n*/\nget_header();\n\n?&gt;\n&lt;main&gt;\n\n &lt;?php\n\n if( isset( $_GET['pid'] ) ) {\n\n // Populate your dynamic content here\n\n }\n\n ?&gt;\n\n\n&lt;/main&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>But you are correct about title and meta tags of the document, they may be already set. Here you need to hook into <code>wp_title</code> filter and <code>wp_head</code> action, using <code>is_page_template</code> function to check if you are in the page template.</p>\n\n<p>For example, suppose that your page tempalte file name is something like <code>page-mytemplate.php</code> and it is located in the root of your theme:</p>\n\n<pre><code>add_filter( 'wp_title', function( $title, $sep ) {\n\n if( is_page_template( 'page-mytemplate.php' ) ) {\n\n // Modify the $title here\n $title = 'my new title';\n\n }\n\n return $title;\n\n}, 10, 2 );\n\nadd_action( 'wp_head', function() {\n\n if( is_page_template( 'page-mytemplate.php' ) ) {\n\n // Echo/print your meta tags here\n echo '&lt;meta name=....&gt;';\n\n }\n\n} );\n</code></pre>\n\n<p><strong>The problem</strong></p>\n\n<p>The are a big problem with <code>&lt;meta&gt;</code> tags. WordPress has not a standard way to manage <code>&lt;meta&gt;</code> tags of the docuemnt. If you use any plugin that add <code>&lt;meta&gt;</code> tags, you won't be able to override them unless the plugin offer a way to do it.</p>\n\n<p><strong>Reference</strong></p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title\" rel=\"nofollow\">wp_title filter</a></li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\">wp_head action</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/is_page_template\" rel=\"nofollow\">is_page_template() function</a></li>\n</ul>\n" }, { "answer_id": 339956, "author": "Debbie Kurth", "author_id": 119560, "author_profile": "https://wordpress.stackexchange.com/users/119560", "pm_score": 0, "selected": false, "text": "<p>I have done this myself just recently. This may be late to the party, but in the event other want to know how, these were my steps in a wordpress environment </p>\n\n<ol>\n<li><p>Create a function that read the URL parameter, such as:</p>\n\n<pre><code>function details_Page($atts)\n {\n global $wpdb; \n\n\n // Get the database record for this details\n $DatabaseId = $_GET['pid'];\n if(!is_numeric ($DatabaseId))\n {\n // GO TO MISSING PAGE. PAGE IS NOT VALID. \n header('Location: /missing-page/'); \n return;\n }\n\n GENERATE YOUR PAGE CODE HERE\n}\n</code></pre></li>\n</ol>\n\n<p>Now create a shortcode for this function or use it in your page template. Functionally speaking, this is another way to do a page template.</p>\n\n<pre><code> add_shortcode('DETAILS_PAGE', 'details_Page');\n</code></pre>\n\n<p>Now add the shortcode to the specifically defined page (or template).</p>\n\n<p>To change the header to match you data, making sure the add_action call is in the primary loop or functions.php. Otherwise you will have a race condition.</p>\n\n<pre><code> add_action( 'wp_head', 'MMD_listings_add_custom_meta', 10 );\n function add_custom_meta()\n {\n $slug = basename(get_permalink()); // I use for the particular page\n if( $slug == 'details')\n {\n $Name = $_GET[ 'Name' ];\n $Desc = $_GET[ 'Desc' ];\n $Logo = $_GET[ 'Logo' ];\n ?&gt; \n &lt;meta content=\"&lt;?php echo $Name; ?&gt;&gt;\"/&gt;\n &lt;meta content=\"&lt;?php echo $Desc; ?&gt;\"&gt;\n &lt;?PHP\n }\n }\n</code></pre>\n" } ]
2015/04/18
[ "https://wordpress.stackexchange.com/questions/184627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70816/" ]
first of all, im sorry for my poor english, when i upadte a post this code changes the post slug to a "profileid" costom field value.. ``` add_action('save_post', 'my_custom_slug'); function my_custom_slug($post_id) { //Check it's not an auto save routine if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return; //Perform permission checks! For example: if ( !current_user_can('edit_post', $post_id) ) return; //If calling wp_update_post, unhook this function so it doesn't loop infinitely remove_action('save_post', 'my_custom_slug'); //call wp_update_post update, which calls save_post again. E.g: wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'profileid',true))); // re-hook this function add_action('save_post', 'my_custom_slug'); } ``` it works fine, but how i can use this for only a specific custom post type? my custom post type is "masters".. i used this, but not works! anyone can help? ``` add_action('save_post', 'my_custom_slug'); function my_custom_slug($post_id) { $slug = 'masters'; // If this isn't a 'masters' post, don't update it. if ( $slug != $post->post_type ) return $post_id; //Check it's not an auto save routine if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return; //Perform permission checks! For example: if ( !current_user_can('edit_post', $post_id) ) return; //If calling wp_update_post, unhook this function so it doesn't loop infinitely remove_action('save_post', 'my_custom_slug'); //call wp_update_post update, which calls save_post again. E.g: wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'profileid',true))); // re-hook this function add_action('save_post', 'my_custom_slug'); } ```
As you are building a page template, you can insert in the content of that template whatever you want and use any PHP snippet you want. So, you can continue doing it as you was doing in PHP. For example, this could be your page template: ``` <?php /* Template Name: My template */ get_header(); ?> <main> <?php if( isset( $_GET['pid'] ) ) { // Populate your dynamic content here } ?> </main> <?php get_footer(); ?> ``` But you are correct about title and meta tags of the document, they may be already set. Here you need to hook into `wp_title` filter and `wp_head` action, using `is_page_template` function to check if you are in the page template. For example, suppose that your page tempalte file name is something like `page-mytemplate.php` and it is located in the root of your theme: ``` add_filter( 'wp_title', function( $title, $sep ) { if( is_page_template( 'page-mytemplate.php' ) ) { // Modify the $title here $title = 'my new title'; } return $title; }, 10, 2 ); add_action( 'wp_head', function() { if( is_page_template( 'page-mytemplate.php' ) ) { // Echo/print your meta tags here echo '<meta name=....>'; } } ); ``` **The problem** The are a big problem with `<meta>` tags. WordPress has not a standard way to manage `<meta>` tags of the docuemnt. If you use any plugin that add `<meta>` tags, you won't be able to override them unless the plugin offer a way to do it. **Reference** * [wp\_title filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title) * [wp\_head action](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head) * [is\_page\_template() function](https://codex.wordpress.org/Function_Reference/is_page_template)
184,637
<p>I want to be able to trigger the WooCommerce order complete email at a different stage in the WooCommerce checkout process. So I've disabled WooCommerce order complete email from the backend and am now looking for a line of code that will trigger the email at the point that I want. I've done a bit of research and I've found how to <em>remove</em> the order complete email but not how to trigger it manually. Any tips?</p> <p>Thanks!</p>
[ { "answer_id": 184639, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 5, "selected": true, "text": "<p>You can try this</p>\n\n<pre><code>$mailer = WC()-&gt;mailer();\n$mails = $mailer-&gt;get_emails();\nif ( ! empty( $mails ) ) {\n foreach ( $mails as $mail ) {\n if ( $mail-&gt;id == 'customer_completed_order' ) {\n $mail-&gt;trigger( $order-&gt;id );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 314657, "author": "Karthik Thayyil", "author_id": 129405, "author_profile": "https://wordpress.stackexchange.com/users/129405", "pm_score": 3, "selected": false, "text": "<p>Rather than looping or reusing the same object as suggested by @Sumit.\nYou can initiate a new object and then call the trigger. </p>\n\n<pre><code>$email_oc = new WC_Email_Customer_Completed_Order();\n$email_oc-&gt;trigger($order_id);\n</code></pre>\n" }, { "answer_id": 391744, "author": "ewroman", "author_id": 44722, "author_profile": "https://wordpress.stackexchange.com/users/44722", "pm_score": 0, "selected": false, "text": "<p>It can also be used like that;</p>\n<pre><code>WC()-&gt;mailer()-&gt;emails['WC_Email_Customer_Completed_Order']-&gt;trigger( $order_id );\n</code></pre>\n" } ]
2015/04/18
[ "https://wordpress.stackexchange.com/questions/184637", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45404/" ]
I want to be able to trigger the WooCommerce order complete email at a different stage in the WooCommerce checkout process. So I've disabled WooCommerce order complete email from the backend and am now looking for a line of code that will trigger the email at the point that I want. I've done a bit of research and I've found how to *remove* the order complete email but not how to trigger it manually. Any tips? Thanks!
You can try this ``` $mailer = WC()->mailer(); $mails = $mailer->get_emails(); if ( ! empty( $mails ) ) { foreach ( $mails as $mail ) { if ( $mail->id == 'customer_completed_order' ) { $mail->trigger( $order->id ); } } } ```
184,646
<p>So I have the following code:</p> <pre><code> &lt;span class="delete"&gt;&lt;a onclick="return confirm('Are you sure?');" href="&lt;?php echo wp_nonce_url( add_query_arg( array( 'action' =&gt; 'my-delete-product', 'product_id' =&gt; $post-&gt;ID ), my_get_navigation_url('products') ), 'my-delete-product' ); ?&gt;"&gt;&lt;?php _e( '삭제', 'my' ); ?&gt;&lt;/a&gt; | &lt;/span&gt; </code></pre> <p>It is a simple button.</p> <p>I want to make this into a shortcode so that I can use it anywhere where appropriate.</p> <p>Any suggestions?</p> <p>Thanks. </p>
[ { "answer_id": 184639, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 5, "selected": true, "text": "<p>You can try this</p>\n\n<pre><code>$mailer = WC()-&gt;mailer();\n$mails = $mailer-&gt;get_emails();\nif ( ! empty( $mails ) ) {\n foreach ( $mails as $mail ) {\n if ( $mail-&gt;id == 'customer_completed_order' ) {\n $mail-&gt;trigger( $order-&gt;id );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 314657, "author": "Karthik Thayyil", "author_id": 129405, "author_profile": "https://wordpress.stackexchange.com/users/129405", "pm_score": 3, "selected": false, "text": "<p>Rather than looping or reusing the same object as suggested by @Sumit.\nYou can initiate a new object and then call the trigger. </p>\n\n<pre><code>$email_oc = new WC_Email_Customer_Completed_Order();\n$email_oc-&gt;trigger($order_id);\n</code></pre>\n" }, { "answer_id": 391744, "author": "ewroman", "author_id": 44722, "author_profile": "https://wordpress.stackexchange.com/users/44722", "pm_score": 0, "selected": false, "text": "<p>It can also be used like that;</p>\n<pre><code>WC()-&gt;mailer()-&gt;emails['WC_Email_Customer_Completed_Order']-&gt;trigger( $order_id );\n</code></pre>\n" } ]
2015/04/19
[ "https://wordpress.stackexchange.com/questions/184646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So I have the following code: ``` <span class="delete"><a onclick="return confirm('Are you sure?');" href="<?php echo wp_nonce_url( add_query_arg( array( 'action' => 'my-delete-product', 'product_id' => $post->ID ), my_get_navigation_url('products') ), 'my-delete-product' ); ?>"><?php _e( '삭제', 'my' ); ?></a> | </span> ``` It is a simple button. I want to make this into a shortcode so that I can use it anywhere where appropriate. Any suggestions? Thanks.
You can try this ``` $mailer = WC()->mailer(); $mails = $mailer->get_emails(); if ( ! empty( $mails ) ) { foreach ( $mails as $mail ) { if ( $mail->id == 'customer_completed_order' ) { $mail->trigger( $order->id ); } } } ```
184,674
<p>I want to integrate a public API to a plugin that I develop.</p> <p>The usual way other plugins integrate APIs is to define some functions that can be called by any theme or plugin.</p> <p>However, I think this is a bad idea since it will cause errors when my API plugin is not active and I came up with the idea of using filters and actions for the API. Much like this:</p> <pre><code>// Get some user specific data from my plugin: $data = false; if ( apply_filters( 'mp:is-active' ) ) { $data = apply_filters( 'mp:get-user-data' ); } // Add a private notification for a single user: do_action( 'mp:send-notification', $user_id, $message ); </code></pre> <p>The question is: </p> <p>I have never seen this kind of API in other plugins yet, so is there a good reason not to use it (e.g. bad performance, etc)</p> <p>Or do you think this is a good way to go?</p>
[ { "answer_id": 184680, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": true, "text": "<p>Surely this approach has some benefits, but has also some issues.</p>\n\n<h2>It's not really easy to use</h2>\n\n<p>If the target of your plugin are WordPress developers, they will be very familiar with plugin API, but <em>end users</em> are not.</p>\n\n<p>For a non-developer, something like:</p>\n\n<pre><code>$data = give_me_the_data();\n</code></pre>\n\n<p>It's easier to understand, remember and type than:</p>\n\n<pre><code>$data = apply_filters( 'give_me_the_data' );\n</code></pre>\n\n<p>If you look at some of the questions on this site, you can understand how much confusion there is regarding action and filters in WordPress among newbie and non developers.</p>\n\n<h2>The \"typo\" issue</h2>\n\n<p>As a person that makes a lot of typos, I know that they are frustrating. If you write a function with a typo, it throws an error and the user immediately recognizes the problem. A typo in an action name will make the API fail but it's pretty hard to recognize.</p>\n\n<p>As example:</p>\n\n<pre><code>$data = apply_filters('mp:get-user-data'); // works\n\n$data = apply_filters('mo:get-user-data'); // does not work, hard to find why\n\n$data = mp_get_user_data(); // works\n\n$data = mo_get_user_data(); // does not work and throws an error, immediately found\n</code></pre>\n\n<h2>The global hell</h2>\n\n<p>Actions and filters are just global variables. If you use them to build your API, your code can be f***ed up by any single other line of code present in the system.</p>\n\n<p>It means that a bug in any who-knows-which plugin can make your plugin fail for no apparent reason. And the reason is that is not your plugin to fail.</p>\n\n<p>Example:</p>\n\n<pre><code>do_action( 'mp:send-notification', $user_id, $message );\n\n// somewhere else\nadd_action( 'all', 'do_something_bad_that_makes_your_plugin_fail');\n</code></pre>\n\n<p>Moreover, anyone can use those hooks and even if it may bring a lot of flexibility to your API, it also introduces a lot of complexity.</p>\n\n<p>For example, if you use objects as arguments, being objects passed by reference, it's possible they are modified before your callback runs.</p>\n\n<h2>Conclusion</h2>\n\n<p>These are all the reasons that come now into my mind, but maybe there are other reasons if this approach is not widely used.</p>\n\n<p>For me, I would not use this approach, especially for the last point, but I can not say it is absolutely wrong in WordPress context.</p>\n\n<p>So I don't want to strongly discourage you in using it, just suggesting to consider all the issues in advance, because once you publicly release an API, it's very hard to switch.</p>\n" }, { "answer_id": 184683, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": false, "text": "<p>Both approaches are not mutually exclusive. As @gmazzap said, don’t create a callback hell. </p>\n\n<p>But you can provide an initial hook, so other developers don’t have to rely on the rather slow <code>function_exists()</code> checks.</p>\n\n<h2>Example</h2>\n\n<p>In your plugin, provide a hook that other developers can use to call your classes and functions safely.</p>\n\n<pre><code>add_action( 'wp_loaded', [new Your_Plugin_Bootstrap, 'setup' ], 0 );\n\nclass Your_Plugin_Bootstrap {\n\n public function setup() {\n\n // set up your data and the auto-loader, then:\n do_action( 'your_plugin_loaded' );\n }\n}\n</code></pre>\n\n<p>Now a third-party developer can use that hook and proceed with \"normal\" PHP.</p>\n\n<pre><code>add_action( 'your_plugin_loaded', function() {\n\n // safely use your plugin's classes here.\n});\n</code></pre>\n\n<p>We <a href=\"http://make.marketpress.com/multilingualpress/2014/10/a-basic-plugin-for-multilingualpress/\" rel=\"nofollow noreferrer\" title=\"A basic plugin for MultilingualPress\">do that in MultilingualPress</a>, and the feedback from other developers was very good so far. It is easy to understand, and you have to learn just one hook.</p>\n\n<p>See also: <a href=\"https://wordpress.stackexchange.com/a/98783/73\">How to create an API for my plugin?</a></p>\n" } ]
2015/04/19
[ "https://wordpress.stackexchange.com/questions/184674", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31140/" ]
I want to integrate a public API to a plugin that I develop. The usual way other plugins integrate APIs is to define some functions that can be called by any theme or plugin. However, I think this is a bad idea since it will cause errors when my API plugin is not active and I came up with the idea of using filters and actions for the API. Much like this: ``` // Get some user specific data from my plugin: $data = false; if ( apply_filters( 'mp:is-active' ) ) { $data = apply_filters( 'mp:get-user-data' ); } // Add a private notification for a single user: do_action( 'mp:send-notification', $user_id, $message ); ``` The question is: I have never seen this kind of API in other plugins yet, so is there a good reason not to use it (e.g. bad performance, etc) Or do you think this is a good way to go?
Surely this approach has some benefits, but has also some issues. It's not really easy to use --------------------------- If the target of your plugin are WordPress developers, they will be very familiar with plugin API, but *end users* are not. For a non-developer, something like: ``` $data = give_me_the_data(); ``` It's easier to understand, remember and type than: ``` $data = apply_filters( 'give_me_the_data' ); ``` If you look at some of the questions on this site, you can understand how much confusion there is regarding action and filters in WordPress among newbie and non developers. The "typo" issue ---------------- As a person that makes a lot of typos, I know that they are frustrating. If you write a function with a typo, it throws an error and the user immediately recognizes the problem. A typo in an action name will make the API fail but it's pretty hard to recognize. As example: ``` $data = apply_filters('mp:get-user-data'); // works $data = apply_filters('mo:get-user-data'); // does not work, hard to find why $data = mp_get_user_data(); // works $data = mo_get_user_data(); // does not work and throws an error, immediately found ``` The global hell --------------- Actions and filters are just global variables. If you use them to build your API, your code can be f\*\*\*ed up by any single other line of code present in the system. It means that a bug in any who-knows-which plugin can make your plugin fail for no apparent reason. And the reason is that is not your plugin to fail. Example: ``` do_action( 'mp:send-notification', $user_id, $message ); // somewhere else add_action( 'all', 'do_something_bad_that_makes_your_plugin_fail'); ``` Moreover, anyone can use those hooks and even if it may bring a lot of flexibility to your API, it also introduces a lot of complexity. For example, if you use objects as arguments, being objects passed by reference, it's possible they are modified before your callback runs. Conclusion ---------- These are all the reasons that come now into my mind, but maybe there are other reasons if this approach is not widely used. For me, I would not use this approach, especially for the last point, but I can not say it is absolutely wrong in WordPress context. So I don't want to strongly discourage you in using it, just suggesting to consider all the issues in advance, because once you publicly release an API, it's very hard to switch.
184,689
<p>I'm not sure what this feature is called, but I've seen examples of this before. Lets say, on my site I want additional collections of things (besides blog posts) that have their own sections in the admin area.</p> <p>For example, I have:</p> <ul> <li>a list of events</li> <li>a list of products</li> <li>a list of testimonials</li> </ul> <p>...and they each need their own page to list them.</p> <p>How does this work in WordPress and how can I create my own?</p>
[ { "answer_id": 185589, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>These are called <strong>custom post types</strong>. There are several ways to create new post type, using a plugin or creating yourself.</p>\n\n<ul>\n<li>If you prefer using a plugin, try this- <a href=\"https://wordpress.org/plugins/custom-post-type-ui/\" rel=\"nofollow\">https://wordpress.org/plugins/custom-post-type-ui/</a></li>\n<li>If you want to create them yourself without any plugins, you need to add some codes to <code>functions.php</code> file in your theme. This is a simple example:</li>\n</ul>\n\n\n\n<pre><code>function codex_custom_init() {\n $args = array(\n 'public' =&gt; true,\n 'label' =&gt; 'Books'\n );\n register_post_type( 'book', $args );\n}\nadd_action( 'init', 'codex_custom_init' );\n</code></pre>\n\n<p>This will add a new type of content(post) called Book.</p>\n\n<p>See codex page for details -<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n" }, { "answer_id": 185591, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 5, "selected": true, "text": "<p>I believe what you're referring to is called <strong>\"Post Types\"</strong>. By default, WordPress has a complete post types you're already familiar with - <code>post</code> ( news / blog ), <code>page</code> ( Pages ), <code>attachment</code> ( Media ), <code>revision</code> ( Page / Post Revisions ). You can read up on the full list of built in post types on <a href=\"https://codex.wordpress.org/Post_Types\">The Codex - Post Types</a>. </p>\n\n<p>If you want to register a <em>new</em> Custom Post Type ( CPT ) you can do pretty easily with some PHP knowledge. Let's go through and create our own post type called \"Products\".</p>\n\n<p><strong>Step One</strong> - Connect to FTP - you <strong>do not</strong> want to do this using <code>Appearance -&gt; Editor</code>. </p>\n\n<p><strong>Step Two</strong> - Locate your theme, if you're using a child theme open that up and locate the <code>functions.php</code> file. Open the file in <a href=\"http://notepad-plus-plus.org/\">Notepad++</a> or your editor of choice.</p>\n\n<p><strong>Step Three</strong> - Register Your Post Type</p>\n\n<p>Toward the top of your <code>functions.php</code> file we're going to <em>hook</em> into WordPress <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\"><code>init</code></a> and use a built-in WordPress function cleverly called: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\"><code>register_post_type</code></a>. I <em>highly</em> suggest you read these codex links as I will not explain each point but instead give a brief description.</p>\n\n<pre><code>/** Create Post Type **/\nfunction cpt_init() {\n\n // Products Custom Post Type\n register_post_type( 'cpt_products', array( // Internal name `cpt_products` - this is what we test against in queries\n 'labels' =&gt; array( // An array of Administrative labels\n 'name' =&gt; __( 'Products' ),\n 'singular_name' =&gt; __( 'Product' ),\n 'all_items' =&gt; __( 'View Products' ),\n 'add_new' =&gt; __( 'New Product' ),\n 'add_new_item' =&gt; __( 'New Product' ),\n 'edit_item' =&gt; __( 'Edit Product' ),\n 'view_item' =&gt; __( 'View Product' ),\n 'search_items' =&gt; __( 'Search Products' ),\n 'no_found' =&gt; __( 'No Products Found' ),\n 'not_found_in_trash' =&gt; __( 'No Products in Trash' )\n ),\n 'public' =&gt; true, // Whether it will be publically available or only in the admin panel\n 'publicly_queryable'=&gt; true, // \" \"\n 'show_ui' =&gt; true, // Whether we want this post type to show up in the admin panel\n 'show_in_nav_menus' =&gt; false, // If we want Products to show up in the `Appearance -&gt; Menu`\n 'capability_type' =&gt; 'page', // Mostly used for user capability\n 'hierarchical' =&gt; false, // If you will allow products to have child products / assigned a parent\n 'rewrite' =&gt; array( 'slug' =&gt; 'product', 'with_front' =&gt; false ), // This is going to be what the single post will be located at `/product/product-name/`\n 'menu_icon' =&gt; 'dashicons-cart', // https://developer.wordpress.org/resource/dashicons/#welcome-widgets-menus\n 'menu_position' =&gt; 5, // Where you want it to show up in the admin panel\n 'supports' =&gt; array( 'title', 'editor', 'page-attributes', 'revisions' ) // What is actually shown when a new product is added - admin panel\n ) );\n}\nadd_action( 'init', 'cpt_init' );\n</code></pre>\n\n<p><strong>Step Four</strong> - Upload <code>functions.php</code> - an important note here is to also <strong>flush permalinks</strong> which is as easy as going to <code>Settings -&gt; Permalinks</code> and click \"Save\" button at the bottom of the page.</p>\n\n<hr>\n\n<p>Similar to creating a post type, if you want to create <em>Categories</em> ( similar to Post Categories ) you can do so using the <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\"><code>register_taxonomy</code></a> function. Follow the steps as above until Step 3.</p>\n\n<p><strong>Step 3</strong> - Register Taxonomy</p>\n\n<p>The first two parameters are important to link the taxonomy to the post type. The next important part is the <code>hierarchical</code> parameter - this will be the difference between <a href=\"https://codex.wordpress.org/Posts_Tags_Screen\"><code>post_tags</code></a> ( false ) and <a href=\"https://codex.wordpress.org/Posts_Categories_Screen\"><code>categories</code></a> ( true ). We will make this taxonomy hierarchical which is similar to post categories.</p>\n\n<pre><code>/** Add Custom Taxonomy **/\nfunction tax_init() {\n // Product Categories\n register_taxonomy( \n 'tax_products', // Taxonomy slug\n 'cpt_products', // What post type we're assigning the taxonomy to.\n array( // Array of Arguments\n 'labels' =&gt; array( // User Friendly Labels\n 'name' =&gt; __( 'Product Categories' ),\n 'singular_name' =&gt; __( 'Product Category' ),\n 'search_items' =&gt; __( 'Search Product Categories' ),\n 'all_items' =&gt; __( 'All Product Categories' ),\n 'parent_item' =&gt; __( 'Parent Product Category' ),\n 'parent_item_colon' =&gt; __( 'Parent Product Category:' ),\n 'edit_item' =&gt; __( 'Edit Product Category' ), \n 'update_item' =&gt; __( 'Update Product Category' ),\n 'add_new_item' =&gt; __( 'Add New Product Category' ),\n 'new_item_name' =&gt; __( 'New Product Category' ),\n 'menu_name' =&gt; __( 'Product Categories' )\n ),\n 'public' =&gt; true, // Whether it will be public or only used in the admin panel\n 'hierarchical' =&gt; true, // The differnce between *Tags* and *Categories*\n 'show_in_nav_menus' =&gt; true, // To show up in `Appearance -&gt; Menus` or not.\n 'show_admin_column' =&gt; true, // If we want an column next to the title when listing our products\n 'rewrite' =&gt; array( 'slug' =&gt; 'products/category', 'with_front' =&gt; false, 'hierarchical' =&gt; true ) // Similar to post type, where to find the categories `products/category/category-1/`\n ) \n );\n}\nadd_action( 'init', 'tax_init');\n</code></pre>\n" } ]
2015/04/19
[ "https://wordpress.stackexchange.com/questions/184689", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60152/" ]
I'm not sure what this feature is called, but I've seen examples of this before. Lets say, on my site I want additional collections of things (besides blog posts) that have their own sections in the admin area. For example, I have: * a list of events * a list of products * a list of testimonials ...and they each need their own page to list them. How does this work in WordPress and how can I create my own?
I believe what you're referring to is called **"Post Types"**. By default, WordPress has a complete post types you're already familiar with - `post` ( news / blog ), `page` ( Pages ), `attachment` ( Media ), `revision` ( Page / Post Revisions ). You can read up on the full list of built in post types on [The Codex - Post Types](https://codex.wordpress.org/Post_Types). If you want to register a *new* Custom Post Type ( CPT ) you can do pretty easily with some PHP knowledge. Let's go through and create our own post type called "Products". **Step One** - Connect to FTP - you **do not** want to do this using `Appearance -> Editor`. **Step Two** - Locate your theme, if you're using a child theme open that up and locate the `functions.php` file. Open the file in [Notepad++](http://notepad-plus-plus.org/) or your editor of choice. **Step Three** - Register Your Post Type Toward the top of your `functions.php` file we're going to *hook* into WordPress [`init`](https://codex.wordpress.org/Plugin_API/Action_Reference/init) and use a built-in WordPress function cleverly called: [`register_post_type`](https://codex.wordpress.org/Function_Reference/register_post_type). I *highly* suggest you read these codex links as I will not explain each point but instead give a brief description. ``` /** Create Post Type **/ function cpt_init() { // Products Custom Post Type register_post_type( 'cpt_products', array( // Internal name `cpt_products` - this is what we test against in queries 'labels' => array( // An array of Administrative labels 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ), 'all_items' => __( 'View Products' ), 'add_new' => __( 'New Product' ), 'add_new_item' => __( 'New Product' ), 'edit_item' => __( 'Edit Product' ), 'view_item' => __( 'View Product' ), 'search_items' => __( 'Search Products' ), 'no_found' => __( 'No Products Found' ), 'not_found_in_trash' => __( 'No Products in Trash' ) ), 'public' => true, // Whether it will be publically available or only in the admin panel 'publicly_queryable'=> true, // " " 'show_ui' => true, // Whether we want this post type to show up in the admin panel 'show_in_nav_menus' => false, // If we want Products to show up in the `Appearance -> Menu` 'capability_type' => 'page', // Mostly used for user capability 'hierarchical' => false, // If you will allow products to have child products / assigned a parent 'rewrite' => array( 'slug' => 'product', 'with_front' => false ), // This is going to be what the single post will be located at `/product/product-name/` 'menu_icon' => 'dashicons-cart', // https://developer.wordpress.org/resource/dashicons/#welcome-widgets-menus 'menu_position' => 5, // Where you want it to show up in the admin panel 'supports' => array( 'title', 'editor', 'page-attributes', 'revisions' ) // What is actually shown when a new product is added - admin panel ) ); } add_action( 'init', 'cpt_init' ); ``` **Step Four** - Upload `functions.php` - an important note here is to also **flush permalinks** which is as easy as going to `Settings -> Permalinks` and click "Save" button at the bottom of the page. --- Similar to creating a post type, if you want to create *Categories* ( similar to Post Categories ) you can do so using the [`register_taxonomy`](https://codex.wordpress.org/Function_Reference/register_taxonomy) function. Follow the steps as above until Step 3. **Step 3** - Register Taxonomy The first two parameters are important to link the taxonomy to the post type. The next important part is the `hierarchical` parameter - this will be the difference between [`post_tags`](https://codex.wordpress.org/Posts_Tags_Screen) ( false ) and [`categories`](https://codex.wordpress.org/Posts_Categories_Screen) ( true ). We will make this taxonomy hierarchical which is similar to post categories. ``` /** Add Custom Taxonomy **/ function tax_init() { // Product Categories register_taxonomy( 'tax_products', // Taxonomy slug 'cpt_products', // What post type we're assigning the taxonomy to. array( // Array of Arguments 'labels' => array( // User Friendly Labels 'name' => __( 'Product Categories' ), 'singular_name' => __( 'Product Category' ), 'search_items' => __( 'Search Product Categories' ), 'all_items' => __( 'All Product Categories' ), 'parent_item' => __( 'Parent Product Category' ), 'parent_item_colon' => __( 'Parent Product Category:' ), 'edit_item' => __( 'Edit Product Category' ), 'update_item' => __( 'Update Product Category' ), 'add_new_item' => __( 'Add New Product Category' ), 'new_item_name' => __( 'New Product Category' ), 'menu_name' => __( 'Product Categories' ) ), 'public' => true, // Whether it will be public or only used in the admin panel 'hierarchical' => true, // The differnce between *Tags* and *Categories* 'show_in_nav_menus' => true, // To show up in `Appearance -> Menus` or not. 'show_admin_column' => true, // If we want an column next to the title when listing our products 'rewrite' => array( 'slug' => 'products/category', 'with_front' => false, 'hierarchical' => true ) // Similar to post type, where to find the categories `products/category/category-1/` ) ); } add_action( 'init', 'tax_init'); ```
184,708
<p>I have a bunch of redirects to sites like sharethis, media6, and some random character urls. Most of these are leading to a blank pixel or each other. I know a lot has to do with facebook and needed resources but how would I find out where these are being loaded from? So I can figure out what plugin is causing them and remove it if its not necessary.The last three are the main problem. But when I search the source I can not find them so it has to be some JS thats loading them. Also is there an easy way maybe at the server level (nginx) to access all these resources from my server through a cache or something? Short of changing the code to load them locally. </p> <pre><code>http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700&amp;subset=latin,latin-ext https://connect.facebook.net/en_US/all.js#xfbml=1 http://www.jscache.com/wejs?wtype=selfserveprop&amp;uniqu2&amp;locationId=1856968&amp;lang=en_US&amp;rating=true&amp;nreviews=5&amp;writereviewlink=true&amp;popIdx=false&amp;iswide=false&amp;border=true http://fonts.googleapis.com/css?family=Lato:300,400,700 https://www.google-analytics.com/analytics.js http://www.tripadvisor.com/WidgetEmbed-selfserveprop?border=true&amp;popIdx=false&amp;iswide=false&amp;locationId=1856968&amp;rating=true&amp;uniqu2=&amp;nreviews=5&amp;lang=en_US&amp;writereviewlink=true http://static.addtoany.com/menu/page.js http://wd-edge.sharethis.com/button/getAllAppDefault.esi?cb=stLight.allDefault&amp;app=all&amp;publisher=ur.00000000-0000-0000-0000-000000000000&amp;domain=chflive.japayton.com http://wd-edge.sharethis.com/button/checkOAuth.esi http://www.google-analytics.com/ga.js http://www.google-analytics.com/r/__utm.gif?utmwv=5.6.4&amp;utms=1&amp;utmn=1610840262&amp;utmhn=static.addtoany.com&amp;utmcs=UTF-8&amp;utmsr=1024x875&amp;utmsc=24-bit&amp;utmul=en-us&amp;utmje=0&amp;utmfl=11.2%20r202&amp;utmdt=A2A&amp;utmhid=1437638512&amp;utmr=http%3A%2F%2Fchflive.japayton.com%2F&amp;utmp=%2Fmenu%2Fsm12.html&amp;utmht=1429399749431&amp;utmac=UA-1244922-8&amp;utmcc=__utma%3D66866668.767249130.1429399749.1429399749.1429399749.1%3B%2B__utmz%3D66866668.1429399749.1.1.utmcsr%3Dchflive.japayton.com%7Cutmccn%3D(referral)%7Cutmcmd%3Dreferral%7Cutmcct%3D%2F%3B&amp;utmjid=1770988977&amp;utmredir=1&amp;utmu=qAAAAAAAAAAAAAAAAAAAAAAE~ http://d.agkn.com/pixel/6644/?che=1429399749&amp;sk=&amp;lr=&amp;py=&amp;cp=&amp;wb= http://map.media6degrees.com/orbserv/hbpix?pixId=23460&amp;pcv=46&amp;cckz=true http://p.nexac.com/e/sr/a-1548/s-3271/s-3271.xgi?rd=Y </code></pre>
[ { "answer_id": 185589, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>These are called <strong>custom post types</strong>. There are several ways to create new post type, using a plugin or creating yourself.</p>\n\n<ul>\n<li>If you prefer using a plugin, try this- <a href=\"https://wordpress.org/plugins/custom-post-type-ui/\" rel=\"nofollow\">https://wordpress.org/plugins/custom-post-type-ui/</a></li>\n<li>If you want to create them yourself without any plugins, you need to add some codes to <code>functions.php</code> file in your theme. This is a simple example:</li>\n</ul>\n\n\n\n<pre><code>function codex_custom_init() {\n $args = array(\n 'public' =&gt; true,\n 'label' =&gt; 'Books'\n );\n register_post_type( 'book', $args );\n}\nadd_action( 'init', 'codex_custom_init' );\n</code></pre>\n\n<p>This will add a new type of content(post) called Book.</p>\n\n<p>See codex page for details -<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n" }, { "answer_id": 185591, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 5, "selected": true, "text": "<p>I believe what you're referring to is called <strong>\"Post Types\"</strong>. By default, WordPress has a complete post types you're already familiar with - <code>post</code> ( news / blog ), <code>page</code> ( Pages ), <code>attachment</code> ( Media ), <code>revision</code> ( Page / Post Revisions ). You can read up on the full list of built in post types on <a href=\"https://codex.wordpress.org/Post_Types\">The Codex - Post Types</a>. </p>\n\n<p>If you want to register a <em>new</em> Custom Post Type ( CPT ) you can do pretty easily with some PHP knowledge. Let's go through and create our own post type called \"Products\".</p>\n\n<p><strong>Step One</strong> - Connect to FTP - you <strong>do not</strong> want to do this using <code>Appearance -&gt; Editor</code>. </p>\n\n<p><strong>Step Two</strong> - Locate your theme, if you're using a child theme open that up and locate the <code>functions.php</code> file. Open the file in <a href=\"http://notepad-plus-plus.org/\">Notepad++</a> or your editor of choice.</p>\n\n<p><strong>Step Three</strong> - Register Your Post Type</p>\n\n<p>Toward the top of your <code>functions.php</code> file we're going to <em>hook</em> into WordPress <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\"><code>init</code></a> and use a built-in WordPress function cleverly called: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\"><code>register_post_type</code></a>. I <em>highly</em> suggest you read these codex links as I will not explain each point but instead give a brief description.</p>\n\n<pre><code>/** Create Post Type **/\nfunction cpt_init() {\n\n // Products Custom Post Type\n register_post_type( 'cpt_products', array( // Internal name `cpt_products` - this is what we test against in queries\n 'labels' =&gt; array( // An array of Administrative labels\n 'name' =&gt; __( 'Products' ),\n 'singular_name' =&gt; __( 'Product' ),\n 'all_items' =&gt; __( 'View Products' ),\n 'add_new' =&gt; __( 'New Product' ),\n 'add_new_item' =&gt; __( 'New Product' ),\n 'edit_item' =&gt; __( 'Edit Product' ),\n 'view_item' =&gt; __( 'View Product' ),\n 'search_items' =&gt; __( 'Search Products' ),\n 'no_found' =&gt; __( 'No Products Found' ),\n 'not_found_in_trash' =&gt; __( 'No Products in Trash' )\n ),\n 'public' =&gt; true, // Whether it will be publically available or only in the admin panel\n 'publicly_queryable'=&gt; true, // \" \"\n 'show_ui' =&gt; true, // Whether we want this post type to show up in the admin panel\n 'show_in_nav_menus' =&gt; false, // If we want Products to show up in the `Appearance -&gt; Menu`\n 'capability_type' =&gt; 'page', // Mostly used for user capability\n 'hierarchical' =&gt; false, // If you will allow products to have child products / assigned a parent\n 'rewrite' =&gt; array( 'slug' =&gt; 'product', 'with_front' =&gt; false ), // This is going to be what the single post will be located at `/product/product-name/`\n 'menu_icon' =&gt; 'dashicons-cart', // https://developer.wordpress.org/resource/dashicons/#welcome-widgets-menus\n 'menu_position' =&gt; 5, // Where you want it to show up in the admin panel\n 'supports' =&gt; array( 'title', 'editor', 'page-attributes', 'revisions' ) // What is actually shown when a new product is added - admin panel\n ) );\n}\nadd_action( 'init', 'cpt_init' );\n</code></pre>\n\n<p><strong>Step Four</strong> - Upload <code>functions.php</code> - an important note here is to also <strong>flush permalinks</strong> which is as easy as going to <code>Settings -&gt; Permalinks</code> and click \"Save\" button at the bottom of the page.</p>\n\n<hr>\n\n<p>Similar to creating a post type, if you want to create <em>Categories</em> ( similar to Post Categories ) you can do so using the <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\"><code>register_taxonomy</code></a> function. Follow the steps as above until Step 3.</p>\n\n<p><strong>Step 3</strong> - Register Taxonomy</p>\n\n<p>The first two parameters are important to link the taxonomy to the post type. The next important part is the <code>hierarchical</code> parameter - this will be the difference between <a href=\"https://codex.wordpress.org/Posts_Tags_Screen\"><code>post_tags</code></a> ( false ) and <a href=\"https://codex.wordpress.org/Posts_Categories_Screen\"><code>categories</code></a> ( true ). We will make this taxonomy hierarchical which is similar to post categories.</p>\n\n<pre><code>/** Add Custom Taxonomy **/\nfunction tax_init() {\n // Product Categories\n register_taxonomy( \n 'tax_products', // Taxonomy slug\n 'cpt_products', // What post type we're assigning the taxonomy to.\n array( // Array of Arguments\n 'labels' =&gt; array( // User Friendly Labels\n 'name' =&gt; __( 'Product Categories' ),\n 'singular_name' =&gt; __( 'Product Category' ),\n 'search_items' =&gt; __( 'Search Product Categories' ),\n 'all_items' =&gt; __( 'All Product Categories' ),\n 'parent_item' =&gt; __( 'Parent Product Category' ),\n 'parent_item_colon' =&gt; __( 'Parent Product Category:' ),\n 'edit_item' =&gt; __( 'Edit Product Category' ), \n 'update_item' =&gt; __( 'Update Product Category' ),\n 'add_new_item' =&gt; __( 'Add New Product Category' ),\n 'new_item_name' =&gt; __( 'New Product Category' ),\n 'menu_name' =&gt; __( 'Product Categories' )\n ),\n 'public' =&gt; true, // Whether it will be public or only used in the admin panel\n 'hierarchical' =&gt; true, // The differnce between *Tags* and *Categories*\n 'show_in_nav_menus' =&gt; true, // To show up in `Appearance -&gt; Menus` or not.\n 'show_admin_column' =&gt; true, // If we want an column next to the title when listing our products\n 'rewrite' =&gt; array( 'slug' =&gt; 'products/category', 'with_front' =&gt; false, 'hierarchical' =&gt; true ) // Similar to post type, where to find the categories `products/category/category-1/`\n ) \n );\n}\nadd_action( 'init', 'tax_init');\n</code></pre>\n" } ]
2015/04/19
[ "https://wordpress.stackexchange.com/questions/184708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70863/" ]
I have a bunch of redirects to sites like sharethis, media6, and some random character urls. Most of these are leading to a blank pixel or each other. I know a lot has to do with facebook and needed resources but how would I find out where these are being loaded from? So I can figure out what plugin is causing them and remove it if its not necessary.The last three are the main problem. But when I search the source I can not find them so it has to be some JS thats loading them. Also is there an easy way maybe at the server level (nginx) to access all these resources from my server through a cache or something? Short of changing the code to load them locally. ``` http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700&subset=latin,latin-ext https://connect.facebook.net/en_US/all.js#xfbml=1 http://www.jscache.com/wejs?wtype=selfserveprop&uniqu2&locationId=1856968&lang=en_US&rating=true&nreviews=5&writereviewlink=true&popIdx=false&iswide=false&border=true http://fonts.googleapis.com/css?family=Lato:300,400,700 https://www.google-analytics.com/analytics.js http://www.tripadvisor.com/WidgetEmbed-selfserveprop?border=true&popIdx=false&iswide=false&locationId=1856968&rating=true&uniqu2=&nreviews=5&lang=en_US&writereviewlink=true http://static.addtoany.com/menu/page.js http://wd-edge.sharethis.com/button/getAllAppDefault.esi?cb=stLight.allDefault&app=all&publisher=ur.00000000-0000-0000-0000-000000000000&domain=chflive.japayton.com http://wd-edge.sharethis.com/button/checkOAuth.esi http://www.google-analytics.com/ga.js http://www.google-analytics.com/r/__utm.gif?utmwv=5.6.4&utms=1&utmn=1610840262&utmhn=static.addtoany.com&utmcs=UTF-8&utmsr=1024x875&utmsc=24-bit&utmul=en-us&utmje=0&utmfl=11.2%20r202&utmdt=A2A&utmhid=1437638512&utmr=http%3A%2F%2Fchflive.japayton.com%2F&utmp=%2Fmenu%2Fsm12.html&utmht=1429399749431&utmac=UA-1244922-8&utmcc=__utma%3D66866668.767249130.1429399749.1429399749.1429399749.1%3B%2B__utmz%3D66866668.1429399749.1.1.utmcsr%3Dchflive.japayton.com%7Cutmccn%3D(referral)%7Cutmcmd%3Dreferral%7Cutmcct%3D%2F%3B&utmjid=1770988977&utmredir=1&utmu=qAAAAAAAAAAAAAAAAAAAAAAE~ http://d.agkn.com/pixel/6644/?che=1429399749&sk=&lr=&py=&cp=&wb= http://map.media6degrees.com/orbserv/hbpix?pixId=23460&pcv=46&cckz=true http://p.nexac.com/e/sr/a-1548/s-3271/s-3271.xgi?rd=Y ```
I believe what you're referring to is called **"Post Types"**. By default, WordPress has a complete post types you're already familiar with - `post` ( news / blog ), `page` ( Pages ), `attachment` ( Media ), `revision` ( Page / Post Revisions ). You can read up on the full list of built in post types on [The Codex - Post Types](https://codex.wordpress.org/Post_Types). If you want to register a *new* Custom Post Type ( CPT ) you can do pretty easily with some PHP knowledge. Let's go through and create our own post type called "Products". **Step One** - Connect to FTP - you **do not** want to do this using `Appearance -> Editor`. **Step Two** - Locate your theme, if you're using a child theme open that up and locate the `functions.php` file. Open the file in [Notepad++](http://notepad-plus-plus.org/) or your editor of choice. **Step Three** - Register Your Post Type Toward the top of your `functions.php` file we're going to *hook* into WordPress [`init`](https://codex.wordpress.org/Plugin_API/Action_Reference/init) and use a built-in WordPress function cleverly called: [`register_post_type`](https://codex.wordpress.org/Function_Reference/register_post_type). I *highly* suggest you read these codex links as I will not explain each point but instead give a brief description. ``` /** Create Post Type **/ function cpt_init() { // Products Custom Post Type register_post_type( 'cpt_products', array( // Internal name `cpt_products` - this is what we test against in queries 'labels' => array( // An array of Administrative labels 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ), 'all_items' => __( 'View Products' ), 'add_new' => __( 'New Product' ), 'add_new_item' => __( 'New Product' ), 'edit_item' => __( 'Edit Product' ), 'view_item' => __( 'View Product' ), 'search_items' => __( 'Search Products' ), 'no_found' => __( 'No Products Found' ), 'not_found_in_trash' => __( 'No Products in Trash' ) ), 'public' => true, // Whether it will be publically available or only in the admin panel 'publicly_queryable'=> true, // " " 'show_ui' => true, // Whether we want this post type to show up in the admin panel 'show_in_nav_menus' => false, // If we want Products to show up in the `Appearance -> Menu` 'capability_type' => 'page', // Mostly used for user capability 'hierarchical' => false, // If you will allow products to have child products / assigned a parent 'rewrite' => array( 'slug' => 'product', 'with_front' => false ), // This is going to be what the single post will be located at `/product/product-name/` 'menu_icon' => 'dashicons-cart', // https://developer.wordpress.org/resource/dashicons/#welcome-widgets-menus 'menu_position' => 5, // Where you want it to show up in the admin panel 'supports' => array( 'title', 'editor', 'page-attributes', 'revisions' ) // What is actually shown when a new product is added - admin panel ) ); } add_action( 'init', 'cpt_init' ); ``` **Step Four** - Upload `functions.php` - an important note here is to also **flush permalinks** which is as easy as going to `Settings -> Permalinks` and click "Save" button at the bottom of the page. --- Similar to creating a post type, if you want to create *Categories* ( similar to Post Categories ) you can do so using the [`register_taxonomy`](https://codex.wordpress.org/Function_Reference/register_taxonomy) function. Follow the steps as above until Step 3. **Step 3** - Register Taxonomy The first two parameters are important to link the taxonomy to the post type. The next important part is the `hierarchical` parameter - this will be the difference between [`post_tags`](https://codex.wordpress.org/Posts_Tags_Screen) ( false ) and [`categories`](https://codex.wordpress.org/Posts_Categories_Screen) ( true ). We will make this taxonomy hierarchical which is similar to post categories. ``` /** Add Custom Taxonomy **/ function tax_init() { // Product Categories register_taxonomy( 'tax_products', // Taxonomy slug 'cpt_products', // What post type we're assigning the taxonomy to. array( // Array of Arguments 'labels' => array( // User Friendly Labels 'name' => __( 'Product Categories' ), 'singular_name' => __( 'Product Category' ), 'search_items' => __( 'Search Product Categories' ), 'all_items' => __( 'All Product Categories' ), 'parent_item' => __( 'Parent Product Category' ), 'parent_item_colon' => __( 'Parent Product Category:' ), 'edit_item' => __( 'Edit Product Category' ), 'update_item' => __( 'Update Product Category' ), 'add_new_item' => __( 'Add New Product Category' ), 'new_item_name' => __( 'New Product Category' ), 'menu_name' => __( 'Product Categories' ) ), 'public' => true, // Whether it will be public or only used in the admin panel 'hierarchical' => true, // The differnce between *Tags* and *Categories* 'show_in_nav_menus' => true, // To show up in `Appearance -> Menus` or not. 'show_admin_column' => true, // If we want an column next to the title when listing our products 'rewrite' => array( 'slug' => 'products/category', 'with_front' => false, 'hierarchical' => true ) // Similar to post type, where to find the categories `products/category/category-1/` ) ); } add_action( 'init', 'tax_init'); ```
184,711
<p>Im trying to change the title of a post, but I want to include info from a meta field, the value of which isn't saved to the database until after the posts has already been saved. Other than this one thing, it's working fine as a <code>wp_insert_post_data</code> filter.</p> <pre><code>// add_filter('wp_insert_post_data', 'tr_change_show_title', 99, 2); function tr_change_show_title($data, $postarr) { if('post' != $data['post_type']) { // don't bother if its an auto-draft, as the post title may not have been completed yet, or in the trash if ( !in_array( $data['post_status'], array( 'auto-draft', 'trash' ) )) $child_ID = $postarr['ID']; // Child post id $parent_ID = get_post_meta($child_ID, "_wpcf_belongs_booking_id", true); // parent ID $post_type = $data['post_type']; if ($post_type == 'show' &amp;&amp; get_post_type($parent_ID) == 'booking') { $parent_title = get_the_title($parent_ID); $data['post_title'] = $parent_title; // save the parent title first } if (function_exists('types_render_field')) { //this isn't working as the meta field isn't saved yet $show_time = types_render_field( "show-time", array("post_id"=&gt;"$child_ID", "raw"=&gt;"true") ); if ($show_time){ $data['post_title'] .= ' : ' . $show_time; // Append Show time to title } } $data['post_title'] .= ': show-' . $child_ID; // add the original post id } return $data; } </code></pre> <p>I have read the codex, and this wpse post: <a href="https://wordpress.stackexchange.com/a/54713/13551">https://wordpress.stackexchange.com/a/54713/13551</a> <a href="https://codex.wordpress.org/Function_Reference/wp_update_post" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/wp_update_post</a></p> <p>What I understand is that a infinite loop is a risk. To avoid this, we unhook and then rehook the <code>save_post</code> before and after the meat of our work. Ive come up with the following, but dont quite understand why Im still running into an infinite loop. </p> <pre><code>add_action( 'save_post', 'tr_save_post_show_title', 99 ); function tr_save_post_show_title($post_ID){ if ( !wp_is_post_revision( $post_ID ) ) { // do nothing if a revision // Prevent infinite loop remove_action('save_post', 'tr_save_post_show_title'); // Add our filter add_filter('wp_insert_post_data', 'tr_change_show_title', 99, 2); write_log(array( 'ID' =&gt; $post_ID)); // Re-save the post this time with filter wp_update_post( array( 'ID' =&gt; $post_ID), true ); // true for error catching // Catch errors if (is_wp_error($post_id)) { $errors = $post_id-&gt;get_error_messages(); foreach ($errors as $error) { write_log($error); } } // re-hook the save_post action add_action('save_post', 'tr_save_post_show_title'); } } </code></pre>
[ { "answer_id": 184739, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>You hook the <code>tr_change_show_title</code> to a filter inside the function itself, that can make a infinite loop. All the stuff removing/adding actions and filters inside the functions should be deleted; instead check if the post data should be updated or not. In your case you should check if the title has the value you desire or not, if not run <code>wp_update_post</code> with the new value:</p>\n\n<pre><code>add_action( 'save_post', 'tr_save_post_show_title', 99, 2 );\nfunction tr_save_post_show_title( $post_ID, $post ){\n\n if ( !wp_is_post_revision( $post_ID ) ) { // do nothing if a revision\n\n $meta = get_post_meta($post_ID, \"your-meta-key\", true );\n\n if( $meta != '' ) {\n\n $desired_title = \"Whatever you want as title\";\n\n // Check the title value to check if it should be modified\n if( $post-&gt;post_title != $desired_title ) {\n\n $post-&gt;post_title = $desired_title;\n wp_update_post( $post, true );\n\n }\n\n }\n\n }\n\n\n}\n</code></pre>\n\n<p>You are worried about running that function after a meta field has been saved/updated. If the meta field is in the form where you are editing the post, you can access to the meta field value like any other meta field. Anyway, if you want to be sure that the meta field has been saved/updated, you can use the <code>updated_{$meta_type}_meta</code> action hook instead of <code>save_post</code>; as advantage, in this action hook you have direct access to current meta value (if any):</p>\n\n<pre><code>add_action( 'updated_post_meta', 'tr_save_post_show_title', 99, 4 );\nfunction tr_save_post_show_title( $meta_id, $object_id, $meta_key, $meta_value ) {\n\n if ( $meta_key == 'the_meta_key_here' &amp;&amp; $meta_value != '' &amp;&amp; $object_id &amp;&amp; ! wp_is_post_revision( $object_id ) ) {\n\n //write_log(array( 'ID' =&gt; $post_id ));\n\n // Get post data\n $post = get_post( $object_id );\n\n if( $post ) {\n $desired_title = 'Combine here the $post-&gt;post_title with $meta_value as you desire.';\n\n // Check the title value to check if it should be modified\n if( $post-&gt;post_title != $desired_title ) {\n\n $post-&gt;post_title = $desired_title;\n wp_update_post( $post );\n\n }\n\n }\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 185066, "author": "orionrush", "author_id": 13551, "author_profile": "https://wordpress.stackexchange.com/users/13551", "pm_score": 0, "selected": false, "text": "<p>With respect to @cybmeta's contribution, I think that the Types plugin may be throwing us a curveball.</p>\n\n<p>He is correct in that you cannot (at least in this context) add a filter at the point of <code>save_post</code> without creating an infinite loop.</p>\n\n<p>As I was trying to access the value of a meta field, his suggestion for <code>updated_post_meta</code> may be appropriate, but didn't seem to work as the the meta key wasn't available when the hook ran. This again could be an issue with the way Types sets up custom fields.</p>\n\n<p>In the end I have corrected my original approach. Regardless of any influence from Types the following is a working example of changing a post title, at the point of <code>save_post</code>, incorporating the value of a meta field, and preventing an infinite loop. As <code>save_post</code> is the last action in the chain, it should run after all other database changes, and therefore you should feel fairly confident that the <code>WP_Post Object</code> will include any meta field values, and all changes made by any previous filters or actions. If I hadn't wanted current information from my meta fields, a simple filtering via <code>wp_insert_post_data</code> would have sufficed.</p>\n\n<pre><code>add_action('save_post', 'tr_save_post_show_title', 99, 2);\n\nfunction tr_save_post_show_title ($post_ID, $post) {\n if($post-&gt;post_type == 'show' &amp;&amp; !in_array($post -&gt; post_status, array('auto-draft', 'revision', 'trash'))) {\n // don't bother if our CPT post is an auto-draft, a revision or in the trash\n\n $parent_ID = get_post_meta($post_ID, \"_wpcf_belongs_booking_id\", true); // Types relationship\n $current_title = $post -&gt; post_title; // Get current post title saved in DB\n\n $post_showtime = get_post_meta($post_ID, \"wpcf-show-time\", true ); // our custom meta field\n if ($post_showtime == ''){\n $post_showtime = 'To be confirmed';\n }\n\n if ($parent_ID &amp;&amp; get_post_type($parent_ID) == 'booking') { // Check to see if Types a parent relationship has been assigned.\n\n $show_post_title = get_the_title($parent_ID); // get the id of the parent post\n if ($show_post_title != ''){\n $show_post_title .= ': ' . $post_showtime;\n }\n } else if (!$parent_ID){ // when a parent is not assigned\n $show_title = \"Show not yet assigned to venue: \" . $post_showtime;\n }\n if ($current_title != $show_post_title ){ // The current title does not match what we would like it to be\n\n // Prevent infinite loop\n remove_action('save_post', 'tr_save_post_show_title');\n\n // Re-save the post with our new title\n wp_update_post( array( 'ID' =&gt; $post_ID, 'post_title' =&gt; $show_post_title ), false ); // true for error catching\n\n // re-hook the save_post action\n add_action('save_post', 'tr_save_post_show_title', 99, 2);\n\n // Catch any errors with our custom logging function http://goo.gl/P9HbcK\n if (is_wp_error($post_ID)) {\n $errors = $post_id-&gt;get_error_messages();\n foreach ($errors as $error) {\n write_log($error);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Interestingly <a href=\"https://core.trac.wordpress.org/ticket/16176#comment:32\" rel=\"nofollow\"><code>save_post_&lt;post_type&gt;</code></a> which <em>runs just before</em> <code>save_post</code> wasn't getting the most recent values from the meta field either.</p>\n" }, { "answer_id": 233038, "author": "Amarok", "author_id": 98833, "author_profile": "https://wordpress.stackexchange.com/users/98833", "pm_score": 0, "selected": false, "text": "<p>My approach to this problem is to access \"raw\" metadata directly from $_POST[metabox_id] in wp_insert_post_data filter hook. I do admit that this approach is suitable more for my project where posts are generated entirely out of metadata and need to be re-rendered everytime. Tough someone might find it useful.</p>\n" } ]
2015/04/19
[ "https://wordpress.stackexchange.com/questions/184711", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13551/" ]
Im trying to change the title of a post, but I want to include info from a meta field, the value of which isn't saved to the database until after the posts has already been saved. Other than this one thing, it's working fine as a `wp_insert_post_data` filter. ``` // add_filter('wp_insert_post_data', 'tr_change_show_title', 99, 2); function tr_change_show_title($data, $postarr) { if('post' != $data['post_type']) { // don't bother if its an auto-draft, as the post title may not have been completed yet, or in the trash if ( !in_array( $data['post_status'], array( 'auto-draft', 'trash' ) )) $child_ID = $postarr['ID']; // Child post id $parent_ID = get_post_meta($child_ID, "_wpcf_belongs_booking_id", true); // parent ID $post_type = $data['post_type']; if ($post_type == 'show' && get_post_type($parent_ID) == 'booking') { $parent_title = get_the_title($parent_ID); $data['post_title'] = $parent_title; // save the parent title first } if (function_exists('types_render_field')) { //this isn't working as the meta field isn't saved yet $show_time = types_render_field( "show-time", array("post_id"=>"$child_ID", "raw"=>"true") ); if ($show_time){ $data['post_title'] .= ' : ' . $show_time; // Append Show time to title } } $data['post_title'] .= ': show-' . $child_ID; // add the original post id } return $data; } ``` I have read the codex, and this wpse post: <https://wordpress.stackexchange.com/a/54713/13551> <https://codex.wordpress.org/Function_Reference/wp_update_post> What I understand is that a infinite loop is a risk. To avoid this, we unhook and then rehook the `save_post` before and after the meat of our work. Ive come up with the following, but dont quite understand why Im still running into an infinite loop. ``` add_action( 'save_post', 'tr_save_post_show_title', 99 ); function tr_save_post_show_title($post_ID){ if ( !wp_is_post_revision( $post_ID ) ) { // do nothing if a revision // Prevent infinite loop remove_action('save_post', 'tr_save_post_show_title'); // Add our filter add_filter('wp_insert_post_data', 'tr_change_show_title', 99, 2); write_log(array( 'ID' => $post_ID)); // Re-save the post this time with filter wp_update_post( array( 'ID' => $post_ID), true ); // true for error catching // Catch errors if (is_wp_error($post_id)) { $errors = $post_id->get_error_messages(); foreach ($errors as $error) { write_log($error); } } // re-hook the save_post action add_action('save_post', 'tr_save_post_show_title'); } } ```
You hook the `tr_change_show_title` to a filter inside the function itself, that can make a infinite loop. All the stuff removing/adding actions and filters inside the functions should be deleted; instead check if the post data should be updated or not. In your case you should check if the title has the value you desire or not, if not run `wp_update_post` with the new value: ``` add_action( 'save_post', 'tr_save_post_show_title', 99, 2 ); function tr_save_post_show_title( $post_ID, $post ){ if ( !wp_is_post_revision( $post_ID ) ) { // do nothing if a revision $meta = get_post_meta($post_ID, "your-meta-key", true ); if( $meta != '' ) { $desired_title = "Whatever you want as title"; // Check the title value to check if it should be modified if( $post->post_title != $desired_title ) { $post->post_title = $desired_title; wp_update_post( $post, true ); } } } } ``` You are worried about running that function after a meta field has been saved/updated. If the meta field is in the form where you are editing the post, you can access to the meta field value like any other meta field. Anyway, if you want to be sure that the meta field has been saved/updated, you can use the `updated_{$meta_type}_meta` action hook instead of `save_post`; as advantage, in this action hook you have direct access to current meta value (if any): ``` add_action( 'updated_post_meta', 'tr_save_post_show_title', 99, 4 ); function tr_save_post_show_title( $meta_id, $object_id, $meta_key, $meta_value ) { if ( $meta_key == 'the_meta_key_here' && $meta_value != '' && $object_id && ! wp_is_post_revision( $object_id ) ) { //write_log(array( 'ID' => $post_id )); // Get post data $post = get_post( $object_id ); if( $post ) { $desired_title = 'Combine here the $post->post_title with $meta_value as you desire.'; // Check the title value to check if it should be modified if( $post->post_title != $desired_title ) { $post->post_title = $desired_title; wp_update_post( $post ); } } } } ```
184,717
<p>I've set up a select field labeled "asset_type" with two values: "image" and "video". I then have two fields that rely on conditional logic to be displayed. If "image" is selected from the select I show the "image_asset" field, and if "video" is selected from the select I show the "video_asset" field. Reading through the docs and a few other stack questions, I thought I had the logic setup correctly, but for the life of me can not get the content to display. This is what my code looks like:</p> <pre><code>&lt;?php if(get_sub_field('asset_type') == "image") { ?&gt; &lt;div&gt;&lt;?php the_sub_field('image_asset'); ?&gt;&lt;/div&gt; &lt;?php } ?&gt; &lt;?php if(get_sub_field('asset_type') == "video") { ?&gt; &lt;div&gt;&lt;?php the_sub_field('video_asset'); ?&gt;&lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>Any help or advice is greatly appreciated, thanks!</p>
[ { "answer_id": 184720, "author": "pcarvalho", "author_id": 18559, "author_profile": "https://wordpress.stackexchange.com/users/18559", "pm_score": 3, "selected": true, "text": "<p>Just for the sake of closing the question:\n</p>\n\n<pre><code>&lt;?php if(get_sub_field('asset_type') == \"Image\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('image_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n&lt;?php if(get_sub_field('asset_type') == \"Video\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('video_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 278536, "author": "Jake", "author_id": 15883, "author_profile": "https://wordpress.stackexchange.com/users/15883", "pm_score": 0, "selected": false, "text": "<p>If you wanted to use the <code>value</code> of your select field instead of the label in your statement you can do this in ACF:</p>\n\n<pre><code>image : Image\nvideo : Video\n</code></pre>\n\n<p>And this in your template (using the value not the human readable label):</p>\n\n<pre><code>&lt;?php if(get_sub_field('asset_type', '') == \"image\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('image_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n&lt;?php if(get_sub_field('asset_type', '') == \"video\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('video_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>Here <code>get_sub_field('asset_type')</code> has been changed to <code>get_sub_field('asset_type', '')</code></p>\n\n<p>This is a much cleaner option when faced with long labels e.g.</p>\n\n<pre><code>video : First Event Video 1920x1080\n</code></pre>\n\n<p>It also allows you to quickly change the label for the user without having to rework your code.</p>\n" } ]
2015/04/19
[ "https://wordpress.stackexchange.com/questions/184717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70865/" ]
I've set up a select field labeled "asset\_type" with two values: "image" and "video". I then have two fields that rely on conditional logic to be displayed. If "image" is selected from the select I show the "image\_asset" field, and if "video" is selected from the select I show the "video\_asset" field. Reading through the docs and a few other stack questions, I thought I had the logic setup correctly, but for the life of me can not get the content to display. This is what my code looks like: ``` <?php if(get_sub_field('asset_type') == "image") { ?> <div><?php the_sub_field('image_asset'); ?></div> <?php } ?> <?php if(get_sub_field('asset_type') == "video") { ?> <div><?php the_sub_field('video_asset'); ?></div> <?php } ?> ``` Any help or advice is greatly appreciated, thanks!
Just for the sake of closing the question: ``` <?php if(get_sub_field('asset_type') == "Image") { ?> <div><?php the_sub_field('image_asset'); ?></div> <?php } ?> <?php if(get_sub_field('asset_type') == "Video") { ?> <div><?php the_sub_field('video_asset'); ?></div> <?php } ?> ```
184,750
<p>I have added a new image size to a wordpress site with lots of images already present with all their thumbnails.</p> <p>Is there a way to do this: given the post using a specific image, get the attachment image and generate the thumbnail of the new size?</p> <p>I'm looking for a way to do this when needed and only on specific selected posts (it's an image size only used for some posts placed in a "highlighted news" box), so no generic plugins which scan the whole 8gb directory of images, but I'd like to use wordpress tools (basically what it does when you upload an image and all thumbs are generated) instead of doing it all by hand.</p> <p><strong>EDIT</strong></p> <p>I will clarify the scenario so that it's more understandable. I have a simple admin tab where the user enters the URLs of the posts that go in a specific highlight box in the homepage. It all works perfectly, except for the images.</p> <p>What I want to do is this: whenever an URL is entered in that admin panel the image attached to that post must be processed to create a new thumbnail with the recently added image size (since it's a new size, all images predating it do not have the relative thumbnail). This should be an automatic process, otherwise the user has to go to the media library, find the correct image and regenerate its thumbnail, thus losing the simplicity of the original idea.</p> <p>Basically I'm looking for something like:</p> <pre><code>wp_generate_thumb($attachment_id, $image_size); // EXAMPLE, function not really existing </code></pre> <p>which should just accept the attachment id and the string of the image size defined with <code>add_image_size()</code> and take care of everything else.</p> <p>The closest I found is this <code>wp_get_image_editor()</code> which doesn't really seem to do what I need.</p>
[ { "answer_id": 184720, "author": "pcarvalho", "author_id": 18559, "author_profile": "https://wordpress.stackexchange.com/users/18559", "pm_score": 3, "selected": true, "text": "<p>Just for the sake of closing the question:\n</p>\n\n<pre><code>&lt;?php if(get_sub_field('asset_type') == \"Image\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('image_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n&lt;?php if(get_sub_field('asset_type') == \"Video\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('video_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 278536, "author": "Jake", "author_id": 15883, "author_profile": "https://wordpress.stackexchange.com/users/15883", "pm_score": 0, "selected": false, "text": "<p>If you wanted to use the <code>value</code> of your select field instead of the label in your statement you can do this in ACF:</p>\n\n<pre><code>image : Image\nvideo : Video\n</code></pre>\n\n<p>And this in your template (using the value not the human readable label):</p>\n\n<pre><code>&lt;?php if(get_sub_field('asset_type', '') == \"image\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('image_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n&lt;?php if(get_sub_field('asset_type', '') == \"video\") { ?&gt;\n &lt;div&gt;&lt;?php the_sub_field('video_asset'); ?&gt;&lt;/div&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>Here <code>get_sub_field('asset_type')</code> has been changed to <code>get_sub_field('asset_type', '')</code></p>\n\n<p>This is a much cleaner option when faced with long labels e.g.</p>\n\n<pre><code>video : First Event Video 1920x1080\n</code></pre>\n\n<p>It also allows you to quickly change the label for the user without having to rework your code.</p>\n" } ]
2015/04/20
[ "https://wordpress.stackexchange.com/questions/184750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/745/" ]
I have added a new image size to a wordpress site with lots of images already present with all their thumbnails. Is there a way to do this: given the post using a specific image, get the attachment image and generate the thumbnail of the new size? I'm looking for a way to do this when needed and only on specific selected posts (it's an image size only used for some posts placed in a "highlighted news" box), so no generic plugins which scan the whole 8gb directory of images, but I'd like to use wordpress tools (basically what it does when you upload an image and all thumbs are generated) instead of doing it all by hand. **EDIT** I will clarify the scenario so that it's more understandable. I have a simple admin tab where the user enters the URLs of the posts that go in a specific highlight box in the homepage. It all works perfectly, except for the images. What I want to do is this: whenever an URL is entered in that admin panel the image attached to that post must be processed to create a new thumbnail with the recently added image size (since it's a new size, all images predating it do not have the relative thumbnail). This should be an automatic process, otherwise the user has to go to the media library, find the correct image and regenerate its thumbnail, thus losing the simplicity of the original idea. Basically I'm looking for something like: ``` wp_generate_thumb($attachment_id, $image_size); // EXAMPLE, function not really existing ``` which should just accept the attachment id and the string of the image size defined with `add_image_size()` and take care of everything else. The closest I found is this `wp_get_image_editor()` which doesn't really seem to do what I need.
Just for the sake of closing the question: ``` <?php if(get_sub_field('asset_type') == "Image") { ?> <div><?php the_sub_field('image_asset'); ?></div> <?php } ?> <?php if(get_sub_field('asset_type') == "Video") { ?> <div><?php the_sub_field('video_asset'); ?></div> <?php } ?> ```
184,761
<p>I want to cleanup all inactive widgets. I tried following snippet as suggested by this answer <a href="https://wordpress.stackexchange.com/questions/13510/script-to-remove-all-inactive-widgets]">Script to remove all inactive widgets?</a>.</p> <pre><code>$sidebars_widgets = get_option( 'sidebars_widgets' ); $sidebars_widgets['wp_inactive_widgets'] = array(); update_option( 'sidebars_widgets', $sidebars_widgets ); </code></pre> <p>I also tried deleting option <code>sidebars_widgets</code> directly from the options table. </p> <p>But after page is refreshed, old value is restored with all inactive widgets. How can I remove all those inactive widgets at once? Thanks in advance.</p>
[ { "answer_id": 184781, "author": "Behzad", "author_id": 70359, "author_profile": "https://wordpress.stackexchange.com/users/70359", "pm_score": 3, "selected": true, "text": "<p>You should do it with <code>after_setup_theme</code> action: </p>\n\n<pre><code>function remove_inactive_widgets() {\n $sidebars_widgets = get_option( 'sidebars_widgets' );\n $sidebars_widgets['wp_inactive_widgets'] = array();\n update_option( 'sidebars_widgets', $sidebars_widgets );\n}\nadd_action( 'after_setup_theme', 'remove_inactive_widgets' );\n</code></pre>\n" }, { "answer_id": 310417, "author": "Sergio Cabral", "author_id": 111489, "author_profile": "https://wordpress.stackexchange.com/users/111489", "pm_score": 1, "selected": false, "text": "<p>Widget customizations are saved in the widget itself. So in addition to deleting the <code>sidebars_widgets</code>, you have to delete the custom data in the widget as well.</p>\n\n<pre><code>$sidebars_widgets = get_option('sidebars_widgets');\nforeach ($sidebars_widgets as $key =&gt; $value) {\n foreach ($value as $widget_id) {\n $pieces = explode('-', $widget_id);\n $multi_number = array_pop($pieces);\n $id_base = implode('-', $pieces);\n $widget = get_option('widget_' . $id_base);\n\n //Here it deletes the widget customizations that are linked to an id\n unset($widget[$multi_number]);\n\n update_option('widget_' . $id_base, $widget);\n }\n\n //Here it erases all the page's widget. Set ampty array.\n $sidebars_widgets[$key] = array();\n}\nupdate_option('sidebars_widgets', $sidebars_widgets);\n</code></pre>\n" } ]
2015/04/20
[ "https://wordpress.stackexchange.com/questions/184761", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27998/" ]
I want to cleanup all inactive widgets. I tried following snippet as suggested by this answer [Script to remove all inactive widgets?](https://wordpress.stackexchange.com/questions/13510/script-to-remove-all-inactive-widgets]). ``` $sidebars_widgets = get_option( 'sidebars_widgets' ); $sidebars_widgets['wp_inactive_widgets'] = array(); update_option( 'sidebars_widgets', $sidebars_widgets ); ``` I also tried deleting option `sidebars_widgets` directly from the options table. But after page is refreshed, old value is restored with all inactive widgets. How can I remove all those inactive widgets at once? Thanks in advance.
You should do it with `after_setup_theme` action: ``` function remove_inactive_widgets() { $sidebars_widgets = get_option( 'sidebars_widgets' ); $sidebars_widgets['wp_inactive_widgets'] = array(); update_option( 'sidebars_widgets', $sidebars_widgets ); } add_action( 'after_setup_theme', 'remove_inactive_widgets' ); ```
184,780
<p>I am working in wordpress and on pressing the submit button I want the function to return result through ajax and result should be shown as an alert on the screen. But when I press submit nothing shows.</p> <p>Below is my code</p> <p>Ajax code (ajaxinsert.js file)</p> <pre><code>jQuery(document).ready(function(){ //////////////////////////////////////////////////////////// jQuery("#addimage").submit(function (e) { //form is intercepted e.preventDefault(); //serialize the form which contains secretcode var sentdataa = $(this).serializeArray(); //Add the additional param to the data sentdataa.push({ name: 'action', value: 'wp_up' }) //set sentdata as the data to be sent jQuery.post(yess.ajaxurl, sentdataa, function (rez) { //start of funciton alert(rez); return false; } //end of function , 'html'); //set the dataType as json, so you will get the parsed data in the callback }); // submit end here }); </code></pre> <p>HTML Form</p> <pre><code>&lt;form id="addimage" action="" method="post" enctype="multipart/form-data"&gt; &lt;input type="submit" name="upload" style="margin-bottom:15px;"&gt; &lt;/form&gt; </code></pre> <p>PHP code (I have used shortcode on the page for this code and below code is in functions.php file):</p> <pre><code>add_shortcode( 'test', 'addimage' ); function wp_up() { echo "zeeshanaslamdurrani"; exit(); } function addimage(){ add_action( 'wp_ajax_wp_up', 'wp_up' ); add_action( 'wp_ajax_nopriv_wp_up', 'wp_up'); // register &amp; enqueue a javascript file called globals.js wp_register_script( 'globalss', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) ); wp_enqueue_script( 'globalss' ); // use wp_localize_script to pass PHP variables into javascript wp_localize_script( 'globalss', 'yess', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) ); } </code></pre>
[ { "answer_id": 184786, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>Shortcodes are too late to add ajax actions. Additionally, that actions would be added only if shortcode is executed, which is very unlikely to happen on a ajax request. The quickest way to make your code work is to move the <code>add_action</code> outside <code>addimage()</code> function.</p>\n\n<pre><code>add_action( 'wp_ajax_wp_up', 'wp_up' );\nadd_action( 'wp_ajax_nopriv_wp_up', 'wp_up');\nfunction wp_up() { \n echo \"zeeshanaslamdurrani\";\n exit();\n}\n\nadd_shortcode( 'test', 'addimage' );\nfunction addimage(){ \n\n // register &amp; enqueue a javascript file called globals.js\n wp_register_script( 'globalss', get_stylesheet_directory_uri() . \"/js/ajaxinsert.js\", array( 'jquery' ) ); \n wp_enqueue_script( 'globalss' );\n\n // use wp_localize_script to pass PHP variables into javascript\n wp_localize_script( 'globalss', 'yess', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) );\n} \n</code></pre>\n\n<p>Viewing your code, you may be interested also in this question: <a href=\"https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present\">Enqueue Scripts / Styles when shortcode is present</a>.</p>\n" }, { "answer_id": 184793, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>You specify in the jquery API call that you expect to receive as a response a valid html, but the server returns simple text and not html, and this is probably the reason jquery decides that the request failed.</p>\n\n<p>Always look at the actual traffic with browser developer tool to debug whether ajax responses are being sent or not.</p>\n" } ]
2015/04/20
[ "https://wordpress.stackexchange.com/questions/184780", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67938/" ]
I am working in wordpress and on pressing the submit button I want the function to return result through ajax and result should be shown as an alert on the screen. But when I press submit nothing shows. Below is my code Ajax code (ajaxinsert.js file) ``` jQuery(document).ready(function(){ //////////////////////////////////////////////////////////// jQuery("#addimage").submit(function (e) { //form is intercepted e.preventDefault(); //serialize the form which contains secretcode var sentdataa = $(this).serializeArray(); //Add the additional param to the data sentdataa.push({ name: 'action', value: 'wp_up' }) //set sentdata as the data to be sent jQuery.post(yess.ajaxurl, sentdataa, function (rez) { //start of funciton alert(rez); return false; } //end of function , 'html'); //set the dataType as json, so you will get the parsed data in the callback }); // submit end here }); ``` HTML Form ``` <form id="addimage" action="" method="post" enctype="multipart/form-data"> <input type="submit" name="upload" style="margin-bottom:15px;"> </form> ``` PHP code (I have used shortcode on the page for this code and below code is in functions.php file): ``` add_shortcode( 'test', 'addimage' ); function wp_up() { echo "zeeshanaslamdurrani"; exit(); } function addimage(){ add_action( 'wp_ajax_wp_up', 'wp_up' ); add_action( 'wp_ajax_nopriv_wp_up', 'wp_up'); // register & enqueue a javascript file called globals.js wp_register_script( 'globalss', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) ); wp_enqueue_script( 'globalss' ); // use wp_localize_script to pass PHP variables into javascript wp_localize_script( 'globalss', 'yess', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } ```
Shortcodes are too late to add ajax actions. Additionally, that actions would be added only if shortcode is executed, which is very unlikely to happen on a ajax request. The quickest way to make your code work is to move the `add_action` outside `addimage()` function. ``` add_action( 'wp_ajax_wp_up', 'wp_up' ); add_action( 'wp_ajax_nopriv_wp_up', 'wp_up'); function wp_up() { echo "zeeshanaslamdurrani"; exit(); } add_shortcode( 'test', 'addimage' ); function addimage(){ // register & enqueue a javascript file called globals.js wp_register_script( 'globalss', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) ); wp_enqueue_script( 'globalss' ); // use wp_localize_script to pass PHP variables into javascript wp_localize_script( 'globalss', 'yess', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } ``` Viewing your code, you may be interested also in this question: [Enqueue Scripts / Styles when shortcode is present](https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present).
184,785
<p>I'm a total newbie regarding to wp or coding or anything like that but I manage to get things done with a bit of reading. I need a way to convert IPTC extracted keywords that are attached to it's media file to a blog post tags. </p> <p>This is my workflow - I upload an image, image get's attached to a post as featured image, it get's watermarked, it has a link to original size. The image itself has keywords, name, description etc... </p> <p>Everything is almost automated. Upload with media uploader, everything above happens on autopilot, except I need to copy the media file keywords from the media page to that blog post tags. </p> <p>Is there a way I can assign keywords from an image attached to a post to automatically add themselves to that blog post tags? </p>
[ { "answer_id": 184792, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>It depends. To extract the IPTC keywords you will have to find a library or a code sample that you can use as I don't remember anything in wordpress doing that.</p>\n\n<p>As for using the keywords as tags for posts, in theory it is possible. The main issue with it is that images are not attached to posts in a \"hard\" way. A post just includes a url of an image so while an image might be display in the admin as being associated with the post in which it was uploaded, it is not restricted to appear only there. So the tricky part is to decide which images should be used as the source of the tags.</p>\n" }, { "answer_id": 184803, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>WordPres has a function that extract IPTC info from images, that function is <code>wp_read_image_metadata</code>. That function is only available on admin side and, <a href=\"https://codex.wordpress.org/Function_Reference/wp_read_image_metadata\" rel=\"nofollow\">according with the codex</a>, it doesn't extract IPTC keywords. But you can use <a href=\"http://php.net/manual/es/function.iptcparse.php\" rel=\"nofollow\"><code>iptcparse</code> from PHP</a> at your own to extract IPTC keywords and set them as post tags.</p>\n\n<p>In your question, you said that you have already automated the proccess to attach the image as featured image of the post, so you can easily grab the image ID and the post ID during that proccess. Once you have attached the image to the post, store the post ID in <code>$post_ID</code> and the image ID in <code>$image_ID</code> and then you could do something like this:</p>\n\n<pre><code>$image = getimagesize( get_attached_file( $image_ID ), $info );\n\nif( isset( $info['APP13'] ) ) {\n\n $iptc = iptcparse( $info['APP13'] );\n\n // 2#025 is the key in the iptc array for keywords\n if( isset( $iptc['2#025'] ) &amp;&amp; is_array( $iptc['2#025'] ) ) {\n\n // Last param is true to append these tags to existing tags,\n // set it to false to replace existing tags\n // See https://codex.wordpress.org/Function_Reference/wp_set_post_tags\n wp_set_post_tags( $post_ID, $iptc['2#025'], true );\n\n }\n\n}\n</code></pre>\n\n<p>If you set the featured image using <code>set_post_thumbnail</code> function (using the edit post screen to set the featured image use that function as well), you could hook the above code to <code>updated_post_meta</code> action (<code>set_post_thumbnail</code> use metadata to set the featured image):</p>\n\n<pre><code>add_action( 'updated_post_meta', function( $meta_id, $object_id, $meta_key, $_meta_value ) {\n\n // Check that meta \n if( $meta_key == '_thumbnail_id' ) {\n\n $image = getimagesize( get_attached_file( $_meta_value ), $info );\n\n if( isset( $info['APP13'] ) ) {\n\n $iptc = iptcparse( $info['APP13'] );\n\n if( isset( $iptc['2#025'] ) &amp;&amp; is_array( $iptc['2#025'] ) ) {\n\n wp_set_post_tags( $object_id, $iptc['2#025'], true );\n\n }\n\n }\n\n\n }\n\n}, 10, 4 );\n</code></pre>\n\n<p><strong>Note</strong>: code not tested. Just written here. You may need to handle also when the featured image is removed or changed.</p>\n\n<p><strong>Note2</strong>: I've re-read your question and notice that you are (quoting you) \"newbie regarding to wp or coding or anything like that\". Not sure if you will understand the code above and I think the second block of code can be more helpful to you than the first.</p>\n" } ]
2015/04/20
[ "https://wordpress.stackexchange.com/questions/184785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70892/" ]
I'm a total newbie regarding to wp or coding or anything like that but I manage to get things done with a bit of reading. I need a way to convert IPTC extracted keywords that are attached to it's media file to a blog post tags. This is my workflow - I upload an image, image get's attached to a post as featured image, it get's watermarked, it has a link to original size. The image itself has keywords, name, description etc... Everything is almost automated. Upload with media uploader, everything above happens on autopilot, except I need to copy the media file keywords from the media page to that blog post tags. Is there a way I can assign keywords from an image attached to a post to automatically add themselves to that blog post tags?
WordPres has a function that extract IPTC info from images, that function is `wp_read_image_metadata`. That function is only available on admin side and, [according with the codex](https://codex.wordpress.org/Function_Reference/wp_read_image_metadata), it doesn't extract IPTC keywords. But you can use [`iptcparse` from PHP](http://php.net/manual/es/function.iptcparse.php) at your own to extract IPTC keywords and set them as post tags. In your question, you said that you have already automated the proccess to attach the image as featured image of the post, so you can easily grab the image ID and the post ID during that proccess. Once you have attached the image to the post, store the post ID in `$post_ID` and the image ID in `$image_ID` and then you could do something like this: ``` $image = getimagesize( get_attached_file( $image_ID ), $info ); if( isset( $info['APP13'] ) ) { $iptc = iptcparse( $info['APP13'] ); // 2#025 is the key in the iptc array for keywords if( isset( $iptc['2#025'] ) && is_array( $iptc['2#025'] ) ) { // Last param is true to append these tags to existing tags, // set it to false to replace existing tags // See https://codex.wordpress.org/Function_Reference/wp_set_post_tags wp_set_post_tags( $post_ID, $iptc['2#025'], true ); } } ``` If you set the featured image using `set_post_thumbnail` function (using the edit post screen to set the featured image use that function as well), you could hook the above code to `updated_post_meta` action (`set_post_thumbnail` use metadata to set the featured image): ``` add_action( 'updated_post_meta', function( $meta_id, $object_id, $meta_key, $_meta_value ) { // Check that meta if( $meta_key == '_thumbnail_id' ) { $image = getimagesize( get_attached_file( $_meta_value ), $info ); if( isset( $info['APP13'] ) ) { $iptc = iptcparse( $info['APP13'] ); if( isset( $iptc['2#025'] ) && is_array( $iptc['2#025'] ) ) { wp_set_post_tags( $object_id, $iptc['2#025'], true ); } } } }, 10, 4 ); ``` **Note**: code not tested. Just written here. You may need to handle also when the featured image is removed or changed. **Note2**: I've re-read your question and notice that you are (quoting you) "newbie regarding to wp or coding or anything like that". Not sure if you will understand the code above and I think the second block of code can be more helpful to you than the first.
184,798
<p>We are looking to modify the registration so that no email is required (yes we know this will be an issue). We are using the Registration Plus Redux plugin since it has options we are using currently.</p> <p>How can we have it so that when a new user signs up, we only ask for their First Name, Username they choose and password?</p> <p><strong>UPDATE</strong></p> <p>Our servers/system doesn't allow email to be sent (company policy) and we can't store email addresses due to PII policies (we'll be dealing with European countries that doesn't allow for email addresses to be stored since its a Privacy issue). </p> <p>We can only have First name and their password (with Registration Redux, we are creating registration codes they can use, that will appear in their profile, to help with password reset, which will be done through our customer service). No email notifications will be sent out (we have auto-approval on).</p>
[ { "answer_id": 184923, "author": "user42826", "author_id": 42826, "author_profile": "https://wordpress.stackexchange.com/users/42826", "pm_score": -1, "selected": false, "text": "<p>To customize your registration form, follow the instructions outlined here - <a href=\"https://codex.wordpress.org/Customizing_the_Registration_Form\" rel=\"nofollow\" title=\"Customizing the Registration Form\">Customizing the Registration Form</a>. Note that your requirements are unusual so your customization will be more extensive. AFAIK you will need to provide a fake email address per account. You can use javascript in the registration form to fill-in necessary data (e.g. email address).</p>\n" }, { "answer_id": 349971, "author": "Biswas", "author_id": 176424, "author_profile": "https://wordpress.stackexchange.com/users/176424", "pm_score": 1, "selected": false, "text": "<p>Just install a plugin called - <em>Snippets &amp; Activate</em>.\nThan on left panel click <em>Snippets -> Add new</em>.\nType a title of your own &amp; paste below code.\nAfter that click a option there in the bottom \"Run snippet everywhere\" and press Save/Active.\nThat's all you need to do. Enjoy...</p>\n\n<pre><code>add_action('user_profile_update_errors', 'my_user_profile_update_errors', 10, 3);\nfunction my_user_profile_update_errors($errors, $update, $user) {\n $errors-&gt;remove('empty_email');\n}\n\nadd_action('user_new_form', 'my_user_new_form', 10, 1);\nadd_action('show_user_profile', 'my_user_new_form', 10, 1);\nadd_action('edit_user_profile', 'my_user_new_form', 10, 1);\nfunction my_user_new_form($form_type) {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery('#email').closest('tr').removeClass('form-required').find('.description').remove();\n\n &lt;?php if (isset($form_type) &amp;&amp; $form_type === 'add-new-user') : ?&gt;\n jQuery ('#send_user_notification') .removeAttr('checked');\n &lt;?php endif; ?&gt;\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n" } ]
2015/04/20
[ "https://wordpress.stackexchange.com/questions/184798", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70898/" ]
We are looking to modify the registration so that no email is required (yes we know this will be an issue). We are using the Registration Plus Redux plugin since it has options we are using currently. How can we have it so that when a new user signs up, we only ask for their First Name, Username they choose and password? **UPDATE** Our servers/system doesn't allow email to be sent (company policy) and we can't store email addresses due to PII policies (we'll be dealing with European countries that doesn't allow for email addresses to be stored since its a Privacy issue). We can only have First name and their password (with Registration Redux, we are creating registration codes they can use, that will appear in their profile, to help with password reset, which will be done through our customer service). No email notifications will be sent out (we have auto-approval on).
Just install a plugin called - *Snippets & Activate*. Than on left panel click *Snippets -> Add new*. Type a title of your own & paste below code. After that click a option there in the bottom "Run snippet everywhere" and press Save/Active. That's all you need to do. Enjoy... ``` add_action('user_profile_update_errors', 'my_user_profile_update_errors', 10, 3); function my_user_profile_update_errors($errors, $update, $user) { $errors->remove('empty_email'); } add_action('user_new_form', 'my_user_new_form', 10, 1); add_action('show_user_profile', 'my_user_new_form', 10, 1); add_action('edit_user_profile', 'my_user_new_form', 10, 1); function my_user_new_form($form_type) { ?> <script type="text/javascript"> jQuery('#email').closest('tr').removeClass('form-required').find('.description').remove(); <?php if (isset($form_type) && $form_type === 'add-new-user') : ?> jQuery ('#send_user_notification') .removeAttr('checked'); <?php endif; ?> </script> <?php } ```
184,880
<p>I try to get the current post index number and echo the number of this lesson(post)in a series of lessons(category).</p> <p>I'm inside the loop on single.php page</p> <p>my code looks like this:</p> <pre><code>$args = array( 'cat' =&gt; 22, ); $query = new WP_Query( $args ); echo $query-&gt;current_post; echo $query-&gt;post_count; </code></pre> <p>the "$query->post_count" works great and give me the number of the posts that are inside this category, but the "$query->current_post" don't work and give me "-1" all the time in every post...</p> <p>what i'm doing wrong?</p>
[ { "answer_id": 184884, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>What you are seeing is totally expected as you are trying to get the value of <code>$current_post</code> outside the loop. Before and after the loop, the value of <code>$current_post</code> will always be set to <code>-1</code>.</p>\n\n<p>To get the proper value, you need to check <code>$current_post</code> inside the loop, the first post will be <code>0</code> and this will increase by one on every iteration of the loop. </p>\n\n<p>For more info on creating the <code>Post X of Y</code> thing, check out <a href=\"https://wordpress.stackexchange.com/search?q=x+of+y\">these</a> site searches on this issue</p>\n" }, { "answer_id": 184891, "author": "Erez Lieberman", "author_id": 39259, "author_profile": "https://wordpress.stackexchange.com/users/39259", "pm_score": 1, "selected": false, "text": "<p>Thanks, Pieter.</p>\n<p>Based on <a href=\"https://wordpress.stackexchange.com/a/35543/39259\">this answer</a>, I made some changes to work on specific category. Here is my final code:</p>\n<pre><code>&lt;div class=&quot;lessonNumber&quot;&gt;\n &lt;?php \n\n class MY_Post_Numbers {\n\n private $count = 0;\n private $posts = array();\n\n public function display_count() {\n $this-&gt;init(); // prevent unnecessary queries\n $id = get_the_ID();\n echo __('שיעור', 'swgeula') . ' ' . $this-&gt;posts[$id] . ' ' . __('מתוך', 'swgeula') . ' ' . $this-&gt;count;\n }\n\n private function init() {\n if ( $this-&gt;count )\n return;\n $parent_cat = get_the_category()[0];\n $parent_cat_id = $parent_cat-&gt;cat_ID;\n global $wpdb; \n $posts = $wpdb-&gt;get_col( &quot;SELECT ID FROM $wpdb-&gt;posts WHERE post_status = 'publish' AND post_type = 'post' AND ID IN ( SELECT object_id FROM {$wpdb-&gt;term_relationships} WHERE term_taxonomy_id = '&quot; . $parent_cat_id . &quot;' ) ORDER BY post_date &quot; ); \n \n // can add or change order if you want \n $this-&gt;count = count($posts);\n \n\n foreach ( $posts as $key =&gt; $value ) {\n $this-&gt;posts[$value] = $key + 1;\n }\n unset($posts);\n }\n\n }\n\n $GLOBALS['my_post_numbers'] = new MY_Post_Numbers;\n\n function my_post_number() {\n $GLOBALS['my_post_numbers']-&gt;display_count();\n }\n\n my_post_number(); \n\n ?&gt;\n&lt;/div&gt; \n</code></pre>\n" } ]
2015/04/21
[ "https://wordpress.stackexchange.com/questions/184880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39259/" ]
I try to get the current post index number and echo the number of this lesson(post)in a series of lessons(category). I'm inside the loop on single.php page my code looks like this: ``` $args = array( 'cat' => 22, ); $query = new WP_Query( $args ); echo $query->current_post; echo $query->post_count; ``` the "$query->post\_count" works great and give me the number of the posts that are inside this category, but the "$query->current\_post" don't work and give me "-1" all the time in every post... what i'm doing wrong?
What you are seeing is totally expected as you are trying to get the value of `$current_post` outside the loop. Before and after the loop, the value of `$current_post` will always be set to `-1`. To get the proper value, you need to check `$current_post` inside the loop, the first post will be `0` and this will increase by one on every iteration of the loop. For more info on creating the `Post X of Y` thing, check out [these](https://wordpress.stackexchange.com/search?q=x+of+y) site searches on this issue
184,993
<p>I have over 4000 posts. I am trying to query all the posts and get the count of tags each post has and sum up posts count based on number of tags the post has in dashboard. The posts count shows up properly when post_per_page is less than 2000 but beyond 2000 , the query timesout . It just shows '0' for all.</p> <p>Code</p> <pre><code> $args = array( 'posts_per_page' =&gt; 4000, 'post_status' =&gt; 'publish', ); $zerotags = 0; $onetag = 0; $twotags = 0; $morethantwo = 0; $sixtags_plus = 0; $query = new WP_Query( $args ); while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); $posttags = get_the_tags(); $tag_count = 0; foreach($posttags as $tag) { $tag_count++; } if ($tag_count == 0) { $zerotags++; } if ($tag_count == 1) { $onetag++; } if ($tag_count == 2) { $twotags++; } if ($tag_count &gt; 2 &amp;&amp; $tag_count &lt; 6) { $morethantwo++; } if ($tag_count &gt;= 6) { $sixtags_plus++; } endwhile; echo 'Zero Tags : '.$zerotags.'posts'; echo 'One Tag : '.$onetag.'posts'; echo 'Two Tags : '.$twotags.'posts'; echo 'More than 2 and less than 6 : '.$morethantwo.'posts'; echo 'More than 6 tags : '.$sixtags_plus.'posts'; </code></pre> <p>Is there a better approach to query this so that the timeout doesn't occur?</p>
[ { "answer_id": 184996, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>I addressed <a href=\"https://wordpress.stackexchange.com/a/184562/1685\">a similar problem</a> not long ago - it's all in the memory:</p>\n\n<pre><code>$post_ids = get_posts(\n array(\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish',\n 'fields' =&gt; 'ids', // Just grab IDs instead of pulling 1000's of objects into memory\n )\n);\n\nupdate_object_term_cache( $post_ids, 'post' ); // Cache all the post terms in one query, memory should be ok\n\nforeach ( $post_ids as $post_id ) {\n if ( ! $tags = get_object_term_cache( $post_id, 'post_tag' ) ) {\n $zerotags++;\n } else {\n $tag_count = count( $tags );\n\n if ( $tag_count === 1 ) {\n $onetag++;\n } elseif ( $tag_count === 2 ) {\n $twotags++;\n } elseif ( $tag_count &gt;= 6 ) {\n $sixtags_plus++;\n }\n\n if ( $tag_count &gt; 2 &amp;&amp; $tag_count &lt; 6 ) {\n $morethantwo++;\n }\n }\n}\n</code></pre>\n\n<p><strong>Update:</strong> Switched <code>get_the_tags</code> to <code>get_object_term_cache</code> - otherwise we lose all our hard work! (the former hits <code>get_post</code>, which will hit the db on every iteration and chuck the post object into memory - props @Pieter Goosen).</p>\n\n<p><strong>Update 2:</strong> The second argument for <code>update_object_term_cache</code> should be the <em>post</em> type, not the taxonomy.</p>\n" }, { "answer_id": 184997, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<h2>Frequency table - custom SQL query:</h2>\n\n<p>You can try the following custom query for your posts/terms statistics for a given taxonomy, post status and type:</p>\n\n<pre><code>/**\n * Frequency data: Count how many posts have a given number of terms, \n * for a given post type, post status and taxonomy.\n *\n * @param string $taxonomy Taxonomy slug\n * @param string $post_status Post status (draft, publish, ...)\n * @param string $post_type Post type (post, page, ...)\n * @return array Array containing freq. data with 'total' (posts) and 'term' counts\n */\n\nfunction get_post_terms_stats_wpse_184993( \n $taxonomy = 'post_tag', \n $post_status = 'publish', \n $post_type = 'post' \n){\n global $wpdb;\n $sql = \" \n SELECT COUNT( s.terms_per_post ) as total, s.terms_per_post \n FROM ( \n SELECT COUNT( tr.object_id ) terms_per_post, tr.object_id \n FROM {$wpdb-&gt;term_relationships} tr \n LEFT JOIN {$wpdb-&gt;term_taxonomy} tt USING( term_taxonomy_id ) \n LEFT JOIN {$wpdb-&gt;posts} p ON p.ID = tr.object_id \n WHERE tt.taxonomy = '%s' \n AND p.post_status = '%s' \n AND p.post_type = '%s'\n GROUP BY tr.object_id \n ) as s \n GROUP by s.terms_per_post\n ORDER BY total DESC\";\n\n return $wpdb-&gt;get_results( \n $wpdb-&gt;prepare( $sql, $taxonomy, $post_status, $post_type ), \n ARRAY_A \n );\n}\n</code></pre>\n\n<h2>Example on an install with ~10k posts:</h2>\n\n<p>Here's an example for <em>category</em> in <em>published</em> <em>posts</em>:</p>\n\n<pre><code>$stats = get_post_terms_stats_wpse_184993( \n $taxonomy = 'category', \n $post_status = 'publish', \n $post_type = 'post' \n); \n\nprint_r( $stats );\n</code></pre>\n\n<p>with the following output:</p>\n\n<pre><code>Array\n(\n [0] =&gt; Array\n (\n [total] =&gt; 8173\n [terms_per_post] =&gt; 1\n )\n\n [1] =&gt; Array\n (\n [total] =&gt; 948\n [terms_per_post] =&gt; 2\n )\n\n [2] =&gt; Array\n (\n [total] =&gt; 94\n [terms_per_post] =&gt; 3\n )\n\n [3] =&gt; Array\n (\n [total] =&gt; 2\n [terms_per_post] =&gt; 4\n )\n\n [4] =&gt; Array\n (\n [total] =&gt; 1\n [terms_per_post] =&gt; 6\n )\n\n [5] =&gt; Array\n (\n [total] =&gt; 1\n [terms_per_post] =&gt; 8\n )\n\n)\n</code></pre>\n\n<p>We can output it in a HTML table:</p>\n\n<pre><code>foreach( $stats as $row )\n{\n $rows .= sprintf( \n \"&lt;tr&gt;&lt;td&gt;%d&lt;/td&gt;&lt;td&gt;%d&lt;/td&gt;&lt;/tr&gt;\", \n $row['total'], \n $row['terms_per_post'] \n );\n}\nprintf( \"&lt;table&gt;&lt;tr&gt;&lt;th&gt;#Posts&lt;/th&gt;&lt;th&gt;#Terms&lt;/th&gt;&lt;/tr&gt;%s&lt;/table&gt;\", $rows );\n</code></pre>\n\n<p>with the following output:</p>\n\n<p><img src=\"https://i.stack.imgur.com/N6GDV.jpg\" alt=\"stats\"></p>\n\n<p>So here we can see how many posts have a given number of terms, in order. </p>\n\n<p>Currently the SQL query uses temporary and filesort, so there are definitely opportunities to adjust it. On a 10k posts install this took under 0.2s to run on my small VPS. We could for example remove the post table join to make it faster, but then it would be less flexible.</p>\n\n<p>We can also cache the output, for example with the <em>transients</em> API, as mentioned by @Pieter Goosen in his answer.</p>\n" }, { "answer_id": 184998, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>You are hiting the db with a 500 mile per hour hurricane, no wonder your query times out.</p>\n\n<p>Here is an idea or two to speed things up</p>\n\n<ul>\n<li><p>Add <code>'fields' =&gt; 'ids',</code> to your <code>WP_Query</code> arguments. This will speed up your query dramatically. This will only return the post id's, and this is the only thing that you actually need</p></li>\n<li><p>Use <code>wp_get_post_terms()</code> to get the post tags. The third parameter takes an array of arguments, one beign <code>fields</code> which you can also set to just return <code>ids</code> which will also speed up your query as it will also just return tag ID's and not the complete tag object</p></li>\n<li><p>Use transients to save your results and flush them when a new post is published, or when a post is deleted, undeleted or updated. Use <code>transition_post_status</code></p></li>\n</ul>\n\n<h2>EDIT- IDEA TO CODE TRANSITION</h2>\n\n<p>Setup the function to delete the tansient if a new post is published, or when a post is deleted or undeleted or updated</p>\n\n<p>In your functions.php</p>\n\n<pre><code>add_action( 'transition_post_status', function ()\n{\n global $wpdb;\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_tag_list_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_tag_list_%')\" );\n});\n</code></pre>\n\n<p>Get the tag count and add it to a transient</p>\n\n<pre><code>function get_term_post_count( $taxonomy = 'post_tag', $post_type = 'post' )\n{\n if ( false === ( $total_counts = get_transient( 'tag_list_' . md5( $taxonomy . $post_type ) ) ) ) {\n\n if ( !taxonomy_exists( $taxonomy ) )\n return $total_counts = null;\n\n $args = [\n 'nopaging' =&gt; true, //Gets all posts\n 'fields' =&gt; 'ids'\n ];\n $q = new WP_Query( $args );\n\n if ( empty( $q-&gt;posts ) )\n return $total_counts = null;\n\n update_object_term_cache( $q-&gt;posts, $post_type );\n\n foreach ( $q-&gt;posts as $single_post ) {\n\n $tags = get_object_term_cache( $single_post, $taxonomy );\n\n if ( empty( $tags ) ) {\n $no_tags[] = $single_post;\n } else {\n $count = count( $tags );\n if ( $count == 1 ) {\n $one[] = $single_post;\n } elseif ( $count == 2 ) {\n $two[] = $single_post;\n } elseif ( $count &gt;= 3 &amp;&amp; $count &lt;= 6 ) {\n $more_than_two[] = $single_post;\n } elseif ( $count &gt; 6 ) {\n $more_than_six[] = $single_post;\n }\n }\n }\n\n $total_counts = [\n 'none' =&gt; isset( $no_tags ) ? ( (int) count( $no_tags ) ) : 0,\n 'one' =&gt; isset( $one ) ? ( (int) count( $one ) ) : 0,\n 'two' =&gt; isset( $two ) ? ( (int) count( $two ) ) : 0,\n 'more_than_two' =&gt; isset( $more_than_two ) ? ( (int) count( $more_than_two ) ) : 0,\n 'more_than_six' =&gt; isset( $more_than_six ) ? ( (int) count( $more_than_six) ) : 0\n ];\n\n\n set_transient( 'tag_list_' . md5( $taxonomy . $post_type ), $total_counts, 24 * HOUR_IN_SECONDS );\n\n return $total_counts;\n}\n</code></pre>\n\n<p>You can use the function as follows in your template</p>\n\n<pre><code>$q = get_term_post_count();\nif ( $q !== null ) {\n echo 'Zero Tags : '.$q['none'].'posts &lt;/br&gt;'; \n echo 'One Tag : '.$q['one'].'posts &lt;/br&gt;';\n echo 'Two Tags : '.$q['two'].'posts &lt;/br&gt;';\n echo 'More than 2 and less than 6 : '.$q['more_than_two'].'posts &lt;/br&gt;';\n echo 'More than 6 tags : '.$q['more_than_six'].'posts &lt;/br&gt;';\n}\n</code></pre>\n\n<h2>FEW IMPORTANT NOTES</h2>\n\n<ul>\n<li><p>The code above is untested and might be buggy</p></li>\n<li><p>Requires PHP 5.4 +</p></li>\n<li><p>The first parameter is <code>$taxonomy</code>. You can pass any taxonomy to the code, the deafault is <code>post_tag</code>. The second parameter is <code>$post_type</code> which is set to default <code>post</code>. You can pass any post type to the parameter</p></li>\n<li><p>Modify and abuse as you see fit</p></li>\n</ul>\n\n<h2>EDIT 1</h2>\n\n<p>Fixed a couple of minor bugs, the code is now tested and is working </p>\n\n<h2>EDIT 2 - PERFORMANCE TESTING</h2>\n\n<p>---SCRAPPED---</p>\n\n<h2>EDIT 3 thanks to @TheDeadMedic</h2>\n\n<p>I have also learned a bit from @TheDeadMedic about <a href=\"http://wpseek.com/function/update_object_term_cache/\" rel=\"nofollow\"><code>update_object_term_cache</code></a> and <a href=\"http://wpseek.com/function/get_object_term_cache/\" rel=\"nofollow\"><code>get_object_term_cache</code></a> which increases the performance a lot. I have updated ( <em>stole a bit from @TheDeadMedic, upvoted his answer in return :-)</em>) my answer with this info. It does hit the memory a bit, but this problem is partly overcome with the use of transients.</p>\n\n<p>The code now gives me </p>\n\n<blockquote>\n <p>2 queries in 0.09766 seconds.</p>\n</blockquote>\n\n<p>without using transients</p>\n" } ]
2015/04/22
[ "https://wordpress.stackexchange.com/questions/184993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37899/" ]
I have over 4000 posts. I am trying to query all the posts and get the count of tags each post has and sum up posts count based on number of tags the post has in dashboard. The posts count shows up properly when post\_per\_page is less than 2000 but beyond 2000 , the query timesout . It just shows '0' for all. Code ``` $args = array( 'posts_per_page' => 4000, 'post_status' => 'publish', ); $zerotags = 0; $onetag = 0; $twotags = 0; $morethantwo = 0; $sixtags_plus = 0; $query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post(); $posttags = get_the_tags(); $tag_count = 0; foreach($posttags as $tag) { $tag_count++; } if ($tag_count == 0) { $zerotags++; } if ($tag_count == 1) { $onetag++; } if ($tag_count == 2) { $twotags++; } if ($tag_count > 2 && $tag_count < 6) { $morethantwo++; } if ($tag_count >= 6) { $sixtags_plus++; } endwhile; echo 'Zero Tags : '.$zerotags.'posts'; echo 'One Tag : '.$onetag.'posts'; echo 'Two Tags : '.$twotags.'posts'; echo 'More than 2 and less than 6 : '.$morethantwo.'posts'; echo 'More than 6 tags : '.$sixtags_plus.'posts'; ``` Is there a better approach to query this so that the timeout doesn't occur?
I addressed [a similar problem](https://wordpress.stackexchange.com/a/184562/1685) not long ago - it's all in the memory: ``` $post_ids = get_posts( array( 'posts_per_page' => -1, 'post_status' => 'publish', 'fields' => 'ids', // Just grab IDs instead of pulling 1000's of objects into memory ) ); update_object_term_cache( $post_ids, 'post' ); // Cache all the post terms in one query, memory should be ok foreach ( $post_ids as $post_id ) { if ( ! $tags = get_object_term_cache( $post_id, 'post_tag' ) ) { $zerotags++; } else { $tag_count = count( $tags ); if ( $tag_count === 1 ) { $onetag++; } elseif ( $tag_count === 2 ) { $twotags++; } elseif ( $tag_count >= 6 ) { $sixtags_plus++; } if ( $tag_count > 2 && $tag_count < 6 ) { $morethantwo++; } } } ``` **Update:** Switched `get_the_tags` to `get_object_term_cache` - otherwise we lose all our hard work! (the former hits `get_post`, which will hit the db on every iteration and chuck the post object into memory - props @Pieter Goosen). **Update 2:** The second argument for `update_object_term_cache` should be the *post* type, not the taxonomy.
185,004
<p>For a specific section on my website I loop through some categories and get the three latest posts in that categorie and list them. Like so:</p> <pre><code>&lt;?php $categories = get_categories(array('exclude' =&gt; '1, 4, 9, 10, 2899')); ?&gt; &lt;?php foreach ($categories as $category) : ?&gt; &lt;div class="subject"&gt; &lt;h3&gt;&lt;?php echo $category-&gt;cat_name; ?&gt;&lt;/h3&gt; &lt;ul&gt; &lt;?php $args = array( 'cat' =&gt; $category-&gt;cat_ID, 'posts_per_page' =&gt; 3 ); ?&gt; &lt;?php if (false === ( $category_posts_query = get_transient( 'category_posts' ) ) ) { $category_posts_query = new WP_Query($args); set_transient( 'category_posts', $category_posts_query, 36 * HOUR_IN_SECONDS ); } ?&gt; &lt;?php while($category_posts_query-&gt;have_posts()) : ?&gt; &lt;?php $category_posts_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>However, the result is not what is expected: all posts are the same across categories even though the posts don't belong to the different categories: <img src="https://i.stack.imgur.com/yjRiO.png" alt="enter image description here"></p> <p>When I remove the <code>transient</code> for caching, everything works as expted.</p> <pre><code>&lt;?php $categories = get_categories(array('exclude' =&gt; '1, 4, 9, 10, 2899')); ?&gt; &lt;?php foreach ($categories as $category) : ?&gt; &lt;div class="subject"&gt; &lt;h3&gt;&lt;?php echo $category-&gt;cat_name; ?&gt;&lt;/h3&gt; &lt;ul&gt; &lt;?php $args = array( 'cat' =&gt; $category-&gt;cat_ID, 'posts_per_page' =&gt; 3 ); ?&gt; &lt;?php $category_posts_query = new WP_Query($args); ?&gt; &lt;?php while($category_posts_query-&gt;have_posts()) : ?&gt; &lt;?php $category_posts_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>How do I add chacing to this last snippet?</p>
[ { "answer_id": 185010, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 0, "selected": false, "text": "<p>Your category is ID being changed at every loop iteration and you are setting a common transient, which gives the same result every time even if category ID has been changed. </p>\n\n<p>So you need to save transient for every category.</p>\n\n<pre><code>set_transient( 'category_posts_' . $category-&gt;cat_ID, $category_posts_query, 36 * HOUR_IN_SECONDS );\n</code></pre>\n\n<p>Try this solution</p>\n\n<pre><code>&lt;?php $categories = get_categories(array('exclude' =&gt; '1, 4, 9, 10, 2899')); ?&gt;\n\n&lt;?php foreach ($categories as $category) : ?&gt;\n &lt;div class=\"subject\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;cat_name; ?&gt;&lt;/h3&gt;\n &lt;ul&gt;\n &lt;?php $args = array(\n 'cat' =&gt; $category-&gt;cat_ID,\n 'posts_per_page' =&gt; 3\n ); ?&gt;\n &lt;?php if (false === ( $category_posts_query = get_transient( 'category_posts_' . $category-&gt;cat_ID ) ) ) {\n $category_posts_query = new WP_Query($args);\n set_transient( 'category_posts_' . $category-&gt;cat_ID, $category_posts_query, 36 * HOUR_IN_SECONDS );\n }\n ?&gt;\n &lt;?php while($category_posts_query-&gt;have_posts()) : ?&gt;\n &lt;?php $category_posts_query-&gt;the_post(); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n" }, { "answer_id": 185048, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I don't think you need so many transients set, one for each category. You can only use one, that is enough. Transients are quite expensive to set as it requires additional db queries, so you would want to cut down on the use.</p>\n\n<p>As always, I like to keep my templates simple, short and sweet, so I tend to write custom functions to move the bulk of the code outside my templates. You can put everything in one function with one transient</p>\n\n<p>You can try something like this (<em>Requires PHP 5.4+</em>)</p>\n\n<pre><code>function get_term_post_list( $taxonomy = 'category', $args = [], $query_args = [] ) \n{\n /*\n * Check if we have a transient set\n */\n if ( false === ( $output = get_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ) ) ) ) {\n\n /*\n * Use get_terms to get an array of terms\n */\n $terms = get_terms( $taxonomy, $args );\n\n if ( is_wp_error( $terms ) || empty( $terms ) )\n return null;\n\n /*\n * We will create a string with our output\n */\n $output = ''; \n foreach ( $terms as $term ) {\n\n $output .= '&lt;div class=\"subject\"&gt;';\n $output .= '&lt;h3&gt;' . $term-&gt;name . '&lt;/h3&gt;';\n $output .= '&lt;ul&gt;';\n\n /*\n * Use a tax_query to make this dynamic for all taxonomies\n */\n $default_args = [\n 'no_found_rows' =&gt; true,\n 'suppress_filters' =&gt; true,\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $term-&gt;term_id,\n 'include_children' =&gt; false\n ]\n ]\n ];\n /*\n * Merge the tax_query with the user set arguments\n */\n $merged_args = array_merge( $default_args, $query_args );\n\n $q = new WP_Query( $merged_args );\n\n while($q-&gt;have_posts()) {\n $q-&gt;the_post();\n\n $output .= '&lt;li&gt;&lt;a href=\"' . get_permalink() . '\" title=\"' . apply_filters( 'the_title', get_the_title() ) . '\"&gt;' . apply_filters( 'the_title', get_the_title() ) . '&lt;/a&gt;&lt;/li&gt;';\n\n }\n wp_reset_postdata();\n\n $output .= '&lt;/ul&gt;';\n $output .= '&lt;/div&gt;';\n\n }\n /*\n * Set our transient, use all arguments to create a unique key for the transient name\n */\n set_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ), $output, 36 * HOUR_IN_SECONDS );\n }\n /*\n * $output will be atring, treat as such\n */\n return $output;\n}\n</code></pre>\n\n<h2>FEW NOTES</h2>\n\n<ul>\n<li><p>The first parameter, $taxonomy is the taxonomy to get terms and posts from. It defaults to 'category'</p></li>\n<li><p>The second parameter is <code>$args</code> which is the arguments which should be passed to <code>get_terms()</code>. For more info, check <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a></p></li>\n<li><p>The third parameter, <code>$query_args</code> is the arguments that should be passed to the custom query. Remember to avoid using any taxonomy related parameters. For more info, see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a></p></li>\n<li><p>If the second parameter is not set and the third parameter is set, pass an empty array to the second parameter</p></li>\n<li><p>Modify and abuse the code as you see fit</p></li>\n</ul>\n\n<h2>USAGE</h2>\n\n<p>You can now use the function as follow in your templates</p>\n\n<pre><code>$post_list = get_term_post_list( 'category', ['exclude' =&gt; '1, 4, 9, 10, 2899'], ['posts_per_page' =&gt; 3] );\nif ( $post_list !== null ) {\n echo $post_list;\n}\n</code></pre>\n\n<p>If you do not pass anything to the second parameter but to the third, you should do the following (pass empty array)</p>\n\n<pre><code>$post_list = get_term_post_list( 'category', [], ['posts_per_page' =&gt; 3] );\nif ( $post_list !== null ) {\n echo $post_list;\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>In a rush, I totally forgot to add a function to flush the transient when a new post is published, updated, deleted or undeleted. As your code stands, the list will only be updated when the transient expires. </p>\n\n<p>To flush the transient on the above post conditions, simply use the <code>transition_post_status</code> hook. Add the following to your functions.php</p>\n\n<pre><code>add_action( 'transition_post_status', function ()\n{\n global $wpdb;\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_term_list_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_term_list_%')\" );\n});\n</code></pre>\n\n<h2>EDIT 2</h2>\n\n<p>From your comment to this answer</p>\n\n<blockquote>\n <p>As you might have guessed I'd liked to use this in combination <a href=\"https://wordpress.stackexchange.com/q/185011/31545\">with my other question</a>. How would I go about doing that? Should the exclusion of the terms happen in <code>get_term_post_list()</code>? Or should the two functions be merged somehow? (As I don't need them seperately.) </p>\n</blockquote>\n\n<p>The best way to accomplish is to merge the two functions into one. That would make the most sense. I have merged the two functions and modified the functionality with the exclude parameters. What I have done is, you can now add an array of term id's to excludse via the <code>get_terms()</code> <code>exclude</code> parameter and you can also within the same function set an array of term slugs to exclude. The results will be merged into one single <code>exclude</code> parameter before being passed to <code>get_terms()</code></p>\n\n<p>Here is the function, again I have commented it well to make it easy to follow (<em>This goes into functions.php</em>)</p>\n\n<pre><code>function get_term_post_list( $taxonomy = 'category', $args = [], $query_args = [], $exclude_by_slug = [] ) \n{\n /*\n * Check if we have a transient set\n */\n if ( false === ( $output = get_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ) ) ) ) {\n\n /*\n * Check if any array of slugs is passed and if it is a valid array\n */\n if ( is_array( $exclude_by_slug ) &amp;&amp; !empty( $exclude_by_slug ) ) {\n\n foreach ( $exclude_by_slug as $value ) {\n\n /*\n * Use get_term_by to get the term ID and add ID's to an array\n */\n $term_objects = get_term_by( 'slug', $value, $taxonomy );\n $term_ids[] = (int) $term_objects-&gt;term_id;\n\n }\n\n }\n\n /*\n * Merge $args['exclude'] and $term_ids \n */\n if ( isset( $args['exclude'] ) &amp;&amp; isset( $term_ids ) ) {\n\n $excluded_args = (array) $args['exclude'];\n unset( $args['exclude'] );\n $args['exclude'] = array_merge( $excluded_args, $term_ids );\n\n } elseif ( !isset( $args['exclude'] ) &amp;&amp; isset( $term_ids ) ) {\n\n $args['exclude'] = $term_ids;\n\n } \n\n /*\n * Use get_terms to get an array of terms\n */\n $terms = get_terms( $taxonomy, $args );\n\n if ( is_wp_error( $terms ) || empty( $terms ) )\n return null;\n\n /*\n * We will create a string with our output\n */\n $output = ''; \n foreach ( $terms as $term ) {\n\n $output .= '&lt;div class=\"subject\"&gt;';\n $output .= '&lt;h3&gt;' . $term-&gt;name . '&lt;/h3&gt;';\n $output .= '&lt;ul&gt;';\n\n /*\n * Use a tax_query to make this dynamic for all taxonomies\n */\n $default_args = [\n 'no_found_rows' =&gt; true,\n 'suppress_filters' =&gt; true,\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; $taxonomy,\n 'terms' =&gt; $term-&gt;term_id,\n 'include_children' =&gt; false\n ]\n ]\n ];\n /*\n * Merge the tax_query with the user set arguments\n */\n $merged_args = array_merge( $default_args, $query_args );\n\n $q = new WP_Query( $merged_args );\n\n while($q-&gt;have_posts()) {\n $q-&gt;the_post();\n\n $output .= '&lt;li&gt;&lt;a href=\"' . get_permalink() . '\" title=\"' . apply_filters( 'the_title', get_the_title() ) . '\"&gt;' . apply_filters( 'the_title', get_the_title() ) . '&lt;/a&gt;&lt;/li&gt;';\n\n }\n wp_reset_postdata();\n\n $output .= '&lt;/ul&gt;';\n $output .= '&lt;/div&gt;';\n\n }\n /*\n * Set our transient, use all arguments to create a unique key for the transient name\n */\n set_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ), $output, 36 * HOUR_IN_SECONDS );\n }\n /*\n * $output will be string, treat as such\n */\n return $output;\n}\n</code></pre>\n\n<p>As far as usage, you first need to look at the parameters that you can pass</p>\n\n<ul>\n<li><p>Parameter 1 - <code>$taxonomy</code> -> taxonomy to get terms from. Default <code>category</code></p></li>\n<li><p>Parameter 2 - <code>$args</code> -> The arguments that should be passed to <code>get_terms()</code>. Please see <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> for a full list of parameters that can be passed as an array. Default empty array <code>[]</code></p></li>\n<li><p>Parameter 3 - <code>$query_args</code> -> Custom argument to be passed to <code>WP_Query</code>. You should not pass taxonomy related parameters here as it cause issues with the deafult build in <code>tax_query</code>. For a full list of valid arguments which can be passed in an array, see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a>. Default empty array <code>[]</code></p></li>\n<li><p>Parameter 4 - <code>$exclude_by_slug</code> -> An array of slugs to exclude. Please note, this has to be a valid array for this to work. Strings will be ignored. Default empty array <code>[]</code></p></li>\n</ul>\n\n<p>You can now call the function in any of your template files as</p>\n\n<pre><code>$a = get_term_post_list( 'category', ['exclude' =&gt; [1, 13, 42]], ['posts_per_page' =&gt; 3], ['term-slug-1', 'term-slug-2'] );\necho $a;\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$taxonomy = 'category';\n$args = [\n 'exclude' =&gt; [1, 13, 42]\n];\n$query_args = [\n 'posts_per_page' =&gt; 3\n];\n$exclude_by_slug = [\n '0' =&gt; ['term-slug-1', 'term-slug-2']\n];\n$a = get_term_post_list( $taxonomy, $args, $query_args, $exclude_by_slug );\necho $a;\n</code></pre>\n\n<p>Final note, if you don't need to pass a specific parameter, remember to just pass an empty array like</p>\n\n<pre><code>$a = get_term_post_list( 'category', [], [], ['term-slug-1'] );\necho $a;\n</code></pre>\n\n<p>All the above replaces all your code in your question</p>\n" } ]
2015/04/22
[ "https://wordpress.stackexchange.com/questions/185004", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16574/" ]
For a specific section on my website I loop through some categories and get the three latest posts in that categorie and list them. Like so: ``` <?php $categories = get_categories(array('exclude' => '1, 4, 9, 10, 2899')); ?> <?php foreach ($categories as $category) : ?> <div class="subject"> <h3><?php echo $category->cat_name; ?></h3> <ul> <?php $args = array( 'cat' => $category->cat_ID, 'posts_per_page' => 3 ); ?> <?php if (false === ( $category_posts_query = get_transient( 'category_posts' ) ) ) { $category_posts_query = new WP_Query($args); set_transient( 'category_posts', $category_posts_query, 36 * HOUR_IN_SECONDS ); } ?> <?php while($category_posts_query->have_posts()) : ?> <?php $category_posts_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> </div> <?php wp_reset_postdata(); ?> <?php endforeach; ?> ``` However, the result is not what is expected: all posts are the same across categories even though the posts don't belong to the different categories: ![enter image description here](https://i.stack.imgur.com/yjRiO.png) When I remove the `transient` for caching, everything works as expted. ``` <?php $categories = get_categories(array('exclude' => '1, 4, 9, 10, 2899')); ?> <?php foreach ($categories as $category) : ?> <div class="subject"> <h3><?php echo $category->cat_name; ?></h3> <ul> <?php $args = array( 'cat' => $category->cat_ID, 'posts_per_page' => 3 ); ?> <?php $category_posts_query = new WP_Query($args); ?> <?php while($category_posts_query->have_posts()) : ?> <?php $category_posts_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> </div> <?php wp_reset_postdata(); ?> <?php endforeach; ?> ``` How do I add chacing to this last snippet?
I don't think you need so many transients set, one for each category. You can only use one, that is enough. Transients are quite expensive to set as it requires additional db queries, so you would want to cut down on the use. As always, I like to keep my templates simple, short and sweet, so I tend to write custom functions to move the bulk of the code outside my templates. You can put everything in one function with one transient You can try something like this (*Requires PHP 5.4+*) ``` function get_term_post_list( $taxonomy = 'category', $args = [], $query_args = [] ) { /* * Check if we have a transient set */ if ( false === ( $output = get_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ) ) ) ) { /* * Use get_terms to get an array of terms */ $terms = get_terms( $taxonomy, $args ); if ( is_wp_error( $terms ) || empty( $terms ) ) return null; /* * We will create a string with our output */ $output = ''; foreach ( $terms as $term ) { $output .= '<div class="subject">'; $output .= '<h3>' . $term->name . '</h3>'; $output .= '<ul>'; /* * Use a tax_query to make this dynamic for all taxonomies */ $default_args = [ 'no_found_rows' => true, 'suppress_filters' => true, 'tax_query' => [ [ 'taxonomy' => $taxonomy, 'terms' => $term->term_id, 'include_children' => false ] ] ]; /* * Merge the tax_query with the user set arguments */ $merged_args = array_merge( $default_args, $query_args ); $q = new WP_Query( $merged_args ); while($q->have_posts()) { $q->the_post(); $output .= '<li><a href="' . get_permalink() . '" title="' . apply_filters( 'the_title', get_the_title() ) . '">' . apply_filters( 'the_title', get_the_title() ) . '</a></li>'; } wp_reset_postdata(); $output .= '</ul>'; $output .= '</div>'; } /* * Set our transient, use all arguments to create a unique key for the transient name */ set_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ), $output, 36 * HOUR_IN_SECONDS ); } /* * $output will be atring, treat as such */ return $output; } ``` FEW NOTES --------- * The first parameter, $taxonomy is the taxonomy to get terms and posts from. It defaults to 'category' * The second parameter is `$args` which is the arguments which should be passed to `get_terms()`. For more info, check [`get_terms()`](https://codex.wordpress.org/Function_Reference/get_terms) * The third parameter, `$query_args` is the arguments that should be passed to the custom query. Remember to avoid using any taxonomy related parameters. For more info, see [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) * If the second parameter is not set and the third parameter is set, pass an empty array to the second parameter * Modify and abuse the code as you see fit USAGE ----- You can now use the function as follow in your templates ``` $post_list = get_term_post_list( 'category', ['exclude' => '1, 4, 9, 10, 2899'], ['posts_per_page' => 3] ); if ( $post_list !== null ) { echo $post_list; } ``` If you do not pass anything to the second parameter but to the third, you should do the following (pass empty array) ``` $post_list = get_term_post_list( 'category', [], ['posts_per_page' => 3] ); if ( $post_list !== null ) { echo $post_list; } ``` EDIT ---- In a rush, I totally forgot to add a function to flush the transient when a new post is published, updated, deleted or undeleted. As your code stands, the list will only be updated when the transient expires. To flush the transient on the above post conditions, simply use the `transition_post_status` hook. Add the following to your functions.php ``` add_action( 'transition_post_status', function () { global $wpdb; $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_term_list_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_term_list_%')" ); }); ``` EDIT 2 ------ From your comment to this answer > > As you might have guessed I'd liked to use this in combination [with my other question](https://wordpress.stackexchange.com/q/185011/31545). How would I go about doing that? Should the exclusion of the terms happen in `get_term_post_list()`? Or should the two functions be merged somehow? (As I don't need them seperately.) > > > The best way to accomplish is to merge the two functions into one. That would make the most sense. I have merged the two functions and modified the functionality with the exclude parameters. What I have done is, you can now add an array of term id's to excludse via the `get_terms()` `exclude` parameter and you can also within the same function set an array of term slugs to exclude. The results will be merged into one single `exclude` parameter before being passed to `get_terms()` Here is the function, again I have commented it well to make it easy to follow (*This goes into functions.php*) ``` function get_term_post_list( $taxonomy = 'category', $args = [], $query_args = [], $exclude_by_slug = [] ) { /* * Check if we have a transient set */ if ( false === ( $output = get_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ) ) ) ) { /* * Check if any array of slugs is passed and if it is a valid array */ if ( is_array( $exclude_by_slug ) && !empty( $exclude_by_slug ) ) { foreach ( $exclude_by_slug as $value ) { /* * Use get_term_by to get the term ID and add ID's to an array */ $term_objects = get_term_by( 'slug', $value, $taxonomy ); $term_ids[] = (int) $term_objects->term_id; } } /* * Merge $args['exclude'] and $term_ids */ if ( isset( $args['exclude'] ) && isset( $term_ids ) ) { $excluded_args = (array) $args['exclude']; unset( $args['exclude'] ); $args['exclude'] = array_merge( $excluded_args, $term_ids ); } elseif ( !isset( $args['exclude'] ) && isset( $term_ids ) ) { $args['exclude'] = $term_ids; } /* * Use get_terms to get an array of terms */ $terms = get_terms( $taxonomy, $args ); if ( is_wp_error( $terms ) || empty( $terms ) ) return null; /* * We will create a string with our output */ $output = ''; foreach ( $terms as $term ) { $output .= '<div class="subject">'; $output .= '<h3>' . $term->name . '</h3>'; $output .= '<ul>'; /* * Use a tax_query to make this dynamic for all taxonomies */ $default_args = [ 'no_found_rows' => true, 'suppress_filters' => true, 'tax_query' => [ [ 'taxonomy' => $taxonomy, 'terms' => $term->term_id, 'include_children' => false ] ] ]; /* * Merge the tax_query with the user set arguments */ $merged_args = array_merge( $default_args, $query_args ); $q = new WP_Query( $merged_args ); while($q->have_posts()) { $q->the_post(); $output .= '<li><a href="' . get_permalink() . '" title="' . apply_filters( 'the_title', get_the_title() ) . '">' . apply_filters( 'the_title', get_the_title() ) . '</a></li>'; } wp_reset_postdata(); $output .= '</ul>'; $output .= '</div>'; } /* * Set our transient, use all arguments to create a unique key for the transient name */ set_transient( 'term_list_' . md5( $taxonomy . json_encode( $args ) . json_encode( $query_args ) ), $output, 36 * HOUR_IN_SECONDS ); } /* * $output will be string, treat as such */ return $output; } ``` As far as usage, you first need to look at the parameters that you can pass * Parameter 1 - `$taxonomy` -> taxonomy to get terms from. Default `category` * Parameter 2 - `$args` -> The arguments that should be passed to `get_terms()`. Please see [`get_terms()`](https://codex.wordpress.org/Function_Reference/get_terms) for a full list of parameters that can be passed as an array. Default empty array `[]` * Parameter 3 - `$query_args` -> Custom argument to be passed to `WP_Query`. You should not pass taxonomy related parameters here as it cause issues with the deafult build in `tax_query`. For a full list of valid arguments which can be passed in an array, see [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query). Default empty array `[]` * Parameter 4 - `$exclude_by_slug` -> An array of slugs to exclude. Please note, this has to be a valid array for this to work. Strings will be ignored. Default empty array `[]` You can now call the function in any of your template files as ``` $a = get_term_post_list( 'category', ['exclude' => [1, 13, 42]], ['posts_per_page' => 3], ['term-slug-1', 'term-slug-2'] ); echo $a; ``` OR ``` $taxonomy = 'category'; $args = [ 'exclude' => [1, 13, 42] ]; $query_args = [ 'posts_per_page' => 3 ]; $exclude_by_slug = [ '0' => ['term-slug-1', 'term-slug-2'] ]; $a = get_term_post_list( $taxonomy, $args, $query_args, $exclude_by_slug ); echo $a; ``` Final note, if you don't need to pass a specific parameter, remember to just pass an empty array like ``` $a = get_term_post_list( 'category', [], [], ['term-slug-1'] ); echo $a; ``` All the above replaces all your code in your question
185,011
<p>I am trying to exclude some categories from a for-loop.</p> <pre><code>&lt;?php $categories = get_categories(array('exclude' =&gt; 'apps, windows')); ?&gt; &lt;?php foreach ($categories as $category) : ?&gt; // the_loop &lt;?php endforeach; ?&gt; </code></pre> <p>Even though no error is thrown, it doesn't work: all categories are used in the loop. How can I exclude some categories by slug?</p> <p>I am working with multiple sites that have different cat IDs but the same slug, so I need to filter by slug rather than by cat ID.</p> <hr> <p>For future readers: Pieter Goosen answered this question and another in into a merged answer <a href="https://wordpress.stackexchange.com/a/185048/16574">here</a>.</p>
[ { "answer_id": 185014, "author": "impsart", "author_id": 65286, "author_profile": "https://wordpress.stackexchange.com/users/65286", "pm_score": 0, "selected": false, "text": "<p>There's a small error on your first line of code. You should separate 'each' category with quotes in the array. So the first line should be:</p>\n\n<pre><code>&lt;?php $categories = get_categories(array('exclude' =&gt; 'apps', 'windows')); ?&gt;\n</code></pre>\n" }, { "answer_id": 185038, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As I already stated, straight from the <a href=\"https://codex.wordpress.org/Function_Reference/get_categories\" rel=\"nofollow\">codex</a></p>\n\n<blockquote>\n <p><strong>exclude</strong></p>\n \n <p>(string) Excludes one or more categories from the list generated by wp_list_categories. This parameter takes a comma-separated list of categories by unique ID, in ascending order</p>\n</blockquote>\n\n<p>As you have stated, you have to use the category slug. To make this possible and dynamic, I think the best will be to write your own wrapper function to achieve this. We are going to use <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\"><code>get_terms()</code></a> (which is used by <a href=\"https://codex.wordpress.org/Function_Reference/get_categories\" rel=\"nofollow\"><code>get_categories()</code></a> internally) to get our categories and <a href=\"https://codex.wordpress.org/Function_Reference/get_term_by\" rel=\"nofollow\"><code>get_term_by()</code></a> to get the category ID so that we can pass that to <code>get_terms()</code></p>\n\n<p>Here is the function, I have commented it well for better understanding (<em>Requires PHP 5.4+</em>)</p>\n\n<pre><code>function exclude_term_by( $taxonomy = 'category', $args = [], $exclude = [] )\n{\n /*\n * If there are no term slugs to exclude or if $exclude is not a valid array, return get_terms\n */\n if ( empty( $exclude ) || !is_array( $exclude ) )\n return get_terms( $taxonomy, $args );\n\n /*\n * If we reach this point, then we have terms to exclude by slug\n * Simply continue the process. \n */ \n foreach ( $exclude as $value ) {\n\n /*\n * Use get_term_by to get the term ID and add ID's to an array\n */\n $term_objects = get_term_by( 'slug', $value, $taxonomy );\n $term_ids[] = (int) $term_objects-&gt;term_id;\n\n }\n\n /*\n * Set up the exclude parameter with an array of ids from $term_ids\n */\n $excluded_ids = [\n 'exclude' =&gt; $term_ids\n ];\n\n /*\n * Merge the user passed arguments $args with the excluded terms $excluded_ids\n * If any value is passed to $args['exclude'], it will be ignored\n */\n $merged_arguments = array_merge( $args, $excluded_ids );\n\n /*\n * Lets pass everything to get_terms\n */\n $terms = get_terms( $taxonomy, $merged_arguments ); \n\n /*\n * Return the results from get_terms\n */\n return $terms;\n}\n</code></pre>\n\n<p>Before I go into usage, here are a few notes</p>\n\n<ul>\n<li><p>The first parameter, <code>$taxonomy</code> is the particular taxonomy to pass to <code>get_terms()</code> inside the function, it defaults to <code>category</code></p></li>\n<li><p>The second parameter, <code>$args</code> takes the same parameters as <code>get_terms()</code>. Just a note, if the third parameter is set, the default <code>exclude</code> parameter's value is ignored if anything is passed to it. This value will be overridden by whatever is passed to <code>$exclude</code>. If nothing is passed to this parameter, and anything is passed to <code>$exclude</code>, you need to pass an empty array as value</p></li>\n<li><p>The third parameter, <code>$excludes</code> takes an array of term slugs which should be excluded. If the value is not a valid array, <code>get_terms()</code> will be returned without excluding the necessary terms, so be sure to pass an array of slugs</p></li>\n<li><p>Treat the output from the function in the same way you would with <code>get_terms()</code>. Remember, you should also check for empty values and <code>WP_Error</code> objects before using the value from the function</p></li>\n<li><p>Modify and abuse the code as you see fit</p></li>\n</ul>\n\n<p>Now for the usage in your template files. Note the empty array passed to the <code>$args</code> parameter if anything is passed to the <code>$exclude</code> parameter</p>\n\n<pre><code>$terms = exclude_term_by( 'category', [], ['term-slug-one', 'term-slug-two'] );\nif ( !empty( $terms ) &amp;&amp; !is_wp_error( $terms ) ) {\n ?&gt;&lt;pre&gt;&lt;?php var_dump($terms); ?&gt;&lt;/pre&gt;&lt;?php\n} \n</code></pre>\n\n<p>For any extra info on usage, see <code>get_terms()</code>.</p>\n" } ]
2015/04/22
[ "https://wordpress.stackexchange.com/questions/185011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16574/" ]
I am trying to exclude some categories from a for-loop. ``` <?php $categories = get_categories(array('exclude' => 'apps, windows')); ?> <?php foreach ($categories as $category) : ?> // the_loop <?php endforeach; ?> ``` Even though no error is thrown, it doesn't work: all categories are used in the loop. How can I exclude some categories by slug? I am working with multiple sites that have different cat IDs but the same slug, so I need to filter by slug rather than by cat ID. --- For future readers: Pieter Goosen answered this question and another in into a merged answer [here](https://wordpress.stackexchange.com/a/185048/16574).
As I already stated, straight from the [codex](https://codex.wordpress.org/Function_Reference/get_categories) > > **exclude** > > > (string) Excludes one or more categories from the list generated by wp\_list\_categories. This parameter takes a comma-separated list of categories by unique ID, in ascending order > > > As you have stated, you have to use the category slug. To make this possible and dynamic, I think the best will be to write your own wrapper function to achieve this. We are going to use [`get_terms()`](https://codex.wordpress.org/Function_Reference/get_terms) (which is used by [`get_categories()`](https://codex.wordpress.org/Function_Reference/get_categories) internally) to get our categories and [`get_term_by()`](https://codex.wordpress.org/Function_Reference/get_term_by) to get the category ID so that we can pass that to `get_terms()` Here is the function, I have commented it well for better understanding (*Requires PHP 5.4+*) ``` function exclude_term_by( $taxonomy = 'category', $args = [], $exclude = [] ) { /* * If there are no term slugs to exclude or if $exclude is not a valid array, return get_terms */ if ( empty( $exclude ) || !is_array( $exclude ) ) return get_terms( $taxonomy, $args ); /* * If we reach this point, then we have terms to exclude by slug * Simply continue the process. */ foreach ( $exclude as $value ) { /* * Use get_term_by to get the term ID and add ID's to an array */ $term_objects = get_term_by( 'slug', $value, $taxonomy ); $term_ids[] = (int) $term_objects->term_id; } /* * Set up the exclude parameter with an array of ids from $term_ids */ $excluded_ids = [ 'exclude' => $term_ids ]; /* * Merge the user passed arguments $args with the excluded terms $excluded_ids * If any value is passed to $args['exclude'], it will be ignored */ $merged_arguments = array_merge( $args, $excluded_ids ); /* * Lets pass everything to get_terms */ $terms = get_terms( $taxonomy, $merged_arguments ); /* * Return the results from get_terms */ return $terms; } ``` Before I go into usage, here are a few notes * The first parameter, `$taxonomy` is the particular taxonomy to pass to `get_terms()` inside the function, it defaults to `category` * The second parameter, `$args` takes the same parameters as `get_terms()`. Just a note, if the third parameter is set, the default `exclude` parameter's value is ignored if anything is passed to it. This value will be overridden by whatever is passed to `$exclude`. If nothing is passed to this parameter, and anything is passed to `$exclude`, you need to pass an empty array as value * The third parameter, `$excludes` takes an array of term slugs which should be excluded. If the value is not a valid array, `get_terms()` will be returned without excluding the necessary terms, so be sure to pass an array of slugs * Treat the output from the function in the same way you would with `get_terms()`. Remember, you should also check for empty values and `WP_Error` objects before using the value from the function * Modify and abuse the code as you see fit Now for the usage in your template files. Note the empty array passed to the `$args` parameter if anything is passed to the `$exclude` parameter ``` $terms = exclude_term_by( 'category', [], ['term-slug-one', 'term-slug-two'] ); if ( !empty( $terms ) && !is_wp_error( $terms ) ) { ?><pre><?php var_dump($terms); ?></pre><?php } ``` For any extra info on usage, see `get_terms()`.
185,015
<p>I have been experiencing 404 errors in my Google webmaster tools reports, caused by Custom Post Type (CPT) feed URLs.</p> <p>I would like to completely deactivate the CPT feed URLs, so that the 404 errors don't appear anymore in my Google webmaster tools reports. In other words, I'd like to fix all these errors at once by deactivating the functionality that causes them.</p>
[ { "answer_id": 185014, "author": "impsart", "author_id": 65286, "author_profile": "https://wordpress.stackexchange.com/users/65286", "pm_score": 0, "selected": false, "text": "<p>There's a small error on your first line of code. You should separate 'each' category with quotes in the array. So the first line should be:</p>\n\n<pre><code>&lt;?php $categories = get_categories(array('exclude' =&gt; 'apps', 'windows')); ?&gt;\n</code></pre>\n" }, { "answer_id": 185038, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As I already stated, straight from the <a href=\"https://codex.wordpress.org/Function_Reference/get_categories\" rel=\"nofollow\">codex</a></p>\n\n<blockquote>\n <p><strong>exclude</strong></p>\n \n <p>(string) Excludes one or more categories from the list generated by wp_list_categories. This parameter takes a comma-separated list of categories by unique ID, in ascending order</p>\n</blockquote>\n\n<p>As you have stated, you have to use the category slug. To make this possible and dynamic, I think the best will be to write your own wrapper function to achieve this. We are going to use <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\"><code>get_terms()</code></a> (which is used by <a href=\"https://codex.wordpress.org/Function_Reference/get_categories\" rel=\"nofollow\"><code>get_categories()</code></a> internally) to get our categories and <a href=\"https://codex.wordpress.org/Function_Reference/get_term_by\" rel=\"nofollow\"><code>get_term_by()</code></a> to get the category ID so that we can pass that to <code>get_terms()</code></p>\n\n<p>Here is the function, I have commented it well for better understanding (<em>Requires PHP 5.4+</em>)</p>\n\n<pre><code>function exclude_term_by( $taxonomy = 'category', $args = [], $exclude = [] )\n{\n /*\n * If there are no term slugs to exclude or if $exclude is not a valid array, return get_terms\n */\n if ( empty( $exclude ) || !is_array( $exclude ) )\n return get_terms( $taxonomy, $args );\n\n /*\n * If we reach this point, then we have terms to exclude by slug\n * Simply continue the process. \n */ \n foreach ( $exclude as $value ) {\n\n /*\n * Use get_term_by to get the term ID and add ID's to an array\n */\n $term_objects = get_term_by( 'slug', $value, $taxonomy );\n $term_ids[] = (int) $term_objects-&gt;term_id;\n\n }\n\n /*\n * Set up the exclude parameter with an array of ids from $term_ids\n */\n $excluded_ids = [\n 'exclude' =&gt; $term_ids\n ];\n\n /*\n * Merge the user passed arguments $args with the excluded terms $excluded_ids\n * If any value is passed to $args['exclude'], it will be ignored\n */\n $merged_arguments = array_merge( $args, $excluded_ids );\n\n /*\n * Lets pass everything to get_terms\n */\n $terms = get_terms( $taxonomy, $merged_arguments ); \n\n /*\n * Return the results from get_terms\n */\n return $terms;\n}\n</code></pre>\n\n<p>Before I go into usage, here are a few notes</p>\n\n<ul>\n<li><p>The first parameter, <code>$taxonomy</code> is the particular taxonomy to pass to <code>get_terms()</code> inside the function, it defaults to <code>category</code></p></li>\n<li><p>The second parameter, <code>$args</code> takes the same parameters as <code>get_terms()</code>. Just a note, if the third parameter is set, the default <code>exclude</code> parameter's value is ignored if anything is passed to it. This value will be overridden by whatever is passed to <code>$exclude</code>. If nothing is passed to this parameter, and anything is passed to <code>$exclude</code>, you need to pass an empty array as value</p></li>\n<li><p>The third parameter, <code>$excludes</code> takes an array of term slugs which should be excluded. If the value is not a valid array, <code>get_terms()</code> will be returned without excluding the necessary terms, so be sure to pass an array of slugs</p></li>\n<li><p>Treat the output from the function in the same way you would with <code>get_terms()</code>. Remember, you should also check for empty values and <code>WP_Error</code> objects before using the value from the function</p></li>\n<li><p>Modify and abuse the code as you see fit</p></li>\n</ul>\n\n<p>Now for the usage in your template files. Note the empty array passed to the <code>$args</code> parameter if anything is passed to the <code>$exclude</code> parameter</p>\n\n<pre><code>$terms = exclude_term_by( 'category', [], ['term-slug-one', 'term-slug-two'] );\nif ( !empty( $terms ) &amp;&amp; !is_wp_error( $terms ) ) {\n ?&gt;&lt;pre&gt;&lt;?php var_dump($terms); ?&gt;&lt;/pre&gt;&lt;?php\n} \n</code></pre>\n\n<p>For any extra info on usage, see <code>get_terms()</code>.</p>\n" } ]
2015/04/22
[ "https://wordpress.stackexchange.com/questions/185015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50943/" ]
I have been experiencing 404 errors in my Google webmaster tools reports, caused by Custom Post Type (CPT) feed URLs. I would like to completely deactivate the CPT feed URLs, so that the 404 errors don't appear anymore in my Google webmaster tools reports. In other words, I'd like to fix all these errors at once by deactivating the functionality that causes them.
As I already stated, straight from the [codex](https://codex.wordpress.org/Function_Reference/get_categories) > > **exclude** > > > (string) Excludes one or more categories from the list generated by wp\_list\_categories. This parameter takes a comma-separated list of categories by unique ID, in ascending order > > > As you have stated, you have to use the category slug. To make this possible and dynamic, I think the best will be to write your own wrapper function to achieve this. We are going to use [`get_terms()`](https://codex.wordpress.org/Function_Reference/get_terms) (which is used by [`get_categories()`](https://codex.wordpress.org/Function_Reference/get_categories) internally) to get our categories and [`get_term_by()`](https://codex.wordpress.org/Function_Reference/get_term_by) to get the category ID so that we can pass that to `get_terms()` Here is the function, I have commented it well for better understanding (*Requires PHP 5.4+*) ``` function exclude_term_by( $taxonomy = 'category', $args = [], $exclude = [] ) { /* * If there are no term slugs to exclude or if $exclude is not a valid array, return get_terms */ if ( empty( $exclude ) || !is_array( $exclude ) ) return get_terms( $taxonomy, $args ); /* * If we reach this point, then we have terms to exclude by slug * Simply continue the process. */ foreach ( $exclude as $value ) { /* * Use get_term_by to get the term ID and add ID's to an array */ $term_objects = get_term_by( 'slug', $value, $taxonomy ); $term_ids[] = (int) $term_objects->term_id; } /* * Set up the exclude parameter with an array of ids from $term_ids */ $excluded_ids = [ 'exclude' => $term_ids ]; /* * Merge the user passed arguments $args with the excluded terms $excluded_ids * If any value is passed to $args['exclude'], it will be ignored */ $merged_arguments = array_merge( $args, $excluded_ids ); /* * Lets pass everything to get_terms */ $terms = get_terms( $taxonomy, $merged_arguments ); /* * Return the results from get_terms */ return $terms; } ``` Before I go into usage, here are a few notes * The first parameter, `$taxonomy` is the particular taxonomy to pass to `get_terms()` inside the function, it defaults to `category` * The second parameter, `$args` takes the same parameters as `get_terms()`. Just a note, if the third parameter is set, the default `exclude` parameter's value is ignored if anything is passed to it. This value will be overridden by whatever is passed to `$exclude`. If nothing is passed to this parameter, and anything is passed to `$exclude`, you need to pass an empty array as value * The third parameter, `$excludes` takes an array of term slugs which should be excluded. If the value is not a valid array, `get_terms()` will be returned without excluding the necessary terms, so be sure to pass an array of slugs * Treat the output from the function in the same way you would with `get_terms()`. Remember, you should also check for empty values and `WP_Error` objects before using the value from the function * Modify and abuse the code as you see fit Now for the usage in your template files. Note the empty array passed to the `$args` parameter if anything is passed to the `$exclude` parameter ``` $terms = exclude_term_by( 'category', [], ['term-slug-one', 'term-slug-two'] ); if ( !empty( $terms ) && !is_wp_error( $terms ) ) { ?><pre><?php var_dump($terms); ?></pre><?php } ``` For any extra info on usage, see `get_terms()`.
185,047
<p>I have a custom database in my WordPress site where I want to save multiple values to one row.</p> <p>Let's say I have an entry:</p> <ul> <li>id: auto increment</li> <li>pageid: id of current page</li> <li>time: text (is an array created with implode)</li> </ul> <p>Example:</p> <pre><code>id pageid time 1 1 121212,121314,121415 2 2 121212,121314 </code></pre> <p>What I am trying to achieve is a way I can extend the "time" field. Every time the function goes off, I want a <code>timestamp</code> added to the existing values.</p> <p>So it would look like this:</p> <pre><code>id pageid time 1 1 121212,121314,121415, 181920 2 2 121212,121314, 292929, 988339 </code></pre> <p>What would be the best way to solve this and how?</p> <pre><code>function custom_setup_db(){ global $wpdb; $table_name = "customdb"; $charset_collate = $wpdb-&gt;get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, userid mediumint(9) NOT NULL, timestamparray text, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } function wp_install_data(){ global $wpdb; $table_name = 'customdb'; $timestamparray = array(); array_push($timestamparray, '121212', '131415', '121316'); $timeofvisit = implode(",", $timeofvisit); $wpdb-&gt;insert( $table_name, array( 'timeofvisit' =&gt; $timeofvisit, 'userid' =&gt; '2' ) ); } </code></pre>
[ { "answer_id": 185027, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 4, "selected": true, "text": "<p>Use <code>$wpdb-&gt;base_prefix . 'table_name'</code> as a table name when you want to create a table for the whole network, or when you want to run queries on it.</p>\n\n<p><code>$wpdb-&gt;base_prefix</code> is always the prefix for the current network’s main table.</p>\n" }, { "answer_id": 185029, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>You should create a table only on activation, if is not created, exist in the database. A small source example should help you.</p>\n\n<p>The follow source create a table, also in single sites, maybe the plugin will activate in single mode for each side in the network.</p>\n\n<pre><code>register_activation_hook( __FILE__, 'on_activate' );\nfunction on_activate() {\n\n create_table();\n}\n\nfunction create_table() {\n global $wpdb;\n\n $table_name = $wpdb-&gt;prefix . 'your_table_name';\n\n // Check, if exists\n if ( $wpdb-&gt;get_var( \"show tables like '{$table_name}'\" ) == $table_name ) {\n return NULL;\n }\n\n $sql = \"CREATE TABLE \" . $table_name . \" (\n id mediumint(9) NOT NULL AUTO_INCREMENT,\n col VARCHAR(100) NOT NULL,\n PRIMARY KEY (id)\n );\";\n\n // // make dbDelta() available\n require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n dbDelta( $sql );\n}\n</code></pre>\n\n<p>If your plugin is only for network activation, then add comment to the head blog of the plugin <code>Network: TRUE</code>. WP cheks this and allow the activation only networkwide. Also add in the source a check for Multisite, like <code>if (function_exists('is_multisite') &amp;&amp; is_multisite())</code>.</p>\n\n<p>But now the important part, is the value for the global <code>$wpdb</code>. To create a table in the globals namespace, not for an specific site use <code>$wpdb-&gt;base_prefix</code>, NOT <code>$wpdb-&gt;prefix</code>.</p>\n" } ]
2015/04/22
[ "https://wordpress.stackexchange.com/questions/185047", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71025/" ]
I have a custom database in my WordPress site where I want to save multiple values to one row. Let's say I have an entry: * id: auto increment * pageid: id of current page * time: text (is an array created with implode) Example: ``` id pageid time 1 1 121212,121314,121415 2 2 121212,121314 ``` What I am trying to achieve is a way I can extend the "time" field. Every time the function goes off, I want a `timestamp` added to the existing values. So it would look like this: ``` id pageid time 1 1 121212,121314,121415, 181920 2 2 121212,121314, 292929, 988339 ``` What would be the best way to solve this and how? ``` function custom_setup_db(){ global $wpdb; $table_name = "customdb"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, userid mediumint(9) NOT NULL, timestamparray text, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } function wp_install_data(){ global $wpdb; $table_name = 'customdb'; $timestamparray = array(); array_push($timestamparray, '121212', '131415', '121316'); $timeofvisit = implode(",", $timeofvisit); $wpdb->insert( $table_name, array( 'timeofvisit' => $timeofvisit, 'userid' => '2' ) ); } ```
Use `$wpdb->base_prefix . 'table_name'` as a table name when you want to create a table for the whole network, or when you want to run queries on it. `$wpdb->base_prefix` is always the prefix for the current network’s main table.
185,075
<p>For the past two days I've been trying to debug an issue with <code>WP_Query()</code> and Pagination. </p> <p>A website I'm a dev for uses a Wordpress theme (Salient by ThemeNectar) that includes the visual composer plugin. My job is essentially to make sure the site is just functional, so a while ago I wrote an extension for the visual composer. This extension uses <code>WP_Query()</code> to create a new query, looks for posts in specific categories (with a default established), and then returns the output of that query</p> <p>Here's the code that renders posts and pagination inside that visual composer component</p> <pre><code>public function renderPosts( $atts, $content = null ) { global $post; setup_postdata($post); extract( shortcode_atts( array( 'foo' =&gt; 5, //default of 5 'categoryslug' =&gt; 'news-views' // Currently news and views. ), $atts) ); // For getting the Query variable on a statcci front page, you have // to use 'page' and not 'paged'. Weird. $paged = ( get_query_var('page') ) ? get_query_var('page') : 1; // Two things needed: Not using the game library, // Definitely using the supplied slug. // These are two objects. $dontUse = get_category_by_slug('game-library'); $catUsed = get_category_by_slug($atts-&gt;categoryslug); // Args for the custom query $query_args = array( 'posts_per_page' =&gt; intval($foo), 'category__not_in' =&gt; $dontUse-&gt;term_id, 'cat' =&gt; $catUsed-&gt;term_id, 'page' =&gt; $paged ); $custom_query = new WP_Query($query_args); $output = '&lt;div id="blogroll"&gt;'; while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post(); $output .= "&lt;div class='home_post col span_12 clear-both'&gt;"; $output .= "&lt;div class='col span_3'&gt;&lt;a href='" . get_the_permalink() . "'&gt;" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . "&lt;/a&gt;&lt;/div&gt;"; $output .= "&lt;div class='col span_9 col_last right-edge'&gt;"; $output .= "&lt;h2 class='home_post_header'&gt;"; $output .= '&lt;a href="' . get_the_permalink() . '"&gt;' . get_the_title() . "&lt;/a&gt;"; $output .= "&lt;/h2&gt;"; $output .= get_the_excerpt(); $output .= '&lt;a class="home-more-link" href="' . get_the_permalink() . '"&gt;&lt;span class="continue-reading"&gt;Read More&lt;/span&gt;&lt;/a&gt;'; $output .= "&lt;/div&gt;"; $output .= "&lt;/div&gt;"; endwhile; wp_reset_postdata(); // Pagination not working, but it outputs just fine? $output .= '&lt;div id="pagination" class="blogroll-pagination"&gt;' . home_pagination($custom_query) . '&lt;/div&gt;&lt;/div&gt;'; wp_reset_query(); return $output; } </code></pre> <p>Now, I'm aware that the code to generate the content is just a giant concatenated string, but it's only because the extension function has to return something. At the very end, I output pagination with use of another function defined above.</p> <p><a href="http://pastebin.com/Cb4uL0d5" rel="nofollow">Here's the function</a> I've created called <code>home_pagination(query)</code></p> <pre><code>function home_pagination($query = null) { /*if ( !$query ) { global $wp_query; $query = $wp_query; } commented out because do I need this? */ $big = 999999999; // need an unlikely integer $pagination = paginate_links( array( 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' =&gt; '?paged=%#%', 'current' =&gt; max( 1, get_query_var( 'page' ) ), 'total' =&gt; $query-&gt;max_num_pages, 'prev_text' =&gt; '&amp;laquo; Previous', 'next_text' =&gt; 'Next &amp;raquo;', ) ); return $pagination; } </code></pre> <p>Now, this was functioning not a week ago but I can't seem to get it to work now... Here's what I've tried:</p> <ol> <li>Playing around with <code>get_query_var('page')</code></li> <li>Using a plugin (Wp_page_navi)</li> <li>Changing where and when <code>wp_reset_postdata()</code> and <code>wp_reset_query()</code> are used</li> <li>Using the <code>max_num_pages</code> workaround for <code>next_posts_link()</code> and <code>previous_posts_link()</code></li> </ol> <p>This is on a <strong>static front page</strong> and I'm aware that the rules are different with 'page' and 'paged'</p> <p><strong>Interesting to note</strong>: When I change the 'paged' variable in the query args, it returns the proper corresponding page. </p> <p>I'm trying to figure out why the pagination I'm outputting as a part of this query is doing ABSOLUTELY NOTHING when I try to navigate with it? It's as if it wants to navigate to /page/2 or whichever number, but then immediately redirects to the site itself...</p> <p>I'm considering not putting the <code>paginate_links()</code> call in a separate function. There are probably glaring mistakes, but I've been grinding away at pagination that no longer seems to work. Any ideas on how I can best approach this? Is there something huge I'm missing? </p>
[ { "answer_id": 185775, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I'm not quite sure what do you mean by you have extended the visual composer, but I do have a couple of concerns here.</p>\n\n<ul>\n<li><p><a href=\"http://en.m.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">SoC</a> -> From your code I detect that you are using a shortcode, which should have its own separate class. You should not extend the class to the visual editor (<em>at least this is how I read your question</em>). Classes should never multi task, they should do <strong>one</strong> single duty. This keeps your class extentable, short, easy to maintain and reusable and easy to test</p></li>\n<li><p>Extending the previous point, front end and back end functionalities should not be mixed</p></li>\n<li><p>I don't see the usefulness of using <code>global $post</code> and setting up post data. Doing this and not resetting postdata afterwards will have unexpected influences on any query afterwards and on the main query. You should drop that completely</p></li>\n<li><p>Never ever use <code>extract()</code> in shortcodes ( and any other function for that matter ). It is very unrealiable and untestable and leads to unexpected output. This makes it extremely hard to debug in case of failures. For this very reason, it was completely removed from core. See <a href=\"https://core.trac.wordpress.org/ticket/22400\" rel=\"nofollow noreferrer\">trac ticket 22400</a></p></li>\n<li><p>Because you are using multiple category conditions, and to make it more dynamic, I would rather use a <code>tax_query</code> to handle the conditions. The big plus here would be that you will save on db calls as you can get rid of <code>get_category_by_slug</code></p></li>\n<li><p>There is no need for <code>wp_reset_query()</code>. This is used with <code>query_posts</code> which you should never ever use. It is a page breaker.</p></li>\n<li><p>Front pages and single pages uses the query variable <code>page</code> (<code>get_query_var( 'page' )</code>) for pagination, and not <code>paged</code> (<code>get_query_var( 'paged' )</code>) as other pages. The query argument for <code>WP_Query</code> for both however is the same, it should be <code>paged</code>, not <code>page</code>. The <strong>value</strong> to the <code>paged</code> parameter/argument should be <code>page</code> for static front pages and <code>paged</code> for all other pages</p></li>\n</ul>\n\n<p>You can rewrite your method above as follow: (<em>CAVEAT: Untested</em>)</p>\n\n<pre><code>public function renderPosts( $atts ) \n{\n $attributes = shortcode_atts( array(\n 'foo' =&gt; 5, //default of 5\n 'include' =&gt; 'news-views', // Currently news and views.\n 'exclude' =&gt; 'game-library' // Exclude this category\n ), $atts);\n\n /* \n * For getting the Query variable on a static front page, you have\n * to use 'page' and not 'paged'. Weird.\n */ \n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n /*\n * Args for the custom query\n */\n $query_args = array(\n 'posts_per_page' =&gt; intval($attributes['foo']),\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['include'] ) ),\n 'include_children' =&gt; false\n ),\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ),\n 'operator' =&gt; 'NOT IN'\n )\n ),\n 'paged' =&gt; $paged\n );\n\n $custom_query = new WP_Query($query_args); \n\n $output = '';\n if ( $custom_query-&gt;have_posts() ) { \n\n $output .= '&lt;div id=\"blogroll\"&gt;'; \n\n while ( $custom_query-&gt;have_posts() ) { \n\n $custom_query-&gt;the_post();\n\n $output .= \"&lt;div class='home_post col span_12 clear-both'&gt;\";\n $output .= \"&lt;div class='col span_3'&gt;&lt;a href='\" . get_the_permalink() . \"'&gt;\" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . \"&lt;/a&gt;&lt;/div&gt;\";\n $output .= \"&lt;div class='col span_9 col_last right-edge'&gt;\";\n $output .= \"&lt;h2 class='home_post_header'&gt;\";\n $output .= '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . \"&lt;/a&gt;\";\n $output .= \"&lt;/h2&gt;\";\n $output .= get_the_excerpt();\n $output .= '&lt;a class=\"home-more-link\" href=\"' . get_the_permalink() . '\"&gt;&lt;span class=\"continue-reading\"&gt;Read More&lt;/span&gt;&lt;/a&gt;';\n $output .= \"&lt;/div&gt;\";\n $output .= \"&lt;/div&gt;\";\n\n }\n\n wp_reset_postdata();\n\n $output .= '&lt;div id=\"pagination\" class=\"blogroll-pagination\"&gt;' . home_pagination( $custom_query ) . '&lt;/div&gt;&lt;/div&gt;';\n\n }\n\n return $output; \n}\n</code></pre>\n\n<p>Just remember, the I have changed the attributes for readability, <code>include</code> takes a comma separated string of category <strong>slugs</strong> (<em><code>include='slug-1, slug-2'</code></em>). This attribute will be used to include categories. <code>exclude</code> works the same (<em><code>exclude='slug-1, slug-2'</code></em>), except that it takes a comma separated string of category <strong>slugs</strong></p>\n\n<h2>EDIT</h2>\n\n<p>I have tested my code and fixed a couple of small bugs. It works as expected if I just create a normal shortcode from it.</p>\n\n<h2>PROOF OF CONCEPT - SHORTCODE</h2>\n\n<pre><code>add_shortcode( 'testcode', function ( $atts )\n{\n $attributes = shortcode_atts( array(\n 'foo' =&gt; 5, //default of 5\n 'include' =&gt; 'news-views', // Currently news and views.\n 'exclude' =&gt; 'game-library' // Exclude this category\n ), $atts);\n\n /* \n * For getting the Query variable on a static front page, you have\n * to use 'page' and not 'paged'. Weird.\n */ \n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n /*\n * Args for the custom query\n */\n $query_args = array(\n 'posts_per_page' =&gt; intval($attributes['foo']),\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['include'] ) ),\n 'include_children' =&gt; false\n ),\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ),\n 'operator' =&gt; 'NOT IN'\n )\n ),\n 'paged' =&gt; $paged\n );\n\n $custom_query = new WP_Query($query_args); \n\n $output = '';\n if ( $custom_query-&gt;have_posts() ) { \n\n $output .= '&lt;div id=\"blogroll\"&gt;'; \n\n while ( $custom_query-&gt;have_posts() ) { \n\n $custom_query-&gt;the_post();\n\n $output .= \"&lt;div class='home_post col span_12 clear-both'&gt;\";\n $output .= \"&lt;div class='col span_3'&gt;&lt;a href='\" . get_the_permalink() . \"'&gt;\" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . \"&lt;/a&gt;&lt;/div&gt;\";\n $output .= \"&lt;div class='col span_9 col_last right-edge'&gt;\";\n $output .= \"&lt;h2 class='home_post_header'&gt;\";\n $output .= '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . \"&lt;/a&gt;\";\n $output .= \"&lt;/h2&gt;\";\n $output .= get_the_excerpt();\n $output .= '&lt;a class=\"home-more-link\" href=\"' . get_the_permalink() . '\"&gt;&lt;span class=\"continue-reading\"&gt;Read More&lt;/span&gt;&lt;/a&gt;';\n $output .= \"&lt;/div&gt;\";\n $output .= \"&lt;/div&gt;\";\n\n }\n\n wp_reset_postdata();\n\n $output .= '&lt;div id=\"pagination\" class=\"blogroll-pagination\"&gt;' . home_pagination( $custom_query ) . '&lt;/div&gt;&lt;/div&gt;';\n\n }\n\n return $output; \n});\n</code></pre>\n\n<p>which I use as follow</p>\n\n<pre><code>[testcode include='testslug-1, testslug-2' exclude='testslug-3, testslug-4']\n</code></pre>\n\n<p>I have tested your pagination function as well and that also works as expected. </p>\n\n<pre><code>function home_pagination( $query = null ) \n{\n\n $big = 999999999; // need an unlikely integer\n\n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n $pagination = paginate_links( \n array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; $paged,\n 'total' =&gt; $query-&gt;max_num_pages,\n 'prev_text' =&gt; '&amp;laquo; Previous',\n 'next_text' =&gt; 'Next &amp;raquo;',\n ) \n );\n\n return $pagination;\n\n} \n</code></pre>\n\n<h2>EDIT 2</h2>\n\n<p>Frm your comments, and as I have already stated, static front pages and single pages uses <code>get_query_var( 'page' )</code> for pagination while all the other uses <code>get_query_var( 'paged' )</code>. I have updated all the code above with the following</p>\n\n<pre><code>if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n} elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n} else { \n $paged = 1; \n}\n</code></pre>\n\n<p>This will sort the problem with <code>page</code> and <code>paged</code> and make your shortcode and pagination work across all pages without any specific changes made to it</p>\n\n<h2>EDIT 3</h2>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/63842/31545\">Here is a sligtly modified version of the code by @ChipBennet</a> which will sort the problem of <code>/page/2</code></p>\n\n<pre><code>function home_pagination( $query = null ) \n{\n global $wp_rewrite;\n\n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n $pagination = array( \n 'base' =&gt; @add_query_arg( 'paged', '%#%' ),\n 'format' =&gt; '',\n 'current' =&gt; $paged,\n 'total' =&gt; $query-&gt;max_num_pages,\n 'prev_text' =&gt; '&amp;laquo; Previous',\n 'next_text' =&gt; 'Next &amp;raquo;',\n );\n\n if ( $wp_rewrite-&gt;using_permalinks() )\n $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ).'/%#%/', '' );\n\n if ( ! empty( $wp_query-&gt;query_vars['s'] ) )\n $pagination['add_args'] = array( 's' =&gt; get_query_var( 's' ) );\n\n return paginate_links( $pagination );\n} \n</code></pre>\n" }, { "answer_id": 185824, "author": "Vikram", "author_id": 35612, "author_profile": "https://wordpress.stackexchange.com/users/35612", "pm_score": 0, "selected": false, "text": "<p>According to the <a href=\"https://codex.wordpress.org/Pagination#static_front_page\" rel=\"nofollow\">codex</a></p>\n\n<p>If the pagination is broken on a static front page you have to add the \"paged\" parameter this way: </p>\n\n<pre><code>if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }\nelseif ( get_query_var('page') ) { $paged = get_query_var('page'); }\nelse { $paged = 1; }\n\nquery_posts('posts_per_page=3&amp;paged=' . $paged); \n</code></pre>\n\n<p>Page parameter is changed to Paged, update function code as follows </p>\n\n<pre><code>public function renderPosts( $atts, $content = null ) {\n global $post;\n setup_postdata($post);\n\n extract( shortcode_atts( array(\n 'foo' =&gt; 5, //default of 5\n 'categoryslug' =&gt; 'news-views' // Currently news and views.\n ), $atts) );\n\n // For getting the Query variable on a statcci front page, you have\n // to use 'page' and not 'paged'. Weird. \n $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n\n\n // Two things needed: Not using the game library,\n // Definitely using the supplied slug.\n // These are two objects.\n\n $dontUse = get_category_by_slug('game-library');\n $catUsed = get_category_by_slug($atts-&gt;categoryslug);\n\n // Args for the custom query\n $query_args = array(\n 'posts_per_page' =&gt; intval($foo),\n 'category__not_in' =&gt; $dontUse-&gt;term_id,\n 'cat' =&gt; $catUsed-&gt;term_id,\n 'paged' =&gt; $paged\n );\n\n $custom_query = new WP_Query($query_args); \n\n $output = '&lt;div id=\"blogroll\"&gt;'; \n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n\n $output .= \"&lt;div class='home_post col span_12 clear-both'&gt;\";\n $output .= \"&lt;div class='col span_3'&gt;&lt;a href='\" . get_the_permalink() . \"'&gt;\" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . \"&lt;/a&gt;&lt;/div&gt;\";\n $output .= \"&lt;div class='col span_9 col_last right-edge'&gt;\";\n $output .= \"&lt;h2 class='home_post_header'&gt;\";\n $output .= '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . \"&lt;/a&gt;\";\n $output .= \"&lt;/h2&gt;\";\n $output .= get_the_excerpt();\n $output .= '&lt;a class=\"home-more-link\" href=\"' . get_the_permalink() . '\"&gt;&lt;span class=\"continue-reading\"&gt;Read More&lt;/span&gt;&lt;/a&gt;';\n $output .= \"&lt;/div&gt;\";\n $output .= \"&lt;/div&gt;\";\n\n endwhile;\n\n wp_reset_postdata();\n\n // Pagination not working, but it outputs just fine?\n $output .= '&lt;div id=\"pagination\" class=\"blogroll-pagination\"&gt;' . home_pagination($custom_query) . '&lt;/div&gt;&lt;/div&gt;';\n wp_reset_query(); \n\n return $output; \n }\n</code></pre>\n" }, { "answer_id": 185932, "author": "Touqeer Shafi", "author_id": 63430, "author_profile": "https://wordpress.stackexchange.com/users/63430", "pm_score": -1, "selected": false, "text": "<p>Well if i need to use Pagination i will go with <a href=\"https://wordpress.org/plugins/wp-pagenavi/\" rel=\"nofollow\">WP-PageNavi</a> plugin.</p>\n\n<pre><code>$paged = get_query_var('paged') ? get_query_var('paged') : 1;\n$args = array('post_type' =&gt; 'post', 'posts_per_page' =&gt; 5, 'paged' =&gt; $paged);\n$loop = new WP_Query( $args );\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n\n // Your Custom Loop Code Here\n\nendwhile; ?&gt;\n\n&lt;?php wp_pagenavi( array( 'query' =&gt; $loop ) ); ?&gt;\n</code></pre>\n\n<p>WP-PageNavi will render pagination according to your query.</p>\n" } ]
2015/04/23
[ "https://wordpress.stackexchange.com/questions/185075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71045/" ]
For the past two days I've been trying to debug an issue with `WP_Query()` and Pagination. A website I'm a dev for uses a Wordpress theme (Salient by ThemeNectar) that includes the visual composer plugin. My job is essentially to make sure the site is just functional, so a while ago I wrote an extension for the visual composer. This extension uses `WP_Query()` to create a new query, looks for posts in specific categories (with a default established), and then returns the output of that query Here's the code that renders posts and pagination inside that visual composer component ``` public function renderPosts( $atts, $content = null ) { global $post; setup_postdata($post); extract( shortcode_atts( array( 'foo' => 5, //default of 5 'categoryslug' => 'news-views' // Currently news and views. ), $atts) ); // For getting the Query variable on a statcci front page, you have // to use 'page' and not 'paged'. Weird. $paged = ( get_query_var('page') ) ? get_query_var('page') : 1; // Two things needed: Not using the game library, // Definitely using the supplied slug. // These are two objects. $dontUse = get_category_by_slug('game-library'); $catUsed = get_category_by_slug($atts->categoryslug); // Args for the custom query $query_args = array( 'posts_per_page' => intval($foo), 'category__not_in' => $dontUse->term_id, 'cat' => $catUsed->term_id, 'page' => $paged ); $custom_query = new WP_Query($query_args); $output = '<div id="blogroll">'; while ( $custom_query->have_posts() ) : $custom_query->the_post(); $output .= "<div class='home_post col span_12 clear-both'>"; $output .= "<div class='col span_3'><a href='" . get_the_permalink() . "'>" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . "</a></div>"; $output .= "<div class='col span_9 col_last right-edge'>"; $output .= "<h2 class='home_post_header'>"; $output .= '<a href="' . get_the_permalink() . '">' . get_the_title() . "</a>"; $output .= "</h2>"; $output .= get_the_excerpt(); $output .= '<a class="home-more-link" href="' . get_the_permalink() . '"><span class="continue-reading">Read More</span></a>'; $output .= "</div>"; $output .= "</div>"; endwhile; wp_reset_postdata(); // Pagination not working, but it outputs just fine? $output .= '<div id="pagination" class="blogroll-pagination">' . home_pagination($custom_query) . '</div></div>'; wp_reset_query(); return $output; } ``` Now, I'm aware that the code to generate the content is just a giant concatenated string, but it's only because the extension function has to return something. At the very end, I output pagination with use of another function defined above. [Here's the function](http://pastebin.com/Cb4uL0d5) I've created called `home_pagination(query)` ``` function home_pagination($query = null) { /*if ( !$query ) { global $wp_query; $query = $wp_query; } commented out because do I need this? */ $big = 999999999; // need an unlikely integer $pagination = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var( 'page' ) ), 'total' => $query->max_num_pages, 'prev_text' => '&laquo; Previous', 'next_text' => 'Next &raquo;', ) ); return $pagination; } ``` Now, this was functioning not a week ago but I can't seem to get it to work now... Here's what I've tried: 1. Playing around with `get_query_var('page')` 2. Using a plugin (Wp\_page\_navi) 3. Changing where and when `wp_reset_postdata()` and `wp_reset_query()` are used 4. Using the `max_num_pages` workaround for `next_posts_link()` and `previous_posts_link()` This is on a **static front page** and I'm aware that the rules are different with 'page' and 'paged' **Interesting to note**: When I change the 'paged' variable in the query args, it returns the proper corresponding page. I'm trying to figure out why the pagination I'm outputting as a part of this query is doing ABSOLUTELY NOTHING when I try to navigate with it? It's as if it wants to navigate to /page/2 or whichever number, but then immediately redirects to the site itself... I'm considering not putting the `paginate_links()` call in a separate function. There are probably glaring mistakes, but I've been grinding away at pagination that no longer seems to work. Any ideas on how I can best approach this? Is there something huge I'm missing?
I'm not quite sure what do you mean by you have extended the visual composer, but I do have a couple of concerns here. * [SoC](http://en.m.wikipedia.org/wiki/Separation_of_concerns) -> From your code I detect that you are using a shortcode, which should have its own separate class. You should not extend the class to the visual editor (*at least this is how I read your question*). Classes should never multi task, they should do **one** single duty. This keeps your class extentable, short, easy to maintain and reusable and easy to test * Extending the previous point, front end and back end functionalities should not be mixed * I don't see the usefulness of using `global $post` and setting up post data. Doing this and not resetting postdata afterwards will have unexpected influences on any query afterwards and on the main query. You should drop that completely * Never ever use `extract()` in shortcodes ( and any other function for that matter ). It is very unrealiable and untestable and leads to unexpected output. This makes it extremely hard to debug in case of failures. For this very reason, it was completely removed from core. See [trac ticket 22400](https://core.trac.wordpress.org/ticket/22400) * Because you are using multiple category conditions, and to make it more dynamic, I would rather use a `tax_query` to handle the conditions. The big plus here would be that you will save on db calls as you can get rid of `get_category_by_slug` * There is no need for `wp_reset_query()`. This is used with `query_posts` which you should never ever use. It is a page breaker. * Front pages and single pages uses the query variable `page` (`get_query_var( 'page' )`) for pagination, and not `paged` (`get_query_var( 'paged' )`) as other pages. The query argument for `WP_Query` for both however is the same, it should be `paged`, not `page`. The **value** to the `paged` parameter/argument should be `page` for static front pages and `paged` for all other pages You can rewrite your method above as follow: (*CAVEAT: Untested*) ``` public function renderPosts( $atts ) { $attributes = shortcode_atts( array( 'foo' => 5, //default of 5 'include' => 'news-views', // Currently news and views. 'exclude' => 'game-library' // Exclude this category ), $atts); /* * For getting the Query variable on a static front page, you have * to use 'page' and not 'paged'. Weird. */ if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } /* * Args for the custom query */ $query_args = array( 'posts_per_page' => intval($attributes['foo']), 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['include'] ) ), 'include_children' => false ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ), 'operator' => 'NOT IN' ) ), 'paged' => $paged ); $custom_query = new WP_Query($query_args); $output = ''; if ( $custom_query->have_posts() ) { $output .= '<div id="blogroll">'; while ( $custom_query->have_posts() ) { $custom_query->the_post(); $output .= "<div class='home_post col span_12 clear-both'>"; $output .= "<div class='col span_3'><a href='" . get_the_permalink() . "'>" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . "</a></div>"; $output .= "<div class='col span_9 col_last right-edge'>"; $output .= "<h2 class='home_post_header'>"; $output .= '<a href="' . get_the_permalink() . '">' . get_the_title() . "</a>"; $output .= "</h2>"; $output .= get_the_excerpt(); $output .= '<a class="home-more-link" href="' . get_the_permalink() . '"><span class="continue-reading">Read More</span></a>'; $output .= "</div>"; $output .= "</div>"; } wp_reset_postdata(); $output .= '<div id="pagination" class="blogroll-pagination">' . home_pagination( $custom_query ) . '</div></div>'; } return $output; } ``` Just remember, the I have changed the attributes for readability, `include` takes a comma separated string of category **slugs** (*`include='slug-1, slug-2'`*). This attribute will be used to include categories. `exclude` works the same (*`exclude='slug-1, slug-2'`*), except that it takes a comma separated string of category **slugs** EDIT ---- I have tested my code and fixed a couple of small bugs. It works as expected if I just create a normal shortcode from it. PROOF OF CONCEPT - SHORTCODE ---------------------------- ``` add_shortcode( 'testcode', function ( $atts ) { $attributes = shortcode_atts( array( 'foo' => 5, //default of 5 'include' => 'news-views', // Currently news and views. 'exclude' => 'game-library' // Exclude this category ), $atts); /* * For getting the Query variable on a static front page, you have * to use 'page' and not 'paged'. Weird. */ if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } /* * Args for the custom query */ $query_args = array( 'posts_per_page' => intval($attributes['foo']), 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['include'] ) ), 'include_children' => false ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ), 'operator' => 'NOT IN' ) ), 'paged' => $paged ); $custom_query = new WP_Query($query_args); $output = ''; if ( $custom_query->have_posts() ) { $output .= '<div id="blogroll">'; while ( $custom_query->have_posts() ) { $custom_query->the_post(); $output .= "<div class='home_post col span_12 clear-both'>"; $output .= "<div class='col span_3'><a href='" . get_the_permalink() . "'>" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . "</a></div>"; $output .= "<div class='col span_9 col_last right-edge'>"; $output .= "<h2 class='home_post_header'>"; $output .= '<a href="' . get_the_permalink() . '">' . get_the_title() . "</a>"; $output .= "</h2>"; $output .= get_the_excerpt(); $output .= '<a class="home-more-link" href="' . get_the_permalink() . '"><span class="continue-reading">Read More</span></a>'; $output .= "</div>"; $output .= "</div>"; } wp_reset_postdata(); $output .= '<div id="pagination" class="blogroll-pagination">' . home_pagination( $custom_query ) . '</div></div>'; } return $output; }); ``` which I use as follow ``` [testcode include='testslug-1, testslug-2' exclude='testslug-3, testslug-4'] ``` I have tested your pagination function as well and that also works as expected. ``` function home_pagination( $query = null ) { $big = 999999999; // need an unlikely integer if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $pagination = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => $paged, 'total' => $query->max_num_pages, 'prev_text' => '&laquo; Previous', 'next_text' => 'Next &raquo;', ) ); return $pagination; } ``` EDIT 2 ------ Frm your comments, and as I have already stated, static front pages and single pages uses `get_query_var( 'page' )` for pagination while all the other uses `get_query_var( 'paged' )`. I have updated all the code above with the following ``` if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } ``` This will sort the problem with `page` and `paged` and make your shortcode and pagination work across all pages without any specific changes made to it EDIT 3 ------ [Here is a sligtly modified version of the code by @ChipBennet](https://wordpress.stackexchange.com/a/63842/31545) which will sort the problem of `/page/2` ``` function home_pagination( $query = null ) { global $wp_rewrite; if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $pagination = array( 'base' => @add_query_arg( 'paged', '%#%' ), 'format' => '', 'current' => $paged, 'total' => $query->max_num_pages, 'prev_text' => '&laquo; Previous', 'next_text' => 'Next &raquo;', ); if ( $wp_rewrite->using_permalinks() ) $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ).'/%#%/', '' ); if ( ! empty( $wp_query->query_vars['s'] ) ) $pagination['add_args'] = array( 's' => get_query_var( 's' ) ); return paginate_links( $pagination ); } ```
185,115
<p>I am trying to add pagination for my Archive. I want to show 12 posts per page and then show the 'next' / 'previous' buttons.</p> <p>When I manually change the value of the $paged variable, the 1 into a 2 it works. When I click the Next button on the archive page, it loads a very weird theme page. The url looks like: '/page/2/'. </p> <p>What am I doing wrong?</p> <p>This is the code I wrote so far: </p> <pre><code>&lt;?php global $paged,$wp_query; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; 'realisaties', 'posts_per_page' =&gt; 12, 'paged' =&gt; $paged, 'order' =&gt; 'ASC' ); $archive_query = new WP_Query($args); while ($archive_query-&gt;have_posts()) : $archive_query-&gt;the_post(); $image = get_field('preview_afbeelding'); if( !empty($image) ): $url = $image['url']; $title = $image['title']; $alt = $image['alt']; $caption = $image['caption']; // thumbnail $size = 'medium'; $thumb = $image['sizes'][ $size ]; $width = $image['sizes'][ $size . '-width' ]; $height = $image['sizes'][ $size . '-height' ]; if( $caption ): ?&gt; &lt;div class="wp-caption"&gt; &lt;?php endif; ?&gt; &lt;div class="col-md-3"&gt; &lt;?php echo get_the_title(); ?&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php echo $title; ?&gt;"&gt; &lt;img class="realisatie-img img-responsive" src="&lt;?php echo $thumb; ?&gt;" alt="&lt;?php echo $alt; ?&gt;" title="" width="&lt;?php echo $width; ?&gt;" height="&lt;?php echo $height; ?&gt;" /&gt; &lt;br /&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php if( $caption ): ?&gt; &lt;h2&gt; &lt;?php echo get_the_title(); ?&gt;&lt;/h2&gt; &lt;p class="wp-caption-text"&gt;&lt;?php echo $caption; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endif; endif; endwhile; ?&gt; &lt;?php next_posts_link('Older Entries »', $archive_query-&gt;max_num_pages); ?&gt; &lt;?php previous_posts_link('Newer Entries', $archive_query-&gt;max_num_pages); ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 185775, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>I'm not quite sure what do you mean by you have extended the visual composer, but I do have a couple of concerns here.</p>\n\n<ul>\n<li><p><a href=\"http://en.m.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">SoC</a> -> From your code I detect that you are using a shortcode, which should have its own separate class. You should not extend the class to the visual editor (<em>at least this is how I read your question</em>). Classes should never multi task, they should do <strong>one</strong> single duty. This keeps your class extentable, short, easy to maintain and reusable and easy to test</p></li>\n<li><p>Extending the previous point, front end and back end functionalities should not be mixed</p></li>\n<li><p>I don't see the usefulness of using <code>global $post</code> and setting up post data. Doing this and not resetting postdata afterwards will have unexpected influences on any query afterwards and on the main query. You should drop that completely</p></li>\n<li><p>Never ever use <code>extract()</code> in shortcodes ( and any other function for that matter ). It is very unrealiable and untestable and leads to unexpected output. This makes it extremely hard to debug in case of failures. For this very reason, it was completely removed from core. See <a href=\"https://core.trac.wordpress.org/ticket/22400\" rel=\"nofollow noreferrer\">trac ticket 22400</a></p></li>\n<li><p>Because you are using multiple category conditions, and to make it more dynamic, I would rather use a <code>tax_query</code> to handle the conditions. The big plus here would be that you will save on db calls as you can get rid of <code>get_category_by_slug</code></p></li>\n<li><p>There is no need for <code>wp_reset_query()</code>. This is used with <code>query_posts</code> which you should never ever use. It is a page breaker.</p></li>\n<li><p>Front pages and single pages uses the query variable <code>page</code> (<code>get_query_var( 'page' )</code>) for pagination, and not <code>paged</code> (<code>get_query_var( 'paged' )</code>) as other pages. The query argument for <code>WP_Query</code> for both however is the same, it should be <code>paged</code>, not <code>page</code>. The <strong>value</strong> to the <code>paged</code> parameter/argument should be <code>page</code> for static front pages and <code>paged</code> for all other pages</p></li>\n</ul>\n\n<p>You can rewrite your method above as follow: (<em>CAVEAT: Untested</em>)</p>\n\n<pre><code>public function renderPosts( $atts ) \n{\n $attributes = shortcode_atts( array(\n 'foo' =&gt; 5, //default of 5\n 'include' =&gt; 'news-views', // Currently news and views.\n 'exclude' =&gt; 'game-library' // Exclude this category\n ), $atts);\n\n /* \n * For getting the Query variable on a static front page, you have\n * to use 'page' and not 'paged'. Weird.\n */ \n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n /*\n * Args for the custom query\n */\n $query_args = array(\n 'posts_per_page' =&gt; intval($attributes['foo']),\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['include'] ) ),\n 'include_children' =&gt; false\n ),\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ),\n 'operator' =&gt; 'NOT IN'\n )\n ),\n 'paged' =&gt; $paged\n );\n\n $custom_query = new WP_Query($query_args); \n\n $output = '';\n if ( $custom_query-&gt;have_posts() ) { \n\n $output .= '&lt;div id=\"blogroll\"&gt;'; \n\n while ( $custom_query-&gt;have_posts() ) { \n\n $custom_query-&gt;the_post();\n\n $output .= \"&lt;div class='home_post col span_12 clear-both'&gt;\";\n $output .= \"&lt;div class='col span_3'&gt;&lt;a href='\" . get_the_permalink() . \"'&gt;\" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . \"&lt;/a&gt;&lt;/div&gt;\";\n $output .= \"&lt;div class='col span_9 col_last right-edge'&gt;\";\n $output .= \"&lt;h2 class='home_post_header'&gt;\";\n $output .= '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . \"&lt;/a&gt;\";\n $output .= \"&lt;/h2&gt;\";\n $output .= get_the_excerpt();\n $output .= '&lt;a class=\"home-more-link\" href=\"' . get_the_permalink() . '\"&gt;&lt;span class=\"continue-reading\"&gt;Read More&lt;/span&gt;&lt;/a&gt;';\n $output .= \"&lt;/div&gt;\";\n $output .= \"&lt;/div&gt;\";\n\n }\n\n wp_reset_postdata();\n\n $output .= '&lt;div id=\"pagination\" class=\"blogroll-pagination\"&gt;' . home_pagination( $custom_query ) . '&lt;/div&gt;&lt;/div&gt;';\n\n }\n\n return $output; \n}\n</code></pre>\n\n<p>Just remember, the I have changed the attributes for readability, <code>include</code> takes a comma separated string of category <strong>slugs</strong> (<em><code>include='slug-1, slug-2'</code></em>). This attribute will be used to include categories. <code>exclude</code> works the same (<em><code>exclude='slug-1, slug-2'</code></em>), except that it takes a comma separated string of category <strong>slugs</strong></p>\n\n<h2>EDIT</h2>\n\n<p>I have tested my code and fixed a couple of small bugs. It works as expected if I just create a normal shortcode from it.</p>\n\n<h2>PROOF OF CONCEPT - SHORTCODE</h2>\n\n<pre><code>add_shortcode( 'testcode', function ( $atts )\n{\n $attributes = shortcode_atts( array(\n 'foo' =&gt; 5, //default of 5\n 'include' =&gt; 'news-views', // Currently news and views.\n 'exclude' =&gt; 'game-library' // Exclude this category\n ), $atts);\n\n /* \n * For getting the Query variable on a static front page, you have\n * to use 'page' and not 'paged'. Weird.\n */ \n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n /*\n * Args for the custom query\n */\n $query_args = array(\n 'posts_per_page' =&gt; intval($attributes['foo']),\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['include'] ) ),\n 'include_children' =&gt; false\n ),\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ),\n 'operator' =&gt; 'NOT IN'\n )\n ),\n 'paged' =&gt; $paged\n );\n\n $custom_query = new WP_Query($query_args); \n\n $output = '';\n if ( $custom_query-&gt;have_posts() ) { \n\n $output .= '&lt;div id=\"blogroll\"&gt;'; \n\n while ( $custom_query-&gt;have_posts() ) { \n\n $custom_query-&gt;the_post();\n\n $output .= \"&lt;div class='home_post col span_12 clear-both'&gt;\";\n $output .= \"&lt;div class='col span_3'&gt;&lt;a href='\" . get_the_permalink() . \"'&gt;\" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . \"&lt;/a&gt;&lt;/div&gt;\";\n $output .= \"&lt;div class='col span_9 col_last right-edge'&gt;\";\n $output .= \"&lt;h2 class='home_post_header'&gt;\";\n $output .= '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . \"&lt;/a&gt;\";\n $output .= \"&lt;/h2&gt;\";\n $output .= get_the_excerpt();\n $output .= '&lt;a class=\"home-more-link\" href=\"' . get_the_permalink() . '\"&gt;&lt;span class=\"continue-reading\"&gt;Read More&lt;/span&gt;&lt;/a&gt;';\n $output .= \"&lt;/div&gt;\";\n $output .= \"&lt;/div&gt;\";\n\n }\n\n wp_reset_postdata();\n\n $output .= '&lt;div id=\"pagination\" class=\"blogroll-pagination\"&gt;' . home_pagination( $custom_query ) . '&lt;/div&gt;&lt;/div&gt;';\n\n }\n\n return $output; \n});\n</code></pre>\n\n<p>which I use as follow</p>\n\n<pre><code>[testcode include='testslug-1, testslug-2' exclude='testslug-3, testslug-4']\n</code></pre>\n\n<p>I have tested your pagination function as well and that also works as expected. </p>\n\n<pre><code>function home_pagination( $query = null ) \n{\n\n $big = 999999999; // need an unlikely integer\n\n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n $pagination = paginate_links( \n array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; $paged,\n 'total' =&gt; $query-&gt;max_num_pages,\n 'prev_text' =&gt; '&amp;laquo; Previous',\n 'next_text' =&gt; 'Next &amp;raquo;',\n ) \n );\n\n return $pagination;\n\n} \n</code></pre>\n\n<h2>EDIT 2</h2>\n\n<p>Frm your comments, and as I have already stated, static front pages and single pages uses <code>get_query_var( 'page' )</code> for pagination while all the other uses <code>get_query_var( 'paged' )</code>. I have updated all the code above with the following</p>\n\n<pre><code>if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n} elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n} else { \n $paged = 1; \n}\n</code></pre>\n\n<p>This will sort the problem with <code>page</code> and <code>paged</code> and make your shortcode and pagination work across all pages without any specific changes made to it</p>\n\n<h2>EDIT 3</h2>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/63842/31545\">Here is a sligtly modified version of the code by @ChipBennet</a> which will sort the problem of <code>/page/2</code></p>\n\n<pre><code>function home_pagination( $query = null ) \n{\n global $wp_rewrite;\n\n if ( get_query_var('paged') ) {\n $paged = get_query_var('paged'); \n } elseif ( get_query_var('page') ) { \n $paged = get_query_var('page'); \n } else { \n $paged = 1; \n }\n\n\n $pagination = array( \n 'base' =&gt; @add_query_arg( 'paged', '%#%' ),\n 'format' =&gt; '',\n 'current' =&gt; $paged,\n 'total' =&gt; $query-&gt;max_num_pages,\n 'prev_text' =&gt; '&amp;laquo; Previous',\n 'next_text' =&gt; 'Next &amp;raquo;',\n );\n\n if ( $wp_rewrite-&gt;using_permalinks() )\n $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ).'/%#%/', '' );\n\n if ( ! empty( $wp_query-&gt;query_vars['s'] ) )\n $pagination['add_args'] = array( 's' =&gt; get_query_var( 's' ) );\n\n return paginate_links( $pagination );\n} \n</code></pre>\n" }, { "answer_id": 185824, "author": "Vikram", "author_id": 35612, "author_profile": "https://wordpress.stackexchange.com/users/35612", "pm_score": 0, "selected": false, "text": "<p>According to the <a href=\"https://codex.wordpress.org/Pagination#static_front_page\" rel=\"nofollow\">codex</a></p>\n\n<p>If the pagination is broken on a static front page you have to add the \"paged\" parameter this way: </p>\n\n<pre><code>if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }\nelseif ( get_query_var('page') ) { $paged = get_query_var('page'); }\nelse { $paged = 1; }\n\nquery_posts('posts_per_page=3&amp;paged=' . $paged); \n</code></pre>\n\n<p>Page parameter is changed to Paged, update function code as follows </p>\n\n<pre><code>public function renderPosts( $atts, $content = null ) {\n global $post;\n setup_postdata($post);\n\n extract( shortcode_atts( array(\n 'foo' =&gt; 5, //default of 5\n 'categoryslug' =&gt; 'news-views' // Currently news and views.\n ), $atts) );\n\n // For getting the Query variable on a statcci front page, you have\n // to use 'page' and not 'paged'. Weird. \n $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n\n\n // Two things needed: Not using the game library,\n // Definitely using the supplied slug.\n // These are two objects.\n\n $dontUse = get_category_by_slug('game-library');\n $catUsed = get_category_by_slug($atts-&gt;categoryslug);\n\n // Args for the custom query\n $query_args = array(\n 'posts_per_page' =&gt; intval($foo),\n 'category__not_in' =&gt; $dontUse-&gt;term_id,\n 'cat' =&gt; $catUsed-&gt;term_id,\n 'paged' =&gt; $paged\n );\n\n $custom_query = new WP_Query($query_args); \n\n $output = '&lt;div id=\"blogroll\"&gt;'; \n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n\n $output .= \"&lt;div class='home_post col span_12 clear-both'&gt;\";\n $output .= \"&lt;div class='col span_3'&gt;&lt;a href='\" . get_the_permalink() . \"'&gt;\" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . \"&lt;/a&gt;&lt;/div&gt;\";\n $output .= \"&lt;div class='col span_9 col_last right-edge'&gt;\";\n $output .= \"&lt;h2 class='home_post_header'&gt;\";\n $output .= '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . \"&lt;/a&gt;\";\n $output .= \"&lt;/h2&gt;\";\n $output .= get_the_excerpt();\n $output .= '&lt;a class=\"home-more-link\" href=\"' . get_the_permalink() . '\"&gt;&lt;span class=\"continue-reading\"&gt;Read More&lt;/span&gt;&lt;/a&gt;';\n $output .= \"&lt;/div&gt;\";\n $output .= \"&lt;/div&gt;\";\n\n endwhile;\n\n wp_reset_postdata();\n\n // Pagination not working, but it outputs just fine?\n $output .= '&lt;div id=\"pagination\" class=\"blogroll-pagination\"&gt;' . home_pagination($custom_query) . '&lt;/div&gt;&lt;/div&gt;';\n wp_reset_query(); \n\n return $output; \n }\n</code></pre>\n" }, { "answer_id": 185932, "author": "Touqeer Shafi", "author_id": 63430, "author_profile": "https://wordpress.stackexchange.com/users/63430", "pm_score": -1, "selected": false, "text": "<p>Well if i need to use Pagination i will go with <a href=\"https://wordpress.org/plugins/wp-pagenavi/\" rel=\"nofollow\">WP-PageNavi</a> plugin.</p>\n\n<pre><code>$paged = get_query_var('paged') ? get_query_var('paged') : 1;\n$args = array('post_type' =&gt; 'post', 'posts_per_page' =&gt; 5, 'paged' =&gt; $paged);\n$loop = new WP_Query( $args );\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n\n // Your Custom Loop Code Here\n\nendwhile; ?&gt;\n\n&lt;?php wp_pagenavi( array( 'query' =&gt; $loop ) ); ?&gt;\n</code></pre>\n\n<p>WP-PageNavi will render pagination according to your query.</p>\n" } ]
2015/04/23
[ "https://wordpress.stackexchange.com/questions/185115", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49106/" ]
I am trying to add pagination for my Archive. I want to show 12 posts per page and then show the 'next' / 'previous' buttons. When I manually change the value of the $paged variable, the 1 into a 2 it works. When I click the Next button on the archive page, it loads a very weird theme page. The url looks like: '/page/2/'. What am I doing wrong? This is the code I wrote so far: ``` <?php global $paged,$wp_query; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'realisaties', 'posts_per_page' => 12, 'paged' => $paged, 'order' => 'ASC' ); $archive_query = new WP_Query($args); while ($archive_query->have_posts()) : $archive_query->the_post(); $image = get_field('preview_afbeelding'); if( !empty($image) ): $url = $image['url']; $title = $image['title']; $alt = $image['alt']; $caption = $image['caption']; // thumbnail $size = 'medium'; $thumb = $image['sizes'][ $size ]; $width = $image['sizes'][ $size . '-width' ]; $height = $image['sizes'][ $size . '-height' ]; if( $caption ): ?> <div class="wp-caption"> <?php endif; ?> <div class="col-md-3"> <?php echo get_the_title(); ?> <a href="<?php the_permalink() ?>" title="<?php echo $title; ?>"> <img class="realisatie-img img-responsive" src="<?php echo $thumb; ?>" alt="<?php echo $alt; ?>" title="" width="<?php echo $width; ?>" height="<?php echo $height; ?>" /> <br /> </a> </div> <?php if( $caption ): ?> <h2> <?php echo get_the_title(); ?></h2> <p class="wp-caption-text"><?php echo $caption; ?></p> </div> <?php endif; endif; endwhile; ?> <?php next_posts_link('Older Entries »', $archive_query->max_num_pages); ?> <?php previous_posts_link('Newer Entries', $archive_query->max_num_pages); ?> <?php wp_reset_query(); ?> </div> </div> ```
I'm not quite sure what do you mean by you have extended the visual composer, but I do have a couple of concerns here. * [SoC](http://en.m.wikipedia.org/wiki/Separation_of_concerns) -> From your code I detect that you are using a shortcode, which should have its own separate class. You should not extend the class to the visual editor (*at least this is how I read your question*). Classes should never multi task, they should do **one** single duty. This keeps your class extentable, short, easy to maintain and reusable and easy to test * Extending the previous point, front end and back end functionalities should not be mixed * I don't see the usefulness of using `global $post` and setting up post data. Doing this and not resetting postdata afterwards will have unexpected influences on any query afterwards and on the main query. You should drop that completely * Never ever use `extract()` in shortcodes ( and any other function for that matter ). It is very unrealiable and untestable and leads to unexpected output. This makes it extremely hard to debug in case of failures. For this very reason, it was completely removed from core. See [trac ticket 22400](https://core.trac.wordpress.org/ticket/22400) * Because you are using multiple category conditions, and to make it more dynamic, I would rather use a `tax_query` to handle the conditions. The big plus here would be that you will save on db calls as you can get rid of `get_category_by_slug` * There is no need for `wp_reset_query()`. This is used with `query_posts` which you should never ever use. It is a page breaker. * Front pages and single pages uses the query variable `page` (`get_query_var( 'page' )`) for pagination, and not `paged` (`get_query_var( 'paged' )`) as other pages. The query argument for `WP_Query` for both however is the same, it should be `paged`, not `page`. The **value** to the `paged` parameter/argument should be `page` for static front pages and `paged` for all other pages You can rewrite your method above as follow: (*CAVEAT: Untested*) ``` public function renderPosts( $atts ) { $attributes = shortcode_atts( array( 'foo' => 5, //default of 5 'include' => 'news-views', // Currently news and views. 'exclude' => 'game-library' // Exclude this category ), $atts); /* * For getting the Query variable on a static front page, you have * to use 'page' and not 'paged'. Weird. */ if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } /* * Args for the custom query */ $query_args = array( 'posts_per_page' => intval($attributes['foo']), 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['include'] ) ), 'include_children' => false ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ), 'operator' => 'NOT IN' ) ), 'paged' => $paged ); $custom_query = new WP_Query($query_args); $output = ''; if ( $custom_query->have_posts() ) { $output .= '<div id="blogroll">'; while ( $custom_query->have_posts() ) { $custom_query->the_post(); $output .= "<div class='home_post col span_12 clear-both'>"; $output .= "<div class='col span_3'><a href='" . get_the_permalink() . "'>" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . "</a></div>"; $output .= "<div class='col span_9 col_last right-edge'>"; $output .= "<h2 class='home_post_header'>"; $output .= '<a href="' . get_the_permalink() . '">' . get_the_title() . "</a>"; $output .= "</h2>"; $output .= get_the_excerpt(); $output .= '<a class="home-more-link" href="' . get_the_permalink() . '"><span class="continue-reading">Read More</span></a>'; $output .= "</div>"; $output .= "</div>"; } wp_reset_postdata(); $output .= '<div id="pagination" class="blogroll-pagination">' . home_pagination( $custom_query ) . '</div></div>'; } return $output; } ``` Just remember, the I have changed the attributes for readability, `include` takes a comma separated string of category **slugs** (*`include='slug-1, slug-2'`*). This attribute will be used to include categories. `exclude` works the same (*`exclude='slug-1, slug-2'`*), except that it takes a comma separated string of category **slugs** EDIT ---- I have tested my code and fixed a couple of small bugs. It works as expected if I just create a normal shortcode from it. PROOF OF CONCEPT - SHORTCODE ---------------------------- ``` add_shortcode( 'testcode', function ( $atts ) { $attributes = shortcode_atts( array( 'foo' => 5, //default of 5 'include' => 'news-views', // Currently news and views. 'exclude' => 'game-library' // Exclude this category ), $atts); /* * For getting the Query variable on a static front page, you have * to use 'page' and not 'paged'. Weird. */ if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } /* * Args for the custom query */ $query_args = array( 'posts_per_page' => intval($attributes['foo']), 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['include'] ) ), 'include_children' => false ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => explode( ',', str_replace( ' ', '', $attributes['exclude'] ) ), 'operator' => 'NOT IN' ) ), 'paged' => $paged ); $custom_query = new WP_Query($query_args); $output = ''; if ( $custom_query->have_posts() ) { $output .= '<div id="blogroll">'; while ( $custom_query->have_posts() ) { $custom_query->the_post(); $output .= "<div class='home_post col span_12 clear-both'>"; $output .= "<div class='col span_3'><a href='" . get_the_permalink() . "'>" . get_the_post_thumbnail(get_the_ID(), 'home_post_thumb') . "</a></div>"; $output .= "<div class='col span_9 col_last right-edge'>"; $output .= "<h2 class='home_post_header'>"; $output .= '<a href="' . get_the_permalink() . '">' . get_the_title() . "</a>"; $output .= "</h2>"; $output .= get_the_excerpt(); $output .= '<a class="home-more-link" href="' . get_the_permalink() . '"><span class="continue-reading">Read More</span></a>'; $output .= "</div>"; $output .= "</div>"; } wp_reset_postdata(); $output .= '<div id="pagination" class="blogroll-pagination">' . home_pagination( $custom_query ) . '</div></div>'; } return $output; }); ``` which I use as follow ``` [testcode include='testslug-1, testslug-2' exclude='testslug-3, testslug-4'] ``` I have tested your pagination function as well and that also works as expected. ``` function home_pagination( $query = null ) { $big = 999999999; // need an unlikely integer if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $pagination = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => $paged, 'total' => $query->max_num_pages, 'prev_text' => '&laquo; Previous', 'next_text' => 'Next &raquo;', ) ); return $pagination; } ``` EDIT 2 ------ Frm your comments, and as I have already stated, static front pages and single pages uses `get_query_var( 'page' )` for pagination while all the other uses `get_query_var( 'paged' )`. I have updated all the code above with the following ``` if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } ``` This will sort the problem with `page` and `paged` and make your shortcode and pagination work across all pages without any specific changes made to it EDIT 3 ------ [Here is a sligtly modified version of the code by @ChipBennet](https://wordpress.stackexchange.com/a/63842/31545) which will sort the problem of `/page/2` ``` function home_pagination( $query = null ) { global $wp_rewrite; if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $pagination = array( 'base' => @add_query_arg( 'paged', '%#%' ), 'format' => '', 'current' => $paged, 'total' => $query->max_num_pages, 'prev_text' => '&laquo; Previous', 'next_text' => 'Next &raquo;', ); if ( $wp_rewrite->using_permalinks() ) $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ).'/%#%/', '' ); if ( ! empty( $wp_query->query_vars['s'] ) ) $pagination['add_args'] = array( 's' => get_query_var( 's' ) ); return paginate_links( $pagination ); } ```
185,126
<p>I'm creating a form plugin to handle forms that can be hooked into using actions/filters by developers.</p> <p>My plug-in needs to be able to handle different forms with different sets of filters and I see 2 ways of doing this.</p> <h2>Method 1</h2> <p>Fire of specific hooks for each form.</p> <p>So code like this could be called form within my plugin:</p> <pre><code>$formId = 'contact'; $errors = apply_filters('forms_validate_' . $formId, $errors, $data); </code></pre> <p>And could be used like so:</p> <pre><code>add_filter('forms_validate_contact', function($errors, $data){ if(empty($data['name'])){ $errors['name'] = 'Name is required'; } return $errors; } 10, 2) </code></pre> <h2>Method 2</h2> <p>Pass a parameter to the calling function.</p> <p>So code like this could be called form within my plugin:</p> <pre><code>$formId = 'contact'; $errors = apply_filters('forms_validate', $formId, $errors, $data); </code></pre> <p>And could be used like so:</p> <pre><code>add_filter('forms_validate', function($formId, $error, $data){ switch($formId){ case 'contact': if(empty($data['name'])){ $errors['name'] = 'Name is required'; } break; } return $errors; }, 10, 3) </code></pre> <hr> <p>Are there any examples in the WordPress core where this sort of issue is tackled?</p> <p>Is there a preferred method of dealing with this?</p>
[ { "answer_id": 185127, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>Make the hook name specific to what it does, not where it is called. Do not pass multiple parameters, because that is not easy to extend. Pass a parameter object instead.</p>\n\n<h2>Example</h2>\n\n<p>Create the parameter object with an interface for dependency injection:</p>\n\n<pre><code>interface Validation_Parameters {\n\n public function id();\n\n public function errors();\n\n // not a good name …\n public function details();\n}\n\nclass Form_Validation_Parameters implements Validation_Parameters {\n\n private $id;\n\n private $errors;\n\n private $details;\n\n public function __construct( $id, $errors, $details ) {\n\n $this-&gt;id = $id;\n $this-&gt;errors = $errors;\n $this-&gt;details = $details;\n }\n\n public function id() {\n return $this-&gt;id;\n }\n\n public function errors() {\n return $this-&gt;errors;\n }\n\n public function details() {\n return $this-&gt;details;\n }\n}\n\n$params = new Form_Validation_Parameters( \n 'contact',\n new WP_Error(), // should be prepared better.\n [ 'request' =&gt; $_SERVER['REQUEST_URI'] ]\n);\n</code></pre>\n\n<p>Now pass it in your filter:</p>\n\n<pre><code>$valid = apply_filters( 'form_is_valid', TRUE, $params );\n</code></pre>\n\n<p>A third-party developer can read it now, but not change it, so the others can rely on its structure, because there is no way to corrupt it.</p>\n\n<pre><code>add_filter( 'form_is_valid', function( $bool, Validation_Parameters $params ) {\n // do something and return a value\n});\n</code></pre>\n" }, { "answer_id": 185993, "author": "adelval", "author_id": 40965, "author_profile": "https://wordpress.stackexchange.com/users/40965", "pm_score": 3, "selected": true, "text": "<p>Method 1 is much more robust and extendable, in my opinion. </p>\n\n<p><strong>Method 1:</strong> To add or remove forms, or other functionality, you just add or remove functions. In particular, you can do this from other files, such as separate modules of your plugin or other external plugins. I think this is the main argument in its favor: extensibility and modularity. </p>\n\n<p><strong>Method 2:</strong> In order to add or remove forms or other functionality you need to modify an existing function, which is much more bug prone. A switch statement like the one in method 2 easily gets out of hand. The list of cases can get very long, and it is easy to introduce bugs as soon as you have several filters with the same kind of switch statement. For example, you may want filters for validation, display of empty forms to be filled, display of the content of filled out forms, database management,... So now you have a bunch of functions each with a very long list of switch cases, that you have to keep in sync.</p>\n\n<p>(I had some bad experience of this with a popular extension for gravity forms - it's not unmanageable if you are disciplined, e.g. keep the list of cases in the same order in all functions, but it's not pretty either.)</p>\n\n<p><strong>Locating bugs:</strong> Much easier with Method 1: the culprit will usually be the newly added filter or form, rather than some typo inadvertently introduced in that very long function of Method 2.</p>\n\n<p><strong>Examples:</strong> You'll find tons of examples of Method 1 in the wordpress core (e.g. <a href=\"https://developer.wordpress.org/?s=post+type&amp;post_type[]=wp-parser-hook\" rel=\"nofollow\">https://developer.wordpress.org/?s=post+type&amp;post_type[]=wp-parser-hook</a>), but I don't remember a single instance of Method 2. </p>\n" } ]
2015/04/23
[ "https://wordpress.stackexchange.com/questions/185126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18340/" ]
I'm creating a form plugin to handle forms that can be hooked into using actions/filters by developers. My plug-in needs to be able to handle different forms with different sets of filters and I see 2 ways of doing this. Method 1 -------- Fire of specific hooks for each form. So code like this could be called form within my plugin: ``` $formId = 'contact'; $errors = apply_filters('forms_validate_' . $formId, $errors, $data); ``` And could be used like so: ``` add_filter('forms_validate_contact', function($errors, $data){ if(empty($data['name'])){ $errors['name'] = 'Name is required'; } return $errors; } 10, 2) ``` Method 2 -------- Pass a parameter to the calling function. So code like this could be called form within my plugin: ``` $formId = 'contact'; $errors = apply_filters('forms_validate', $formId, $errors, $data); ``` And could be used like so: ``` add_filter('forms_validate', function($formId, $error, $data){ switch($formId){ case 'contact': if(empty($data['name'])){ $errors['name'] = 'Name is required'; } break; } return $errors; }, 10, 3) ``` --- Are there any examples in the WordPress core where this sort of issue is tackled? Is there a preferred method of dealing with this?
Method 1 is much more robust and extendable, in my opinion. **Method 1:** To add or remove forms, or other functionality, you just add or remove functions. In particular, you can do this from other files, such as separate modules of your plugin or other external plugins. I think this is the main argument in its favor: extensibility and modularity. **Method 2:** In order to add or remove forms or other functionality you need to modify an existing function, which is much more bug prone. A switch statement like the one in method 2 easily gets out of hand. The list of cases can get very long, and it is easy to introduce bugs as soon as you have several filters with the same kind of switch statement. For example, you may want filters for validation, display of empty forms to be filled, display of the content of filled out forms, database management,... So now you have a bunch of functions each with a very long list of switch cases, that you have to keep in sync. (I had some bad experience of this with a popular extension for gravity forms - it's not unmanageable if you are disciplined, e.g. keep the list of cases in the same order in all functions, but it's not pretty either.) **Locating bugs:** Much easier with Method 1: the culprit will usually be the newly added filter or form, rather than some typo inadvertently introduced in that very long function of Method 2. **Examples:** You'll find tons of examples of Method 1 in the wordpress core (e.g. <https://developer.wordpress.org/?s=post+type&post_type[]=wp-parser-hook>), but I don't remember a single instance of Method 2.
185,148
<p>I am having problems with my form. When the submit button is clicked a 404 error is spit out. If anyone has any suggestions I'd be grateful.</p> <p>Ajax handling of form. Going into theme's js.</p> <pre><code>&lt;script type="text/javascript"&gt; jQuery('#BookingForm').submit(ajaxSubmit); function ajaxSubmit(){ var BookingForm = jQuery(this).serialize(); jQuery.ajax({ action : 'make_booking', type : "POST", url : "/wp-admin/admin-ajax.php", data : BookingForm, success: function(data){ jQuery("#feedback").html(data); } }); return false; } &lt;/script&gt; </code></pre> <p>PHP going into <code>functions.php</code></p> <pre><code>function makeBooking(){ global $wpdb; $type = $_POST["optionsRadios"]; $to = $_POST["to"]; $from = $_POST["from"]; $date = $_POST["date"]; $time = $_POST["time"]; $name = $_POST["name"]; $tel = $_POST["tel"]; $email = $_POST["email"]; $passenger = $_POST["optionsRadios2"]; $other = $_POST["other"]; if( $wpdb-&gt;insert('Booking', array( 'type'=&gt;$type, 'from1'=&gt;$from, 'to1'=&gt;$to, 'date'=&gt;$date, 'time'=&gt;$time, 'name'=&gt;$name, 'tel'=&gt;$tel, 'email'=&gt;$email, 'passenger'=&gt;$passenger, 'other'=&gt;$other ) ) === FALSE ) { echo "Error"; } else { echo "Submission successful, an email receipt has been sent to your email address. &lt;br&gt; Your Booking ID is:&lt;b&gt;ZCA- ".$wpdb-&gt;reference . "&lt;/b&gt;"; //Prepare email body $msg = "Reference: ZCA-" . $reference . "\nType:" . $type . "\nFrom:" . $from . "\nTo:" . $to . "\nDate" . $date . "\nTime:" . $time . "\nName:" . $name . "\nNumber:" . $tel . "\nEmail:" . $email . "\nPassengers:" . $passenger . "\nOther:" . $other; mail("[email protected]","Booking",$msg); mail($email,"Zcars Global Booking","Thank you for your enquiry. We aim to deal with your request straight away." . $msg); } die(); } add_action('wp_ajax_make_booking', 'makeBooking'); add_action('wp_ajax_nopriv_make_booking', 'makeBooking'); // not really needed </code></pre> <p>I am including the HTML form as I am still getting the 404 error, maybe it's something here?</p> <pre><code>&lt;form method="post" id="BookingForm"&gt; &lt;div class="radio"&gt; &lt;label&gt; &lt;input type="radio" name="optionsRadios" id="booking" value="booking" checked&gt; Booking &lt;/label&gt; &lt;/div&gt; &lt;div class="radio"&gt; &lt;label&gt; &lt;input type="radio" name="optionsRadios" id="quotation" value="quotation"&gt; Quotation &lt;/label&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="from"&gt;From *&lt;/label&gt; &lt;input name="from" id="from" type="text" class="form-control" placeholder="Where are you?" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="to"&gt;Going to *&lt;/label&gt; &lt;input name="to" id="to" type="text" class="form-control" placeholder="Where are you going to?" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="date"&gt;Date *&lt;/label&gt; &lt;input name="date" id="date" type="date" class="form-control" required min="&lt;?php echo date("dd-mm-yyyy"); ?&gt;"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="time"&gt;Time *&lt;/label&gt; &lt;input name="time" id="time" type="time" class="form-control" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;Name *&lt;/label&gt; &lt;input name="name" id="name" type="text" class="form-control" placeholder="What is your name?" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="tel"&gt;Telephone Number *&lt;/label&gt; &lt;input name="tel" id="tel" type="number" class="form-control" placeholder="What is your number?" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;Email *&lt;/label&gt; &lt;input name="email" id="email" type="email" class="form-control" placeholder="What is your email?" required&gt; &lt;/div&gt; &lt;h4&gt;Passengers&lt;/h4&gt; &lt;div class="radio"&gt; &lt;label&gt; &lt;input type="radio" name="optionsRadios2" id="4orless" value="1to4" checked&gt; 4 or Less &lt;/label&gt; &lt;/div&gt; &lt;div class="radio"&gt; &lt;label&gt; &lt;input type="radio" name="optionsRadios2" id="4to6" value="4to6"&gt; 4 to 6 &lt;/label&gt; &lt;/div&gt; &lt;div class="radio"&gt; &lt;label&gt; &lt;input type="radio" name="optionsRadios2" id="6to8" value="6to8"&gt; 6 to 8 &lt;/label&gt; &lt;/div&gt; &lt;textarea name="other" class="form-control" rows="3"&gt;Please write here anything else we need to know&lt;/textarea&gt; &lt;input type="hidden" name="action" value="makeBooking"/&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p><br/><br/></p> <p><br/><br/></p>
[ { "answer_id": 185158, "author": "Trang", "author_id": 70868, "author_profile": "https://wordpress.stackexchange.com/users/70868", "pm_score": 0, "selected": false, "text": "<p>You cannot use Ajax on Wordpress that way. There are many tutorial about using Ajax on wordpress. I think the simplest is <a href=\"http://natko.com/wordpress-ajax-login-without-a-plugin-the-right-way/\" rel=\"nofollow\">http://natko.com/wordpress-ajax-login-without-a-plugin-the-right-way/</a></p>\n" }, { "answer_id": 185164, "author": "CeganB", "author_id": 71063, "author_profile": "https://wordpress.stackexchange.com/users/71063", "pm_score": 3, "selected": false, "text": "<p>Your attempt to send your AJAX requests to <em>wp-admin/admin-ajax.php</em> is correct but it will be better to create a javascript global variable using <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script()</a> to make any data available to your script in functions.php that you can normally only get from the server side of WordPress.</p>\n\n<p>For example, your javascript code can be in the same folder with functions.php as such: </p>\n\n<p>[Theme Folder]</p>\n\n<p>-->functions.php</p>\n\n<p>-->js [folder] --> makebooking.js</p>\n\n<p>Your jquery in <em>makebooking.js</em> should look like this:</p>\n\n<pre><code>jQuery(document).ready(function(event) {\n\n jQuery('#BookingForm').submit(ajaxSubmit);\n\n function ajaxSubmit() {\n var BookingForm = jQuery(this).serialize();\n jQuery.ajax({\n action: 'make_booking',\n type: \"POST\",\n url: MBAjax.admin_url,\n data: BookingForm,\n success: function(data) {\n jQuery(\"#feedback\").html(data);\n }\n });\n return false;\n }\n});\n</code></pre>\n\n<p>With <em>makeBooking()</em> processing the data, add the following at the top your functions.php:</p>\n\n<pre><code>// embed the javascript file that makes the AJAX request\nwp_enqueue_script( 'make-booking-ajax','js/makebooking.js', array( 'jquery' ) );\n\n// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)\nwp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) );\n\nadd_action('wp_ajax_make_booking', 'makeBooking');\n</code></pre>\n\n<p>For more reference, have a look at <a href=\"http://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/\" rel=\"nofollow noreferrer\">5 Tips for using Ajax in Wordpress</a></p>\n" }, { "answer_id": 308282, "author": "Syed Waqar Haider", "author_id": 146763, "author_profile": "https://wordpress.stackexchange.com/users/146763", "pm_score": 1, "selected": false, "text": "<pre><code>add_action('wp_ajax_make_booking', 'makeBooking');\nadd_action('wp_ajax_nopriv_make_booking', 'makeBooking'); // not really needed\n</code></pre>\n\n<p><strong>Put these two lines above the makeBooking function.</strong></p>\n\n<p>Worked for me!\nAlso, see how I'm sending the action in data!</p>\n\n<pre><code>$( \"#signupFormTag\" ).submit(function( event ) {\n\n event.preventDefault();\n\n var signupForm = jQuery(this).serialize();\n jQuery.ajax({\n // action : 'signup_paragon',\n type : \"POST\",\n url : \"/paragaon-3/wp-admin/admin-ajax.php\",\n data : {\n from: signupForm,\n action: 'signup_paragon'\n },\n success: function(data){\n console.log(data);\n //jQuery(\"#feedback\").html(data);\n }\n });\n // return false;\n\n });\n</code></pre>\n" }, { "answer_id": 345080, "author": "test", "author_id": 173481, "author_profile": "https://wordpress.stackexchange.com/users/173481", "pm_score": 0, "selected": false, "text": "<pre><code>jQuery(document).ready(function($) {\n\n // Perform AJAX login on form submit\n $('form#login').on('submit', function(e){\n $('form#login p.status').show().text(ajax_login_object.loadingmessage);\n $.ajax({\n type: 'POST',\n dataType: 'json',\n url: ajax_login_object.ajaxurl,\n data: { \n 'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin\n 'username': $('form#login #username').val(), \n 'password': $('form#login #password').val(), \n 'security': $('form#login #security').val() },\n success: function(data){\n $('form#login p.status').text(data.message);\n if (data.loggedin == true){\n document.location.href = ajax_login_object.redirecturl;\n }\n }\n });\n e.preventDefault();\n });\n\n});\n</code></pre>\n" } ]
2015/04/23
[ "https://wordpress.stackexchange.com/questions/185148", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71081/" ]
I am having problems with my form. When the submit button is clicked a 404 error is spit out. If anyone has any suggestions I'd be grateful. Ajax handling of form. Going into theme's js. ``` <script type="text/javascript"> jQuery('#BookingForm').submit(ajaxSubmit); function ajaxSubmit(){ var BookingForm = jQuery(this).serialize(); jQuery.ajax({ action : 'make_booking', type : "POST", url : "/wp-admin/admin-ajax.php", data : BookingForm, success: function(data){ jQuery("#feedback").html(data); } }); return false; } </script> ``` PHP going into `functions.php` ``` function makeBooking(){ global $wpdb; $type = $_POST["optionsRadios"]; $to = $_POST["to"]; $from = $_POST["from"]; $date = $_POST["date"]; $time = $_POST["time"]; $name = $_POST["name"]; $tel = $_POST["tel"]; $email = $_POST["email"]; $passenger = $_POST["optionsRadios2"]; $other = $_POST["other"]; if( $wpdb->insert('Booking', array( 'type'=>$type, 'from1'=>$from, 'to1'=>$to, 'date'=>$date, 'time'=>$time, 'name'=>$name, 'tel'=>$tel, 'email'=>$email, 'passenger'=>$passenger, 'other'=>$other ) ) === FALSE ) { echo "Error"; } else { echo "Submission successful, an email receipt has been sent to your email address. <br> Your Booking ID is:<b>ZCA- ".$wpdb->reference . "</b>"; //Prepare email body $msg = "Reference: ZCA-" . $reference . "\nType:" . $type . "\nFrom:" . $from . "\nTo:" . $to . "\nDate" . $date . "\nTime:" . $time . "\nName:" . $name . "\nNumber:" . $tel . "\nEmail:" . $email . "\nPassengers:" . $passenger . "\nOther:" . $other; mail("[email protected]","Booking",$msg); mail($email,"Zcars Global Booking","Thank you for your enquiry. We aim to deal with your request straight away." . $msg); } die(); } add_action('wp_ajax_make_booking', 'makeBooking'); add_action('wp_ajax_nopriv_make_booking', 'makeBooking'); // not really needed ``` I am including the HTML form as I am still getting the 404 error, maybe it's something here? ``` <form method="post" id="BookingForm"> <div class="radio"> <label> <input type="radio" name="optionsRadios" id="booking" value="booking" checked> Booking </label> </div> <div class="radio"> <label> <input type="radio" name="optionsRadios" id="quotation" value="quotation"> Quotation </label> </div> <div class="form-group"> <label for="from">From *</label> <input name="from" id="from" type="text" class="form-control" placeholder="Where are you?" required> </div> <div class="form-group"> <label for="to">Going to *</label> <input name="to" id="to" type="text" class="form-control" placeholder="Where are you going to?" required> </div> <div class="form-group"> <label for="date">Date *</label> <input name="date" id="date" type="date" class="form-control" required min="<?php echo date("dd-mm-yyyy"); ?>"> </div> <div class="form-group"> <label for="time">Time *</label> <input name="time" id="time" type="time" class="form-control" required> </div> <div class="form-group"> <label for="name">Name *</label> <input name="name" id="name" type="text" class="form-control" placeholder="What is your name?" required> </div> <div class="form-group"> <label for="tel">Telephone Number *</label> <input name="tel" id="tel" type="number" class="form-control" placeholder="What is your number?" required> </div> <div class="form-group"> <label for="email">Email *</label> <input name="email" id="email" type="email" class="form-control" placeholder="What is your email?" required> </div> <h4>Passengers</h4> <div class="radio"> <label> <input type="radio" name="optionsRadios2" id="4orless" value="1to4" checked> 4 or Less </label> </div> <div class="radio"> <label> <input type="radio" name="optionsRadios2" id="4to6" value="4to6"> 4 to 6 </label> </div> <div class="radio"> <label> <input type="radio" name="optionsRadios2" id="6to8" value="6to8"> 6 to 8 </label> </div> <textarea name="other" class="form-control" rows="3">Please write here anything else we need to know</textarea> <input type="hidden" name="action" value="makeBooking"/> <input type="submit"> </form> ```
Your attempt to send your AJAX requests to *wp-admin/admin-ajax.php* is correct but it will be better to create a javascript global variable using [wp\_localize\_script()](https://codex.wordpress.org/Function_Reference/wp_localize_script) to make any data available to your script in functions.php that you can normally only get from the server side of WordPress. For example, your javascript code can be in the same folder with functions.php as such: [Theme Folder] -->functions.php -->js [folder] --> makebooking.js Your jquery in *makebooking.js* should look like this: ``` jQuery(document).ready(function(event) { jQuery('#BookingForm').submit(ajaxSubmit); function ajaxSubmit() { var BookingForm = jQuery(this).serialize(); jQuery.ajax({ action: 'make_booking', type: "POST", url: MBAjax.admin_url, data: BookingForm, success: function(data) { jQuery("#feedback").html(data); } }); return false; } }); ``` With *makeBooking()* processing the data, add the following at the top your functions.php: ``` // embed the javascript file that makes the AJAX request wp_enqueue_script( 'make-booking-ajax','js/makebooking.js', array( 'jquery' ) ); // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) wp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); add_action('wp_ajax_make_booking', 'makeBooking'); ``` For more reference, have a look at [5 Tips for using Ajax in Wordpress](http://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/)
185,203
<pre><code>register_post_type("butik", [ "labels" =&gt; [ "name" =&gt; "Butik", "singular_name" =&gt; "Butik" ], "show_ui" =&gt; true, 'public' =&gt; true, 'rewrite' =&gt; [ 'slug' =&gt; 'butik' ], "supports" =&gt; [ "title", "editor", "thumbnail" ], 'taxonomies' =&gt; array('category') ]); </code></pre> <p>That's my code for registering the post type and trying to add the taxonomies, but it still aint showing.</p> <p>Any clues?</p> <p>Thankyou for your effort!</p>
[ { "answer_id": 185205, "author": "Webimetry Solutions", "author_id": 71060, "author_profile": "https://wordpress.stackexchange.com/users/71060", "pm_score": 2, "selected": true, "text": "<p>That is not the way to register a Taxonomy.Please find the code below to register a Taxonomy for a custom post type :-</p>\n\n<pre><code>$args = array(\n \"label\" =&gt; \"Butik Categories\",\n \"singular_label\" =&gt; \"Butik Category\",\n 'public' =&gt; true,\n 'hierarchical' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_nav_menus' =&gt; false,\n 'args' =&gt; array( 'orderby' =&gt; 'term_order' ),\n 'rewrite' =&gt; false,\n 'query_var' =&gt; true\n);\n\nregister_taxonomy( 'butik-category', 'butik', $args );\n</code></pre>\n\n<p>Hope that solves the problem.You can also use plugins like Custom Post Type UI to easily create Custom Post Type.Here is the link :- <a href=\"https://wordpress.org/plugins/custom-post-type-ui/\" rel=\"nofollow\">https://wordpress.org/plugins/custom-post-type-ui/</a>\nHope that helps :)</p>\n" }, { "answer_id": 185210, "author": "Joelgullander", "author_id": 71110, "author_profile": "https://wordpress.stackexchange.com/users/71110", "pm_score": 0, "selected": false, "text": "<pre><code>$args = array(\n \"label\" =&gt; \"Butik Categories\",\n \"singular_label\" =&gt; \"Butik Category\",\n 'public' =&gt; true,\n 'hierarchical' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_nav_menus' =&gt; false,\n 'args' =&gt; array( 'orderby' =&gt; 'term_order' ),\n 'rewrite' =&gt; false,\n 'query_var' =&gt; true\n);\n\nregister_taxonomy( 'butik-category', 'butik', $args );\n</code></pre>\n\n<p>That's exactly what I was looking for. Thanks.</p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71110/" ]
``` register_post_type("butik", [ "labels" => [ "name" => "Butik", "singular_name" => "Butik" ], "show_ui" => true, 'public' => true, 'rewrite' => [ 'slug' => 'butik' ], "supports" => [ "title", "editor", "thumbnail" ], 'taxonomies' => array('category') ]); ``` That's my code for registering the post type and trying to add the taxonomies, but it still aint showing. Any clues? Thankyou for your effort!
That is not the way to register a Taxonomy.Please find the code below to register a Taxonomy for a custom post type :- ``` $args = array( "label" => "Butik Categories", "singular_label" => "Butik Category", 'public' => true, 'hierarchical' => true, 'show_ui' => true, 'show_in_nav_menus' => false, 'args' => array( 'orderby' => 'term_order' ), 'rewrite' => false, 'query_var' => true ); register_taxonomy( 'butik-category', 'butik', $args ); ``` Hope that solves the problem.You can also use plugins like Custom Post Type UI to easily create Custom Post Type.Here is the link :- <https://wordpress.org/plugins/custom-post-type-ui/> Hope that helps :)
185,212
<p>I want to make an AJAX request on every select value change to update the real value from database. I'm coding inside a shortcode on <code>functions.php</code>. I have a <code>select</code> element like this one below,</p> <pre><code>echo '&lt;select name="changeValue" onchange="changeValue(' . $user-&gt;ID . ', this.options[this.selectedIndex])"&gt;' </code></pre> <p>At the end of the shortcode, I do:</p> <pre><code>?&gt; &lt;script type="text/javascript"&gt; function changeValue(id, valueElement) { jQuery.post( "&lt;?php echo admin_url('admin-ajax.php'); ?&gt;", { 'action': 'update_value', 'data': { user_id: id, value: valueElement.value } }, function(response){ console.log(response) } ); } &lt;/script&gt; &lt;? } add_shortcode('the_shortcode', 'the_shortcode'); function update_value() { $user_id = $_POST['data']['user_id']; $value= $_POST['data']['value']; echo $user_id . ' - ' . $empresa; //return update_user_meta($user_id , 'value', $value); wp_die(); } add_action( 'wp_ajax_update_value', 'update_value' ); add_action( 'wp_ajax_nopriv_update_value', 'update_value' ); </code></pre> <p>My code <strong>works when I'm logged as Admin</strong>. However if I'm logged as another user, <code>console.log(response)</code> returns the whole HTML page content. What am I doing wrong?</p> <p>EDIT: Another difference is that when logged as Admin, <code>admin-ajax.php</code> returns <code>200 OK</code>, whereas when logged as a user it returns <code>302 Found</code>.</p>
[ { "answer_id": 185407, "author": "Ahmed Mostafa", "author_id": 71196, "author_profile": "https://wordpress.stackexchange.com/users/71196", "pm_score": 1, "selected": false, "text": "<p>What a type you work with response \nIf you work with json</p>\n\n<pre><code>$.post( ajaxurl , data , function(res){\n// your code \n},'json');\n</code></pre>\n\n<p>Remove wp_die() and replace with die()</p>\n" }, { "answer_id": 307337, "author": "Leon Magee", "author_id": 145917, "author_profile": "https://wordpress.stackexchange.com/users/145917", "pm_score": 0, "selected": false, "text": "<p>When using <code>admin-ajax.php</code> the <code>admin_init</code> hook is fired, so many functions that run in the admin will also run when ajax is used. In this case there is some code locking non admin users out of the admin by redirecting them somewhere else. This could be part of your theme or coming from a plugin.</p>\n\n<p>When the redirect fires it 'returns' the html of the homepage to your ajax request, which is why you see html instead of the response you expect.</p>\n\n<p>The redirect would need to be modified to ignore ajax requests:</p>\n\n<pre><code>if ( ( ! current_user_can( 'level_5' ) ) &amp;&amp; ( $_SERVER['PHP_SELF'] != '/wp- admin/admin-ajax.php' ) ) {\n wp_redirect( site_url() );\n}\n</code></pre>\n\n<p>You could also use the REST API instead of ajax to avoid this issue.</p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185212", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51091/" ]
I want to make an AJAX request on every select value change to update the real value from database. I'm coding inside a shortcode on `functions.php`. I have a `select` element like this one below, ``` echo '<select name="changeValue" onchange="changeValue(' . $user->ID . ', this.options[this.selectedIndex])">' ``` At the end of the shortcode, I do: ``` ?> <script type="text/javascript"> function changeValue(id, valueElement) { jQuery.post( "<?php echo admin_url('admin-ajax.php'); ?>", { 'action': 'update_value', 'data': { user_id: id, value: valueElement.value } }, function(response){ console.log(response) } ); } </script> <? } add_shortcode('the_shortcode', 'the_shortcode'); function update_value() { $user_id = $_POST['data']['user_id']; $value= $_POST['data']['value']; echo $user_id . ' - ' . $empresa; //return update_user_meta($user_id , 'value', $value); wp_die(); } add_action( 'wp_ajax_update_value', 'update_value' ); add_action( 'wp_ajax_nopriv_update_value', 'update_value' ); ``` My code **works when I'm logged as Admin**. However if I'm logged as another user, `console.log(response)` returns the whole HTML page content. What am I doing wrong? EDIT: Another difference is that when logged as Admin, `admin-ajax.php` returns `200 OK`, whereas when logged as a user it returns `302 Found`.
What a type you work with response If you work with json ``` $.post( ajaxurl , data , function(res){ // your code },'json'); ``` Remove wp\_die() and replace with die()
185,231
<p>I have 7 services in a page. All 7 services have featured images. I want to show all the 7 images and content in a slideshow.</p> <pre><code> $args = array( 'post_type' =&gt; 'page', 'post__in' =&gt; $myarray ); // The Query&lt;br&gt; $the_query = new WP_Query( $args ); </code></pre> <p>How can I show the featured image in the slide show. Please guide me.</p>
[ { "answer_id": 185246, "author": "Webimetry Solutions", "author_id": 71060, "author_profile": "https://wordpress.stackexchange.com/users/71060", "pm_score": 0, "selected": false, "text": "<p>You will need to create a WP query to grab posts and then put them in a Slider like Flex Slider to display them in a slider.Here is the query :-</p>\n\n<pre><code>&lt;?php \n $args = array(\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; 'carousel',\n 'carousel-category' =&gt; 'your-category',\n 'posts_per_page' =&gt; 7\n );\n $recentPosts = new WP_Query( $args );\n if ( $recentPosts-&gt;have_posts() ) : ?&gt; \n</code></pre>\n\n<p>Now grab the featured image using the following code (in loop):-</p>\n\n<pre><code>&lt;?php \nif ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.\n the_post_thumbnail();\n} \n?&gt; \n</code></pre>\n\n<p>You will need to them inside Div elements to create a carousel.Here is a tutorial that you can use for better understanding :-\n<a href=\"http://www.wordpressauthors.com/wordpress-development/display-a-carousel-of-most-recent-posts/\" rel=\"nofollow\">http://www.wordpressauthors.com/wordpress-development/display-a-carousel-of-most-recent-posts/</a></p>\n\n<p>Hope that helps. :)</p>\n" }, { "answer_id": 185249, "author": "GastroGeek", "author_id": 70445, "author_profile": "https://wordpress.stackexchange.com/users/70445", "pm_score": 1, "selected": false, "text": "<p>this is a fairly broad question since there are multiple solutions depending on your exact needs. My method might involve:</p>\n\n<ul>\n<li>Setup normal 'Loop'</li>\n<li>in each iteration grab the featured image using: wp_get_attachment_image_src( get_post_thumbnail_id( post->ID ), 'large' );</li>\n<li>build an unordered list of images</li>\n<li>Use a plugin that works with UL listitems to generated a slideshow with the desired features</li>\n</ul>\n\n<p>That's pretty much it. Can't test this but might end up looking like:</p>\n\n<pre><code>$the_query = new WP_Query( $args );\nif ( $the_query-&gt;have_posts() ) {\n echo '&lt;div class=\"flexslider\"&gt;&lt;ul class=\"slides\"&gt;'; \n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;&lt;img src=\"' . wp_get_attachment_image_src( get_post_thumbnail_id( post-&gt;ID ), 'large' ) . '\" /&gt;&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;&lt;/div&gt;';\n}\n</code></pre>\n\n<p>And then use maybe </p>\n\n<p><a href=\"http://www.woothemes.com/flexslider/\" rel=\"nofollow\">Flexslider2</a></p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185231", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71122/" ]
I have 7 services in a page. All 7 services have featured images. I want to show all the 7 images and content in a slideshow. ``` $args = array( 'post_type' => 'page', 'post__in' => $myarray ); // The Query<br> $the_query = new WP_Query( $args ); ``` How can I show the featured image in the slide show. Please guide me.
this is a fairly broad question since there are multiple solutions depending on your exact needs. My method might involve: * Setup normal 'Loop' * in each iteration grab the featured image using: wp\_get\_attachment\_image\_src( get\_post\_thumbnail\_id( post->ID ), 'large' ); * build an unordered list of images * Use a plugin that works with UL listitems to generated a slideshow with the desired features That's pretty much it. Can't test this but might end up looking like: ``` $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { echo '<div class="flexslider"><ul class="slides">'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li><img src="' . wp_get_attachment_image_src( get_post_thumbnail_id( post->ID ), 'large' ) . '" /></li>'; } echo '</ul></div>'; } ``` And then use maybe [Flexslider2](http://www.woothemes.com/flexslider/)
185,271
<p>I would like to add new tab to upload manager and inside list images from </p> <pre><code>theme_folder/images/patterns </code></pre> <p>I tried something like this to add a tab but it does not work for me since it is adding tabs on the side of media manager but on image upload that tab is not visible. </p> <pre><code>function custom_media_upload_tab_name( $tabs ) { $newtab = array( 'tab_slug' =&gt; 'Patterns' ); return array_merge( $tabs, $newtab ); } add_filter( 'media_upload_tabs', 'custom_media_upload_tab_name' ); function custom_media_upload_tab_content() { // Add you content here. echo 'Hello content'; } add_action( 'media_upload_tab_slug', 'custom_media_upload_tab_content' ); </code></pre> <p>to be precise this is where I would like to add a new tab and in that tab I would like to list images from theme folder. </p> <p><img src="https://i.stack.imgur.com/6Ph7u.png" alt="enter image description here"></p> <p>I am aware that media manager JS needs to be rewritten for it but to be honest I dont know where to start. Looks like I need to write completely new template for media manager in order to achieve this. </p> <p><strong>I went trough all suggestions but seems like no one is reading the question. As advised "I tried something like this to add a tab but it does not work for me since it is adding tabs on the side of media manager but on image upload that tab is not visible."</strong> </p> <p>So for now no one is able to find the solution for this.</p>
[ { "answer_id": 190580, "author": "sarath", "author_id": 74204, "author_profile": "https://wordpress.stackexchange.com/users/74204", "pm_score": -1, "selected": false, "text": "<pre><code> function axcoto_genify_media_menu($tabs) {\n $newtab = array('genify' =&gt; __('Axcoto Genify', 'axcotogenify'));\n return array_merge($tabs, $newtab);\n }\n add_filter('media_upload_tabs', 'axcoto_genify_media_menu');\n\n array('genify' =&gt; __('Axcoto Genify', 'axcotogenify'));\n\n\n function axcoto_genify_media_process() {\n media_upload_header();\n echo 'hello';\n }\n function axcoto_genify_media_menu_handle() {\n return wp_iframe( 'axcoto_genify_media_process');\n }\n\n\n\n if ( ( is_array( $content_func ) &amp;&amp; ! empty( $content_func[1] ) &amp;&amp; 0 === strpos( (string) $content_func[1], 'media' ) ) || 0 === strpos( $content_func, 'media' ) )\n wp_enqueue_style( 'media' );\n</code></pre>\n" }, { "answer_id": 190604, "author": "Touqeer Shafi", "author_id": 63430, "author_profile": "https://wordpress.stackexchange.com/users/63430", "pm_score": 3, "selected": false, "text": "<p>According to WordPress <a href=\"http://codex.wordpress.org/Function_Reference/wp_iframe\" rel=\"noreferrer\">Codex</a> you can add custom tab in media uploader like this:</p>\n\n<pre><code>// add the tab\nadd_filter('media_upload_tabs', 'my_upload_tab');\nfunction my_upload_tab($tabs) {\n $tabs['mytabname'] = \"My Tab Name\";\n return $tabs;\n}\n\n// call the new tab with wp_iframe\nadd_action('media_upload_mytabname', 'add_my_new_form');\nfunction add_my_new_form() {\n wp_iframe( 'my_new_form' );\n}\n\n// the tab content\nfunction my_new_form() {\n echo media_upload_header(); // This function is used for print media uploader headers etc.\n echo '&lt;p&gt;Example HTML content goes here.&lt;/p&gt;';\n}\n</code></pre>\n\n<p>Hope it will help you.</p>\n" }, { "answer_id": 313729, "author": "gubbfett", "author_id": 43773, "author_profile": "https://wordpress.stackexchange.com/users/43773", "pm_score": 3, "selected": false, "text": "<p>This is an old thread but for me still as still as relevant.\nI have been fiddling and has come up with this code for adding a media tab here, maybe someone want to continue for how the handle content for the tab? :)</p>\n\n<pre><code>add_action('admin_enqueue_scripts', function(){\n wp_enqueue_script( 'my-media-tab', plugin_dir_url( __FILE__ ) . '/js/mytab.js', array( 'jquery' ), '', true );\n});\n</code></pre>\n\n<p>And then the js file:</p>\n\n<pre><code>var l10n = wp.media.view.l10n;\nwp.media.view.MediaFrame.Select.prototype.browseRouter = function( routerView ) {\n routerView.set({\n upload: {\n text: l10n.uploadFilesTitle,\n priority: 20\n },\n browse: {\n text: l10n.mediaLibraryTitle,\n priority: 40\n },\n my_tab: {\n text: \"My tab\",\n priority: 60\n }\n });\n};\n</code></pre>\n\n<p>EDIT:\nOk, so. For handling the content i have not found a nice way to do this by wp.media. My current solution are 2 liseners, one for opening the media library and one for clicking in the media router menu;</p>\n\n<pre><code>jQuery(document).ready(function($){\n if ( wp.media ) {\n wp.media.view.Modal.prototype.on( \"open\", function() {\n if($('body').find('.media-modal-content .media-router a.media-menu-item.active')[0].innerText == \"My tab\")\n doMyTabContent();\n });\n $(wp.media).on('click', '.media-router a.media-menu-item', function(e){\n if(e.target.innerText == \"My tab\")\n doMyTabContent();\n });\n }\n});\n</code></pre>\n\n<p>the function doMyTabContent(); is just something like;</p>\n\n<pre><code>function doMyTabContent() {\n var html = '&lt;div class=\"myTabContent\"&gt;';\n //My tab content here\n html += '&lt;/div&gt;';\n $('body .media-modal-content .media-frame-content')[0].innerHTML = html;\n}\n</code></pre>\n\n<p>I'm very sure this can be done in a much more delicate way. Whoever reads this and has a better solution, please fill in :-) </p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67176/" ]
I would like to add new tab to upload manager and inside list images from ``` theme_folder/images/patterns ``` I tried something like this to add a tab but it does not work for me since it is adding tabs on the side of media manager but on image upload that tab is not visible. ``` function custom_media_upload_tab_name( $tabs ) { $newtab = array( 'tab_slug' => 'Patterns' ); return array_merge( $tabs, $newtab ); } add_filter( 'media_upload_tabs', 'custom_media_upload_tab_name' ); function custom_media_upload_tab_content() { // Add you content here. echo 'Hello content'; } add_action( 'media_upload_tab_slug', 'custom_media_upload_tab_content' ); ``` to be precise this is where I would like to add a new tab and in that tab I would like to list images from theme folder. ![enter image description here](https://i.stack.imgur.com/6Ph7u.png) I am aware that media manager JS needs to be rewritten for it but to be honest I dont know where to start. Looks like I need to write completely new template for media manager in order to achieve this. **I went trough all suggestions but seems like no one is reading the question. As advised "I tried something like this to add a tab but it does not work for me since it is adding tabs on the side of media manager but on image upload that tab is not visible."** So for now no one is able to find the solution for this.
According to WordPress [Codex](http://codex.wordpress.org/Function_Reference/wp_iframe) you can add custom tab in media uploader like this: ``` // add the tab add_filter('media_upload_tabs', 'my_upload_tab'); function my_upload_tab($tabs) { $tabs['mytabname'] = "My Tab Name"; return $tabs; } // call the new tab with wp_iframe add_action('media_upload_mytabname', 'add_my_new_form'); function add_my_new_form() { wp_iframe( 'my_new_form' ); } // the tab content function my_new_form() { echo media_upload_header(); // This function is used for print media uploader headers etc. echo '<p>Example HTML content goes here.</p>'; } ``` Hope it will help you.
185,287
<p>I use wp-load() to load the basic WP environment and then read some info from the DB without any problem.</p> <p>But now i need to render the full header for a page, including the <a href="https://yoast.com/wordpress/plugins/seo/" rel="nofollow">Yoast SEO</a> plugin. After calling wp-load() and getting my data from the DB, i call wp_head() to render the header, but the output is basically empty as the normal WP environment has not been loaded. How can load the WP environment to the point that all the plugins without any problems.</p> <p>I did try various aproaches</p> <ul> <li>calling <code>wp('p=83');</code> to init the environment with the data of the correct page (ID = 83)</li> <li>initializing the <code>$wp_query</code> and <code>$post</code> vars manually with the same data they would get in a normal page call</li> <li>trying to find more global data structs that are set in a normal call but not with wp_load</li> </ul> <p>but no love.</p> <h2>EDIT:</h2> <p>So the exact situation is this:</p> <pre><code>/test.php /wordpress/{all the wp stuff} </code></pre> <p>in my test.php I include the wp_load.php</p> <pre><code>require_once("wordpress/wp-load.php"); </code></pre> <p>then i tried various versions, including the two solutions given by fischi,</p> <ul> <li>using wp_head directly in test.php</li> <li>using the get_header() directly in test.php</li> <li>placing it in a template file and call that via get_header('justthehead')</li> </ul> <p>But nothing works!</p> <p>My problem was not that i couldn't execute the wp_head() function, that was working from the beginning, but that apparently the wp_load is not enough for some plugins to work correctly.</p> <p>In my case i try to get the Yoast SEO plugin to work, but it does not show me the same output as when called in 'the normal way' inside the template for page p=83.</p> <p>So i DO get the wp_head output, but it is not complete as the data from the plugin is missing.</p>
[ { "answer_id": 185288, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 2, "selected": false, "text": "<p>You are looking for the function <code>get_header()</code>.</p>\n\n<p><code>wp_head()</code> is the internal function of WordPress for doing things inside the head section (listing scripts, styles, metadata etc.).</p>\n\n<p>The real HTML output comes from the function <code>get_header()</code>, which includes your theme's <code>header.php</code>.</p>\n\n<p>I suppose that you do not really want just this part of the header, as it leaves a lot of tags open, so my suggestion would be to create a file in your theme folder: <code>header-justthehead.php</code></p>\n\n<p>You can the call this file with a simple line:</p>\n\n<pre><code>get_header( 'justthehead' );\n</code></pre>\n\n<p>and you are in full control of the output for your custom header, and you do not have to mess with the header of your website itself. The only thing you still have to take care of, is that the right post is loaded. Define the <code>$args</code> for your <code>query_posts()</code>, and this should work for you. Never forget the <code>wp_reset_query()</code> - even if you do not need it in this case.</p>\n\n<pre><code>include( 'wp-load.php' ); // loads WordPress Environment\n\nquery_posts( $args ); // load your desired Post/Page\n\nif ( have_posts() ) : while ( have_posts() ) : the_post(); // Setup the Post/Page\n\n get_header( 'justthehead' ); // Get your custom header-justthehead.php, containing your wp_head() call\n\nendwhile; endif; // quit the loop\n\nwp_reset_query(); // clean it up\n</code></pre>\n" }, { "answer_id": 185334, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 0, "selected": false, "text": "<p>Another way to go would be to make a switch in your template file.</p>\n\n<p>Let's say you have got your <code>page.php</code> calling the <code>get_header()</code> function.</p>\n\n<pre><code>&lt;?php get_header(); ?&gt;\n\n //Template Stuff\n</code></pre>\n\n<p>If you put the switch before this call, you can make it work like that, setting a parameter defining which header you want to include.</p>\n\n<pre><code>&lt;?php\n if ( $_GET['justtheheader'] == 'true'] ) {\n get_header( 'justtheheader' );\n } else {\n get_header();\n }\n?&gt;\n</code></pre>\n\n<p>In your <code>header-justtheheader.php</code> you initialize the header and quit qith a <code>die()</code> (important, do not use the <code>wp_die()</code>, as this delivers additional HTML output.</p>\n\n<p>You can call every page for the header with <code>yourdomain.com/pagetoshow?justtheheader=true</code>.</p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185287", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34517/" ]
I use wp-load() to load the basic WP environment and then read some info from the DB without any problem. But now i need to render the full header for a page, including the [Yoast SEO](https://yoast.com/wordpress/plugins/seo/) plugin. After calling wp-load() and getting my data from the DB, i call wp\_head() to render the header, but the output is basically empty as the normal WP environment has not been loaded. How can load the WP environment to the point that all the plugins without any problems. I did try various aproaches * calling `wp('p=83');` to init the environment with the data of the correct page (ID = 83) * initializing the `$wp_query` and `$post` vars manually with the same data they would get in a normal page call * trying to find more global data structs that are set in a normal call but not with wp\_load but no love. EDIT: ----- So the exact situation is this: ``` /test.php /wordpress/{all the wp stuff} ``` in my test.php I include the wp\_load.php ``` require_once("wordpress/wp-load.php"); ``` then i tried various versions, including the two solutions given by fischi, * using wp\_head directly in test.php * using the get\_header() directly in test.php * placing it in a template file and call that via get\_header('justthehead') But nothing works! My problem was not that i couldn't execute the wp\_head() function, that was working from the beginning, but that apparently the wp\_load is not enough for some plugins to work correctly. In my case i try to get the Yoast SEO plugin to work, but it does not show me the same output as when called in 'the normal way' inside the template for page p=83. So i DO get the wp\_head output, but it is not complete as the data from the plugin is missing.
You are looking for the function `get_header()`. `wp_head()` is the internal function of WordPress for doing things inside the head section (listing scripts, styles, metadata etc.). The real HTML output comes from the function `get_header()`, which includes your theme's `header.php`. I suppose that you do not really want just this part of the header, as it leaves a lot of tags open, so my suggestion would be to create a file in your theme folder: `header-justthehead.php` You can the call this file with a simple line: ``` get_header( 'justthehead' ); ``` and you are in full control of the output for your custom header, and you do not have to mess with the header of your website itself. The only thing you still have to take care of, is that the right post is loaded. Define the `$args` for your `query_posts()`, and this should work for you. Never forget the `wp_reset_query()` - even if you do not need it in this case. ``` include( 'wp-load.php' ); // loads WordPress Environment query_posts( $args ); // load your desired Post/Page if ( have_posts() ) : while ( have_posts() ) : the_post(); // Setup the Post/Page get_header( 'justthehead' ); // Get your custom header-justthehead.php, containing your wp_head() call endwhile; endif; // quit the loop wp_reset_query(); // clean it up ```
185,289
<p>Just updated my local and live installs for a side project to 4.2 in order to take advantage of the newly added Emoji features. Emoji are working just fine on my local machine, but they seem to not be working as comments on the live version.</p> <p><strong>Local</strong></p> <ul> <li>emoji in post title - working</li> <li>emoji in post content - working</li> <li>emoji in comments - working</li> </ul> <p><strong>Live</strong></p> <ul> <li>emoji in post title - working</li> <li>emoji in post content - working</li> <li>emoji in comments - not working</li> </ul> <p><strong>Troubleshooting</strong></p> <ul> <li>Theme - Tried activating Twenty Fifteen; didn't work.</li> <li>Plugins - Tried deactivating all plugins; didn't work.</li> <li>Theme + Plugins - Tried activating Twenty Fifteen and deactivating all plugins; didn't work.</li> <li>Normal comments - Regular characters save and display as comments just fine.</li> <li>Emoji - they display in the 'comment field' when adding a comment, but once submitted, the seem to be stripped out. In wp-admin an emoji comment just seems to be blank with no text at all.</li> </ul> <p>I have tried all of the basic troubleshooting I can think of, are there any other things I am not thinking of?</p>
[ { "answer_id": 185288, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 2, "selected": false, "text": "<p>You are looking for the function <code>get_header()</code>.</p>\n\n<p><code>wp_head()</code> is the internal function of WordPress for doing things inside the head section (listing scripts, styles, metadata etc.).</p>\n\n<p>The real HTML output comes from the function <code>get_header()</code>, which includes your theme's <code>header.php</code>.</p>\n\n<p>I suppose that you do not really want just this part of the header, as it leaves a lot of tags open, so my suggestion would be to create a file in your theme folder: <code>header-justthehead.php</code></p>\n\n<p>You can the call this file with a simple line:</p>\n\n<pre><code>get_header( 'justthehead' );\n</code></pre>\n\n<p>and you are in full control of the output for your custom header, and you do not have to mess with the header of your website itself. The only thing you still have to take care of, is that the right post is loaded. Define the <code>$args</code> for your <code>query_posts()</code>, and this should work for you. Never forget the <code>wp_reset_query()</code> - even if you do not need it in this case.</p>\n\n<pre><code>include( 'wp-load.php' ); // loads WordPress Environment\n\nquery_posts( $args ); // load your desired Post/Page\n\nif ( have_posts() ) : while ( have_posts() ) : the_post(); // Setup the Post/Page\n\n get_header( 'justthehead' ); // Get your custom header-justthehead.php, containing your wp_head() call\n\nendwhile; endif; // quit the loop\n\nwp_reset_query(); // clean it up\n</code></pre>\n" }, { "answer_id": 185334, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 0, "selected": false, "text": "<p>Another way to go would be to make a switch in your template file.</p>\n\n<p>Let's say you have got your <code>page.php</code> calling the <code>get_header()</code> function.</p>\n\n<pre><code>&lt;?php get_header(); ?&gt;\n\n //Template Stuff\n</code></pre>\n\n<p>If you put the switch before this call, you can make it work like that, setting a parameter defining which header you want to include.</p>\n\n<pre><code>&lt;?php\n if ( $_GET['justtheheader'] == 'true'] ) {\n get_header( 'justtheheader' );\n } else {\n get_header();\n }\n?&gt;\n</code></pre>\n\n<p>In your <code>header-justtheheader.php</code> you initialize the header and quit qith a <code>die()</code> (important, do not use the <code>wp_die()</code>, as this delivers additional HTML output.</p>\n\n<p>You can call every page for the header with <code>yourdomain.com/pagetoshow?justtheheader=true</code>.</p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185289", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5019/" ]
Just updated my local and live installs for a side project to 4.2 in order to take advantage of the newly added Emoji features. Emoji are working just fine on my local machine, but they seem to not be working as comments on the live version. **Local** * emoji in post title - working * emoji in post content - working * emoji in comments - working **Live** * emoji in post title - working * emoji in post content - working * emoji in comments - not working **Troubleshooting** * Theme - Tried activating Twenty Fifteen; didn't work. * Plugins - Tried deactivating all plugins; didn't work. * Theme + Plugins - Tried activating Twenty Fifteen and deactivating all plugins; didn't work. * Normal comments - Regular characters save and display as comments just fine. * Emoji - they display in the 'comment field' when adding a comment, but once submitted, the seem to be stripped out. In wp-admin an emoji comment just seems to be blank with no text at all. I have tried all of the basic troubleshooting I can think of, are there any other things I am not thinking of?
You are looking for the function `get_header()`. `wp_head()` is the internal function of WordPress for doing things inside the head section (listing scripts, styles, metadata etc.). The real HTML output comes from the function `get_header()`, which includes your theme's `header.php`. I suppose that you do not really want just this part of the header, as it leaves a lot of tags open, so my suggestion would be to create a file in your theme folder: `header-justthehead.php` You can the call this file with a simple line: ``` get_header( 'justthehead' ); ``` and you are in full control of the output for your custom header, and you do not have to mess with the header of your website itself. The only thing you still have to take care of, is that the right post is loaded. Define the `$args` for your `query_posts()`, and this should work for you. Never forget the `wp_reset_query()` - even if you do not need it in this case. ``` include( 'wp-load.php' ); // loads WordPress Environment query_posts( $args ); // load your desired Post/Page if ( have_posts() ) : while ( have_posts() ) : the_post(); // Setup the Post/Page get_header( 'justthehead' ); // Get your custom header-justthehead.php, containing your wp_head() call endwhile; endif; // quit the loop wp_reset_query(); // clean it up ```
185,299
<p>As a WordPress admin newbie, I just went through my first non-automatic WordPress upgrade.</p> <p>I upgraded five different WordPress installs from 4.1.3 to 4.2.</p> <p>They all refer to different web sites hosted on the same web host as one main domain and four addon domains.</p> <p>On each of the websites, I use the following plug-ins:</p> <ul> <li>Akismet;</li> <li>Google Analytics by Yoast;</li> <li>Google Adsense;</li> <li>Google XML Sitemaps and</li> <li>Jetpack by WordPress.com.</li> </ul> <p>In order to streamline further administration, I considering consolidating all five installs into a single multisite install.</p> <p>So far, I have found it quite hard to find definitive answers on the compatibility of each of those plugins with a multisite installation on the plugin's websites.</p> <p><strong>Is the plugin's page the right place to search for this?</strong></p> <p><strong>Is there a central location where this information can be found?</strong></p>
[ { "answer_id": 185303, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Unless a plugin states it's compatible, the only reliable way to find out is to create a local multisite installation and test it.</p>\n\n<p>Sometimes there are signs you can look for, but these are always a symptom of bad code, e.g. hardcoding database table names rather than using the prefix from <code>$wpdb</code>, in which case I would recommend steering clear of the plugin even if you don't use multisite</p>\n" }, { "answer_id": 185307, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 4, "selected": true, "text": "<p>There are two types of multisite compatibility: </p>\n\n<ol>\n<li>Passive compatibility: doing nothing multisite specific, just works without breaking anything.</li>\n<li>Active compatibility: changing or extending multisite specific behavior.</li>\n</ol>\n\n<p>I guess you are out for 1. See my <a href=\"http://slides.wpkrauts.com/2015/prague-multisite/\">slides from WordCamp Prague 2015</a> for the second part.</p>\n\n<p>Plugins that do not say anything about multisite should not be activated as network plugins. WooCommerce for example creates some custom tables during the installation. If you activate it network-wide, the subsites don’t get these tables and the sky will fall onto your head.</p>\n\n<p>Unfortunately, most plugins don’t check for their activation type, so they let you do the wrong activation. </p>\n\n<p>related are UX problems like admin pointers or special \"About\" pages that you have to click away on ever subsite in non-compatible plugins. <a href=\"https://github.com/Yoast/wordpress-seo/issues/2282\">Yoast’s WP SEO is one example</a>. This will be fixed in that plugin soon, I guess. :)</p>\n\n<p>Other issues depend on what you do with that multisite. If you are building a multilingual website where each site is written in one language and the sites are connected with each other, you want to synchronize the posts when you write content. That means that you call <code>switch_to_blog()</code> on the hook <code>save_post</code>, and save the connected posts too. <code>save_post</code> will be called multiple times during one request now. Many plugins are not aware of such a situation, so they just overwrite the post meta information for the connected posts, thinking that they are still on the first post.</p>\n\n<p>Look out for plugins that are dealing with post meta and lack a check like this:</p>\n\n<pre><code>if ( is_multisite() &amp;&amp; ms_is_switched() )\n return FALSE;\n</code></pre>\n\n<p>These plugins are not compatible.</p>\n\n<p>Similar, albeit harder to specify, are issues when plugins touch user meta fields or rewrite rules. </p>\n\n<p>Some plugins try write content into files without including the site ID in the file name. They are very likely broken too.</p>\n\n<p>Like Tom said: Create a test installation, run every use case you can imagine. You cannot trust the plugin page, and usually there is not enough information anyway.</p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185299", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68808/" ]
As a WordPress admin newbie, I just went through my first non-automatic WordPress upgrade. I upgraded five different WordPress installs from 4.1.3 to 4.2. They all refer to different web sites hosted on the same web host as one main domain and four addon domains. On each of the websites, I use the following plug-ins: * Akismet; * Google Analytics by Yoast; * Google Adsense; * Google XML Sitemaps and * Jetpack by WordPress.com. In order to streamline further administration, I considering consolidating all five installs into a single multisite install. So far, I have found it quite hard to find definitive answers on the compatibility of each of those plugins with a multisite installation on the plugin's websites. **Is the plugin's page the right place to search for this?** **Is there a central location where this information can be found?**
There are two types of multisite compatibility: 1. Passive compatibility: doing nothing multisite specific, just works without breaking anything. 2. Active compatibility: changing or extending multisite specific behavior. I guess you are out for 1. See my [slides from WordCamp Prague 2015](http://slides.wpkrauts.com/2015/prague-multisite/) for the second part. Plugins that do not say anything about multisite should not be activated as network plugins. WooCommerce for example creates some custom tables during the installation. If you activate it network-wide, the subsites don’t get these tables and the sky will fall onto your head. Unfortunately, most plugins don’t check for their activation type, so they let you do the wrong activation. related are UX problems like admin pointers or special "About" pages that you have to click away on ever subsite in non-compatible plugins. [Yoast’s WP SEO is one example](https://github.com/Yoast/wordpress-seo/issues/2282). This will be fixed in that plugin soon, I guess. :) Other issues depend on what you do with that multisite. If you are building a multilingual website where each site is written in one language and the sites are connected with each other, you want to synchronize the posts when you write content. That means that you call `switch_to_blog()` on the hook `save_post`, and save the connected posts too. `save_post` will be called multiple times during one request now. Many plugins are not aware of such a situation, so they just overwrite the post meta information for the connected posts, thinking that they are still on the first post. Look out for plugins that are dealing with post meta and lack a check like this: ``` if ( is_multisite() && ms_is_switched() ) return FALSE; ``` These plugins are not compatible. Similar, albeit harder to specify, are issues when plugins touch user meta fields or rewrite rules. Some plugins try write content into files without including the site ID in the file name. They are very likely broken too. Like Tom said: Create a test installation, run every use case you can imagine. You cannot trust the plugin page, and usually there is not enough information anyway.
185,313
<p>Trying to make a custom 'read more' link for different custom post types. </p> <p>Tried this code but does not work as expected. Fairly certain the if/else logic is amiss.</p> <p>Using a Genesis theme if that makes a difference.</p> <pre><code>function excerpt_read_more_link($output) { global $post; if ($post-&gt;post_type = 'speaker') { $output .= '&lt;p&gt;&lt;a class="speaker-more-link" href="'. get_permalink($post-&gt;ID) . '"&gt;View Speaker Profile&lt;/a&gt;&lt;/p&gt;'; } elseif ($post-&gt;post_type = 'resources') { $output .= '&lt;p&gt;&lt;a class="speaker-more-link" href="'. get_permalink($post-&gt;ID) . '"&gt;More Resource Content&lt;/a&gt;&lt;/p&gt;'; } else $read_more_text = 'Read more'; return $output . '&lt;a class="more-link" href="'. get_permalink($post-&gt;ID) . '"&gt;'.$read_more_text.'&lt;/a&gt;'; } add_filter('the_excerpt', 'excerpt_read_more_link'); </code></pre>
[ { "answer_id": 185303, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Unless a plugin states it's compatible, the only reliable way to find out is to create a local multisite installation and test it.</p>\n\n<p>Sometimes there are signs you can look for, but these are always a symptom of bad code, e.g. hardcoding database table names rather than using the prefix from <code>$wpdb</code>, in which case I would recommend steering clear of the plugin even if you don't use multisite</p>\n" }, { "answer_id": 185307, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 4, "selected": true, "text": "<p>There are two types of multisite compatibility: </p>\n\n<ol>\n<li>Passive compatibility: doing nothing multisite specific, just works without breaking anything.</li>\n<li>Active compatibility: changing or extending multisite specific behavior.</li>\n</ol>\n\n<p>I guess you are out for 1. See my <a href=\"http://slides.wpkrauts.com/2015/prague-multisite/\">slides from WordCamp Prague 2015</a> for the second part.</p>\n\n<p>Plugins that do not say anything about multisite should not be activated as network plugins. WooCommerce for example creates some custom tables during the installation. If you activate it network-wide, the subsites don’t get these tables and the sky will fall onto your head.</p>\n\n<p>Unfortunately, most plugins don’t check for their activation type, so they let you do the wrong activation. </p>\n\n<p>related are UX problems like admin pointers or special \"About\" pages that you have to click away on ever subsite in non-compatible plugins. <a href=\"https://github.com/Yoast/wordpress-seo/issues/2282\">Yoast’s WP SEO is one example</a>. This will be fixed in that plugin soon, I guess. :)</p>\n\n<p>Other issues depend on what you do with that multisite. If you are building a multilingual website where each site is written in one language and the sites are connected with each other, you want to synchronize the posts when you write content. That means that you call <code>switch_to_blog()</code> on the hook <code>save_post</code>, and save the connected posts too. <code>save_post</code> will be called multiple times during one request now. Many plugins are not aware of such a situation, so they just overwrite the post meta information for the connected posts, thinking that they are still on the first post.</p>\n\n<p>Look out for plugins that are dealing with post meta and lack a check like this:</p>\n\n<pre><code>if ( is_multisite() &amp;&amp; ms_is_switched() )\n return FALSE;\n</code></pre>\n\n<p>These plugins are not compatible.</p>\n\n<p>Similar, albeit harder to specify, are issues when plugins touch user meta fields or rewrite rules. </p>\n\n<p>Some plugins try write content into files without including the site ID in the file name. They are very likely broken too.</p>\n\n<p>Like Tom said: Create a test installation, run every use case you can imagine. You cannot trust the plugin page, and usually there is not enough information anyway.</p>\n" } ]
2015/04/24
[ "https://wordpress.stackexchange.com/questions/185313", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54058/" ]
Trying to make a custom 'read more' link for different custom post types. Tried this code but does not work as expected. Fairly certain the if/else logic is amiss. Using a Genesis theme if that makes a difference. ``` function excerpt_read_more_link($output) { global $post; if ($post->post_type = 'speaker') { $output .= '<p><a class="speaker-more-link" href="'. get_permalink($post->ID) . '">View Speaker Profile</a></p>'; } elseif ($post->post_type = 'resources') { $output .= '<p><a class="speaker-more-link" href="'. get_permalink($post->ID) . '">More Resource Content</a></p>'; } else $read_more_text = 'Read more'; return $output . '<a class="more-link" href="'. get_permalink($post->ID) . '">'.$read_more_text.'</a>'; } add_filter('the_excerpt', 'excerpt_read_more_link'); ```
There are two types of multisite compatibility: 1. Passive compatibility: doing nothing multisite specific, just works without breaking anything. 2. Active compatibility: changing or extending multisite specific behavior. I guess you are out for 1. See my [slides from WordCamp Prague 2015](http://slides.wpkrauts.com/2015/prague-multisite/) for the second part. Plugins that do not say anything about multisite should not be activated as network plugins. WooCommerce for example creates some custom tables during the installation. If you activate it network-wide, the subsites don’t get these tables and the sky will fall onto your head. Unfortunately, most plugins don’t check for their activation type, so they let you do the wrong activation. related are UX problems like admin pointers or special "About" pages that you have to click away on ever subsite in non-compatible plugins. [Yoast’s WP SEO is one example](https://github.com/Yoast/wordpress-seo/issues/2282). This will be fixed in that plugin soon, I guess. :) Other issues depend on what you do with that multisite. If you are building a multilingual website where each site is written in one language and the sites are connected with each other, you want to synchronize the posts when you write content. That means that you call `switch_to_blog()` on the hook `save_post`, and save the connected posts too. `save_post` will be called multiple times during one request now. Many plugins are not aware of such a situation, so they just overwrite the post meta information for the connected posts, thinking that they are still on the first post. Look out for plugins that are dealing with post meta and lack a check like this: ``` if ( is_multisite() && ms_is_switched() ) return FALSE; ``` These plugins are not compatible. Similar, albeit harder to specify, are issues when plugins touch user meta fields or rewrite rules. Some plugins try write content into files without including the site ID in the file name. They are very likely broken too. Like Tom said: Create a test installation, run every use case you can imagine. You cannot trust the plugin page, and usually there is not enough information anyway.
185,315
<p>I am working on a custom theme using ACF. I would like to check if the plugin is active or not. I am using this code:</p> <pre><code>&lt;?php include_once( ABSPATH . 'wp-content/plugins/advanced-custom-fields-pro/acf.php' ); if ( is_plugin_active( 'advanced-custom-fields-pro/acf.php' ) ) { echo "hi"; } ?&gt; </code></pre> <p>However, I am getting the following error:</p> <p>Fatal error: Call to undefined function is_plugin_active() in /Users/johann/htdocs/clarity_v21/wp-content/themes/clarity/templates/header.php on line 21</p> <p>Any ideas what could be wrong?</p> <hr> <p>So based on the provided answer I tried:</p> <pre><code>if( class_exists('acf') ) { if (($header_style)=='style2') { } </code></pre> <p>and it worked! So basically the solution is to try to find a class that's related to the plugin you are trying to check on. In this case, the class "acf" is specific to the Advanced Custom Fields plugin and allowed me to run the conditional only if the plugin was active.</p>
[ { "answer_id": 185330, "author": "Behzad", "author_id": 70359, "author_profile": "https://wordpress.stackexchange.com/users/70359", "pm_score": 5, "selected": true, "text": "<p>Try to check <strong>class_exists</strong>: </p>\n\n<pre><code>&lt;?php \n if( class_exists('acf') ) {\n echo \"hi\";\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 185341, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 3, "selected": false, "text": "<p><code>is_plugin_active()</code> only available inside the admin area.\nYou need to include the core <code>plugin.php</code> file in front end to use this function.</p>\n\n<p>From WordPress <a href=\"https://codex.wordpress.org/Function_Reference/is_plugin_active\" rel=\"noreferrer\">documentation</a></p>\n\n<blockquote>\n <p>NOTE: defined in wp-admin/includes/plugin.php, so this is only\n available from within the admin pages, and any references to this\n function must be hooked to admin_init or a later action. If you want\n to use this function from within a template, you will need to manually\n require plugin.php, an example is below.</p>\n</blockquote>\n\n<p>So it will be like </p>\n\n<pre><code>&lt;?php include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); \nif ( is_plugin_active( 'advanced-custom-fields-pro/acf.php' ) ) {\n echo \"hi\";\n} ?&gt;\n</code></pre>\n" } ]
2015/04/25
[ "https://wordpress.stackexchange.com/questions/185315", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21245/" ]
I am working on a custom theme using ACF. I would like to check if the plugin is active or not. I am using this code: ``` <?php include_once( ABSPATH . 'wp-content/plugins/advanced-custom-fields-pro/acf.php' ); if ( is_plugin_active( 'advanced-custom-fields-pro/acf.php' ) ) { echo "hi"; } ?> ``` However, I am getting the following error: Fatal error: Call to undefined function is\_plugin\_active() in /Users/johann/htdocs/clarity\_v21/wp-content/themes/clarity/templates/header.php on line 21 Any ideas what could be wrong? --- So based on the provided answer I tried: ``` if( class_exists('acf') ) { if (($header_style)=='style2') { } ``` and it worked! So basically the solution is to try to find a class that's related to the plugin you are trying to check on. In this case, the class "acf" is specific to the Advanced Custom Fields plugin and allowed me to run the conditional only if the plugin was active.
Try to check **class\_exists**: ``` <?php if( class_exists('acf') ) { echo "hi"; } ?> ```