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
243,942
<p>I implement a <code>class</code> structure in my plugin, for example:</p> <pre><code>class Ethans_Plugin { public function __construct() { add_filter( 'admin_init', array( $this, 'admin' ), 10, 1 ); add_action( 'admin_footer', array( $this, 'footer' ), 10, 1 ); } public function admin() { # code here... } public function footer() { # code here... } } </code></pre> <p>When I define functions with generic names such as <code>admin</code> or <code>footer</code> will this conflict with any other function that have the same names? Or, since they are within a class, these function names will make them unique?</p>
[ { "answer_id": 243943, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": -1, "selected": false, "text": "<p>yes. they could conflict. Always create your namespace. What if another ethan is thinking the exact same thing as you? MIND BLOWN!</p>\n" }, { "answer_id": 243947, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 4, "selected": true, "text": "<p>A method name is not callable without an instance of the class, so no, it cannot conflict with the same method names from other classes, because the class names, including the namespace, must be unique.</p>\n\n<p>Btw: <a href=\"https://wordpress.stackexchange.com/a/166532/73\">Never register callbacks in a constructor</a>.</p>\n" } ]
2016/10/25
[ "https://wordpress.stackexchange.com/questions/243942", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98212/" ]
I implement a `class` structure in my plugin, for example: ``` class Ethans_Plugin { public function __construct() { add_filter( 'admin_init', array( $this, 'admin' ), 10, 1 ); add_action( 'admin_footer', array( $this, 'footer' ), 10, 1 ); } public function admin() { # code here... } public function footer() { # code here... } } ``` When I define functions with generic names such as `admin` or `footer` will this conflict with any other function that have the same names? Or, since they are within a class, these function names will make them unique?
A method name is not callable without an instance of the class, so no, it cannot conflict with the same method names from other classes, because the class names, including the namespace, must be unique. Btw: [Never register callbacks in a constructor](https://wordpress.stackexchange.com/a/166532/73).
243,949
<p>I would like to add a rewrite for only certain pages (not all pages) that would insert a base slug into the permalink. This is sort of a unique situation where we know all the page names beforehand and they will not change.</p> <p><strong>For example:</strong></p> <p><code>sitename.com/pagetitle</code></p> <p>to</p> <p><code>sitename.com/service/pagetitle</code></p> <p>I am trying to use "add_rewrite_rule", but not having much luck. Below is one of my iterations and I have had many. Any guidance would be appreciated.</p> <p>I understand that there is a plugin that allows you to totally change your permalinks of your post and pages to whatever you want, but was hoping I could do it programmatically myself.</p> <pre><code>add_action( 'init', 'page_change' ); function page_change() { add_rewrite_rule( '^pagenamehere/?', 'index.php?post_type=service', 'top' ); } </code></pre> <p><strong>Updated code below:</strong></p> <pre><code>function new_rewrite_rule() { add_rewrite_rule('^services/statictitle$', 'index.php?pagename=oldname', 'top'); } add_action('init', 'new_rewrite_rule'); </code></pre> <p>So this code allows the link to be accessible at 'services/statictitle.' However, the old link is still accessible as well. So I am not sure I am going about this in the correct way.....Any help would be appreciated.</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Here is an alternative way that I think might be more suitable. Although, this targets all pages. Would there be a way to just target the pagename or id?</p> <pre><code>function custom_page_rules() { global $wp_rewrite; $wp_rewrite-&gt;page_structure = $wp_rewrite-&gt;root . 'services/%pagename%'; } </code></pre>
[ { "answer_id": 244228, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 2, "selected": false, "text": "<p><strong>Asumption:</strong> You use Apache as your web server.</p>\n\n<p>If you already know the page slugs and they won't change, just add them to your <code>.htaccess</code> file. It'll be much faster and less complicated. </p>\n\n<p>Paste the following <code>Redirect</code> lines at the top of your <code>.htaccess</code> file.</p>\n\n<pre><code>Redirect 301 /pagetitle/ /service/pagetitle/\nRedirect 301 /pagetitle2/ /another-dir/pagetitle2/\n\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n....\n</code></pre>\n" }, { "answer_id": 244231, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 0, "selected": false, "text": "<p>Please have a look on the code below:</p>\n\n<pre><code>add_rewrite_rule( 'services/([^/]*)/?','index.php?post_type='.$post_type.'&name=$matches[1]','top');\n</code></pre>\n\n<p>For better understanding of rewrite API please check the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Rewrite\" rel=\"nofollow\">WP_REWRITE_API</a> and <a href=\"https://premium.wpmudev.org/blog/building-customized-urls-wordpress/?utm_expid=3606929-90.6a_uo883STWy99lnGf8x1g.0\" rel=\"nofollow\">Building Customized URLs in WordPress</a></p>\n\n<p>Waiting for your feedback!</p>\n\n<p>Hope it will work for you!</p>\n" }, { "answer_id": 244511, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>This approach might be a little more flexible.</p>\n\n<pre><code>$basePageRewrite-&gt;add_rule( 'service', 'page-title' );\n</code></pre>\n\n<p>At the end of the class definition you should be able to add a <code>base</code> and <code>page</code>. The URL rewrites will be constructed dynamically for the rules you add. If a <code>page</code> is called directly is will be redirected to the <code>$base/$pageTitle</code>.</p>\n\n<pre><code>&lt;?php\n\nif ( ! class_exists( 'BasePageRewrite' ) ):\n\n class BasePageRewrite {\n\n const ENDPOINT_QUERY_PARAM_REDIRECT = '____base_page_rewrite__redirect';\n\n private static $_hash_map = array ();\n\n /**\n * BasePageRewrite constructor.\n */\n public function __construct() {\n add_filter( 'query_vars', array ( $this, 'add_query_vars' ), 0 );\n add_action( 'parse_request', array ( $this, 'sniff_requests' ), 0 );\n add_action( 'init', array ( $this, 'add_endpoint' ), 0 );\n }\n\n /**\n * Add rewrite rules here.\n *\n * @param string $base Base of URL\n * @param string $page Slug of page\n */\n public function add_rule( $base, $page ) {\n if ( ! array_key_exists( $base, static::$_hash_map ) ) {\n static::$_hash_map[ $base ] = array ();\n }\n\n if ( ! array_key_exists( $page, static::$_hash_map[ $base ] ) ) {\n static::$_hash_map[ $base ][ $page ] = 'name';\n }\n }\n\n /**\n * Add our custom query arg to check in `parse_request`.\n *\n * @param $vars\n *\n * @return array\n */\n public function add_query_vars( $vars ) {\n $vars[] = static::ENDPOINT_QUERY_PARAM_REDIRECT;\n\n return $vars;\n }\n\n /**\n * Add rewrite rules.\n *\n * page --&gt; base/page\n *\n * base/page === page\n *\n * Note:\n *\n * `flush_rewrite_rules()` is only added for testing.\n */\n public function add_endpoint() {\n\n foreach ( static::$_hash_map as $base =&gt; $pages ) {\n\n foreach ( $pages as $pageName =&gt; $param ) {\n\n // page --&gt; service/page\n\n add_rewrite_rule( \"^$pageName/\", 'index.php?' . static::ENDPOINT_QUERY_PARAM_REDIRECT . \"=/$base/$pageName/\", 'top' );\n\n // service/page === page\n\n add_rewrite_rule( \"^$base/$pageName/\", \"index.php?$param=$pageName\", 'top' );\n }\n }\n\n //////////////////////////////////\n flush_rewrite_rules( true ); //// &lt;---------- REMOVE THIS WHEN DONE TESTING\n //////////////////////////////////\n }\n\n /**\n * Redirect regular page to base/page,\n *\n * @param $wp_query\n */\n public function sniff_requests( $wp_query ) {\n\n global $wp;\n\n if ( isset( $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM_REDIRECT ] ) ) {\n\n // page --&gt; service/page\n\n $redirect = $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM_REDIRECT ];\n $new_url = site_url( $redirect );\n wp_redirect( $new_url, 301 );\n die();\n }\n }\n }\n\n // Create the class\n $basePageRewrite = new BasePageRewrite();\n\n // Add individual rules\n $basePageRewrite-&gt;add_rule( 'service', 'page-title' );\n $basePageRewrite-&gt;add_rule( 'another-service', 'another-page-title' );\n\nendif; // BasePageRewrite\n</code></pre>\n" }, { "answer_id": 244945, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The other part that you need to do here, it is to change the permalink of the page with the <code>page_link</code> filter or <code>the_permalink</code> filter.</p>\n\n<p>here is a mirror question to your own - <a href=\"https://stackoverflow.com/questions/27432586/wordpress-page-link-filter\">https://stackoverflow.com/questions/27432586/wordpress-page-link-filter</a></p>\n\n<p>This will do the redirects because wordpress redirects to the canonical address when the url being accessed is different then the canonical one, and the canonical url for posts and pages is their permalink. As an added bonus you get everything else pointing to the right URL as well with no need of redirection at all.</p>\n" }, { "answer_id": 244958, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 0, "selected": false, "text": "<p>I know you specifically asked for rewrite rules, but what about redirection? You can achieve the same end result and same user experience. You can change the hierarchy of your pages if you want so that</p>\n\n<pre><code>sitename.com/service/pagetitle\n</code></pre>\n\n<p>is available and</p>\n\n<pre><code>sitename.com/pagetitle\n</code></pre>\n\n<p>is something that gets redirected to the first address.</p>\n\n<p>This skips your <code>.htaccess</code> altogether for simplicity. It looks like you actually want to learn how to do this as a rewrite rule, which is cool, but if you decide that it is being difficult and you just want a solution that works whether you learn this or not then there are a few different redirection plugins that can handle this for you. My personal favorite is titled \"Redirection\" and it can handle regex (with a little practice) and it also counts the number of times a redirect rule is used so that you can monitor if you even need to keep it in place.</p>\n\n<p>Lastly, I mentioned in the beginning that you can change your page hierarchy to reflect what you want your URLs to look like and you should probably do this either way if you haven't already. If not then you might find yourself with an infinite redirect situation. (which is also something to keep in mind if you go the redirect plugin route as well as I've seen this happen easily with users who have a lot of redirects and they make a new one that conflicts with one that already exists.)</p>\n\n<p><strong>TLDR</strong>: outside the box answer. there are one or more plugins that can achieve this function without actually doing a rewrite.</p>\n" }, { "answer_id": 244977, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 0, "selected": false, "text": "<p>I've encountered a very similar situation to what seems to be your expectations.</p>\n\n<p>We have a parent page \"Our Services\" (<code>domain.com/services/</code>) ...</p>\n\n<p>We also have several child pages representing each service provided under the parent page \"Our Services\". For example: \"Web Design\" (<code>domain.com/services/web-design/</code>)</p>\n\n<p>Now, we also have a \"Portfolio\". Instead of dedicating an entire top level section on the website for the portfolio, we decided that we wanted it underneath the main \"services\" section (<code>domain.com/services/</code>). </p>\n\n<p>So for example, the main section of our portfolio was to be located here: <code>domain.com/services/portfolio/</code></p>\n\n<p>The portfolio is it's own custom post type, containing individual portfolio items.</p>\n\n<p>So the URL to a specific portfolio item looked like this: <code>domain.com/services/portfolio/sample-portfolio-item/</code>.</p>\n\n<p>When you register your custom post type, there's a configurable parameter for <code>rewrite['slug']</code>. This is where you would specify <code>$args['rewrite']['slug'] = 'services/portfolio';</code></p>\n\n<p>Of course, anytime you make changes to URL rewrite rules, you need to flush the rewrite rules. Programmatically you would use <code>flush_rewrite_rules();</code> optionally for quick testing you could always just navigate to <code>Dashboard -&gt; Settings -&gt; Permalinks</code> since this automatically flushes the rewrite rules for you, simply just by visiting that admin page.</p>\n\n<p>Hope you (or someone) finds the information in my answer useful and relevant.</p>\n" } ]
2016/10/25
[ "https://wordpress.stackexchange.com/questions/243949", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60781/" ]
I would like to add a rewrite for only certain pages (not all pages) that would insert a base slug into the permalink. This is sort of a unique situation where we know all the page names beforehand and they will not change. **For example:** `sitename.com/pagetitle` to `sitename.com/service/pagetitle` I am trying to use "add\_rewrite\_rule", but not having much luck. Below is one of my iterations and I have had many. Any guidance would be appreciated. I understand that there is a plugin that allows you to totally change your permalinks of your post and pages to whatever you want, but was hoping I could do it programmatically myself. ``` add_action( 'init', 'page_change' ); function page_change() { add_rewrite_rule( '^pagenamehere/?', 'index.php?post_type=service', 'top' ); } ``` **Updated code below:** ``` function new_rewrite_rule() { add_rewrite_rule('^services/statictitle$', 'index.php?pagename=oldname', 'top'); } add_action('init', 'new_rewrite_rule'); ``` So this code allows the link to be accessible at 'services/statictitle.' However, the old link is still accessible as well. So I am not sure I am going about this in the correct way.....Any help would be appreciated. Thanks. **Update** Here is an alternative way that I think might be more suitable. Although, this targets all pages. Would there be a way to just target the pagename or id? ``` function custom_page_rules() { global $wp_rewrite; $wp_rewrite->page_structure = $wp_rewrite->root . 'services/%pagename%'; } ```
**Asumption:** You use Apache as your web server. If you already know the page slugs and they won't change, just add them to your `.htaccess` file. It'll be much faster and less complicated. Paste the following `Redirect` lines at the top of your `.htaccess` file. ``` Redirect 301 /pagetitle/ /service/pagetitle/ Redirect 301 /pagetitle2/ /another-dir/pagetitle2/ # BEGIN WordPress <IfModule mod_rewrite.c> .... ```
243,952
<p>I found this code that works perfectly what I'm working on but needs a minor changes. What I need is to just display the sub categories of the parent. </p> <p>How do I alter the <code>get_categories()</code> to only get the specific categories I need? because doing this will display all available categories.</p> <pre><code>function ba_SearchFilter($query) { if (!$query-&gt;is_search) { return $query; } if (isset($_POST['cat'])){ $query-&gt;set('category__and', $_POST['cat']); } if (isset($_POST['tags'])){ $query-&gt;set('tag__and', $_POST['tags']); } return $query; } //hook filters to search add_filter('pre_get_posts','ba_SearchFilter'); function ba_search_with_filters(){ $out = '&lt;form role="search" method="get" id="searchform" action="'. home_url( '/' ).'"&gt; &lt;div&gt;&lt;label class="screen-reader-text" for="s"&gt;Search for:&lt;/label&gt; &lt;input type="text" value="" name="s" id="s" /&gt;&lt;br /&gt;'; $categories= get_categories(); foreach ($categories as $category) { $option = ''; $option .= '&lt;input type="checkbox" name="cat[]" id="cat[]" value="'.$category-&gt;term_id.'"&gt; '; $option .= $category-&gt;cat_name .'&lt;br /&gt;'; $out.= $option; } $tags= get_categories(); foreach ($tags as $tag) { $option = ''; $option .= '&lt;input type="checkbox" name="tags[]" id="tags[]" value="'.$tag-&gt;term_id.'"&gt; '; $option .= $tag-&gt;cat_name .'&lt;br /&gt;'; $out.= $option; } $out .='&lt;input type="submit" id="searchsubmit" value="Search" /&gt; &lt;/div&gt; &lt;/form&gt;'; return $out; } add_shortcode('search_with_filter','ba_search_with_filters'); </code></pre>
[ { "answer_id": 244228, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 2, "selected": false, "text": "<p><strong>Asumption:</strong> You use Apache as your web server.</p>\n\n<p>If you already know the page slugs and they won't change, just add them to your <code>.htaccess</code> file. It'll be much faster and less complicated. </p>\n\n<p>Paste the following <code>Redirect</code> lines at the top of your <code>.htaccess</code> file.</p>\n\n<pre><code>Redirect 301 /pagetitle/ /service/pagetitle/\nRedirect 301 /pagetitle2/ /another-dir/pagetitle2/\n\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n....\n</code></pre>\n" }, { "answer_id": 244231, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 0, "selected": false, "text": "<p>Please have a look on the code below:</p>\n\n<pre><code>add_rewrite_rule( 'services/([^/]*)/?','index.php?post_type='.$post_type.'&name=$matches[1]','top');\n</code></pre>\n\n<p>For better understanding of rewrite API please check the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Rewrite\" rel=\"nofollow\">WP_REWRITE_API</a> and <a href=\"https://premium.wpmudev.org/blog/building-customized-urls-wordpress/?utm_expid=3606929-90.6a_uo883STWy99lnGf8x1g.0\" rel=\"nofollow\">Building Customized URLs in WordPress</a></p>\n\n<p>Waiting for your feedback!</p>\n\n<p>Hope it will work for you!</p>\n" }, { "answer_id": 244511, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>This approach might be a little more flexible.</p>\n\n<pre><code>$basePageRewrite-&gt;add_rule( 'service', 'page-title' );\n</code></pre>\n\n<p>At the end of the class definition you should be able to add a <code>base</code> and <code>page</code>. The URL rewrites will be constructed dynamically for the rules you add. If a <code>page</code> is called directly is will be redirected to the <code>$base/$pageTitle</code>.</p>\n\n<pre><code>&lt;?php\n\nif ( ! class_exists( 'BasePageRewrite' ) ):\n\n class BasePageRewrite {\n\n const ENDPOINT_QUERY_PARAM_REDIRECT = '____base_page_rewrite__redirect';\n\n private static $_hash_map = array ();\n\n /**\n * BasePageRewrite constructor.\n */\n public function __construct() {\n add_filter( 'query_vars', array ( $this, 'add_query_vars' ), 0 );\n add_action( 'parse_request', array ( $this, 'sniff_requests' ), 0 );\n add_action( 'init', array ( $this, 'add_endpoint' ), 0 );\n }\n\n /**\n * Add rewrite rules here.\n *\n * @param string $base Base of URL\n * @param string $page Slug of page\n */\n public function add_rule( $base, $page ) {\n if ( ! array_key_exists( $base, static::$_hash_map ) ) {\n static::$_hash_map[ $base ] = array ();\n }\n\n if ( ! array_key_exists( $page, static::$_hash_map[ $base ] ) ) {\n static::$_hash_map[ $base ][ $page ] = 'name';\n }\n }\n\n /**\n * Add our custom query arg to check in `parse_request`.\n *\n * @param $vars\n *\n * @return array\n */\n public function add_query_vars( $vars ) {\n $vars[] = static::ENDPOINT_QUERY_PARAM_REDIRECT;\n\n return $vars;\n }\n\n /**\n * Add rewrite rules.\n *\n * page --&gt; base/page\n *\n * base/page === page\n *\n * Note:\n *\n * `flush_rewrite_rules()` is only added for testing.\n */\n public function add_endpoint() {\n\n foreach ( static::$_hash_map as $base =&gt; $pages ) {\n\n foreach ( $pages as $pageName =&gt; $param ) {\n\n // page --&gt; service/page\n\n add_rewrite_rule( \"^$pageName/\", 'index.php?' . static::ENDPOINT_QUERY_PARAM_REDIRECT . \"=/$base/$pageName/\", 'top' );\n\n // service/page === page\n\n add_rewrite_rule( \"^$base/$pageName/\", \"index.php?$param=$pageName\", 'top' );\n }\n }\n\n //////////////////////////////////\n flush_rewrite_rules( true ); //// &lt;---------- REMOVE THIS WHEN DONE TESTING\n //////////////////////////////////\n }\n\n /**\n * Redirect regular page to base/page,\n *\n * @param $wp_query\n */\n public function sniff_requests( $wp_query ) {\n\n global $wp;\n\n if ( isset( $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM_REDIRECT ] ) ) {\n\n // page --&gt; service/page\n\n $redirect = $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM_REDIRECT ];\n $new_url = site_url( $redirect );\n wp_redirect( $new_url, 301 );\n die();\n }\n }\n }\n\n // Create the class\n $basePageRewrite = new BasePageRewrite();\n\n // Add individual rules\n $basePageRewrite-&gt;add_rule( 'service', 'page-title' );\n $basePageRewrite-&gt;add_rule( 'another-service', 'another-page-title' );\n\nendif; // BasePageRewrite\n</code></pre>\n" }, { "answer_id": 244945, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The other part that you need to do here, it is to change the permalink of the page with the <code>page_link</code> filter or <code>the_permalink</code> filter.</p>\n\n<p>here is a mirror question to your own - <a href=\"https://stackoverflow.com/questions/27432586/wordpress-page-link-filter\">https://stackoverflow.com/questions/27432586/wordpress-page-link-filter</a></p>\n\n<p>This will do the redirects because wordpress redirects to the canonical address when the url being accessed is different then the canonical one, and the canonical url for posts and pages is their permalink. As an added bonus you get everything else pointing to the right URL as well with no need of redirection at all.</p>\n" }, { "answer_id": 244958, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 0, "selected": false, "text": "<p>I know you specifically asked for rewrite rules, but what about redirection? You can achieve the same end result and same user experience. You can change the hierarchy of your pages if you want so that</p>\n\n<pre><code>sitename.com/service/pagetitle\n</code></pre>\n\n<p>is available and</p>\n\n<pre><code>sitename.com/pagetitle\n</code></pre>\n\n<p>is something that gets redirected to the first address.</p>\n\n<p>This skips your <code>.htaccess</code> altogether for simplicity. It looks like you actually want to learn how to do this as a rewrite rule, which is cool, but if you decide that it is being difficult and you just want a solution that works whether you learn this or not then there are a few different redirection plugins that can handle this for you. My personal favorite is titled \"Redirection\" and it can handle regex (with a little practice) and it also counts the number of times a redirect rule is used so that you can monitor if you even need to keep it in place.</p>\n\n<p>Lastly, I mentioned in the beginning that you can change your page hierarchy to reflect what you want your URLs to look like and you should probably do this either way if you haven't already. If not then you might find yourself with an infinite redirect situation. (which is also something to keep in mind if you go the redirect plugin route as well as I've seen this happen easily with users who have a lot of redirects and they make a new one that conflicts with one that already exists.)</p>\n\n<p><strong>TLDR</strong>: outside the box answer. there are one or more plugins that can achieve this function without actually doing a rewrite.</p>\n" }, { "answer_id": 244977, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 0, "selected": false, "text": "<p>I've encountered a very similar situation to what seems to be your expectations.</p>\n\n<p>We have a parent page \"Our Services\" (<code>domain.com/services/</code>) ...</p>\n\n<p>We also have several child pages representing each service provided under the parent page \"Our Services\". For example: \"Web Design\" (<code>domain.com/services/web-design/</code>)</p>\n\n<p>Now, we also have a \"Portfolio\". Instead of dedicating an entire top level section on the website for the portfolio, we decided that we wanted it underneath the main \"services\" section (<code>domain.com/services/</code>). </p>\n\n<p>So for example, the main section of our portfolio was to be located here: <code>domain.com/services/portfolio/</code></p>\n\n<p>The portfolio is it's own custom post type, containing individual portfolio items.</p>\n\n<p>So the URL to a specific portfolio item looked like this: <code>domain.com/services/portfolio/sample-portfolio-item/</code>.</p>\n\n<p>When you register your custom post type, there's a configurable parameter for <code>rewrite['slug']</code>. This is where you would specify <code>$args['rewrite']['slug'] = 'services/portfolio';</code></p>\n\n<p>Of course, anytime you make changes to URL rewrite rules, you need to flush the rewrite rules. Programmatically you would use <code>flush_rewrite_rules();</code> optionally for quick testing you could always just navigate to <code>Dashboard -&gt; Settings -&gt; Permalinks</code> since this automatically flushes the rewrite rules for you, simply just by visiting that admin page.</p>\n\n<p>Hope you (or someone) finds the information in my answer useful and relevant.</p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/243952", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62183/" ]
I found this code that works perfectly what I'm working on but needs a minor changes. What I need is to just display the sub categories of the parent. How do I alter the `get_categories()` to only get the specific categories I need? because doing this will display all available categories. ``` function ba_SearchFilter($query) { if (!$query->is_search) { return $query; } if (isset($_POST['cat'])){ $query->set('category__and', $_POST['cat']); } if (isset($_POST['tags'])){ $query->set('tag__and', $_POST['tags']); } return $query; } //hook filters to search add_filter('pre_get_posts','ba_SearchFilter'); function ba_search_with_filters(){ $out = '<form role="search" method="get" id="searchform" action="'. home_url( '/' ).'"> <div><label class="screen-reader-text" for="s">Search for:</label> <input type="text" value="" name="s" id="s" /><br />'; $categories= get_categories(); foreach ($categories as $category) { $option = ''; $option .= '<input type="checkbox" name="cat[]" id="cat[]" value="'.$category->term_id.'"> '; $option .= $category->cat_name .'<br />'; $out.= $option; } $tags= get_categories(); foreach ($tags as $tag) { $option = ''; $option .= '<input type="checkbox" name="tags[]" id="tags[]" value="'.$tag->term_id.'"> '; $option .= $tag->cat_name .'<br />'; $out.= $option; } $out .='<input type="submit" id="searchsubmit" value="Search" /> </div> </form>'; return $out; } add_shortcode('search_with_filter','ba_search_with_filters'); ```
**Asumption:** You use Apache as your web server. If you already know the page slugs and they won't change, just add them to your `.htaccess` file. It'll be much faster and less complicated. Paste the following `Redirect` lines at the top of your `.htaccess` file. ``` Redirect 301 /pagetitle/ /service/pagetitle/ Redirect 301 /pagetitle2/ /another-dir/pagetitle2/ # BEGIN WordPress <IfModule mod_rewrite.c> .... ```
243,959
<p>Here is my dropdown selection which is getting from database.</p> <pre><code> &lt;div class="col-sm-12"&gt; &lt;div class="form-group"&gt; &lt;div class="col-sm-12"&gt; &lt;label class="control-label col-sm-5"&gt;Project Choice &lt;span&gt;*&lt;/span&gt; &lt;/label&gt; &lt;div class="col-md-7"&gt; &lt;select class="form-control" id="category" name="project_choice" required&gt; &lt;?php $the_query = array( 'orderby' =&gt; 'name', 'order' =&gt; 'ASC', 'parent' =&gt; 0 ); $categories = get_categories($the_query); foreach ($categories as $category) { ?&gt; &lt;option value="&lt;?php echo $category-&gt;term_id; ?&gt;"&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>here is my result section which is associated with above category section.</p> <pre><code>&lt;div class="col-sm-12"&gt; &lt;div class="form-group"&gt; &lt;div class="col-sm-12"&gt; &lt;label class="control-label col-sm-5"&gt;Program &lt;span&gt;*&lt;/span&gt; &lt;/label&gt; &lt;div class="col-md-7" id="results"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here is my enqueue script for forntend user.</p> <pre><code>function my_enqueue() { wp_enqueue_script('ajax-script', get_template_directory_uri() . '/js/main.js', array('jquery'), '', true); wp_localize_script('ajax-script', 'main', array('ajax_url' =&gt; admin_url('admin-ajax.php'))); </code></pre> <p>}</p> <p>This is my main.js file script</p> <pre><code>$(document).ready(function () { $('#category').change(function () { $.ajax({ url: ajax_object.ajaxurl, type: 'POST', dataType: "html", data: { 'action': 'get_program_by_category', // this is name of your function that gets trigger 'datas': category // valuse you want to pass }, success: function (data) { debug(data); // result that return from function console.log(data); }, }); }); </code></pre> <p>});</p>
[ { "answer_id": 244228, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 2, "selected": false, "text": "<p><strong>Asumption:</strong> You use Apache as your web server.</p>\n\n<p>If you already know the page slugs and they won't change, just add them to your <code>.htaccess</code> file. It'll be much faster and less complicated. </p>\n\n<p>Paste the following <code>Redirect</code> lines at the top of your <code>.htaccess</code> file.</p>\n\n<pre><code>Redirect 301 /pagetitle/ /service/pagetitle/\nRedirect 301 /pagetitle2/ /another-dir/pagetitle2/\n\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\n....\n</code></pre>\n" }, { "answer_id": 244231, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 0, "selected": false, "text": "<p>Please have a look on the code below:</p>\n\n<pre><code>add_rewrite_rule( 'services/([^/]*)/?','index.php?post_type='.$post_type.'&name=$matches[1]','top');\n</code></pre>\n\n<p>For better understanding of rewrite API please check the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Rewrite\" rel=\"nofollow\">WP_REWRITE_API</a> and <a href=\"https://premium.wpmudev.org/blog/building-customized-urls-wordpress/?utm_expid=3606929-90.6a_uo883STWy99lnGf8x1g.0\" rel=\"nofollow\">Building Customized URLs in WordPress</a></p>\n\n<p>Waiting for your feedback!</p>\n\n<p>Hope it will work for you!</p>\n" }, { "answer_id": 244511, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>This approach might be a little more flexible.</p>\n\n<pre><code>$basePageRewrite-&gt;add_rule( 'service', 'page-title' );\n</code></pre>\n\n<p>At the end of the class definition you should be able to add a <code>base</code> and <code>page</code>. The URL rewrites will be constructed dynamically for the rules you add. If a <code>page</code> is called directly is will be redirected to the <code>$base/$pageTitle</code>.</p>\n\n<pre><code>&lt;?php\n\nif ( ! class_exists( 'BasePageRewrite' ) ):\n\n class BasePageRewrite {\n\n const ENDPOINT_QUERY_PARAM_REDIRECT = '____base_page_rewrite__redirect';\n\n private static $_hash_map = array ();\n\n /**\n * BasePageRewrite constructor.\n */\n public function __construct() {\n add_filter( 'query_vars', array ( $this, 'add_query_vars' ), 0 );\n add_action( 'parse_request', array ( $this, 'sniff_requests' ), 0 );\n add_action( 'init', array ( $this, 'add_endpoint' ), 0 );\n }\n\n /**\n * Add rewrite rules here.\n *\n * @param string $base Base of URL\n * @param string $page Slug of page\n */\n public function add_rule( $base, $page ) {\n if ( ! array_key_exists( $base, static::$_hash_map ) ) {\n static::$_hash_map[ $base ] = array ();\n }\n\n if ( ! array_key_exists( $page, static::$_hash_map[ $base ] ) ) {\n static::$_hash_map[ $base ][ $page ] = 'name';\n }\n }\n\n /**\n * Add our custom query arg to check in `parse_request`.\n *\n * @param $vars\n *\n * @return array\n */\n public function add_query_vars( $vars ) {\n $vars[] = static::ENDPOINT_QUERY_PARAM_REDIRECT;\n\n return $vars;\n }\n\n /**\n * Add rewrite rules.\n *\n * page --&gt; base/page\n *\n * base/page === page\n *\n * Note:\n *\n * `flush_rewrite_rules()` is only added for testing.\n */\n public function add_endpoint() {\n\n foreach ( static::$_hash_map as $base =&gt; $pages ) {\n\n foreach ( $pages as $pageName =&gt; $param ) {\n\n // page --&gt; service/page\n\n add_rewrite_rule( \"^$pageName/\", 'index.php?' . static::ENDPOINT_QUERY_PARAM_REDIRECT . \"=/$base/$pageName/\", 'top' );\n\n // service/page === page\n\n add_rewrite_rule( \"^$base/$pageName/\", \"index.php?$param=$pageName\", 'top' );\n }\n }\n\n //////////////////////////////////\n flush_rewrite_rules( true ); //// &lt;---------- REMOVE THIS WHEN DONE TESTING\n //////////////////////////////////\n }\n\n /**\n * Redirect regular page to base/page,\n *\n * @param $wp_query\n */\n public function sniff_requests( $wp_query ) {\n\n global $wp;\n\n if ( isset( $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM_REDIRECT ] ) ) {\n\n // page --&gt; service/page\n\n $redirect = $wp-&gt;query_vars[ static::ENDPOINT_QUERY_PARAM_REDIRECT ];\n $new_url = site_url( $redirect );\n wp_redirect( $new_url, 301 );\n die();\n }\n }\n }\n\n // Create the class\n $basePageRewrite = new BasePageRewrite();\n\n // Add individual rules\n $basePageRewrite-&gt;add_rule( 'service', 'page-title' );\n $basePageRewrite-&gt;add_rule( 'another-service', 'another-page-title' );\n\nendif; // BasePageRewrite\n</code></pre>\n" }, { "answer_id": 244945, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The other part that you need to do here, it is to change the permalink of the page with the <code>page_link</code> filter or <code>the_permalink</code> filter.</p>\n\n<p>here is a mirror question to your own - <a href=\"https://stackoverflow.com/questions/27432586/wordpress-page-link-filter\">https://stackoverflow.com/questions/27432586/wordpress-page-link-filter</a></p>\n\n<p>This will do the redirects because wordpress redirects to the canonical address when the url being accessed is different then the canonical one, and the canonical url for posts and pages is their permalink. As an added bonus you get everything else pointing to the right URL as well with no need of redirection at all.</p>\n" }, { "answer_id": 244958, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 0, "selected": false, "text": "<p>I know you specifically asked for rewrite rules, but what about redirection? You can achieve the same end result and same user experience. You can change the hierarchy of your pages if you want so that</p>\n\n<pre><code>sitename.com/service/pagetitle\n</code></pre>\n\n<p>is available and</p>\n\n<pre><code>sitename.com/pagetitle\n</code></pre>\n\n<p>is something that gets redirected to the first address.</p>\n\n<p>This skips your <code>.htaccess</code> altogether for simplicity. It looks like you actually want to learn how to do this as a rewrite rule, which is cool, but if you decide that it is being difficult and you just want a solution that works whether you learn this or not then there are a few different redirection plugins that can handle this for you. My personal favorite is titled \"Redirection\" and it can handle regex (with a little practice) and it also counts the number of times a redirect rule is used so that you can monitor if you even need to keep it in place.</p>\n\n<p>Lastly, I mentioned in the beginning that you can change your page hierarchy to reflect what you want your URLs to look like and you should probably do this either way if you haven't already. If not then you might find yourself with an infinite redirect situation. (which is also something to keep in mind if you go the redirect plugin route as well as I've seen this happen easily with users who have a lot of redirects and they make a new one that conflicts with one that already exists.)</p>\n\n<p><strong>TLDR</strong>: outside the box answer. there are one or more plugins that can achieve this function without actually doing a rewrite.</p>\n" }, { "answer_id": 244977, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 0, "selected": false, "text": "<p>I've encountered a very similar situation to what seems to be your expectations.</p>\n\n<p>We have a parent page \"Our Services\" (<code>domain.com/services/</code>) ...</p>\n\n<p>We also have several child pages representing each service provided under the parent page \"Our Services\". For example: \"Web Design\" (<code>domain.com/services/web-design/</code>)</p>\n\n<p>Now, we also have a \"Portfolio\". Instead of dedicating an entire top level section on the website for the portfolio, we decided that we wanted it underneath the main \"services\" section (<code>domain.com/services/</code>). </p>\n\n<p>So for example, the main section of our portfolio was to be located here: <code>domain.com/services/portfolio/</code></p>\n\n<p>The portfolio is it's own custom post type, containing individual portfolio items.</p>\n\n<p>So the URL to a specific portfolio item looked like this: <code>domain.com/services/portfolio/sample-portfolio-item/</code>.</p>\n\n<p>When you register your custom post type, there's a configurable parameter for <code>rewrite['slug']</code>. This is where you would specify <code>$args['rewrite']['slug'] = 'services/portfolio';</code></p>\n\n<p>Of course, anytime you make changes to URL rewrite rules, you need to flush the rewrite rules. Programmatically you would use <code>flush_rewrite_rules();</code> optionally for quick testing you could always just navigate to <code>Dashboard -&gt; Settings -&gt; Permalinks</code> since this automatically flushes the rewrite rules for you, simply just by visiting that admin page.</p>\n\n<p>Hope you (or someone) finds the information in my answer useful and relevant.</p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/243959", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96435/" ]
Here is my dropdown selection which is getting from database. ``` <div class="col-sm-12"> <div class="form-group"> <div class="col-sm-12"> <label class="control-label col-sm-5">Project Choice <span>*</span> </label> <div class="col-md-7"> <select class="form-control" id="category" name="project_choice" required> <?php $the_query = array( 'orderby' => 'name', 'order' => 'ASC', 'parent' => 0 ); $categories = get_categories($the_query); foreach ($categories as $category) { ?> <option value="<?php echo $category->term_id; ?>"><?php echo $category->name; ?></option> <?php } ?> </select> </div> </div> </div> </div> ``` here is my result section which is associated with above category section. ``` <div class="col-sm-12"> <div class="form-group"> <div class="col-sm-12"> <label class="control-label col-sm-5">Program <span>*</span> </label> <div class="col-md-7" id="results"> </div> </div> </div> </div> ``` Here is my enqueue script for forntend user. ``` function my_enqueue() { wp_enqueue_script('ajax-script', get_template_directory_uri() . '/js/main.js', array('jquery'), '', true); wp_localize_script('ajax-script', 'main', array('ajax_url' => admin_url('admin-ajax.php'))); ``` } This is my main.js file script ``` $(document).ready(function () { $('#category').change(function () { $.ajax({ url: ajax_object.ajaxurl, type: 'POST', dataType: "html", data: { 'action': 'get_program_by_category', // this is name of your function that gets trigger 'datas': category // valuse you want to pass }, success: function (data) { debug(data); // result that return from function console.log(data); }, }); }); ``` });
**Asumption:** You use Apache as your web server. If you already know the page slugs and they won't change, just add them to your `.htaccess` file. It'll be much faster and less complicated. Paste the following `Redirect` lines at the top of your `.htaccess` file. ``` Redirect 301 /pagetitle/ /service/pagetitle/ Redirect 301 /pagetitle2/ /another-dir/pagetitle2/ # BEGIN WordPress <IfModule mod_rewrite.c> .... ```
243,967
<p>I don't know coding. I was just trying to install a theme and this error keeps showing up on both the 'visit site' and the admin panel itself.</p> <blockquote> <p>Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in /home/designe6/public_html/wp-content/themes/qoon-child/functions.php on line 60</p> <p>Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in /home/designe6/public_html/wp-content/themes/qoon-creative-wordpress-portfolio-theme/functions.php on line 60</p> </blockquote> <p>And to show you what line 60 is in the child theme:</p> <pre><code>if ( $wpdb-&gt;get_var('SELECT count(*) FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = &quot;'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'&quot;') == '1' ) </code></pre> <p>And the line 60 for the main theme is:</p> <pre><code>if ( $wpdb-&gt;get_var('SELECT count(*) FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = &quot;'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'&quot;') == '1' ) </code></pre> <p>Please help I don't know how to fix. Can anybody volunteer to help me convert my php files to the most compatible mysqli or PDO?</p>
[ { "answer_id": 243968, "author": "Damithatt", "author_id": 105063, "author_profile": "https://wordpress.stackexchange.com/users/105063", "pm_score": -1, "selected": false, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/esc_sql/\" rel=\"nofollow\">esc_sql()</a> instead of mysql_escape_string.</p>\n\n<p>Update : </p>\n\n<pre><code>if ( $wpdb-&gt;get_var('SELECT count(*) FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = \"'.esc_sql( $_SERVER['REQUEST_URI'] ).'\"') == '1' )\n</code></pre>\n" }, { "answer_id": 244006, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\" rel=\"nofollow noreferrer\">mysql_real_escape_string()</a> extension was deprecated in PHP 5.5.0. So you can try below code:</p>\n\n<pre><code>if ( $wpdb-&gt;get_var( $wpdb-&gt;prepare( \"SELECT count(*) FROM {$wpdb-&gt;prefix}datalist WHERE `url` = %s\", $_SERVER['REQUEST_URI'] ) == '1' ) )\n</code></pre>\n\n<p>You can get more <a href=\"https://wordpress.stackexchange.com/questions/244077/replacing-mysql-real-escape-string-in-wordpress-theme/244097#244097\">here</a>.</p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/243967", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105664/" ]
I don't know coding. I was just trying to install a theme and this error keeps showing up on both the 'visit site' and the admin panel itself. > > Deprecated: mysql\_escape\_string(): This function is deprecated; use mysql\_real\_escape\_string() instead. in /home/designe6/public\_html/wp-content/themes/qoon-child/functions.php on line 60 > > > Deprecated: mysql\_escape\_string(): This function is deprecated; use mysql\_real\_escape\_string() instead. in /home/designe6/public\_html/wp-content/themes/qoon-creative-wordpress-portfolio-theme/functions.php on line 60 > > > And to show you what line 60 is in the child theme: ``` if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' ) ``` And the line 60 for the main theme is: ``` if ( $wpdb->get_var('SELECT count(*) FROM `' . $wpdb->prefix . 'datalist` WHERE `url` = "'.mysql_escape_string( $_SERVER['REQUEST_URI'] ).'"') == '1' ) ``` Please help I don't know how to fix. Can anybody volunteer to help me convert my php files to the most compatible mysqli or PDO?
[mysql\_real\_escape\_string()](http://php.net/manual/en/function.mysql-real-escape-string.php) extension was deprecated in PHP 5.5.0. So you can try below code: ``` if ( $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM {$wpdb->prefix}datalist WHERE `url` = %s", $_SERVER['REQUEST_URI'] ) == '1' ) ) ``` You can get more [here](https://wordpress.stackexchange.com/questions/244077/replacing-mysql-real-escape-string-in-wordpress-theme/244097#244097).
243,981
<p>Is it possible to edit roles in my blog in sharing section? I want contributor role WITH uploading capability. Goal is that people I invite to write my blog can add their own images, but no publishing rights. The administer will review it before publishing. </p>
[ { "answer_id": 243968, "author": "Damithatt", "author_id": 105063, "author_profile": "https://wordpress.stackexchange.com/users/105063", "pm_score": -1, "selected": false, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/esc_sql/\" rel=\"nofollow\">esc_sql()</a> instead of mysql_escape_string.</p>\n\n<p>Update : </p>\n\n<pre><code>if ( $wpdb-&gt;get_var('SELECT count(*) FROM `' . $wpdb-&gt;prefix . 'datalist` WHERE `url` = \"'.esc_sql( $_SERVER['REQUEST_URI'] ).'\"') == '1' )\n</code></pre>\n" }, { "answer_id": 244006, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\" rel=\"nofollow noreferrer\">mysql_real_escape_string()</a> extension was deprecated in PHP 5.5.0. So you can try below code:</p>\n\n<pre><code>if ( $wpdb-&gt;get_var( $wpdb-&gt;prepare( \"SELECT count(*) FROM {$wpdb-&gt;prefix}datalist WHERE `url` = %s\", $_SERVER['REQUEST_URI'] ) == '1' ) )\n</code></pre>\n\n<p>You can get more <a href=\"https://wordpress.stackexchange.com/questions/244077/replacing-mysql-real-escape-string-in-wordpress-theme/244097#244097\">here</a>.</p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/243981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105671/" ]
Is it possible to edit roles in my blog in sharing section? I want contributor role WITH uploading capability. Goal is that people I invite to write my blog can add their own images, but no publishing rights. The administer will review it before publishing.
[mysql\_real\_escape\_string()](http://php.net/manual/en/function.mysql-real-escape-string.php) extension was deprecated in PHP 5.5.0. So you can try below code: ``` if ( $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM {$wpdb->prefix}datalist WHERE `url` = %s", $_SERVER['REQUEST_URI'] ) == '1' ) ) ``` You can get more [here](https://wordpress.stackexchange.com/questions/244077/replacing-mysql-real-escape-string-in-wordpress-theme/244097#244097).
243,985
<p>is there any way to setup wordpress so that when I create a CPT and then have a menu item (preferably the archive page) that will automatically create a dropdown of all the actual posts and the links will be to the CPT single pages?</p> <p>so for instance if i had stores as my CPT the menu would look like this:</p> <p>Stores (to archive page)</p> <ul> <li><p>location 1(to location 1 single)</p></li> <li><p>location 2(to location 2 single)</p></li> <li><p>location 3(to location 3 single)</p></li> </ul> <p>and then if i add a new store location a new link would be created in this menu that would go to location 4(to location single)</p> <p>my custom post type is currently created by a custom plugin so i would be interested in adding the code to there if possible. I saw another question that said i may have to use wp_nav_menu but i'm not sure where to start with that.</p>
[ { "answer_id": 243988, "author": "Rasika Wadibhasme", "author_id": 89431, "author_profile": "https://wordpress.stackexchange.com/users/89431", "pm_score": 0, "selected": false, "text": "<p>Did you tried with \"<a href=\"https://i.stack.imgur.com/Y3ZDQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y3ZDQ.png\" alt=\"Automatically add new-top level pages to this menu option\"></a>\" at the bottom of the menu page. It add's any post or page automatically to menu even if it is custom. I just have no idea about adding it to submenu.</p>\n" }, { "answer_id": 247693, "author": "pressword", "author_id": 105668, "author_profile": "https://wordpress.stackexchange.com/users/105668", "pm_score": 3, "selected": true, "text": "<p>This should work:</p>\n\n<pre><code>add_filter( 'wp_get_nav_menu_items', 'cpt_locations_filter', 10, 3 );\n\nfunction cpt_locations_filter( $items, $menu, $args ) {\n $child_items = array(); \n $menu_order = count($items); \n $parent_item_id = 0;\n\n foreach ( $items as $item ) {\n if ( in_array('locations-menu', $item-&gt;classes) ){ //add this class to your menu item\n $parent_item_id = $item-&gt;ID;\n }\n }\n\n if($parent_item_id &gt; 0){\n\n foreach ( get_posts( 'post_type=cpt-post-type-here&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n }\n\n return array_merge( $items, $child_items );\n}\n</code></pre>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/243985", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
is there any way to setup wordpress so that when I create a CPT and then have a menu item (preferably the archive page) that will automatically create a dropdown of all the actual posts and the links will be to the CPT single pages? so for instance if i had stores as my CPT the menu would look like this: Stores (to archive page) * location 1(to location 1 single) * location 2(to location 2 single) * location 3(to location 3 single) and then if i add a new store location a new link would be created in this menu that would go to location 4(to location single) my custom post type is currently created by a custom plugin so i would be interested in adding the code to there if possible. I saw another question that said i may have to use wp\_nav\_menu but i'm not sure where to start with that.
This should work: ``` add_filter( 'wp_get_nav_menu_items', 'cpt_locations_filter', 10, 3 ); function cpt_locations_filter( $items, $menu, $args ) { $child_items = array(); $menu_order = count($items); $parent_item_id = 0; foreach ( $items as $item ) { if ( in_array('locations-menu', $item->classes) ){ //add this class to your menu item $parent_item_id = $item->ID; } } if($parent_item_id > 0){ foreach ( get_posts( 'post_type=cpt-post-type-here&numberposts=-1' ) as $post ) { $post->menu_item_parent = $parent_item_id; $post->post_type = 'nav_menu_item'; $post->object = 'custom'; $post->type = 'custom'; $post->menu_order = ++$menu_order; $post->title = $post->post_title; $post->url = get_permalink( $post->ID ); array_push($child_items, $post); } } return array_merge( $items, $child_items ); } ```
244,001
<p>I recently installed WP-CLI on windows with the instructions below. However when I type <code>wp shell</code> I get en error: The system cannot find the path specified.</p> <p>One solution on github says: </p> <p>Psysh is not bundled in wp-cli.phar, but you should be able to include it, like so:</p> <pre><code>wget psysh.org/psysh -O psysh.phar php wp-cli.phar --require=psysh.phar shell` </code></pre> <p>However, that also produces an error: <code>'wget' is not recognized as an internal or external command, operable program or batch file.</code></p> <p>Please help! I'm too far down the rabbit hole. I wanted to use WP CLI to make my life easier!</p> <p>Installation instructions followed (from <a href="http://wp-cli.org/docs/installing/" rel="nofollow">http://wp-cli.org/docs/installing/</a>):</p> <blockquote> <p>Installing on Windows# Install via composer as described above or use the following method.</p> <p>Make sure you have php installed and in your path so you can execute it globally.</p> <p>Download wp-cli.phar manually and save it to a folder, for example c:\wp-cli</p> <p>Create a file named wp.bat in c:\wp-cli with the following contents:</p> <p>@ECHO OFF php "c:/wp-cli/wp-cli.phar" %* Add c:\wp-cli to your path:</p> <p>setx path "%path%;c:\wp-cli" You can now use WP-CLI from anywhere in Windows command line.</p> </blockquote>
[ { "answer_id": 244587, "author": "Robin Andrews", "author_id": 98276, "author_profile": "https://wordpress.stackexchange.com/users/98276", "pm_score": 2, "selected": false, "text": "<p>OK, I've now solved this.</p>\n\n<p>Here's what I did.</p>\n\n<p>When I tried to use Composer to install psy/psysh using composer, there was a clash of versions of symphony due to some work I'd done with Laravel. I decided to completely re-install Composer using the Windows installer, since I didn't really understand what was going on. (First I had to delete it - instructions here: <a href=\"https://stackoverflow.com/questions/30396451/remove-composer\">https://stackoverflow.com/questions/30396451/remove-composer</a>).</p>\n\n<p>Once composer was installed, I used just two commands to make everything work perfectly:</p>\n\n<p><code>composer global require wp-cli/wp-cli</code></p>\n\n<p><code>composer global require psy/psysh</code></p>\n\n<p>Now, when I type <code>wp shell</code> in the command line, it's good to go. Yay!</p>\n" }, { "answer_id": 283445, "author": "Mat Lipe", "author_id": 129914, "author_profile": "https://wordpress.stackexchange.com/users/129914", "pm_score": 0, "selected": false, "text": "<p>I didn't like the idea of having to install a global dependency to composer for just one library. While this worked fine, it felt a little too much like an anti-pattern to me. </p>\n\n<p>Instead I <a href=\"https://github.com/lipemat/wp-cli\" rel=\"nofollow noreferrer\">forked wp-cli</a> to create a version that has the requirement built in so it will work on Windows using a standard wp-cli.phar </p>\n\n<p><a href=\"http://matlipe.com/content/uploads/wp-cli.zip\" rel=\"nofollow noreferrer\">Download the latest -windows version here</a></p>\n\n<p>At the time of writing, the forked version is 1.4.0. </p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/244001", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98276/" ]
I recently installed WP-CLI on windows with the instructions below. However when I type `wp shell` I get en error: The system cannot find the path specified. One solution on github says: Psysh is not bundled in wp-cli.phar, but you should be able to include it, like so: ``` wget psysh.org/psysh -O psysh.phar php wp-cli.phar --require=psysh.phar shell` ``` However, that also produces an error: `'wget' is not recognized as an internal or external command, operable program or batch file.` Please help! I'm too far down the rabbit hole. I wanted to use WP CLI to make my life easier! Installation instructions followed (from <http://wp-cli.org/docs/installing/>): > > Installing on Windows# Install via composer as described above or use > the following method. > > > Make sure you have php installed and in your path so you can execute > it globally. > > > Download wp-cli.phar manually and save it to a folder, for example > c:\wp-cli > > > Create a file named wp.bat in c:\wp-cli with the following contents: > > > @ECHO OFF php "c:/wp-cli/wp-cli.phar" %\* Add c:\wp-cli to your path: > > > setx path "%path%;c:\wp-cli" You can now use WP-CLI from anywhere in > Windows command line. > > >
OK, I've now solved this. Here's what I did. When I tried to use Composer to install psy/psysh using composer, there was a clash of versions of symphony due to some work I'd done with Laravel. I decided to completely re-install Composer using the Windows installer, since I didn't really understand what was going on. (First I had to delete it - instructions here: <https://stackoverflow.com/questions/30396451/remove-composer>). Once composer was installed, I used just two commands to make everything work perfectly: `composer global require wp-cli/wp-cli` `composer global require psy/psysh` Now, when I type `wp shell` in the command line, it's good to go. Yay!
244,013
<p>Hi I have disabled all my plugins to try and determine a plugin conflit and ended up breaking my site with one click!</p> <p>I have searched arrond to find people saying that you can turn them om via FTP.</p> <p>I think I have found my "<code>active plugins</code>" tasble in phpmyadmin and it reads as follows </p> <pre><code>a:1:{i:4;s:27:"cornerstone/cornerstone.php";} </code></pre> <p>But I have all these in my plugins folder and they were all active before.</p> <p><strong>File path:</strong><br> /public_html/wp-content/plugins/all-in-one-wp-security-and-firewall<br> /public_html/wp-content/plugins/business-worldpay-gateway-for-woocommerce<br> /public_html/wp-content/plugins/contact-form-7<br> /public_html/wp-content/plugins/contact-form-7-to-database-extension<br> /public_html/wp-content/plugins/cornerstone<br> /public_html/wp-content/plugins/really-simple-captcha<br> /public_html/wp-content/plugins/remove-query-strings-from-static-resources<br> /public_html/wp-content/plugins/revision-control<br> /public_html/wp-content/plugins/simple-301-redirects<br> /public_html/wp-content/plugins/simple-custom-css<br> /public_html/wp-content/plugins/updraftplus<br> /public_html/wp-content/plugins/woocommerce<br> /public_html/wp-content/plugins/woocommerce-order-delivery<br> /public_html/wp-content/plugins/woocommerce-products-filter<br> /public_html/wp-content/plugins/woothemes-updater<br> /public_html/wp-content/plugins/wordpress-seo-premium<br> /public_html/wp-content/plugins/wp-optimize<br> /public_html/wp-content/plugins/wp-smushit<br> /public_html/wp-content/plugins/x-content-dock<br> /public_html/wp-content/plugins/x-custom-404<br> /public_html/wp-content/plugins/x-facebook-comments<br> /public_html/wp-content/plugins/x-google-analytics<br> /public_html/wp-content/plugins/x-smooth-scroll<br> /public_html/wp-content/plugins/advanced-cache.php<br> /public_html/wp-content/plugins/index.php<br></p> <p>How do I turn all those on? Sorry I know it is a big ask! Could anyone tell me if I can activate my plugings again from here please?</p> <p>Thanks</p> <p>Ben</p>
[ { "answer_id": 244014, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 3, "selected": true, "text": "<p>Try the below mysql query to activate your plugin:</p>\n\n<pre><code>UPDATE wp_options SET option_value = 'a:22:{i:0;s:19:\"akismet/akismet.php\";i:1;s:58:\"contact-form-7-to-database-extension/contact-form-7-db.php\";i:2;s:36:\"contact-form-7/wp-contact-form-7.php\";i:3;s:27:\"js_composer/js_composer.php\";i:4;s:23:\"revslider/revslider.php\";i:5;s:23:\"soliloquy/soliloquy.php\";i:6;s:27:\"updraftplus/updraftplus.php\";i:7;s:41:\"wordpress-importer/wordpress-importer.php\";i:8;s:24:\"wordpress-seo/wp-seo.php\";i:9;s:25:\"wp-smushit/wp-smushit.php\";i:10;s:33:\"x-content-dock/x-content-dock.php\";i:11;s:29:\"x-custom-404/x-custom-404.php\";i:12;s:39:\"x-disqus-comments/x-disqus-comments.php\";i:13;s:39:\"x-email-mailchimp/x-email-mailchimp.php\";i:14;s:43:\"x-facebook-comments/x-facebook-comments.php\";i:15;s:41:\"x-google-analytics/x-google-analytics.php\";i:16;s:43:\"x-olark-integration/x-olark-integration.php\";i:17;s:29:\"x-shortcodes/x-shortcodes.php\";i:18;s:35:\"x-smooth-scroll/x-smooth-scroll.php\";i:19;s:45:\"x-under-construction/x-under-construction.php\";i:20;s:29:\"x-video-lock/x-video-lock.php\";i:21;s:31:\"x-white-label/x-white-label.php\";}' WHERE option_name = 'active_plugins';\n</code></pre>\n\n<p>But as you say 'determine a plugin conflit and ended up breaking my site' I suggest you to follow below steps:</p>\n\n<p><strong>1 De-activate All Plugins via phpmyadmin</strong>\nIn the options table, find the <code>option_name</code> column and find find the line named <code>active_plugins</code>. On the <code>active_plugins</code> line, click edit. You will see something similar to this:</p>\n\n<pre><code>a:22:{i:0;s:19:\"akismet/akismet.php\";i:1;s:58:\"contact-form-7-to-database-extension/contact-form-7-db.php\";i:2;s:36:\"contact-form-7/wp-contact-form-7.php\";i:3;s:27:\"js_composer/js_composer.php\";i:4;s:23:\"revslider/revslider.php\";i:5;s:23:\"soliloquy/soliloquy.php\";i:6;s:27:\"updraftplus/updraftplus.php\";i:7;s:41:\"wordpress-importer/wordpress-importer.php\";i:8;s:24:\"wordpress-seo/wp-seo.php\";i:9;s:25:\"wp-smushit/wp-smushit.php\";i:10;s:33:\"x-content-dock/x-content-dock.php\";i:11;s:29:\"x-custom-404/x-custom-404.php\";i:12;s:39:\"x-disqus-comments/x-disqus-comments.php\";i:13;s:39:\"x-email-mailchimp/x-email-mailchimp.php\";i:14;s:43:\"x-facebook-comments/x-facebook-comments.php\";i:15;s:41:\"x-google-analytics/x-google-analytics.php\";i:16;s:43:\"x-olark-integration/x-olark-integration.php\";i:17;s:29:\"x-shortcodes/x-shortcodes.php\";i:18;s:35:\"x-smooth-scroll/x-smooth-scroll.php\";i:19;s:45:\"x-under-construction/x-under-construction.php\";i:20;s:29:\"x-video-lock/x-video-lock.php\";i:21;s:31:\"x-white-label/x-white-label.php\";}\n</code></pre>\n\n<p>Cut that code and click Go. Now all the plugins are successfully Inactivated.</p>\n\n<p><strong>2 Determine the cause plugin</strong>\nNow the best way to determine which plugin is causing the issue is to enable each plugin one by one via your <em>WordPress admin login page > Go to Plugins > Installed Plugins > Enable a plugin</em> one by and check you website front every time.</p>\n\n<p>Hope this work for you</p>\n" }, { "answer_id": 244018, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<p>In FTP, rename:</p>\n\n<ol>\n<li><code>wp-content/themes</code> to <code>wp-content/themes-tmp</code></li>\n<li><code>wp-content/plugins</code> to <code>wp-content/plugins-tmp</code></li>\n</ol>\n\n<p>...at this point, you should be able to log back in/get at your dashboard (the front end of your site will be completely dead at this point, that's ok).</p>\n\n<p>So now you're in, go to \"Plugins\" - this will ensure that WP permanently deactivates all plugins, now that they are technically no longer installed (from having renamed the directory). </p>\n\n<p>Back in FTP, restore the <code>plugins</code> directory, leave <code>themes-tmp</code> alone. Then back again to WordPress, and reactivate all your required plugins.</p>\n\n<p>Now finally back to FTP to restore <code>themes</code>.</p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/244013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105684/" ]
Hi I have disabled all my plugins to try and determine a plugin conflit and ended up breaking my site with one click! I have searched arrond to find people saying that you can turn them om via FTP. I think I have found my "`active plugins`" tasble in phpmyadmin and it reads as follows ``` a:1:{i:4;s:27:"cornerstone/cornerstone.php";} ``` But I have all these in my plugins folder and they were all active before. **File path:** /public\_html/wp-content/plugins/all-in-one-wp-security-and-firewall /public\_html/wp-content/plugins/business-worldpay-gateway-for-woocommerce /public\_html/wp-content/plugins/contact-form-7 /public\_html/wp-content/plugins/contact-form-7-to-database-extension /public\_html/wp-content/plugins/cornerstone /public\_html/wp-content/plugins/really-simple-captcha /public\_html/wp-content/plugins/remove-query-strings-from-static-resources /public\_html/wp-content/plugins/revision-control /public\_html/wp-content/plugins/simple-301-redirects /public\_html/wp-content/plugins/simple-custom-css /public\_html/wp-content/plugins/updraftplus /public\_html/wp-content/plugins/woocommerce /public\_html/wp-content/plugins/woocommerce-order-delivery /public\_html/wp-content/plugins/woocommerce-products-filter /public\_html/wp-content/plugins/woothemes-updater /public\_html/wp-content/plugins/wordpress-seo-premium /public\_html/wp-content/plugins/wp-optimize /public\_html/wp-content/plugins/wp-smushit /public\_html/wp-content/plugins/x-content-dock /public\_html/wp-content/plugins/x-custom-404 /public\_html/wp-content/plugins/x-facebook-comments /public\_html/wp-content/plugins/x-google-analytics /public\_html/wp-content/plugins/x-smooth-scroll /public\_html/wp-content/plugins/advanced-cache.php /public\_html/wp-content/plugins/index.php How do I turn all those on? Sorry I know it is a big ask! Could anyone tell me if I can activate my plugings again from here please? Thanks Ben
Try the below mysql query to activate your plugin: ``` UPDATE wp_options SET option_value = 'a:22:{i:0;s:19:"akismet/akismet.php";i:1;s:58:"contact-form-7-to-database-extension/contact-form-7-db.php";i:2;s:36:"contact-form-7/wp-contact-form-7.php";i:3;s:27:"js_composer/js_composer.php";i:4;s:23:"revslider/revslider.php";i:5;s:23:"soliloquy/soliloquy.php";i:6;s:27:"updraftplus/updraftplus.php";i:7;s:41:"wordpress-importer/wordpress-importer.php";i:8;s:24:"wordpress-seo/wp-seo.php";i:9;s:25:"wp-smushit/wp-smushit.php";i:10;s:33:"x-content-dock/x-content-dock.php";i:11;s:29:"x-custom-404/x-custom-404.php";i:12;s:39:"x-disqus-comments/x-disqus-comments.php";i:13;s:39:"x-email-mailchimp/x-email-mailchimp.php";i:14;s:43:"x-facebook-comments/x-facebook-comments.php";i:15;s:41:"x-google-analytics/x-google-analytics.php";i:16;s:43:"x-olark-integration/x-olark-integration.php";i:17;s:29:"x-shortcodes/x-shortcodes.php";i:18;s:35:"x-smooth-scroll/x-smooth-scroll.php";i:19;s:45:"x-under-construction/x-under-construction.php";i:20;s:29:"x-video-lock/x-video-lock.php";i:21;s:31:"x-white-label/x-white-label.php";}' WHERE option_name = 'active_plugins'; ``` But as you say 'determine a plugin conflit and ended up breaking my site' I suggest you to follow below steps: **1 De-activate All Plugins via phpmyadmin** In the options table, find the `option_name` column and find find the line named `active_plugins`. On the `active_plugins` line, click edit. You will see something similar to this: ``` a:22:{i:0;s:19:"akismet/akismet.php";i:1;s:58:"contact-form-7-to-database-extension/contact-form-7-db.php";i:2;s:36:"contact-form-7/wp-contact-form-7.php";i:3;s:27:"js_composer/js_composer.php";i:4;s:23:"revslider/revslider.php";i:5;s:23:"soliloquy/soliloquy.php";i:6;s:27:"updraftplus/updraftplus.php";i:7;s:41:"wordpress-importer/wordpress-importer.php";i:8;s:24:"wordpress-seo/wp-seo.php";i:9;s:25:"wp-smushit/wp-smushit.php";i:10;s:33:"x-content-dock/x-content-dock.php";i:11;s:29:"x-custom-404/x-custom-404.php";i:12;s:39:"x-disqus-comments/x-disqus-comments.php";i:13;s:39:"x-email-mailchimp/x-email-mailchimp.php";i:14;s:43:"x-facebook-comments/x-facebook-comments.php";i:15;s:41:"x-google-analytics/x-google-analytics.php";i:16;s:43:"x-olark-integration/x-olark-integration.php";i:17;s:29:"x-shortcodes/x-shortcodes.php";i:18;s:35:"x-smooth-scroll/x-smooth-scroll.php";i:19;s:45:"x-under-construction/x-under-construction.php";i:20;s:29:"x-video-lock/x-video-lock.php";i:21;s:31:"x-white-label/x-white-label.php";} ``` Cut that code and click Go. Now all the plugins are successfully Inactivated. **2 Determine the cause plugin** Now the best way to determine which plugin is causing the issue is to enable each plugin one by one via your *WordPress admin login page > Go to Plugins > Installed Plugins > Enable a plugin* one by and check you website front every time. Hope this work for you
244,049
<p>This is my code, but I only want echo the code if the current category has children. </p> <pre><code>&lt;?php $terms = get_terms([ 'taxonomy' =&gt; get_queried_object()-&gt;taxonomy, 'parent' =&gt; get_queried_object_id(), ]); echo '&lt;div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;"&gt; &lt;div class="breaker-small"&gt;Refine Search&lt;/div&gt;'; foreach ($terms as $term) { echo '&lt;p class="filters"&gt;&lt;a href="' . get_term_link($term) . '"&gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/p&gt;'; } echo '&lt;/div&gt; &lt;br /&gt;'; ?&gt; </code></pre> <p>So, if </p> <pre><code>$terms = get_terms([ 'taxonomy' =&gt; get_queried_object()-&gt;taxonomy, 'parent' =&gt; get_queried_object_id(), ])); </code></pre> <p>True - then run the echo.</p>
[ { "answer_id": 244014, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 3, "selected": true, "text": "<p>Try the below mysql query to activate your plugin:</p>\n\n<pre><code>UPDATE wp_options SET option_value = 'a:22:{i:0;s:19:\"akismet/akismet.php\";i:1;s:58:\"contact-form-7-to-database-extension/contact-form-7-db.php\";i:2;s:36:\"contact-form-7/wp-contact-form-7.php\";i:3;s:27:\"js_composer/js_composer.php\";i:4;s:23:\"revslider/revslider.php\";i:5;s:23:\"soliloquy/soliloquy.php\";i:6;s:27:\"updraftplus/updraftplus.php\";i:7;s:41:\"wordpress-importer/wordpress-importer.php\";i:8;s:24:\"wordpress-seo/wp-seo.php\";i:9;s:25:\"wp-smushit/wp-smushit.php\";i:10;s:33:\"x-content-dock/x-content-dock.php\";i:11;s:29:\"x-custom-404/x-custom-404.php\";i:12;s:39:\"x-disqus-comments/x-disqus-comments.php\";i:13;s:39:\"x-email-mailchimp/x-email-mailchimp.php\";i:14;s:43:\"x-facebook-comments/x-facebook-comments.php\";i:15;s:41:\"x-google-analytics/x-google-analytics.php\";i:16;s:43:\"x-olark-integration/x-olark-integration.php\";i:17;s:29:\"x-shortcodes/x-shortcodes.php\";i:18;s:35:\"x-smooth-scroll/x-smooth-scroll.php\";i:19;s:45:\"x-under-construction/x-under-construction.php\";i:20;s:29:\"x-video-lock/x-video-lock.php\";i:21;s:31:\"x-white-label/x-white-label.php\";}' WHERE option_name = 'active_plugins';\n</code></pre>\n\n<p>But as you say 'determine a plugin conflit and ended up breaking my site' I suggest you to follow below steps:</p>\n\n<p><strong>1 De-activate All Plugins via phpmyadmin</strong>\nIn the options table, find the <code>option_name</code> column and find find the line named <code>active_plugins</code>. On the <code>active_plugins</code> line, click edit. You will see something similar to this:</p>\n\n<pre><code>a:22:{i:0;s:19:\"akismet/akismet.php\";i:1;s:58:\"contact-form-7-to-database-extension/contact-form-7-db.php\";i:2;s:36:\"contact-form-7/wp-contact-form-7.php\";i:3;s:27:\"js_composer/js_composer.php\";i:4;s:23:\"revslider/revslider.php\";i:5;s:23:\"soliloquy/soliloquy.php\";i:6;s:27:\"updraftplus/updraftplus.php\";i:7;s:41:\"wordpress-importer/wordpress-importer.php\";i:8;s:24:\"wordpress-seo/wp-seo.php\";i:9;s:25:\"wp-smushit/wp-smushit.php\";i:10;s:33:\"x-content-dock/x-content-dock.php\";i:11;s:29:\"x-custom-404/x-custom-404.php\";i:12;s:39:\"x-disqus-comments/x-disqus-comments.php\";i:13;s:39:\"x-email-mailchimp/x-email-mailchimp.php\";i:14;s:43:\"x-facebook-comments/x-facebook-comments.php\";i:15;s:41:\"x-google-analytics/x-google-analytics.php\";i:16;s:43:\"x-olark-integration/x-olark-integration.php\";i:17;s:29:\"x-shortcodes/x-shortcodes.php\";i:18;s:35:\"x-smooth-scroll/x-smooth-scroll.php\";i:19;s:45:\"x-under-construction/x-under-construction.php\";i:20;s:29:\"x-video-lock/x-video-lock.php\";i:21;s:31:\"x-white-label/x-white-label.php\";}\n</code></pre>\n\n<p>Cut that code and click Go. Now all the plugins are successfully Inactivated.</p>\n\n<p><strong>2 Determine the cause plugin</strong>\nNow the best way to determine which plugin is causing the issue is to enable each plugin one by one via your <em>WordPress admin login page > Go to Plugins > Installed Plugins > Enable a plugin</em> one by and check you website front every time.</p>\n\n<p>Hope this work for you</p>\n" }, { "answer_id": 244018, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<p>In FTP, rename:</p>\n\n<ol>\n<li><code>wp-content/themes</code> to <code>wp-content/themes-tmp</code></li>\n<li><code>wp-content/plugins</code> to <code>wp-content/plugins-tmp</code></li>\n</ol>\n\n<p>...at this point, you should be able to log back in/get at your dashboard (the front end of your site will be completely dead at this point, that's ok).</p>\n\n<p>So now you're in, go to \"Plugins\" - this will ensure that WP permanently deactivates all plugins, now that they are technically no longer installed (from having renamed the directory). </p>\n\n<p>Back in FTP, restore the <code>plugins</code> directory, leave <code>themes-tmp</code> alone. Then back again to WordPress, and reactivate all your required plugins.</p>\n\n<p>Now finally back to FTP to restore <code>themes</code>.</p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/244049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105566/" ]
This is my code, but I only want echo the code if the current category has children. ``` <?php $terms = get_terms([ 'taxonomy' => get_queried_object()->taxonomy, 'parent' => get_queried_object_id(), ]); echo '<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;"> <div class="breaker-small">Refine Search</div>'; foreach ($terms as $term) { echo '<p class="filters"><a href="' . get_term_link($term) . '">' . $term->name . '</a></p>'; } echo '</div> <br />'; ?> ``` So, if ``` $terms = get_terms([ 'taxonomy' => get_queried_object()->taxonomy, 'parent' => get_queried_object_id(), ])); ``` True - then run the echo.
Try the below mysql query to activate your plugin: ``` UPDATE wp_options SET option_value = 'a:22:{i:0;s:19:"akismet/akismet.php";i:1;s:58:"contact-form-7-to-database-extension/contact-form-7-db.php";i:2;s:36:"contact-form-7/wp-contact-form-7.php";i:3;s:27:"js_composer/js_composer.php";i:4;s:23:"revslider/revslider.php";i:5;s:23:"soliloquy/soliloquy.php";i:6;s:27:"updraftplus/updraftplus.php";i:7;s:41:"wordpress-importer/wordpress-importer.php";i:8;s:24:"wordpress-seo/wp-seo.php";i:9;s:25:"wp-smushit/wp-smushit.php";i:10;s:33:"x-content-dock/x-content-dock.php";i:11;s:29:"x-custom-404/x-custom-404.php";i:12;s:39:"x-disqus-comments/x-disqus-comments.php";i:13;s:39:"x-email-mailchimp/x-email-mailchimp.php";i:14;s:43:"x-facebook-comments/x-facebook-comments.php";i:15;s:41:"x-google-analytics/x-google-analytics.php";i:16;s:43:"x-olark-integration/x-olark-integration.php";i:17;s:29:"x-shortcodes/x-shortcodes.php";i:18;s:35:"x-smooth-scroll/x-smooth-scroll.php";i:19;s:45:"x-under-construction/x-under-construction.php";i:20;s:29:"x-video-lock/x-video-lock.php";i:21;s:31:"x-white-label/x-white-label.php";}' WHERE option_name = 'active_plugins'; ``` But as you say 'determine a plugin conflit and ended up breaking my site' I suggest you to follow below steps: **1 De-activate All Plugins via phpmyadmin** In the options table, find the `option_name` column and find find the line named `active_plugins`. On the `active_plugins` line, click edit. You will see something similar to this: ``` a:22:{i:0;s:19:"akismet/akismet.php";i:1;s:58:"contact-form-7-to-database-extension/contact-form-7-db.php";i:2;s:36:"contact-form-7/wp-contact-form-7.php";i:3;s:27:"js_composer/js_composer.php";i:4;s:23:"revslider/revslider.php";i:5;s:23:"soliloquy/soliloquy.php";i:6;s:27:"updraftplus/updraftplus.php";i:7;s:41:"wordpress-importer/wordpress-importer.php";i:8;s:24:"wordpress-seo/wp-seo.php";i:9;s:25:"wp-smushit/wp-smushit.php";i:10;s:33:"x-content-dock/x-content-dock.php";i:11;s:29:"x-custom-404/x-custom-404.php";i:12;s:39:"x-disqus-comments/x-disqus-comments.php";i:13;s:39:"x-email-mailchimp/x-email-mailchimp.php";i:14;s:43:"x-facebook-comments/x-facebook-comments.php";i:15;s:41:"x-google-analytics/x-google-analytics.php";i:16;s:43:"x-olark-integration/x-olark-integration.php";i:17;s:29:"x-shortcodes/x-shortcodes.php";i:18;s:35:"x-smooth-scroll/x-smooth-scroll.php";i:19;s:45:"x-under-construction/x-under-construction.php";i:20;s:29:"x-video-lock/x-video-lock.php";i:21;s:31:"x-white-label/x-white-label.php";} ``` Cut that code and click Go. Now all the plugins are successfully Inactivated. **2 Determine the cause plugin** Now the best way to determine which plugin is causing the issue is to enable each plugin one by one via your *WordPress admin login page > Go to Plugins > Installed Plugins > Enable a plugin* one by and check you website front every time. Hope this work for you
244,062
<p>i currently have the following:</p> <pre><code>&lt;?php $field_name = "text_field"; $field = get_field_object($field_name); &lt;table&gt; &lt;tbody&gt; if( isset($field['value'] ): ?&gt; &lt;tr&gt; &lt;th&gt;&lt;?php echo $field['label']; ?&gt;&lt;/th&gt; &lt;td&gt;&lt;?php echo $field['value']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endif; ?&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>my goal is to make the entire table row collapse and not display if there is no value entered.</p> <p>clearly a novice. thanks for taking a look.</p>
[ { "answer_id": 244069, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>You have a mismatch in your PHP tags. Use this: </p>\n\n<pre><code>&lt;?php\n$field_name = \"text_field\";\n$field = get_field_object($field_name); \n?&gt;\n\n&lt;table&gt;\n &lt;tbody&gt;\n &lt;?php\n if( isset($field['value'] ): ?&gt; \n &lt;tr&gt;\n &lt;th&gt;&lt;?php echo $field['label']; ?&gt;&lt;/th&gt;\n &lt;td&gt;&lt;?php echo $field['value']; ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endif; ?&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 244096, "author": "vulgarbulgar", "author_id": 4822, "author_profile": "https://wordpress.stackexchange.com/users/4822", "pm_score": 1, "selected": false, "text": "<p>As per ACF documentation, field[‘value’] will always be set.</p>\n\n<p>Instead do if (!empty($field['value']) or just if ($field['value']).</p>\n\n<p>Thus it should look like this:</p>\n\n<pre><code>&lt;?php\n$field_name = \"text_field\";\n$field = get_field_object($field_name); \n?&gt;\n\n&lt;table&gt;\n &lt;tbody&gt;\n &lt;?php\n if ($field['value']): ?&gt; \n &lt;tr&gt;\n &lt;th&gt;&lt;?php echo $field['label']; ?&gt;&lt;/th&gt;\n &lt;td&gt;&lt;?php echo $field['value']; ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endif; ?&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/244062", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4822/" ]
i currently have the following: ``` <?php $field_name = "text_field"; $field = get_field_object($field_name); <table> <tbody> if( isset($field['value'] ): ?> <tr> <th><?php echo $field['label']; ?></th> <td><?php echo $field['value']; ?></td> </tr> <?php endif; ?> </tbody> </table> ``` my goal is to make the entire table row collapse and not display if there is no value entered. clearly a novice. thanks for taking a look.
You have a mismatch in your PHP tags. Use this: ``` <?php $field_name = "text_field"; $field = get_field_object($field_name); ?> <table> <tbody> <?php if( isset($field['value'] ): ?> <tr> <th><?php echo $field['label']; ?></th> <td><?php echo $field['value']; ?></td> </tr> <?php endif; ?> </tbody> </table> ```
244,077
<p>I'm having an issue with <strong>mysql_real_escape_string</strong>. This is used to display a custom post type (food menu items) for the WooThemes Diner theme. Food menu items no longer display on the Diner menu page because they are being called with <strong>mysql_real_escape_string</strong>.</p> <p>What is the proper way to call these items?</p> <p>Theme: <a href="https://docs.woocommerce.com/document/diner/" rel="nofollow">Diner by WooThemes</a> version 1.9.8 (now retired from active support)</p> <p>Affected file: admin-interface.php</p> <p>Lines: 111 &amp; 118</p> <pre><code>/*-----------------------------------------------------------------------------------*/ /* WooThemes Admin Interface - woothemes_add_admin */ /*-----------------------------------------------------------------------------------*/ if ( ! function_exists( 'woothemes_add_admin' ) ) { function woothemes_add_admin() { global $query_string; global $current_user; $current_user_id = $current_user-&gt;user_login; $super_user = get_option( 'framework_woo_super_user' ); $themename = get_option( 'woo_themename' ); $shortname = get_option( 'woo_shortname' ); // Reset the settings, sanitizing the various requests made. // Use a SWITCH to determine which settings to update. /* Make sure we're making a request. ------------------------------------------------------------*/ if ( isset( $_REQUEST['page'] ) ) { // Sanitize page being requested. $_page = ''; $_page = mysql_real_escape_string( strtolower( trim( strip_tags( $_REQUEST['page'] ) ) ) ); // Sanitize action being requested. $_action = ''; if ( isset( $_REQUEST['woo_save'] ) ) { $_action = mysql_real_escape_string( strtolower( trim( strip_tags( $_REQUEST['woo_save'] ) ) ) ); } // End IF Statement // If the action is "reset", run the SWITCH. /* Perform settings reset. ------------------------------------------------------------*/ </code></pre>
[ { "answer_id": 244097, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 3, "selected": false, "text": "<p>As <a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\" rel=\"nofollow noreferrer\">mysql_real_escape_string()</a> was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0, you can try <a href=\"https://codex.wordpress.org/Function_Reference/esc_sql\" rel=\"nofollow noreferrer\">esc_sql()</a> to work for later WP/PHP versions.</p>\n<p>Replace <code>mysql_real_escape_string()</code> with <code>esc_sql()</code> at line 111 &amp; 118 in your <code>admin-interface.php</code> file.</p>\n<p>Hope this should work well for you!</p>\n" }, { "answer_id": 270779, "author": "Damith Ruwan", "author_id": 120331, "author_profile": "https://wordpress.stackexchange.com/users/120331", "pm_score": 1, "selected": false, "text": "<p><code>mysql_real_escape_string</code> was deprecated previously and removed in PHP7. You have to use <code>mysqli_real_escape_string</code>. But I don't think it is possible with WordPress because you have pass the connection string also.</p>\n\n<p>So alternately you can use <a href=\"https://codex.wordpress.org/Function_Reference/esc_sql\" rel=\"nofollow noreferrer\">esc_sql()</a> instead of <code>mysql_real_escape_string</code>.</p>\n" }, { "answer_id": 395703, "author": "user12143633", "author_id": 189491, "author_profile": "https://wordpress.stackexchange.com/users/189491", "pm_score": 0, "selected": false, "text": "<p>use this</p>\n<pre><code>global $wpdb;\n$string = &quot;&lt;h1&gt;Hello world&lt;/h1&gt;&quot;;\n$string = $wpdb-&gt;_real_escape($string);\n</code></pre>\n<p>link here : <a href=\"https://developer.wordpress.org/reference/classes/wpdb/_real_escape/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wpdb/_real_escape/</a></p>\n" } ]
2016/10/26
[ "https://wordpress.stackexchange.com/questions/244077", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12243/" ]
I'm having an issue with **mysql\_real\_escape\_string**. This is used to display a custom post type (food menu items) for the WooThemes Diner theme. Food menu items no longer display on the Diner menu page because they are being called with **mysql\_real\_escape\_string**. What is the proper way to call these items? Theme: [Diner by WooThemes](https://docs.woocommerce.com/document/diner/) version 1.9.8 (now retired from active support) Affected file: admin-interface.php Lines: 111 & 118 ``` /*-----------------------------------------------------------------------------------*/ /* WooThemes Admin Interface - woothemes_add_admin */ /*-----------------------------------------------------------------------------------*/ if ( ! function_exists( 'woothemes_add_admin' ) ) { function woothemes_add_admin() { global $query_string; global $current_user; $current_user_id = $current_user->user_login; $super_user = get_option( 'framework_woo_super_user' ); $themename = get_option( 'woo_themename' ); $shortname = get_option( 'woo_shortname' ); // Reset the settings, sanitizing the various requests made. // Use a SWITCH to determine which settings to update. /* Make sure we're making a request. ------------------------------------------------------------*/ if ( isset( $_REQUEST['page'] ) ) { // Sanitize page being requested. $_page = ''; $_page = mysql_real_escape_string( strtolower( trim( strip_tags( $_REQUEST['page'] ) ) ) ); // Sanitize action being requested. $_action = ''; if ( isset( $_REQUEST['woo_save'] ) ) { $_action = mysql_real_escape_string( strtolower( trim( strip_tags( $_REQUEST['woo_save'] ) ) ) ); } // End IF Statement // If the action is "reset", run the SWITCH. /* Perform settings reset. ------------------------------------------------------------*/ ```
As [mysql\_real\_escape\_string()](http://php.net/manual/en/function.mysql-real-escape-string.php) was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0, you can try [esc\_sql()](https://codex.wordpress.org/Function_Reference/esc_sql) to work for later WP/PHP versions. Replace `mysql_real_escape_string()` with `esc_sql()` at line 111 & 118 in your `admin-interface.php` file. Hope this should work well for you!
244,146
<p>The sites url structure is as follows:</p> <pre><code>www.sitename.com/mypage/page/ </code></pre> <p>I would like only one certain page on the site to resolve as:</p> <pre><code>www.sitename.com/mypage/page.html </code></pre> <p>This is so that when I run the link through the Facebook Sharing debugger at:</p> <pre><code>https://developers.facebook.com/tools/debug/ </code></pre> <p>... the link works correctly. Currently, Facebook appears to strip query string parameters on pages shared that do not resolve as <code>.html</code>.</p>
[ { "answer_id": 244112, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 3, "selected": true, "text": "<p>It depends. The initial page load trigger should not but performance may degrade as visitors browse your site until the Cron job is finished.</p>\n\n<p>Is the scheduled event you plan on using PHP or DB intensive? How often will it run?</p>\n\n<p><strong>Here's how it works</strong></p>\n\n<ul>\n<li>The scheduled event (aka Cron job) will be initialized once it's due (or past due) by whoever hits your website. So visiting <code>www.test.com/somepage/</code> will tell Mr. WP-Cron, \"Hey dude, it's time to wake up and run this Cron job\".</li>\n<li>If it takes 20-30 seconds to finish and is an intensive DB or PHP task (e.g. lots of DB INSERT or UPDATE statements, or parsing a huge <code>.xml</code> file, etc), there's a good chance the site will be slow for <em>anyone</em> during that time. Especially if you're on shared hosting due to shared CPU and memory. </li>\n</ul>\n\n<p>If it's a Cron job you run once a day or week, I wouldn't worry about the performance hit.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/126002/5549\">Supporting Answer</a></p>\n" }, { "answer_id": 348136, "author": "Lucas Cave", "author_id": 67342, "author_profile": "https://wordpress.stackexchange.com/users/67342", "pm_score": 0, "selected": false, "text": "<p>I think the question asks if any cron job runs in the \"main\" PHP worker, the one which is presenting output to the visitor, or it runs in another PHP worker, without \"blocking\" the visitor thread. </p>\n\n<p>It's easy to find out by experiment. </p>\n\n<p>Try to add an \" <code>echo '&lt;h1&gt;Yes, it Runs on this thread&lt;/h1&gt;';</code> \" statement somewhere in the start of the cron-job script. \nIf you visit your site then, and you see \"Yes, it Runs on this thread\" somewhere on your display, then the cron-job runs on your thread.</p>\n\n<p>If you don't, which by the way is what really happens, the cron-job runs in the background (ie in another PHP \"worker\" when you are using PHP-FPM).</p>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244146", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105999/" ]
The sites url structure is as follows: ``` www.sitename.com/mypage/page/ ``` I would like only one certain page on the site to resolve as: ``` www.sitename.com/mypage/page.html ``` This is so that when I run the link through the Facebook Sharing debugger at: ``` https://developers.facebook.com/tools/debug/ ``` ... the link works correctly. Currently, Facebook appears to strip query string parameters on pages shared that do not resolve as `.html`.
It depends. The initial page load trigger should not but performance may degrade as visitors browse your site until the Cron job is finished. Is the scheduled event you plan on using PHP or DB intensive? How often will it run? **Here's how it works** * The scheduled event (aka Cron job) will be initialized once it's due (or past due) by whoever hits your website. So visiting `www.test.com/somepage/` will tell Mr. WP-Cron, "Hey dude, it's time to wake up and run this Cron job". * If it takes 20-30 seconds to finish and is an intensive DB or PHP task (e.g. lots of DB INSERT or UPDATE statements, or parsing a huge `.xml` file, etc), there's a good chance the site will be slow for *anyone* during that time. Especially if you're on shared hosting due to shared CPU and memory. If it's a Cron job you run once a day or week, I wouldn't worry about the performance hit. [Supporting Answer](https://wordpress.stackexchange.com/a/126002/5549)
244,150
<p>I'm running out of ideas why does my ajax function return 0. I'm trying to get stripe payment and after that my function will try and make a booking through checkfront api.</p> <p>Any ideas or help is more than welcomed at this point!</p> <p>Here is my theme's function for AJAX call:</p> <pre><code>add_action( 'wp_ajax_action_varaa_AJAX', 'varaa_AJAX' ); add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX'); function varaa_AJAX(){ global $chargeID; global $bookingStatus; $amount = $_POST['amount']; $token = $_POST['stripeToken']; $name = $_POST['name']; $cardName = $_POST['cardName']; $email = $_POST['email']; $phone = $_POST['phone']; $accept_terms = $_POST['accept']; $insurance = $_POST['insurance']; $extradates = $_POST['extradates']; $id = $_POST['session_id']; $form = array( 'customer_name' =&gt; $name, 'customer_email' =&gt; $email, 'customer_phone' =&gt; $phone, 'accept_terms' =&gt; $accept_terms ); function make_payment($token, $name, $cardName, $email, $phone, $amount, $insurance, $extradates) { require_once(get_template_directory() . 'vendor/stripe/stripe-php/init.php'); global $chargeID; $stripe_settings = get_option('stripe_settings'); // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys if(isset($stripe_settings['test_mode']) &amp;&amp; $stripe_settings['test_mode']) { $secret_key = $stripe_settings['test_secret_key']; } else { $secret_key = $stripe_settings['live_secret_key']; } \Stripe\Stripe::setApiKey($secret_key); // ANONYYMI VARAUS // Create customer and assign charge with $token $customer = \Stripe\Customer::create(array( "source" =&gt; $token, "email" =&gt; $email, "description" =&gt; "Uusi anonyymi varaus.", "metadata" =&gt; [ "nimi" =&gt; $name, "kortissa oleva nimi" =&gt; $cardName, "puhelin" =&gt; $phone, "insurance" =&gt; $insurance, "extradates" =&gt; $extradates ] )); // Get customer id from create above $stripeID = $customer-&gt;id; // Charge customer $charge = \Stripe\Charge::create(array( "amount" =&gt; $amount, // Amount in cents "currency" =&gt; "eur", "capture" =&gt; false, "customer" =&gt; $stripeID )); // Get charge id from charge above $chargeID = $charge-&gt;id; } // Create booking function create_booking($id, $form){ require_once(get_template_directory() . 'lib/booking.php'); require_once(get_template_directory() . 'lib/form.php'); global $bookingStatus; global $bookingId; $Booking = new Booking(); $bookIt = $Booking-&gt;create( array( 'session_id' =&gt; $id, 'form' =&gt; $form ) ); $bookingStatus = $bookIt['request']['status']; $bookingId = $bookIt['booking']['booking_id']; echo $bookIt; } // Run functions above // Check WP nonce if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'bookNow' ) ) { print 'Sorry, your nonce did not verify.'; exit; } else { // Create a customer and charge card try { // Create charge make_payment($token, $name, $cardName, $email, $phone, $amount, $insurance, $extradates); // Create booking create_booking($id, $form); // Check if booking went through if ( $bookingStatus = 'OK' ) { // Capture charge $ch = \Stripe\Charge::retrieve( $chargeID ); $ch-&gt;capture(); // Booking success $value = array('msg' =&gt; 'success', 'bookingStatus' =&gt; $bookingStatus, 'bookingID' =&gt; $bookingId ); echo json_encode($value); } else { // Refund charge $re = \Stripe\Refund::create(array( "charge" =&gt; $chargeID )); $value = array('msg' =&gt; 'error' ); echo json_encode($value); } } catch(\Stripe\Error\Card $e) { // The card has been declined $value = array('error' =&gt; true); // or $result = array('error' =&gt; false); echo json_encode($value); } } die(); } </code></pre> <p>And here is my jQuery AJAX function:</p> <pre><code> var token = response.id, amount = vm.total * 100, name = vm.form.name, cardName = vm.form.cardName, phone = vm.form.phone, email = vm.form.email, terms = vm.form.terms, insurance = vm.form.insurance, action = 'varaa_AJAX', id = vm.sessionId; var nonce = $('#ilmtrail_nonce').val(); var extradates = Object.keys( vm.daysBetweenStartStop ).length * 25 - 25; jQuery.ajax({ url: AJAXurl, data: { action: action, nonce: nonce, stripeToken: token, insurance: insurance, extradates: extradates, name: name, phone: phone, email: email, cardName: cardName, amount: amount, accept: terms, session_id: id }, type: 'post', success: function(value) { if ( value.msg === 'success' ) { console.log(value); vm.form.sending = false; vm.form.sent = true; $('#receipt').openModal(); return true; } else{ alert ('Jokin meni mönkään. Tarkista tiedot ja kokeile uudestaan, ja jos virhe toistuu ole yhteydessä meihin niin saadaan varaus läpi!'); console.log(value); vm.form.sending = false; $form.find('.submit').prop('disabled', false); return false; } }, error: function(data) { vm.form.sending = false; $form.find('.submit').prop('disabled', false); console.log(data); alert ('Jokin meni mönkään. Tarkista tiedot ja kokeile uudestaan, ja jos virhe toistuu ole yhteydessä meihin niin saadaan varaus läpi!'); return false; } }); </code></pre>
[ { "answer_id": 244112, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 3, "selected": true, "text": "<p>It depends. The initial page load trigger should not but performance may degrade as visitors browse your site until the Cron job is finished.</p>\n\n<p>Is the scheduled event you plan on using PHP or DB intensive? How often will it run?</p>\n\n<p><strong>Here's how it works</strong></p>\n\n<ul>\n<li>The scheduled event (aka Cron job) will be initialized once it's due (or past due) by whoever hits your website. So visiting <code>www.test.com/somepage/</code> will tell Mr. WP-Cron, \"Hey dude, it's time to wake up and run this Cron job\".</li>\n<li>If it takes 20-30 seconds to finish and is an intensive DB or PHP task (e.g. lots of DB INSERT or UPDATE statements, or parsing a huge <code>.xml</code> file, etc), there's a good chance the site will be slow for <em>anyone</em> during that time. Especially if you're on shared hosting due to shared CPU and memory. </li>\n</ul>\n\n<p>If it's a Cron job you run once a day or week, I wouldn't worry about the performance hit.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/126002/5549\">Supporting Answer</a></p>\n" }, { "answer_id": 348136, "author": "Lucas Cave", "author_id": 67342, "author_profile": "https://wordpress.stackexchange.com/users/67342", "pm_score": 0, "selected": false, "text": "<p>I think the question asks if any cron job runs in the \"main\" PHP worker, the one which is presenting output to the visitor, or it runs in another PHP worker, without \"blocking\" the visitor thread. </p>\n\n<p>It's easy to find out by experiment. </p>\n\n<p>Try to add an \" <code>echo '&lt;h1&gt;Yes, it Runs on this thread&lt;/h1&gt;';</code> \" statement somewhere in the start of the cron-job script. \nIf you visit your site then, and you see \"Yes, it Runs on this thread\" somewhere on your display, then the cron-job runs on your thread.</p>\n\n<p>If you don't, which by the way is what really happens, the cron-job runs in the background (ie in another PHP \"worker\" when you are using PHP-FPM).</p>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244150", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105738/" ]
I'm running out of ideas why does my ajax function return 0. I'm trying to get stripe payment and after that my function will try and make a booking through checkfront api. Any ideas or help is more than welcomed at this point! Here is my theme's function for AJAX call: ``` add_action( 'wp_ajax_action_varaa_AJAX', 'varaa_AJAX' ); add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX'); function varaa_AJAX(){ global $chargeID; global $bookingStatus; $amount = $_POST['amount']; $token = $_POST['stripeToken']; $name = $_POST['name']; $cardName = $_POST['cardName']; $email = $_POST['email']; $phone = $_POST['phone']; $accept_terms = $_POST['accept']; $insurance = $_POST['insurance']; $extradates = $_POST['extradates']; $id = $_POST['session_id']; $form = array( 'customer_name' => $name, 'customer_email' => $email, 'customer_phone' => $phone, 'accept_terms' => $accept_terms ); function make_payment($token, $name, $cardName, $email, $phone, $amount, $insurance, $extradates) { require_once(get_template_directory() . 'vendor/stripe/stripe-php/init.php'); global $chargeID; $stripe_settings = get_option('stripe_settings'); // Set your secret key: remember to change this to your live secret key in production // See your keys here: https://dashboard.stripe.com/account/apikeys if(isset($stripe_settings['test_mode']) && $stripe_settings['test_mode']) { $secret_key = $stripe_settings['test_secret_key']; } else { $secret_key = $stripe_settings['live_secret_key']; } \Stripe\Stripe::setApiKey($secret_key); // ANONYYMI VARAUS // Create customer and assign charge with $token $customer = \Stripe\Customer::create(array( "source" => $token, "email" => $email, "description" => "Uusi anonyymi varaus.", "metadata" => [ "nimi" => $name, "kortissa oleva nimi" => $cardName, "puhelin" => $phone, "insurance" => $insurance, "extradates" => $extradates ] )); // Get customer id from create above $stripeID = $customer->id; // Charge customer $charge = \Stripe\Charge::create(array( "amount" => $amount, // Amount in cents "currency" => "eur", "capture" => false, "customer" => $stripeID )); // Get charge id from charge above $chargeID = $charge->id; } // Create booking function create_booking($id, $form){ require_once(get_template_directory() . 'lib/booking.php'); require_once(get_template_directory() . 'lib/form.php'); global $bookingStatus; global $bookingId; $Booking = new Booking(); $bookIt = $Booking->create( array( 'session_id' => $id, 'form' => $form ) ); $bookingStatus = $bookIt['request']['status']; $bookingId = $bookIt['booking']['booking_id']; echo $bookIt; } // Run functions above // Check WP nonce if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'bookNow' ) ) { print 'Sorry, your nonce did not verify.'; exit; } else { // Create a customer and charge card try { // Create charge make_payment($token, $name, $cardName, $email, $phone, $amount, $insurance, $extradates); // Create booking create_booking($id, $form); // Check if booking went through if ( $bookingStatus = 'OK' ) { // Capture charge $ch = \Stripe\Charge::retrieve( $chargeID ); $ch->capture(); // Booking success $value = array('msg' => 'success', 'bookingStatus' => $bookingStatus, 'bookingID' => $bookingId ); echo json_encode($value); } else { // Refund charge $re = \Stripe\Refund::create(array( "charge" => $chargeID )); $value = array('msg' => 'error' ); echo json_encode($value); } } catch(\Stripe\Error\Card $e) { // The card has been declined $value = array('error' => true); // or $result = array('error' => false); echo json_encode($value); } } die(); } ``` And here is my jQuery AJAX function: ``` var token = response.id, amount = vm.total * 100, name = vm.form.name, cardName = vm.form.cardName, phone = vm.form.phone, email = vm.form.email, terms = vm.form.terms, insurance = vm.form.insurance, action = 'varaa_AJAX', id = vm.sessionId; var nonce = $('#ilmtrail_nonce').val(); var extradates = Object.keys( vm.daysBetweenStartStop ).length * 25 - 25; jQuery.ajax({ url: AJAXurl, data: { action: action, nonce: nonce, stripeToken: token, insurance: insurance, extradates: extradates, name: name, phone: phone, email: email, cardName: cardName, amount: amount, accept: terms, session_id: id }, type: 'post', success: function(value) { if ( value.msg === 'success' ) { console.log(value); vm.form.sending = false; vm.form.sent = true; $('#receipt').openModal(); return true; } else{ alert ('Jokin meni mönkään. Tarkista tiedot ja kokeile uudestaan, ja jos virhe toistuu ole yhteydessä meihin niin saadaan varaus läpi!'); console.log(value); vm.form.sending = false; $form.find('.submit').prop('disabled', false); return false; } }, error: function(data) { vm.form.sending = false; $form.find('.submit').prop('disabled', false); console.log(data); alert ('Jokin meni mönkään. Tarkista tiedot ja kokeile uudestaan, ja jos virhe toistuu ole yhteydessä meihin niin saadaan varaus läpi!'); return false; } }); ```
It depends. The initial page load trigger should not but performance may degrade as visitors browse your site until the Cron job is finished. Is the scheduled event you plan on using PHP or DB intensive? How often will it run? **Here's how it works** * The scheduled event (aka Cron job) will be initialized once it's due (or past due) by whoever hits your website. So visiting `www.test.com/somepage/` will tell Mr. WP-Cron, "Hey dude, it's time to wake up and run this Cron job". * If it takes 20-30 seconds to finish and is an intensive DB or PHP task (e.g. lots of DB INSERT or UPDATE statements, or parsing a huge `.xml` file, etc), there's a good chance the site will be slow for *anyone* during that time. Especially if you're on shared hosting due to shared CPU and memory. If it's a Cron job you run once a day or week, I wouldn't worry about the performance hit. [Supporting Answer](https://wordpress.stackexchange.com/a/126002/5549)
244,158
<p>My question is: When I write an AJAX function I can write it using a separate file. I can include <code>wp-load.php</code> to that file and use WP core functions. I know this is wrong. Can you tell me how bad is it? Is it a big security risk? What security risks and disadvantages do I have ?</p>
[ { "answer_id": 244175, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 4, "selected": true, "text": "<p>It's incredibly bad, a major security hole, and <em>easily avoided</em>.</p>\n<p>For a safer route, use a REST API endpoints or the old <code>admin-ajax.php</code> API. Both of these are officially supported, documented, and bring other benefits such as pretty URLs to make requests too, support in debugging plugins such as query monitor, etc.</p>\n<h2>Why Is It Bad</h2>\n<p>If you use a standalone file for AJAX or form submission with <code>wp-load.php</code> you're going to have to face some of these issues and more:</p>\n<ul>\n<li>You will need to implement all of the authentication and validation yourself</li>\n<li>Caching plugins will be unable to interact with your endpoint, slowing things down for common requests</li>\n<li>There's no way for security code to intercept the requests</li>\n<li>The non-standard entry point means HTAccess files get bypassed</li>\n<li>Other WP code will be unaware it's an AJAX request</li>\n<li>Your endpoint will <strong>always</strong> work, even if your plugin is deactivated, or you switch themes</li>\n<li>Your endpoint will be active on all sites on a multisite install, not just those you intended it for, which can lead the endpoint being used in places it isn't intended</li>\n<li>The file will be fragile, moving your plugins folder, or putting the plugin in <code>mu-plugins</code> will cause the endpoint to give 500 fatal errors</li>\n<li>Said endpoint can accept <em><strong>anything</strong></em> and it could return <em><strong>anything</strong></em></li>\n<li>your webhosts security might flag it as malicious, most malware installs standalone PHP files once it's broken into your site</li>\n</ul>\n<p>It would be an understatement to say that standalone endpoints in themes and plugins are a security risk, be it an AJAX handler or a form handler, or even a standalone file for images ( timthumb did this and even the original devs have disowned it due to its security reputation )</p>\n<h2>Better/Safer Alternatives</h2>\n<h3>Admin AJAX</h3>\n<p>You could use the WP AJAX API, which is better, but requires you to implement any auth or sanitising checks yourself, and has some quirks. It also provides no structure, as with a standard endpoint it can receive anything and return anything ( if it returns at all ).</p>\n<h3>REST API endpoints</h3>\n<p>Instead, use the REST API with <code>register_rest_route</code>, it's easier to use, has fewer quirks, and handles authentication for you. It also gives you friendlier URLs and namespacing, e.g.:</p>\n<pre><code>function tomjn_rest_test( $request ) {\n return &quot;moomins&quot;;\n}\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'tomjn/v1', '/test/', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'tomjn_rest_test'\n ] );\n} );\n</code></pre>\n<p>You can see this at:</p>\n<p><a href=\"https://tomjn.com/wp-json/tomjn/v1/test\" rel=\"nofollow noreferrer\">https://tomjn.com/wp-json/tomjn/v1/test</a></p>\n<p>With this I can do a number of things:</p>\n<ul>\n<li>specify that the user must be logged in and exactly what they need to be able to do this</li>\n<li>specify the arguments\n<ul>\n<li>specify the type and sanitiser for each argument separately</li>\n<li>specify if they're required or not</li>\n</ul>\n</li>\n<li>specify if an endpoint is for reading writing or both</li>\n</ul>\n<p>All of which are handled by code written for core. Of course you can implement all of this yourself by hand in each WP AJAX handler, but this is much more concise and tested ( and there are few in the WP community experienced enough to do this properly ),</p>\n<p>e.g. to make my endpoint above only available for admins:</p>\n<pre><code>register_rest_route( 'tomjn/v1', '/test/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'tomjn_rest_test',\n 'permission_callback' =&gt; function( $req ) {\n return current_user_can('manage_options');\n }\n) );\n</code></pre>\n<p>As a bonus, it makes certain best practices much easier to use, such as returning data not HTML, uses standard HTTP GET PUT POST etc, and returns a JSON response that can be validated</p>\n<h3>What's so bad about an endpoint being always active?</h3>\n<p>Earlier I mentioned that a native endpoint is active, even if the plugin it's inside is disabled. The only way to turn it off is via internal checks, or by deleting the file. Why is this bad though?</p>\n<p>The crux of this, is that what might be appropriate in one circumstance, may not be in another.</p>\n<p>For example, scenario 1:</p>\n<blockquote>\n<p>An admin installs a plugin that allows users to login and register on the frontend without refreshing the page. To do this the plugin has an endpoint to create users. However, the admin realises that registration isn't what they wanted, only login, and deactivates the plugin. The files are still there however, and users can still load the endpoint to create new users.</p>\n</blockquote>\n<p>Scenario 2:</p>\n<blockquote>\n<p>A plugin is being used on a multisite install to send emails to the administrator of a blog via a contact form. This is all working as expected, but there are other blogs on the site who have no interest in this functionality. By changing the domain used for the blog, an attacker can send emails to the admins of these other blogs by loading the endpoint used by the contact form in the context of the other blogs on the network, sending emails to anybody who has an admin role anywhere on the multisite installation</p>\n</blockquote>\n<p>Scenario 3:</p>\n<blockquote>\n<p>A plugin has a useful debug feature that allows users to change their emails, but for security reasons you've turned this feature off. However, the endpoint that handles the email change form is a standalone file, anybody who knows how the form is built can still change their email</p>\n</blockquote>\n<p>Scenario 4:</p>\n<blockquote>\n<p>A standalone file is being used as a part of a theme, and time goes by. People forget about the file and it doesn't get updated, then it gets exploited. this was a widespread problem with libraries such as <code>timthumb.php</code></p>\n</blockquote>\n" }, { "answer_id": 244177, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": false, "text": "<p>The main downside of writing a custom file endpoint is that your file would not know <em>where</em> <code>wp-load.php</code> is in general case. Whenever you are <em>in</em> WP environment you have the context provided. If you are trying to find where WP core from arbitrary PHP file it's not going to work for all possible configurations out there.</p>\n\n<p>So the biggest downside of this technique is that it cannot be <em>distributed</em> in public extensions.</p>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44888/" ]
My question is: When I write an AJAX function I can write it using a separate file. I can include `wp-load.php` to that file and use WP core functions. I know this is wrong. Can you tell me how bad is it? Is it a big security risk? What security risks and disadvantages do I have ?
It's incredibly bad, a major security hole, and *easily avoided*. For a safer route, use a REST API endpoints or the old `admin-ajax.php` API. Both of these are officially supported, documented, and bring other benefits such as pretty URLs to make requests too, support in debugging plugins such as query monitor, etc. Why Is It Bad ------------- If you use a standalone file for AJAX or form submission with `wp-load.php` you're going to have to face some of these issues and more: * You will need to implement all of the authentication and validation yourself * Caching plugins will be unable to interact with your endpoint, slowing things down for common requests * There's no way for security code to intercept the requests * The non-standard entry point means HTAccess files get bypassed * Other WP code will be unaware it's an AJAX request * Your endpoint will **always** work, even if your plugin is deactivated, or you switch themes * Your endpoint will be active on all sites on a multisite install, not just those you intended it for, which can lead the endpoint being used in places it isn't intended * The file will be fragile, moving your plugins folder, or putting the plugin in `mu-plugins` will cause the endpoint to give 500 fatal errors * Said endpoint can accept ***anything*** and it could return ***anything*** * your webhosts security might flag it as malicious, most malware installs standalone PHP files once it's broken into your site It would be an understatement to say that standalone endpoints in themes and plugins are a security risk, be it an AJAX handler or a form handler, or even a standalone file for images ( timthumb did this and even the original devs have disowned it due to its security reputation ) Better/Safer Alternatives ------------------------- ### Admin AJAX You could use the WP AJAX API, which is better, but requires you to implement any auth or sanitising checks yourself, and has some quirks. It also provides no structure, as with a standard endpoint it can receive anything and return anything ( if it returns at all ). ### REST API endpoints Instead, use the REST API with `register_rest_route`, it's easier to use, has fewer quirks, and handles authentication for you. It also gives you friendlier URLs and namespacing, e.g.: ``` function tomjn_rest_test( $request ) { return "moomins"; } add_action( 'rest_api_init', function () { register_rest_route( 'tomjn/v1', '/test/', [ 'methods' => 'GET', 'callback' => 'tomjn_rest_test' ] ); } ); ``` You can see this at: <https://tomjn.com/wp-json/tomjn/v1/test> With this I can do a number of things: * specify that the user must be logged in and exactly what they need to be able to do this * specify the arguments + specify the type and sanitiser for each argument separately + specify if they're required or not * specify if an endpoint is for reading writing or both All of which are handled by code written for core. Of course you can implement all of this yourself by hand in each WP AJAX handler, but this is much more concise and tested ( and there are few in the WP community experienced enough to do this properly ), e.g. to make my endpoint above only available for admins: ``` register_rest_route( 'tomjn/v1', '/test/', array( 'methods' => 'GET', 'callback' => 'tomjn_rest_test', 'permission_callback' => function( $req ) { return current_user_can('manage_options'); } ) ); ``` As a bonus, it makes certain best practices much easier to use, such as returning data not HTML, uses standard HTTP GET PUT POST etc, and returns a JSON response that can be validated ### What's so bad about an endpoint being always active? Earlier I mentioned that a native endpoint is active, even if the plugin it's inside is disabled. The only way to turn it off is via internal checks, or by deleting the file. Why is this bad though? The crux of this, is that what might be appropriate in one circumstance, may not be in another. For example, scenario 1: > > An admin installs a plugin that allows users to login and register on the frontend without refreshing the page. To do this the plugin has an endpoint to create users. However, the admin realises that registration isn't what they wanted, only login, and deactivates the plugin. The files are still there however, and users can still load the endpoint to create new users. > > > Scenario 2: > > A plugin is being used on a multisite install to send emails to the administrator of a blog via a contact form. This is all working as expected, but there are other blogs on the site who have no interest in this functionality. By changing the domain used for the blog, an attacker can send emails to the admins of these other blogs by loading the endpoint used by the contact form in the context of the other blogs on the network, sending emails to anybody who has an admin role anywhere on the multisite installation > > > Scenario 3: > > A plugin has a useful debug feature that allows users to change their emails, but for security reasons you've turned this feature off. However, the endpoint that handles the email change form is a standalone file, anybody who knows how the form is built can still change their email > > > Scenario 4: > > A standalone file is being used as a part of a theme, and time goes by. People forget about the file and it doesn't get updated, then it gets exploited. this was a widespread problem with libraries such as `timthumb.php` > > >
244,164
<p>On a development server I have a co-install of <strong>PHP 5.6 &amp; 7</strong>; nginx is configured with <strong>PHP 5.6</strong>. When I type "wp" it returns several errors and at the end of the error is a message containing the following:</p> <blockquote> <p>Your PHP installation appears to be missing the MySQL extension which is required by WordPress.</p> </blockquote> <p>Typing wp --info returns: </p> <blockquote> <p>PHP binary: /usr/bin/php7.0<br> PHP version: 7.0.10-2+deb.sury.org~precise+1<br> php.ini used: /etc/php/7.0/cli/php.ini<br> WP-CLI root dir: phar://wp-cli.phar<br> WP-CLI packages dir:<br> WP-CLI global config: /srv/www/wp-cli.yml<br> WP-CLI project config:<br> WP-CLI version: 0.26.0-alpha-5672b63 </p> </blockquote> <p>WP-CLI seems to be defaulting to PHP 7, I would prefer it to use PHP 5.6. </p> <p>So I was wondering if there was an option I could add to the configuration yml file to select which PHP version to use?</p> <p>If you need any further information, please let me know</p>
[ { "answer_id": 244169, "author": "Shiv", "author_id": 102574, "author_profile": "https://wordpress.stackexchange.com/users/102574", "pm_score": 1, "selected": false, "text": "<p>Sounds like you need to change your default PHP version.</p>\n\n<p>I assume <code>php -v</code> returns 7?</p>\n\n<p>You'll need to change the PATH.</p>\n\n<p>See this: <a href=\"https://stackoverflow.com/questions/31206864/use-different-php-version-cli-executable-for-one-command\">https://stackoverflow.com/questions/31206864/use-different-php-version-cli-executable-for-one-command</a></p>\n\n<p>Or this: <a href=\"https://make.wordpress.org/cli/handbook/installing/#using-a-custom-php-binary\" rel=\"nofollow noreferrer\">https://make.wordpress.org/cli/handbook/installing/#using-a-custom-php-binary</a></p>\n" }, { "answer_id": 244170, "author": "TheGentleman", "author_id": 68563, "author_profile": "https://wordpress.stackexchange.com/users/68563", "pm_score": 3, "selected": false, "text": "<p>You can set the php binary that WP-CLI uses by setting an environment variable in your linux shell.</p>\n\n<pre><code>export WP_CLI_PHP=/path/to/php5.6\n</code></pre>\n" }, { "answer_id": 267036, "author": "madaritech", "author_id": 119744, "author_profile": "https://wordpress.stackexchange.com/users/119744", "pm_score": 4, "selected": false, "text": "<p>Got the same problem! Just switch the php version.\nOn my server PHP5.6 was default for apache, while CLI was configured with PHP7.1. After installing WP-CLI, with <code>wp --info</code> I got this result:</p>\n\n<pre><code>PHP binary: /usr/bin/php7.1\nPHP version: 7.1.5-1+deb.sury.org~xenial+1\nphp.ini used: /etc/php/7.1/cli/php.ini\nWP-CLI root dir: phar://wp-cli.phar\n</code></pre>\n\n<p>And when i used the wp core install command i got the error: Your PHP installation appears to be missing the MySQL extension which is required by WordPress.\nThe problem is just the mix between the different versions: we have just to switch completely to 5.6 or 7.1.\nIn my case problem was solved simply by writing on the shell:</p>\n\n<pre><code>sudo update-alternatives --set php /usr/bin/php5.6\n</code></pre>\n\n<p>And then <code>wp --info</code></p>\n\n<pre><code>PHP binary: /usr/bin/php5.6\nPHP version: 5.6.30-10+deb.sury.org~xenial+2\nphp.ini used: /etc/php/5.6/cli/php.ini\nWP-CLI root dir: phar://wp-cli.phar\n</code></pre>\n\n<p>Problem solved! WP-CLI worked like a charm.</p>\n" }, { "answer_id": 398533, "author": "kubi", "author_id": 152837, "author_profile": "https://wordpress.stackexchange.com/users/152837", "pm_score": 3, "selected": false, "text": "<p>On a system where</p>\n<ul>\n<li>you can't change the <code>/usr/bin/php</code> symlink</li>\n<li>you can't change the <code>PATH</code> to point to a different version (because the php executables don't reside in distinct <code>/lib/</code> directories)</li>\n<li><code>WP_CLI_PHP</code> has no effect</li>\n</ul>\n<p>(like my Arch Linux with <code>php</code>(8), <code>php7</code> installed from <em>extra</em> and <code>wp-cli</code> installed from AUR. I'm using php7 vs php8 here, but this should work for any versions.)</p>\n<p>…a workaround may be to call the <code>wp</code> phar executable with <code>php7</code> cli:</p>\n<pre><code>whereis wp\n# /usr/bin/wp\n\nphp7 /usr/bin/wp cli info\n# PHP binary: /usr/bin/php7\n# PHP version: 7.4.25\n</code></pre>\n<p>for convenience you can add a bash alias in your <code>.bashrc</code>:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>alias wp-php7='php7 /usr/bin/wp'\n# or override wp altogether\nalias wp='php7 /usr/bin/wp'\n</code></pre>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93113/" ]
On a development server I have a co-install of **PHP 5.6 & 7**; nginx is configured with **PHP 5.6**. When I type "wp" it returns several errors and at the end of the error is a message containing the following: > > Your PHP installation appears to be missing the MySQL extension which is required by WordPress. > > > Typing wp --info returns: > > PHP binary: /usr/bin/php7.0 > > PHP version: 7.0.10-2+deb.sury.org~precise+1 > > php.ini used: /etc/php/7.0/cli/php.ini > > WP-CLI root dir: phar://wp-cli.phar > > WP-CLI packages dir: > > WP-CLI global config: /srv/www/wp-cli.yml > > WP-CLI project config: > > WP-CLI version: 0.26.0-alpha-5672b63 > > > WP-CLI seems to be defaulting to PHP 7, I would prefer it to use PHP 5.6. So I was wondering if there was an option I could add to the configuration yml file to select which PHP version to use? If you need any further information, please let me know
Got the same problem! Just switch the php version. On my server PHP5.6 was default for apache, while CLI was configured with PHP7.1. After installing WP-CLI, with `wp --info` I got this result: ``` PHP binary: /usr/bin/php7.1 PHP version: 7.1.5-1+deb.sury.org~xenial+1 php.ini used: /etc/php/7.1/cli/php.ini WP-CLI root dir: phar://wp-cli.phar ``` And when i used the wp core install command i got the error: Your PHP installation appears to be missing the MySQL extension which is required by WordPress. The problem is just the mix between the different versions: we have just to switch completely to 5.6 or 7.1. In my case problem was solved simply by writing on the shell: ``` sudo update-alternatives --set php /usr/bin/php5.6 ``` And then `wp --info` ``` PHP binary: /usr/bin/php5.6 PHP version: 5.6.30-10+deb.sury.org~xenial+2 php.ini used: /etc/php/5.6/cli/php.ini WP-CLI root dir: phar://wp-cli.phar ``` Problem solved! WP-CLI worked like a charm.
244,199
<p>I would like to get all the posts under a category (custom post type ui category) into a different template other than archive.php or category.php.</p> <p>I tried normal way of getting the posts using category id, but it returns empty array. Please help.</p>
[ { "answer_id": 244219, "author": "drdogbot7", "author_id": 105124, "author_profile": "https://wordpress.stackexchange.com/users/105124", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>custom post type ui category</p>\n</blockquote>\n\n<p>It sounds like you might be referring to a <strong>custom</strong> taxonomy that you created with the \"Custom Post Type UI\" plugin. If that's the case, then you'll need to use a taxonomy template: <code>taxonomy.php</code>.</p>\n\n<p><a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow\">Wordpress Template Hierarchy</a></p>\n\n<p><code>category.php</code> and <code>tag.php</code> are only used for the built-in \"category\" and \"tag\" taxonomies.</p>\n" }, { "answer_id": 244281, "author": "codieboie", "author_id": 77627, "author_profile": "https://wordpress.stackexchange.com/users/77627", "pm_score": 1, "selected": false, "text": "<p>Worked perfectly for me!!\nCode will bring the posts(under CPT UI) to any page template.</p>\n\n<pre><code> &lt;?php\n$loop = new WP_Query( array( \n 'post_type' =&gt; 'specialoffers', \n 'cat' =&gt; '12', // Whatever the category ID is for your aerial category\n 'posts_per_page' =&gt; 10,\n 'orderby' =&gt; 'date', // Purely optional - just for some ordering\n 'order' =&gt; 'DESC' // Ditto\n) );\n\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt;\n</code></pre>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244199", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77627/" ]
I would like to get all the posts under a category (custom post type ui category) into a different template other than archive.php or category.php. I tried normal way of getting the posts using category id, but it returns empty array. Please help.
Worked perfectly for me!! Code will bring the posts(under CPT UI) to any page template. ``` <?php $loop = new WP_Query( array( 'post_type' => 'specialoffers', 'cat' => '12', // Whatever the category ID is for your aerial category 'posts_per_page' => 10, 'orderby' => 'date', // Purely optional - just for some ordering 'order' => 'DESC' // Ditto ) ); while ( $loop->have_posts() ) : $loop->the_post(); ?> ```
244,221
<p>I'm doing a QUIZ system, but I'm facing a problem that I dont know how to fix it. </p> <p>I need to make a <code>if</code> basically, where it will check if the current user has a post published, as the question title. It's important to say that the <strong>posts</strong> are a specifically <strong>custom-post-type</strong>, so I need to check if there is a post with a certain post-type with the author-id equal to the current user ID.</p> <p>Can someone help-me?</p>
[ { "answer_id": 244226, "author": "Alex Protopopescu", "author_id": 104577, "author_profile": "https://wordpress.stackexchange.com/users/104577", "pm_score": 3, "selected": true, "text": "<p>Using get_posts or WP_query with similar $args:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'your_custom_post_type',\n 'author' =&gt; get_current_user_id(),\n);\n\n$wp_posts = get_posts($args);\n\nif (count($wp_posts)) {\n echo \"Yes, the current user has 'your_custom_post_type' posts published!\";\n} else {\n echo \"No, the current user does not have 'your_custom_post_type' posts published.\";\n}\n</code></pre>\n" }, { "answer_id": 331466, "author": "Ituk", "author_id": 68680, "author_profile": "https://wordpress.stackexchange.com/users/68680", "pm_score": 3, "selected": false, "text": "<p>diving into this I found that <code>count_user_posts()</code> is a better solution. it's shorter, and also cheaper in resources than <code>get_posts()</code>;</p>\n\n<p>so here it is:</p>\n\n<pre><code>$user_id = get_current_user_id(); //the logged in user's id\n$post_type = 'your-post-type-here';\n$posts = count_user_posts( $user_id, $post_type ); //cout user's posts\nif( $posts &gt; 0 ){\n //user has posts\n}\n</code></pre>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101844/" ]
I'm doing a QUIZ system, but I'm facing a problem that I dont know how to fix it. I need to make a `if` basically, where it will check if the current user has a post published, as the question title. It's important to say that the **posts** are a specifically **custom-post-type**, so I need to check if there is a post with a certain post-type with the author-id equal to the current user ID. Can someone help-me?
Using get\_posts or WP\_query with similar $args: ``` $args = array( 'post_type' => 'your_custom_post_type', 'author' => get_current_user_id(), ); $wp_posts = get_posts($args); if (count($wp_posts)) { echo "Yes, the current user has 'your_custom_post_type' posts published!"; } else { echo "No, the current user does not have 'your_custom_post_type' posts published."; } ```
244,223
<p>I'm creating a loop which wouldn't output anything visible to the user, but needed to create a calculation later on.</p> <p>I have:</p> <pre><code>// posts for the week mon-fri $week_array = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'post', 'post_status' =&gt; array('publish'), 'date_query' =&gt; array( 'before' =&gt; 'next Saturday', 'after' =&gt; 'last Monday', ) ); $week_count = get_posts( $week_array ); $array01 = array(); $array02 = array(); echo '&lt;h1&gt;' . count( $week_count ) . ' posts this week&lt;/h1&gt;'; foreach( $week_count as $post ) { setup_postdata($post); $a = rand(5,15); $meta_array01 = get_post_meta( $post-&gt;ID, 'meta_login', true ); $meta_array02 = get_post_meta( $post-&gt;ID, 'meta_logout', true ); $array01[$post-&gt;ID] = $meta_array01; $array02[$post-&gt;ID] = $meta_array02; } wp_reset_postdata(); </code></pre> <p>My main intention would have been to have something like this outputted:</p> <pre><code>array( [167] =&gt; array( 'meta_login' =&gt; 2016-10-25 18:34:55 'meta_logout' =&gt; 2016-10-25 19:15:12 ), [168] =&gt; array( 'meta_login' =&gt; ... 'meta_logout' =&gt; ... ) ... // and so on for each matching post ); </code></pre> <p>But I couldn't figure that out, so I thought to merge the two arrays above into one, but when I use <code>array_merge_recursive()</code> I get an array from 0 to the last number of posts, but lose their order.</p> <p>Effectively, my aim is to calculate the time between the two meta fields.</p>
[ { "answer_id": 244224, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>Add <code>'fields' =&gt; 'ids'</code> to skip setting up the post and just create the array you want in the <code>foreach</code>.</p>\n\n<pre><code>$week_args = array(\n 'posts_per_page' =&gt; - 1,\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; array( 'publish' ),\n 'fields' =&gt; 'ids',\n 'date_query' =&gt; array(\n 'before' =&gt; 'next Saturday',\n 'after' =&gt; 'last Monday',\n ),\n);\n\n$week_array = get_posts( $week_args );\n$week_count = count( $week_array );\n\nprintf( '&lt;h1&gt;%s posts this week&lt;/h1&gt;', $week_count );\n\n$dates = array();\nforeach ( $week_array as $post_id ) {\n\n $login = get_post_meta( $post_id, 'meta_login', true );\n $logout = get_post_meta( $post_id, 'meta_logout', true );\n\n $dates[ $post_id ] = array(\n \"meta_login\" =&gt; $login ? $login : 0,\n \"meta_logout\" =&gt; $logout ? $logout : 0,\n \"dif\" =&gt; abs(strtotime($logout) - strtotime($login)),\n );\n}\n\necho \"&lt;pre&gt;\";\nprint_r( $dates );\n</code></pre>\n" }, { "answer_id": 244225, "author": "Alex Protopopescu", "author_id": 104577, "author_profile": "https://wordpress.stackexchange.com/users/104577", "pm_score": 0, "selected": false, "text": "<p>Having a look at the get_post_meta WP function <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/get_post_meta/</a> reveals that using it with the parameter $single set to (bool) 'true' the function returns the meta_value of the requested meta_key. If the parameter $single is set to (bool) 'false' then it returns an array of the meta_value or values (in case there are multiple values matching the query) for the requested meta_key.</p>\n\n<p>So to get your desired output you could go at it like this:</p>\n\n<pre><code>foreach( $week_count as $post ) {\n setup_postdata($post);\n $a = rand(5,15);\n\n $meta_array[$post-&gt;ID] = array( 'meta_login' =&gt; get_post_meta($post-&gt;ID, 'meta_login', true), \n 'meta_logout' =&gt; get_post_meta($post-&gt;ID, 'meta_logout', true)\n );\n}\n</code></pre>\n" } ]
2016/10/27
[ "https://wordpress.stackexchange.com/questions/244223", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17411/" ]
I'm creating a loop which wouldn't output anything visible to the user, but needed to create a calculation later on. I have: ``` // posts for the week mon-fri $week_array = array( 'posts_per_page' => -1, 'post_type' => 'post', 'post_status' => array('publish'), 'date_query' => array( 'before' => 'next Saturday', 'after' => 'last Monday', ) ); $week_count = get_posts( $week_array ); $array01 = array(); $array02 = array(); echo '<h1>' . count( $week_count ) . ' posts this week</h1>'; foreach( $week_count as $post ) { setup_postdata($post); $a = rand(5,15); $meta_array01 = get_post_meta( $post->ID, 'meta_login', true ); $meta_array02 = get_post_meta( $post->ID, 'meta_logout', true ); $array01[$post->ID] = $meta_array01; $array02[$post->ID] = $meta_array02; } wp_reset_postdata(); ``` My main intention would have been to have something like this outputted: ``` array( [167] => array( 'meta_login' => 2016-10-25 18:34:55 'meta_logout' => 2016-10-25 19:15:12 ), [168] => array( 'meta_login' => ... 'meta_logout' => ... ) ... // and so on for each matching post ); ``` But I couldn't figure that out, so I thought to merge the two arrays above into one, but when I use `array_merge_recursive()` I get an array from 0 to the last number of posts, but lose their order. Effectively, my aim is to calculate the time between the two meta fields.
Add `'fields' => 'ids'` to skip setting up the post and just create the array you want in the `foreach`. ``` $week_args = array( 'posts_per_page' => - 1, 'post_type' => 'post', 'post_status' => array( 'publish' ), 'fields' => 'ids', 'date_query' => array( 'before' => 'next Saturday', 'after' => 'last Monday', ), ); $week_array = get_posts( $week_args ); $week_count = count( $week_array ); printf( '<h1>%s posts this week</h1>', $week_count ); $dates = array(); foreach ( $week_array as $post_id ) { $login = get_post_meta( $post_id, 'meta_login', true ); $logout = get_post_meta( $post_id, 'meta_logout', true ); $dates[ $post_id ] = array( "meta_login" => $login ? $login : 0, "meta_logout" => $logout ? $logout : 0, "dif" => abs(strtotime($logout) - strtotime($login)), ); } echo "<pre>"; print_r( $dates ); ```
244,237
<p>i have the following code to get the next and the previous article. </p> <pre><code>if(wp_get_post_parent_id($post-&gt;ID)){ $pagelist = get_pages('post_parent='.wp_get_post_parent_id($post-&gt;ID)); $pages = array(); foreach ($pagelist as $page) { $pages[] += $page-&gt;ID; } $current = array_search($post-&gt;ID, $pages); $prevID = $pages[$current-1]; $nextID = $pages[$current+1]; } </code></pre> <p>With the $nextID and $previID I am able to create a link like here:</p> <pre><code>&lt;a title="&lt;?php echo get_the_title( $prevID ); ?&gt;" href="&lt;?php echo get_permalink($prevID); ?&gt;"&gt;&lt;?php echo get_the_title( $prevID ); ?&gt; &amp;raquo;&lt;/a&gt; </code></pre> <p>Now i want to also have the featured image of this $prevID and $nextID. I don't know why, but it does not work. I tried the following:</p> <pre><code>echo wp_get_attachment_url(get_post_thumbnail_id($prevID)); </code></pre> <p>How can i do that? Even if i add the fix ID like 1253 instead of $prevID, it does not work. When i use $post->ID (of the current article, just to check), it works.</p> <p>Any idea?</p>
[ { "answer_id": 244236, "author": "Sebastian Kaczmarek", "author_id": 100836, "author_profile": "https://wordpress.stackexchange.com/users/100836", "pm_score": 1, "selected": false, "text": "<p>If you want to make any text to be translated you have to use a plugin and mark the text as translatable. To do so you have to use <code>__()</code> or <code>_e()</code> instead of <code>echo</code>. The difference beetwen <code>__()</code> and <code>_e()</code> is that first one doesn't <code>echo</code> the text while second one does. So if you do something like this: <code>__(\"Some text\", \"text domain\")</code> it will be marked as translatable text but it won't be displayed but if you use <code>_e(\"Some text\",\"text domain\")</code> the text will be also displayed on screen. Now if anyone will install a plugin he will see translated text</p>\n" }, { "answer_id": 244274, "author": "Haudegen", "author_id": 91039, "author_profile": "https://wordpress.stackexchange.com/users/91039", "pm_score": 0, "selected": false, "text": "<p>actually it's really easy - with <a href=\"https://cloud.google.com/translate/docs/\" rel=\"nofollow\">Google Translator API</a></p>\n\n<ol>\n<li>Get an API Key from Google.</li>\n<li>Write yourself a function (to the functions.php) to translate text.</li>\n<li>Profit.</li>\n</ol>\n\n<p>Here is how to start and where you get the API Key etc.: <a href=\"https://cloud.google.com/translate/v2/quickstart\" rel=\"nofollow\">https://cloud.google.com/translate/v2/quickstart</a></p>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244237", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105824/" ]
i have the following code to get the next and the previous article. ``` if(wp_get_post_parent_id($post->ID)){ $pagelist = get_pages('post_parent='.wp_get_post_parent_id($post->ID)); $pages = array(); foreach ($pagelist as $page) { $pages[] += $page->ID; } $current = array_search($post->ID, $pages); $prevID = $pages[$current-1]; $nextID = $pages[$current+1]; } ``` With the $nextID and $previID I am able to create a link like here: ``` <a title="<?php echo get_the_title( $prevID ); ?>" href="<?php echo get_permalink($prevID); ?>"><?php echo get_the_title( $prevID ); ?> &raquo;</a> ``` Now i want to also have the featured image of this $prevID and $nextID. I don't know why, but it does not work. I tried the following: ``` echo wp_get_attachment_url(get_post_thumbnail_id($prevID)); ``` How can i do that? Even if i add the fix ID like 1253 instead of $prevID, it does not work. When i use $post->ID (of the current article, just to check), it works. Any idea?
If you want to make any text to be translated you have to use a plugin and mark the text as translatable. To do so you have to use `__()` or `_e()` instead of `echo`. The difference beetwen `__()` and `_e()` is that first one doesn't `echo` the text while second one does. So if you do something like this: `__("Some text", "text domain")` it will be marked as translatable text but it won't be displayed but if you use `_e("Some text","text domain")` the text will be also displayed on screen. Now if anyone will install a plugin he will see translated text
244,250
<p>I'm using Advanced Custom Fields to make some sort of personal database of my logins. ACF has a password-field type which works great, but it stores the data in plain text to the database. So I found <a href="http://biostall.com/hashing-acf-password-type-fields-in-wordpress/" rel="nofollow">this topic</a> which enables us to hash the password before sending it to the database:</p> <pre><code>function at_vault_encrypt( $value, $post_id, $field ) { $value = wp_hash_password( $value ); return $value; } add_filter('acf/update_value/type=password', 'at_vault_encrypt', 10, 3); </code></pre> <p>This function uses the <code>wp_hash_password</code> functionality and applies it to the ACF update filter. The core of my question is this: Can I un-hash it when the data get's shown in the backend?</p> <p>The problem is when I save an item with password and reopen it, it shows the hashed password instead of the one I entered. This foregoes the whole point of noting the passwords if I can't read them out later.</p> <p>So I figured I might 'de-hash' the passwords, but that doesn't seem an option. Maybe this is taking WordPress too far and it can't be rightly done, it's just an extra security measure not to have the fields saved plaintext in the database.</p> <p>(PS. I'm not here to start a discussion on data-security. I'm well aware of passwords managers and other (maybe more secure ways) to do this).</p>
[ { "answer_id": 244267, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>By definition, hashing is <strong>one-way ecnryption</strong>, so it can not be reversed (maybe some super hacker can do it, but it should be very difficult or almost imposible to do). It is not a bug, problem or somehting like that, It is the intended behaviour and it how every site should work.</p>\n\n<p>Many people use same password across several services, so no one, including the site owner, should be able to know a user's password. Imaging that the site is hacked, if the passwords can be reversed, the hacker could have access to all passwords, and potentially not only for your site. Or simply a site owner could use the user's password to access user's account in other sites.</p>\n\n<p>So, if you hash a password with <code>wp_hash_password()</code>, or any other hashgin method, and you can not decrypt it, it is exactly like it is designed.</p>\n\n<p>You may be interested in encryption instead of hashing, a method that can be reversed only if the rules applied to do the encryption are known, usually by using secret keys. You can do it in PHP, for example, with <a href=\"http://php.net/manual/en/function.mcrypt-encrypt.php\" rel=\"nofollow noreferrer\"><code>mcrypt_encrypt()</code></a>/<a href=\"http://php.net/manual/en/function.mcrypt-decrypt.php\" rel=\"nofollow noreferrer\"><code>mcrypt_decrypt()</code></a>. But it is not safe for users, because the site owner can know his/her password; use it if you need to keep confidentiality but not integrity.</p>\n\n<p>Or you may be interested in encoding, but encoding is just plain text in another format that a human may not read directly, but just because it is not used to it, not because it is secure or encrypted in some way, that is why it can easily decoded by converting back to the original format (that is, you get zero security).</p>\n\n<p>Some ready to use encoding methods in PHP:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/function.str-rot13.php\" rel=\"nofollow noreferrer\"><code>str_rot13()</code></a> (<a href=\"https://stackoverflow.com/questions/10653981/how-rot13-encode-and-decode-on-a-php-code-string\">do it twice and you get the original</a>)</li>\n<li><a href=\"http://php.net/manual/en/function.base64-encode.php\" rel=\"nofollow noreferrer\"><code>base64_encode()</code></a>/<a href=\"http://php.net/manual/en/function.base64-decode.php\" rel=\"nofollow noreferrer\"><code>base64_decode()</code></a></li>\n<li><a href=\"http://php.net/manual/en/function.gzencode.php\" rel=\"nofollow noreferrer\"><code>gzencode()</code></a>/<a href=\"http://php.net/manual/en/function.gzdecode.php\" rel=\"nofollow noreferrer\"><code>gzdecode()</code></a></li>\n<li>And lots more ....</li>\n</ul>\n" }, { "answer_id": 244285, "author": "Daniel", "author_id": 12865, "author_profile": "https://wordpress.stackexchange.com/users/12865", "pm_score": -1, "selected": false, "text": "<p>Hashes are not meant to be reversible. Instead, you could use an encoding scheme like Base64 for storing your information:</p>\n\n<pre><code>// Encode\nfunction at_vault_encode( $value, $post_id, $field ) { \n return base64_encode($value);\n} \nadd_filter('acf/update_value/type=password', 'at_vault_encode', 10, 3);\n\n// Decode\nfunction at_vault_decode( $value, $post_id, $field ) { \n return base64_decode($value);\n} \nadd_filter('acf/load_value/type=password', 'at_vault_decode', 10, 3);\n</code></pre>\n\n<p>However, it's important to note that this way of storing passwords is just as insecure as storing plaintext strings.</p>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82866/" ]
I'm using Advanced Custom Fields to make some sort of personal database of my logins. ACF has a password-field type which works great, but it stores the data in plain text to the database. So I found [this topic](http://biostall.com/hashing-acf-password-type-fields-in-wordpress/) which enables us to hash the password before sending it to the database: ``` function at_vault_encrypt( $value, $post_id, $field ) { $value = wp_hash_password( $value ); return $value; } add_filter('acf/update_value/type=password', 'at_vault_encrypt', 10, 3); ``` This function uses the `wp_hash_password` functionality and applies it to the ACF update filter. The core of my question is this: Can I un-hash it when the data get's shown in the backend? The problem is when I save an item with password and reopen it, it shows the hashed password instead of the one I entered. This foregoes the whole point of noting the passwords if I can't read them out later. So I figured I might 'de-hash' the passwords, but that doesn't seem an option. Maybe this is taking WordPress too far and it can't be rightly done, it's just an extra security measure not to have the fields saved plaintext in the database. (PS. I'm not here to start a discussion on data-security. I'm well aware of passwords managers and other (maybe more secure ways) to do this).
By definition, hashing is **one-way ecnryption**, so it can not be reversed (maybe some super hacker can do it, but it should be very difficult or almost imposible to do). It is not a bug, problem or somehting like that, It is the intended behaviour and it how every site should work. Many people use same password across several services, so no one, including the site owner, should be able to know a user's password. Imaging that the site is hacked, if the passwords can be reversed, the hacker could have access to all passwords, and potentially not only for your site. Or simply a site owner could use the user's password to access user's account in other sites. So, if you hash a password with `wp_hash_password()`, or any other hashgin method, and you can not decrypt it, it is exactly like it is designed. You may be interested in encryption instead of hashing, a method that can be reversed only if the rules applied to do the encryption are known, usually by using secret keys. You can do it in PHP, for example, with [`mcrypt_encrypt()`](http://php.net/manual/en/function.mcrypt-encrypt.php)/[`mcrypt_decrypt()`](http://php.net/manual/en/function.mcrypt-decrypt.php). But it is not safe for users, because the site owner can know his/her password; use it if you need to keep confidentiality but not integrity. Or you may be interested in encoding, but encoding is just plain text in another format that a human may not read directly, but just because it is not used to it, not because it is secure or encrypted in some way, that is why it can easily decoded by converting back to the original format (that is, you get zero security). Some ready to use encoding methods in PHP: * [`str_rot13()`](http://php.net/manual/en/function.str-rot13.php) ([do it twice and you get the original](https://stackoverflow.com/questions/10653981/how-rot13-encode-and-decode-on-a-php-code-string)) * [`base64_encode()`](http://php.net/manual/en/function.base64-encode.php)/[`base64_decode()`](http://php.net/manual/en/function.base64-decode.php) * [`gzencode()`](http://php.net/manual/en/function.gzencode.php)/[`gzdecode()`](http://php.net/manual/en/function.gzdecode.php) * And lots more ....
244,258
<p>I am trying to use underscore in my WordPress Admin. This is what I have done: I enqueue a script in the very end of the page, like so:</p> <pre><code>function load_admin_scripts() { wp_enqueue_script( "my-admin", get_template_directory_uri() . "/assets/scripts/admin.js", array('jquery', 'wp-util'), null, true ); } add_action('admin_enqueue_scripts', 'load_admin_scripts'); </code></pre> <p>...then in the script file, I am at the moment only trying this:</p> <pre><code>console.log( jQuery ); // is defined console.log( underscore ); // ReferenceError: underscore is not defined(…) </code></pre> <p>Can anyone point me to the solution for this?</p>
[ { "answer_id": 244262, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Go to you chrome <strong>JavaScript</strong> console window and write <code>_.VERSION</code>. Then press Enter. It will return you the version of the included <strong>Underscore JS</strong>. Also it will make sure that <strong>Underscore JS</strong> is included or enqueued. And <strong>Underscore JS</strong> is include in <strong>WordPress</strong> admin by default. You don't need to enqueue it. Just use it as you use any where else.</p>\n" }, { "answer_id": 345838, "author": "Maidul", "author_id": 21142, "author_profile": "https://wordpress.stackexchange.com/users/21142", "pm_score": 1, "selected": false, "text": "<p>Make sure you enqueue underscore js on theme function.php</p>\n\n<pre><code>/**\n * Proper way to enqueue scripts and styles.\n */\nfunction wpdocs_theme_name_scripts() {\n wp_enqueue_script( 'underscore' );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>Then you can check underscore version on browser console</p>\n\n<pre><code>console.log(_.VERSION)\n</code></pre>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244258", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18713/" ]
I am trying to use underscore in my WordPress Admin. This is what I have done: I enqueue a script in the very end of the page, like so: ``` function load_admin_scripts() { wp_enqueue_script( "my-admin", get_template_directory_uri() . "/assets/scripts/admin.js", array('jquery', 'wp-util'), null, true ); } add_action('admin_enqueue_scripts', 'load_admin_scripts'); ``` ...then in the script file, I am at the moment only trying this: ``` console.log( jQuery ); // is defined console.log( underscore ); // ReferenceError: underscore is not defined(…) ``` Can anyone point me to the solution for this?
Go to you chrome **JavaScript** console window and write `_.VERSION`. Then press Enter. It will return you the version of the included **Underscore JS**. Also it will make sure that **Underscore JS** is included or enqueued. And **Underscore JS** is include in **WordPress** admin by default. You don't need to enqueue it. Just use it as you use any where else.
244,268
<p>I have a custom post type that have many taxonomies. In the front end, a user can assign a 'category' (term_meta) value to the taxonomy - hardware or software.</p> <p>I wanted to be able to count how many term_meta posts there were.</p> <pre><code> $base_array = array( 'posts_per_page' =&gt; -1, 'fields' =&gt; 'ids', 'post_type' =&gt; 'cpt', 'post_status' =&gt; array('publish'), 'date_query' =&gt; array( 'before' =&gt; 'next Saturday', 'after' =&gt; 'last Monday' ) ); $base = get_posts($base_array); echo count($base); </code></pre> <p>This will give me the total count of posts in the week. But I want to count the posts that have the taxonomy with the term_meta 'hardware' or 'software'.</p> <p>Is that possible?</p>
[ { "answer_id": 244276, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 2, "selected": false, "text": "<pre><code>$base_array = array(\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids',\n 'post_type' =&gt; 'cpt',\n 'post_status' =&gt; array('publish'),\n 'date_query' =&gt; array(\n 'before' =&gt; 'next Saturday',\n 'after' =&gt; 'last Monday'\n ),\n 'tax_query' =&gt; array(\n 'taxonomy' =&gt; 'pas_here_taxonomy'\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'hardware', 'software'),\n'operator' =&gt; 'IN'\n )\n);\n\n$base = get_posts($base_array);\n\necho count($base);\n</code></pre>\n" }, { "answer_id": 244743, "author": "markb", "author_id": 17411, "author_profile": "https://wordpress.stackexchange.com/users/17411", "pm_score": 2, "selected": true, "text": "<p>So, looking at some other code I have, I feel this would be the right way to go about it. I haven't tested it, but I feel it would work in the way I needed it too (no longer need to count the types).</p>\n\n<pre><code>$base_array = array(\n 'posts_per_page' =&gt; -1,\n 'fields' =&gt; 'ids',\n 'post_type' =&gt; 'cpt',\n 'post_status' =&gt; array('publish'),\n 'date_query' =&gt; array(\n 'before' =&gt; 'next Saturday',\n 'after' =&gt; 'last Monday'\n )\n);\n\n$base = get_posts($base_array);\n\n\nforeach( $base as $post_id ) {\n $term_meta = get_term_meta( post_id, 'tax_term_type', true );\n\n $term_hardware += ($term_meta == 'term_meta_hardware') ? 1 : 0;\n $term_software += ($term_meta == 'term_meta_software') ? 1 : 0;\n}\n\necho count( $term_hardware );\necho count( $term_software );\n</code></pre>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17411/" ]
I have a custom post type that have many taxonomies. In the front end, a user can assign a 'category' (term\_meta) value to the taxonomy - hardware or software. I wanted to be able to count how many term\_meta posts there were. ``` $base_array = array( 'posts_per_page' => -1, 'fields' => 'ids', 'post_type' => 'cpt', 'post_status' => array('publish'), 'date_query' => array( 'before' => 'next Saturday', 'after' => 'last Monday' ) ); $base = get_posts($base_array); echo count($base); ``` This will give me the total count of posts in the week. But I want to count the posts that have the taxonomy with the term\_meta 'hardware' or 'software'. Is that possible?
So, looking at some other code I have, I feel this would be the right way to go about it. I haven't tested it, but I feel it would work in the way I needed it too (no longer need to count the types). ``` $base_array = array( 'posts_per_page' => -1, 'fields' => 'ids', 'post_type' => 'cpt', 'post_status' => array('publish'), 'date_query' => array( 'before' => 'next Saturday', 'after' => 'last Monday' ) ); $base = get_posts($base_array); foreach( $base as $post_id ) { $term_meta = get_term_meta( post_id, 'tax_term_type', true ); $term_hardware += ($term_meta == 'term_meta_hardware') ? 1 : 0; $term_software += ($term_meta == 'term_meta_software') ? 1 : 0; } echo count( $term_hardware ); echo count( $term_software ); ```
244,272
<p>In my error log I m having this error:</p> <blockquote> <p>PHP Warning: strip_tags() expects parameter 1 to be string</p> </blockquote> <p>Which seems to make crash my server . . .</p> <p>I'm not much aware of Server Conf / Back end Dev, but this are the piece of code being impacted:</p> <pre><code>&lt;?php # show categories $categories = get_the_term_list( $post-&gt;ID, 'ev_categories', '&lt;p&gt;', ', ', '&lt;/p&gt;' ); $categories = strip_tags( $categories ); echo $categories; if ($categories &lt;&gt; '') echo '&lt;div class="clear"&gt;&lt;/div&gt;'; ?&gt; ?php # show categories $categories = get_the_term_list( $post-&gt;ID, 'ev_categories', '&lt;p&gt;', ', ', '&lt;/p&gt;' ); $categories = strip_tags( $categories ); if ( strpos($categories,'arts and culture') !== false ) { $catID = 1; }; if ( strpos($categories,'business') !== false ) { $catID = 2; }; if ( strpos($categories,'community') !== false ) { $catID = 3; }; if ( strpos($categories,'education') !== false ) { $catID = 4; }; if ( strpos($categories,'sport') !== false ) { $catID = 5; }; ?&gt; &lt;?php # show categories $categories = get_the_term_list( $post-&gt;ID, 'ev_categories', '&lt;p&gt;', ', ', '&lt;/p&gt;' ); $categories = strip_tags( $categories ); if ( strpos($categories,'arts and culture') !== false ) { $catID = 1; }; if ( strpos($categories,'business') !== false ) { $catID = 2; }; if ( strpos($categories,'community') !== false ) { $catID = 3; }; if ( strpos($categories,'education') !== false ) { $catID = 4; }; if ( strpos($categories,'sport') !== false ) { $catID = 5; }; # show locations $locations = get_the_term_list( $post-&gt;ID, 'ev_locations', '&lt;p&gt;', ', ', '&lt;/p&gt;' ); $locations = strip_tags( $locations ); #echo $locations ; </code></pre> <p>?></p> <p>Each time, related to the second line below:</p> <pre><code>$categories = get_the_term_list( $post-&gt;ID, 'ev_categories', '&lt;p&gt;', ', ', '&lt;/p&gt;' ); $categories = strip_tags( $categories ); </code></pre> <p>If anybody is aware how I can fix this, it will be lovely,</p>
[ { "answer_id": 244277, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>If you look at the source of <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow\"><code>get_the_term_list</code></a>, you will see that it will try to get the terms first. If that doesn't succeed, it will return an error or <code>false</code>. So you would have to account for that before you try to strip the tags:</p>\n\n<pre><code>if (!is_wp_error ($categories) &amp;&amp; false != $categories)\n $categories = strip_tags( $categories );\n</code></pre>\n\n<p>In all other cases <code>get_the_term_list</code> returns a string and your code should work fine.</p>\n\n<p>By the way, it's not very useful to have <code>get_the_term_list</code> to add <code>&lt;p&gt;</code> tags if you strip those away immediately. Also, there is a filter towards the end of <code>get_the_term_list</code> that you could use to strip the link tags that are added by the function. Finally, you may want to take a look at <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow\"><code>get_the_terms</code></a>, which will give you a nice array of terms without any tags to strip.</p>\n" }, { "answer_id": 245050, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p>???\n$categories is an array, and it cant be parsed as string.\ninstead, you'd better to do this:</p>\n\n<pre><code>foreach($categories as $name =&gt;$value){\n $locations[] = strip_tags($value-&gt;slug);\n}\n</code></pre>\n\n<p>or another way for arrays</p>\n\n<pre><code>array_map('strip_tags', $categories);\n</code></pre>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244272", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54146/" ]
In my error log I m having this error: > > PHP Warning: strip\_tags() expects parameter 1 to be string > > > Which seems to make crash my server . . . I'm not much aware of Server Conf / Back end Dev, but this are the piece of code being impacted: ``` <?php # show categories $categories = get_the_term_list( $post->ID, 'ev_categories', '<p>', ', ', '</p>' ); $categories = strip_tags( $categories ); echo $categories; if ($categories <> '') echo '<div class="clear"></div>'; ?> ?php # show categories $categories = get_the_term_list( $post->ID, 'ev_categories', '<p>', ', ', '</p>' ); $categories = strip_tags( $categories ); if ( strpos($categories,'arts and culture') !== false ) { $catID = 1; }; if ( strpos($categories,'business') !== false ) { $catID = 2; }; if ( strpos($categories,'community') !== false ) { $catID = 3; }; if ( strpos($categories,'education') !== false ) { $catID = 4; }; if ( strpos($categories,'sport') !== false ) { $catID = 5; }; ?> <?php # show categories $categories = get_the_term_list( $post->ID, 'ev_categories', '<p>', ', ', '</p>' ); $categories = strip_tags( $categories ); if ( strpos($categories,'arts and culture') !== false ) { $catID = 1; }; if ( strpos($categories,'business') !== false ) { $catID = 2; }; if ( strpos($categories,'community') !== false ) { $catID = 3; }; if ( strpos($categories,'education') !== false ) { $catID = 4; }; if ( strpos($categories,'sport') !== false ) { $catID = 5; }; # show locations $locations = get_the_term_list( $post->ID, 'ev_locations', '<p>', ', ', '</p>' ); $locations = strip_tags( $locations ); #echo $locations ; ``` ?> Each time, related to the second line below: ``` $categories = get_the_term_list( $post->ID, 'ev_categories', '<p>', ', ', '</p>' ); $categories = strip_tags( $categories ); ``` If anybody is aware how I can fix this, it will be lovely,
If you look at the source of [`get_the_term_list`](https://developer.wordpress.org/reference/functions/get_the_term_list/), you will see that it will try to get the terms first. If that doesn't succeed, it will return an error or `false`. So you would have to account for that before you try to strip the tags: ``` if (!is_wp_error ($categories) && false != $categories) $categories = strip_tags( $categories ); ``` In all other cases `get_the_term_list` returns a string and your code should work fine. By the way, it's not very useful to have `get_the_term_list` to add `<p>` tags if you strip those away immediately. Also, there is a filter towards the end of `get_the_term_list` that you could use to strip the link tags that are added by the function. Finally, you may want to take a look at [`get_the_terms`](https://developer.wordpress.org/reference/functions/get_the_terms/), which will give you a nice array of terms without any tags to strip.
244,318
<p>I have a custom post type 'locations', with custom fields 'State', 'City', 'Address', and 'Phone'. </p> <p>I would like to query these fields in an organized list. Let's say I have these three posts:</p> <blockquote> <p>City: Los Angeles; State: California; Address: 123 Main St.; Phone: 888-111-2222</p> <p>City: San Jose; State: California; Address: 55 1st St.; Phone: 888-333-4444</p> <p>City: Brooklyn; State: New York; Address: 9 25th St.; Phone: 888-555-4848</p> </blockquote> <p>Should display like this:</p> <blockquote> <ul> <li>California <ul> <li>Los Angeles <ul> <li>123 Main St.</li> <li>888-111-2222</li> </ul></li> <li>San Jose <ul> <li>55 1st St.</li> <li>888-333-4444</li> </ul></li> </ul></li> <li>New York <ul> <li>Brooklyn <ul> <li>9 25th St.</li> <li>888-555-4848</li> </ul></li> </ul></li> </ul> </blockquote> <p>So far, I am using this code to grab the states in a list and it is working:</p> <pre><code>&lt;ul&gt; &lt;?php global $wpdb; $query = "SELECT meta_value, COUNT(post_id) as count FROM $wpdb-&gt;postmeta WHERE meta_key = 'state' GROUP BY meta_value ORDER BY meta_value;"; $states = $wpdb-&gt;get_results( $query ); foreach( $states as $state ) : echo'&lt;li&gt;'; echo $state-&gt;meta_value; echo '&lt;/li&gt;'; endforeach; ?&gt; &lt;/ul&gt; </code></pre> <p>But this is of course only displaying:</p> <blockquote> <ul> <li>California</li> <li>New York</li> </ul> </blockquote> <p>What I'm trying to figure out is how to query the rest of the data I'm looking for.</p> <p>Thanks in advance!</p>
[ { "answer_id": 244325, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>A little example, based on get_posts and get_post_meta.</p>\n<pre><code>$locations = get_posts(\n array('post_type' =&gt; 'locations',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n );\necho '&lt;ul&gt;';\nforeach ($locations as $location) {\n $location_city = get_post_meta($location-&gt;ID, 'city', true);\n $location_state = get_post_meta($location-&gt;ID, 'state', true);\n $location_address = get_post_meta($location-&gt;ID, 'address', true);\n\n echo '&lt;li&gt;' . $location_city;\n echo '&lt;li&gt;' . $location_state . '&lt;/li&gt;';\n echo '&lt;li&gt;' . $location_address . '&lt;/li&gt;';\n echo '&lt;/li&gt;';\n}\necho '&lt;/ul&gt;';\n</code></pre>\n<p>You'll need to adapt $args array in the get_posts to order by special value. With this way you loop through posts and retrieve their custom fields with get_post_meta.</p>\n<p>Edit:\nYou can add a meta_query array in the arguments for the query, to get or order.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Custom field in WP_Query</a></p>\n<p>Hope it helps.</p>\n" }, { "answer_id": 244352, "author": "Alvin", "author_id": 105873, "author_profile": "https://wordpress.stackexchange.com/users/105873", "pm_score": 1, "selected": true, "text": "<p>I ended up solving my issue using this guide: <a href=\"http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/\" rel=\"nofollow\">http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/</a></p>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105873/" ]
I have a custom post type 'locations', with custom fields 'State', 'City', 'Address', and 'Phone'. I would like to query these fields in an organized list. Let's say I have these three posts: > > City: Los Angeles; State: California; Address: 123 Main St.; Phone: > 888-111-2222 > > > City: San Jose; State: California; Address: 55 1st St.; Phone: > 888-333-4444 > > > City: Brooklyn; State: New York; Address: 9 25th St.; Phone: > 888-555-4848 > > > Should display like this: > > * California > + Los Angeles > - 123 Main St. > - 888-111-2222 > + San Jose > - 55 1st St. > - 888-333-4444 > * New York > + Brooklyn > - 9 25th St. > - 888-555-4848 > > > So far, I am using this code to grab the states in a list and it is working: ``` <ul> <?php global $wpdb; $query = "SELECT meta_value, COUNT(post_id) as count FROM $wpdb->postmeta WHERE meta_key = 'state' GROUP BY meta_value ORDER BY meta_value;"; $states = $wpdb->get_results( $query ); foreach( $states as $state ) : echo'<li>'; echo $state->meta_value; echo '</li>'; endforeach; ?> </ul> ``` But this is of course only displaying: > > * California > * New York > > > What I'm trying to figure out is how to query the rest of the data I'm looking for. Thanks in advance!
I ended up solving my issue using this guide: <http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/>
244,323
<p>Before asking let me tell two things...<br> 1)I know this is very east to someone, but it is hard to me.<br> 2)I am facing this problem to create a WordPress template.That's why I have posted here.<br> Problem: When I print_r the following codes then </p> <pre><code>&lt;?php $home_starting_player_names = rwmb_meta( 'pb_home_starting_player_options', array( 'multiple' =&gt; true ) ); ?&gt; &lt;?php foreach ( $home_starting_player_names as $home_starting_player ){?&gt; &lt;li role="presentation"&gt; &lt;aside class="starting-player-image"&gt;&lt;?php echo get_the_post_thumbnail($home_starting_player); ?&gt;&lt;/aside&gt; &lt;aside class="starting-player-name"&gt;&lt;?php echo get_the_title($home_starting_player); ?&gt;&lt;/aside&gt; &lt;aside class="starting-player-number"&gt;&lt;?php $var_dumps = get_post_meta($home_starting_player); print_r ($var_dumps); ?&gt;&lt;/aside&gt; &lt;?php } ?&gt; </code></pre> <p>it outputs as follows (I have written only one here):</p> <pre><code>Array ( [_edit_last] =&gt; Array ( [0] =&gt; 1 ) [_edit_lock] =&gt; Array ( [0] =&gt; 1477596212:1 ) [pb_squad_number] =&gt; Array ( [0] =&gt; 10 ) [pb_player_date_birth] =&gt; Array ( [0] =&gt; 2016-09-02 ) ) </code></pre> <p>Now I want to show the value of this key <code>[pb_squad_number]</code>.I mean 10. Please help me through codes.</p>
[ { "answer_id": 244325, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>A little example, based on get_posts and get_post_meta.</p>\n<pre><code>$locations = get_posts(\n array('post_type' =&gt; 'locations',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n );\necho '&lt;ul&gt;';\nforeach ($locations as $location) {\n $location_city = get_post_meta($location-&gt;ID, 'city', true);\n $location_state = get_post_meta($location-&gt;ID, 'state', true);\n $location_address = get_post_meta($location-&gt;ID, 'address', true);\n\n echo '&lt;li&gt;' . $location_city;\n echo '&lt;li&gt;' . $location_state . '&lt;/li&gt;';\n echo '&lt;li&gt;' . $location_address . '&lt;/li&gt;';\n echo '&lt;/li&gt;';\n}\necho '&lt;/ul&gt;';\n</code></pre>\n<p>You'll need to adapt $args array in the get_posts to order by special value. With this way you loop through posts and retrieve their custom fields with get_post_meta.</p>\n<p>Edit:\nYou can add a meta_query array in the arguments for the query, to get or order.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Custom field in WP_Query</a></p>\n<p>Hope it helps.</p>\n" }, { "answer_id": 244352, "author": "Alvin", "author_id": 105873, "author_profile": "https://wordpress.stackexchange.com/users/105873", "pm_score": 1, "selected": true, "text": "<p>I ended up solving my issue using this guide: <a href=\"http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/\" rel=\"nofollow\">http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/</a></p>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83330/" ]
Before asking let me tell two things... 1)I know this is very east to someone, but it is hard to me. 2)I am facing this problem to create a WordPress template.That's why I have posted here. Problem: When I print\_r the following codes then ``` <?php $home_starting_player_names = rwmb_meta( 'pb_home_starting_player_options', array( 'multiple' => true ) ); ?> <?php foreach ( $home_starting_player_names as $home_starting_player ){?> <li role="presentation"> <aside class="starting-player-image"><?php echo get_the_post_thumbnail($home_starting_player); ?></aside> <aside class="starting-player-name"><?php echo get_the_title($home_starting_player); ?></aside> <aside class="starting-player-number"><?php $var_dumps = get_post_meta($home_starting_player); print_r ($var_dumps); ?></aside> <?php } ?> ``` it outputs as follows (I have written only one here): ``` Array ( [_edit_last] => Array ( [0] => 1 ) [_edit_lock] => Array ( [0] => 1477596212:1 ) [pb_squad_number] => Array ( [0] => 10 ) [pb_player_date_birth] => Array ( [0] => 2016-09-02 ) ) ``` Now I want to show the value of this key `[pb_squad_number]`.I mean 10. Please help me through codes.
I ended up solving my issue using this guide: <http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/>
244,328
<p>In my Admin Panel, I am constantly checking my Posts by state and visitor count via the All Posts link on the lefthand menu bar. My desired URL looks like:</p> <pre><code>wp-admin/edit.php?post_status=publish&amp;post_type=post&amp;orderby=post_views&amp;order=desc </code></pre> <p>But the default for this link is just</p> <pre><code>wp-admin/edit.php </code></pre> <p>How can I make it so that the default link for my Posts is like the first one?</p>
[ { "answer_id": 244325, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>A little example, based on get_posts and get_post_meta.</p>\n<pre><code>$locations = get_posts(\n array('post_type' =&gt; 'locations',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n );\necho '&lt;ul&gt;';\nforeach ($locations as $location) {\n $location_city = get_post_meta($location-&gt;ID, 'city', true);\n $location_state = get_post_meta($location-&gt;ID, 'state', true);\n $location_address = get_post_meta($location-&gt;ID, 'address', true);\n\n echo '&lt;li&gt;' . $location_city;\n echo '&lt;li&gt;' . $location_state . '&lt;/li&gt;';\n echo '&lt;li&gt;' . $location_address . '&lt;/li&gt;';\n echo '&lt;/li&gt;';\n}\necho '&lt;/ul&gt;';\n</code></pre>\n<p>You'll need to adapt $args array in the get_posts to order by special value. With this way you loop through posts and retrieve their custom fields with get_post_meta.</p>\n<p>Edit:\nYou can add a meta_query array in the arguments for the query, to get or order.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Custom field in WP_Query</a></p>\n<p>Hope it helps.</p>\n" }, { "answer_id": 244352, "author": "Alvin", "author_id": 105873, "author_profile": "https://wordpress.stackexchange.com/users/105873", "pm_score": 1, "selected": true, "text": "<p>I ended up solving my issue using this guide: <a href=\"http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/\" rel=\"nofollow\">http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/</a></p>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244328", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62976/" ]
In my Admin Panel, I am constantly checking my Posts by state and visitor count via the All Posts link on the lefthand menu bar. My desired URL looks like: ``` wp-admin/edit.php?post_status=publish&post_type=post&orderby=post_views&order=desc ``` But the default for this link is just ``` wp-admin/edit.php ``` How can I make it so that the default link for my Posts is like the first one?
I ended up solving my issue using this guide: <http://www.tomoro.com.au/blog/sort-and-group-posts-by-custom-field-with-unique-headings-in-wordpress/>
244,344
<p>Hi have a setting screen where I allow users to create HTML emails with the convenience of the editor they are already used to from posts and pages using wp_editor();</p> <p>Everything seems to work fine except when I try to save with texts which are in quotes when the value returns it has the escaping, I know that's because wp_kses_post(); sanitizes the data but what if user wants to create an HTML email with quotes in it?</p> <p>I know I could do a str_replace, but is there another way? Should I even be using wp_kses_post(); if I plan to allow quotes?</p> <p><strong>wp_editor code:</strong></p> <pre><code>wp_nonce_field('tld_wcdpue_settings_nonce_action', 'tld_wcdpue_settings_nonce_field'); $tld_wcdpue_settings_email_content = get_option('tld_wcdpue_settings_email_content'); wp_editor( $tld_wcdpue_settings_email_content, 'tld_wcdpue_settings_wpeditor', array( 'wpautop' =&gt; false ) ); </code></pre> <p><strong>wp_editor saving code:</strong></p> <pre><code>if( isset(//does authentication here) ){ update_option( 'tld_wcdpue_settings_email_content', wp_kses_post( $_POST['tld_wcdpue_settings_wpeditor'] ) ); } </code></pre> <p>When this gets saved to the DB it gets escaped so the return is: </p> <p><a href="https://i.stack.imgur.com/uDy4O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uDy4O.png" alt="enter image description here"></a></p> <p>I know I could simply do a str_replace but wouldn't that be defeating the purpose of wp_kses_post? Should I even be using it in this case? I also realize I am not escaping when pulling the data from the db, not sure how I should since I want HTML to render in the editor</p>
[ { "answer_id": 244347, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 0, "selected": false, "text": "<p>I don't believe you need to use <code>wp_kses_post()</code>. </p>\n\n<p><code>update_option()</code> runs <code>sanitize_option()</code> which should take care of everything for you.</p>\n\n<p>Test it and let me know what happens.</p>\n" }, { "answer_id": 244359, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>Wordpress always escapes quotes encountered in the super globals variables. It is \ndone in <a href=\"https://developer.wordpress.org/reference/functions/wp_magic_quotes/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_magic_quotes/</a></p>\n\n<p>You will most likely want to strip it with <code>stripslashes</code> before saving it into the DB. something like</p>\n\n<p><code>update_option( 'tld_wcdpue_settings_email_content', wp_kses_post( stripslashes($_POST['tld_wcdpue_settings_wpeditor'] ) ));</code></p>\n" } ]
2016/10/28
[ "https://wordpress.stackexchange.com/questions/244344", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76433/" ]
Hi have a setting screen where I allow users to create HTML emails with the convenience of the editor they are already used to from posts and pages using wp\_editor(); Everything seems to work fine except when I try to save with texts which are in quotes when the value returns it has the escaping, I know that's because wp\_kses\_post(); sanitizes the data but what if user wants to create an HTML email with quotes in it? I know I could do a str\_replace, but is there another way? Should I even be using wp\_kses\_post(); if I plan to allow quotes? **wp\_editor code:** ``` wp_nonce_field('tld_wcdpue_settings_nonce_action', 'tld_wcdpue_settings_nonce_field'); $tld_wcdpue_settings_email_content = get_option('tld_wcdpue_settings_email_content'); wp_editor( $tld_wcdpue_settings_email_content, 'tld_wcdpue_settings_wpeditor', array( 'wpautop' => false ) ); ``` **wp\_editor saving code:** ``` if( isset(//does authentication here) ){ update_option( 'tld_wcdpue_settings_email_content', wp_kses_post( $_POST['tld_wcdpue_settings_wpeditor'] ) ); } ``` When this gets saved to the DB it gets escaped so the return is: [![enter image description here](https://i.stack.imgur.com/uDy4O.png)](https://i.stack.imgur.com/uDy4O.png) I know I could simply do a str\_replace but wouldn't that be defeating the purpose of wp\_kses\_post? Should I even be using it in this case? I also realize I am not escaping when pulling the data from the db, not sure how I should since I want HTML to render in the editor
Wordpress always escapes quotes encountered in the super globals variables. It is done in <https://developer.wordpress.org/reference/functions/wp_magic_quotes/> You will most likely want to strip it with `stripslashes` before saving it into the DB. something like `update_option( 'tld_wcdpue_settings_email_content', wp_kses_post( stripslashes($_POST['tld_wcdpue_settings_wpeditor'] ) ));`
244,351
<p>does anybody know, how to disable the author page only for subscribers ?</p> <p>So it should be only disabled for the user role "subscriber"</p>
[ { "answer_id": 244364, "author": "RodneyHawk", "author_id": 104505, "author_profile": "https://wordpress.stackexchange.com/users/104505", "pm_score": 0, "selected": false, "text": "<p>I was trying in this way but it doesnt function:</p>\n\n<pre><code>function wpse74924_filter_the_author_posts_link( $link ) {\n // Since $author_id doesn't get passed to this filter,\n // we need to query it ourselves\n $author_id = get_the_author_meta( 'ID' );\n\n if ( user_can( $author_id, 'administrator' ) ) {\n // This is an administrator\n __return_false();\n }\n // Otherwise, return $link unmodified\n return $link;\n}\nadd_filter( 'the_author_posts_link', 'wpse74924_filter_the_author_posts_link' );\n</code></pre>\n" }, { "answer_id": 244370, "author": "Florian", "author_id": 10595, "author_profile": "https://wordpress.stackexchange.com/users/10595", "pm_score": 0, "selected": false, "text": "<p>In author.php you could redirect visitors somewhere else if it's the author page for a subscriber. </p>\n\n<pre><code>$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));\n\nif ( get_user_role($curauth-&gt;ID) === 'subscriber' ):\n wp_redirect( 'http://redirect-here.com', 404 );\n endif;\n</code></pre>\n" }, { "answer_id": 244485, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 2, "selected": true, "text": "<p>Oddly, perhaps, there is no <code>get_user_role</code> function, so not surprising that the earlier answer produced an error. </p>\n\n<p>As per my discussion with Rodney Hawk, I still wonder about the point of this exercise - or what security function this operation serves that wouldn't be better served by other methods - but, if the preferred objective is to redirect everyone from the author profile page if the author is a \"subscriber,\" then you might use something like the following:</p>\n\n<pre><code>//for authors template (author.php or variant)\n$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author')) ;\n\n$author_roles = $curauth-&gt;roles ;\n\nif ( in_array( 'subscriber', $author_roles ) ) {\n //probably would want something a little different, but good enough for example\n wp_redirect( 'http://redirect-here.com', 404 ) ;\n //always follow wp_redirect with exit...\n exit ;\n}\n</code></pre>\n\n<p>Note: The $curauth code used above seems to come directly from the Codex. Given the specifics of this case (only for author.php template, only for subscribers), you might be able to write the first lines more simply as follows:</p>\n\n<pre><code>$author_roles = get_user_by('slug', get_query_var('author_name') )-&gt;roles ;\n</code></pre>\n\n<p>Note 2: Haven't tested the redirection part. </p>\n" } ]
2016/10/29
[ "https://wordpress.stackexchange.com/questions/244351", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104505/" ]
does anybody know, how to disable the author page only for subscribers ? So it should be only disabled for the user role "subscriber"
Oddly, perhaps, there is no `get_user_role` function, so not surprising that the earlier answer produced an error. As per my discussion with Rodney Hawk, I still wonder about the point of this exercise - or what security function this operation serves that wouldn't be better served by other methods - but, if the preferred objective is to redirect everyone from the author profile page if the author is a "subscriber," then you might use something like the following: ``` //for authors template (author.php or variant) $curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author')) ; $author_roles = $curauth->roles ; if ( in_array( 'subscriber', $author_roles ) ) { //probably would want something a little different, but good enough for example wp_redirect( 'http://redirect-here.com', 404 ) ; //always follow wp_redirect with exit... exit ; } ``` Note: The $curauth code used above seems to come directly from the Codex. Given the specifics of this case (only for author.php template, only for subscribers), you might be able to write the first lines more simply as follows: ``` $author_roles = get_user_by('slug', get_query_var('author_name') )->roles ; ``` Note 2: Haven't tested the redirection part.
244,376
<p>I'm trying to incorporate a list of checkbox in my plugin's admin settings page from which users can select a few countries from the list of all countries.</p> <p>So far I've done this:</p> <pre><code>add_action( 'admin_init', 'register_page_options' ); function register_page_options() { // Add Section for option fields add_settings_section( 'aicp_section', __( '....text here....', 'aicp' ), 'display_section', 'aicp_settings' ); // id, title, display cb, page // Add Field for selecting countries for which you wanna ban ads add_settings_field( 'aicp_country_list', __( 'Select the countries', 'aicp' ), 'country_list_field', 'aicp_settings', 'aicp_section' ); // id, title, display cb, page, section // Register Settings register_setting( 'aicp_settings', 'aicp_settings_options', array( $this, 'validate_options' ) ); } // now comes the section for checkbox function country_list_field() { $options = get_option( 'aicp_settings_options' ); ?&gt; &lt;input type="checkbox" name="aicp_settings_options[country_list][]" value="AF"&lt;?php checked( 'AF' == $options['country_list'] ); ?&gt; /&gt; Afganistan &lt;input type="checkbox" name="aicp_settings_options[country_list][]" value="AX"&lt;?php checked( 'AX' == $options['country_list'] ); ?&gt; /&gt; Aland Islands &lt;?php } </code></pre> <p><strong>Please Note:</strong> This is not the entire code, but a short part of it to give you guys the idea about my question.</p> <p>Now as you can see I'm using checkboxes above I want all the selected options to be stored as <code>comma seperated</code>, like AF,AX,IN,US etc. so that when I need to work with those data, I can just simply <code>explode</code> them and use.</p> <p>Anyways after a bit digging I found this answer: <a href="https://wordpress.stackexchange.com/questions/4991/how-to-use-checkbox-and-radio-button-in-options-page">How to use checkbox and radio button in options page?</a> which has showed how to handel checkbox &amp; radio box in the settings api.</p> <p>But the problem is that as I'm using the checkbox for a country list, I can't just simply used the <code>checked()</code> to see which of the checkbox are selected as there are a ton of country name and the user can select any one of them or all of them or some of them.</p> <p>Also when I checked this link: <a href="https://stackoverflow.com/questions/6881039/how-to-handle-multiple-checkboxes-in-a-php-form">https://stackoverflow.com/questions/6881039/how-to-handle-multiple-checkboxes-in-a-php-form</a> it showed me to use <code>[]</code> with the name for the <code>checkbox</code> so that they can be stored as array.</p> <p>Now as I'm using the WP Settings API I'm already using naming like <code>aicp_settings_options[country_list]</code> which itself is an array. So, should I have to create a 2 dimentional array like this: <code>aicp_settings_options[country_list][]</code> ?</p> <p>I'm really confused about how should I grab the data and store them. Also how can I easily check which of the checkboxes are selected by the user.</p> <p>It would be great if anyone can help. Thank you in advance.</p>
[ { "answer_id": 257188, "author": "Web Developer", "author_id": 113768, "author_profile": "https://wordpress.stackexchange.com/users/113768", "pm_score": 2, "selected": false, "text": "<pre><code>add_action( 'admin_init', 'register_page_options' );\n\nfunction register_page_options() {\n if (false == get_option('aicp_settings_options')) {\n add_option('aicp_settings_options');\n }\n\n // Add Section for option fields\n add_settings_section( 'aicp_section', __( '....text here....', 'aicp' ), 'display_section', 'aicp_settings' ); // id, title, display cb, page\n\n // Add Field for selecting countries for which you wanna ban ads\n add_settings_field( 'aicp_country_list', __( 'Select the countries', 'aicp' ), 'country_list_field', 'aicp_settings', 'aicp_section' ); // id, title, display cb, page, section\n\n // Register Settings\n register_setting( 'aicp_settings', 'aicp_settings_options', array( $this, 'validate_options' ) );\n}\n\n// now comes the section for checkbox\n\nfunction country_list_field() {\n $options = get_option( 'aicp_settings_options' );\n\n $value = array();\n if (isset($options['country_list']) &amp;&amp; ! empty($options['country_list'])) {\n $value = $options['country_list'];\n }\n\n $html = '&lt;input type=\"checkbox\" name=\"aicp_settings_options[country_list][]\" value=\"AF\"'. in_array('AF', $value) ? 'checked' : '' .'/&gt; Afganistan';\n $html .= '&lt;input type=\"checkbox\" name=\"aicp_settings_options[country_list][]\" value=\"AX\"'. in_array('AX', $value) ? 'checked' : '' .'/&gt; Aland Islands';\n\n echo $html;\n}\n</code></pre>\n" }, { "answer_id": 264758, "author": "Nitesh", "author_id": 6920, "author_profile": "https://wordpress.stackexchange.com/users/6920", "pm_score": 1, "selected": false, "text": "<p>Instead of Using <code>checked()</code> you can make use of <code>in_array()</code> as mentioned below - </p>\n\n<pre><code>&lt;input type=\"checkbox\" name=\"aicp_settings_options[country_list][]\" value=\"AF\"&lt;?php echo in_array('AF', $options['country_list']) ? 'checked' : ''; ?&gt; /&gt; Afganistan\n</code></pre>\n\n<p>I hope this helps.</p>\n" } ]
2016/10/29
[ "https://wordpress.stackexchange.com/questions/244376", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50584/" ]
I'm trying to incorporate a list of checkbox in my plugin's admin settings page from which users can select a few countries from the list of all countries. So far I've done this: ``` add_action( 'admin_init', 'register_page_options' ); function register_page_options() { // Add Section for option fields add_settings_section( 'aicp_section', __( '....text here....', 'aicp' ), 'display_section', 'aicp_settings' ); // id, title, display cb, page // Add Field for selecting countries for which you wanna ban ads add_settings_field( 'aicp_country_list', __( 'Select the countries', 'aicp' ), 'country_list_field', 'aicp_settings', 'aicp_section' ); // id, title, display cb, page, section // Register Settings register_setting( 'aicp_settings', 'aicp_settings_options', array( $this, 'validate_options' ) ); } // now comes the section for checkbox function country_list_field() { $options = get_option( 'aicp_settings_options' ); ?> <input type="checkbox" name="aicp_settings_options[country_list][]" value="AF"<?php checked( 'AF' == $options['country_list'] ); ?> /> Afganistan <input type="checkbox" name="aicp_settings_options[country_list][]" value="AX"<?php checked( 'AX' == $options['country_list'] ); ?> /> Aland Islands <?php } ``` **Please Note:** This is not the entire code, but a short part of it to give you guys the idea about my question. Now as you can see I'm using checkboxes above I want all the selected options to be stored as `comma seperated`, like AF,AX,IN,US etc. so that when I need to work with those data, I can just simply `explode` them and use. Anyways after a bit digging I found this answer: [How to use checkbox and radio button in options page?](https://wordpress.stackexchange.com/questions/4991/how-to-use-checkbox-and-radio-button-in-options-page) which has showed how to handel checkbox & radio box in the settings api. But the problem is that as I'm using the checkbox for a country list, I can't just simply used the `checked()` to see which of the checkbox are selected as there are a ton of country name and the user can select any one of them or all of them or some of them. Also when I checked this link: <https://stackoverflow.com/questions/6881039/how-to-handle-multiple-checkboxes-in-a-php-form> it showed me to use `[]` with the name for the `checkbox` so that they can be stored as array. Now as I'm using the WP Settings API I'm already using naming like `aicp_settings_options[country_list]` which itself is an array. So, should I have to create a 2 dimentional array like this: `aicp_settings_options[country_list][]` ? I'm really confused about how should I grab the data and store them. Also how can I easily check which of the checkboxes are selected by the user. It would be great if anyone can help. Thank you in advance.
``` add_action( 'admin_init', 'register_page_options' ); function register_page_options() { if (false == get_option('aicp_settings_options')) { add_option('aicp_settings_options'); } // Add Section for option fields add_settings_section( 'aicp_section', __( '....text here....', 'aicp' ), 'display_section', 'aicp_settings' ); // id, title, display cb, page // Add Field for selecting countries for which you wanna ban ads add_settings_field( 'aicp_country_list', __( 'Select the countries', 'aicp' ), 'country_list_field', 'aicp_settings', 'aicp_section' ); // id, title, display cb, page, section // Register Settings register_setting( 'aicp_settings', 'aicp_settings_options', array( $this, 'validate_options' ) ); } // now comes the section for checkbox function country_list_field() { $options = get_option( 'aicp_settings_options' ); $value = array(); if (isset($options['country_list']) && ! empty($options['country_list'])) { $value = $options['country_list']; } $html = '<input type="checkbox" name="aicp_settings_options[country_list][]" value="AF"'. in_array('AF', $value) ? 'checked' : '' .'/> Afganistan'; $html .= '<input type="checkbox" name="aicp_settings_options[country_list][]" value="AX"'. in_array('AX', $value) ? 'checked' : '' .'/> Aland Islands'; echo $html; } ```
244,382
<h1>Restrict Website, But Login and Register Page</h1> <hr> <h3>I want my my entire WordPress site to be restricted to visitors, but I want the register and login page to be accessible (not restricted) to the visitors</h3> <p><br> Since my website is a members-only website, I want to restrict it's access so that visitors only see 2 pages, the login page and the register page.</p> <p>I have tried multiple plugins to do exactly that but unfortunately for me, I haven't been able to find the right one. Some plugins redirect the entire website to one page while other plugins require custom redirection settings for each page to be separately added.</p> <p><strong><em>What I want:-</em></strong></p> <ol> <li><strong>Restrict entire WordPress website to visitors by redirection.</strong></li> <li><strong>Do not restrict 2 pages, Login Page and Registration Page.</strong></li> <li><strong>Redirect Users to Login Page and/or Register Page.</strong></li> </ol> <p>There is an option in my Login Page to view the Register Page.<br> I want both of these pages to be accessible to the visitor and the rest of the website to be inaccessible.</p>
[ { "answer_id": 244386, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>Below code will work with WordPress default login/register screens:</p>\n\n<pre><code>add_action( 'wp', 'member_only_site' );\nfunction member_only_site( ) {\n if ( ! is_user_logged_in( ) ) {\n auth_redirect();\n }\n}\n</code></pre>\n" }, { "answer_id": 244391, "author": "BlackOut", "author_id": 99005, "author_profile": "https://wordpress.stackexchange.com/users/99005", "pm_score": 0, "selected": false, "text": "<p>A possible alternative:</p>\n\n<pre><code>global $pagenow;\n\n$accessible_pages = array('wp-login.php', 'wp-login.php?action=register');\n\nif ( !is_user_logged_in() &amp;&amp; !in_array($pagenow, $accessible_pages) &amp;&amp; !is_admin() ) {\n auth_redirect();\n}\n</code></pre>\n\n<p>You can insert in the array \"accessible_pages\" the pages (separated by commas) that you want to be public-accessible to visitors, avoiding redirects to the login page every time that a page is loaded. </p>\n" }, { "answer_id": 244442, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 0, "selected": false, "text": "<p>try this code </p>\n\n<pre><code>function redi() {\nglobal $pagenow;\nif (!is_user_logged_in() &amp;&amp; $pagenow != 'wp-login.php' &amp;&amp; $pagenow !='wp-login.php?action=register') {\nwp_redirect('wp-login.php?action=register');\n}} add_action('template_redirect', 'redi');\n</code></pre>\n" } ]
2016/10/29
[ "https://wordpress.stackexchange.com/questions/244382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105575/" ]
Restrict Website, But Login and Register Page ============================================= --- ### I want my my entire WordPress site to be restricted to visitors, but I want the register and login page to be accessible (not restricted) to the visitors Since my website is a members-only website, I want to restrict it's access so that visitors only see 2 pages, the login page and the register page. I have tried multiple plugins to do exactly that but unfortunately for me, I haven't been able to find the right one. Some plugins redirect the entire website to one page while other plugins require custom redirection settings for each page to be separately added. ***What I want:-*** 1. **Restrict entire WordPress website to visitors by redirection.** 2. **Do not restrict 2 pages, Login Page and Registration Page.** 3. **Redirect Users to Login Page and/or Register Page.** There is an option in my Login Page to view the Register Page. I want both of these pages to be accessible to the visitor and the rest of the website to be inaccessible.
Below code will work with WordPress default login/register screens: ``` add_action( 'wp', 'member_only_site' ); function member_only_site( ) { if ( ! is_user_logged_in( ) ) { auth_redirect(); } } ```
244,394
<p>I have about 2300+ post in my blog is it possible to change status from publish to draft at a time? </p> <pre><code>add_action('publish_post', 'check_publish_post', 10, 2); function check_publish_post ($post_id, $post) { $query = array( 'ID' =&gt; $post_id, 'post_status' =&gt; 'draft', ); wp_update_post( $query, true ); } </code></pre>
[ { "answer_id": 244396, "author": "Nabil Kadimi", "author_id": 17187, "author_profile": "https://wordpress.stackexchange.com/users/17187", "pm_score": 1, "selected": false, "text": "<p>Hers is you code with explanatory comments:</p>\n\n<pre><code>&lt;?php\n\n/**\n * Unpublish all posts (set post_status to draft).\n *\n * This code is run only once in a lifetime. \n */\nadd_action( 'init', 'wpse_244394' );\nfunction wpse_244394(){\n\n /**\n * Make sure this code is run ever once.\n */\n if ( get_option( 'wpse_244394' ) ) {\n return;\n }\n update_option( 'wpse_244394', 1 );\n\n\n /**\n * Get pubkushed posts.\n */\n $posts = get_posts( [\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; 'post',\n 'numberposts' =&gt; -1,\n ] );\n\n /**\n * Unpublish.\n */\n foreach ( $posts as $post ) {\n $post['post_status'] = 'draft';\n wp_update_post( $post );\n }\n}\n</code></pre>\n" }, { "answer_id": 244397, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>Yes, it's possible to loop all publish posts and change their post status to draft.</p>\n\n<pre><code>add_action('admin_init','wpse_244394');\n\nfunction wpse_244394(){\n $args = array('post_type'=&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page'=&gt;-1\n );\n $published_posts = get_posts($args);\n\n foreach($published_posts as $post_to_draft){\n $query = array(\n 'ID' =&gt; $post_to_draft-&gt;ID,\n 'post_status' =&gt; 'draft',\n );\n wp_update_post( $query, true ); \n }\n}\n</code></pre>\n" }, { "answer_id": 244398, "author": "Unnikrishnan R", "author_id": 101689, "author_profile": "https://wordpress.stackexchange.com/users/101689", "pm_score": 1, "selected": false, "text": "<p>you can change the all post status directly from database.</p>\n\n<pre><code>UPDATE wp_posts SET post_status = 'draft' WHERE post_status = 'publish';\n</code></pre>\n" }, { "answer_id": 274604, "author": "user1551496", "author_id": 111109, "author_profile": "https://wordpress.stackexchange.com/users/111109", "pm_score": 0, "selected": false, "text": "<p>The solution from @Nabil Kadimi don't work (for me). I got a 500 error.\nHere my updated code.</p>\n\n<p><strong>No guarantee! Be sure to create SQL Backup!</strong></p>\n\n<pre><code>/**\n * Unpublish all posts (set post_status to draft).\n *\n * This code is run only once in a lifetime. \n */\nadd_action( 'init', 'wpse_244394' );\nfunction wpse_244394(){\n\n /**\n * Make sure this code is run ever once.\n */\n if ( get_option( 'wpse_244394' ) ) {\n return;\n }\n update_option( 'wpse_244394', 1 );\n\n\n /**\n * Get published posts.\n */\n\n $args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1\n );\n $posts = get_posts( $args );\n\n\n /**\n * Unpublish.\n */\n foreach ( $posts as $post ) {\n $my_post = array(\n 'ID' =&gt; $post-&gt;ID,\n 'post_status' =&gt; 'draft',\n );\n\n // Update the post into the database\n wp_update_post( $my_post );\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 274622, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p><strong>Here's a way with WP-CLI:</strong></p>\n\n<p>We can list the <em>published</em> posts (ids) with:</p>\n\n<pre><code>wp post list --post_status=publish --post_type=post --format=ids \n</code></pre>\n\n<p>We can update a post with ID as 123 to <em>draft</em> status with:</p>\n\n<pre><code>wp post update 123 --post_status=draft\n</code></pre>\n\n<p>We can combine these two commands, to bulk change all <em>published</em> posts to <em>draft</em>, with:</p>\n\n<pre><code>wp post list --post-status=publish --post_type=post --format=ids \\\n| xargs -d ' ' -I % wp post update % --post_status=draft\n</code></pre>\n\n<p>where we set the <code>xargs</code> <em>delimiter</em> to <code>' '</code> to match the <code>ids</code> format.</p>\n\n<p>Alternatively we can use:</p>\n\n<pre><code>for post_id in $(wp post list --post_status=publish --post_type=post --format=ids); \\ \ndo wp post update $post_id --post_status=draft; done;\n</code></pre>\n\n<p>Note: Remember to backup before testing.</p>\n" } ]
2016/10/29
[ "https://wordpress.stackexchange.com/questions/244394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82233/" ]
I have about 2300+ post in my blog is it possible to change status from publish to draft at a time? ``` add_action('publish_post', 'check_publish_post', 10, 2); function check_publish_post ($post_id, $post) { $query = array( 'ID' => $post_id, 'post_status' => 'draft', ); wp_update_post( $query, true ); } ```
Yes, it's possible to loop all publish posts and change their post status to draft. ``` add_action('admin_init','wpse_244394'); function wpse_244394(){ $args = array('post_type'=> 'post', 'post_status' => 'publish', 'posts_per_page'=>-1 ); $published_posts = get_posts($args); foreach($published_posts as $post_to_draft){ $query = array( 'ID' => $post_to_draft->ID, 'post_status' => 'draft', ); wp_update_post( $query, true ); } } ```
244,403
<p>I want to mass redirect subdirectories/subpages/pages to a single page.</p> <p><strong>from</strong> </p> <pre><code>example.com/definicje example.com/definicje/521/ example.com/definicje/592/a.html etc. </code></pre> <p><strong>to a single page</strong></p> <pre><code>example.com/single-page/ </code></pre> <p>My rewrite rule actually doesn't redirect anything:</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] RewriteRule ^definicje(.*)$ http://example.com/single-page/ [R=301,L] &lt;/IfModule&gt; </code></pre>
[ { "answer_id": 244566, "author": "user105919", "author_id": 105919, "author_profile": "https://wordpress.stackexchange.com/users/105919", "pm_score": 2, "selected": false, "text": "<p>The solution is to put the rewriterule just after RewriteEngine On.</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteRule ^definicje(.*)$ http://example.com/single-page/ [R=301,L]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 301477, "author": "Webmaster TheCMG", "author_id": 142207, "author_profile": "https://wordpress.stackexchange.com/users/142207", "pm_score": 1, "selected": false, "text": "<p>There's a plugin to do redirection for all theses kinds of cases. It's simply called redirection. Search the plugin directory. I use it to redirect directories or certain pages. \n<a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/redirection/</a></p>\n" } ]
2016/10/29
[ "https://wordpress.stackexchange.com/questions/244403", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105919/" ]
I want to mass redirect subdirectories/subpages/pages to a single page. **from** ``` example.com/definicje example.com/definicje/521/ example.com/definicje/592/a.html etc. ``` **to a single page** ``` example.com/single-page/ ``` My rewrite rule actually doesn't redirect anything: ``` # 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] RewriteRule ^definicje(.*)$ http://example.com/single-page/ [R=301,L] </IfModule> ```
The solution is to put the rewriterule just after RewriteEngine On. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^definicje(.*)$ http://example.com/single-page/ [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ```
244,415
<p>Looking to add a data attribute to a <strong>list item</strong> in a menu, I can see that some threads on here can add it to the actual <code>&lt;a&gt;</code> link tag, I am looking to add it to the list item itself <code>&lt;li&gt;</code></p> <p>So this code adds the attribute to the <code>&lt;a&gt;</code>tag</p> <pre><code>add_filter( 'nav_menu_link_attributes', 'themeprefix_menu_attribute_add', 10, 3 ); function themeprefix_menu_attribute_add( $atts, $item, $args ) { // Set the menu ID $menu_link1 = 20; // Conditionally match the ID and add the attribute and value if ($item-&gt;ID == $menu_link1) { $atts['data-content'] = 'about'; //Return the new attribute return $atts; </code></pre> <p>Any ideas how to add the attribute to the <code>&lt;li&gt;</code> without using jQuery.</p>
[ { "answer_id": 244566, "author": "user105919", "author_id": 105919, "author_profile": "https://wordpress.stackexchange.com/users/105919", "pm_score": 2, "selected": false, "text": "<p>The solution is to put the rewriterule just after RewriteEngine On.</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteRule ^definicje(.*)$ http://example.com/single-page/ [R=301,L]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 301477, "author": "Webmaster TheCMG", "author_id": 142207, "author_profile": "https://wordpress.stackexchange.com/users/142207", "pm_score": 1, "selected": false, "text": "<p>There's a plugin to do redirection for all theses kinds of cases. It's simply called redirection. Search the plugin directory. I use it to redirect directories or certain pages. \n<a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/redirection/</a></p>\n" } ]
2016/10/29
[ "https://wordpress.stackexchange.com/questions/244415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70831/" ]
Looking to add a data attribute to a **list item** in a menu, I can see that some threads on here can add it to the actual `<a>` link tag, I am looking to add it to the list item itself `<li>` So this code adds the attribute to the `<a>`tag ``` add_filter( 'nav_menu_link_attributes', 'themeprefix_menu_attribute_add', 10, 3 ); function themeprefix_menu_attribute_add( $atts, $item, $args ) { // Set the menu ID $menu_link1 = 20; // Conditionally match the ID and add the attribute and value if ($item->ID == $menu_link1) { $atts['data-content'] = 'about'; //Return the new attribute return $atts; ``` Any ideas how to add the attribute to the `<li>` without using jQuery.
The solution is to put the rewriterule just after RewriteEngine On. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^definicje(.*)$ http://example.com/single-page/ [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ```
244,418
<p>I know that WordPress can filter shortcodes like <code>the_content</code> but is it possible to filter <code>get_the_content</code>?</p> <p>I have a function that is able to use <code>substr</code> and <code>strpos</code> and I know it works on <code>the_title</code>. I tried the same thing for <code>get_the_title</code> but I couldn't get it to work.</p> <p>Is it possible for the same to work on <code>get_the_title</code>?</p> <p>Code I have so far:</p> <pre><code>function gg_short_title($title) { // This can return false, so check there is something $linkt=array(); $linkt[] = substr($title, 0, strpos($title, ' &amp;#8212;')); $linkt[] = substr($title, 0, strpos($title, ' &amp;#8211;')); $linkt[] = substr($title, 0, strpos($title, ' &amp;#124;')); $linkt[] = substr($title, 0, strpos($title, ' -')); $short_title = implode('', $linkt); if ($short_title) { return $short_title; } // Else just return the normal title return $title; } add_filter('get_the_title', 'gg_short_title', 10, 1); </code></pre> <p>Thanks.</p>
[ { "answer_id": 244421, "author": "moraleida", "author_id": 7890, "author_profile": "https://wordpress.stackexchange.com/users/7890", "pm_score": 3, "selected": true, "text": "<p>The function <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow\"><code>the_title()</code></a> is just a wrapper around the function <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow\"><code>get_the_title()</code></a>. </p>\n\n<p>It's understandably confusing that the filter <code>the_title</code> actually exists inside <code>get_the_title()</code>. So, whatever the function you're using to actually display it, it doesn't matter, you can filter its content by hooking into <code>the_title</code></p>\n" }, { "answer_id": 244422, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 2, "selected": false, "text": "<p>In addition to moraleida's answer, here's a shorter way to match and output your titles.</p>\n\n<p><strong>Note</strong> - It will split the string on the first match it finds so if there are multiple '|' or 'em dash' characters, that could be a problem (even for your original code).</p>\n\n<pre><code>function gg_short_title( $title ) {\n\n if ( 1 === preg_match( '(&amp;#8212;|&amp;#8211;|&amp;#124;|-|\\|)', $title, $matches ) ) {\n $short_title = explode( $matches[0], $title, 2 );\n $title = trim( $short_title[0] );\n }\n\n return $title;\n}\nadd_filter( 'the_title', 'gg_short_title', 10, 1 );\n</code></pre>\n" } ]
2016/10/30
[ "https://wordpress.stackexchange.com/questions/244418", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I know that WordPress can filter shortcodes like `the_content` but is it possible to filter `get_the_content`? I have a function that is able to use `substr` and `strpos` and I know it works on `the_title`. I tried the same thing for `get_the_title` but I couldn't get it to work. Is it possible for the same to work on `get_the_title`? Code I have so far: ``` function gg_short_title($title) { // This can return false, so check there is something $linkt=array(); $linkt[] = substr($title, 0, strpos($title, ' &#8212;')); $linkt[] = substr($title, 0, strpos($title, ' &#8211;')); $linkt[] = substr($title, 0, strpos($title, ' &#124;')); $linkt[] = substr($title, 0, strpos($title, ' -')); $short_title = implode('', $linkt); if ($short_title) { return $short_title; } // Else just return the normal title return $title; } add_filter('get_the_title', 'gg_short_title', 10, 1); ``` Thanks.
The function [`the_title()`](https://developer.wordpress.org/reference/functions/the_title/) is just a wrapper around the function [`get_the_title()`](https://developer.wordpress.org/reference/functions/get_the_title/). It's understandably confusing that the filter `the_title` actually exists inside `get_the_title()`. So, whatever the function you're using to actually display it, it doesn't matter, you can filter its content by hooking into `the_title`
244,431
<p>I wanna do a query in my header.php inside "head" to generate a title. I wanna ask, if the current page is single an do it like it follows:</p> <pre><code>&lt;?php if ( is_single() ) { ?&gt; &lt;title&gt;Test&lt;/title&gt; &lt;?php } ?&gt; </code></pre> <p>But it doesnt function an doesnt give out anything. Do I have to do another quaery over the "head tag" ?</p>
[ { "answer_id": 244421, "author": "moraleida", "author_id": 7890, "author_profile": "https://wordpress.stackexchange.com/users/7890", "pm_score": 3, "selected": true, "text": "<p>The function <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow\"><code>the_title()</code></a> is just a wrapper around the function <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow\"><code>get_the_title()</code></a>. </p>\n\n<p>It's understandably confusing that the filter <code>the_title</code> actually exists inside <code>get_the_title()</code>. So, whatever the function you're using to actually display it, it doesn't matter, you can filter its content by hooking into <code>the_title</code></p>\n" }, { "answer_id": 244422, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 2, "selected": false, "text": "<p>In addition to moraleida's answer, here's a shorter way to match and output your titles.</p>\n\n<p><strong>Note</strong> - It will split the string on the first match it finds so if there are multiple '|' or 'em dash' characters, that could be a problem (even for your original code).</p>\n\n<pre><code>function gg_short_title( $title ) {\n\n if ( 1 === preg_match( '(&amp;#8212;|&amp;#8211;|&amp;#124;|-|\\|)', $title, $matches ) ) {\n $short_title = explode( $matches[0], $title, 2 );\n $title = trim( $short_title[0] );\n }\n\n return $title;\n}\nadd_filter( 'the_title', 'gg_short_title', 10, 1 );\n</code></pre>\n" } ]
2016/10/30
[ "https://wordpress.stackexchange.com/questions/244431", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104505/" ]
I wanna do a query in my header.php inside "head" to generate a title. I wanna ask, if the current page is single an do it like it follows: ``` <?php if ( is_single() ) { ?> <title>Test</title> <?php } ?> ``` But it doesnt function an doesnt give out anything. Do I have to do another quaery over the "head tag" ?
The function [`the_title()`](https://developer.wordpress.org/reference/functions/the_title/) is just a wrapper around the function [`get_the_title()`](https://developer.wordpress.org/reference/functions/get_the_title/). It's understandably confusing that the filter `the_title` actually exists inside `get_the_title()`. So, whatever the function you're using to actually display it, it doesn't matter, you can filter its content by hooking into `the_title`
244,475
<p>I want to be able to loop through my posts, but <strong>for every post to this:</strong></p> <p><strong>1)</strong> check if some custom field is true or false.</p> <p><strong>2)</strong> if is true just display the post's data (<em>the_title, the_content...</em>).</p> <p><strong>3)</strong> if is false display the same structure of data (<em>the_title, the_content...</em>) but with the pervious revision of this post.</p> <p>Is it possible? and how?</p>
[ { "answer_id": 244480, "author": "Piotr Kliks", "author_id": 33598, "author_profile": "https://wordpress.stackexchange.com/users/33598", "pm_score": 1, "selected": false, "text": "<p>Yes it's possible. You can access to post's revisions using <code>wp_get_post_revisions($post_id)</code> function. It returns array of post's revision, first element of an array is the same as current version of post so you should take second's element values.</p>\n" }, { "answer_id": 244502, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<h2>First we look into the <code>wp_get_post_autosave</code> function</h2>\n\n<p>It's informative to see how the core function <code>wp_get_post_autosave()</code> uses \nthe <code>wp_get_post_revisions()</code> function.</p>\n\n<p>It loops over all revisions from </p>\n\n<pre><code>$revisions = wp_get_post_revisions( \n $post_id, \n array( \n 'check_enabled' =&gt; false \n ) \n);\n</code></pre>\n\n<p>and then uses:</p>\n\n<pre><code>foreach ( $revisions as $revision ) {\n if ( false !== strpos( $revision-&gt;post_name, \"{$post_id}-autosave\" ) ) {\n if ( $user_id &amp;&amp; $user_id != $revision-&gt;post_author )\n continue;\n\n return $revision;\n }\n}\n</code></pre>\n\n<p>to return the first revision with a slug containing <code>\"{$post_id}-autosave\"</code> and where the <code>$user_id</code> possibly matches it's author.</p>\n\n<p><strong>Alternative</strong></p>\n\n<p>Now <code>wp_get_post_revisions()</code> is a wrapper for <code>get_children()</code>, so I wonder why it has to fetch all the revisions for the given post, before filtering out a single one. Why not try to fetch it directly, only what's needed? When we try e.g. the following (PHP 5.4+):</p>\n\n<pre><code>$revisions = wp_get_post_revisions(\n $post_id,\n [\n 'offset' =&gt; 1, // Start from the previous change (ofset changed to offset)\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'name' =&gt; \"{$post_id}-autosave-v1\",\n 'check_enabled' =&gt; false,\n ]\n);\n</code></pre>\n\n<p>then the <code>posts_per_page</code> will not have any effect. After playing around with this I managed to get the following to work with the <code>posts_per_page</code> argument:</p>\n\n<pre><code>$revisions = wp_get_post_revisions(\n $post_id,\n [\n 'offset' =&gt; 1, // Start from the previous change\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'post_name__in' =&gt; [ \"{$post_id}-autosave-v1\" ],\n 'check_enabled' =&gt; false,\n ]\n);\n</code></pre>\n\n<h2>Get only the previous revision</h2>\n\n<p>Now we can adjust the above to only fetch the previous revision, i.e. that's not an <em>auto-save</em>:</p>\n\n<pre><code>$revisions = wp_get_post_revisions(\n $post_id,\n [\n 'offset' =&gt; 1, // Start from the previous change\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'post_name__in' =&gt; [ \"{$post_id}-revision-v1\" ],\n 'check_enabled' =&gt; false,\n ]\n);\n</code></pre>\n\n<p>Here we target the <code>{$post_id}-revision-v1</code> slug.</p>\n\n<p>Note the here we use the <code>v1</code>, but we could adjust that if needed later on.</p>\n\n<h2>Example</h2>\n\n<p>So to finally answer your question, here's a suggestion:</p>\n\n<pre><code>$show = get_post_meta( get_the_ID(), 'somekey', true );\n\nif( $show )\n{\n // Template part\n get_template_part( 'template-parts/content' );\n}\nelse\n{\n // Fetch the previous revision only\n $revisions = wp_get_post_revisions(\n get_the_ID(),\n [\n 'offset' =&gt; 1, // Start from the previous change\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'post_name__in' =&gt; [ sprintf( \"%d-revision-v1\", get_the_ID() ) ],\n 'check_enabled' =&gt; false,\n ]\n );\n\n if( $revisions )\n {\n $post = reset( $revisions );\n setup_postdata( $post );\n\n // Template part\n get_template_part( 'template-parts/content' );\n\n wp_reset_postdata();\n }\n else\n {\n // Some fallback here\n }\n}\n</code></pre>\n\n<p>Hopefully you can adjust it further to your needs!</p>\n" } ]
2016/10/30
[ "https://wordpress.stackexchange.com/questions/244475", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43619/" ]
I want to be able to loop through my posts, but **for every post to this:** **1)** check if some custom field is true or false. **2)** if is true just display the post's data (*the\_title, the\_content...*). **3)** if is false display the same structure of data (*the\_title, the\_content...*) but with the pervious revision of this post. Is it possible? and how?
First we look into the `wp_get_post_autosave` function ------------------------------------------------------ It's informative to see how the core function `wp_get_post_autosave()` uses the `wp_get_post_revisions()` function. It loops over all revisions from ``` $revisions = wp_get_post_revisions( $post_id, array( 'check_enabled' => false ) ); ``` and then uses: ``` foreach ( $revisions as $revision ) { if ( false !== strpos( $revision->post_name, "{$post_id}-autosave" ) ) { if ( $user_id && $user_id != $revision->post_author ) continue; return $revision; } } ``` to return the first revision with a slug containing `"{$post_id}-autosave"` and where the `$user_id` possibly matches it's author. **Alternative** Now `wp_get_post_revisions()` is a wrapper for `get_children()`, so I wonder why it has to fetch all the revisions for the given post, before filtering out a single one. Why not try to fetch it directly, only what's needed? When we try e.g. the following (PHP 5.4+): ``` $revisions = wp_get_post_revisions( $post_id, [ 'offset' => 1, // Start from the previous change (ofset changed to offset) 'posts_per_page' => 1, // Only a single revision 'name' => "{$post_id}-autosave-v1", 'check_enabled' => false, ] ); ``` then the `posts_per_page` will not have any effect. After playing around with this I managed to get the following to work with the `posts_per_page` argument: ``` $revisions = wp_get_post_revisions( $post_id, [ 'offset' => 1, // Start from the previous change 'posts_per_page' => 1, // Only a single revision 'post_name__in' => [ "{$post_id}-autosave-v1" ], 'check_enabled' => false, ] ); ``` Get only the previous revision ------------------------------ Now we can adjust the above to only fetch the previous revision, i.e. that's not an *auto-save*: ``` $revisions = wp_get_post_revisions( $post_id, [ 'offset' => 1, // Start from the previous change 'posts_per_page' => 1, // Only a single revision 'post_name__in' => [ "{$post_id}-revision-v1" ], 'check_enabled' => false, ] ); ``` Here we target the `{$post_id}-revision-v1` slug. Note the here we use the `v1`, but we could adjust that if needed later on. Example ------- So to finally answer your question, here's a suggestion: ``` $show = get_post_meta( get_the_ID(), 'somekey', true ); if( $show ) { // Template part get_template_part( 'template-parts/content' ); } else { // Fetch the previous revision only $revisions = wp_get_post_revisions( get_the_ID(), [ 'offset' => 1, // Start from the previous change 'posts_per_page' => 1, // Only a single revision 'post_name__in' => [ sprintf( "%d-revision-v1", get_the_ID() ) ], 'check_enabled' => false, ] ); if( $revisions ) { $post = reset( $revisions ); setup_postdata( $post ); // Template part get_template_part( 'template-parts/content' ); wp_reset_postdata(); } else { // Some fallback here } } ``` Hopefully you can adjust it further to your needs!
244,492
<p>the following function I was producing together with some users here and it is function perfectly.</p> <pre><code> add_filter('wpseo_set_title', 'wpseo_set_title_callback'); $meinungen = "Meinungen zu: "; function wpseo_set_title_callback($input) { $page_comment = get_query_var('cpage'); if (is_single() &amp;&amp; $page_comment &gt; 0) { global $meinungen; return ''. $meinungen . ''. $input . ''; } else { return ''. $input . ''; } } </code></pre> <p>Now I wanna extend this function in this point, that I wanna say if "$page_comment" more than 3 "$meinungen" is "Kontroverse Diskussionen zu". In all other cases "$meinungen" stays on "Meinungen zu",</p> <p>I tryed like it follows, but it doesnt function...I think the reason could be, that the query of comes later, but I dont know, how to get this in a point. Perhaps somebody could help me ?</p> <pre><code> add_filter('wpseo_set_title', 'wpseo_set_title_callback'); if $page_comment &gt; 3) { $meinungen = "Kontroverse Diskussionen zu: "; } else { $meinungen = "Meinungen zu: "; } function wpseo_set_title_callback($input) { $page_comment = get_query_var('cpage'); if (is_single() &amp;&amp; $page_comment &gt; 0) { global $meinungen; return ''. $meinungen . ''. $input . ''; } else { return ''. $input . ''; } } </code></pre>
[ { "answer_id": 244480, "author": "Piotr Kliks", "author_id": 33598, "author_profile": "https://wordpress.stackexchange.com/users/33598", "pm_score": 1, "selected": false, "text": "<p>Yes it's possible. You can access to post's revisions using <code>wp_get_post_revisions($post_id)</code> function. It returns array of post's revision, first element of an array is the same as current version of post so you should take second's element values.</p>\n" }, { "answer_id": 244502, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<h2>First we look into the <code>wp_get_post_autosave</code> function</h2>\n\n<p>It's informative to see how the core function <code>wp_get_post_autosave()</code> uses \nthe <code>wp_get_post_revisions()</code> function.</p>\n\n<p>It loops over all revisions from </p>\n\n<pre><code>$revisions = wp_get_post_revisions( \n $post_id, \n array( \n 'check_enabled' =&gt; false \n ) \n);\n</code></pre>\n\n<p>and then uses:</p>\n\n<pre><code>foreach ( $revisions as $revision ) {\n if ( false !== strpos( $revision-&gt;post_name, \"{$post_id}-autosave\" ) ) {\n if ( $user_id &amp;&amp; $user_id != $revision-&gt;post_author )\n continue;\n\n return $revision;\n }\n}\n</code></pre>\n\n<p>to return the first revision with a slug containing <code>\"{$post_id}-autosave\"</code> and where the <code>$user_id</code> possibly matches it's author.</p>\n\n<p><strong>Alternative</strong></p>\n\n<p>Now <code>wp_get_post_revisions()</code> is a wrapper for <code>get_children()</code>, so I wonder why it has to fetch all the revisions for the given post, before filtering out a single one. Why not try to fetch it directly, only what's needed? When we try e.g. the following (PHP 5.4+):</p>\n\n<pre><code>$revisions = wp_get_post_revisions(\n $post_id,\n [\n 'offset' =&gt; 1, // Start from the previous change (ofset changed to offset)\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'name' =&gt; \"{$post_id}-autosave-v1\",\n 'check_enabled' =&gt; false,\n ]\n);\n</code></pre>\n\n<p>then the <code>posts_per_page</code> will not have any effect. After playing around with this I managed to get the following to work with the <code>posts_per_page</code> argument:</p>\n\n<pre><code>$revisions = wp_get_post_revisions(\n $post_id,\n [\n 'offset' =&gt; 1, // Start from the previous change\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'post_name__in' =&gt; [ \"{$post_id}-autosave-v1\" ],\n 'check_enabled' =&gt; false,\n ]\n);\n</code></pre>\n\n<h2>Get only the previous revision</h2>\n\n<p>Now we can adjust the above to only fetch the previous revision, i.e. that's not an <em>auto-save</em>:</p>\n\n<pre><code>$revisions = wp_get_post_revisions(\n $post_id,\n [\n 'offset' =&gt; 1, // Start from the previous change\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'post_name__in' =&gt; [ \"{$post_id}-revision-v1\" ],\n 'check_enabled' =&gt; false,\n ]\n);\n</code></pre>\n\n<p>Here we target the <code>{$post_id}-revision-v1</code> slug.</p>\n\n<p>Note the here we use the <code>v1</code>, but we could adjust that if needed later on.</p>\n\n<h2>Example</h2>\n\n<p>So to finally answer your question, here's a suggestion:</p>\n\n<pre><code>$show = get_post_meta( get_the_ID(), 'somekey', true );\n\nif( $show )\n{\n // Template part\n get_template_part( 'template-parts/content' );\n}\nelse\n{\n // Fetch the previous revision only\n $revisions = wp_get_post_revisions(\n get_the_ID(),\n [\n 'offset' =&gt; 1, // Start from the previous change\n 'posts_per_page' =&gt; 1, // Only a single revision\n 'post_name__in' =&gt; [ sprintf( \"%d-revision-v1\", get_the_ID() ) ],\n 'check_enabled' =&gt; false,\n ]\n );\n\n if( $revisions )\n {\n $post = reset( $revisions );\n setup_postdata( $post );\n\n // Template part\n get_template_part( 'template-parts/content' );\n\n wp_reset_postdata();\n }\n else\n {\n // Some fallback here\n }\n}\n</code></pre>\n\n<p>Hopefully you can adjust it further to your needs!</p>\n" } ]
2016/10/30
[ "https://wordpress.stackexchange.com/questions/244492", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104505/" ]
the following function I was producing together with some users here and it is function perfectly. ``` add_filter('wpseo_set_title', 'wpseo_set_title_callback'); $meinungen = "Meinungen zu: "; function wpseo_set_title_callback($input) { $page_comment = get_query_var('cpage'); if (is_single() && $page_comment > 0) { global $meinungen; return ''. $meinungen . ''. $input . ''; } else { return ''. $input . ''; } } ``` Now I wanna extend this function in this point, that I wanna say if "$page\_comment" more than 3 "$meinungen" is "Kontroverse Diskussionen zu". In all other cases "$meinungen" stays on "Meinungen zu", I tryed like it follows, but it doesnt function...I think the reason could be, that the query of comes later, but I dont know, how to get this in a point. Perhaps somebody could help me ? ``` add_filter('wpseo_set_title', 'wpseo_set_title_callback'); if $page_comment > 3) { $meinungen = "Kontroverse Diskussionen zu: "; } else { $meinungen = "Meinungen zu: "; } function wpseo_set_title_callback($input) { $page_comment = get_query_var('cpage'); if (is_single() && $page_comment > 0) { global $meinungen; return ''. $meinungen . ''. $input . ''; } else { return ''. $input . ''; } } ```
First we look into the `wp_get_post_autosave` function ------------------------------------------------------ It's informative to see how the core function `wp_get_post_autosave()` uses the `wp_get_post_revisions()` function. It loops over all revisions from ``` $revisions = wp_get_post_revisions( $post_id, array( 'check_enabled' => false ) ); ``` and then uses: ``` foreach ( $revisions as $revision ) { if ( false !== strpos( $revision->post_name, "{$post_id}-autosave" ) ) { if ( $user_id && $user_id != $revision->post_author ) continue; return $revision; } } ``` to return the first revision with a slug containing `"{$post_id}-autosave"` and where the `$user_id` possibly matches it's author. **Alternative** Now `wp_get_post_revisions()` is a wrapper for `get_children()`, so I wonder why it has to fetch all the revisions for the given post, before filtering out a single one. Why not try to fetch it directly, only what's needed? When we try e.g. the following (PHP 5.4+): ``` $revisions = wp_get_post_revisions( $post_id, [ 'offset' => 1, // Start from the previous change (ofset changed to offset) 'posts_per_page' => 1, // Only a single revision 'name' => "{$post_id}-autosave-v1", 'check_enabled' => false, ] ); ``` then the `posts_per_page` will not have any effect. After playing around with this I managed to get the following to work with the `posts_per_page` argument: ``` $revisions = wp_get_post_revisions( $post_id, [ 'offset' => 1, // Start from the previous change 'posts_per_page' => 1, // Only a single revision 'post_name__in' => [ "{$post_id}-autosave-v1" ], 'check_enabled' => false, ] ); ``` Get only the previous revision ------------------------------ Now we can adjust the above to only fetch the previous revision, i.e. that's not an *auto-save*: ``` $revisions = wp_get_post_revisions( $post_id, [ 'offset' => 1, // Start from the previous change 'posts_per_page' => 1, // Only a single revision 'post_name__in' => [ "{$post_id}-revision-v1" ], 'check_enabled' => false, ] ); ``` Here we target the `{$post_id}-revision-v1` slug. Note the here we use the `v1`, but we could adjust that if needed later on. Example ------- So to finally answer your question, here's a suggestion: ``` $show = get_post_meta( get_the_ID(), 'somekey', true ); if( $show ) { // Template part get_template_part( 'template-parts/content' ); } else { // Fetch the previous revision only $revisions = wp_get_post_revisions( get_the_ID(), [ 'offset' => 1, // Start from the previous change 'posts_per_page' => 1, // Only a single revision 'post_name__in' => [ sprintf( "%d-revision-v1", get_the_ID() ) ], 'check_enabled' => false, ] ); if( $revisions ) { $post = reset( $revisions ); setup_postdata( $post ); // Template part get_template_part( 'template-parts/content' ); wp_reset_postdata(); } else { // Some fallback here } } ``` Hopefully you can adjust it further to your needs!
244,501
<p>What is the best way to add JS script in wordpress and apply it to one page? As I understand, adding it in template is not recommended. My simple JS is:</p> <pre><code>var allStates = $("svg.us &gt; *"); allStates.on("click", function() { allStates.removeClass("on"); $(this).addClass("on"); }); </code></pre>
[ { "answer_id": 244503, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Check your page with <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow\"><code>is_page</code></a> in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> just in time for <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow\"><code>wp_add_inline_script</code></a>.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function() {\n\n if ( is_page( 'your-page-name' ) ) : ob_start(); ?&gt;\n\n // generic \n alert('Custom JS Loaded!');\n\n // custom \n var allStates = $(\"svg.us &gt; *\");\n\n allStates.on(\"click\", function() {\n\n allStates.removeClass(\"on\");\n $(this).addClass(\"on\");\n\n });\n &lt;?php wp_add_inline_script( 'jquery-migrate', sprintf( '( function( $ ) { %s } )( jQuery );', ob_get_clean() ) );\n\n endif; // test page\n\n} );\n</code></pre>\n" }, { "answer_id": 244504, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 3, "selected": true, "text": "<p>Create a new dir and file dedicated to your javascript. <code>/js/scripts.js</code>.</p>\n\n<p>Wrap your entire javascript like this:</p>\n\n<pre><code>( function( $ ) {\n\n var allStates = $(\"svg.us &gt; *\");\n\n allStates.on(\"click\", function() {\n\n allStates.removeClass(\"on\");\n $(this).addClass(\"on\");\n\n });\n\n} )( jQuery );\n</code></pre>\n\n<p>Then in your theme's functions file, put this code. It loads your new js file.</p>\n\n<pre><code>function your_scripts() {\n wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false );\n}\nadd_action( 'wp_enqueue_scripts', 'your_scripts' );\n</code></pre>\n\n<p>That way, all your javascript is available on any page and is loaded only once (afterwards, it's in browser cache). Since your function is <code>on click</code> it's fine for it to be available on all pages.</p>\n" }, { "answer_id": 244505, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 1, "selected": false, "text": "<p>You could do something like the following to check for a page before enqueuing. You may need to update your login inside the if statement if the post type is not a page - that this is the general concept:</p>\n\n<pre><code>add_action( 'wp_enqueue_script', 'enqueue_my_script');\nfunction enqueue_my_script() {\n $page_title = 'Page Title';\n if ( is_page( $page_title ) ) {\n wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false );\n }\n}\n</code></pre>\n" } ]
2016/10/31
[ "https://wordpress.stackexchange.com/questions/244501", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105189/" ]
What is the best way to add JS script in wordpress and apply it to one page? As I understand, adding it in template is not recommended. My simple JS is: ``` var allStates = $("svg.us > *"); allStates.on("click", function() { allStates.removeClass("on"); $(this).addClass("on"); }); ```
Create a new dir and file dedicated to your javascript. `/js/scripts.js`. Wrap your entire javascript like this: ``` ( function( $ ) { var allStates = $("svg.us > *"); allStates.on("click", function() { allStates.removeClass("on"); $(this).addClass("on"); }); } )( jQuery ); ``` Then in your theme's functions file, put this code. It loads your new js file. ``` function your_scripts() { wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false ); } add_action( 'wp_enqueue_scripts', 'your_scripts' ); ``` That way, all your javascript is available on any page and is loaded only once (afterwards, it's in browser cache). Since your function is `on click` it's fine for it to be available on all pages.
244,515
<p>I started to learn from a wordpress video tutorials on Tutsplus. <a href="https://webdesign.tutsplus.com/courses/building-wordpress-themes-with-bootstrap" rel="nofollow">Click Here</a>. Adi Purdila has created a function on that Tutorial →</p> <pre><code>/* ------------------------------------------------ */ /* 4. NUMBERED PAGINATION */ /* ------------------------------------------------ */ if ( ! function_exists( 'tuts_numbered_pagination' ) ) { function tuts_numbered_pagination() { $args = array( 'prev_next' =&gt; false, 'type' =&gt; 'array' ); echo '&lt;div class="col-md-12"&gt;'; $pagination = paginate_links( $args ); if ( is_array( $pagination ) ) { echo '&lt;ul class="nav nav-pills"&gt;'; foreach ( $pagination as $page ) { if ( strpos( $page, 'current' ) ) { echo '&lt;li class="active"&gt;&lt;a href="#"&gt;' . $page . '&lt;/a&gt;&lt;/li&gt;'; } else { echo '&lt;li&gt;' . $page . '&lt;/li&gt;'; } } echo '&lt;/ul&gt;'; } echo '&lt;/div&gt;'; } } </code></pre> <p>I am unable to understand this function. Although I can understand markups such as why its been echoed etc, but there are many things that I do not understand, for example →</p> <p>'prev_next' => false, prev_next' → <strong>is it something predefined in wordpress?</strong></p> <p>$page → This no where defined; How come Adi Purdila is using it? Is it some kind of global variable.</p> <p>P.S. to many experts my question will look stupid, but please bear with me as I am a novice.</p>
[ { "answer_id": 244503, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Check your page with <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow\"><code>is_page</code></a> in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> just in time for <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow\"><code>wp_add_inline_script</code></a>.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function() {\n\n if ( is_page( 'your-page-name' ) ) : ob_start(); ?&gt;\n\n // generic \n alert('Custom JS Loaded!');\n\n // custom \n var allStates = $(\"svg.us &gt; *\");\n\n allStates.on(\"click\", function() {\n\n allStates.removeClass(\"on\");\n $(this).addClass(\"on\");\n\n });\n &lt;?php wp_add_inline_script( 'jquery-migrate', sprintf( '( function( $ ) { %s } )( jQuery );', ob_get_clean() ) );\n\n endif; // test page\n\n} );\n</code></pre>\n" }, { "answer_id": 244504, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 3, "selected": true, "text": "<p>Create a new dir and file dedicated to your javascript. <code>/js/scripts.js</code>.</p>\n\n<p>Wrap your entire javascript like this:</p>\n\n<pre><code>( function( $ ) {\n\n var allStates = $(\"svg.us &gt; *\");\n\n allStates.on(\"click\", function() {\n\n allStates.removeClass(\"on\");\n $(this).addClass(\"on\");\n\n });\n\n} )( jQuery );\n</code></pre>\n\n<p>Then in your theme's functions file, put this code. It loads your new js file.</p>\n\n<pre><code>function your_scripts() {\n wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false );\n}\nadd_action( 'wp_enqueue_scripts', 'your_scripts' );\n</code></pre>\n\n<p>That way, all your javascript is available on any page and is loaded only once (afterwards, it's in browser cache). Since your function is <code>on click</code> it's fine for it to be available on all pages.</p>\n" }, { "answer_id": 244505, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 1, "selected": false, "text": "<p>You could do something like the following to check for a page before enqueuing. You may need to update your login inside the if statement if the post type is not a page - that this is the general concept:</p>\n\n<pre><code>add_action( 'wp_enqueue_script', 'enqueue_my_script');\nfunction enqueue_my_script() {\n $page_title = 'Page Title';\n if ( is_page( $page_title ) ) {\n wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false );\n }\n}\n</code></pre>\n" } ]
2016/10/31
[ "https://wordpress.stackexchange.com/questions/244515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I started to learn from a wordpress video tutorials on Tutsplus. [Click Here](https://webdesign.tutsplus.com/courses/building-wordpress-themes-with-bootstrap). Adi Purdila has created a function on that Tutorial → ``` /* ------------------------------------------------ */ /* 4. NUMBERED PAGINATION */ /* ------------------------------------------------ */ if ( ! function_exists( 'tuts_numbered_pagination' ) ) { function tuts_numbered_pagination() { $args = array( 'prev_next' => false, 'type' => 'array' ); echo '<div class="col-md-12">'; $pagination = paginate_links( $args ); if ( is_array( $pagination ) ) { echo '<ul class="nav nav-pills">'; foreach ( $pagination as $page ) { if ( strpos( $page, 'current' ) ) { echo '<li class="active"><a href="#">' . $page . '</a></li>'; } else { echo '<li>' . $page . '</li>'; } } echo '</ul>'; } echo '</div>'; } } ``` I am unable to understand this function. Although I can understand markups such as why its been echoed etc, but there are many things that I do not understand, for example → 'prev\_next' => false, prev\_next' → **is it something predefined in wordpress?** $page → This no where defined; How come Adi Purdila is using it? Is it some kind of global variable. P.S. to many experts my question will look stupid, but please bear with me as I am a novice.
Create a new dir and file dedicated to your javascript. `/js/scripts.js`. Wrap your entire javascript like this: ``` ( function( $ ) { var allStates = $("svg.us > *"); allStates.on("click", function() { allStates.removeClass("on"); $(this).addClass("on"); }); } )( jQuery ); ``` Then in your theme's functions file, put this code. It loads your new js file. ``` function your_scripts() { wp_enqueue_script( 'your-script-handle', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), '1.0', false ); } add_action( 'wp_enqueue_scripts', 'your_scripts' ); ``` That way, all your javascript is available on any page and is loaded only once (afterwards, it's in browser cache). Since your function is `on click` it's fine for it to be available on all pages.
244,526
<p>I am developing a plugin that is going to be used internally (inside the admin panel only).</p> <p>I wonder what is the correct way to build the requests (action, params, etc) and what hook to use to be able to catch those requests. Can somebody help?</p>
[ { "answer_id": 244530, "author": "BlackOut", "author_id": 99005, "author_profile": "https://wordpress.stackexchange.com/users/99005", "pm_score": 1, "selected": false, "text": "<p><em>You should post some code examples, explaining what are you trying to do, to get more useful answers.</em></p>\n\n<p>There are various hooks, and the one you should use depends on <strong>what</strong> you need. Anyway, here <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow\">Codex: Actions Run During an Admin Page Request</a> and here <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Administrative_Actions\" rel=\"nofollow\">Codex: Administrative Actions</a> the codex list the hooks to use for admin panel requests. </p>\n\n<p>Example: If you have to activate something in the admin initialization, you can use the <code>admin_init</code> action hook, so the code will be: <code>add_action('admin_init', 'your-custom-function');</code> If you have to operate when a page load in the dashboard, you can use the <code>load-(page)</code> hook; for example: <code>add_action('load-post.php', 'your-custom-function');</code> and so on.</p>\n\n<p>You can manage GET and POST requests with <code>$_GET['x']</code> and <code>$_POST['x']</code>, where <code>x</code> is the variable you want to take from the query string. Example: </p>\n\n<pre><code>wp-admin/post.php?post=69\n$_GET['post'] == 69\n</code></pre>\n" }, { "answer_id": 244548, "author": "Waleed", "author_id": 105983, "author_profile": "https://wordpress.stackexchange.com/users/105983", "pm_score": 0, "selected": false, "text": "<p>I don't know much, but I like this way. </p>\n\n<p>For forms:</p>\n\n<pre><code>&lt;form action=\"&lt;?php echo esc_url( admin_url('admin-post.php') ); ?&gt;\" method=\"POST\"&gt;\n&lt;input type=\"hidden\" name=\"action\" value=\"my_action\"&gt;\n</code></pre>\n\n<p>Backend</p>\n\n<pre><code>add_action( 'admin_post_nopriv_my_action', 'myhandler' );\nadd_action( 'admin_post_my_action', 'myhandler' );\n\nfunction myhandler(){\n\n // Do magic :)\n print_r($_POST);\n\n}\n</code></pre>\n" } ]
2016/10/31
[ "https://wordpress.stackexchange.com/questions/244526", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105980/" ]
I am developing a plugin that is going to be used internally (inside the admin panel only). I wonder what is the correct way to build the requests (action, params, etc) and what hook to use to be able to catch those requests. Can somebody help?
*You should post some code examples, explaining what are you trying to do, to get more useful answers.* There are various hooks, and the one you should use depends on **what** you need. Anyway, here [Codex: Actions Run During an Admin Page Request](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request) and here [Codex: Administrative Actions](https://codex.wordpress.org/Plugin_API/Action_Reference#Administrative_Actions) the codex list the hooks to use for admin panel requests. Example: If you have to activate something in the admin initialization, you can use the `admin_init` action hook, so the code will be: `add_action('admin_init', 'your-custom-function');` If you have to operate when a page load in the dashboard, you can use the `load-(page)` hook; for example: `add_action('load-post.php', 'your-custom-function');` and so on. You can manage GET and POST requests with `$_GET['x']` and `$_POST['x']`, where `x` is the variable you want to take from the query string. Example: ``` wp-admin/post.php?post=69 $_GET['post'] == 69 ```
244,613
<p>I have a Gravity Forms page set up where, after you fill out the form, you are taken to a confirmation page where you can download some resources.</p> <p>The problem with this setup is: Let's say someone fills out the form and then gets to the confirmation page, and then leaves the site. Later they remember they need to download a different file from the confirmation page. They come back to the site and have to fill out the form again.</p> <p>Is there some option in Gravity Forms to specify a cookie or something that indicates that the user already filled out the form and to take them directly to the confirmation page again?</p>
[ { "answer_id": 244733, "author": "Dave from Gravity Wiz", "author_id": 50224, "author_profile": "https://wordpress.stackexchange.com/users/50224", "pm_score": 2, "selected": false, "text": "<p>This is pretty close to that:</p>\n\n<p><a href=\"http://gravitywiz.com/submit-gravity-form-access-content/\" rel=\"nofollow noreferrer\">http://gravitywiz.com/submit-gravity-form-access-content/</a></p>\n\n<p>Based on your scenario <em>and</em> assuming your confirmation content is static, you would setup a WordPress page with your desired content. You would then configure the snippet so the user must submit the form to access that content. On subsequent visits, it would just show the content (without the form) if the user already submitted it.</p>\n" }, { "answer_id": 244736, "author": "brianjohnhanna", "author_id": 65403, "author_profile": "https://wordpress.stackexchange.com/users/65403", "pm_score": 4, "selected": true, "text": "<p>Here's some code on how you could simply leverage the <code>gform_after_submission</code> hook of Gravity Forms to set a cookie based on your form ID once submitted, then check for that on the confirmation page by hooking into <code>template_redirect</code>.</p>\n\n<p>In order to customize the functionality, you'll want to look at the docs for <a href=\"http://php.net/manual/en/function.setcookie.php\" rel=\"noreferrer\"><code>setcookie</code></a>, <a href=\"https://www.gravityhelp.com/documentation/article/gform_after_submission/\" rel=\"noreferrer\"><code>gform_after_submission</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"noreferrer\"><code>template_redirect</code></a>.</p>\n\n<p><strong>For the form</strong></p>\n\n<pre><code>// Make sure to swap out {your_form_id} with the ID of the form.\n\nadd_action( 'gform_after_submission_{your_form_id}', 'wpse_set_submitted_cookie', 10, 2 );\n\nfunction wpse_set_submitted_cookie( $entry, $form ) {\n\n // Set a third parameter to specify a cookie expiration time, \n // otherwise it will last until the end of the current session.\n\n setcookie( 'wpse_form_submitted', 'true' );\n}\n</code></pre>\n\n<p><strong>For the page</strong> </p>\n\n<pre><code>add_action( 'template_redirect', 'wpse_protect_confirmation_page' );\n\nfunction wpse_protect_confirmation_page() {\n if( is_page( 'my-confirmation-page' ) &amp;&amp; ! isset( $_COOKIE['wpse_form_submitted'] ) ) {\n wp_redirect( home_url( '/my-form/' ) );\n exit();\n }\n}\n</code></pre>\n" } ]
2016/10/31
[ "https://wordpress.stackexchange.com/questions/244613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8160/" ]
I have a Gravity Forms page set up where, after you fill out the form, you are taken to a confirmation page where you can download some resources. The problem with this setup is: Let's say someone fills out the form and then gets to the confirmation page, and then leaves the site. Later they remember they need to download a different file from the confirmation page. They come back to the site and have to fill out the form again. Is there some option in Gravity Forms to specify a cookie or something that indicates that the user already filled out the form and to take them directly to the confirmation page again?
Here's some code on how you could simply leverage the `gform_after_submission` hook of Gravity Forms to set a cookie based on your form ID once submitted, then check for that on the confirmation page by hooking into `template_redirect`. In order to customize the functionality, you'll want to look at the docs for [`setcookie`](http://php.net/manual/en/function.setcookie.php), [`gform_after_submission`](https://www.gravityhelp.com/documentation/article/gform_after_submission/) and [`template_redirect`](https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect). **For the form** ``` // Make sure to swap out {your_form_id} with the ID of the form. add_action( 'gform_after_submission_{your_form_id}', 'wpse_set_submitted_cookie', 10, 2 ); function wpse_set_submitted_cookie( $entry, $form ) { // Set a third parameter to specify a cookie expiration time, // otherwise it will last until the end of the current session. setcookie( 'wpse_form_submitted', 'true' ); } ``` **For the page** ``` add_action( 'template_redirect', 'wpse_protect_confirmation_page' ); function wpse_protect_confirmation_page() { if( is_page( 'my-confirmation-page' ) && ! isset( $_COOKIE['wpse_form_submitted'] ) ) { wp_redirect( home_url( '/my-form/' ) ); exit(); } } ```
244,657
<p>I've created a new post type gallery using CPT UI plugin, Now I want to add options to choose post Format and Featured Image in add new gallery post. Please check the attached screenshot. Could you please tell me how to get this option in add new post page.</p> <p><a href="https://i.stack.imgur.com/cjtaR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cjtaR.png" alt="enter image description here"></a></p>
[ { "answer_id": 244666, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 0, "selected": false, "text": "<p>When you will add new Custom Post Type using CPT UI plugin, you will see an option under <strong>Settings -> Support -> Post Formats</strong> in CPT UI Plugin.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zrlom.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zrlom.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 244670, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 2, "selected": true, "text": "<p>First of all themes need to use <code>add_theme_support()</code> in the <code>functions.php</code> file to tell <code>WordPress</code> which post formats to support by passing an array of formats like so:</p>\n\n<pre><code>add_theme_support( 'post-formats', array( 'aside', 'gallery' ) );\n</code></pre>\n\n<p><strong><em>Note that you must call this before the init hook gets called! A good hook to use is the <code>after_setup_theme</code> hook.</em></strong></p>\n\n<p>Then by code you can add the post formats like below-</p>\n\n<pre><code>//add post-formats to post_type 'your_custom_post_type'\nadd_post_type_support( 'your_custom_post_type', 'post-formats' );\n</code></pre>\n\n<p>Also can add support on creation of post type like below-</p>\n\n<pre><code>// register custom post type 'your_custom_post_type' with 'supports' parameter\nadd_action( 'init', 'create_your_post_type' );\nfunction create_my_post_type() {\n register_post_type( 'your_custom_post_type',\n array(\n 'labels' =&gt; array( 'name' =&gt; __( 'Products' ) ),\n 'public' =&gt; true,\n 'supports' =&gt; array('title', 'editor', 'post-formats')\n )\n );\n} \n</code></pre>\n" }, { "answer_id": 244676, "author": "Suresh Alagar", "author_id": 106060, "author_profile": "https://wordpress.stackexchange.com/users/106060", "pm_score": 0, "selected": false, "text": "<p>I've added the following code in funtions.php in my theme:</p>\n\n<pre><code>&lt;?php\n\nadd_theme_support( 'post-formats', array( 'gallery', 'image', 'video' ) );\n\n//add post-formats to post_type 'your_custom_post_type'\nadd_post_type_support( 'your_custom_post_type', 'post-formats' );\n\n// register custom post type 'your_custom_post_type' with 'supports' parameter\nadd_action( 'init', 'create_your_post_type' );\nfunction create_my_post_type() {\n register_post_type( 'your_custom_post_type',\n array(\n 'labels' =&gt; array( 'name' =&gt; __( 'Products' ) ),\n 'public' =&gt; true,\n 'supports' =&gt; array('title', 'editor', 'post-formats')\n )\n );\n}\n</code></pre>\n" }, { "answer_id": 401082, "author": "samjco", "author_id": 29133, "author_profile": "https://wordpress.stackexchange.com/users/29133", "pm_score": 0, "selected": false, "text": "<p>After adding post format support to your CPT:</p>\n<pre><code>function jt_add_post_type_support() {\n\n //add post-formats to post_type 'your_custom_post_type'\n add_post_type_support( 'your_custom_post_type', 'post-formats' );\n}\nadd_action( 'init', 'jt_add_post_type_support', 10 );\n</code></pre>\n<p>You can modify it when this:\n(*DO FORGET TO CHANGE &quot;your_custom_post_type&quot; to your CPT in both functions)</p>\n<pre><code>add_action( 'load-post.php', 'jt_post_format_support_filter' );\nadd_action( 'load-post-new.php', 'jt_post_format_support_filter' );\nadd_action( 'load-edit.php', 'jt_post_format_support_filter' );\n\nfunction jt_get_allowed_project_formats() {\n //CHANGE TO THE ONES YOU WANT HERE:\n return array( 'standard', 'quote', 'image', 'video' );\n}\n\nfunction jt_default_post_format_filter( $format ) {\n\n return in_array( $format, jt_get_allowed_project_formats() ) ? $format : 'standard';\n}\n\nfunction jt_post_format_support_filter() {\n\n $screen = get_current_screen();\n\n // Bail if not on the projects screen.\n if ( empty( $screen-&gt;post_type ) || $screen-&gt;post_type !== 'your_custom_post_type' )\n return;\n\n // Check if the current theme supports formats.\n if ( current_theme_supports( 'post-formats' ) ) {\n\n $formats = get_theme_support( 'post-formats' );\n\n // If we have formats, add theme support for only the allowed formats.\n if ( isset( $formats[0] ) ) {\n $new_formats = array_intersect( $formats[0], jt_get_allowed_project_formats() );\n\n // Remove post formats support.\n remove_theme_support( 'post-formats' );\n\n // If the theme supports the allowed formats, add support for them.\n if ( $new_formats )\n add_theme_support( 'post-formats', $new_formats );\n }\n }\n\n // Filter the default post format.\n add_filter( 'option_default_post_format', 'jt_default_post_format_filter', 95 );\n}\n</code></pre>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244657", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106060/" ]
I've created a new post type gallery using CPT UI plugin, Now I want to add options to choose post Format and Featured Image in add new gallery post. Please check the attached screenshot. Could you please tell me how to get this option in add new post page. [![enter image description here](https://i.stack.imgur.com/cjtaR.png)](https://i.stack.imgur.com/cjtaR.png)
First of all themes need to use `add_theme_support()` in the `functions.php` file to tell `WordPress` which post formats to support by passing an array of formats like so: ``` add_theme_support( 'post-formats', array( 'aside', 'gallery' ) ); ``` ***Note that you must call this before the init hook gets called! A good hook to use is the `after_setup_theme` hook.*** Then by code you can add the post formats like below- ``` //add post-formats to post_type 'your_custom_post_type' add_post_type_support( 'your_custom_post_type', 'post-formats' ); ``` Also can add support on creation of post type like below- ``` // register custom post type 'your_custom_post_type' with 'supports' parameter add_action( 'init', 'create_your_post_type' ); function create_my_post_type() { register_post_type( 'your_custom_post_type', array( 'labels' => array( 'name' => __( 'Products' ) ), 'public' => true, 'supports' => array('title', 'editor', 'post-formats') ) ); } ```
244,663
<p>I have a simple if statement:</p> <pre><code>if (class_exists('Woocommerce')) { echo 'yes'; } else { echo 'no'; } </code></pre> <p>This works fine when using it in a theme file (functions.php for example). But when I'm using it on a plugin (plugins/myplugin/myplugin.php) it doesn't work at all. How can I check if the plugin exists/is-active within my plugin to enable/disable some features? Am I missing something?</p>
[ { "answer_id": 244668, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 3, "selected": true, "text": "<p>Woo Commerce provides <a href=\"https://docs.woocommerce.com/document/create-a-plugin/\" rel=\"nofollow\">code</a> to check to see if WooCommerce is installed :</p>\n\n<pre>\n<code>\n/**\n * Check if WooCommerce is active\n **/\nif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {\n // Put your plugin code here\n}\n</code>\n</pre>\n\n<p>If no idea where WooCommerece install then :</p>\n\n<pre>\n<code>\n $all_plugins = get_plugins();\n $active_plugins = get_option( \"active_plugins\" );\n\n foreach ( $all_plugins as $plugin_path => $value ) {\n\n if( basename( $plugin_path, \".php\" ) == 'woocommerce') {\n if( in_array( $plugin_path, $active_plugins ) ) {\n return true;\n }else {\n return false;\n }\n }\n }\n</code>\n</pre>\n" }, { "answer_id": 244671, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The best way is to run your code at actions triggered by the other plugin. If it has some initialization action than it is a perfect solution.</p>\n\n<p>Otherwise this kind of check should better be done on the core <code>wp_loaded</code> hook and for sure not before <code>plugins_loaded</code> hook. Running it directly without any dependence on hook will just never work reliably. </p>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28159/" ]
I have a simple if statement: ``` if (class_exists('Woocommerce')) { echo 'yes'; } else { echo 'no'; } ``` This works fine when using it in a theme file (functions.php for example). But when I'm using it on a plugin (plugins/myplugin/myplugin.php) it doesn't work at all. How can I check if the plugin exists/is-active within my plugin to enable/disable some features? Am I missing something?
Woo Commerce provides [code](https://docs.woocommerce.com/document/create-a-plugin/) to check to see if WooCommerce is installed : ``` /** * Check if WooCommerce is active **/ if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) { // Put your plugin code here } ``` If no idea where WooCommerece install then : ``` $all_plugins = get_plugins(); $active_plugins = get_option( "active_plugins" ); foreach ( $all_plugins as $plugin_path => $value ) { if( basename( $plugin_path, ".php" ) == 'woocommerce') { if( in_array( $plugin_path, $active_plugins ) ) { return true; }else { return false; } } } ```
244,685
<p>I want to change a text label to an image. This label is on WooCommerce shop page.</p> <p><a href="https://i.stack.imgur.com/P1aKI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P1aKI.jpg" alt="Member Discount"></a></p> <p>The script contains the text "Member discount!":</p> <pre><code>$label = __( 'Member discount!', 'woocommerce-memberships' ); </code></pre> <p>I tried changing the script, E.g.: <code>&lt;img src="http://siteh87h8.com/gambar.png" /&gt;</code>, but the text is still not changed.</p> <p>Relevant code:</p> <pre><code>/** * Get member discount badge * * @since 1.6.4 * @param \WC_Product $product The product object to output a badge for (passed to filter) * @param bool $variation Whether to output a discount badge specific for a product variation (default false) * @return string */ public function get_member_discount_badge( $product, $variation = false ) { $label = __( 'Member discount!', 'woocommerce-memberships' ); // we have a slight different output for badge classes and filter if ( true !== $variation ) { global $post; // used in filter for backwards compatibility reasons $the_post = $post; if ( ! $the_post instanceof WP_Post ) { $the_post = $product-&gt;post; } $badge = '&lt;span class="onsale wc-memberships-member-discount"&gt;' . esc_html( $label ) . '&lt;/span&gt;'; /** * Filter the member discount badge * * @since 1.0.0 * @param string $badge The badge HTML * @param \WP_Post $post The product post object * @param \WC_Product_Variation $variation The product variation */ $badge = apply_filters( 'wc_memberships_member_discount_badge', $badge, $the_post, $product ); } else { $badge = '&lt;span class="wc-memberships-variation-member-discount"&gt;' . esc_html( $label ) . '&lt;/span&gt;'; /** * Filter the variation member discount badge * * @since 1.3.2 * @param string $badge The badge HTML * @param \WC_Product|\WC_Product_Variation $variation The product variation */ $badge = apply_filters( 'wc_memberships_variation_member_discount_badge', $badge, $product ); } return $badge; } /** * Filter the member discount badge for products excluded * from member discount rules * * @internal * * @since 1.7.0 * @param string $badge Badge HTML * @param \WP_Post $post The post object * @param \WC_Product $product The product object * @return string Empty string if product is excluded from member discounts */ public function disable_discount_badge_for_excluded_products( $badge, $post, $product ) { return $this-&gt;is_product_excluded_from_member_discounts( $product ) ? '' : $badge; } </code></pre> <p>Full script here: <a href="http://pastebin.com/AGztQYYt" rel="nofollow noreferrer">http://pastebin.com/AGztQYYt</a> (relevant code starts on line 1032).</p> <p><strong>Edit:</strong> The accepted answer worked for me. Along with the code from that answer, I used this CSS:</p> <pre><code>.woocommerce ul.products.grid li.product .badgescarisan{position:absolute;right: 0px;} </code></pre> <p>And this HTML:</p> <pre><code>$badge = '&lt;span class="badgescarisan wc-memberships-member-discount"&gt;' . '&lt;img src="https://www.conecplus.com/wp-content/uploads/2016/11/Badges-Membership-Carisan.png" alt="meow"&gt;' . '&lt;/span&gt;'; </code></pre>
[ { "answer_id": 244720, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<h2>Changing the label text (text only)</h2>\n\n<p>The text \"Member discount!\" can be changed using a translation filter, but it's not possible to add an image or any HTML to that because it is escaped later in the code referenced in the question:</p>\n\n<pre><code> $badge = '&lt;span class=\"onsale wc-memberships-member-discount\"&gt;' . esc_html( $label ) . '&lt;/span&gt;';\n</code></pre>\n\n<p>Here is an example showing how to change the <em>Member discount!</em> text, but it will only work with text, not HTML:</p>\n\n<pre><code>add_filter( 'gettext', 'wpse244685_change_text', 20, 3 );\nfunction wpse244685_change_text( $translated_text, $untranslated_text, $domain ) {\n if ( 'woocommerce-memberships' !== $domain ) {\n return $translated_text; \n }\n\n // make the changes to the text\n switch( $untranslated_text ) {\n\n case 'Member discount!' :\n // $translated_text = __( 'New text', 'text_domain' ); // Example of new string\n $translated_text = ''; // Empty strings should not be translated\n break;\n\n // add more items\n }\n\n return $translated_text; \n}\n</code></pre>\n\n<h2>Adding an image or other HTML</h2>\n\n<p>Depending on how your product is configured, it looks like you can change the HTML for the badge, and therefore add an image, via either the <code>wc_memberships_member_discount_badge</code> or <code>wc_memberships_variation_member_discount_badge</code> filters as follows:</p>\n\n<p><strong>Standard Product:</strong></p>\n\n<pre><code>add_filter( 'wc_memberships_member_discount_badge', 'wpse244685_wc_memberships_member_discount_badge', 10, 3 );\nfunction wpse244685_wc_memberships_member_discount_badge( $badge, $the_post, $product ) {\n $badge = '&lt;span class=\"onsale wc-memberships-member-discount\"&gt;' . \n '&lt;img src=\"https://placekitten.com/300/300\" alt=\"meow\"&gt;' .\n '&lt;/span&gt;';\n\n return $badge; \n}\n</code></pre>\n\n<p><strong>Variable Product:</strong></p>\n\n<pre><code>add_filter( 'wc_memberships_variation_member_discount_badge', 'wpse244685_wc_memberships_variation_member_discount_badge', 10, 2 );\nfunction wpse244685_wc_memberships_member_discount_badge( $badge, $product ) {\n $badge = '&lt;span class=\"onsale wc-memberships-member-discount\"&gt;' . \n '&lt;img src=\"https://placekitten.com/300/300\" alt=\"meow\"&gt;' .\n '&lt;/span&gt;';\n\n return $badge; \n}\n</code></pre>\n" }, { "answer_id": 244732, "author": "Rangga Setiaga", "author_id": 106078, "author_profile": "https://wordpress.stackexchange.com/users/106078", "pm_score": 0, "selected": false, "text": "<p>Succeed ^o^ I change the css class \"onsale\" to \"badgescarisan\"</p>\n\n<pre><code>.woocommerce ul.products.grid li.product .badgescarisan{position:absolute;right: 0px;}\n</code></pre>\n\n<p>And add pictures</p>\n\n<pre><code>$badge = '&lt;span class=\"badgescarisan wc-memberships-member-discount\"&gt;' . '&lt;img src=\"https://www.conecplus.com/wp-content/uploads/2016/11/Badges-Membership-Carisan.png\" alt=\"meow\"&gt;' .'&lt;/span&gt;';\n</code></pre>\n\n<p>Thank you for helping me. Sorry my english is bad. ^_^</p>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244685", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106078/" ]
I want to change a text label to an image. This label is on WooCommerce shop page. [![Member Discount](https://i.stack.imgur.com/P1aKI.jpg)](https://i.stack.imgur.com/P1aKI.jpg) The script contains the text "Member discount!": ``` $label = __( 'Member discount!', 'woocommerce-memberships' ); ``` I tried changing the script, E.g.: `<img src="http://siteh87h8.com/gambar.png" />`, but the text is still not changed. Relevant code: ``` /** * Get member discount badge * * @since 1.6.4 * @param \WC_Product $product The product object to output a badge for (passed to filter) * @param bool $variation Whether to output a discount badge specific for a product variation (default false) * @return string */ public function get_member_discount_badge( $product, $variation = false ) { $label = __( 'Member discount!', 'woocommerce-memberships' ); // we have a slight different output for badge classes and filter if ( true !== $variation ) { global $post; // used in filter for backwards compatibility reasons $the_post = $post; if ( ! $the_post instanceof WP_Post ) { $the_post = $product->post; } $badge = '<span class="onsale wc-memberships-member-discount">' . esc_html( $label ) . '</span>'; /** * Filter the member discount badge * * @since 1.0.0 * @param string $badge The badge HTML * @param \WP_Post $post The product post object * @param \WC_Product_Variation $variation The product variation */ $badge = apply_filters( 'wc_memberships_member_discount_badge', $badge, $the_post, $product ); } else { $badge = '<span class="wc-memberships-variation-member-discount">' . esc_html( $label ) . '</span>'; /** * Filter the variation member discount badge * * @since 1.3.2 * @param string $badge The badge HTML * @param \WC_Product|\WC_Product_Variation $variation The product variation */ $badge = apply_filters( 'wc_memberships_variation_member_discount_badge', $badge, $product ); } return $badge; } /** * Filter the member discount badge for products excluded * from member discount rules * * @internal * * @since 1.7.0 * @param string $badge Badge HTML * @param \WP_Post $post The post object * @param \WC_Product $product The product object * @return string Empty string if product is excluded from member discounts */ public function disable_discount_badge_for_excluded_products( $badge, $post, $product ) { return $this->is_product_excluded_from_member_discounts( $product ) ? '' : $badge; } ``` Full script here: <http://pastebin.com/AGztQYYt> (relevant code starts on line 1032). **Edit:** The accepted answer worked for me. Along with the code from that answer, I used this CSS: ``` .woocommerce ul.products.grid li.product .badgescarisan{position:absolute;right: 0px;} ``` And this HTML: ``` $badge = '<span class="badgescarisan wc-memberships-member-discount">' . '<img src="https://www.conecplus.com/wp-content/uploads/2016/11/Badges-Membership-Carisan.png" alt="meow">' . '</span>'; ```
Changing the label text (text only) ----------------------------------- The text "Member discount!" can be changed using a translation filter, but it's not possible to add an image or any HTML to that because it is escaped later in the code referenced in the question: ``` $badge = '<span class="onsale wc-memberships-member-discount">' . esc_html( $label ) . '</span>'; ``` Here is an example showing how to change the *Member discount!* text, but it will only work with text, not HTML: ``` add_filter( 'gettext', 'wpse244685_change_text', 20, 3 ); function wpse244685_change_text( $translated_text, $untranslated_text, $domain ) { if ( 'woocommerce-memberships' !== $domain ) { return $translated_text; } // make the changes to the text switch( $untranslated_text ) { case 'Member discount!' : // $translated_text = __( 'New text', 'text_domain' ); // Example of new string $translated_text = ''; // Empty strings should not be translated break; // add more items } return $translated_text; } ``` Adding an image or other HTML ----------------------------- Depending on how your product is configured, it looks like you can change the HTML for the badge, and therefore add an image, via either the `wc_memberships_member_discount_badge` or `wc_memberships_variation_member_discount_badge` filters as follows: **Standard Product:** ``` add_filter( 'wc_memberships_member_discount_badge', 'wpse244685_wc_memberships_member_discount_badge', 10, 3 ); function wpse244685_wc_memberships_member_discount_badge( $badge, $the_post, $product ) { $badge = '<span class="onsale wc-memberships-member-discount">' . '<img src="https://placekitten.com/300/300" alt="meow">' . '</span>'; return $badge; } ``` **Variable Product:** ``` add_filter( 'wc_memberships_variation_member_discount_badge', 'wpse244685_wc_memberships_variation_member_discount_badge', 10, 2 ); function wpse244685_wc_memberships_member_discount_badge( $badge, $product ) { $badge = '<span class="onsale wc-memberships-member-discount">' . '<img src="https://placekitten.com/300/300" alt="meow">' . '</span>'; return $badge; } ```
244,693
<p>I have several categories on my wp site.</p> <p>On the front page I want to make sections for all of existing categories and than output 4 most recent articles from each of the category.</p> <p>Is there a more elegant way of querying for those articles?</p> <p>Currently I'm first getting all of existing categories :</p> <pre><code>get_terms('category', array('hide_empty' =&gt; 0) </code></pre> <p>Than I'm using <code>foreach</code> to loop through those categories and in each loop cycle I'm getting 4 articles from that category by using :</p> <pre><code>$articles = get_posts(array('numberposts' =&gt; 4, 'category' =&gt; $c-&gt;term_id)); </code></pre> <p>And all of that is within my template file which I don't like.</p> <p><strong>Is this the recommended wordpress way, or is there more elegant solution?</strong></p> <p>I'm also bothered that by default, wordpress allready queries for most recent articles in advance on the homepage, so that query is kind of going to waste in my case.</p>
[ { "answer_id": 244720, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<h2>Changing the label text (text only)</h2>\n\n<p>The text \"Member discount!\" can be changed using a translation filter, but it's not possible to add an image or any HTML to that because it is escaped later in the code referenced in the question:</p>\n\n<pre><code> $badge = '&lt;span class=\"onsale wc-memberships-member-discount\"&gt;' . esc_html( $label ) . '&lt;/span&gt;';\n</code></pre>\n\n<p>Here is an example showing how to change the <em>Member discount!</em> text, but it will only work with text, not HTML:</p>\n\n<pre><code>add_filter( 'gettext', 'wpse244685_change_text', 20, 3 );\nfunction wpse244685_change_text( $translated_text, $untranslated_text, $domain ) {\n if ( 'woocommerce-memberships' !== $domain ) {\n return $translated_text; \n }\n\n // make the changes to the text\n switch( $untranslated_text ) {\n\n case 'Member discount!' :\n // $translated_text = __( 'New text', 'text_domain' ); // Example of new string\n $translated_text = ''; // Empty strings should not be translated\n break;\n\n // add more items\n }\n\n return $translated_text; \n}\n</code></pre>\n\n<h2>Adding an image or other HTML</h2>\n\n<p>Depending on how your product is configured, it looks like you can change the HTML for the badge, and therefore add an image, via either the <code>wc_memberships_member_discount_badge</code> or <code>wc_memberships_variation_member_discount_badge</code> filters as follows:</p>\n\n<p><strong>Standard Product:</strong></p>\n\n<pre><code>add_filter( 'wc_memberships_member_discount_badge', 'wpse244685_wc_memberships_member_discount_badge', 10, 3 );\nfunction wpse244685_wc_memberships_member_discount_badge( $badge, $the_post, $product ) {\n $badge = '&lt;span class=\"onsale wc-memberships-member-discount\"&gt;' . \n '&lt;img src=\"https://placekitten.com/300/300\" alt=\"meow\"&gt;' .\n '&lt;/span&gt;';\n\n return $badge; \n}\n</code></pre>\n\n<p><strong>Variable Product:</strong></p>\n\n<pre><code>add_filter( 'wc_memberships_variation_member_discount_badge', 'wpse244685_wc_memberships_variation_member_discount_badge', 10, 2 );\nfunction wpse244685_wc_memberships_member_discount_badge( $badge, $product ) {\n $badge = '&lt;span class=\"onsale wc-memberships-member-discount\"&gt;' . \n '&lt;img src=\"https://placekitten.com/300/300\" alt=\"meow\"&gt;' .\n '&lt;/span&gt;';\n\n return $badge; \n}\n</code></pre>\n" }, { "answer_id": 244732, "author": "Rangga Setiaga", "author_id": 106078, "author_profile": "https://wordpress.stackexchange.com/users/106078", "pm_score": 0, "selected": false, "text": "<p>Succeed ^o^ I change the css class \"onsale\" to \"badgescarisan\"</p>\n\n<pre><code>.woocommerce ul.products.grid li.product .badgescarisan{position:absolute;right: 0px;}\n</code></pre>\n\n<p>And add pictures</p>\n\n<pre><code>$badge = '&lt;span class=\"badgescarisan wc-memberships-member-discount\"&gt;' . '&lt;img src=\"https://www.conecplus.com/wp-content/uploads/2016/11/Badges-Membership-Carisan.png\" alt=\"meow\"&gt;' .'&lt;/span&gt;';\n</code></pre>\n\n<p>Thank you for helping me. Sorry my english is bad. ^_^</p>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105920/" ]
I have several categories on my wp site. On the front page I want to make sections for all of existing categories and than output 4 most recent articles from each of the category. Is there a more elegant way of querying for those articles? Currently I'm first getting all of existing categories : ``` get_terms('category', array('hide_empty' => 0) ``` Than I'm using `foreach` to loop through those categories and in each loop cycle I'm getting 4 articles from that category by using : ``` $articles = get_posts(array('numberposts' => 4, 'category' => $c->term_id)); ``` And all of that is within my template file which I don't like. **Is this the recommended wordpress way, or is there more elegant solution?** I'm also bothered that by default, wordpress allready queries for most recent articles in advance on the homepage, so that query is kind of going to waste in my case.
Changing the label text (text only) ----------------------------------- The text "Member discount!" can be changed using a translation filter, but it's not possible to add an image or any HTML to that because it is escaped later in the code referenced in the question: ``` $badge = '<span class="onsale wc-memberships-member-discount">' . esc_html( $label ) . '</span>'; ``` Here is an example showing how to change the *Member discount!* text, but it will only work with text, not HTML: ``` add_filter( 'gettext', 'wpse244685_change_text', 20, 3 ); function wpse244685_change_text( $translated_text, $untranslated_text, $domain ) { if ( 'woocommerce-memberships' !== $domain ) { return $translated_text; } // make the changes to the text switch( $untranslated_text ) { case 'Member discount!' : // $translated_text = __( 'New text', 'text_domain' ); // Example of new string $translated_text = ''; // Empty strings should not be translated break; // add more items } return $translated_text; } ``` Adding an image or other HTML ----------------------------- Depending on how your product is configured, it looks like you can change the HTML for the badge, and therefore add an image, via either the `wc_memberships_member_discount_badge` or `wc_memberships_variation_member_discount_badge` filters as follows: **Standard Product:** ``` add_filter( 'wc_memberships_member_discount_badge', 'wpse244685_wc_memberships_member_discount_badge', 10, 3 ); function wpse244685_wc_memberships_member_discount_badge( $badge, $the_post, $product ) { $badge = '<span class="onsale wc-memberships-member-discount">' . '<img src="https://placekitten.com/300/300" alt="meow">' . '</span>'; return $badge; } ``` **Variable Product:** ``` add_filter( 'wc_memberships_variation_member_discount_badge', 'wpse244685_wc_memberships_variation_member_discount_badge', 10, 2 ); function wpse244685_wc_memberships_member_discount_badge( $badge, $product ) { $badge = '<span class="onsale wc-memberships-member-discount">' . '<img src="https://placekitten.com/300/300" alt="meow">' . '</span>'; return $badge; } ```
244,705
<p>I have about 2000 post with the titles in the following format:</p> <pre><code>[i like apples] </code></pre> <p>I want make them:</p> <pre><code>[I Like Apples] </code></pre> <p>I used the <a href="https://wordpress.org/plugins/wp-title-case/" rel="nofollow noreferrer">WP Title Case plugin</a>, but the problem is that this plugin is only capitalizing the title of the post itself, so just <code>h1</code> looks normal but <code>&lt;title&gt;</code> in <code>&lt;head&gt;</code> is still not capitalized. I guess the real non-capitalized titles are being fetched from database. </p> <p>Maybe there is a SQL script to capitalize the column in the table of the database or a php script to change the <code>&lt;title&gt;</code> in head into normal format?</p>
[ { "answer_id": 244707, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 3, "selected": true, "text": "<p><strong>EDIT: WP Title Hook</strong></p>\n\n<p>Ok, so if you're using wp_title (which you probably are, it's default) that function should have two filters in it you could use.</p>\n\n<p>The first one is wp_title_parts, which returns your title broken up into an array.</p>\n\n<pre><code>function wp_title_capitalize( $title_parts ) {\n\n // Only uppercases the words of the first element (should be the page title)\n $title_parts[0] = ucwords( $title_parts[0] );\n\n return $title_parts;\n\n}\nadd_filter( 'wp_title_parts', 'wp_title_capitalize' );\n</code></pre>\n\n<p>OR if you're ok with running the uppercase filter on the whole thing, you can run it on wp_title</p>\n\n<pre><code>function wp_full_title_capitalize( $title, $sep, $seplocation ) {\n\n // Uppercases the entire title\n $title = ucwords( $title );\n\n return $title;\n\n}\nadd_filter( 'wp_title', 'wp_full_title_capitalize' );\n</code></pre>\n\n<p>The second answer is easier to understand, since it runs on the whole thing, but if your titles look like</p>\n\n<pre><code>About Us | COMPANY NAME\n</code></pre>\n\n<p>Then, you probably want to go with the first option.</p>\n\n<p>As always, with hooks &amp; filters, these go in functions.php of your theme.</p>\n\n<p><strong>Old Answer (CSS ONLY)</strong></p>\n\n<p>If you're only worried about the display, you can just apply</p>\n\n<pre><code>text-transform: capitalize;\n</code></pre>\n\n<p>to the CSS of your h1.</p>\n\n<p><a href=\"http://www.w3schools.com/cssref/playit.asp?filename=playcss_text-transform&amp;preval=capitalize\" rel=\"nofollow noreferrer\">http://www.w3schools.com/cssref/playit.asp?filename=playcss_text-transform&amp;preval=capitalize</a></p>\n" }, { "answer_id": 244831, "author": "blackstar", "author_id": 106156, "author_profile": "https://wordpress.stackexchange.com/users/106156", "pm_score": 1, "selected": false, "text": "<p>You can use wordpress hooks in functions.php but as socki03 answered I think this is abit better </p>\n\n<pre><code>add_filter( 'wp_title', 'ucwords' );\n</code></pre>\n\n<p>I still believe this is abit overkill</p>\n\n<pre><code>function wp_full_title_capitalize( $title, $sep, $seplocation ) {\n\n // Uppercases the entire title\n $title = ucwords( $title );\n\n return $title;\n\n}\nadd_filter( 'wp_title', 'wp_full_title_capitalize' );\n</code></pre>\n\n<p>I can't comment his answer so i am leaving this as a answer :)</p>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106087/" ]
I have about 2000 post with the titles in the following format: ``` [i like apples] ``` I want make them: ``` [I Like Apples] ``` I used the [WP Title Case plugin](https://wordpress.org/plugins/wp-title-case/), but the problem is that this plugin is only capitalizing the title of the post itself, so just `h1` looks normal but `<title>` in `<head>` is still not capitalized. I guess the real non-capitalized titles are being fetched from database. Maybe there is a SQL script to capitalize the column in the table of the database or a php script to change the `<title>` in head into normal format?
**EDIT: WP Title Hook** Ok, so if you're using wp\_title (which you probably are, it's default) that function should have two filters in it you could use. The first one is wp\_title\_parts, which returns your title broken up into an array. ``` function wp_title_capitalize( $title_parts ) { // Only uppercases the words of the first element (should be the page title) $title_parts[0] = ucwords( $title_parts[0] ); return $title_parts; } add_filter( 'wp_title_parts', 'wp_title_capitalize' ); ``` OR if you're ok with running the uppercase filter on the whole thing, you can run it on wp\_title ``` function wp_full_title_capitalize( $title, $sep, $seplocation ) { // Uppercases the entire title $title = ucwords( $title ); return $title; } add_filter( 'wp_title', 'wp_full_title_capitalize' ); ``` The second answer is easier to understand, since it runs on the whole thing, but if your titles look like ``` About Us | COMPANY NAME ``` Then, you probably want to go with the first option. As always, with hooks & filters, these go in functions.php of your theme. **Old Answer (CSS ONLY)** If you're only worried about the display, you can just apply ``` text-transform: capitalize; ``` to the CSS of your h1. <http://www.w3schools.com/cssref/playit.asp?filename=playcss_text-transform&preval=capitalize>
244,722
<p>I have an HTML code here →</p> <pre><code>&lt;!-- Page Header --&gt; &lt;!-- Set your background image for this header on the line below. --&gt; &lt;header class="intro-header" style="background-image: url('img/home-bg.jpg')"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"&gt; &lt;div class="site-heading"&gt; &lt;h1&gt; Clean Blog &lt;/h1&gt; &lt;hr class="small"&gt; &lt;span class="subheading"&gt;A Clean Blog Theme by Start Bootstrap&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; </code></pre> <p>I was trying to convert this into WP dynamically.</p> <p>How to convert this dynamically →</p> <pre><code> &lt;header class="intro-header" style="background-image: url('img/home-bg.jpg')"&gt; </code></pre> <p><code>style="background-image: url('img/home-bg.jpg')</code> → How to convert this dynamically so that the image in the background should come from wordpress features image section.</p> <p>I was trying this, but it didn't worked = </p> <pre><code>&lt;header class="intro-header" style="&lt;?php the_post_thumbnail(); ?&gt;"&gt; </code></pre>
[ { "answer_id": 244724, "author": "The Maniac", "author_id": 10966, "author_profile": "https://wordpress.stackexchange.com/users/10966", "pm_score": 0, "selected": false, "text": "<p>The function <code>the_post_thumbnail</code> returns the entire HTML for the image. You will need to use <a href=\"https://codex.wordpress.org/Function_Reference/get_post_thumbnail_id\" rel=\"nofollow noreferrer\"><code>wp_get_post_thumbnail_id</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_image_src</code></a> in combination to get the image's url.</p>\n\n<p>Here's a helper function I usually throw into <code>functions.php</code> when I'm building a theme to make this easier:</p>\n\n<pre><code>function mytheme_get_image_url( $size = 'full' ) {\n $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), $size );\n return $image_data[0];\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&lt;header class=\"intro-header\" style=\"background-image: url('&lt;?php echo mytheme_get_image_url(); ?&gt;')\"&gt;\n</code></pre>\n" }, { "answer_id": 244725, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>It sounds like you're looking for <a href=\"https://codex.wordpress.org/Function_Reference/the_post_thumbnail_url\" rel=\"nofollow noreferrer\">the_post_thumbnail_url()</a>:</p>\n\n<pre><code>&lt;header class=\"intro-header\" style=\"background-image: url('&lt;?php the_post_thumbnail_url(); ?&gt;')\"&gt;\n</code></pre>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244722", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I have an HTML code here → ``` <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('img/home-bg.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="site-heading"> <h1> Clean Blog </h1> <hr class="small"> <span class="subheading">A Clean Blog Theme by Start Bootstrap</span> </div> </div> </div> </div> </header> ``` I was trying to convert this into WP dynamically. How to convert this dynamically → ``` <header class="intro-header" style="background-image: url('img/home-bg.jpg')"> ``` `style="background-image: url('img/home-bg.jpg')` → How to convert this dynamically so that the image in the background should come from wordpress features image section. I was trying this, but it didn't worked = ``` <header class="intro-header" style="<?php the_post_thumbnail(); ?>"> ```
It sounds like you're looking for [the\_post\_thumbnail\_url()](https://codex.wordpress.org/Function_Reference/the_post_thumbnail_url): ``` <header class="intro-header" style="background-image: url('<?php the_post_thumbnail_url(); ?>')"> ```
244,740
<p>I am trying to display a single attribute ('size') value on shop page. I used the following code to show all values, tried to adapt to to show a single attribute, but with no success...</p> <p>Can you please help me adapt the code to only display values of the attribute 'size'?</p> <pre><code>// Get the attributes $attributes = $product-&gt;get_attributes(); // Start the loop foreach ( $attributes as $attribute ) : // Check and output, adopted from /templates/single-product/product-attributes.php if ( $attribute['is_taxonomy'] ) { $values = wc_get_product_terms( $product-&gt;id, $attribute['name'], array( 'fields' =&gt; 'names' ) ); echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values ); } else { // Convert pipes to commas and display values $values = array_map( 'trim', explode( WC_DELIMITER, $attribute['value'] ) ); echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values ); } endforeach; </code></pre> <p>Can you please let me know how to modify it</p>
[ { "answer_id": 244767, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 5, "selected": true, "text": "<p>Just use <code>global $product</code> then use <code>get_attribute()</code> method of that product object, like below-</p>\n\n<pre><code>$size = $product-&gt;get_attribute( 'pa_size' );\n</code></pre>\n\n<p>And you can also get that by below code-</p>\n\n<pre><code>global $product;\n$size = array_shift( wc_get_product_terms( $product-&gt;id, 'pa_size', array( 'fields' =&gt; 'names' ) ) );\n</code></pre>\n\n<p>Rememeber you need to use must the <code>global $product</code>.</p>\n" }, { "answer_id": 308678, "author": "bhavik", "author_id": 147003, "author_profile": "https://wordpress.stackexchange.com/users/147003", "pm_score": -1, "selected": false, "text": "<pre><code>$product = wc_get_product();\necho $product-&gt;get_attribute( 'Size' );\n</code></pre>\n" } ]
2016/11/01
[ "https://wordpress.stackexchange.com/questions/244740", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106110/" ]
I am trying to display a single attribute ('size') value on shop page. I used the following code to show all values, tried to adapt to to show a single attribute, but with no success... Can you please help me adapt the code to only display values of the attribute 'size'? ``` // Get the attributes $attributes = $product->get_attributes(); // Start the loop foreach ( $attributes as $attribute ) : // Check and output, adopted from /templates/single-product/product-attributes.php if ( $attribute['is_taxonomy'] ) { $values = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ); echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values ); } else { // Convert pipes to commas and display values $values = array_map( 'trim', explode( WC_DELIMITER, $attribute['value'] ) ); echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values ); } endforeach; ``` Can you please let me know how to modify it
Just use `global $product` then use `get_attribute()` method of that product object, like below- ``` $size = $product->get_attribute( 'pa_size' ); ``` And you can also get that by below code- ``` global $product; $size = array_shift( wc_get_product_terms( $product->id, 'pa_size', array( 'fields' => 'names' ) ) ); ``` Rememeber you need to use must the `global $product`.
244,789
<p>can anyone help me to sort Posts list in WP-admin by wp_posts table field like comment_status.</p> <p>I know, that we can easy sort by meta field key, but cannot find any way how to sort by wp_posts table actual field.</p> <p>If we dig in to source code of WP Query, we can find that there are allowed only these types of keys - </p> <pre><code> $allowed_keys = array( 'name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count', 'type' ); </code></pre> <p><a href="https://github.com/WordPress/WordPress/blob/9d123aa326a908ff8ed6170e0fea5d85a4b1619f/wp-includes/query.php#L2719" rel="nofollow noreferrer">https://github.com/WordPress/WordPress/blob/9d123aa326a908ff8ed6170e0fea5d85a4b1619f/wp-includes/query.php#L2719</a></p> <p>Is there any way how to override them?</p> <p>This is how I can sort by meta_key, but I need to sort by actual table field.</p> <pre><code>add_filter('manage_edit-post_sortable_columns', 'jepc_add_comments_column_table_sorting'); add_filter('request', 'jepc_column_sort'); function jepc_add_comments_column_table_sorting($columns) { $columns['comment_status'] = 'comment_status'; return $columns; } function jepc_column_sort($vars) { if (isset( $vars['orderby']) &amp;&amp; 'comment_status' == $vars['orderby']) { $vars = array_merge( $vars, array( 'meta_key' =&gt; 'comment_status', 'orderby' =&gt; 'meta_value' )); } return $vars; } </code></pre> <p>Thanks.</p>
[ { "answer_id": 244807, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>Here's a way to add an extra <em>Comment Status</em> field to the posts list table:</p>\n\n<pre><code>add_filter('manage_post_posts_columns', function ( $columns ) \n{\n $_columns = [];\n\n foreach( (array) $columns as $key =&gt; $label )\n {\n $_columns[$key] = $label; \n if( 'title' === $key )\n $_columns['wpse_comment_status'] = esc_html__( 'Comment Status', 'mydomain' );\n }\n return $_columns;\n} );\n\nadd_action( 'manage_post_posts_custom_column', function ( $column_name, $post_id ) \n{\n if ( $column_name == 'wpse_comment_status')\n echo get_post_field( 'comment_status', $post_id ); \n\n}, 10, 2 );\n</code></pre>\n\n<p>Here's how we can add a support for <em>comment status</em> ordering through the <code>posts_orderby</code> filter:</p>\n\n<pre><code>add_filter( 'manage_edit-post_sortable_columns', function ( $columns ) \n{\n $columns['wpse_comment_status'] = 'comment_status';\n return $columns;\n} );\n\nadd_filter( 'posts_orderby', function( $orderby, \\WP_Query $q ) use ( &amp;$wpdb )\n{ \n $_orderby = $q-&gt;get( 'orderby' );\n $_order = $q-&gt;get( 'order' );\n\n if( \n is_admin() \n &amp;&amp; $q-&gt;is_main_query() \n &amp;&amp; did_action( 'load-edit.php' )\n &amp;&amp; 'comment_status' === $_orderby \n )\n $orderby = \" {$wpdb-&gt;posts}.comment_status \" \n . ( 'ASC' === strtoupper( $_order ) ? 'ASC' : 'DESC' )\n . \", {$wpdb-&gt;posts}.ID DESC \";\n\n return $orderby;\n}, 10, 2 );\n</code></pre>\n\n<p>where we sub-order by the post ID.</p>\n\n<p>Here's an example output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QhvZK.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QhvZK.jpg\" alt=\"status\"></a></p>\n\n<p>PS: Since WordPress 4.5 (<a href=\"https://core.trac.wordpress.org/ticket/35601\" rel=\"nofollow noreferrer\">#35601</a>) it's possible to filter <code>WP_Query</code> by <code>comment_status</code> and <code>ping_status</code>, so you should be able to implement such filtering for your the posts list table, as well</p>\n" }, { "answer_id": 244909, "author": "Janiis", "author_id": 43543, "author_profile": "https://wordpress.stackexchange.com/users/43543", "pm_score": 0, "selected": false, "text": "<p>Awesome! I have modified code to meet my requirements.</p>\n\n<pre><code>// Sort columns by WP_posts table fields - comment_status and ping_status\nadd_filter( 'posts_orderby', function( $orderby, \\WP_Query $q ) use ( &amp;$wpdb ) {\n\n $_orderby = $q-&gt;get( 'orderby' );\n $_order = $q-&gt;get( 'order' );\n\n if ($_orderby != 'comment_status' &amp;&amp; $_orderby != 'ping_status') {\n return $orderby;\n }\n\n if( $q-&gt;is_main_query() &amp;&amp; did_action('load-edit.php')) {\n $orderby = \" {$wpdb-&gt;posts}.{$_orderby} \"\n . ( 'ASC' === strtoupper( $_order ) ? 'ASC' : 'DESC' )\n . \", {$wpdb-&gt;posts}.ID DESC \";\n }\n\n return $orderby;\n\n}, 10, 2);\n</code></pre>\n\n<p>For those who want to use the code in older versions of PHP.</p>\n\n<pre><code>add_filter( 'posts_orderby', 'jepc_comment_status_column_sort', 10, 2);\n\nfunction jepc_comment_status_column_sort($orderby, \\WP_Query $q) {\n\n global $wpdb;\n\n $_orderby = $q-&gt;get( 'orderby' );\n $_order = $q-&gt;get( 'order' );\n\n if ($_orderby != 'comment_status' &amp;&amp; $_orderby != 'ping_status') {\n return $orderby;\n }\n\n if( $q-&gt;is_main_query() &amp;&amp; did_action('load-edit.php')) {\n $orderby = \" {$wpdb-&gt;posts}.{$_orderby} \"\n . ( 'ASC' === strtoupper( $_order ) ? 'ASC' : 'DESC' )\n . \", {$wpdb-&gt;posts}.ID DESC \";\n }\n\n return $orderby;\n\n}\n</code></pre>\n\n<p>Thanks, you are awesome!</p>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/244789", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43543/" ]
can anyone help me to sort Posts list in WP-admin by wp\_posts table field like comment\_status. I know, that we can easy sort by meta field key, but cannot find any way how to sort by wp\_posts table actual field. If we dig in to source code of WP Query, we can find that there are allowed only these types of keys - ``` $allowed_keys = array( 'name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count', 'type' ); ``` <https://github.com/WordPress/WordPress/blob/9d123aa326a908ff8ed6170e0fea5d85a4b1619f/wp-includes/query.php#L2719> Is there any way how to override them? This is how I can sort by meta\_key, but I need to sort by actual table field. ``` add_filter('manage_edit-post_sortable_columns', 'jepc_add_comments_column_table_sorting'); add_filter('request', 'jepc_column_sort'); function jepc_add_comments_column_table_sorting($columns) { $columns['comment_status'] = 'comment_status'; return $columns; } function jepc_column_sort($vars) { if (isset( $vars['orderby']) && 'comment_status' == $vars['orderby']) { $vars = array_merge( $vars, array( 'meta_key' => 'comment_status', 'orderby' => 'meta_value' )); } return $vars; } ``` Thanks.
Here's a way to add an extra *Comment Status* field to the posts list table: ``` add_filter('manage_post_posts_columns', function ( $columns ) { $_columns = []; foreach( (array) $columns as $key => $label ) { $_columns[$key] = $label; if( 'title' === $key ) $_columns['wpse_comment_status'] = esc_html__( 'Comment Status', 'mydomain' ); } return $_columns; } ); add_action( 'manage_post_posts_custom_column', function ( $column_name, $post_id ) { if ( $column_name == 'wpse_comment_status') echo get_post_field( 'comment_status', $post_id ); }, 10, 2 ); ``` Here's how we can add a support for *comment status* ordering through the `posts_orderby` filter: ``` add_filter( 'manage_edit-post_sortable_columns', function ( $columns ) { $columns['wpse_comment_status'] = 'comment_status'; return $columns; } ); add_filter( 'posts_orderby', function( $orderby, \WP_Query $q ) use ( &$wpdb ) { $_orderby = $q->get( 'orderby' ); $_order = $q->get( 'order' ); if( is_admin() && $q->is_main_query() && did_action( 'load-edit.php' ) && 'comment_status' === $_orderby ) $orderby = " {$wpdb->posts}.comment_status " . ( 'ASC' === strtoupper( $_order ) ? 'ASC' : 'DESC' ) . ", {$wpdb->posts}.ID DESC "; return $orderby; }, 10, 2 ); ``` where we sub-order by the post ID. Here's an example output: [![status](https://i.stack.imgur.com/QhvZK.jpg)](https://i.stack.imgur.com/QhvZK.jpg) PS: Since WordPress 4.5 ([#35601](https://core.trac.wordpress.org/ticket/35601)) it's possible to filter `WP_Query` by `comment_status` and `ping_status`, so you should be able to implement such filtering for your the posts list table, as well
244,802
<p>I'm using $wpdb->insert to insert data to my plugin table. How can I get the id of the new line I Just insert. Because I have a lot of users that add data to the table I can't use $wpdb->insert_id Because it's not necessary the last one. </p>
[ { "answer_id": 244809, "author": "Niels van Renselaar", "author_id": 67313, "author_profile": "https://wordpress.stackexchange.com/users/67313", "pm_score": 4, "selected": false, "text": "<p>There is no other way, but I can not see how you need any other way then this. I believe that the insert ID accessed by $wpdb is the last ID by this instance of WPDB, other inserts should not affect that but I'm not sure.</p>\n\n<pre><code>&lt;?php\n\n $wpdb-&gt;insert(\"QUERY\");\n\n $this_insert = $wpdb-&gt;insert_id;\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 375532, "author": "Hugo R", "author_id": 125294, "author_profile": "https://wordpress.stackexchange.com/users/125294", "pm_score": 1, "selected": false, "text": "<p>$wpdb-&gt;insert_id is global withint the database session. since Wordpress creates a new session per user session this is not a problem, even when using a connection pooling.\nthe only caveat is that this variable will always have the last inserted auto-increment ID, so you have to check after each insert.\nIf you really want to capture the list of new inserted records, you can do it inside a stored procedure and capture it in a transaction. or inside a trigger.</p>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/244802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62945/" ]
I'm using $wpdb->insert to insert data to my plugin table. How can I get the id of the new line I Just insert. Because I have a lot of users that add data to the table I can't use $wpdb->insert\_id Because it's not necessary the last one.
There is no other way, but I can not see how you need any other way then this. I believe that the insert ID accessed by $wpdb is the last ID by this instance of WPDB, other inserts should not affect that but I'm not sure. ``` <?php $wpdb->insert("QUERY"); $this_insert = $wpdb->insert_id; ?> ```
244,811
<p>I'm a designer not a developer.</p> <p>A client is using a free 3rd party Wordpress theme, and when The Events Calendar is installed, the default events calendar does not load @ <a href="http://www.banksia.wa.edu.au/events" rel="nofollow noreferrer">/events</a>.</p> <p>The body tag looks correct:</p> <p><code>&lt;body class="archive post-type-archive post-type-archive-tribe_events logged-in admin-bar no-customize-support tribe-filter-live events-gridview events-archive tribe-events-style-full tribe-events-style-theme tribe-theme-peachclub-theme page-template-page-php singular" &gt;</code></p> <p>A working events calendar page on another website has a body tag of:</p> <p><code>&lt;body class="archive post-type-archive post-type-archive-tribe_events tribe-filter-live events-gridview events-archive tribe-events-style-full tribe-events-style-theme tribe-theme-parent-ManiaFramework tribe-theme-child-AutoRacing page-template-page-php singular"&gt;</code></p> <p>Additionally, if I visit Dashboard > Events > Settings, I don't see any settings:</p> <p><a href="https://i.stack.imgur.com/4WLHY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4WLHY.png" alt="enter image description here"></a></p> <p>If I change the theme to TwentyFifteen, the calendar shows at <code>/events</code>, and the Events settings page shows.</p> <p>I've asked the plugin author for help, but they say the theme is not compatible with The Events Calendar.</p> <p>I'm wondering if this is because the theme and the plugin conflict over slugs in some way?</p> <p>How would I test that the theme uses perhaps custom post type slugs used by The Events Calendar?</p> <p>I tried deactivting The Events Calendar, and adding the following code in my theme's <code>functions.php</code>:</p> <pre><code>if ( ! function_exists( 'unregister_post_type' ) ) : function unregister_post_type() { global $wp_post_types; if ( isset( $wp_post_types[ 'event' ] ) ) { unset( $wp_post_types[ 'event' ] ); return true; } if ( isset( $wp_post_types[ 'events' ] ) ) { unset( $wp_post_types[ 'events' ] ); return true; } return false; } endif; add_action('init', 'unregister_post_type'); </code></pre> <p>After uploading <code>functions.php</code>, and reloading the home page, <code>/events</code> produced a 404, which I thought was promising, but reactivating The Events Calendar did not make the calendar load @ <code>/events</code>.</p> <p>Help appreciated.</p>
[ { "answer_id": 245092, "author": "Sandun", "author_id": 105973, "author_profile": "https://wordpress.stackexchange.com/users/105973", "pm_score": 1, "selected": false, "text": "<p>Disable the WordPress event plugin.</p>\n\n<p>Use following code in functions.php to find your theme has events function.</p>\n\n<pre><code>if ( post_type_exists( 'events' ) ) {\n echo 'the Event post type exists';\n}else{\n echo 'the Event post type does not exists';\n}\n</code></pre>\n\n<ol>\n<li><p>If you find theme has events custom post type, find where your theme register the custom post type. Most probably it is functions.php. Check functions.php has <code>register_post_type( 'events', $args );</code> . $args variable may be has different name. So find where is locating <code>register_post_type( 'events',</code> using IDE or pressing ctrl+f5.</p></li>\n<li><p>If you found it in functions.php create a child theme. Just a google search, you can find how to create a child theme even you are not a WordPress developer. It is not hard.</p></li>\n<li><p>Then copied functions.php file to child theme. Then remove the <code>register_post_type( 'events', $args );</code> parts from it.</p></li>\n</ol>\n" }, { "answer_id": 245143, "author": "Svetoslav Marinov", "author_id": 26487, "author_profile": "https://wordpress.stackexchange.com/users/26487", "pm_score": 0, "selected": false, "text": "<p>Ask the theme developer or the plugin developer to prefix their custom post type. If you can't wait do it yourself by starting with the code that's smaller I am thinking the theme.</p>\n" }, { "answer_id": 245148, "author": "cowgill", "author_id": 5549, "author_profile": "https://wordpress.stackexchange.com/users/5549", "pm_score": 0, "selected": false, "text": "<p>You can't fix what you don't know is broken.</p>\n\n<p><strong>View the Error Logs</strong></p>\n\n<p>Do you have accesss to their webhost?</p>\n\n<p>It's likely available through cPanel. See what type of errors are displaying. It could be a similarly named PHP function or something else causing the issue.</p>\n\n<p><strong>Confirm Post Type Name Collision</strong></p>\n\n<p>If you have access to the database, it's easy to see if the post types conflict or not. </p>\n\n<ol>\n<li>Login to your database => cPanel => phpMyAdmin</li>\n<li>Open the correct database and select the wp_posts table</li>\n<li>View the contents and scroll to the right until you see the <code>post_type</code> column</li>\n<li>Look to see if there are multiple different post types</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/LGNu1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LGNu1.png\" alt=\"wordpress posts table post type\"></a></p>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/244811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
I'm a designer not a developer. A client is using a free 3rd party Wordpress theme, and when The Events Calendar is installed, the default events calendar does not load @ [/events](http://www.banksia.wa.edu.au/events). The body tag looks correct: `<body class="archive post-type-archive post-type-archive-tribe_events logged-in admin-bar no-customize-support tribe-filter-live events-gridview events-archive tribe-events-style-full tribe-events-style-theme tribe-theme-peachclub-theme page-template-page-php singular" >` A working events calendar page on another website has a body tag of: `<body class="archive post-type-archive post-type-archive-tribe_events tribe-filter-live events-gridview events-archive tribe-events-style-full tribe-events-style-theme tribe-theme-parent-ManiaFramework tribe-theme-child-AutoRacing page-template-page-php singular">` Additionally, if I visit Dashboard > Events > Settings, I don't see any settings: [![enter image description here](https://i.stack.imgur.com/4WLHY.png)](https://i.stack.imgur.com/4WLHY.png) If I change the theme to TwentyFifteen, the calendar shows at `/events`, and the Events settings page shows. I've asked the plugin author for help, but they say the theme is not compatible with The Events Calendar. I'm wondering if this is because the theme and the plugin conflict over slugs in some way? How would I test that the theme uses perhaps custom post type slugs used by The Events Calendar? I tried deactivting The Events Calendar, and adding the following code in my theme's `functions.php`: ``` if ( ! function_exists( 'unregister_post_type' ) ) : function unregister_post_type() { global $wp_post_types; if ( isset( $wp_post_types[ 'event' ] ) ) { unset( $wp_post_types[ 'event' ] ); return true; } if ( isset( $wp_post_types[ 'events' ] ) ) { unset( $wp_post_types[ 'events' ] ); return true; } return false; } endif; add_action('init', 'unregister_post_type'); ``` After uploading `functions.php`, and reloading the home page, `/events` produced a 404, which I thought was promising, but reactivating The Events Calendar did not make the calendar load @ `/events`. Help appreciated.
Disable the WordPress event plugin. Use following code in functions.php to find your theme has events function. ``` if ( post_type_exists( 'events' ) ) { echo 'the Event post type exists'; }else{ echo 'the Event post type does not exists'; } ``` 1. If you find theme has events custom post type, find where your theme register the custom post type. Most probably it is functions.php. Check functions.php has `register_post_type( 'events', $args );` . $args variable may be has different name. So find where is locating `register_post_type( 'events',` using IDE or pressing ctrl+f5. 2. If you found it in functions.php create a child theme. Just a google search, you can find how to create a child theme even you are not a WordPress developer. It is not hard. 3. Then copied functions.php file to child theme. Then remove the `register_post_type( 'events', $args );` parts from it.
244,832
<p>I have made my own routes by using <code>add_rewrite_rule</code> method. I would like to know if it is possible using given method to force all my created routes to redirect to URL where there is trailing slash in the end. For example if i do </p> <p><code>add_rewrite_rule('^my-route/', 'index.php?_my_route=1', 'top')</code> </p> <p>or </p> <p><code>add_rewrite_rule('^my-route', 'index.php?_my_route=1', 'top')</code> </p> <p>and i make a call to <code>http://site.dev/my-route</code> then it does not redirect it to <code>http://site.dev/my-route/</code>. If it is possible then i would be thankful for sharing :).</p>
[ { "answer_id": 244834, "author": "blackstar", "author_id": 106156, "author_profile": "https://wordpress.stackexchange.com/users/106156", "pm_score": -1, "selected": false, "text": "<p>If think this will work for you\nAdd this is functions.php </p>\n\n<pre><code>add_action( 'init',function(){\n global $wp;\n $current_url = home_url(add_query_arg(array(),$wp-&gt;request));\n $last_char = substr($current_url, -1); \n\n if($last_char == '/' &amp;&amp; filter_var($current_url, FILTER_VALIDATE_URL)){\n wp_redirect( trailingslashit( $current_url ) );\n }\n});\n</code></pre>\n" }, { "answer_id": 361114, "author": "sagar shinde", "author_id": 184576, "author_profile": "https://wordpress.stackexchange.com/users/184576", "pm_score": 0, "selected": false, "text": "<p>just change your rule to this</p>\n\n<pre><code>add_rewrite_rule('^my-route?$', 'index.php?_my_route=1', 'top')\n</code></pre>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/244832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91525/" ]
I have made my own routes by using `add_rewrite_rule` method. I would like to know if it is possible using given method to force all my created routes to redirect to URL where there is trailing slash in the end. For example if i do `add_rewrite_rule('^my-route/', 'index.php?_my_route=1', 'top')` or `add_rewrite_rule('^my-route', 'index.php?_my_route=1', 'top')` and i make a call to `http://site.dev/my-route` then it does not redirect it to `http://site.dev/my-route/`. If it is possible then i would be thankful for sharing :).
just change your rule to this ``` add_rewrite_rule('^my-route?$', 'index.php?_my_route=1', 'top') ```
244,848
<p>Apologies if this has been asked before, but I couldn't find, specifically, another question that gets me going in the right direction.</p> <p>I'm creating a series of multiple loops on a page. I also created another taxonomy for posts, "Issue". One of the loops I'm trying to create, I'd like to query this taxonomy and a particular category, "featured". But taking that a step further, I first need to figure out the "newest" issue and then offset by one. </p> <p>Example: In my custom taxonomy, I have terms "Issue 1", "Issue 2", and "Issue 3". All created chronologically. This loop should find the newest term in this taxonomy (read: highest ID), then exclude it from the loop, then given what's left, only show posts in the category "Featured".</p> <p>Here's the code I've code up with thus far:</p> <pre><code>$issue = get_terms('issue', array( 'orderby' =&gt; 'none', 'order' =&gt; 'DESC', 'number' =&gt; 1, 'offset' =&gt; 1 ) ); $latest_issue = $issue-&gt;slug; $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; '5', 'order_by' =&gt; 'date', 'order' =&gt; 'DESC', 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; array( 'featured' ), ), array( 'taxonomy' =&gt; 'issue', 'field' =&gt; 'slug', 'terms' =&gt; array( $latest_issue ) ) ) ); $query = new WP_Query( $args ); echo '&lt;div class="home-middle widget-area"&gt;'; echo '&lt;h4 class="widget-title widgettitle"&gt;&lt;span&gt;From the Archives&lt;/span&gt;&lt;/h4&gt;'; if (have_posts()) { while( $query-&gt;have_posts() ) { $query-&gt;the_post(); echo '&lt;h4&gt;' . get_the_title() . '&lt;/h4&gt;'; } } else { echo 'No posts in the Archive'; } echo '&lt;/div&gt;'; wp_reset_postdata(); </code></pre> <hr> <hr> <p><strong>UPDATE EDIT</strong></p> <p>Thanks @adelval for pointing out the errors in the query. I've since updated that and have made some progress. My problem now is that my query gets only the posts in the newest (by newest, I mean the one with the highest taxonomy ID) taxonomy term and then displays it 5 times. <a href="http://csl.nsta.org/development/" rel="nofollow noreferrer">You can see it in action, at the bottom of the page, here</a> (under the section heading <em>From the Archives</em>). And here's the new code:</p> <pre><code>$issue = get_terms(array( 'taxonomy' =&gt; 'issue', 'hide_empty' =&gt; false, 'orderby' =&gt; 'id', 'order' =&gt; 'DESC', 'number' =&gt; 1 ) ); $latest_issue = $issue[0]-&gt;slug; $args = array( 'post_type' =&gt; 'post', 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; array( 'featured' ), ), array( 'taxonomy' =&gt; 'issue', // My Custom Taxonomy 'terms' =&gt; array( $latest_issue ), // My Taxonomy Term that I wanted to exclude 'field' =&gt; 'slug', // Whether I am passing term Slug or term ID 'operator' =&gt; 'NOT IN', ) ) ); $query = new WP_Query( $args ); echo '&lt;div class="home-middle widget-area"&gt;'; echo '&lt;h4 class="widget-title widgettitle"&gt;&lt;span&gt;From the Archives&lt;/span&gt;&lt;/h4&gt;'; if ( $query-&gt;post_count &gt; 0 ){ foreach ( $query-&gt;get_posts() as $post ): echo '&lt;article class="post type-post status-publish format-standard has-post-thumbnail entry"&gt;'; echo '&lt;a href="' . get_the_permalink() . '" class="alignleft" aria-hidden="true"&gt;'; echo the_post_thumbnail( 'home-middle' ); echo '&lt;time class="entry-time" itemprop="datePublished"&gt;' . get_the_date() . '&lt;/time&gt;'; echo '&lt;/a&gt;'; echo '&lt;h4&gt;' . get_the_title() . '&lt;/h4&gt;'; echo get_the_excerpt(); echo '&lt;/article&gt;'; endforeach; } else { echo 'No posts in the Archive'; } echo '&lt;/div&gt;'; wp_reset_postdata(); </code></pre> <p>To be clear on what I'm trying to accomplish, this function should:</p> <ol> <li>Get all terms of the taxonomy issue. <em>Done</em></li> <li>Determine and set as a variable the newest taxonomy term of issue (I currently have "Issue 1", "Issue 2", and "Issue 3", all created chronologically. "Issue 3" is the newest taxonomy term of issue). <em>Done</em></li> <li>Create a query that uses both categories and issues; in that query, exclude the taxonomy term that was found in #2 above. <em>Needs refinement</em></li> </ol> <p>Thanks for the help!</p>
[ { "answer_id": 244834, "author": "blackstar", "author_id": 106156, "author_profile": "https://wordpress.stackexchange.com/users/106156", "pm_score": -1, "selected": false, "text": "<p>If think this will work for you\nAdd this is functions.php </p>\n\n<pre><code>add_action( 'init',function(){\n global $wp;\n $current_url = home_url(add_query_arg(array(),$wp-&gt;request));\n $last_char = substr($current_url, -1); \n\n if($last_char == '/' &amp;&amp; filter_var($current_url, FILTER_VALIDATE_URL)){\n wp_redirect( trailingslashit( $current_url ) );\n }\n});\n</code></pre>\n" }, { "answer_id": 361114, "author": "sagar shinde", "author_id": 184576, "author_profile": "https://wordpress.stackexchange.com/users/184576", "pm_score": 0, "selected": false, "text": "<p>just change your rule to this</p>\n\n<pre><code>add_rewrite_rule('^my-route?$', 'index.php?_my_route=1', 'top')\n</code></pre>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/244848", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5295/" ]
Apologies if this has been asked before, but I couldn't find, specifically, another question that gets me going in the right direction. I'm creating a series of multiple loops on a page. I also created another taxonomy for posts, "Issue". One of the loops I'm trying to create, I'd like to query this taxonomy and a particular category, "featured". But taking that a step further, I first need to figure out the "newest" issue and then offset by one. Example: In my custom taxonomy, I have terms "Issue 1", "Issue 2", and "Issue 3". All created chronologically. This loop should find the newest term in this taxonomy (read: highest ID), then exclude it from the loop, then given what's left, only show posts in the category "Featured". Here's the code I've code up with thus far: ``` $issue = get_terms('issue', array( 'orderby' => 'none', 'order' => 'DESC', 'number' => 1, 'offset' => 1 ) ); $latest_issue = $issue->slug; $args = array( 'post_type' => 'post', 'posts_per_page' => '5', 'order_by' => 'date', 'order' => 'DESC', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'featured' ), ), array( 'taxonomy' => 'issue', 'field' => 'slug', 'terms' => array( $latest_issue ) ) ) ); $query = new WP_Query( $args ); echo '<div class="home-middle widget-area">'; echo '<h4 class="widget-title widgettitle"><span>From the Archives</span></h4>'; if (have_posts()) { while( $query->have_posts() ) { $query->the_post(); echo '<h4>' . get_the_title() . '</h4>'; } } else { echo 'No posts in the Archive'; } echo '</div>'; wp_reset_postdata(); ``` --- --- **UPDATE EDIT** Thanks @adelval for pointing out the errors in the query. I've since updated that and have made some progress. My problem now is that my query gets only the posts in the newest (by newest, I mean the one with the highest taxonomy ID) taxonomy term and then displays it 5 times. [You can see it in action, at the bottom of the page, here](http://csl.nsta.org/development/) (under the section heading *From the Archives*). And here's the new code: ``` $issue = get_terms(array( 'taxonomy' => 'issue', 'hide_empty' => false, 'orderby' => 'id', 'order' => 'DESC', 'number' => 1 ) ); $latest_issue = $issue[0]->slug; $args = array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'featured' ), ), array( 'taxonomy' => 'issue', // My Custom Taxonomy 'terms' => array( $latest_issue ), // My Taxonomy Term that I wanted to exclude 'field' => 'slug', // Whether I am passing term Slug or term ID 'operator' => 'NOT IN', ) ) ); $query = new WP_Query( $args ); echo '<div class="home-middle widget-area">'; echo '<h4 class="widget-title widgettitle"><span>From the Archives</span></h4>'; if ( $query->post_count > 0 ){ foreach ( $query->get_posts() as $post ): echo '<article class="post type-post status-publish format-standard has-post-thumbnail entry">'; echo '<a href="' . get_the_permalink() . '" class="alignleft" aria-hidden="true">'; echo the_post_thumbnail( 'home-middle' ); echo '<time class="entry-time" itemprop="datePublished">' . get_the_date() . '</time>'; echo '</a>'; echo '<h4>' . get_the_title() . '</h4>'; echo get_the_excerpt(); echo '</article>'; endforeach; } else { echo 'No posts in the Archive'; } echo '</div>'; wp_reset_postdata(); ``` To be clear on what I'm trying to accomplish, this function should: 1. Get all terms of the taxonomy issue. *Done* 2. Determine and set as a variable the newest taxonomy term of issue (I currently have "Issue 1", "Issue 2", and "Issue 3", all created chronologically. "Issue 3" is the newest taxonomy term of issue). *Done* 3. Create a query that uses both categories and issues; in that query, exclude the taxonomy term that was found in #2 above. *Needs refinement* Thanks for the help!
just change your rule to this ``` add_rewrite_rule('^my-route?$', 'index.php?_my_route=1', 'top') ```
244,867
<p>I'm looking through _s (underscores) starter theme and see that they're using esc_html for nearly everything. Just an example from functions.php</p> <pre><code>register_nav_menus( array( 'primary' =&gt; esc_html__( 'Primary', '_s' ), ) ); register_sidebar( array( 'name' =&gt; esc_html__( 'Sidebar', '_s' ), 'id' =&gt; 'sidebar-1', 'description' =&gt; esc_html__( 'Add widgets here.', '_s' ), 'before_widget' =&gt; '&lt;section id="%1$s" class="widget %2$s"&gt;', 'after_widget' =&gt; '&lt;/section&gt;', 'before_title' =&gt; '&lt;h2 class="widget-title"&gt;', 'after_title' =&gt; '&lt;/h2&gt;', ) ); </code></pre> <p>My current understanding of esc_html is to use it when we output either data from the database or user input. </p> <p><strong>Why escape the names of the menu and sidebar?</strong> </p> <p>It's only available to people that have access to the php files and it doesn't appear to be put into the db. I looked through the db and couldn't find anything related to the names, please correct me if I'm wrong.</p> <p><strong>Is the underscores theme just being overly cautious about everything?</strong></p> <p>Thanks</p>
[ { "answer_id": 244868, "author": "Nabil Kadimi", "author_id": 17187, "author_profile": "https://wordpress.stackexchange.com/users/17187", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/esc_html/#source\" rel=\"noreferrer\">esc_html()</a> does two things:</p>\n\n<ol>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_check_invalid_utf8/\" rel=\"noreferrer\">Checks for invalid UTF8 in a string.</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/_wp_specialchars/\" rel=\"noreferrer\">Converts a number of special characters into their HTML entities</a>, specifically deals with: &amp;, &lt;, >, “, and ‘.</li>\n</ol>\n\n<p>Using it instead of <code>__()</code>, <code>_e</code> and other i18n functions protects your website from possible errors that can occur with unaware translators who may use text that contains (1) invalid UTF8 characters or (2) unwanted HTML code. Trust me, many translators will be tempted to use some 'nice' HTML tags like <code>&lt;i&gt;</code>, <code>&lt;b&gt;</code> etc, even worse, they won't close them correctly.</p>\n" }, { "answer_id": 244871, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 3, "selected": false, "text": "<pre><code>esc_html__( string $text, string $domain = 'default' )\n</code></pre>\n\n<p>Retrieve the translation of $text and escapes it for safe use in HTML output.\nso <code>esc_html__()</code> use to make internationalize as well as security purpose </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/esc_html_2\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/esc_html_2</a></p>\n" }, { "answer_id": 286688, "author": "Mac", "author_id": 80070, "author_profile": "https://wordpress.stackexchange.com/users/80070", "pm_score": 2, "selected": false, "text": "<p>The waters are muddy here. OP's question asks about <strong><a href=\"https://developer.wordpress.org/reference/functions/esc_html/\" rel=\"nofollow noreferrer\">esc_html()</a></strong>, but his code clearly uses <strong><a href=\"https://codex.wordpress.org/Function_Reference/esc_html_2\" rel=\"nofollow noreferrer\">esc_html__()</a></strong>. These are not the same. The accepted answer is wrong: it refers to <strong>esc_html()</strong>, which deals with safely escaping HTML blocks. Kanon Chowdhury's reply should be the accepted answer, because OP's code deals with the I18n aspects of the Underscores WordPress starter theme (which uses the <strong>esc_html__()</strong> function).</p>\n" }, { "answer_id": 305405, "author": "Prashad", "author_id": 89669, "author_profile": "https://wordpress.stackexchange.com/users/89669", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\">esc_html()</a> and <a href=\"https://codex.wordpress.org/Function_Reference/esc_html_2\" rel=\"nofollow noreferrer\">esc_html__()</a> are <strong>NOT</strong> the same functions. The main difference is,\nesc_html() takes just one string and returns <strong>an escaped HTML</strong> string. On the other hand, esc_html__() takes 2 strings as parameters and returns <strong>a translated and escaped</strong> string.</p>\n\n<p>The accepted answer is incorrect, indeed.</p>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/244867", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48950/" ]
I'm looking through \_s (underscores) starter theme and see that they're using esc\_html for nearly everything. Just an example from functions.php ``` register_nav_menus( array( 'primary' => esc_html__( 'Primary', '_s' ), ) ); register_sidebar( array( 'name' => esc_html__( 'Sidebar', '_s' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Add widgets here.', '_s' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); ``` My current understanding of esc\_html is to use it when we output either data from the database or user input. **Why escape the names of the menu and sidebar?** It's only available to people that have access to the php files and it doesn't appear to be put into the db. I looked through the db and couldn't find anything related to the names, please correct me if I'm wrong. **Is the underscores theme just being overly cautious about everything?** Thanks
[esc\_html()](https://developer.wordpress.org/reference/functions/esc_html/#source) does two things: 1. [Checks for invalid UTF8 in a string.](https://developer.wordpress.org/reference/functions/wp_check_invalid_utf8/) 2. [Converts a number of special characters into their HTML entities](https://developer.wordpress.org/reference/functions/_wp_specialchars/), specifically deals with: &, <, >, “, and ‘. Using it instead of `__()`, `_e` and other i18n functions protects your website from possible errors that can occur with unaware translators who may use text that contains (1) invalid UTF8 characters or (2) unwanted HTML code. Trust me, many translators will be tempted to use some 'nice' HTML tags like `<i>`, `<b>` etc, even worse, they won't close them correctly.
244,874
<p>I have a WP installation in its own folder (<em>my-domain.com/site</em>) and I'm trying that site works over <em>my-domain.com</em>. I'm not moving the installation files, actually I'm just <a href="https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory" rel="nofollow noreferrer">giving to WP its own directory</a>.</p> <p>The WP installation is running over an <strong>IIS server</strong>. So I have a <strong>web.config</strong> file.</p> <p>I've already done the steps that Wordpress Codex says: </p> <ol> <li>Change the site address to <em>my-domain.com</em>.</li> <li>Copy (not move) the <em>index.php</em> and MOVE the <em>web.config</em>, both to root directory.</li> <li>In <em>index.php</em> (root directory) I've changed this line: <code>require( dirname( __FILE__ ) . '/site/wp-blog-header.php' );</code></li> </ol> <p>According <a href="https://codex.wordpress.org/Using_Permalinks#Permalinks_without_mod_rewrite" rel="nofollow noreferrer">WP Codex for Permalinks without mod_rewrite</a>, in the permalinks settings (in dashboard) I set to: <code>/index.php/%postname%/</code>. If I remove the <code>index.php</code> part from the permalinks settings doesn't work anymore.</p> <p>Right now my permalinks are working, but in this way: <em>my-domain.com/index.php/page_example</em>. I want to remove the "/index.php/" part from the url.</p> <p>In my <strong>web.config</strong> I have: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;rewrite&gt; &lt;rules&gt; &lt;rule name="wordpress" stopProcessing="true"&gt; &lt;match url=".*" /&gt; &lt;conditions logicalGrouping="MatchAll"&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /&gt; &lt;/conditions&gt; &lt;action type="Rewrite" url="index.php" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>I've tried even add a <code>&lt;clear/&gt;</code> <a href="https://wordpress.stackexchange.com/questions/181509/removing-index-php-iis-7-5-webconfig">before add the rule</a> but without success.</p> <p><strong>Note:</strong> If I left the site address (URL) with: <em>my-domain.com/site</em> and remove the "/index.php/" part from permalinks settings, the permalinks works good like this: <em>my-domain.com/page_example</em>.</p> <p>Any idea how to solve this? Maybe I'm missing some rules in the web.config</p>
[ { "answer_id": 244868, "author": "Nabil Kadimi", "author_id": 17187, "author_profile": "https://wordpress.stackexchange.com/users/17187", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/esc_html/#source\" rel=\"noreferrer\">esc_html()</a> does two things:</p>\n\n<ol>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_check_invalid_utf8/\" rel=\"noreferrer\">Checks for invalid UTF8 in a string.</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/_wp_specialchars/\" rel=\"noreferrer\">Converts a number of special characters into their HTML entities</a>, specifically deals with: &amp;, &lt;, >, “, and ‘.</li>\n</ol>\n\n<p>Using it instead of <code>__()</code>, <code>_e</code> and other i18n functions protects your website from possible errors that can occur with unaware translators who may use text that contains (1) invalid UTF8 characters or (2) unwanted HTML code. Trust me, many translators will be tempted to use some 'nice' HTML tags like <code>&lt;i&gt;</code>, <code>&lt;b&gt;</code> etc, even worse, they won't close them correctly.</p>\n" }, { "answer_id": 244871, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 3, "selected": false, "text": "<pre><code>esc_html__( string $text, string $domain = 'default' )\n</code></pre>\n\n<p>Retrieve the translation of $text and escapes it for safe use in HTML output.\nso <code>esc_html__()</code> use to make internationalize as well as security purpose </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/esc_html_2\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/esc_html_2</a></p>\n" }, { "answer_id": 286688, "author": "Mac", "author_id": 80070, "author_profile": "https://wordpress.stackexchange.com/users/80070", "pm_score": 2, "selected": false, "text": "<p>The waters are muddy here. OP's question asks about <strong><a href=\"https://developer.wordpress.org/reference/functions/esc_html/\" rel=\"nofollow noreferrer\">esc_html()</a></strong>, but his code clearly uses <strong><a href=\"https://codex.wordpress.org/Function_Reference/esc_html_2\" rel=\"nofollow noreferrer\">esc_html__()</a></strong>. These are not the same. The accepted answer is wrong: it refers to <strong>esc_html()</strong>, which deals with safely escaping HTML blocks. Kanon Chowdhury's reply should be the accepted answer, because OP's code deals with the I18n aspects of the Underscores WordPress starter theme (which uses the <strong>esc_html__()</strong> function).</p>\n" }, { "answer_id": 305405, "author": "Prashad", "author_id": 89669, "author_profile": "https://wordpress.stackexchange.com/users/89669", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\">esc_html()</a> and <a href=\"https://codex.wordpress.org/Function_Reference/esc_html_2\" rel=\"nofollow noreferrer\">esc_html__()</a> are <strong>NOT</strong> the same functions. The main difference is,\nesc_html() takes just one string and returns <strong>an escaped HTML</strong> string. On the other hand, esc_html__() takes 2 strings as parameters and returns <strong>a translated and escaped</strong> string.</p>\n\n<p>The accepted answer is incorrect, indeed.</p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244874", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73970/" ]
I have a WP installation in its own folder (*my-domain.com/site*) and I'm trying that site works over *my-domain.com*. I'm not moving the installation files, actually I'm just [giving to WP its own directory](https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory). The WP installation is running over an **IIS server**. So I have a **web.config** file. I've already done the steps that Wordpress Codex says: 1. Change the site address to *my-domain.com*. 2. Copy (not move) the *index.php* and MOVE the *web.config*, both to root directory. 3. In *index.php* (root directory) I've changed this line: `require( dirname( __FILE__ ) . '/site/wp-blog-header.php' );` According [WP Codex for Permalinks without mod\_rewrite](https://codex.wordpress.org/Using_Permalinks#Permalinks_without_mod_rewrite), in the permalinks settings (in dashboard) I set to: `/index.php/%postname%/`. If I remove the `index.php` part from the permalinks settings doesn't work anymore. Right now my permalinks are working, but in this way: *my-domain.com/index.php/page\_example*. I want to remove the "/index.php/" part from the url. In my **web.config** I have: ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="wordpress" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="index.php" /> </rule> </rules> </rewrite> </system.webServer> </configuration> ``` I've tried even add a `<clear/>` [before add the rule](https://wordpress.stackexchange.com/questions/181509/removing-index-php-iis-7-5-webconfig) but without success. **Note:** If I left the site address (URL) with: *my-domain.com/site* and remove the "/index.php/" part from permalinks settings, the permalinks works good like this: *my-domain.com/page\_example*. Any idea how to solve this? Maybe I'm missing some rules in the web.config
[esc\_html()](https://developer.wordpress.org/reference/functions/esc_html/#source) does two things: 1. [Checks for invalid UTF8 in a string.](https://developer.wordpress.org/reference/functions/wp_check_invalid_utf8/) 2. [Converts a number of special characters into their HTML entities](https://developer.wordpress.org/reference/functions/_wp_specialchars/), specifically deals with: &, <, >, “, and ‘. Using it instead of `__()`, `_e` and other i18n functions protects your website from possible errors that can occur with unaware translators who may use text that contains (1) invalid UTF8 characters or (2) unwanted HTML code. Trust me, many translators will be tempted to use some 'nice' HTML tags like `<i>`, `<b>` etc, even worse, they won't close them correctly.
244,890
<p>I just added following code to functions.php.</p> <pre><code>$my_post = array( 'post_title' =&gt; 'Test Title 02', 'post_content' =&gt; 'Test Des 02', 'post_status' =&gt; 'publish', 'post_author' =&gt; 1 ); wp_insert_post( $my_post ); </code></pre> <p>There are 8 posts were created just one page load. Seems like functions.php file is called 8 time for just one page load. Why is that? How it happens?</p>
[ { "answer_id": 244892, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>Add a plugin like <a href=\"https://wordpress.org/plugins/kint-debugger/\" rel=\"nofollow noreferrer\"><code>Kint Debugger</code></a> + <a href=\"https://wordpress.org/plugins/debug-bar/\" rel=\"nofollow noreferrer\"><code>Debug Bar</code></a> and add the following code to your <code>functions.php</code>.</p>\n\n<pre><code> global $wp;\n ob_start('kint_debug_ob');\n d($wp);\n ob_end_flush();\n</code></pre>\n\n<p>When you check the Debug Bar you should see the backtrace which will tell you which order functions were fired in. Loading 8 times is quite high for a single request.</p>\n\n<p>There is also a backtrace function you can use that is less detailed if you don't want to go the plugin route - <a href=\"https://developer.wordpress.org/reference/functions/wp_debug_backtrace_summary/\" rel=\"nofollow noreferrer\"><code>wp_debug_backtrace_summary</code></a>.</p>\n\n<pre><code>echo \"&lt;!----- BACKTRACE / START -----&gt;\";\n\nprint_r ( wp_debug_backtrace_summary() );\n\necho \"&lt;!----- BACKTRACE / END -----&gt;\";\n</code></pre>\n\n<p>It is a bit odd to just have a random <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\"><code>wp_insert_post</code></a> in your <code>functions.php</code> so perhaps wrapping your logic in a hook like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow noreferrer\"><code>init</code></a> could help in the mean time.</p>\n\n<p>There is also a possibility this is not just a single request. <a href=\"https://codex.wordpress.org/Function_Reference/wp_heartbeat_settings\" rel=\"nofollow noreferrer\"><code>heartbeats</code></a> will ping the backend if you're in the admin section and It's possible <a href=\"https://codex.wordpress.org/Function_Reference/wp_cron\" rel=\"nofollow noreferrer\"><code>wp-cron</code></a> can trigger it to load as well (but I'm not sure).</p>\n\n<p>To double check it all, enable <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\"><code>WP_DEBUG_LOG</code></a> and log the events.</p>\n" }, { "answer_id": 245048, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p><strong>Solution</strong> - ALWAYS PUT commands in actions:</p>\n\n<pre><code>add_action('init', 'my_func');\nfunction my_func(){\n //.......\n //.......\n wp_insert_post( $my_post );\n}\n</code></pre>\n\n<p>also, to avoid repeated inclusion, put this code in top of .php file:</p>\n\n<pre><code>if (defined('my_wpse_9999')) || !define('my_wpse_9999',true)) return;\n</code></pre>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105973/" ]
I just added following code to functions.php. ``` $my_post = array( 'post_title' => 'Test Title 02', 'post_content' => 'Test Des 02', 'post_status' => 'publish', 'post_author' => 1 ); wp_insert_post( $my_post ); ``` There are 8 posts were created just one page load. Seems like functions.php file is called 8 time for just one page load. Why is that? How it happens?
Add a plugin like [`Kint Debugger`](https://wordpress.org/plugins/kint-debugger/) + [`Debug Bar`](https://wordpress.org/plugins/debug-bar/) and add the following code to your `functions.php`. ``` global $wp; ob_start('kint_debug_ob'); d($wp); ob_end_flush(); ``` When you check the Debug Bar you should see the backtrace which will tell you which order functions were fired in. Loading 8 times is quite high for a single request. There is also a backtrace function you can use that is less detailed if you don't want to go the plugin route - [`wp_debug_backtrace_summary`](https://developer.wordpress.org/reference/functions/wp_debug_backtrace_summary/). ``` echo "<!----- BACKTRACE / START ----->"; print_r ( wp_debug_backtrace_summary() ); echo "<!----- BACKTRACE / END ----->"; ``` It is a bit odd to just have a random [`wp_insert_post`](https://developer.wordpress.org/reference/functions/wp_insert_post/) in your `functions.php` so perhaps wrapping your logic in a hook like [`init`](https://codex.wordpress.org/Plugin_API/Action_Reference/init) could help in the mean time. There is also a possibility this is not just a single request. [`heartbeats`](https://codex.wordpress.org/Function_Reference/wp_heartbeat_settings) will ping the backend if you're in the admin section and It's possible [`wp-cron`](https://codex.wordpress.org/Function_Reference/wp_cron) can trigger it to load as well (but I'm not sure). To double check it all, enable [`WP_DEBUG_LOG`](https://codex.wordpress.org/WP_DEBUG) and log the events.
244,915
<p>I'm trying to wrap the first sub-menu of a navigation into a seperate div. None of the children or sub-levels should get the same treatment. </p> <p>I'm really new to the Nav Walker-thingie and I'm really struggling and could need some help </p> <p>This is the structure I'm trying to achieve:</p> <pre><code>&lt;ul class="menu"&gt; &lt;li class="menu-item"&gt; &lt;a href="#"&gt;Menu Item&lt;/a&gt; &lt;!-- wrapper-class around the first sub-menu --&gt; &lt;div class="sub-menu__wrapper"&gt; &lt;ul class="sub-menu"&gt; &lt;li class="menu-item"&gt; &lt;a href="#"&gt;Menu Item&lt;/a&gt; &lt;!-- NO wrapper-class around following levels --&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;...&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I thought it would be easy to do with a simple if-statement that only prints the sub-menu__wrapper on the first level, but somehow the following HTML-output gets mixed up pretty bad.</p> <p>Here's my Walker-class:</p> <pre><code>class sublevel_wrapper extends Walker_Nav_Menu { function start_lvl( &amp;$output, $depth = 0, $args = array() ) { if ($depth == 0) { $output .= "&lt;div class='sub-menu__wrapper'&gt;&lt;ul class='sub-menu'&gt;\n"; } //$output .= "&lt;ul class='sub-menu'&gt;\n"; } function end_lvl( &amp;$output, $depth = 0, $args = array() ) { if ($depth == 0) { $output .= "&lt;/ul&gt;&lt;/div&gt;\n"; } //$output .= "&lt;/ul&gt;\n"; } } </code></pre> <p>Which prints the following structure:</p> <pre><code>&lt;ul class="menu"&gt; &lt;li class="menu-item"&gt; &lt;a href="#"&gt;Menu Item&lt;/a&gt; &lt;!-- wrapper-class around the first sub-menu --&gt; &lt;div class="sub-menu__wrapper"&gt; &lt;ul class="sub-menu"&gt; &lt;li class="menu-item"&gt;Parent Menu Item&lt;/li&gt; &lt;!-- the following items are supposed to be nested in the "parent menu item" before --&gt; &lt;li class="menu-item"&gt;Child Menu Item&lt;/li&gt; &lt;li class="menu-item"&gt;Child Menu Item&lt;/li&gt; &lt;li class="menu-item"&gt;Child Menu Item&lt;/li&gt; &lt;li class="menu-item"&gt;Parent Menu Item&lt;/li&gt; &lt;!-- again the following items are supposed to be nested in the "parent menu item" before --&gt; &lt;li class="menu-item"&gt;Child Menu Item&lt;/li&gt; &lt;li class="menu-item"&gt;Child Menu Item&lt;/li&gt; &lt;li class="menu-item"&gt;Child Menu Item&lt;/li&gt; ... &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>As you can see in the comments I tried to alter the output, if the if-statement is false, but that messes up the output even more </p> <p>Any help, constructive criticism or nudge in the right direction is much appreciated </p>
[ { "answer_id": 244926, "author": "Roland Allla", "author_id": 76247, "author_profile": "https://wordpress.stackexchange.com/users/76247", "pm_score": 1, "selected": false, "text": "<pre><code>function sevenMenu( ) {\n$menu_name = 'primary'; // specify custom menu slug\n$menu_list ='';\nif (($locations = get_nav_menu_locations()) &amp;&amp; isset($locations[$menu_name])) {\n $menu = wp_get_nav_menu_object($locations[$menu_name]);\n $menu_items = wp_get_nav_menu_items($menu-&gt;term_id);\n\n foreach( $menu_items as $menu_item ) {\n if( $menu_item-&gt;menu_item_parent == 0 ) {\n\n $parent = $menu_item-&gt;ID;\n\n $menu_array = array();\n foreach( $menu_items as $submenu ) {\n if( $submenu-&gt;menu_item_parent == $parent ) {\n $bool = true;\n $menu_array[] = '&lt;li&gt;&lt;a href=\"' . $submenu-&gt;url . '\"&gt;' . $submenu-&gt;title . '&lt;/a&gt;&lt;/li&gt; ' .\"\\n\";\n }\n }\n if( $bool == true &amp;&amp; count( $menu_array ) &gt; 0 ) {\n $menu_list .= '&lt;li role=\"presentation\" class=\"dropdown\"&gt;' .\"\\n\";\n $menu_list .= '&lt;a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\"&gt;' . $menu_item-&gt;title . ' &lt;span class=\"caret\"&gt;&lt;/span&gt;&lt;/a&gt;' .\"\\n\";\n\n $menu_list .= '&lt;ul class=\"dropdown-menu\"&gt;' .\"\\n\";\n $menu_list .= implode( \"\\n\", $menu_array );\n $menu_list .= '&lt;/ul&gt;' .\"\\n\";\n\n } else {\n\n $menu_list .= '&lt;li&gt;' .\"\\n\";\n $menu_list .= '&lt;a href=\"' . $menu_item-&gt;url . '\"&gt;' . $menu_item-&gt;title . '&lt;/a&gt;' .\"\\n\";\n $menu_list .= '&lt;li&gt;' .\"\\n\";\n }\n\n }\n\n // end &lt;li&gt;\n\n }\n\n} else {\n $menu_list = '&lt;!-- no menu defined in location \"'.$theme_location.'\" --&gt;';\n}\n\necho $menu_list;}\n</code></pre>\n\n<p>Check Out This bootstrap menu , you can add this at your function.php change your menu_name , and call this menu into your template by : </p>\n\n<pre><code>&lt;?php if (function_exists(sevenMenu())) sevenMenu(); ?&gt;\n</code></pre>\n" }, { "answer_id": 245074, "author": "Jörg Mayer", "author_id": 70248, "author_profile": "https://wordpress.stackexchange.com/users/70248", "pm_score": 4, "selected": true, "text": "<p>To be honest, I don't really know why my solution works, but it does </p>\n\n<p>I based my snippet on this solution and tweaked the output to my needs:\n<a href=\"https://wordpress.stackexchange.com/questions/204872/custom-nav-walker-with-different-output-depending-on-depth\">Custom nav walker with different output depending on depth</a></p>\n\n<pre><code>class sublevel_wrapper extends Walker_Nav_Menu {\n // add classes to ul sub-menus\n function start_lvl( &amp;$output, $depth = 0, $args = array() ) {\n // depth dependent classes\n $indent = ( $depth &gt; 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n $display_depth = ( $depth + 1); // because it counts the first submenu as 0\n $classes = array(\n 'sub-menu',\n 'menu-depth-' . $display_depth\n );\n $class_names = implode( ' ', $classes );\n\n // build html\n if ($display_depth == 1) {\n $output .= \"\\n\" . $indent . '&lt;div class=\"sub-menu__wrapper\"&gt;&lt;ul class=\"' . $class_names . '\"&gt;' . \"\\n\";\n } else {\n $output .= \"\\n\" . $indent . '&lt;ul class=\"' . $class_names . '\"&gt;' . \"\\n\";\n }\n }\n}\n</code></pre>\n\n<p>Compared to my first snippet he leaves out the end_lvl-function completely and for whatever reason it worked. I also liked how he adds the $display_depth-variable. </p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244915", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70248/" ]
I'm trying to wrap the first sub-menu of a navigation into a seperate div. None of the children or sub-levels should get the same treatment. I'm really new to the Nav Walker-thingie and I'm really struggling and could need some help This is the structure I'm trying to achieve: ``` <ul class="menu"> <li class="menu-item"> <a href="#">Menu Item</a> <!-- wrapper-class around the first sub-menu --> <div class="sub-menu__wrapper"> <ul class="sub-menu"> <li class="menu-item"> <a href="#">Menu Item</a> <!-- NO wrapper-class around following levels --> <ul class="sub-menu"> <li>...</li> </ul> </li> </ul> </div> </li> </ul> ``` I thought it would be easy to do with a simple if-statement that only prints the sub-menu\_\_wrapper on the first level, but somehow the following HTML-output gets mixed up pretty bad. Here's my Walker-class: ``` class sublevel_wrapper extends Walker_Nav_Menu { function start_lvl( &$output, $depth = 0, $args = array() ) { if ($depth == 0) { $output .= "<div class='sub-menu__wrapper'><ul class='sub-menu'>\n"; } //$output .= "<ul class='sub-menu'>\n"; } function end_lvl( &$output, $depth = 0, $args = array() ) { if ($depth == 0) { $output .= "</ul></div>\n"; } //$output .= "</ul>\n"; } } ``` Which prints the following structure: ``` <ul class="menu"> <li class="menu-item"> <a href="#">Menu Item</a> <!-- wrapper-class around the first sub-menu --> <div class="sub-menu__wrapper"> <ul class="sub-menu"> <li class="menu-item">Parent Menu Item</li> <!-- the following items are supposed to be nested in the "parent menu item" before --> <li class="menu-item">Child Menu Item</li> <li class="menu-item">Child Menu Item</li> <li class="menu-item">Child Menu Item</li> <li class="menu-item">Parent Menu Item</li> <!-- again the following items are supposed to be nested in the "parent menu item" before --> <li class="menu-item">Child Menu Item</li> <li class="menu-item">Child Menu Item</li> <li class="menu-item">Child Menu Item</li> ... </ul> </div> </li> </ul> ``` As you can see in the comments I tried to alter the output, if the if-statement is false, but that messes up the output even more Any help, constructive criticism or nudge in the right direction is much appreciated
To be honest, I don't really know why my solution works, but it does I based my snippet on this solution and tweaked the output to my needs: [Custom nav walker with different output depending on depth](https://wordpress.stackexchange.com/questions/204872/custom-nav-walker-with-different-output-depending-on-depth) ``` class sublevel_wrapper extends Walker_Nav_Menu { // add classes to ul sub-menus function start_lvl( &$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'sub-menu', 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // build html if ($display_depth == 1) { $output .= "\n" . $indent . '<div class="sub-menu__wrapper"><ul class="' . $class_names . '">' . "\n"; } else { $output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n"; } } } ``` Compared to my first snippet he leaves out the end\_lvl-function completely and for whatever reason it worked. I also liked how he adds the $display\_depth-variable.
244,943
<p>It seems that wordpress will cache all the data including the meta values of all the posts in the current page by <code>_prime_post_caches</code>:</p> <p><img src="https://i.imgur.com/s6mie3d.png" alt=""></p> <p>As shown, it tried to fetch information for posts id within (76-100).</p> <p>While in my project, most of the data of the post are saved in another table rather than the <code>wp_posts</code> table or <code>wp_posts_meta</code> table by my custom plugin. So the above query will cache only the basic information of the posts.</p> <p>So wordpress will try to trigger a sql query for each post in the page:</p> <p><img src="https://imgur.com/1HVfyJW.png" alt=""></p> <p>Even I have used the <code>wp_cache_add()</code> to ensure this kind of query for a certain post will be queried only once, I think it maybe better if I can select them all by one sql query.</p> <p>However through the docs of <a href="https://developer.wordpress.org/reference/functions/_prime_post_caches/" rel="nofollow noreferrer">_prime_post_caches</a>, this method is private, and I did not find any actions can be used to cache them.</p> <p>Any idea?</p> <p><strong>Update1 :</strong></p> <p>Why I use separate tables to save the data is that these data are generated by another system which is out of my control. While that system does not have the view model, so I use WordPress here.</p> <p>And I use <code>$wpdb</code> to communicate with the database. Actually, there are two tables joined by a key to get the full information for a single record.</p> <p><strong>Update 2:</strong></p> <p>Here is how I use the hooks to get my own data:</p> <pre><code>add_filter("the_title", function ($origin_content, $id) { $info = my_get_info($id); return $info["name"]; }, 10, 2); add_filter("the_content", function ($origin_content) { $info = my_get_info(get_the_ID()); return $info["summary"]; }); function movie4oy_get_info($post_id) { $guid = get_the_guid($post_id); $result = wp_cache_get($guid, "_my_post_info"); if (!$result) { $data = _my_get_info_db($guid); if ($data) { wp_cache_add($guid, $data, "_my_post_info"); $result = $data; } } return $result; } function _my_get_info_db($guid) { global $SQL; global $wpdb; $row = $wpdb-&gt;get_row($wpdb-&gt;prepare($SQL,$guid), ARRAY_A); $data = array( ...... ); return $data; } </code></pre>
[ { "answer_id": 244976, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": true, "text": "<p>These bits of caching are generally considered inadvisable to be messed with. If I remember right you can somewhat control the behavior by query arguments and wrapping related code in <code>wp_suspend_cache_addition()</code> calls.</p>\n\n<p>From look through the source it doesn't seem to be meant to carry custom logic. If you would like similar behavior for your custom data from non–native table you will likely have to implement caching logic for it yourself.</p>\n" }, { "answer_id": 245305, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Your filtering doesn't work because the filtering of the content and title happen after they've been cached, not before. <code>the_title</code> and <code>the_content</code> are used when displaying that data. If they work how you expected, it would be impossible to filter the content different ways on the same page.</p>\n\n<p>e.g. here is the ordering of things:</p>\n\n<ul>\n<li>WP_Query class makes a request\n\n<ul>\n<li>request is processed by database</li>\n<li>results are stored in WP_Cache</li>\n</ul></li>\n<li>Template loops over each post\n\n<ul>\n<li>template calls <code>the_title</code>\n\n<ul>\n<li>A last chance to modify the titles output in this template happens in <code>the_title</code> filter</li>\n</ul></li>\n<li>template calls <code>the_content</code>\n\n<ul>\n<li>A last chance to modify the contents output in this template happens in <code>the_content</code> filter</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>These filters are were OEmbeds and shortcodes happen. By this point, the caching has already happened. These filters aren't a chance to change the content before it's cached, they're a chance to modify the final content.</p>\n\n<p>For your filters to work, you'd need to hook into filters during the <code>WP_Query</code> phase. This is why your code functions and gives you the correct result, but isn't performant.</p>\n\n<p>To top that off, without a persistent object cache, <code>WP_Cache</code> will do very little for you. Requesting the same data a second time will avoid a second query, but once the page is finished loading all that data dies. The next page load will need to fetch it again. An object cache backed by Redis/Memcached/etc will solve this. </p>\n\n<p>Instead, you need to take a very different approach, by replicating the data.</p>\n\n<p>Store the title in the posts title, and the content in the posts content, so that they behave as standard normal posts with no filters or special mysql calls. This immediately saves you 2 expensive SQL calls, eliminates the need to write any SQL queries in WordPress, and lets you take full advantage of all the caching WordPress can do.</p>\n\n<p>In your other system, when content changes, ping the WordPress install indicating that a particular piece of content is stale, and send the new data along with it. A REST API endpoint should work well for this.</p>\n\n<p>Add in some code to make sure that the title and content can't be changed from WordPress, and you're sorted. Now you have normal standard posts that work the way they do on every other WordPress site.</p>\n\n<p>If you can't push, consider pulling the data from a regular cron job instead ( less efficient, has a timing trade off ).</p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244943", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104900/" ]
It seems that wordpress will cache all the data including the meta values of all the posts in the current page by `_prime_post_caches`: ![](https://i.imgur.com/s6mie3d.png) As shown, it tried to fetch information for posts id within (76-100). While in my project, most of the data of the post are saved in another table rather than the `wp_posts` table or `wp_posts_meta` table by my custom plugin. So the above query will cache only the basic information of the posts. So wordpress will try to trigger a sql query for each post in the page: ![](https://imgur.com/1HVfyJW.png) Even I have used the `wp_cache_add()` to ensure this kind of query for a certain post will be queried only once, I think it maybe better if I can select them all by one sql query. However through the docs of [\_prime\_post\_caches](https://developer.wordpress.org/reference/functions/_prime_post_caches/), this method is private, and I did not find any actions can be used to cache them. Any idea? **Update1 :** Why I use separate tables to save the data is that these data are generated by another system which is out of my control. While that system does not have the view model, so I use WordPress here. And I use `$wpdb` to communicate with the database. Actually, there are two tables joined by a key to get the full information for a single record. **Update 2:** Here is how I use the hooks to get my own data: ``` add_filter("the_title", function ($origin_content, $id) { $info = my_get_info($id); return $info["name"]; }, 10, 2); add_filter("the_content", function ($origin_content) { $info = my_get_info(get_the_ID()); return $info["summary"]; }); function movie4oy_get_info($post_id) { $guid = get_the_guid($post_id); $result = wp_cache_get($guid, "_my_post_info"); if (!$result) { $data = _my_get_info_db($guid); if ($data) { wp_cache_add($guid, $data, "_my_post_info"); $result = $data; } } return $result; } function _my_get_info_db($guid) { global $SQL; global $wpdb; $row = $wpdb->get_row($wpdb->prepare($SQL,$guid), ARRAY_A); $data = array( ...... ); return $data; } ```
These bits of caching are generally considered inadvisable to be messed with. If I remember right you can somewhat control the behavior by query arguments and wrapping related code in `wp_suspend_cache_addition()` calls. From look through the source it doesn't seem to be meant to carry custom logic. If you would like similar behavior for your custom data from non–native table you will likely have to implement caching logic for it yourself.
244,950
<p>I want to list all site pages with the template they use.</p> <p>Is there a mod to wp_list_pages which does this?</p>
[ { "answer_id": 244952, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 0, "selected": false, "text": "<p>I have tried flowing code to get all page with template, and worked perfect for me. this code purpose was to get all custom page template,as i was developed single page template.</p>\n\n<pre><code>$args = array(\n \"post_type\" =&gt; \"page\",\n \"order\" =&gt; \"ASC\",\n \"orderby\" =&gt; \"menu_order\"\n);\n$the_query = new WP_Query( $args );\nif ( have_posts() ) {\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n ?&gt;\n &lt;div id=\"post-&lt;?php the_ID() ?&gt;\"&gt;\n &lt;?php\n global $post;\n $slug = $post-&gt;post_name;\n get_template_part(\"page\", $slug);\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n }\n wp_reset_postdata();\n}\n</code></pre>\n" }, { "answer_id": 244984, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_page_template_slug\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_page_template_slug</a></p>\n\n<p>a basic query to get all pages, sorted by title, then output page title and template file name:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; array( 'page' ),\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'title'\n );\n$the_query = new WP_Query( $args );\nif ( $the_query-&gt;have_posts() ) {\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;p&gt;'; \n the_title();\n echo ' - ';\n echo get_page_template_slug(); \n echo '&lt;/p&gt;';\n }\n wp_reset_postdata();\n}\n</code></pre>\n" }, { "answer_id": 363311, "author": "david_nash", "author_id": 63888, "author_profile": "https://wordpress.stackexchange.com/users/63888", "pm_score": 0, "selected": false, "text": "<p>Rather than do this in PHP, you can do it with this mysql:</p>\n\n<p><code>SELECT distinct meta_value FROM `wp_postmeta` WHERE meta_key='_wp_page_template'</code></p>\n\n<p>I just needed it for a quick check so that I could clean up unused templates with the <code>theme_page_templates</code> filter.</p>\n" }, { "answer_id": 383529, "author": "Jorge Ramírez", "author_id": 200181, "author_profile": "https://wordpress.stackexchange.com/users/200181", "pm_score": 0, "selected": false, "text": "<p>Using phpmyadmin (sql) you can run this query to get a list of all pages with its used template:</p>\n<pre><code>SELECT p.post_name, p.post_title, meta_key, meta_value FROM `wp_postmeta` INNER JOIN wp_posts p ON p.ID = post_id WHERE meta_key='_wp_page_template' ORDER BY meta_value, p.post_name\n</code></pre>\n" }, { "answer_id": 409288, "author": "Loosie94", "author_id": 113139, "author_profile": "https://wordpress.stackexchange.com/users/113139", "pm_score": 2, "selected": false, "text": "<p>If you wish to get a list of posts within all post types that are using a template, use:</p>\n<pre><code>$args = array(\n 'post_type' =&gt; 'any',\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'title',\n 'posts_per_page' =&gt; -1\n );\n $query = new WP_Query($args);\n if ($query-&gt;have_posts()) {\n while ($query-&gt;have_posts()) {\n $query-&gt;the_post();\n if (get_page_template_slug($post-&gt;ID)) {\n echo '&lt;a href=&quot;' . get_the_permalink() . '&quot;&gt;' . get_the_title() . ' - ' . esc_html(get_page_template_slug($post-&gt;ID)) . '&lt;/a&gt;&lt;br&gt;';\n }\n }\n wp_reset_postdata();\n }\n</code></pre>\n<p>Can be a large query though.</p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244950", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I want to list all site pages with the template they use. Is there a mod to wp\_list\_pages which does this?
<https://codex.wordpress.org/Function_Reference/get_page_template_slug> a basic query to get all pages, sorted by title, then output page title and template file name: ``` $args = array( 'post_type' => array( 'page' ), 'order' => 'ASC', 'orderby' => 'title' ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<p>'; the_title(); echo ' - '; echo get_page_template_slug(); echo '</p>'; } wp_reset_postdata(); } ```
244,967
<p>Can anyone help me installing Wordpress multi-site. I want to Partition my database. Suppose I want to use 1 database for 300 blogs and I am expecting to have 10000 blogs. So I will need 33/34 database. (I am not sure about the calculation would be helpful if anyone can help me about the how many blogs for 1 database. I am not sure how many blogs a database can hold.)</p> <p>So how can I setup it?</p> <pre><code>$wpdb-&gt;add_database(array( 'host' =&gt; 'global.db.example.com', 'user' =&gt; 'globaluser', 'password' =&gt; 'globalpassword', 'name' =&gt; 'globaldb', )); $wpdb-&gt;add_database(array( 'host' =&gt; 'blog.db1.example.com', 'user' =&gt; 'bloguser1', 'password' =&gt; 'blogpassword', 'name' =&gt; 'blogdb1', 'dataset' =&gt; 'blog_one', )); $wpdb-&gt;add_database(array( 'host' =&gt; 'blog.db2.example.com', 'user' =&gt; 'bloguser2', 'password' =&gt; 'blogpassword', 'name' =&gt; 'blogdb2', 'dataset' =&gt; 'blog_two', )); </code></pre> <p>And so on? (this is just a theory) </p> <p>How my new blogs will move to those database? When new blog sign up how it will move to new database?</p> <p>Most important this is how can I tell how many database to move to this database and how many to move that database?</p>
[ { "answer_id": 244973, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The theory behind how HyperDB and such plugins work is that they use a simple calculation on the blog number to allocate a DB for it at creation time, and access it later. I am not sure what exactly happens when you need do add a new DB server, you will either need to look at the code or ask for support from the author.... looking at the code seems like to can associate blogs with groups which I assume can be associated with specific servers but you probably don't want to use this functionality unless you need it (move a very active blog).</p>\n\n<p>As for the number of DBs needed, It depends very much on the load they are going to have, but your estimate of having a 33 sites per DB sounds to me as too conservative. I ran a multisite as big (30+ blogs) on a relatively low level VPS and had no performance problems with it. In the end it will depend on usage and caching, but I think you can get to 100 blogs per DB with proper caching being applied (memcache probably). Anyway the nice thing about having DB servers is that it is easy to upgrade a specific one if it gets hammered more than the others.</p>\n" }, { "answer_id": 356449, "author": "samjco", "author_id": 29133, "author_profile": "https://wordpress.stackexchange.com/users/29133", "pm_score": 0, "selected": false, "text": "<p>You would probably want to use MultiDB for this:\n<a href=\"https://github.com/wpmudev/multi-db\" rel=\"nofollow noreferrer\">https://github.com/wpmudev/multi-db</a></p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244967", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106235/" ]
Can anyone help me installing Wordpress multi-site. I want to Partition my database. Suppose I want to use 1 database for 300 blogs and I am expecting to have 10000 blogs. So I will need 33/34 database. (I am not sure about the calculation would be helpful if anyone can help me about the how many blogs for 1 database. I am not sure how many blogs a database can hold.) So how can I setup it? ``` $wpdb->add_database(array( 'host' => 'global.db.example.com', 'user' => 'globaluser', 'password' => 'globalpassword', 'name' => 'globaldb', )); $wpdb->add_database(array( 'host' => 'blog.db1.example.com', 'user' => 'bloguser1', 'password' => 'blogpassword', 'name' => 'blogdb1', 'dataset' => 'blog_one', )); $wpdb->add_database(array( 'host' => 'blog.db2.example.com', 'user' => 'bloguser2', 'password' => 'blogpassword', 'name' => 'blogdb2', 'dataset' => 'blog_two', )); ``` And so on? (this is just a theory) How my new blogs will move to those database? When new blog sign up how it will move to new database? Most important this is how can I tell how many database to move to this database and how many to move that database?
The theory behind how HyperDB and such plugins work is that they use a simple calculation on the blog number to allocate a DB for it at creation time, and access it later. I am not sure what exactly happens when you need do add a new DB server, you will either need to look at the code or ask for support from the author.... looking at the code seems like to can associate blogs with groups which I assume can be associated with specific servers but you probably don't want to use this functionality unless you need it (move a very active blog). As for the number of DBs needed, It depends very much on the load they are going to have, but your estimate of having a 33 sites per DB sounds to me as too conservative. I ran a multisite as big (30+ blogs) on a relatively low level VPS and had no performance problems with it. In the end it will depend on usage and caching, but I think you can get to 100 blogs per DB with proper caching being applied (memcache probably). Anyway the nice thing about having DB servers is that it is easy to upgrade a specific one if it gets hammered more than the others.
244,969
<p>I am trying to remove the query string from my URLs when I redirect them but it is preserving them. I can't get the regex right.</p> <p>Also, I have multiple templates that redirect to different urls so I can't just use <code>.*</code> after <code>howto.php</code></p> <p><code>.htaccess</code> is not an option in this case so I must figure out how to do this in the Redirection plugin</p> <p>I want <code>/templates/howto.php?page=template-business-plan</code></p> <p>to go to</p> <p><code>/business-plan</code></p> <p>but i keep getting <code>/business-plan?page=template-business-plan</code></p>
[ { "answer_id": 244975, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 0, "selected": false, "text": "<p>I also use this plugin, so I figured I'd dig into the code to see if I can find the answer.</p>\n\n<p>There are two actions you could use for this that may work redirection_first and redirection_last</p>\n\n<p>Both take two arguments: $url and $this (which is the wordpress module for the redirection plugin)</p>\n\n<p>Here's the snippet of code from the module init() in \\modules\\wordpress.php</p>\n\n<pre><code>public function init() {\n $url = $_SERVER['REQUEST_URI'];\n\n // Make sure we don't try and redirect something essential\n if ( ! $this-&gt;protected_url( $url ) &amp;&amp; $this-&gt;matched === false ) {\n do_action( 'redirection_first', $url, $this );\n\n $redirects = Red_Item::get_for_url( $url, 'wp' );\n\n foreach ( (array) $redirects as $item ) {\n if ( $item-&gt;matches( $url ) ) {\n $this-&gt;matched = $item;\n break;\n }\n }\n\n do_action( 'redirection_last', $url, $this );\n }\n}\n</code></pre>\n\n<p>So, $url is your requested URL, and in redirection_last, $this->matched has your redirection url in it. I would start with redirection_start and you could run something like:</p>\n\n<pre><code>function redirection_strip_query_string( $url = '', $this ) {\n\n if ( strpos( $url, '?page=' ) !== false ) {\n\n $url = preg_replace('/\\?.*/', '', $url);\n\n }\n\n}\n\nadd_action( 'redirection_first', 'redirection_strip_query_string' );\n</code></pre>\n\n<p>Two notes:</p>\n\n<ol>\n<li>I have not tested this code.</li>\n<li>I wanted to give credit to the <a href=\"https://stackoverflow.com/questions/4270677/removing-query-string-in-php-sometimes-based-on-referrer\">simple URL preg_replace</a></li>\n</ol>\n" }, { "answer_id": 257448, "author": "Vladan", "author_id": 74876, "author_profile": "https://wordpress.stackexchange.com/users/74876", "pm_score": -1, "selected": false, "text": "<p>I've solved it by slight change in plugin code, by adding two filter hooks. Hoping that author will incorporate those hooks - 2 non-destructive lines, as they allows us much more customization of plugin behaviour. Explained here in detail: <a href=\"https://github.com/johngodley/redirection/issues/180\" rel=\"nofollow noreferrer\">https://github.com/johngodley/redirection/issues/180</a></p>\n\n<p>UPDATE: This \"suggestion\" of mine is incorporated upstream, in plugin itself, so there is no need to modify anything: we now have <code>redirection_url_target</code> and <code>redirection_url_source</code> filters so custom code can manipulate the source and target redirect for special purposes.now there</p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244969", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98395/" ]
I am trying to remove the query string from my URLs when I redirect them but it is preserving them. I can't get the regex right. Also, I have multiple templates that redirect to different urls so I can't just use `.*` after `howto.php` `.htaccess` is not an option in this case so I must figure out how to do this in the Redirection plugin I want `/templates/howto.php?page=template-business-plan` to go to `/business-plan` but i keep getting `/business-plan?page=template-business-plan`
I also use this plugin, so I figured I'd dig into the code to see if I can find the answer. There are two actions you could use for this that may work redirection\_first and redirection\_last Both take two arguments: $url and $this (which is the wordpress module for the redirection plugin) Here's the snippet of code from the module init() in \modules\wordpress.php ``` public function init() { $url = $_SERVER['REQUEST_URI']; // Make sure we don't try and redirect something essential if ( ! $this->protected_url( $url ) && $this->matched === false ) { do_action( 'redirection_first', $url, $this ); $redirects = Red_Item::get_for_url( $url, 'wp' ); foreach ( (array) $redirects as $item ) { if ( $item->matches( $url ) ) { $this->matched = $item; break; } } do_action( 'redirection_last', $url, $this ); } } ``` So, $url is your requested URL, and in redirection\_last, $this->matched has your redirection url in it. I would start with redirection\_start and you could run something like: ``` function redirection_strip_query_string( $url = '', $this ) { if ( strpos( $url, '?page=' ) !== false ) { $url = preg_replace('/\?.*/', '', $url); } } add_action( 'redirection_first', 'redirection_strip_query_string' ); ``` Two notes: 1. I have not tested this code. 2. I wanted to give credit to the [simple URL preg\_replace](https://stackoverflow.com/questions/4270677/removing-query-string-in-php-sometimes-based-on-referrer)
244,978
<p>I have custom CSS for the login and admin pages.</p> <p>Is it OK to add it as I've done below, or is there a better alternative?</p> <pre><code>function custom_admin_css() { wp_enqueue_style( 'custom_admin_css', get_template_directory_uri() . '/css/admin.css', array(), filemtime( get_template_directory() . '/css/admin.css' ) ); } add_action( 'login_enqueue_scripts', 'custom_admin_css', 10 ); add_action( 'admin_enqueue_scripts', 'custom_admin_css', 10 ); </code></pre>
[ { "answer_id": 244983, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 4, "selected": true, "text": "<p>That's pretty fine and it's the proper way to add CSS to login page. But you can also change login page CSS by below code-</p>\n\n<pre><code>function the_dramatist_custom_login_css() {\n echo '&lt;style type=\"text/css\"&gt; //Write your css here &lt;/style&gt;';\n}\nadd_action('login_head', 'the_dramatist_custom_login_css');\n</code></pre>\n\n<p>This actually prints CSS code inline in the login page. And for admin CSS your way is correct.</p>\n" }, { "answer_id": 392511, "author": "Zaheer Abbas", "author_id": 135489, "author_profile": "https://wordpress.stackexchange.com/users/135489", "pm_score": 0, "selected": false, "text": "<p>Sometimes you have to add CSS to the content created with help of jQuery so the above methods will not work if jquery code loads in the footer. you can use the below code too.</p>\n<pre class=\"lang-php prettyprint-override\"><code> function the_king_custom_login_css() {\n echo '&lt;style type=&quot;text/css&quot;&gt;\n .nsl-container {\n text-align:center !important;\n }\n &lt;/style&gt;';\n }\n add_action('wp_footer', 'the_king_custom_login_css');\n</code></pre>\n" }, { "answer_id": 396626, "author": "infomasud", "author_id": 213368, "author_profile": "https://wordpress.stackexchange.com/users/213368", "pm_score": 0, "selected": false, "text": "<p>as explained at <a href=\"https://developer.wordpress.org/reference/hooks/login_head/\" rel=\"nofollow noreferrer\">here </a> you can do as below:</p>\n<pre><code>// custom login for theme\nfunction childtheme_custom_login() {\n echo '&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;' . \n get_bloginfo('stylesheet_directory') . '/customlogin.css&quot; /&gt;';\n}\n\nadd_action('login_head', 'childtheme_custom_login');\n</code></pre>\n<p><strong>another way for plugin:</strong></p>\n<p>If you want to load extra css for login page from your plugin you can do as below:</p>\n<p>I assume you know basics of wp plugin development.</p>\n<p>make a css directory in your plugin directory create a login.css file.</p>\n<p>in your init function add this.</p>\n<pre><code> public static function init(){\n //other function as your need\n add_action( 'login_enqueue_scripts', __CLASS__.'::custom_login_css', 10 );\n }\n</code></pre>\n<p>then you can write function like this.</p>\n<pre><code>public static function custom_login_css(){\n wp_enqueue_style('custom_login_css', plugins_url('/css/login.css', __FILE__), [], '1.0.0');\n }\n</code></pre>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244978", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I have custom CSS for the login and admin pages. Is it OK to add it as I've done below, or is there a better alternative? ``` function custom_admin_css() { wp_enqueue_style( 'custom_admin_css', get_template_directory_uri() . '/css/admin.css', array(), filemtime( get_template_directory() . '/css/admin.css' ) ); } add_action( 'login_enqueue_scripts', 'custom_admin_css', 10 ); add_action( 'admin_enqueue_scripts', 'custom_admin_css', 10 ); ```
That's pretty fine and it's the proper way to add CSS to login page. But you can also change login page CSS by below code- ``` function the_dramatist_custom_login_css() { echo '<style type="text/css"> //Write your css here </style>'; } add_action('login_head', 'the_dramatist_custom_login_css'); ``` This actually prints CSS code inline in the login page. And for admin CSS your way is correct.
244,982
<p>I'm using WordPress 4.6.1, is it possible for us to hook into <code>function register_admin_color_schemes()</code> located in <code>wp-includes/general-template.php</code>? This way we can send or concatenate or bind the following code to that function:</p> <pre><code>wp_admin_css_color( 'ffa', _x( 'My Custom Color Combo', 'admin color scheme' ), admin_url( "/my-plugin=directory/css/colors/my-custom-color-combo/colors$suffix.css" ), array( '#ffffff', '#ffcd00', '#c7a589', '#9ea476' ), array( 'base' =&gt; '#f3f2f1', 'focus' =&gt; '#fff', 'current' =&gt; '#fff' ) ); </code></pre> <p>If possible, how can we do this dynamically?</p> <p>FYI, I see that I can manually modify the <code>general-template.php</code> file, but I would have to do that every time I update WordPress.</p>
[ { "answer_id": 244983, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 4, "selected": true, "text": "<p>That's pretty fine and it's the proper way to add CSS to login page. But you can also change login page CSS by below code-</p>\n\n<pre><code>function the_dramatist_custom_login_css() {\n echo '&lt;style type=\"text/css\"&gt; //Write your css here &lt;/style&gt;';\n}\nadd_action('login_head', 'the_dramatist_custom_login_css');\n</code></pre>\n\n<p>This actually prints CSS code inline in the login page. And for admin CSS your way is correct.</p>\n" }, { "answer_id": 392511, "author": "Zaheer Abbas", "author_id": 135489, "author_profile": "https://wordpress.stackexchange.com/users/135489", "pm_score": 0, "selected": false, "text": "<p>Sometimes you have to add CSS to the content created with help of jQuery so the above methods will not work if jquery code loads in the footer. you can use the below code too.</p>\n<pre class=\"lang-php prettyprint-override\"><code> function the_king_custom_login_css() {\n echo '&lt;style type=&quot;text/css&quot;&gt;\n .nsl-container {\n text-align:center !important;\n }\n &lt;/style&gt;';\n }\n add_action('wp_footer', 'the_king_custom_login_css');\n</code></pre>\n" }, { "answer_id": 396626, "author": "infomasud", "author_id": 213368, "author_profile": "https://wordpress.stackexchange.com/users/213368", "pm_score": 0, "selected": false, "text": "<p>as explained at <a href=\"https://developer.wordpress.org/reference/hooks/login_head/\" rel=\"nofollow noreferrer\">here </a> you can do as below:</p>\n<pre><code>// custom login for theme\nfunction childtheme_custom_login() {\n echo '&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;' . \n get_bloginfo('stylesheet_directory') . '/customlogin.css&quot; /&gt;';\n}\n\nadd_action('login_head', 'childtheme_custom_login');\n</code></pre>\n<p><strong>another way for plugin:</strong></p>\n<p>If you want to load extra css for login page from your plugin you can do as below:</p>\n<p>I assume you know basics of wp plugin development.</p>\n<p>make a css directory in your plugin directory create a login.css file.</p>\n<p>in your init function add this.</p>\n<pre><code> public static function init(){\n //other function as your need\n add_action( 'login_enqueue_scripts', __CLASS__.'::custom_login_css', 10 );\n }\n</code></pre>\n<p>then you can write function like this.</p>\n<pre><code>public static function custom_login_css(){\n wp_enqueue_style('custom_login_css', plugins_url('/css/login.css', __FILE__), [], '1.0.0');\n }\n</code></pre>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/244982", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
I'm using WordPress 4.6.1, is it possible for us to hook into `function register_admin_color_schemes()` located in `wp-includes/general-template.php`? This way we can send or concatenate or bind the following code to that function: ``` wp_admin_css_color( 'ffa', _x( 'My Custom Color Combo', 'admin color scheme' ), admin_url( "/my-plugin=directory/css/colors/my-custom-color-combo/colors$suffix.css" ), array( '#ffffff', '#ffcd00', '#c7a589', '#9ea476' ), array( 'base' => '#f3f2f1', 'focus' => '#fff', 'current' => '#fff' ) ); ``` If possible, how can we do this dynamically? FYI, I see that I can manually modify the `general-template.php` file, but I would have to do that every time I update WordPress.
That's pretty fine and it's the proper way to add CSS to login page. But you can also change login page CSS by below code- ``` function the_dramatist_custom_login_css() { echo '<style type="text/css"> //Write your css here </style>'; } add_action('login_head', 'the_dramatist_custom_login_css'); ``` This actually prints CSS code inline in the login page. And for admin CSS your way is correct.
245,009
<p>I have this code in my php file that creates a button labeled from a field called speaker_file_label and links to a pdf file based on the url entered in the speker_file_url. The fields are created by ACF</p> <pre><code> echo do_shortcode( "[av_button label='".get_sub_field('speaker_file_label')."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'&lt;br&gt;'; </code></pre> <p>This works perfectly when someone just enters text. However if they say somehting like "joe's files" (without quotes) Then the shortcode breaks and the label just becomes "click"</p> <p>How can i make wordpress not interpret that apostrophe as part of code?</p>
[ { "answer_id": 245011, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 0, "selected": false, "text": "<p>Two ways to fix it, would be to invert your quotes from the outset (replace all double quotes (\") with single quotes (') and vice versa.</p>\n\n<pre><code>echo do_shortcode( '[av_button label=\"' . get_sub_field('speaker_file_label') . '\" link=\"manually,' . get_sub_field ('speaker_file_url') . '\" link_target=\"_blank\" size=\"medium\" position=\"left\" color=\"theme-color\"]' ).'&lt;br&gt;';\n</code></pre>\n\n<p>But that won't stop if people use double quotes (\"), so you can escape them, by using <a href=\"http://www.w3schools.com/php/func_string_addslashes.asp\" rel=\"nofollow noreferrer\">addslashes</a></p>\n\n<pre><code>echo do_shortcode( '[av_button label=\"' . addslashes( get_sub_field('speaker_file_label') ) . '\" link=\"manually,' . addslashes( get_sub_field ('speaker_file_url') ) . '\" link_target=\"_blank\" size=\"medium\" position=\"left\" color=\"theme-color\"]' ) . '&lt;br&gt;';\n</code></pre>\n\n<p>This should fix most issues, the first one might fix them all if you don't expect people to use double quotes. I haven't tested either, so let me know if they worked for you or not.</p>\n" }, { "answer_id": 245012, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": true, "text": "<p>you could apply the content filters:</p>\n\n<pre><code> echo do_shortcode( \"[av_button label='\".apply_filters('the_content',(get_sub_field('speaker_file_label')).\"' link='manually,\".get_sub_field ('speaker_file_url').\"' link_target='_blank' size='medium' position='left' color='theme-color']\" ).'&lt;br&gt;';\n</code></pre>\n\n<p>the above added pp marks <code>&lt;p&gt;&lt;/p&gt;</code></p>\n\n<p>try this:</p>\n\n<pre><code> echo do_shortcode( \"[av_button label='\".wptexturize( get_sub_field('speaker_file_label')).\"' link='manually,\".get_sub_field ('speaker_file_url').\"' link_target='_blank' size='medium' position='left' color='theme-color']\" ).'&lt;br&gt;';\n</code></pre>\n" }, { "answer_id": 245016, "author": "Nabil Kadimi", "author_id": 17187, "author_profile": "https://wordpress.stackexchange.com/users/17187", "pm_score": 2, "selected": false, "text": "<p>Wrap user input in <a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\">esc_html()</a>.</p>\n\n<p>Using your example:</p>\n\n<pre><code> echo do_shortcode( \"[av_button \n label='\" . esc_html( get_sub_field( 'speaker_file_label' ) ) . \"' \n link='manually,\" . esc_html( get_sub_field ( 'speaker_file_url' ) ).\"' \n link_target='_blank'\n size='medium' position='left' color='theme-color']\" ).'&lt;br&gt;';\n</code></pre>\n\n<p>You can make it more readable:</p>\n\n<pre><code>$shortcode = sprintf( \"[av_button label='%1$s' link='manually,%2$s' link_target='_blank' size='medium' position='left' color='theme-color']\"\n , esc_html( get_sub_field( 'speaker_file_label' ) )\n , esc_html( get_sub_field( 'speaker_file_url' ) )\n);\n\necho do_shortcode( $shortcode ) . '&lt;br&gt;';\n</code></pre>\n" }, { "answer_id": 395750, "author": "Mr SKT", "author_id": 210558, "author_profile": "https://wordpress.stackexchange.com/users/210558", "pm_score": 0, "selected": false, "text": "<p>You can write &quot;<code>&amp;#39;</code>&quot; instead of <code>'</code> (single quotation mark) in your text fields.</p>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/245009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105668/" ]
I have this code in my php file that creates a button labeled from a field called speaker\_file\_label and links to a pdf file based on the url entered in the speker\_file\_url. The fields are created by ACF ``` echo do_shortcode( "[av_button label='".get_sub_field('speaker_file_label')."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'<br>'; ``` This works perfectly when someone just enters text. However if they say somehting like "joe's files" (without quotes) Then the shortcode breaks and the label just becomes "click" How can i make wordpress not interpret that apostrophe as part of code?
you could apply the content filters: ``` echo do_shortcode( "[av_button label='".apply_filters('the_content',(get_sub_field('speaker_file_label'))."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'<br>'; ``` the above added pp marks `<p></p>` try this: ``` echo do_shortcode( "[av_button label='".wptexturize( get_sub_field('speaker_file_label'))."' link='manually,".get_sub_field ('speaker_file_url')."' link_target='_blank' size='medium' position='left' color='theme-color']" ).'<br>'; ```
245,025
<p>I have a <strong>hierarchical</strong> Custom Post Type called <code>project</code>, registered as follows:</p> <pre><code>register_post_type( 'project', array( 'public' =&gt; true, 'hierarchical' =&gt; true, 'rewrite' =&gt; array( 'with_front' =&gt; false ) ) ); </code></pre> <p>The URLs currently look like this:</p> <ul> <li><a href="https://example.com/project/hello" rel="nofollow noreferrer">https://example.com/project/hello</a></li> <li><a href="https://example.com/project/hello/world" rel="nofollow noreferrer">https://example.com/project/hello/world</a></li> </ul> <p>I would like the URLs to look like this:</p> <ul> <li><a href="https://example.com/hello" rel="nofollow noreferrer">https://example.com/hello</a></li> <li><a href="https://example.com/hello/world" rel="nofollow noreferrer">https://example.com/hello/world</a></li> </ul> <p>How can I most efficiently accomplish this such that other URLs are not interfered with (e.g. <code>page</code>s, blog <code>post</code>s, other custom post types)?</p> <p>All the solutions that are currently out there either cause 404s on other pages on the site or do not work correctly with nested URLs.</p>
[ { "answer_id": 245031, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>This will allow you to use the post name without the slug. Essentially anytime the link is requested it can be altered to exclude the base post type. And any time a query runs with just a name, the available post types used in the search are altered to include your post type.</p>\n<pre><code>function wpse_remove_cpt_slug( $post_link, $post, $leavename ) {\n\n // leave these CPT alone\n $whitelist = array ('project');\n\n if ( ! in_array( $post-&gt;post_type, $whitelist ) || 'publish' != $post-&gt;post_status )\n return $post_link;\n\n if( isset($GLOBALS['wp_post_types'][$post-&gt;post_type],\n $GLOBALS['wp_post_types'][$post-&gt;post_type]-&gt;rewrite['slug'])){\n $slug = $GLOBALS['wp_post_types'][$post-&gt;post_type]-&gt;rewrite['slug'];\n } else {\n $slug = $post-&gt;post_type;\n }\n\n // remove post slug from url\n $post_link = str_replace( '/' . $slug . '/', '/', $post_link );\n\n return $post_link;\n}\nadd_filter( 'post_type_link', 'wpse_remove_cpt_slug', 10, 3 );\nadd_filter( 'post_link', 'wpse_remove_cpt_slug', 10, 3 );\n\nfunction wpse_parse_request( $query ) {\n\n // Only noop the main query\n if ( ! $query-&gt;is_main_query() )\n return;\n\n // Only noop our very specific rewrite rule match\n if ( 2 != count( $query-&gt;query )\n || ! isset( $query-&gt;query['page'] ) )\n return;\n\n // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match\n if ( ! empty( $query-&gt;query['name'] ) )\n $query-&gt;set( 'post_type', array( 'post', 'project', 'page' ) );\n}\nadd_action( 'pre_get_posts', 'wpse_parse_request' );\n</code></pre>\n<hr />\n<p>Reference</p>\n<blockquote>\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_type_link\" rel=\"nofollow noreferrer\">post_type_link</a> is a filter applied to the permalink URL for a post or custom post type prior to printing by the function get_post_permalink.</p>\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_link\" rel=\"nofollow noreferrer\">post_link</a> is a filter applied to the permalink URL for a post prior to returning the processed url by the function get_permalink.</p>\n<p>This hook is called after the query variable object is created, but before the actual query is run. The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">pre_get_posts</a> action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object - no return value is necessary).</p>\n</blockquote>\n" }, { "answer_id": 392213, "author": "Abhishek R", "author_id": 86915, "author_profile": "https://wordpress.stackexchange.com/users/86915", "pm_score": 0, "selected": false, "text": "<p>Try this. It will replace the slug <code>project</code> without 404 error for both parent and child.</p>\n<pre><code>/**\n * Strip the slug out of a hierarchical custom post type\n */\n\nif ( !class_exists( 'project_Rewrites' ) ) :\n\nclass project_Rewrites {\n\n private static $instance;\n\n public $rules;\n\n private function __construct() {\n /* Don't do anything, needs to be initialized via instance() method */\n }\n\n public static function instance() {\n if ( ! isset( self::$instance ) ) {\n self::$instance = new project_Rewrites;\n self::$instance-&gt;setup();\n }\n return self::$instance;\n }\n\n public function setup() {\n add_action( 'init', array( $this, 'add_rewrites' ), 20 );\n add_filter( 'request', array( $this, 'check_rewrite_conflicts' ) );\n add_filter( 'project_rewrite_rules', array( $this, 'strip_project_rules' ) );\n add_filter( 'rewrite_rules_array', array( $this, 'inject_project_rules' ) );\n }\n\n public function add_rewrites() {\n add_rewrite_tag( &quot;%project%&quot;, '(.+?)', &quot;project=&quot; );\n add_permastruct( 'project', &quot;%project%&quot;, array(\n 'ep_mask' =&gt; EP_PERMALINK\n ) );\n }\n\n public function check_rewrite_conflicts( $qv ) {\n if ( isset( $qv['project'] ) ) {\n if ( get_page_by_path( $qv['project'] ) ) {\n $qv = array( 'pagename' =&gt; $qv['project'] );\n }\n }\n return $qv;\n }\n\n public function strip_project_rules( $rules ) {\n $this-&gt;rules = $rules;\n # We no longer need the attachment rules, so strip them out\n foreach ( $this-&gt;rules as $regex =&gt; $value ) {\n if ( strpos( $value, 'attachment' ) )\n unset( $this-&gt;rules[ $regex ] );\n }\n return array();\n }\n\n public function inject_project_rules( $rules ) {\n # This is the first 'page' rule\n $offset = array_search( '(.?.+?)/trackback/?$', array_keys( $rules ) );\n $page_rules = array_slice( $rules, $offset, null, true );\n $other_rules = array_slice( $rules, 0, $offset, true );\n return array_merge( $other_rules, $this-&gt;rules, $page_rules );\n }\n}\n\nproject_Rewrites::instance();\n\nendif;\n</code></pre>\n" } ]
2016/11/03
[ "https://wordpress.stackexchange.com/questions/245025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83312/" ]
I have a **hierarchical** Custom Post Type called `project`, registered as follows: ``` register_post_type( 'project', array( 'public' => true, 'hierarchical' => true, 'rewrite' => array( 'with_front' => false ) ) ); ``` The URLs currently look like this: * <https://example.com/project/hello> * <https://example.com/project/hello/world> I would like the URLs to look like this: * <https://example.com/hello> * <https://example.com/hello/world> How can I most efficiently accomplish this such that other URLs are not interfered with (e.g. `page`s, blog `post`s, other custom post types)? All the solutions that are currently out there either cause 404s on other pages on the site or do not work correctly with nested URLs.
This will allow you to use the post name without the slug. Essentially anytime the link is requested it can be altered to exclude the base post type. And any time a query runs with just a name, the available post types used in the search are altered to include your post type. ``` function wpse_remove_cpt_slug( $post_link, $post, $leavename ) { // leave these CPT alone $whitelist = array ('project'); if ( ! in_array( $post->post_type, $whitelist ) || 'publish' != $post->post_status ) return $post_link; if( isset($GLOBALS['wp_post_types'][$post->post_type], $GLOBALS['wp_post_types'][$post->post_type]->rewrite['slug'])){ $slug = $GLOBALS['wp_post_types'][$post->post_type]->rewrite['slug']; } else { $slug = $post->post_type; } // remove post slug from url $post_link = str_replace( '/' . $slug . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'wpse_remove_cpt_slug', 10, 3 ); add_filter( 'post_link', 'wpse_remove_cpt_slug', 10, 3 ); function wpse_parse_request( $query ) { // Only noop the main query if ( ! $query->is_main_query() ) return; // Only noop our very specific rewrite rule match if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) return; // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match if ( ! empty( $query->query['name'] ) ) $query->set( 'post_type', array( 'post', 'project', 'page' ) ); } add_action( 'pre_get_posts', 'wpse_parse_request' ); ``` --- Reference > > [post\_type\_link](https://codex.wordpress.org/Plugin_API/Filter_Reference/post_type_link) is a filter applied to the permalink URL for a post or custom post type prior to printing by the function get\_post\_permalink. > > > [post\_link](https://codex.wordpress.org/Plugin_API/Filter_Reference/post_link) is a filter applied to the permalink URL for a post prior to returning the processed url by the function get\_permalink. > > > This hook is called after the query variable object is created, but before the actual query is run. The [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object - no return value is necessary). > > >
245,038
<p>My transition to 4.6.1 has been hellish and I'd like to go back until I have time to code my way round the issues it causes.</p> <p>The trouble is I've had the site live for a day and user interactions have changed the database. I'd like to keep the new database and roll back the WP install to my previous version by simply restoring my compressed root folder back to where it was and save the new one for another day.</p> <p>In testing this locally it seemed to work absolutely fine but am I setting myself up for a big future headache for when it comes time to update again? Often when it seems too simple - it is....</p>
[ { "answer_id": 245031, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>This will allow you to use the post name without the slug. Essentially anytime the link is requested it can be altered to exclude the base post type. And any time a query runs with just a name, the available post types used in the search are altered to include your post type.</p>\n<pre><code>function wpse_remove_cpt_slug( $post_link, $post, $leavename ) {\n\n // leave these CPT alone\n $whitelist = array ('project');\n\n if ( ! in_array( $post-&gt;post_type, $whitelist ) || 'publish' != $post-&gt;post_status )\n return $post_link;\n\n if( isset($GLOBALS['wp_post_types'][$post-&gt;post_type],\n $GLOBALS['wp_post_types'][$post-&gt;post_type]-&gt;rewrite['slug'])){\n $slug = $GLOBALS['wp_post_types'][$post-&gt;post_type]-&gt;rewrite['slug'];\n } else {\n $slug = $post-&gt;post_type;\n }\n\n // remove post slug from url\n $post_link = str_replace( '/' . $slug . '/', '/', $post_link );\n\n return $post_link;\n}\nadd_filter( 'post_type_link', 'wpse_remove_cpt_slug', 10, 3 );\nadd_filter( 'post_link', 'wpse_remove_cpt_slug', 10, 3 );\n\nfunction wpse_parse_request( $query ) {\n\n // Only noop the main query\n if ( ! $query-&gt;is_main_query() )\n return;\n\n // Only noop our very specific rewrite rule match\n if ( 2 != count( $query-&gt;query )\n || ! isset( $query-&gt;query['page'] ) )\n return;\n\n // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match\n if ( ! empty( $query-&gt;query['name'] ) )\n $query-&gt;set( 'post_type', array( 'post', 'project', 'page' ) );\n}\nadd_action( 'pre_get_posts', 'wpse_parse_request' );\n</code></pre>\n<hr />\n<p>Reference</p>\n<blockquote>\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_type_link\" rel=\"nofollow noreferrer\">post_type_link</a> is a filter applied to the permalink URL for a post or custom post type prior to printing by the function get_post_permalink.</p>\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_link\" rel=\"nofollow noreferrer\">post_link</a> is a filter applied to the permalink URL for a post prior to returning the processed url by the function get_permalink.</p>\n<p>This hook is called after the query variable object is created, but before the actual query is run. The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">pre_get_posts</a> action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object - no return value is necessary).</p>\n</blockquote>\n" }, { "answer_id": 392213, "author": "Abhishek R", "author_id": 86915, "author_profile": "https://wordpress.stackexchange.com/users/86915", "pm_score": 0, "selected": false, "text": "<p>Try this. It will replace the slug <code>project</code> without 404 error for both parent and child.</p>\n<pre><code>/**\n * Strip the slug out of a hierarchical custom post type\n */\n\nif ( !class_exists( 'project_Rewrites' ) ) :\n\nclass project_Rewrites {\n\n private static $instance;\n\n public $rules;\n\n private function __construct() {\n /* Don't do anything, needs to be initialized via instance() method */\n }\n\n public static function instance() {\n if ( ! isset( self::$instance ) ) {\n self::$instance = new project_Rewrites;\n self::$instance-&gt;setup();\n }\n return self::$instance;\n }\n\n public function setup() {\n add_action( 'init', array( $this, 'add_rewrites' ), 20 );\n add_filter( 'request', array( $this, 'check_rewrite_conflicts' ) );\n add_filter( 'project_rewrite_rules', array( $this, 'strip_project_rules' ) );\n add_filter( 'rewrite_rules_array', array( $this, 'inject_project_rules' ) );\n }\n\n public function add_rewrites() {\n add_rewrite_tag( &quot;%project%&quot;, '(.+?)', &quot;project=&quot; );\n add_permastruct( 'project', &quot;%project%&quot;, array(\n 'ep_mask' =&gt; EP_PERMALINK\n ) );\n }\n\n public function check_rewrite_conflicts( $qv ) {\n if ( isset( $qv['project'] ) ) {\n if ( get_page_by_path( $qv['project'] ) ) {\n $qv = array( 'pagename' =&gt; $qv['project'] );\n }\n }\n return $qv;\n }\n\n public function strip_project_rules( $rules ) {\n $this-&gt;rules = $rules;\n # We no longer need the attachment rules, so strip them out\n foreach ( $this-&gt;rules as $regex =&gt; $value ) {\n if ( strpos( $value, 'attachment' ) )\n unset( $this-&gt;rules[ $regex ] );\n }\n return array();\n }\n\n public function inject_project_rules( $rules ) {\n # This is the first 'page' rule\n $offset = array_search( '(.?.+?)/trackback/?$', array_keys( $rules ) );\n $page_rules = array_slice( $rules, $offset, null, true );\n $other_rules = array_slice( $rules, 0, $offset, true );\n return array_merge( $other_rules, $this-&gt;rules, $page_rules );\n }\n}\n\nproject_Rewrites::instance();\n\nendif;\n</code></pre>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47618/" ]
My transition to 4.6.1 has been hellish and I'd like to go back until I have time to code my way round the issues it causes. The trouble is I've had the site live for a day and user interactions have changed the database. I'd like to keep the new database and roll back the WP install to my previous version by simply restoring my compressed root folder back to where it was and save the new one for another day. In testing this locally it seemed to work absolutely fine but am I setting myself up for a big future headache for when it comes time to update again? Often when it seems too simple - it is....
This will allow you to use the post name without the slug. Essentially anytime the link is requested it can be altered to exclude the base post type. And any time a query runs with just a name, the available post types used in the search are altered to include your post type. ``` function wpse_remove_cpt_slug( $post_link, $post, $leavename ) { // leave these CPT alone $whitelist = array ('project'); if ( ! in_array( $post->post_type, $whitelist ) || 'publish' != $post->post_status ) return $post_link; if( isset($GLOBALS['wp_post_types'][$post->post_type], $GLOBALS['wp_post_types'][$post->post_type]->rewrite['slug'])){ $slug = $GLOBALS['wp_post_types'][$post->post_type]->rewrite['slug']; } else { $slug = $post->post_type; } // remove post slug from url $post_link = str_replace( '/' . $slug . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'wpse_remove_cpt_slug', 10, 3 ); add_filter( 'post_link', 'wpse_remove_cpt_slug', 10, 3 ); function wpse_parse_request( $query ) { // Only noop the main query if ( ! $query->is_main_query() ) return; // Only noop our very specific rewrite rule match if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) return; // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match if ( ! empty( $query->query['name'] ) ) $query->set( 'post_type', array( 'post', 'project', 'page' ) ); } add_action( 'pre_get_posts', 'wpse_parse_request' ); ``` --- Reference > > [post\_type\_link](https://codex.wordpress.org/Plugin_API/Filter_Reference/post_type_link) is a filter applied to the permalink URL for a post or custom post type prior to printing by the function get\_post\_permalink. > > > [post\_link](https://codex.wordpress.org/Plugin_API/Filter_Reference/post_link) is a filter applied to the permalink URL for a post prior to returning the processed url by the function get\_permalink. > > > This hook is called after the query variable object is created, but before the actual query is run. The [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object - no return value is necessary). > > >
245,042
<p>I have setup a custom post type with a custom taxonomy as categories.</p> <p>I need to use <a href="https://developer.wordpress.org/reference/functions/get_the_terms/" rel="nofollow noreferrer"><code>get_the_terms</code></a> or <a href="https://developer.wordpress.org/reference/functions/wp_get_post_terms/" rel="nofollow noreferrer"><code>wp_get_post_terms</code></a> to return the first category of a post in the custom post type.</p> <p>But I can't quite figure out how to use it in comparison to <a href="https://developer.wordpress.org/reference/functions/get_the_category/" rel="nofollow noreferrer"><code>get_the_category</code></a>.</p>
[ { "answer_id": 245060, "author": "vol4ikman", "author_id": 31075, "author_profile": "https://wordpress.stackexchange.com/users/31075", "pm_score": 0, "selected": false, "text": "<p>Try this one please:</p>\n\n<p><code>$terms = get_the_terms();\n$term = reset($terms);</code></p>\n" }, { "answer_id": 245067, "author": "Roland Allla", "author_id": 76247, "author_profile": "https://wordpress.stackexchange.com/users/76247", "pm_score": 1, "selected": false, "text": "<p>Hello here is an example i have used : </p>\n\n<pre><code>&lt;?php while ( have_posts() ) : the_post(); \n\n $category = get_the_terms( $id, 'event_category' );\n //get First Category\n $firstCategory = $category[0];\n //get category link\n $category_link = get_category_link($firstCategory-&gt;term_id);\n //echo category name\n echo $firstCategory-&gt;name;\n\n endwhile;\n?&gt; \n</code></pre>\n\n<p>change event_category with your taxonomy slug </p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106278/" ]
I have setup a custom post type with a custom taxonomy as categories. I need to use [`get_the_terms`](https://developer.wordpress.org/reference/functions/get_the_terms/) or [`wp_get_post_terms`](https://developer.wordpress.org/reference/functions/wp_get_post_terms/) to return the first category of a post in the custom post type. But I can't quite figure out how to use it in comparison to [`get_the_category`](https://developer.wordpress.org/reference/functions/get_the_category/).
Hello here is an example i have used : ``` <?php while ( have_posts() ) : the_post(); $category = get_the_terms( $id, 'event_category' ); //get First Category $firstCategory = $category[0]; //get category link $category_link = get_category_link($firstCategory->term_id); //echo category name echo $firstCategory->name; endwhile; ?> ``` change event\_category with your taxonomy slug
245,049
<p>In my index page, I want to display 12 posts for each category, so I iterate the categories:</p> <pre><code>&lt;?php foreach ($sub_cates as $cate) { ?&gt; &lt;section class="b"&gt; &lt;div class="grid"&gt; &lt;header class="title"&gt; &lt;h2&gt;&lt;?php echo $cate-&gt;name ?&gt;&lt;a class="more" href="&lt;?php echo get_category_link($cate) ?&gt;"&gt;More&lt;/a&gt;&lt;/h2&gt; &lt;/header&gt; &lt;div class="row"&gt; &lt;?php //rewind_posts(); query_posts(array( "category" =&gt; $cate-&gt;term_id, "numberposts" =&gt; 12 )); $w = $GLOBALS['wp_query']; while (have_posts()) { the_post(); ?&gt; &lt;article class="col-xs-4 col-sm-3 col-md-2 "&gt; &lt;?php get_template_part("grid-item") ?&gt; &lt;/article&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php } ?&gt; </code></pre> <p>However each section print the same collections of posts, even after I use the <code>rewind_posts</code> before the loop.</p> <p>What's going on?</p>
[ { "answer_id": 245053, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>The job of <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow noreferrer\"><code>rewind_posts()</code></a> is to rewind the same query -- which is not was you want in this case.</p>\n\n<p>Have you tried with <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata#Example_1\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> instead? <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a> is needed for the <code>$post</code> object but <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\"><code>wp_reset_query()</code></a> isn't required after the loop in this case.</p>\n\n<pre><code>&lt;?php foreach ( $sub_cates as $cate ) { ?&gt;\n\n &lt;section class=\"b\"&gt;\n &lt;div class=\"grid\"&gt;\n &lt;header class=\"title\"&gt;\n &lt;h2&gt;&lt;?php echo $cate-&gt;name ?&gt;&lt;a class=\"more\" href=\"&lt;?php echo get_category_link( $cate ) ?&gt;\"&gt;More&lt;/a&gt;\n &lt;/h2&gt;\n &lt;/header&gt;\n &lt;div class=\"row\"&gt;\n &lt;?php\n\n $posts = get_posts( array (\n \"category\" =&gt; $cate-&gt;term_id, // empty value will query a bunch of posts\n \"numberposts\" =&gt; 12,\n ) );\n\n foreach ( $posts as $post_object ) {\n\n setup_postdata( $GLOBALS['post'] =&amp; $post_object );\n\n ?&gt;\n &lt;article class=\"col-xs-4 col-sm-3 col-md-2 \"&gt;\n &lt;?php get_template_part( \"grid-item\" ) ?&gt;\n &lt;/article&gt;\n &lt;?php\n }\n\n wp_reset_postdata(); // like wp_reset_query() but for $post\n\n ?&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n &lt;/section&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 245058, "author": "hguser", "author_id": 104900, "author_profile": "https://wordpress.stackexchange.com/users/104900", "pm_score": 1, "selected": false, "text": "<p>Finally, I figure it out.</p>\n\n<p>It seems that the <code>get_posts</code> and <code>query_posts</code> accept different arguments, when I use the <code>get_posts</code> I can setup the arguments like this:</p>\n\n<pre><code> get_posts(array(\n \"category\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>While when I use <code>query_posts</code> I have change that to:</p>\n\n<pre><code> query_posts(array(\n \"cat\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>Notice the <code>category</code> to <code>cat</code>. This is a sad story.:(</p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104900/" ]
In my index page, I want to display 12 posts for each category, so I iterate the categories: ``` <?php foreach ($sub_cates as $cate) { ?> <section class="b"> <div class="grid"> <header class="title"> <h2><?php echo $cate->name ?><a class="more" href="<?php echo get_category_link($cate) ?>">More</a></h2> </header> <div class="row"> <?php //rewind_posts(); query_posts(array( "category" => $cate->term_id, "numberposts" => 12 )); $w = $GLOBALS['wp_query']; while (have_posts()) { the_post(); ?> <article class="col-xs-4 col-sm-3 col-md-2 "> <?php get_template_part("grid-item") ?> </article> <?php } ?> </div> </div> </section> <?php } ?> ``` However each section print the same collections of posts, even after I use the `rewind_posts` before the loop. What's going on?
Finally, I figure it out. It seems that the `get_posts` and `query_posts` accept different arguments, when I use the `get_posts` I can setup the arguments like this: ``` get_posts(array( "category" => $cate->term_id, "numberposts" => 12 )); ``` While when I use `query_posts` I have change that to: ``` query_posts(array( "cat" => $cate->term_id, "numberposts" => 12 )); ``` Notice the `category` to `cat`. This is a sad story.:(
245,068
<p>I'm using woocommerce which is working fine. On the template for the related products for example you'll find this:</p> <pre><code>&lt;?php woocommerce_product_loop_start(); ?&gt; </code></pre> <p>This calls the loop-start.php. Is there any possibility to add some variables to this function which I can call in the loop-start.php?</p> <p>for example: woocommerce_product_loop_start($test)</p> <p>And in loop-start.php I can do "echo $test". I also tried with global variables but it didn't work out.</p> <p>Same goes for the content loop call "wc_get_template_part( 'content', 'product' );". Can I add some variables on this?</p> <p>Thank you very much.</p>
[ { "answer_id": 245053, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>The job of <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow noreferrer\"><code>rewind_posts()</code></a> is to rewind the same query -- which is not was you want in this case.</p>\n\n<p>Have you tried with <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata#Example_1\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> instead? <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a> is needed for the <code>$post</code> object but <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\"><code>wp_reset_query()</code></a> isn't required after the loop in this case.</p>\n\n<pre><code>&lt;?php foreach ( $sub_cates as $cate ) { ?&gt;\n\n &lt;section class=\"b\"&gt;\n &lt;div class=\"grid\"&gt;\n &lt;header class=\"title\"&gt;\n &lt;h2&gt;&lt;?php echo $cate-&gt;name ?&gt;&lt;a class=\"more\" href=\"&lt;?php echo get_category_link( $cate ) ?&gt;\"&gt;More&lt;/a&gt;\n &lt;/h2&gt;\n &lt;/header&gt;\n &lt;div class=\"row\"&gt;\n &lt;?php\n\n $posts = get_posts( array (\n \"category\" =&gt; $cate-&gt;term_id, // empty value will query a bunch of posts\n \"numberposts\" =&gt; 12,\n ) );\n\n foreach ( $posts as $post_object ) {\n\n setup_postdata( $GLOBALS['post'] =&amp; $post_object );\n\n ?&gt;\n &lt;article class=\"col-xs-4 col-sm-3 col-md-2 \"&gt;\n &lt;?php get_template_part( \"grid-item\" ) ?&gt;\n &lt;/article&gt;\n &lt;?php\n }\n\n wp_reset_postdata(); // like wp_reset_query() but for $post\n\n ?&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n &lt;/section&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 245058, "author": "hguser", "author_id": 104900, "author_profile": "https://wordpress.stackexchange.com/users/104900", "pm_score": 1, "selected": false, "text": "<p>Finally, I figure it out.</p>\n\n<p>It seems that the <code>get_posts</code> and <code>query_posts</code> accept different arguments, when I use the <code>get_posts</code> I can setup the arguments like this:</p>\n\n<pre><code> get_posts(array(\n \"category\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>While when I use <code>query_posts</code> I have change that to:</p>\n\n<pre><code> query_posts(array(\n \"cat\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>Notice the <code>category</code> to <code>cat</code>. This is a sad story.:(</p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245068", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28159/" ]
I'm using woocommerce which is working fine. On the template for the related products for example you'll find this: ``` <?php woocommerce_product_loop_start(); ?> ``` This calls the loop-start.php. Is there any possibility to add some variables to this function which I can call in the loop-start.php? for example: woocommerce\_product\_loop\_start($test) And in loop-start.php I can do "echo $test". I also tried with global variables but it didn't work out. Same goes for the content loop call "wc\_get\_template\_part( 'content', 'product' );". Can I add some variables on this? Thank you very much.
Finally, I figure it out. It seems that the `get_posts` and `query_posts` accept different arguments, when I use the `get_posts` I can setup the arguments like this: ``` get_posts(array( "category" => $cate->term_id, "numberposts" => 12 )); ``` While when I use `query_posts` I have change that to: ``` query_posts(array( "cat" => $cate->term_id, "numberposts" => 12 )); ``` Notice the `category` to `cat`. This is a sad story.:(
245,070
<p>We have a WordPress based News Website... A few months back we started customizing the website (some changes in the Post and page layout and look) on a copy/Staging Website and also kept adding new News/Posts, Pages on Old Original Website. On Old website, we have thousands of posts and pages grown up with the passage of time.</p> <p>Now, when we are planning to make the website live, we want to have (Keep) these posts, but obviously if we will replace/deploy from the Staging to Live we will loose these posts as on Staging we never added New Posts. Writing/Adding these posts and pages on the newly migrated website will be a trouble, so how we can handle this situation where we do not loose our Pages and Posts. Away can be to use the Plugins like WP Exporter but don't it affect the Layout of the Pages and Posts as we have also done some customizations on the Pages/Posts on Staging Website. Please advise with the most efficient solution. Thanks in advance!</p>
[ { "answer_id": 245053, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>The job of <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow noreferrer\"><code>rewind_posts()</code></a> is to rewind the same query -- which is not was you want in this case.</p>\n\n<p>Have you tried with <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata#Example_1\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> instead? <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a> is needed for the <code>$post</code> object but <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\"><code>wp_reset_query()</code></a> isn't required after the loop in this case.</p>\n\n<pre><code>&lt;?php foreach ( $sub_cates as $cate ) { ?&gt;\n\n &lt;section class=\"b\"&gt;\n &lt;div class=\"grid\"&gt;\n &lt;header class=\"title\"&gt;\n &lt;h2&gt;&lt;?php echo $cate-&gt;name ?&gt;&lt;a class=\"more\" href=\"&lt;?php echo get_category_link( $cate ) ?&gt;\"&gt;More&lt;/a&gt;\n &lt;/h2&gt;\n &lt;/header&gt;\n &lt;div class=\"row\"&gt;\n &lt;?php\n\n $posts = get_posts( array (\n \"category\" =&gt; $cate-&gt;term_id, // empty value will query a bunch of posts\n \"numberposts\" =&gt; 12,\n ) );\n\n foreach ( $posts as $post_object ) {\n\n setup_postdata( $GLOBALS['post'] =&amp; $post_object );\n\n ?&gt;\n &lt;article class=\"col-xs-4 col-sm-3 col-md-2 \"&gt;\n &lt;?php get_template_part( \"grid-item\" ) ?&gt;\n &lt;/article&gt;\n &lt;?php\n }\n\n wp_reset_postdata(); // like wp_reset_query() but for $post\n\n ?&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n &lt;/section&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 245058, "author": "hguser", "author_id": 104900, "author_profile": "https://wordpress.stackexchange.com/users/104900", "pm_score": 1, "selected": false, "text": "<p>Finally, I figure it out.</p>\n\n<p>It seems that the <code>get_posts</code> and <code>query_posts</code> accept different arguments, when I use the <code>get_posts</code> I can setup the arguments like this:</p>\n\n<pre><code> get_posts(array(\n \"category\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>While when I use <code>query_posts</code> I have change that to:</p>\n\n<pre><code> query_posts(array(\n \"cat\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>Notice the <code>category</code> to <code>cat</code>. This is a sad story.:(</p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245070", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101240/" ]
We have a WordPress based News Website... A few months back we started customizing the website (some changes in the Post and page layout and look) on a copy/Staging Website and also kept adding new News/Posts, Pages on Old Original Website. On Old website, we have thousands of posts and pages grown up with the passage of time. Now, when we are planning to make the website live, we want to have (Keep) these posts, but obviously if we will replace/deploy from the Staging to Live we will loose these posts as on Staging we never added New Posts. Writing/Adding these posts and pages on the newly migrated website will be a trouble, so how we can handle this situation where we do not loose our Pages and Posts. Away can be to use the Plugins like WP Exporter but don't it affect the Layout of the Pages and Posts as we have also done some customizations on the Pages/Posts on Staging Website. Please advise with the most efficient solution. Thanks in advance!
Finally, I figure it out. It seems that the `get_posts` and `query_posts` accept different arguments, when I use the `get_posts` I can setup the arguments like this: ``` get_posts(array( "category" => $cate->term_id, "numberposts" => 12 )); ``` While when I use `query_posts` I have change that to: ``` query_posts(array( "cat" => $cate->term_id, "numberposts" => 12 )); ``` Notice the `category` to `cat`. This is a sad story.:(
245,097
<p>I want to hide my custom post type from search results. So, I followed the codex and used:</p> <p><code>exclude_from_search =&gt; 'true'</code> while registering my custom post type.</p> <p>That hides the custom post type and it does not appear in search results any more. </p> <p>But now I am unable to load posts using <code>get_posts</code> but they appear fine with <code>WP_Query</code>. I wonder why it is happening.</p>
[ { "answer_id": 245053, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>The job of <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow noreferrer\"><code>rewind_posts()</code></a> is to rewind the same query -- which is not was you want in this case.</p>\n\n<p>Have you tried with <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata#Example_1\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> instead? <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a> is needed for the <code>$post</code> object but <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\"><code>wp_reset_query()</code></a> isn't required after the loop in this case.</p>\n\n<pre><code>&lt;?php foreach ( $sub_cates as $cate ) { ?&gt;\n\n &lt;section class=\"b\"&gt;\n &lt;div class=\"grid\"&gt;\n &lt;header class=\"title\"&gt;\n &lt;h2&gt;&lt;?php echo $cate-&gt;name ?&gt;&lt;a class=\"more\" href=\"&lt;?php echo get_category_link( $cate ) ?&gt;\"&gt;More&lt;/a&gt;\n &lt;/h2&gt;\n &lt;/header&gt;\n &lt;div class=\"row\"&gt;\n &lt;?php\n\n $posts = get_posts( array (\n \"category\" =&gt; $cate-&gt;term_id, // empty value will query a bunch of posts\n \"numberposts\" =&gt; 12,\n ) );\n\n foreach ( $posts as $post_object ) {\n\n setup_postdata( $GLOBALS['post'] =&amp; $post_object );\n\n ?&gt;\n &lt;article class=\"col-xs-4 col-sm-3 col-md-2 \"&gt;\n &lt;?php get_template_part( \"grid-item\" ) ?&gt;\n &lt;/article&gt;\n &lt;?php\n }\n\n wp_reset_postdata(); // like wp_reset_query() but for $post\n\n ?&gt;\n &lt;/div&gt;\n\n &lt;/div&gt;\n &lt;/section&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 245058, "author": "hguser", "author_id": 104900, "author_profile": "https://wordpress.stackexchange.com/users/104900", "pm_score": 1, "selected": false, "text": "<p>Finally, I figure it out.</p>\n\n<p>It seems that the <code>get_posts</code> and <code>query_posts</code> accept different arguments, when I use the <code>get_posts</code> I can setup the arguments like this:</p>\n\n<pre><code> get_posts(array(\n \"category\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>While when I use <code>query_posts</code> I have change that to:</p>\n\n<pre><code> query_posts(array(\n \"cat\" =&gt; $cate-&gt;term_id,\n \"numberposts\" =&gt; 12\n ));\n</code></pre>\n\n<p>Notice the <code>category</code> to <code>cat</code>. This is a sad story.:(</p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102532/" ]
I want to hide my custom post type from search results. So, I followed the codex and used: `exclude_from_search => 'true'` while registering my custom post type. That hides the custom post type and it does not appear in search results any more. But now I am unable to load posts using `get_posts` but they appear fine with `WP_Query`. I wonder why it is happening.
Finally, I figure it out. It seems that the `get_posts` and `query_posts` accept different arguments, when I use the `get_posts` I can setup the arguments like this: ``` get_posts(array( "category" => $cate->term_id, "numberposts" => 12 )); ``` While when I use `query_posts` I have change that to: ``` query_posts(array( "cat" => $cate->term_id, "numberposts" => 12 )); ``` Notice the `category` to `cat`. This is a sad story.:(
245,109
<p>I am building a site/theme where post content is authored in a modular way (mostly, but not exclusively) with ACF's flexible content field. These fields could have JavaScript functionality attached to them on the public front-end. You might have an image upload that has parallax applied to it or a text block that has a click or hover animation applied to it, for example. I'm trying to determine the most useful method for conditionally loading the different JavaScript libraries that might power this functionality (in the post, as the public sees it, I'm not talking about the admin side). Specifically I'm trying to avoid always loading everything, instead I'm hoping to load specific libraries based on the fields actually present in the post. Is there an established way, outside of the brute force method of looping through the content multiple times to first check for fields and then later to display them?</p>
[ { "answer_id": 245112, "author": "lavekyl", "author_id": 106322, "author_profile": "https://wordpress.stackexchange.com/users/106322", "pm_score": 2, "selected": false, "text": "<p>I would suggest using the True/False in ACF to determine whether you should load the scripts you are referencing. And create a function for those specific scripts to load them if \"True\". Something like this...</p>\n\n<pre><code>&lt;?php\n\n if( get_field('true_false_field') ) { \n add_action( 'wp_enqueue_scripts', 'enqueue_the_script' );\n }\n\n function enqueue_the_script() {\n wp_enqueue_script( 'my-js', 'filename.js', false );\n }\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 245191, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 3, "selected": true, "text": "<p>ACF has finegrained <a href=\"https://www.advancedcustomfields.com/resources/acf-load_field/\" rel=\"nofollow noreferrer\">filters</a> for fields when they get loaded. </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'register_my_scripts', 5 );\nfunction register_my_scripts() {\n wp_register_script( 'my-script', 'path-to/my-script.js', array(), 'version', true );\n}\n\nadd_filter('acf/load_field/name=my_field_name', 'load_field_my_field_name');\nfunction load_field_my_field_name( $field ) {\n wp_enqueue_script( 'my-script' );\n return $field;\n}\n</code></pre>\n\n<p>Normally all scripts should be enqueued in <code>wp_enqueue_scripts</code> hook. So you should make sure your script and its dependencies (which haven't been loaded yet) can be loaded in footer. Like this your script gets enqueued when the fields are accessed in the content.</p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98703/" ]
I am building a site/theme where post content is authored in a modular way (mostly, but not exclusively) with ACF's flexible content field. These fields could have JavaScript functionality attached to them on the public front-end. You might have an image upload that has parallax applied to it or a text block that has a click or hover animation applied to it, for example. I'm trying to determine the most useful method for conditionally loading the different JavaScript libraries that might power this functionality (in the post, as the public sees it, I'm not talking about the admin side). Specifically I'm trying to avoid always loading everything, instead I'm hoping to load specific libraries based on the fields actually present in the post. Is there an established way, outside of the brute force method of looping through the content multiple times to first check for fields and then later to display them?
ACF has finegrained [filters](https://www.advancedcustomfields.com/resources/acf-load_field/) for fields when they get loaded. ``` add_action( 'wp_enqueue_scripts', 'register_my_scripts', 5 ); function register_my_scripts() { wp_register_script( 'my-script', 'path-to/my-script.js', array(), 'version', true ); } add_filter('acf/load_field/name=my_field_name', 'load_field_my_field_name'); function load_field_my_field_name( $field ) { wp_enqueue_script( 'my-script' ); return $field; } ``` Normally all scripts should be enqueued in `wp_enqueue_scripts` hook. So you should make sure your script and its dependencies (which haven't been loaded yet) can be loaded in footer. Like this your script gets enqueued when the fields are accessed in the content.
245,111
<p>I am working on Arabic wordpress website and I have a problem when using arabic title for the post. the single post page always redirect to 404 page but with english permalinks it work perfectly</p> <p>when I tried to use <code>the_permalink();</code> it returns:</p> <pre><code>http://a3lamy.com/%d8%aa%d8%ac%d8%b1%d8%a8%d8%a9/ </code></pre> <p>while in wordpress admin dashboard when edit post the permalink looks like:</p> <pre><code>http://a3lamy.com/تجربة/ </code></pre> <p>the datebase server collation is <code>utf8_general_ci</code></p> <p>when I open the wp-posts table I found the post-name is :</p> <pre><code>%d8%aa%d8%ac%d8%b1%d8%a8%d8%a9 </code></pre> <p>and when I change it manually it become <code>تجربة</code> in the database but still the permalink redirects to 404 not found page!</p> <p>My web.config</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;rewrite&gt; &lt;rules&gt; &lt;rule name="WordPress Rule" stopProcessing="true"&gt; &lt;match url=".*" /&gt; &lt;conditions&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /&gt; &lt;/conditions&gt; &lt;action type="Rewrite" url="index.php" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Any help will be appreciated.</p>
[ { "answer_id": 245121, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>That's because what you want isn't possible, the RFC says URLs must be a subset of ANSI characters, which covers a subset of latin a-Z characters, numbers and symbols. There is no such thing as a Unicode URL, and it has nothing to do with your database encoding, WordPress is doing its job and this is expected behaviour.</p>\n\n<p><a href=\"http://www.blooberry.com/indexdot/html/topics/urlencoding.htm\" rel=\"nofollow noreferrer\">http://www.blooberry.com/indexdot/html/topics/urlencoding.htm</a></p>\n\n<blockquote>\n <p>\"...Only alphanumerics [0-9a-zA-Z], the special characters \"$-_.+!*'(),\" [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL.\"</p>\n</blockquote>\n\n<p>However, not every country speaks US english, so we have RFC3986:\n <a href=\"http://www.faqs.org/rfcs/rfc3986.html\" rel=\"nofollow noreferrer\">http://www.faqs.org/rfcs/rfc3986.html</a></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier\" rel=\"nofollow noreferrer\">Wikipedia</a> says:</p>\n\n<blockquote>\n <p>While URIs are limited to a subset of the ASCII character set, IRIs may contain characters from the Universal Character Set (Unicode/ISO 10646), including Chinese or Japanese kanji, Korean, Cyrillic characters, and so forth.</p>\n \n <h3>Syntax</h3>\n \n <p>IRI extend upon URIs by using the Universal Character Set whereas URIs were limited to the ASCII with far fewer characters. IRIs may be represented by a sequence of octets but by definition is defined as a sequence of characters because IRIs can be spoken or written by hand.<a href=\"https://i.stack.imgur.com/IIBUq.png\" rel=\"nofollow noreferrer\">2</a>\n This is how URLs work with foreign non-ANSI characters. Because URLs only support a subset of ANSI, non-latin characters must be encoded.</p>\n</blockquote>\n\n<p>It's not great, but the original HTTP spec can't handle non-english characters, and this is the hack they used to get around that. The same thing will happen with Kanji, emoji, and other non-english letters</p>\n\n<h1>An Experiment</h1>\n\n<p>So if I create a test page named تجربة :</p>\n\n<p><a href=\"https://i.stack.imgur.com/CxXGV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CxXGV.png\" alt=\"edit screen\"></a></p>\n\n<p>Then visit the page:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IIBUq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IIBUq.png\" alt=\"the page\"></a></p>\n\n<p>Everything looks correct, but if I copy paste the URL, I get this:</p>\n\n<pre><code>https://tomjn.com/%D8%AA%D8%AC%D8%B1%D8%A8%D8%A9/\n</code></pre>\n\n<p>Which is the <a href=\"https://tomjn.com/%D8%AA%D8%AC%D8%B1%D8%A8%D8%A9/\" rel=\"nofollow noreferrer\">https://tomjn.com/تجربة/</a> encoded as a URL</p>\n\n<p>%D8%AA%D8%AC%D8%B1%D8%A8%D8%A9 is a set of arabic characters, where each % encoded octet represents the character code in the universal character set </p>\n\n<p>This is expected behaviour, and how it's supposed to work and is implemented in all browsers and HTTP speaking applications that support internationalised URLs and domains</p>\n\n<p>The reason <code>the_permalink</code> does this is because it runs the URL through <code>esc_url</code> and <code>urlencode</code>, but if you removed this and output it as is on the page, it wouldn't change things as the browser would then do it automatically at the users end. If it didn't, then you'd end up with a mangled HTTP request that didn't work correctly.</p>\n\n<h1>So Where Do the 404s Come From?</h1>\n\n<p>If you go into the database and change the slug manually to <code>تجربة</code> then WordPress will never be able to find it. The browser will change it to <code>%d8%aa%d8%ac%d8%b1%d8%a8%d8%a9</code>, and WP will then search for that in the database. It won't find it though as it's been changed to <code>تجربة</code></p>\n" }, { "answer_id": 301362, "author": "SOAL ABDELDJALLIL", "author_id": 124518, "author_profile": "https://wordpress.stackexchange.com/users/124518", "pm_score": 2, "selected": false, "text": "<p>This issues is caused due to IIS does not recognize the multi language urls,</p>\n\n<p>You need to add the following code at the end of the wp-config.php file:</p>\n\n<pre><code>if ( isset($_SERVER['UNENCODED_URL']) ) {\n$_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL'];}\n</code></pre>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88617/" ]
I am working on Arabic wordpress website and I have a problem when using arabic title for the post. the single post page always redirect to 404 page but with english permalinks it work perfectly when I tried to use `the_permalink();` it returns: ``` http://a3lamy.com/%d8%aa%d8%ac%d8%b1%d8%a8%d8%a9/ ``` while in wordpress admin dashboard when edit post the permalink looks like: ``` http://a3lamy.com/تجربة/ ``` the datebase server collation is `utf8_general_ci` when I open the wp-posts table I found the post-name is : ``` %d8%aa%d8%ac%d8%b1%d8%a8%d8%a9 ``` and when I change it manually it become `تجربة` in the database but still the permalink redirects to 404 not found page! My web.config ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="WordPress Rule" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="index.php" /> </rule> </rules> </rewrite> </system.webServer> </configuration> ``` Any help will be appreciated.
That's because what you want isn't possible, the RFC says URLs must be a subset of ANSI characters, which covers a subset of latin a-Z characters, numbers and symbols. There is no such thing as a Unicode URL, and it has nothing to do with your database encoding, WordPress is doing its job and this is expected behaviour. <http://www.blooberry.com/indexdot/html/topics/urlencoding.htm> > > "...Only alphanumerics [0-9a-zA-Z], the special characters "$-\_.+!\*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL." > > > However, not every country speaks US english, so we have RFC3986: <http://www.faqs.org/rfcs/rfc3986.html> [Wikipedia](https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier) says: > > While URIs are limited to a subset of the ASCII character set, IRIs may contain characters from the Universal Character Set (Unicode/ISO 10646), including Chinese or Japanese kanji, Korean, Cyrillic characters, and so forth. > > > ### Syntax > > > IRI extend upon URIs by using the Universal Character Set whereas URIs were limited to the ASCII with far fewer characters. IRIs may be represented by a sequence of octets but by definition is defined as a sequence of characters because IRIs can be spoken or written by hand.[2](https://i.stack.imgur.com/IIBUq.png) > This is how URLs work with foreign non-ANSI characters. Because URLs only support a subset of ANSI, non-latin characters must be encoded. > > > It's not great, but the original HTTP spec can't handle non-english characters, and this is the hack they used to get around that. The same thing will happen with Kanji, emoji, and other non-english letters An Experiment ============= So if I create a test page named تجربة : [![edit screen](https://i.stack.imgur.com/CxXGV.png)](https://i.stack.imgur.com/CxXGV.png) Then visit the page: [![the page](https://i.stack.imgur.com/IIBUq.png)](https://i.stack.imgur.com/IIBUq.png) Everything looks correct, but if I copy paste the URL, I get this: ``` https://tomjn.com/%D8%AA%D8%AC%D8%B1%D8%A8%D8%A9/ ``` Which is the [https://tomjn.com/تجربة/](https://tomjn.com/%D8%AA%D8%AC%D8%B1%D8%A8%D8%A9/) encoded as a URL %D8%AA%D8%AC%D8%B1%D8%A8%D8%A9 is a set of arabic characters, where each % encoded octet represents the character code in the universal character set This is expected behaviour, and how it's supposed to work and is implemented in all browsers and HTTP speaking applications that support internationalised URLs and domains The reason `the_permalink` does this is because it runs the URL through `esc_url` and `urlencode`, but if you removed this and output it as is on the page, it wouldn't change things as the browser would then do it automatically at the users end. If it didn't, then you'd end up with a mangled HTTP request that didn't work correctly. So Where Do the 404s Come From? =============================== If you go into the database and change the slug manually to `تجربة` then WordPress will never be able to find it. The browser will change it to `%d8%aa%d8%ac%d8%b1%d8%a8%d8%a9`, and WP will then search for that in the database. It won't find it though as it's been changed to `تجربة`
245,114
<p>I'm creating plugin and can't understand how to add custom fields like in WooCommerce - selects, inputs, textareas, etc.</p> <p>I'm talking not about WP Custom fields. I've registered custom post type with <code>register_post_type</code> function with arguments:</p> <pre><code>'capability_type' =&gt; 'post', 'supports' =&gt; array( 'title', 'custom-fields' ) </code></pre> <p>And now I have only <code>Title</code> and <code>Custom fields</code>. How I can add some custom inputs/select/radiobuttons to <code>Edit %custom_post_type%</code> page?</p>
[ { "answer_id": 245116, "author": "lavekyl", "author_id": 106322, "author_profile": "https://wordpress.stackexchange.com/users/106322", "pm_score": 1, "selected": false, "text": "<p>Use the Advanced Custom Fields plugin to add some additional fields to your Custom Post Type. It's free in the plugin directory and has plenty of examples on the website.</p>\n\n<p>Plugin Page: <a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/advanced-custom-fields/</a></p>\n\n<p>Website: <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/</a></p>\n" }, { "answer_id": 245119, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>You need to add your own metabox for the custom post type created. You can use the action <code>add_meta_boxes_{cpt_slug}</code></p>\n\n<pre><code>add_action( 'add_meta_boxes_' . $cpt_public_slug, 'adding_custom_meta_boxes' );\nadd_action( 'save_post', 'save_metabox' , 10, 2 );\n\nfunction adding_custom_meta_boxes(){\n global $cpt_public_slug;\n add_meta_box(\n 'plugin-site',\n __( 'Website', 'text_domain' ),\n 'cpt_form_site_Render',\n $cpt_public_slug,\n 'normal',\n 'high'\n );\n}\n\nfunction cpt_form_site_Render(){\n global $post;\n\n $post_meta = get_post_meta($post-&gt;ID); \n\n // render the input field\n ?&gt;\n &lt;input type=\"text\" name=\"meta_key\" value=\"&lt;?php echo $post_meta['meta_value'][0]; ?&gt;\"/&gt;\n &lt;?php\n // do it for all your metas\n}\n\nfunction save_metabox($post_id, $post){\n\n foreach ($_POST as $the_posted_key=&gt;$the_posted_value) {\n if (strpos($the_posted_key, brozzme_passport_config::$custom_fields_prefix)!==false) {\n update_post_meta($post_id, $the_posted_key, $the_posted_value);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 274505, "author": "pptigra", "author_id": 124508, "author_profile": "https://wordpress.stackexchange.com/users/124508", "pm_score": 1, "selected": false, "text": "<p>there is working example. I used it for bbpress custom metabox creation</p>\n\n<pre><code>$cpt_public_slug = 'topic';\n\nadd_action( 'add_meta_boxes_' . $cpt_public_slug, 'adding_custom_meta_boxes' );\nadd_action( 'save_post', 'save_metabox' , 10, 2 );\nadd_action( 'publish_'.$cpt_public_slug, 'save_metabox' , 10, 2 );\n\nfunction adding_custom_meta_boxes(){\n global $cpt_public_slug;\n add_meta_box('topictimeout', 'Time', 'cpt_form_site_Render', $cpt_public_slug, 'side', 'high');\n}\n\nfunction cpt_form_site_Render(){\n global $post;\n $post_meta = get_post_meta($post->ID); \n // put here input or textarea \n }\n\nfunction save_metabox($post_id, $post){\n global $post;\n// when first publish and then save\n if( isset( $_POST['save'] ) || isset( $_POST['publish'] ) ) {\n\n // you will need to use a $_POST param and validate before saving\n $meta_val = isset( $_POST['topictimeout'] ) ? sanitize_text_field( $_POST['topictimeout'] ) : '';\n // the $meta_val would be a $_POST param from inner meta box form\n update_post_meta($post_id, 'topictimeout', $meta_val);\n }\n\n}</code></pre>\n\n<p>U can put there this input for example:</p>\n\n<pre><code>&lt;input type=\"text\" name=\"topictimeout\" value=\"&lt;?=$post_meta['topictimeout'][0]; ?&gt;\"/&gt; in minutes\n</code></pre>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245114", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88455/" ]
I'm creating plugin and can't understand how to add custom fields like in WooCommerce - selects, inputs, textareas, etc. I'm talking not about WP Custom fields. I've registered custom post type with `register_post_type` function with arguments: ``` 'capability_type' => 'post', 'supports' => array( 'title', 'custom-fields' ) ``` And now I have only `Title` and `Custom fields`. How I can add some custom inputs/select/radiobuttons to `Edit %custom_post_type%` page?
You need to add your own metabox for the custom post type created. You can use the action `add_meta_boxes_{cpt_slug}` ``` add_action( 'add_meta_boxes_' . $cpt_public_slug, 'adding_custom_meta_boxes' ); add_action( 'save_post', 'save_metabox' , 10, 2 ); function adding_custom_meta_boxes(){ global $cpt_public_slug; add_meta_box( 'plugin-site', __( 'Website', 'text_domain' ), 'cpt_form_site_Render', $cpt_public_slug, 'normal', 'high' ); } function cpt_form_site_Render(){ global $post; $post_meta = get_post_meta($post->ID); // render the input field ?> <input type="text" name="meta_key" value="<?php echo $post_meta['meta_value'][0]; ?>"/> <?php // do it for all your metas } function save_metabox($post_id, $post){ foreach ($_POST as $the_posted_key=>$the_posted_value) { if (strpos($the_posted_key, brozzme_passport_config::$custom_fields_prefix)!==false) { update_post_meta($post_id, $the_posted_key, $the_posted_value); } } } ```
245,120
<p>I would like to rewrite the default post type URL to <code>/blog/2016/11/my-post-name/</code> without affect the other post type url. I tried:</p> <pre><code>add_action('admin_menu','remove_default_post_type'); function remove_default_post_type() { remove_menu_page('edit.php'); } add_action( 'init', 'set_default_post_type', 1 ); function set_default_post_type() { register_post_type( 'post', array( 'labels' =&gt; array( 'name_admin_bar' =&gt; _x( 'Post', 'add new on admin bar' ), ), 'public' =&gt; true, '_builtin' =&gt; false, '_edit_link' =&gt; 'post.php?post=%d', 'capability_type' =&gt; 'post', 'map_meta_cap' =&gt; true, 'hierarchical' =&gt; false, 'rewrite' =&gt; array( 'slug' =&gt; 'blog/%year%/%monthnum%/%postname%/', 'with_front'=&gt; false, ), 'query_var' =&gt; false, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); } </code></pre> <p>But with no success. The url stay as <code>/blog/my-post</code>. Is there one way to have permalinks of default post type like <code>/blog/2016/11/my-post-name/</code> (where 2016 is the year of post and 11 is the month of post) Without affect others post types urls?</p>
[ { "answer_id": 245136, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Use the field in the admin <code>Settings &gt; Permalinks</code> page to set your permalink structure to <code>/blog/%year%/%monthnum%/%postname%/</code>.</p>\n\n<p>To prevent custom post types from inheriting the post permalink structure, set <code>with_front</code> to <code>false</code> in your <code>register_post_type</code> arguments for all custom post types.</p>\n\n<p>Version 4.4 also added the <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\" rel=\"nofollow noreferrer\"><code>register_post_type_args</code></a> filter to allow modification of post type arguments for types registered by code you don't have access to change.</p>\n" }, { "answer_id": 245137, "author": "Demyd Ganenko", "author_id": 88455, "author_profile": "https://wordpress.stackexchange.com/users/88455", "pm_score": 0, "selected": false, "text": "<p>You can use <code>Custom Permalink</code> plugin <a href=\"https://ru.wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow noreferrer\">https://ru.wordpress.org/plugins/custom-permalinks/</a></p>\n\n<p>But it can't use permalink \"templates\". You will need to enter your custom permalink for each post on editing page.</p>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106326/" ]
I would like to rewrite the default post type URL to `/blog/2016/11/my-post-name/` without affect the other post type url. I tried: ``` add_action('admin_menu','remove_default_post_type'); function remove_default_post_type() { remove_menu_page('edit.php'); } add_action( 'init', 'set_default_post_type', 1 ); function set_default_post_type() { register_post_type( 'post', array( 'labels' => array( 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ), ), 'public' => true, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => array( 'slug' => 'blog/%year%/%monthnum%/%postname%/', 'with_front'=> false, ), 'query_var' => false, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); } ``` But with no success. The url stay as `/blog/my-post`. Is there one way to have permalinks of default post type like `/blog/2016/11/my-post-name/` (where 2016 is the year of post and 11 is the month of post) Without affect others post types urls?
Use the field in the admin `Settings > Permalinks` page to set your permalink structure to `/blog/%year%/%monthnum%/%postname%/`. To prevent custom post types from inheriting the post permalink structure, set `with_front` to `false` in your `register_post_type` arguments for all custom post types. Version 4.4 also added the [`register_post_type_args`](https://developer.wordpress.org/reference/hooks/register_post_type_args/) filter to allow modification of post type arguments for types registered by code you don't have access to change.
245,126
<p>I'm trying to enque stylesheet depending on template but unfortunetelly my code isn't working. What I am doing wrong?</p> <pre><code> if ( is_page_template('single-location.php')) { function themename_include_page_specific_css() { wp_enqueue_style('paralax_style', get_template_directory_uri().'/paralax.css'); } add_action('wp_enqueue_scripts', 'paralax_style'); } </code></pre> <p>I tried also with that one, but still nothing.</p> <pre><code> function load_theme_files() { if (is_page_template('single-location.php')) { wp_enqueue_style('paralax_style', esc_url( get_template_directory_uri() ).'/paralax.css'); } } add_action('wp_enqueue_scripts', 'load_theme_files'); </code></pre>
[ { "answer_id": 245130, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You need to first register the style and then en-queue it! This might work!</p>\n\n<pre><code>function custom_style_method() {\n wp_register_style( 'paralax_style', get_template_directory_uri().'/paralax.css' );\n}\nadd_action('wp_enqueue_scripts', 'custom_style_method');\n\nadd_filter( 'template_include', 'themename_include_page_specific_css', 1000 );\n\nfunction themename_include_page_specific_css( $template ){\n\n if ( is_page_template('single-location.php' ) ) {\n wp_enqueue_style( 'paralax_style' );\n }\n\nreturn $template;\n}\n</code></pre>\n" }, { "answer_id": 245138, "author": "lavekyl", "author_id": 106322, "author_profile": "https://wordpress.stackexchange.com/users/106322", "pm_score": 2, "selected": false, "text": "<p>Try this putting this code in your function where you enqueue your other scripts and styles and it should work.</p>\n\n<pre><code>wp_register_style( 'template-style', get_stylesheet_directory_uri().'/templates/css/template.css', array(), '', true );\n\nif ( is_page_template( 'template-name.php' ) ) {\n wp_enqueue_style( 'template-style' );\n}\n</code></pre>\n" }, { "answer_id": 245155, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 1, "selected": false, "text": "<p><code>single-location.php</code> naming for a page template is very poor choice as it conflicts with default page <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow noreferrer\">template hierarchy</a> <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow noreferrer\"><code>single-$posttype.php</code></a>.</p>\n\n<p>So I would encourage you to change the name to something like <code>tem-location.php</code>, then the following code will work, also please take a note at enqueue handler because that should also not conflict with others(I mean if you already have a script/style enqueued with handle <code>paralar-style</code> then even if you enqueue the script/style with the same handle won't work.</p>\n\n<p>Also please make sure that your template location is correct, for example if you place <code>tem-location.php</code> in <code>page-templates</code> folder then you should check for <code>page-templates\\tem-location.php</code>.</p>\n\n<pre><code>function wpse245126_load_theme_files() {\n if (is_page_template('tem-location.php')) {\n wp_enqueue_style('tem-location-style', esc_url( get_template_directory_uri() ).'/paralax.css');\n }\n}\nadd_action('wp_enqueue_scripts', 'wpse245126_load_theme_files');\n</code></pre>\n" }, { "answer_id": 276593, "author": "PayteR", "author_id": 122916, "author_profile": "https://wordpress.stackexchange.com/users/122916", "pm_score": 0, "selected": false, "text": "<p>You can use this filter, to filter out styles with any condition, or alternate output href string on certain templates, example:</p>\n\n<pre><code>add_filter( 'style_loader_src', function($href){\nif(strpos($href, \"name-of-allowed.css\") !== false) {\nreturn $href;\n}\nreturn false;\n});\n</code></pre>\n" } ]
2016/11/04
[ "https://wordpress.stackexchange.com/questions/245126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105189/" ]
I'm trying to enque stylesheet depending on template but unfortunetelly my code isn't working. What I am doing wrong? ``` if ( is_page_template('single-location.php')) { function themename_include_page_specific_css() { wp_enqueue_style('paralax_style', get_template_directory_uri().'/paralax.css'); } add_action('wp_enqueue_scripts', 'paralax_style'); } ``` I tried also with that one, but still nothing. ``` function load_theme_files() { if (is_page_template('single-location.php')) { wp_enqueue_style('paralax_style', esc_url( get_template_directory_uri() ).'/paralax.css'); } } add_action('wp_enqueue_scripts', 'load_theme_files'); ```
You need to first register the style and then en-queue it! This might work! ``` function custom_style_method() { wp_register_style( 'paralax_style', get_template_directory_uri().'/paralax.css' ); } add_action('wp_enqueue_scripts', 'custom_style_method'); add_filter( 'template_include', 'themename_include_page_specific_css', 1000 ); function themename_include_page_specific_css( $template ){ if ( is_page_template('single-location.php' ) ) { wp_enqueue_style( 'paralax_style' ); } return $template; } ```
245,153
<p>I am building a theme where I need to add a dropcap to the first letter. This would be done by surrounding the character in question with <code>&lt;span class="dropcap&gt;</code> and <code>&lt;/span&gt;</code>. The actual work of making the dropcap will be done using <a href="http://webplatform.adobe.com/dropcap.js/" rel="nofollow noreferrer">Adobe's Dropcap.js</a>.</p> <p>I would like to do this for the output of <code>the_excerpt()</code> for sure. In addition I would also like to add this span tag to the first character of every Paragraph element that is a sibling of an H3 element (h3 + p).</p> <p>My preference is to do this with PHP as opposed to writing a JavaScript or jQuery script to parse the document and insert it.</p> <p>So far I have only tested this using <code>the_excerpt()</code> and it was an utter failure resulting in a Fatal error about allocated memory exhausted. But here is the code:</p> <pre><code>if ( ! function_exists( 'test_excerpt_dropcap' ) ) : function test_excerpt_dropcap() { global $post; $the_excerpt = get_the_excerpt(); if ( is_singular() &amp;&amp; has_excerpt() ) { $the_excerpt = preg_replace('/^(.)/', '&lt;span class="dropcap"&gt;\1&lt;/span&gt;', $the_excerpt); } return $the_excerpt; } add_filter( 'get_the_excerpt', 'test_excerpt_dropcap' ); endif; </code></pre>
[ { "answer_id": 245157, "author": "spacegrrl", "author_id": 83383, "author_profile": "https://wordpress.stackexchange.com/users/83383", "pm_score": 0, "selected": false, "text": "<p>You may be able to do this with CSS only. </p>\n\n<p>Provided there's a class that will let you select the excerpt, you can then use further CSS pseudo-classes to select the first letter of the first paragraph.</p>\n\n<pre><code>.excerpt p:first-of-type::first-letter {\n /* dropcap styling */\n}\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type\" rel=\"nofollow noreferrer\">first-of-type</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter\" rel=\"nofollow noreferrer\">first-letter</a></p>\n\n<p>Using a sibling selector can get you the first p tag after every h3, for the second task:</p>\n\n<pre><code>.content h3 + p::first-letter {\n /* dropcap styling */\n}\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors\" rel=\"nofollow noreferrer\">adjacent sibling selector</a></p>\n" }, { "answer_id": 245158, "author": "geomagas", "author_id": 39275, "author_profile": "https://wordpress.stackexchange.com/users/39275", "pm_score": 2, "selected": true, "text": "<p><code>get_the_excerpt()</code> returns the excerpt, but only <a href=\"https://codex.wordpress.org/Function_Reference/get_the_excerpt#Return_Values\" rel=\"nofollow noreferrer\">after applying <code>get_the_excerpt</code> filters to it</a>. This causes infinite recursion, as your filter handler will be called to an infinite depth.</p>\n\n<p>Of course, the best solution is the css one (see @spacegrrl's answer), but if you have your reasons for keeping that <code>&lt;span&gt;</code>, please note that the excerpt can be passed as a parameter to your handler. Just add an <code>$the_excerpt</code> parameter and use that, instead of calling <code>get_the_excerpt()</code>.</p>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80069/" ]
I am building a theme where I need to add a dropcap to the first letter. This would be done by surrounding the character in question with `<span class="dropcap>` and `</span>`. The actual work of making the dropcap will be done using [Adobe's Dropcap.js](http://webplatform.adobe.com/dropcap.js/). I would like to do this for the output of `the_excerpt()` for sure. In addition I would also like to add this span tag to the first character of every Paragraph element that is a sibling of an H3 element (h3 + p). My preference is to do this with PHP as opposed to writing a JavaScript or jQuery script to parse the document and insert it. So far I have only tested this using `the_excerpt()` and it was an utter failure resulting in a Fatal error about allocated memory exhausted. But here is the code: ``` if ( ! function_exists( 'test_excerpt_dropcap' ) ) : function test_excerpt_dropcap() { global $post; $the_excerpt = get_the_excerpt(); if ( is_singular() && has_excerpt() ) { $the_excerpt = preg_replace('/^(.)/', '<span class="dropcap">\1</span>', $the_excerpt); } return $the_excerpt; } add_filter( 'get_the_excerpt', 'test_excerpt_dropcap' ); endif; ```
`get_the_excerpt()` returns the excerpt, but only [after applying `get_the_excerpt` filters to it](https://codex.wordpress.org/Function_Reference/get_the_excerpt#Return_Values). This causes infinite recursion, as your filter handler will be called to an infinite depth. Of course, the best solution is the css one (see @spacegrrl's answer), but if you have your reasons for keeping that `<span>`, please note that the excerpt can be passed as a parameter to your handler. Just add an `$the_excerpt` parameter and use that, instead of calling `get_the_excerpt()`.
245,183
<p>I'm using toscho's <a href="https://gist.github.com/toscho/3804204" rel="nofollow noreferrer">Plugin Class Demo</a> code as a foundation for a plugin I'm developing. Amongst other things, my plugin registers a custom post type.</p> <pre><code>public function plugin_setup() { $this-&gt;plugin_url = plugins_url( '/', __FILE__ ); $this-&gt;plugin_path = plugin_dir_path( __FILE__ ); $this-&gt;load_language( 'myplugindomain' ); // more stuff: register actions and filters add_action( 'init', array( 'MyPluginClass', 'register_my_post_types' ) ); } public function register_my_post_types() { $labels = array( ..... ); $args = array( 'show_ui' =&gt; true, 'public' =&gt; true, 'labels' =&gt; $labels, 'supports' =&gt; array('title', 'editor', 'thumbnail'), 'has_archive' =&gt; true ); register_post_type('mycustomtype', $args); } </code></pre> <p>My question is, is it good practice to hook my <code>register_my_post_types()</code> function to the <code>init</code> hook? Or would it be better to call it directly in the <code>plugin_setup()</code> function?</p> <p>Thanks in advance</p>
[ { "answer_id": 245185, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 2, "selected": false, "text": "<p>I always do it in the init hook. If you do it in setup it every time they change setup or settings you will be registering that post type. Plus if your settings change the url or any portion of the new cpt you'll want those active before you change them.</p>\n" }, { "answer_id": 245189, "author": "Jory Hogeveen", "author_id": 99325, "author_profile": "https://wordpress.stackexchange.com/users/99325", "pm_score": 3, "selected": true, "text": "<p>The <code>init</code> hook is the first hook allowed. If called earlier it won't work.</p>\n<p>See WP Codex: <a href=\"https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/</a></p>\n<blockquote>\n<p>Create or modify a post type. register_post_type should only be invoked through the 'init' action. It will not work if called before 'init', and aspects of the newly created or modified post type will work incorrectly if called later.</p>\n</blockquote>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245183", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
I'm using toscho's [Plugin Class Demo](https://gist.github.com/toscho/3804204) code as a foundation for a plugin I'm developing. Amongst other things, my plugin registers a custom post type. ``` public function plugin_setup() { $this->plugin_url = plugins_url( '/', __FILE__ ); $this->plugin_path = plugin_dir_path( __FILE__ ); $this->load_language( 'myplugindomain' ); // more stuff: register actions and filters add_action( 'init', array( 'MyPluginClass', 'register_my_post_types' ) ); } public function register_my_post_types() { $labels = array( ..... ); $args = array( 'show_ui' => true, 'public' => true, 'labels' => $labels, 'supports' => array('title', 'editor', 'thumbnail'), 'has_archive' => true ); register_post_type('mycustomtype', $args); } ``` My question is, is it good practice to hook my `register_my_post_types()` function to the `init` hook? Or would it be better to call it directly in the `plugin_setup()` function? Thanks in advance
The `init` hook is the first hook allowed. If called earlier it won't work. See WP Codex: <https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/> > > Create or modify a post type. register\_post\_type should only be invoked through the 'init' action. It will not work if called before 'init', and aspects of the newly created or modified post type will work incorrectly if called later. > > >
245,184
<p>How can I replace a function from a plugin with a custom version of it.</p> <p>The original function of the plugin is:</p> <pre> function sep_get_the_event_end_date($post = NULL) { $post = get_post($post); if ($post->post_type !== 'event_listing') { return; } $event_xml = get_post_meta(get_the_ID(), 'event_meta', TRUE); $xml_object = new SimpleXMLElement($event_xml); $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $event_date = isset($xml_object->event_date) ? $xml_object->event_date : ''; if (isset($end_date) and '' $end_date and 'checked' $event_date) { $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $end_date = new DateTime($end_date); $end_date = date_format($end_date, 'F d, Y'); } else { $end_date = ''; } return apply_filters('sep_the_event_end_date', $end_date, $post); } </pre> <p>I want to change the date format of <code>$end_date</code>. Something like 'jS M Y'.</p> <p>I tried this:</p> <p>Created a new file: <code>custom-date-planner.php</code> and changed the date format.</p> <pre> function custom_sep_get_the_event_end_date($post = NULL) { $post = get_post($post); if ($post->post_type !== 'event_listing') { return; } $event_xml = get_post_meta(get_the_ID(), 'event_meta', TRUE); $xml_object = new SimpleXMLElement($event_xml); $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $event_date = isset($xml_object->event_date) ? $xml_object->event_date : ''; if (isset($end_date) and '' $end_date and 'checked' $event_date) { $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $end_date = new DateTime($end_date); $end_date = date_format($end_date, 'd M, Y'); } else { $end_date = ''; } return apply_filters('custom_sep_the_event_end_date', $end_date, $post); } </pre> <p>Next in my functions.php I did this:</p> <pre> // Add file require_once(get_stylesheet_directory() . '/public/partials/custom-date-planner.php'); add_action( 'after_setup_theme', 'child_theme_setup', 100 ); function child_theme_setup() { remove_action( 'sep_the_event_end_date', 'sep_get_the_event_end_date' ); add_action( 'sep_the_event_end_date', 'custom_sep_get_the_event_end_date' ); } </pre> <p>With this running, I get the notice: <code>Notice: Trying to get property of non-object in /private/var/www/fashion/data/web/public/wp-content/themes/furnde-child/public/partials/custom-date-planner.php on line 4</code></p> <p>How can I get this to work?</p>
[ { "answer_id": 245188, "author": "Bas van Dijk", "author_id": 106380, "author_profile": "https://wordpress.stackexchange.com/users/106380", "pm_score": 0, "selected": false, "text": "<p>In the function that you are using as a replacement. You don't get the post data, or did you just left that out? </p>\n\n<pre><code>post = get_post($post);\n</code></pre>\n" }, { "answer_id": 245196, "author": "Jory Hogeveen", "author_id": 99325, "author_profile": "https://wordpress.stackexchange.com/users/99325", "pm_score": 0, "selected": false, "text": "<p>It seems the <code>$post</code> parameter isn't always correct.</p>\n\n<p>Maybe a double check.</p>\n\n<p>Change this:<br>\n<code>if ($post-&gt;post_type !== 'event_listing') {</code><br>\nInto this:<br>\n<code>if ( ! isset($post-&gt;post_type) || $post-&gt;post_type !== 'event_listing' ) {</code></p>\n" }, { "answer_id": 245210, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 2, "selected": false, "text": "<p>For your question how can I replace this function . You don't need to replace it. The function has a filter on the returns value, not an action. You don't need to remove it, just filter the result.</p>\n\n<p>So you can create a new function and call it with <code>add_filter('sep_the_event_end_date', 'yourfunction');</code> \n Put this in your functions.php file without the add_action plugin _loaded.</p>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245184", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106378/" ]
How can I replace a function from a plugin with a custom version of it. The original function of the plugin is: ``` function sep_get_the_event_end_date($post = NULL) { $post = get_post($post); if ($post->post_type !== 'event_listing') { return; } $event_xml = get_post_meta(get_the_ID(), 'event_meta', TRUE); $xml_object = new SimpleXMLElement($event_xml); $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $event_date = isset($xml_object->event_date) ? $xml_object->event_date : ''; if (isset($end_date) and '' $end_date and 'checked' $event_date) { $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $end_date = new DateTime($end_date); $end_date = date_format($end_date, 'F d, Y'); } else { $end_date = ''; } return apply_filters('sep_the_event_end_date', $end_date, $post); } ``` I want to change the date format of `$end_date`. Something like 'jS M Y'. I tried this: Created a new file: `custom-date-planner.php` and changed the date format. ``` function custom_sep_get_the_event_end_date($post = NULL) { $post = get_post($post); if ($post->post_type !== 'event_listing') { return; } $event_xml = get_post_meta(get_the_ID(), 'event_meta', TRUE); $xml_object = new SimpleXMLElement($event_xml); $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $event_date = isset($xml_object->event_date) ? $xml_object->event_date : ''; if (isset($end_date) and '' $end_date and 'checked' $event_date) { $end_date = isset($xml_object->end_date) ? $xml_object->end_date : ''; $end_date = new DateTime($end_date); $end_date = date_format($end_date, 'd M, Y'); } else { $end_date = ''; } return apply_filters('custom_sep_the_event_end_date', $end_date, $post); } ``` Next in my functions.php I did this: ``` // Add file require_once(get_stylesheet_directory() . '/public/partials/custom-date-planner.php'); add_action( 'after_setup_theme', 'child_theme_setup', 100 ); function child_theme_setup() { remove_action( 'sep_the_event_end_date', 'sep_get_the_event_end_date' ); add_action( 'sep_the_event_end_date', 'custom_sep_get_the_event_end_date' ); } ``` With this running, I get the notice: `Notice: Trying to get property of non-object in /private/var/www/fashion/data/web/public/wp-content/themes/furnde-child/public/partials/custom-date-planner.php on line 4` How can I get this to work?
For your question how can I replace this function . You don't need to replace it. The function has a filter on the returns value, not an action. You don't need to remove it, just filter the result. So you can create a new function and call it with `add_filter('sep_the_event_end_date', 'yourfunction');` Put this in your functions.php file without the add\_action plugin \_loaded.
245,193
<p>I use the code below to produce a list of 'month+posts that month'.</p> <p>What do I need to do to show, alongside each month, the number of posts that month?</p> <pre><code>&lt;?php $previous_year = $year = 0; $previous_month = $month = 0; $dl_open = false; // Get the posts $myposts = get_posts('numberposts=-1&amp;orderby=post_date&amp;order=DESC&amp;post_type=byte'); ?&gt; &lt;?php foreach($myposts as $post) : ?&gt; &lt;?php // Setup the post variables setup_postdata($post); $year = mysql2date('Y', $post-&gt;post_date); $month = mysql2date('n', $post-&gt;post_date); $day = mysql2date('d', $post-&gt;post_date); ?&gt; &lt;?php if($year != $previous_year || $month != $previous_month) : ?&gt; &lt;?php if($dl_open == true) : ?&gt; &lt;/dl&gt; &lt;?php endif; ?&gt; &lt;h3&gt;&lt;?php the_time('F Y'); ?&gt;&lt;/h3&gt; &lt;dl id="post-list"&gt; &lt;?php $dl_open = true; ?&gt; &lt;?php endif; ?&gt; &lt;?php $previous_year = $year; $previous_month = $month; ?&gt; &lt;dt&gt;&lt;?php the_time('d'); ?&gt;&amp;nbsp;&amp;nbsp;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="read it"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/dt&gt; &lt;dd&gt;&lt;?php the_excerpt(); ?&gt;&lt;/dd&gt; &lt;?php endforeach; ?&gt; &lt;/dl&gt; </code></pre>
[ { "answer_id": 245195, "author": "geomagas", "author_id": 39275, "author_profile": "https://wordpress.stackexchange.com/users/39275", "pm_score": 0, "selected": false, "text": "<p>Employ a counter. On every month change, output it before you close each <code>&lt;dl&gt;</code> and zero it.</p>\n\n<p>Now, if you want it printed before the posts (eg. inside or near the <code>&lt;h3&gt;</code>) you probably shouldn't output your html directly, but instead save it in a string, or use <code>ob</code>, and flush it upon month change.</p>\n" }, { "answer_id": 245197, "author": "Jory Hogeveen", "author_id": 99325, "author_profile": "https://wordpress.stackexchange.com/users/99325", "pm_score": 3, "selected": true, "text": "<p>Why not simply use <code>wp_get_archives</code> and modify it's parameters?</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_archives\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_get_archives</a></p>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245193", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I use the code below to produce a list of 'month+posts that month'. What do I need to do to show, alongside each month, the number of posts that month? ``` <?php $previous_year = $year = 0; $previous_month = $month = 0; $dl_open = false; // Get the posts $myposts = get_posts('numberposts=-1&orderby=post_date&order=DESC&post_type=byte'); ?> <?php foreach($myposts as $post) : ?> <?php // Setup the post variables setup_postdata($post); $year = mysql2date('Y', $post->post_date); $month = mysql2date('n', $post->post_date); $day = mysql2date('d', $post->post_date); ?> <?php if($year != $previous_year || $month != $previous_month) : ?> <?php if($dl_open == true) : ?> </dl> <?php endif; ?> <h3><?php the_time('F Y'); ?></h3> <dl id="post-list"> <?php $dl_open = true; ?> <?php endif; ?> <?php $previous_year = $year; $previous_month = $month; ?> <dt><?php the_time('d'); ?>&nbsp;&nbsp;<a href="<?php the_permalink(); ?>" title="read it"><?php the_title(); ?></a></dt> <dd><?php the_excerpt(); ?></dd> <?php endforeach; ?> </dl> ```
Why not simply use `wp_get_archives` and modify it's parameters? <https://codex.wordpress.org/Function_Reference/wp_get_archives>
245,201
<p>I have two fields. The first is for plain text (but with special characters) and the second for html content (wp_editor is used). Both are later needed for <a href="https://github.com/PHPMailer/PHPMailer" rel="nofollow noreferrer">phpmailer</a>.</p> <pre><code>&lt;textarea style="width:100%;height:200px;" name="doi-altbody"&gt;&lt;?php echo $epn_doi_altbody; ?&gt;&lt;/textarea&gt; wp_editor( $epn_doi_body, 'doi-body', array( 'editor_height' =&gt; '300px' ) ); </code></pre> <p>1) How do i correctly secure them after submitting the form and then save them in the database into a custom table that already exist? (esc_attr, sanitize_text_field ...)</p> <p>2) And when i want to output the content from the database in the exact and original typed version: How do i make this? (wpautop ...)</p> <p>I have tried a few things in the last days. But it never worked as i needed.</p>
[ { "answer_id": 245195, "author": "geomagas", "author_id": 39275, "author_profile": "https://wordpress.stackexchange.com/users/39275", "pm_score": 0, "selected": false, "text": "<p>Employ a counter. On every month change, output it before you close each <code>&lt;dl&gt;</code> and zero it.</p>\n\n<p>Now, if you want it printed before the posts (eg. inside or near the <code>&lt;h3&gt;</code>) you probably shouldn't output your html directly, but instead save it in a string, or use <code>ob</code>, and flush it upon month change.</p>\n" }, { "answer_id": 245197, "author": "Jory Hogeveen", "author_id": 99325, "author_profile": "https://wordpress.stackexchange.com/users/99325", "pm_score": 3, "selected": true, "text": "<p>Why not simply use <code>wp_get_archives</code> and modify it's parameters?</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_archives\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_get_archives</a></p>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245201", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54551/" ]
I have two fields. The first is for plain text (but with special characters) and the second for html content (wp\_editor is used). Both are later needed for [phpmailer](https://github.com/PHPMailer/PHPMailer). ``` <textarea style="width:100%;height:200px;" name="doi-altbody"><?php echo $epn_doi_altbody; ?></textarea> wp_editor( $epn_doi_body, 'doi-body', array( 'editor_height' => '300px' ) ); ``` 1) How do i correctly secure them after submitting the form and then save them in the database into a custom table that already exist? (esc\_attr, sanitize\_text\_field ...) 2) And when i want to output the content from the database in the exact and original typed version: How do i make this? (wpautop ...) I have tried a few things in the last days. But it never worked as i needed.
Why not simply use `wp_get_archives` and modify it's parameters? <https://codex.wordpress.org/Function_Reference/wp_get_archives>
245,206
<p>This is a continuation from a question I asked earlier about doing this with output from <code>the_excerpt()</code>.</p> <p>What I am trying to do is take the following output from <code>the_content()</code> to take the following output as it currently is:</p> <pre><code>&lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Paragraph&lt;/p&gt; </code></pre> <p>And have it do the following:</p> <pre><code>&lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;&lt;span class="dropcap"&gt;P&lt;/span&gt;aragraph&lt;/p&gt; </code></pre> <p>I successfully did this with output from <code>the_excerpt()</code> using the following:</p> <pre><code>$the_excerpt = preg_replace('/^(.)/', '&lt;span class="dropcap"&gt;\1&lt;/span&gt;', $the_excerpt); </code></pre> <p>It works perfectly so I borrowed this line of code and modified it to:</p> <pre><code>$the_content = preg_replace( '/(?&lt;=\&lt;\/h3\&gt;\n&lt;p&gt;)./', '&lt;span class="dropcap"&gt;\1&lt;/span&gt;', $the_content ); </code></pre> <p>When this filter runs it results in the following output:</p> <pre><code>&lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;&lt;span class="dropcap"&gt;&lt;/span&gt;aragraph&lt;/p&gt; </code></pre> <p>But if I change the <code>'&lt;span class="dropcap"&gt;\1&lt;/span&gt;'</code> to a static character or string like '@', then it works.</p> <p>What do I need to change the replacement string to? Seems weird to me that it works in the case of <code>the_excerpt()</code> but not for <code>the_content()</code>.</p>
[ { "answer_id": 245228, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>The major issue is just that you have a <a href=\"https://regex101.com/library/sB3yN5\" rel=\"nofollow noreferrer\"><code>positive lookbehind</code></a> but no <code>capture group</code> so <code>\\1</code> or <code>$1</code> isn't a usable variable.</p>\n\n<p>Fix your <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">regex</a> to provide the capture group: <code>'/(?&lt;=\\&lt;\\/h3\\&gt;\\n&lt;p&gt;)(.)/'</code> then reference as <code>$1</code>.</p>\n\n<pre><code>ob_start();?&gt;\n &lt;h3&gt;Heading&lt;/h3&gt;\n &lt;p&gt;Paragraph&lt;/p&gt;\n &lt;p&gt;Paragraph2&lt;/p&gt;\n&lt;?php\n\n$search = ob_get_clean(); \n\n$result = preg_replace( \n '/(?&lt;=\\&lt;\\/h3\\&gt;\\n&lt;p&gt;)(.)/', \n '&lt;span class=\"dropcap\"&gt;$1&lt;/span&gt;', $search );\n</code></pre>\n" }, { "answer_id": 245251, "author": "Florian", "author_id": 10595, "author_profile": "https://wordpress.stackexchange.com/users/10595", "pm_score": 1, "selected": false, "text": "<p>In case this is for styling with CSS you don't need to use a regular expression. \nWith <code>h3 + p:first-letter</code> you should be able to style the first letter of a <code>&lt;p&gt;</code> after a <code>&lt;h3&gt;</code>. </p>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80069/" ]
This is a continuation from a question I asked earlier about doing this with output from `the_excerpt()`. What I am trying to do is take the following output from `the_content()` to take the following output as it currently is: ``` <h3>Heading</h3> <p>Paragraph</p> ``` And have it do the following: ``` <h3>Heading</h3> <p><span class="dropcap">P</span>aragraph</p> ``` I successfully did this with output from `the_excerpt()` using the following: ``` $the_excerpt = preg_replace('/^(.)/', '<span class="dropcap">\1</span>', $the_excerpt); ``` It works perfectly so I borrowed this line of code and modified it to: ``` $the_content = preg_replace( '/(?<=\<\/h3\>\n<p>)./', '<span class="dropcap">\1</span>', $the_content ); ``` When this filter runs it results in the following output: ``` <h3>Heading</h3> <p><span class="dropcap"></span>aragraph</p> ``` But if I change the `'<span class="dropcap">\1</span>'` to a static character or string like '@', then it works. What do I need to change the replacement string to? Seems weird to me that it works in the case of `the_excerpt()` but not for `the_content()`.
The major issue is just that you have a [`positive lookbehind`](https://regex101.com/library/sB3yN5) but no `capture group` so `\1` or `$1` isn't a usable variable. Fix your [regex](https://regex101.com/) to provide the capture group: `'/(?<=\<\/h3\>\n<p>)(.)/'` then reference as `$1`. ``` ob_start();?> <h3>Heading</h3> <p>Paragraph</p> <p>Paragraph2</p> <?php $search = ob_get_clean(); $result = preg_replace( '/(?<=\<\/h3\>\n<p>)(.)/', '<span class="dropcap">$1</span>', $search ); ```
245,215
<p>I'd like to call a <code>function Y($arg)</code> when the hook <code>X</code> is fired. </p> <p>Alternative: catch the return value from <code>function Y()</code>, which is called via <code>add_action('X', 'Y');</code> in <code>function W</code>, which <strong>contains</strong> the <code>add_action()</code> statement.</p> <p>How do I do that?</p> <p>My use case:</p> <p>I have a function <code>createMainPanel()</code> that returns a string <code>$ret</code> to be displayed.</p> <p>I only have access to the post meta info after the "template_redirect" hook, e.g. <code>get_post()</code> and the like only have sensible values after that hook. Thus, I want to add an <code>add_action('redirect_template', retrievePostInfo')</code> with the currently prepared string for output ($ret)) and let that function build the rest and print the page with echo.</p> <p>An alternative thought was somehow to retrieve the return of <code>retrievePostInfo()</code> and append it to the string of <code>createMainPanel()</code>.</p> <p>However, I can't see a working way to implement either of these possibilities.</p> <p><strong>EDIT</strong></p> <p>I solved my problem in a way unrelated to the question, but here's the code:</p> <p><strong>ERRONEOUS CODE:</strong></p> <pre><code>function showPostMetaInfo() { $id = get_the_ID(); $string.= "&lt;table id='meta-info'&gt;" . "&lt;thead&gt;" . "&lt;tr&gt;" . "&lt;th&gt; Meta Type &lt;/th&gt;" . "&lt;th&gt; Value" . "&lt;/tr&gt;" . "&lt;/thead&gt;" . "&lt;tbody&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Title &lt;/td&gt;" . "&lt;td&gt;".get_the_title($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Author &lt;/td&gt;" . "&lt;td&gt;".get_the_author($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Published &lt;/td&gt;" . "&lt;td&gt;".get_the_date("", $id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Last Modified &lt;/td&gt;" . "&lt;td&gt;".get_the_modified_date("", $id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Categories &lt;/td&gt;" . "&lt;td&gt;".listCategories($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Tags &lt;/td&gt;" . "&lt;td&gt;".listTags($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;/tbody&gt;" . "&lt;/table&gt;"; return $string; } </code></pre> <p><strong>CORRECT CODE:</strong></p> <pre><code>function showPostMetaInfo() { $id = get_queried_object_id(); $string.= "&lt;table id='meta-info'&gt;" . "&lt;thead&gt;" . "&lt;tr&gt;" . "&lt;th&gt; Meta Type &lt;/th&gt;" . "&lt;th&gt; Value" . "&lt;/tr&gt;" . "&lt;/thead&gt;" . "&lt;tbody&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Title &lt;/td&gt;" . "&lt;td&gt;".get_the_title($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Author &lt;/td&gt;" . "&lt;td&gt;".get_the_author($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Published &lt;/td&gt;" . "&lt;td&gt;".get_the_date("", $id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Last Modified &lt;/td&gt;" . "&lt;td&gt;".get_the_modified_date("", $id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Categories &lt;/td&gt;" . "&lt;td&gt;".listCategories($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;tr&gt;" . "&lt;td&gt; Tags &lt;/td&gt;" . "&lt;td&gt;".listTags($id)."&lt;/td&gt;" . "&lt;/tr&gt;" . "&lt;/tbody&gt;" . "&lt;/table&gt;"; return $string; } </code></pre>
[ { "answer_id": 245220, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>You can't get anything back from <code>add_action()</code> -- it always returns <code>true</code>.</p>\n\n<h2>Reference</h2>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action()</code> developer docs</a></li>\n</ul>\n" }, { "answer_id": 245226, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": true, "text": "<p>It's possible to <code>use</code> functions in a way that allow for one action to pass variables to the next. In this case, I've waited till the <code>wp_head</code> event to add <code>the_content</code> filter. And it will be using the <code>queried_object_id</code> when appending content with <code>showPostMetaInfo</code>. </p>\n\n<p>This makes your function a little more OOP friendly.</p>\n\n<pre><code>// Wait till the head\nadd_action( 'wp_head', function() {\n\n // Get the queried ID for use with `the_content`\n $queried_id = get_queried_object_id();\n\n add_filter( 'the_content', function( $content ) use ( $queried_id ) {\n\n // append post meta info to content\n return $content . showPostMetaInfo( $queried_id );\n } );\n} );\n\nfunction showPostMetaInfo( $id = null ) {\n\n if ( empty( $id ) ) {\n return '';\n }\n\n ob_start();\n\n ?&gt;\n &lt;table id='meta-info'&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt; Meta Type&lt;/th&gt;\n &lt;th&gt; Value\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;td&gt; Title&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_the_title( $id ); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt; Author&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_the_author( $id ); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt; Published&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_the_date( \"\", $id ); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt; Last Modified&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_the_modified_date( \"\", $id ); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt; Categories&lt;/td&gt;\n &lt;td&gt;&lt;?php echo listCategories( $id ); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt; Tags&lt;/td&gt;\n &lt;td&gt;&lt;?php echo listTags( $id ); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;&lt;?php\n\n return ob_get_clean();\n}\n\nfunction listCategories( $id ) { return 'listCategories: ' . $id; };\nfunction listTags( $id ) { return 'listTags: ' . $id; };\n</code></pre>\n\n<p>Note: This won't work with all versions of PHP.</p>\n\n<hr>\n\n<h2>Option 2</h2>\n\n<p>Taking this a step further, you could create a class that allows for dynamic data (including methods) and route your functions through it using <a href=\"http://php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow noreferrer\">magic methods</a>.</p>\n\n<pre><code>if ( ! class_exists( 'FunctionProxy' ) ):\n\n class FunctionProxy {\n\n private $s = array ();\n\n // properties\n function __set( $k, $c ) { $this-&gt;s[ $k ] = $c; }\n function __get( $k ) { return isset($this-&gt;s[ $k ]) ? $this-&gt;s[ $k ] : null; }\n\n // methods\n public function __call( $method, $args ) {\n if ( isset($this-&gt;s[ $method ]) &amp;&amp; is_callable( $this-&gt;s[ $method ] ) ) {\n return call_user_func_array( $this-&gt;s[ $method ], func_get_args() );\n } else {\n echo \"unknown method \" . $method;\n return false;\n }\n }\n\n // backtrace caller\n static function get_backtrace_object( $depth = 3 ) {\n $trace = debug_backtrace();\n return isset( $trace[ $depth ][ 'object' ] ) ? $trace[ $depth ][ 'object' ] : null;\n }\n }\n\nendif;\n</code></pre>\n\n<p>Using the <code>FunctionProxy</code> dynamic object you can make methods and properties on the fly.</p>\n\n<pre><code>// Wait till the head\nadd_action( 'wp_head', function() {\n\n // create our dynamic object\n $func = new FunctionProxy();\n\n // Get the queried ID for use with `the_content`\n $func-&gt;queried_id = get_queried_object_id();\n\n // Create a method on the object\n $func-&gt;filter_the_content = function( $content ) {\n\n // Find the callee of this function\n $caller = FunctionProxy::get_backtrace_object();\n\n // Return content plus post meta from our caller object\n return $content . showPostMetaInfo( $caller-&gt;queried_id );\n };\n\n // add content filer\n add_filter( 'the_content', array ( $func, 'filter_the_content' ) );\n} );\n</code></pre>\n\n<hr>\n\n<p>Reference</p>\n\n<ul>\n<li><a href=\"http://fabien.potencier.org/on-php-5-3-lambda-functions-and-closures.html\" rel=\"nofollow noreferrer\">http://fabien.potencier.org/on-php-5-3-lambda-functions-and-closures.html</a></li>\n<li><a href=\"http://lornajane.net/posts/2012/9-magic-methods-in-php\" rel=\"nofollow noreferrer\">http://lornajane.net/posts/2012/9-magic-methods-in-php</a></li>\n<li><a href=\"http://php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/language.oop5.magic.php</a></li>\n</ul>\n" } ]
2016/11/05
[ "https://wordpress.stackexchange.com/questions/245215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92039/" ]
I'd like to call a `function Y($arg)` when the hook `X` is fired. Alternative: catch the return value from `function Y()`, which is called via `add_action('X', 'Y');` in `function W`, which **contains** the `add_action()` statement. How do I do that? My use case: I have a function `createMainPanel()` that returns a string `$ret` to be displayed. I only have access to the post meta info after the "template\_redirect" hook, e.g. `get_post()` and the like only have sensible values after that hook. Thus, I want to add an `add_action('redirect_template', retrievePostInfo')` with the currently prepared string for output ($ret)) and let that function build the rest and print the page with echo. An alternative thought was somehow to retrieve the return of `retrievePostInfo()` and append it to the string of `createMainPanel()`. However, I can't see a working way to implement either of these possibilities. **EDIT** I solved my problem in a way unrelated to the question, but here's the code: **ERRONEOUS CODE:** ``` function showPostMetaInfo() { $id = get_the_ID(); $string.= "<table id='meta-info'>" . "<thead>" . "<tr>" . "<th> Meta Type </th>" . "<th> Value" . "</tr>" . "</thead>" . "<tbody>" . "<tr>" . "<td> Title </td>" . "<td>".get_the_title($id)."</td>" . "</tr>" . "<tr>" . "<td> Author </td>" . "<td>".get_the_author($id)."</td>" . "</tr>" . "<tr>" . "<td> Published </td>" . "<td>".get_the_date("", $id)."</td>" . "</tr>" . "<tr>" . "<td> Last Modified </td>" . "<td>".get_the_modified_date("", $id)."</td>" . "</tr>" . "<tr>" . "<td> Categories </td>" . "<td>".listCategories($id)."</td>" . "</tr>" . "<tr>" . "<td> Tags </td>" . "<td>".listTags($id)."</td>" . "</tr>" . "</tbody>" . "</table>"; return $string; } ``` **CORRECT CODE:** ``` function showPostMetaInfo() { $id = get_queried_object_id(); $string.= "<table id='meta-info'>" . "<thead>" . "<tr>" . "<th> Meta Type </th>" . "<th> Value" . "</tr>" . "</thead>" . "<tbody>" . "<tr>" . "<td> Title </td>" . "<td>".get_the_title($id)."</td>" . "</tr>" . "<tr>" . "<td> Author </td>" . "<td>".get_the_author($id)."</td>" . "</tr>" . "<tr>" . "<td> Published </td>" . "<td>".get_the_date("", $id)."</td>" . "</tr>" . "<tr>" . "<td> Last Modified </td>" . "<td>".get_the_modified_date("", $id)."</td>" . "</tr>" . "<tr>" . "<td> Categories </td>" . "<td>".listCategories($id)."</td>" . "</tr>" . "<tr>" . "<td> Tags </td>" . "<td>".listTags($id)."</td>" . "</tr>" . "</tbody>" . "</table>"; return $string; } ```
It's possible to `use` functions in a way that allow for one action to pass variables to the next. In this case, I've waited till the `wp_head` event to add `the_content` filter. And it will be using the `queried_object_id` when appending content with `showPostMetaInfo`. This makes your function a little more OOP friendly. ``` // Wait till the head add_action( 'wp_head', function() { // Get the queried ID for use with `the_content` $queried_id = get_queried_object_id(); add_filter( 'the_content', function( $content ) use ( $queried_id ) { // append post meta info to content return $content . showPostMetaInfo( $queried_id ); } ); } ); function showPostMetaInfo( $id = null ) { if ( empty( $id ) ) { return ''; } ob_start(); ?> <table id='meta-info'> <thead> <tr> <th> Meta Type</th> <th> Value </tr> </thead> <tbody> <tr> <td> Title</td> <td><?php echo get_the_title( $id ); ?></td> </tr> <tr> <td> Author</td> <td><?php echo get_the_author( $id ); ?></td> </tr> <tr> <td> Published</td> <td><?php echo get_the_date( "", $id ); ?></td> </tr> <tr> <td> Last Modified</td> <td><?php echo get_the_modified_date( "", $id ); ?></td> </tr> <tr> <td> Categories</td> <td><?php echo listCategories( $id ); ?></td> </tr> <tr> <td> Tags</td> <td><?php echo listTags( $id ); ?></td> </tr> </tbody> </table><?php return ob_get_clean(); } function listCategories( $id ) { return 'listCategories: ' . $id; }; function listTags( $id ) { return 'listTags: ' . $id; }; ``` Note: This won't work with all versions of PHP. --- Option 2 -------- Taking this a step further, you could create a class that allows for dynamic data (including methods) and route your functions through it using [magic methods](http://php.net/manual/en/language.oop5.magic.php). ``` if ( ! class_exists( 'FunctionProxy' ) ): class FunctionProxy { private $s = array (); // properties function __set( $k, $c ) { $this->s[ $k ] = $c; } function __get( $k ) { return isset($this->s[ $k ]) ? $this->s[ $k ] : null; } // methods public function __call( $method, $args ) { if ( isset($this->s[ $method ]) && is_callable( $this->s[ $method ] ) ) { return call_user_func_array( $this->s[ $method ], func_get_args() ); } else { echo "unknown method " . $method; return false; } } // backtrace caller static function get_backtrace_object( $depth = 3 ) { $trace = debug_backtrace(); return isset( $trace[ $depth ][ 'object' ] ) ? $trace[ $depth ][ 'object' ] : null; } } endif; ``` Using the `FunctionProxy` dynamic object you can make methods and properties on the fly. ``` // Wait till the head add_action( 'wp_head', function() { // create our dynamic object $func = new FunctionProxy(); // Get the queried ID for use with `the_content` $func->queried_id = get_queried_object_id(); // Create a method on the object $func->filter_the_content = function( $content ) { // Find the callee of this function $caller = FunctionProxy::get_backtrace_object(); // Return content plus post meta from our caller object return $content . showPostMetaInfo( $caller->queried_id ); }; // add content filer add_filter( 'the_content', array ( $func, 'filter_the_content' ) ); } ); ``` --- Reference * <http://fabien.potencier.org/on-php-5-3-lambda-functions-and-closures.html> * <http://lornajane.net/posts/2012/9-magic-methods-in-php> * <http://php.net/manual/en/language.oop5.magic.php>
245,250
<p>I have a plugin YITH Wishlist in use and I want to override their translation with my own translation which I have included in my child theme.</p> <p>So basically I created this folder: /mychildtheme/languages</p> <p>and placed this file in it <code>yith-woocommerce-wishlist-de_DE.mo</code> / <code>yith-woocommerce-wishlist-de_DE.po</code>.</p> <p>Within my functions.php I did the following:</p> <pre><code>add_action( 'plugins_loaded', 'yith_load_textdomain' ); function yith_load_textdomain() { unload_textdomain( 'yith-woocommerce-wishlist' ); load_plugin_textdomain( 'yith-woocommerce-wishlist', false, get_stylesheet_directory_uri() . '/languages' ); } </code></pre> <p>But this has no effect. Does somebody knows how I can override a plugin text domain with my custom translations?</p> <p>Thanks! </p>
[ { "answer_id": 245254, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 4, "selected": true, "text": "<p>If you want to override a plugin text domain, create (if not exist) a folder named <code>languages</code> and another one <code>plugins</code> (in languages) in the wp-content folder.</p>\n\n<p>This folders is intended, with the template and file hierarchy, to be load upon the other that could exist.</p>\n\n<p>When you update a plugin, text domain that you modified and copied into this folder will not be erase. It's up to you to maintain it up to date.</p>\n" }, { "answer_id": 245255, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>You should not be modifying a plug-in's text domain like that. It forces you to have to change it over and over again each time the plugin updates.</p>\n\n<p>If it does not already have it, create a folder <code>/languages</code> in the plugin's directory. In there place a file that contains all the translated text that matches the code you specify in your <code>wp-config.php</code> file. A program like <a href=\"https://poedit.net/download\" rel=\"nofollow noreferrer\">Poedit</a> will help you do this.</p>\n" } ]
2016/11/06
[ "https://wordpress.stackexchange.com/questions/245250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62987/" ]
I have a plugin YITH Wishlist in use and I want to override their translation with my own translation which I have included in my child theme. So basically I created this folder: /mychildtheme/languages and placed this file in it `yith-woocommerce-wishlist-de_DE.mo` / `yith-woocommerce-wishlist-de_DE.po`. Within my functions.php I did the following: ``` add_action( 'plugins_loaded', 'yith_load_textdomain' ); function yith_load_textdomain() { unload_textdomain( 'yith-woocommerce-wishlist' ); load_plugin_textdomain( 'yith-woocommerce-wishlist', false, get_stylesheet_directory_uri() . '/languages' ); } ``` But this has no effect. Does somebody knows how I can override a plugin text domain with my custom translations? Thanks!
If you want to override a plugin text domain, create (if not exist) a folder named `languages` and another one `plugins` (in languages) in the wp-content folder. This folders is intended, with the template and file hierarchy, to be load upon the other that could exist. When you update a plugin, text domain that you modified and copied into this folder will not be erase. It's up to you to maintain it up to date.
245,266
<p>I use the code below to add a message on the edit screen for a CPT 'item'.</p> <pre><code>$screen = get_current_screen(); if($screen-&gt;post_type=='item' &amp;&amp; $screen-&gt;id=='item') </code></pre> <p>What do I need to add to include other CPTs - example 'foo'?</p> <p>I can do it with 'elseif' but think there's maybe a shorter way by using || with a single 'if'.</p>
[ { "answer_id": 245254, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 4, "selected": true, "text": "<p>If you want to override a plugin text domain, create (if not exist) a folder named <code>languages</code> and another one <code>plugins</code> (in languages) in the wp-content folder.</p>\n\n<p>This folders is intended, with the template and file hierarchy, to be load upon the other that could exist.</p>\n\n<p>When you update a plugin, text domain that you modified and copied into this folder will not be erase. It's up to you to maintain it up to date.</p>\n" }, { "answer_id": 245255, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>You should not be modifying a plug-in's text domain like that. It forces you to have to change it over and over again each time the plugin updates.</p>\n\n<p>If it does not already have it, create a folder <code>/languages</code> in the plugin's directory. In there place a file that contains all the translated text that matches the code you specify in your <code>wp-config.php</code> file. A program like <a href=\"https://poedit.net/download\" rel=\"nofollow noreferrer\">Poedit</a> will help you do this.</p>\n" } ]
2016/11/06
[ "https://wordpress.stackexchange.com/questions/245266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I use the code below to add a message on the edit screen for a CPT 'item'. ``` $screen = get_current_screen(); if($screen->post_type=='item' && $screen->id=='item') ``` What do I need to add to include other CPTs - example 'foo'? I can do it with 'elseif' but think there's maybe a shorter way by using || with a single 'if'.
If you want to override a plugin text domain, create (if not exist) a folder named `languages` and another one `plugins` (in languages) in the wp-content folder. This folders is intended, with the template and file hierarchy, to be load upon the other that could exist. When you update a plugin, text domain that you modified and copied into this folder will not be erase. It's up to you to maintain it up to date.
245,274
<p>I need to remove &quot;Archive:&quot; label from the archive page title. I tried this string without results:</p> <pre><code>&lt;?php the_archive_title('&lt;h2&gt;','&lt;/h2&gt;', false);?&gt; </code></pre> <p>The title keeps displaying the &quot;Archive:&quot; label before the title. How can I get rid of it?</p> <p>This is the full code of my page:</p> <pre><code>&lt;?php get_header('inner');?&gt; &lt;div class=&quot;row large-uncollapse&quot;&gt; &lt;div class=&quot;columns small-12 medium-12 large-12&quot;&gt; &lt;div class=&quot;breadcrumbs&quot; typeof=&quot;BreadcrumbList&quot; vocab=&quot;http://schema.org/&quot;&gt; &lt;?php if(function_exists('bcn_display')) { echo '&lt;b&gt;Sei in:&lt;/b&gt;'; bcn_display(); }?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row large-uncollapse&quot;&gt; &lt;div class=&quot;columns small-12 medium-12 large-12 large-centered text-center pad-vr-2&quot;&gt; &lt;?php echo get_the_archive_title();?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php if(is_singular('rassegna-stampa')): ?&gt; &lt;div id=&quot;rassegna-stampa&quot;&gt; &lt;div class=&quot;row large-collapse&quot;&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); echo '&lt;div class=&quot;columns small-12 medium-6 large-4 float-left&quot; style=&quot;margin-bottom:10px;&quot;&gt;'; echo '&lt;div class=&quot;columns small-3 medium-3 large-3&quot;&gt;'; if(has_post_thumbnail()){ echo the_post_thumbnail(); } if( get_field('file') ) { echo '&lt;a href=&quot;'; the_field('file'); echo '&quot; data-featherlight=&quot;iframe&quot; target=&quot;_blank&quot;&gt;'; echo '&lt;button&gt;'; echo '&lt;img src=&quot;'; echo get_site_url(); echo '/wp-content/uploads/2016/09/pdf.png&quot; width=&quot;20px&quot;&gt;'; echo '&lt;/button&gt;'; echo '&lt;/a&gt;'; } if( get_field('link') ) { echo '&lt;a href=&quot;'; echo the_field('link'); echo '&quot; data-featherlight=&quot;iframe&quot;&gt;'; echo '&lt;button&gt;'; echo '&lt;img src=&quot;'; echo get_site_url(); echo '/wp-content/uploads/2016/09/link.png&quot; width=&quot;20px&quot;&gt;'; echo '&lt;/button&gt;'; echo '&lt;/a&gt;'; } echo '&lt;/div&gt;'; echo '&lt;div class=&quot;columns small-9 medium-9 large-9&quot;&gt;'; echo '&lt;h3 style=&quot;margin:0px;&quot;&gt;'; echo the_title(); echo '&lt;/h3&gt;'; echo '&lt;small&gt;'; echo '—'; echo the_field('testata'); echo '&lt;/small&gt;'; echo '&lt;small&gt;'; echo the_field('data'); echo '&lt;/small&gt;'; echo '&lt;span style=&quot;font-size:12px;&quot;&gt;'; the_excerpt(); echo '&lt;/span&gt;'; echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; endwhile; else : echo wpautop( 'Sorry, no posts were found' ); endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php else :?&gt; &lt;div id=&quot;libri&quot;&gt; &lt;div class=&quot;row large-collapse&quot;&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); echo '&lt;div class=&quot;columns small-12 medium-6 large-4 float-left&quot; style=&quot;margin-bottom:10px;padding-bottom: 12px; height:220px;&quot;&gt;'; echo '&lt;div class=&quot;columns small-3 medium-3 large-3&quot;&gt;'; if(has_post_thumbnail()){ echo the_post_thumbnail(); } echo '&lt;/div&gt;'; echo '&lt;div class=&quot;columns small-9 medium-9 large-9&quot;&gt;'; echo '&lt;h3 style=&quot;margin:0px;&quot;&gt;'; echo the_title(); echo '&lt;/h3&gt;'; echo '&lt;div style=&quot;float:left;width:100%;&quot;&gt;'; echo '&lt;small style=&quot;float:left;width:auto;&quot;&gt;'; echo the_field('anno_pubblicazione'); echo '&lt;/small&gt;'; echo '&lt;div style=&quot;float:left; line-height:15px;&quot;&gt;'; echo '&amp;nbsp;—&amp;nbsp; '; echo '&lt;/div&gt;'; echo '&lt;small style=&quot;float:left;width:auto;&quot;&gt;'; echo the_field('editore'); echo '&lt;/small&gt;'; echo '&lt;/div&gt;'; echo '&lt;span style=&quot;font-size:12px;&quot;&gt;'; the_excerpt(); echo '&lt;/span&gt;'; echo '&lt;/div&gt;'; echo '&lt;div class=&quot;columns small-12 medium-12 large-6&quot;&gt;'; echo '&lt;a href=&quot;'; the_permalink(); echo '&quot;&gt;'; echo '&lt;button style=&quot;width:auto; padding:0.4rem; float:left; border:1px #000 solid;&quot;&gt;'; echo 'Leggi tutto'; echo '&lt;/button&gt;'; echo '&lt;/a&gt;'; echo '&lt;/div&gt;'; echo '&lt;div class=&quot;columns small-12 medium-12 large-6&quot;&gt;'; if( get_field('link_acquisto') ): echo '&lt;a href=&quot;'; echo the_field('link_acquisto'); echo '&quot; style=&quot;color:#D34D3D;&quot;&gt;'; echo '&lt;button style=&quot;width:auto; padding:0.4rem; float:left; border:1px #D34D3D solid;&quot;&gt;'; echo 'COMPRA'; echo '&lt;/button&gt;'; echo '&lt;/a&gt;'; endif; echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; endwhile; else : echo wpautop( 'Sorry, no posts were found' ); endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif ;?&gt; &lt;?php get_footer();?&gt; </code></pre> <p>Thanks!</p>
[ { "answer_id": 245283, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 4, "selected": true, "text": "<p>You need to use the filter <code>get_the_archive_title</code>. It works like <code>the_title</code> filter.\nMore details about the function that embed the filter <a href=\"https://developer.wordpress.org/reference/functions/the_archive_title/\" rel=\"noreferrer\">here</a></p>\n\n<p>More in this question <a href=\"https://wordpress.stackexchange.com/questions/179585/remove-category-tag-author-from-the-archive-title\">remove category tag</a></p>\n\n<p>EDIT : </p>\n\n<p>When it's a custom post type archive page, you might use another function to print the title : <code>post_type_archive_title()</code>\nThen you'll be able to hook in the title with the filter <code>post_type_archive_title</code> , but there is no prefix for this function.</p>\n\n<p>So in your template replace the call to <code>get_the_archive_title()</code> function with:</p>\n\n<pre><code>post_type_archive_title();\n</code></pre>\n" }, { "answer_id": 379379, "author": "Sergey Fedirko", "author_id": 97814, "author_profile": "https://wordpress.stackexchange.com/users/97814", "pm_score": 3, "selected": false, "text": "<p>Also, you can remove unnecessary words from any standard title:</p>\n<pre><code>add_filter( 'get_the_archive_title', function ($title) {\n if ( is_category() ) {\n $title = single_cat_title( '', false );\n } elseif ( is_tag() ) {\n $title = single_tag_title( '', false );\n } elseif ( is_author() ) {\n $title = '&lt;span class=&quot;vcard&quot;&gt;' . get_the_author() . '&lt;/span&gt;' ;\n } elseif ( is_tax() ) { //for custom post types\n $title = sprintf( __( '%1$s' ), single_term_title( '', false ) );\n } elseif (is_post_type_archive()) {\n $title = post_type_archive_title( '', false );\n }\n return $title;\n});\n</code></pre>\n" }, { "answer_id": 408321, "author": "Ilona", "author_id": 136877, "author_profile": "https://wordpress.stackexchange.com/users/136877", "pm_score": 1, "selected": false, "text": "<p>If you look at the <a href=\"https://developer.wordpress.org/reference/functions/get_the_archive_title/\" rel=\"nofollow noreferrer\">get_the_archive_title()</a> function, the prefix is now (since WP 5.5.0) wrapped in its own filter (<a href=\"https://developer.wordpress.org/reference/hooks/get_the_archive_title_prefix/\" rel=\"nofollow noreferrer\">get_the_archive_title_prefix</a>):</p>\n<pre><code>$prefix = apply_filters( 'get_the_archive_title_prefix', $prefix );\nif ( $prefix ) {\n $title = sprintf(\n /* translators: 1: Title prefix. 2: Title. */\n _x( '%1$s %2$s', 'archive title' ),\n $prefix,\n '&lt;span&gt;' . $title . '&lt;/span&gt;'\n );\n}\n</code></pre>\n<p>So you could use the filter to return an empty string (or anything you want) to overwrite the 'Archive:' text:</p>\n<pre><code>add_filter( 'get_the_archive_title_prefix', function( $prefix ) {\nreturn '';\n</code></pre>\n<p>} );</p>\n" } ]
2016/11/06
[ "https://wordpress.stackexchange.com/questions/245274", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103072/" ]
I need to remove "Archive:" label from the archive page title. I tried this string without results: ``` <?php the_archive_title('<h2>','</h2>', false);?> ``` The title keeps displaying the "Archive:" label before the title. How can I get rid of it? This is the full code of my page: ``` <?php get_header('inner');?> <div class="row large-uncollapse"> <div class="columns small-12 medium-12 large-12"> <div class="breadcrumbs" typeof="BreadcrumbList" vocab="http://schema.org/"> <?php if(function_exists('bcn_display')) { echo '<b>Sei in:</b>'; bcn_display(); }?> </div> </div> </div> <div class="row large-uncollapse"> <div class="columns small-12 medium-12 large-12 large-centered text-center pad-vr-2"> <?php echo get_the_archive_title();?> </div> </div> <?php if(is_singular('rassegna-stampa')): ?> <div id="rassegna-stampa"> <div class="row large-collapse"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); echo '<div class="columns small-12 medium-6 large-4 float-left" style="margin-bottom:10px;">'; echo '<div class="columns small-3 medium-3 large-3">'; if(has_post_thumbnail()){ echo the_post_thumbnail(); } if( get_field('file') ) { echo '<a href="'; the_field('file'); echo '" data-featherlight="iframe" target="_blank">'; echo '<button>'; echo '<img src="'; echo get_site_url(); echo '/wp-content/uploads/2016/09/pdf.png" width="20px">'; echo '</button>'; echo '</a>'; } if( get_field('link') ) { echo '<a href="'; echo the_field('link'); echo '" data-featherlight="iframe">'; echo '<button>'; echo '<img src="'; echo get_site_url(); echo '/wp-content/uploads/2016/09/link.png" width="20px">'; echo '</button>'; echo '</a>'; } echo '</div>'; echo '<div class="columns small-9 medium-9 large-9">'; echo '<h3 style="margin:0px;">'; echo the_title(); echo '</h3>'; echo '<small>'; echo '—'; echo the_field('testata'); echo '</small>'; echo '<small>'; echo the_field('data'); echo '</small>'; echo '<span style="font-size:12px;">'; the_excerpt(); echo '</span>'; echo '</div>'; echo '</div>'; endwhile; else : echo wpautop( 'Sorry, no posts were found' ); endif; ?> </div> </div> <?php else :?> <div id="libri"> <div class="row large-collapse"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); echo '<div class="columns small-12 medium-6 large-4 float-left" style="margin-bottom:10px;padding-bottom: 12px; height:220px;">'; echo '<div class="columns small-3 medium-3 large-3">'; if(has_post_thumbnail()){ echo the_post_thumbnail(); } echo '</div>'; echo '<div class="columns small-9 medium-9 large-9">'; echo '<h3 style="margin:0px;">'; echo the_title(); echo '</h3>'; echo '<div style="float:left;width:100%;">'; echo '<small style="float:left;width:auto;">'; echo the_field('anno_pubblicazione'); echo '</small>'; echo '<div style="float:left; line-height:15px;">'; echo '&nbsp;—&nbsp; '; echo '</div>'; echo '<small style="float:left;width:auto;">'; echo the_field('editore'); echo '</small>'; echo '</div>'; echo '<span style="font-size:12px;">'; the_excerpt(); echo '</span>'; echo '</div>'; echo '<div class="columns small-12 medium-12 large-6">'; echo '<a href="'; the_permalink(); echo '">'; echo '<button style="width:auto; padding:0.4rem; float:left; border:1px #000 solid;">'; echo 'Leggi tutto'; echo '</button>'; echo '</a>'; echo '</div>'; echo '<div class="columns small-12 medium-12 large-6">'; if( get_field('link_acquisto') ): echo '<a href="'; echo the_field('link_acquisto'); echo '" style="color:#D34D3D;">'; echo '<button style="width:auto; padding:0.4rem; float:left; border:1px #D34D3D solid;">'; echo 'COMPRA'; echo '</button>'; echo '</a>'; endif; echo '</div>'; echo '</div>'; endwhile; else : echo wpautop( 'Sorry, no posts were found' ); endif; ?> </div> </div> <?php endif ;?> <?php get_footer();?> ``` Thanks!
You need to use the filter `get_the_archive_title`. It works like `the_title` filter. More details about the function that embed the filter [here](https://developer.wordpress.org/reference/functions/the_archive_title/) More in this question [remove category tag](https://wordpress.stackexchange.com/questions/179585/remove-category-tag-author-from-the-archive-title) EDIT : When it's a custom post type archive page, you might use another function to print the title : `post_type_archive_title()` Then you'll be able to hook in the title with the filter `post_type_archive_title` , but there is no prefix for this function. So in your template replace the call to `get_the_archive_title()` function with: ``` post_type_archive_title(); ```
245,285
<p>I’ve been searching for a plugin that can track all external links clicked on a blog. Unfortunately the ones that I’ve found are intended to track total clicks per link rather than tracking which user clicked on which link. Is there a plugin that will enable me to track links based on the username?</p> <p>If not, I can write a script to intercept each click, save the username to a db and then redirect to the correct page. But I need some way to determine username before the link is clicked. Is there a plugin that will enable me to insert a parameter (username) to any url/link in a blog post?</p> <p>For example: <a href="http://myblog.com/myscript.php?url=http%3A//www.google.com&amp;user=" rel="nofollow noreferrer">http://myblog.com/myscript.php?url=http%3A//www.google.com&amp;user=</a>{{username}}</p> <p>I’ve looked at the wordpress API and it seems easy enough to retrieve user account info but if I’m linking to a custom script (rather than a wordpress page) which wordpress files do I need to include so that I’ll have access to the WP_User object?</p> <pre><code>&lt;?php // include “someWordPressFile.php”; $user = wp_get_current_user(); ?&gt; </code></pre>
[ { "answer_id": 245286, "author": "Philipp", "author_id": 31140, "author_profile": "https://wordpress.stackexchange.com/users/31140", "pm_score": 1, "selected": true, "text": "<p>I do not know of an existing plugin that does what you want.</p>\n\n<p>Using a custom script is quite difficult, I would not try this. Mainly because you do not know which WP functions you can use/which functions need others to work, ...</p>\n\n<p>If you want to track links then I would use an ajax event send a \"click\" event to WordPress when someone clicks on a link. Also you do not need to include the username in the URL, since you can always use <code>get_current_user_id()</code> to determine the logged in users ID.</p>\n\n<p>The solution could be a simple script, with this structure:</p>\n\n<pre><code>// 1. Add a javascript for click-tracking on every WordPress page.\nadd_action( 'wp_footer', 'add_tracking_script' );\nfunction add_tracking_script() {\n ?&gt;&lt;script&gt;jQuery(function(){\n function domain(url) {\n return url.replace('http://','').replace('https://','').split('/')[0];\n }\n\n var local_domain = domain('&lt;?php echo site_url() ?&gt;');\n\n jQuery('a').on('click', function(){\n var link_url = jQuery(this).attr('href');\n\n if (domain(link_url) === local_domain) {return true;}\n window.wp.ajax.send('tracking-click', {url: link_url})\n return true;\n })\n })&lt;/script&gt;&lt;?php\n}\n\n// 2. Add the ajax handler for the tracking.\nadd_action( 'wp_ajax_tracking-click', 'ajax_handler_tracking' );\nfunction ajax_handler_tracking() {\n $user_id = get_current_user_id();\n $url = $_REQUEST['url'];\n\n // Save the user_id + $url to your DB table...\n\n exit;\n}\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>If you get an JS error <code>window.wp.ajax.send is undefined</code> then you also need to add this php code to tell WordPress that you want to use <code>window.wp</code></p>\n\n<pre><code>// 3. Make sure WordPress loads the window.wp object:\nadd_action( 'wp_enqueue_scripts', 'add_wp_utils' );\nfunction add_wp_utils() {\n wp_enqueue_script( 'wp-utils' );\n}\n</code></pre>\n\n<p>FYI: You can find a bit more information on <code>window.wp.ajax</code> in this post <a href=\"https://wordpress.stackexchange.com/a/245275/31140\">https://wordpress.stackexchange.com/a/245275/31140</a></p>\n" }, { "answer_id": 245289, "author": "tium", "author_id": 106428, "author_profile": "https://wordpress.stackexchange.com/users/106428", "pm_score": 0, "selected": false, "text": "<pre><code>function user_tracking_script() {\n?&gt;&lt;script&gt;jQuery(function(){\n jQuery('a').on('click', function(){\n var a = jQuery(this)[0];\n if (a.hostname === window.location.hostname) {return true;}\n window.wp.ajax.send('tracking-click', {url: a.hostname})\n return true;\n })\n})&lt;/script&gt;&lt;?php\n}\n</code></pre>\n" }, { "answer_id": 245312, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>I realize someone basically made my comment and added as an answer. Here is a fully working version using the built in <a href=\"http://v2.wp-api.org/extending/adding/\" rel=\"nofollow noreferrer\">REST API</a> for variety. It was a little tricky finding docks on authenticated requests, but this should be a drop in.</p>\n\n<pre><code>// send authorization info\nbeforeSend: function(xhr) {\n\n // attach REST nonce for logged in user requests -- otherwise will end up no-priv\n xhr.setRequestHeader ('X-WP-Nonce', '&lt;?php echo wp_create_nonce( 'wp_rest' ); ?&gt;');\n},\n</code></pre>\n\n<p>On an click to an external link, an ajax call is made to a custom REST route. The link is then added to an array of urls in the users meta and incremented for count data.</p>\n\n<p>After a few external clicks you can check the metadata for the user and see all the clicks and counts.</p>\n\n<pre><code>&lt;?php\n\nadd_action( 'rest_api_init', function() {\n\n // namespace of url\n $namespace = 'v2';\n\n // route\n $base = '/link/count/';\n\n // register request\n register_rest_route( $namespace, $base, array (\n\n // hide from discovery\n 'show_in_index' =&gt; false,\n\n // only accept POST methods\n 'methods' =&gt; 'POST',\n\n // handler\n 'callback' =&gt; 'add_link_count',\n\n // validate args\n 'args' =&gt; array(\n 'link' =&gt; array(\n 'validate_callback' =&gt; function($param, $request, $key) {\n return ! empty( $param );\n }\n ),\n ),\n\n // check for logged in users\n 'permission_callback' =&gt; function () {\n return is_user_logged_in();\n }\n ) );\n} );\n\n// only add late in the footer\nadd_action( 'wp_footer', function() {\n\n // only add for logged in users\n if ( ! get_current_user_id() ) {\n return;\n }\n ?&gt;\n &lt;script&gt;\n (function($) {\n\n // only search for links with data\n $ ('a[href^=\"http\"], a[href^=\"//\"]').each (function() {\n\n // excluded specific domains\n var excludes = [\n 'example.com'\n ];\n for (i = 0; i &lt; excludes.length; i++) {\n if (this.href.indexOf (excludes[i]) != -1) {\n return true; // continue each() with next link\n }\n }\n\n // filter by domain -- only track external links\n if (this.href.indexOf (location.hostname) == -1) {\n\n // attach click event\n $ (this).click (function(e) {\n\n // do ajax call\n $.ajax ({\n\n // send request to REST URL\n url: '&lt;?php echo esc_js( get_rest_url( null, '/v2/link/count/' ) ); ?&gt;',\n\n // use the accepted method - POST\n method: 'POST',\n\n // send authorization info\n beforeSend: function(xhr) {\n\n // attach REST nonce for logged in user requests -- otherwise will end up no-priv\n xhr.setRequestHeader ('X-WP-Nonce', '&lt;?php echo wp_create_nonce( 'wp_rest' ); ?&gt;');\n },\n data: {\n // link to track click count\n 'link': this.href\n }\n }).done (function(response) {\n // show response in the console\n // console.log (response);\n });\n\n // block click -- for testing\n // e.preventDefault();\n });\n }\n })\n } (jQuery));\n\n &lt;/script&gt;\n &lt;?php\n}, 30 );\n\n// handle the REST url\nfunction add_link_count( $request ) {\n\n // get the current user\n $user_id = get_current_user_id();\n\n // check for valid user id &gt; 0\n if ( ! $user_id || $user_id &lt; 1 ) {\n return new WP_REST_Response( 'Unauthorized', 403 );\n }\n\n // get the link to log\n $link = $request-&gt;get_param( 'link' );\n\n // validate the request\n if( empty($link)) return new WP_REST_Response( 'Bad Request', 400 );\n\n // pull the previous click data\n $prev = get_user_meta($user_id, 'link_clicks', true);\n\n // generate if it doesn't already exist\n if( ! $prev || ! is_array($prev)) $prev = array();\n\n // make sure the value is numeric\n if( ! is_numeric($prev[$link]) ){\n $prev[$link] = 0;\n }\n\n // increment based on the click\n $prev[$link]++;\n\n // update the users metadata\n update_user_meta( $user_id, 'link_clicks', $prev, null );\n\n // return success response\n return new WP_REST_Response( 'OK', 200 );\n}\n</code></pre>\n\n<p>To read to clicks back, query for users with click meta data:</p>\n\n<pre><code>function get_clicks_by_user() {\n $args = array (\n 'meta_query' =&gt; array (\n array (\n 'key' =&gt; 'link_clicks',\n 'compare' =&gt; 'EXISTS',\n ),\n ),\n );\n $user_query = new WP_User_Query( $args );\n $users = $user_query-&gt;get_results();\n $clicks_by_user = array ();\n foreach ( $users as $user ) {\n $clicks_by_user[ $user-&gt;data-&gt;user_login ] = get_user_meta( $user-&gt;ID, 'link_clicks', true );\n }\n\n return $clicks_by_user;\n}\n</code></pre>\n\n<p>And display the results:</p>\n\n<pre><code>echo \"&lt;pre&gt;\";\nprint_r( get_clicks_by_user() );\n</code></pre>\n" } ]
2016/11/06
[ "https://wordpress.stackexchange.com/questions/245285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106428/" ]
I’ve been searching for a plugin that can track all external links clicked on a blog. Unfortunately the ones that I’ve found are intended to track total clicks per link rather than tracking which user clicked on which link. Is there a plugin that will enable me to track links based on the username? If not, I can write a script to intercept each click, save the username to a db and then redirect to the correct page. But I need some way to determine username before the link is clicked. Is there a plugin that will enable me to insert a parameter (username) to any url/link in a blog post? For example: <http://myblog.com/myscript.php?url=http%3A//www.google.com&user=>{{username}} I’ve looked at the wordpress API and it seems easy enough to retrieve user account info but if I’m linking to a custom script (rather than a wordpress page) which wordpress files do I need to include so that I’ll have access to the WP\_User object? ``` <?php // include “someWordPressFile.php”; $user = wp_get_current_user(); ?> ```
I do not know of an existing plugin that does what you want. Using a custom script is quite difficult, I would not try this. Mainly because you do not know which WP functions you can use/which functions need others to work, ... If you want to track links then I would use an ajax event send a "click" event to WordPress when someone clicks on a link. Also you do not need to include the username in the URL, since you can always use `get_current_user_id()` to determine the logged in users ID. The solution could be a simple script, with this structure: ``` // 1. Add a javascript for click-tracking on every WordPress page. add_action( 'wp_footer', 'add_tracking_script' ); function add_tracking_script() { ?><script>jQuery(function(){ function domain(url) { return url.replace('http://','').replace('https://','').split('/')[0]; } var local_domain = domain('<?php echo site_url() ?>'); jQuery('a').on('click', function(){ var link_url = jQuery(this).attr('href'); if (domain(link_url) === local_domain) {return true;} window.wp.ajax.send('tracking-click', {url: link_url}) return true; }) })</script><?php } // 2. Add the ajax handler for the tracking. add_action( 'wp_ajax_tracking-click', 'ajax_handler_tracking' ); function ajax_handler_tracking() { $user_id = get_current_user_id(); $url = $_REQUEST['url']; // Save the user_id + $url to your DB table... exit; } ``` **Update** If you get an JS error `window.wp.ajax.send is undefined` then you also need to add this php code to tell WordPress that you want to use `window.wp` ``` // 3. Make sure WordPress loads the window.wp object: add_action( 'wp_enqueue_scripts', 'add_wp_utils' ); function add_wp_utils() { wp_enqueue_script( 'wp-utils' ); } ``` FYI: You can find a bit more information on `window.wp.ajax` in this post <https://wordpress.stackexchange.com/a/245275/31140>
245,288
<p>I registered three custom post types to a single taxonomy( the default <code>post_tag</code> taxonomy).</p> <p>When I access <code>example.com/tag/foo</code>, I got the posts that have a <code>foo</code> tag, and the posts were taken from all the three custom post types. </p> <p>I want to constrain the posts to one specific post type. </p> <p>Say when I access <code>example.com/tag/foo/?post_type=BAR</code> or <code>example.com/tag/foo/post_type/BAR</code>, then I should get all the posts that have a <code>foo</code> tag AND the <code>post_type</code> of the posts is <code>BAR</code>.</p> <p>I've tried to set the main-query's <code>query_var</code> to <code>post_type =&gt; BAR</code> in <code>pre_get_post‌s</code> but that won't work.. Because I have to paginate the posts, so I can't just simply use the <code>WP_Query</code> to query and show them all. So please help!</p>
[ { "answer_id": 245299, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>You can use <code>WP_Query</code> for this. By default it will paginate unless you tell it not to by passing it the <code>'nopaging'</code> parameter and set it to <code>true</code>.</p>\n\n<pre><code>$query = new WP_Query( array(\n // Your CPT parameters\n 'nopaging' =&gt; true,\n )\n);\n</code></pre>\n\n<p>In your case, you would simply rewrite the query to tell WordPress how many posts you want, etc.</p>\n\n<pre><code>$query = new WP_Query( array(\n 'post_type' =&gt; 'review',\n 'posts_per_page' =&gt; 15,\n )\n);\n</code></pre>\n\n<p>So this query would grab all post types with the slug of <code>review</code> and show 15 posts per page.</p>\n" }, { "answer_id": 245384, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>This works for me:</p>\n\n<pre><code>function namespace_add_custom_types( $query ) {\n if( is_tag() &amp;&amp; empty( $query-&gt;query_vars['suppress_filters'] ) ) {\n $query-&gt;set( 'post_type', array(\n 'YOUR_CUSTOM_POST_TYPE', 'nav_menu_item'));\n return $query;\n }\n}\nadd_filter( 'pre_get_posts', 'namespace_add_custom_types' );\n</code></pre>\n" } ]
2016/11/06
[ "https://wordpress.stackexchange.com/questions/245288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106430/" ]
I registered three custom post types to a single taxonomy( the default `post_tag` taxonomy). When I access `example.com/tag/foo`, I got the posts that have a `foo` tag, and the posts were taken from all the three custom post types. I want to constrain the posts to one specific post type. Say when I access `example.com/tag/foo/?post_type=BAR` or `example.com/tag/foo/post_type/BAR`, then I should get all the posts that have a `foo` tag AND the `post_type` of the posts is `BAR`. I've tried to set the main-query's `query_var` to `post_type => BAR` in `pre_get_post‌s` but that won't work.. Because I have to paginate the posts, so I can't just simply use the `WP_Query` to query and show them all. So please help!
This works for me: ``` function namespace_add_custom_types( $query ) { if( is_tag() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'YOUR_CUSTOM_POST_TYPE', 'nav_menu_item')); return $query; } } add_filter( 'pre_get_posts', 'namespace_add_custom_types' ); ```
245,313
<p>I have two post types Type_1 and Type_2</p> <p>I'm trying to get the most recent out of both of them so if type_1 has a post created after the most recent of type_2 then I want to show that post and the other way around.</p> <p>What is the best way of doing this?</p> <p>I only want to show 1 post the most recent out of both </p>
[ { "answer_id": 245315, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>Just set <code>post_type</code> to an array of types, and <code>posts_per_page</code> to <code>1</code> and you'll get the most recent post from those types.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; array( 'type_1', 'type_2' ),\n 'posts_per_page' =&gt; 1\n);\n$latest = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 245410, "author": "Nathaniel Meyer", "author_id": 104415, "author_profile": "https://wordpress.stackexchange.com/users/104415", "pm_score": 0, "selected": false, "text": "<p>This is the way that ended up working for me thanks for all your help</p>\n\n<pre><code>$type_1 = get_posts(array(\n 'post_type' =&gt; 'type_1',\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC'\n));\n\n $type_1_query_obj = $type_1[0];\n $type_1_date = $type_1_query_obj-&gt;post_date;\n $type_1_name = $type_1_query_obj-&gt;post_title;\n\n\n\n$type_2 = get_posts(array(\n 'post_type' =&gt; 'type_2',\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC'\n));\n\n $type_2_query_obj = $type_2[0];\n $type_2_date = $type_2_query_obj-&gt;post_date;\n $type_2_name = $type_2_query_obj-&gt;post_title;\n\n\n//compare the dates\n\nif( strtotime($type_1_date) &gt; strtotime($type_2_date) ) {\n echo $type_1_name;\n}else{\n echo $type_2_name;\n}\n</code></pre>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245313", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104415/" ]
I have two post types Type\_1 and Type\_2 I'm trying to get the most recent out of both of them so if type\_1 has a post created after the most recent of type\_2 then I want to show that post and the other way around. What is the best way of doing this? I only want to show 1 post the most recent out of both
Just set `post_type` to an array of types, and `posts_per_page` to `1` and you'll get the most recent post from those types. ``` $args = array( 'post_type' => array( 'type_1', 'type_2' ), 'posts_per_page' => 1 ); $latest = new WP_Query( $args ); ```
245,325
<p>Having modified several plugins, I want to stop them being updated (and over-writing the mods).</p> <p>I don't just want to stop auto-updates, but also inadvertent updates by myself or another admin.</p> <p>I don't want to disable 'new version available' notifications (because if there's a newer version I want to update to it, after editing to apply appropriate mods).</p> <p>I'm wondering if there's something I can add to functions.php, which stops named (or all) plugin updates... and can be temporarily 'commented-out' to re-enable a manual update.</p> <p>UPDATE: After further searches, what I want seems unlikely.</p> <p>I haven't been able to find a way to retain 'update available' notices AND block updates.</p> <p>My possible klunky work-around is:</p> <p>1 Install original plugin. Leave unmodified and inactive. This should get 'update available' notices.</p> <p>2 Install modified plugin, add 'modified' to name and change slug, activate. This shouldn't get 'update available' notices.</p> <p>3 Add a message about which plugins are modified on the plugin page.</p> <p>This way, original plugins can be modified without affecting site function.</p> <p>Modified plugins won't get updated, and (using the reminder on the plugin page) a periodic visual comparison of version info with the original will show if an updated version is available (and which can be modded appropriately).</p> <p>If there's a better option, I'll welcome it.</p> <p>FURTHER UPDATE: I've since found 'Lock Your Updates' plugin (<a href="https://en-gb.wordpress.org/plugins/lock-your-updates/" rel="nofollow noreferrer">https://en-gb.wordpress.org/plugins/lock-your-updates/</a>), which seems a useful solution.</p> <p>Easy to set-up, it allows 'new version available' updates but enables plugins to be selected and blocked/unblocked from updates.</p> <p>There's also a 'notes' feature for reminders on why a plugin is blocked, but I've not been able to get that working.</p>
[ { "answer_id": 245348, "author": "Kevin", "author_id": 87522, "author_profile": "https://wordpress.stackexchange.com/users/87522", "pm_score": 1, "selected": false, "text": "<p>Use <code>add_filter( 'auto_update_plugin', '__return_false' );</code> in your functions.php or plugins main file.</p>\n" }, { "answer_id": 245360, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 2, "selected": false, "text": "<p>Go into the PHP file for the plugin and change the information in the header comment. For example, this is the one from the <code>Hello Dolly</code> plugin that comes with WordPress:</p>\n\n<pre><code>/**\n * @package Hello_Dolly\n * @version 1.6\n */\n/*\nPlugin Name: Hello Dolly\nPlugin URI: http://wordpress.org/plugins/hello-dolly/\nDescription: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from &lt;cite&gt;Hello, Dolly&lt;/cite&gt; in the upper right of your admin screen on every page.\nAuthor: Matt Mullenweg\nVersion: 1.6\nAuthor URI: http://ma.tt/\n*/\n</code></pre>\n\n<p>Change the information in here to reflect that it is a \"new\" plugin. Just make sure you keep any copyright notices and such intact.</p>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
Having modified several plugins, I want to stop them being updated (and over-writing the mods). I don't just want to stop auto-updates, but also inadvertent updates by myself or another admin. I don't want to disable 'new version available' notifications (because if there's a newer version I want to update to it, after editing to apply appropriate mods). I'm wondering if there's something I can add to functions.php, which stops named (or all) plugin updates... and can be temporarily 'commented-out' to re-enable a manual update. UPDATE: After further searches, what I want seems unlikely. I haven't been able to find a way to retain 'update available' notices AND block updates. My possible klunky work-around is: 1 Install original plugin. Leave unmodified and inactive. This should get 'update available' notices. 2 Install modified plugin, add 'modified' to name and change slug, activate. This shouldn't get 'update available' notices. 3 Add a message about which plugins are modified on the plugin page. This way, original plugins can be modified without affecting site function. Modified plugins won't get updated, and (using the reminder on the plugin page) a periodic visual comparison of version info with the original will show if an updated version is available (and which can be modded appropriately). If there's a better option, I'll welcome it. FURTHER UPDATE: I've since found 'Lock Your Updates' plugin (<https://en-gb.wordpress.org/plugins/lock-your-updates/>), which seems a useful solution. Easy to set-up, it allows 'new version available' updates but enables plugins to be selected and blocked/unblocked from updates. There's also a 'notes' feature for reminders on why a plugin is blocked, but I've not been able to get that working.
Go into the PHP file for the plugin and change the information in the header comment. For example, this is the one from the `Hello Dolly` plugin that comes with WordPress: ``` /** * @package Hello_Dolly * @version 1.6 */ /* Plugin Name: Hello Dolly Plugin URI: http://wordpress.org/plugins/hello-dolly/ Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page. Author: Matt Mullenweg Version: 1.6 Author URI: http://ma.tt/ */ ``` Change the information in here to reflect that it is a "new" plugin. Just make sure you keep any copyright notices and such intact.
245,331
<p>My ISP having trouble accessing Wordpress.org through SSL connection, thus I am facing performance issues.<br /><br /> How Can I entirely block WordPress admin trying to access Wordpress.org to check for latest updates and other things ( By other things I mean any reason that WordPress wants to connect to wordpress.org through SSL ). <br /><br /> Thanks.</p>
[ { "answer_id": 245332, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>I hope below code fix your problem-</p>\n\n<pre><code>function the_dramatist_remove_update_check(){\n\n global $wp_version;\n return (object) array(\n 'last_checked' =&gt; time(),\n 'version_checked' =&gt; $wp_version,\n );\n}\nadd_filter('pre_site_transient_update_core', 'the_dramatist_remove_update_check');\nadd_filter('pre_site_transient_update_plugins', 'the_dramatist_remove_update_check');\nadd_filter('pre_site_transient_update_themes', 'the_dramatist_remove_update_check');\n</code></pre>\n\n<p>Place this code in your <code>functions.php</code> or anywhere that executes. It will prevent you WordPress from checking updates.</p>\n" }, { "answer_id": 245391, "author": "appartisan", "author_id": 106502, "author_profile": "https://wordpress.stackexchange.com/users/106502", "pm_score": 0, "selected": false, "text": "<p>Perhaps very hard solution, but you can modify ( if you have access to ) your /etc/hosts file and add a line like:</p>\n\n<p>127.0.0.1 wordpress.org</p>\n\n<p>Your server is going to answer with a 404 very fast in comparison.</p>\n\n<p>Just a little trick, not very serious, but perhaps it works for you.</p>\n\n<p>Do not forget to remove this line from your /etc/hosts file everytime you plan to update.</p>\n\n<p>[NOTE] This solution doesn't require to restart Apache/nginx server nor other restarting issues, you put it and it works from the first time.\n[NOTE 2] This solution makes 'believe' your server that wordpress.org is located in your localhost, and will ask for it in local, and your web server should answer with a 404 not found or 500 error.</p>\n" }, { "answer_id": 245397, "author": "klewis", "author_id": 98671, "author_profile": "https://wordpress.stackexchange.com/users/98671", "pm_score": 1, "selected": false, "text": "<p>There is a feature that you can use in wp-config that relates to disabling plugin and theme updates. You can try it out and see if it helps. </p>\n\n<pre><code>define( 'DISALLOW_FILE_MODS', true );\n</code></pre>\n\n<p>You can learn more about this feature in the codex.</p>\n" }, { "answer_id": 245398, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 0, "selected": false, "text": "<p>When WordPress makes calls to api.wordpress.org, it sets the https scheme using <code>set_url_scheme()</code> depending on whether <code>wp_http_supports()</code> responds that ssl transport is available. See for example in <a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/update.php#L302\" rel=\"nofollow noreferrer\"><code>wp_update_plugins()</code></a> (Line 302 in wp-includes/update.php). </p>\n\n<p>There is a filter in <code>set_url_scheme()</code> which can be used to switch back to http scheme for the api calls.</p>\n\n<pre><code>function wpse245334_set_url_scheme( $url, $scheme, $orig_scheme ) {\n if ( 0 === stripos( $url, 'https://api.wordpress.org/') ) {\n $url = preg_replace( '/^https/i', 'http', $url, 1);\n }\n return $url;\n}\nadd_filter( 'set_url_scheme', 'wpse245334_set_url_scheme' );\n</code></pre>\n\n<p>Like this the calls to the API should all be made without using SSL. This is not as safe, but should still be better than not making the updates. Keep in mind that in case of a failing connection, WordPress might output error messages about failing to establish a secure connection.</p>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245331", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76334/" ]
My ISP having trouble accessing Wordpress.org through SSL connection, thus I am facing performance issues. How Can I entirely block WordPress admin trying to access Wordpress.org to check for latest updates and other things ( By other things I mean any reason that WordPress wants to connect to wordpress.org through SSL ). Thanks.
There is a feature that you can use in wp-config that relates to disabling plugin and theme updates. You can try it out and see if it helps. ``` define( 'DISALLOW_FILE_MODS', true ); ``` You can learn more about this feature in the codex.
245,343
<p>I want to filter posts using dates stored in the post meta table. Here is an image that shows how the meta data is being stored:</p> <p><a href="https://i.stack.imgur.com/VwvRL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VwvRL.png" alt="Date meta data"></a></p> <p>I want to filter records between the start date and end date. Here is my query which is not working:</p> <pre><code>$start_date = date('d-m-Y',strtotime($date." +15 days")); $end_date = date('d-m-Y',strtotime($date." -15 days")); $query_args['meta_query'][] = array( 'key' =&gt; '_start_date', 'value' =&gt; array($end_date, $start_date), 'compare' =&gt; 'BETWEEN', 'type' =&gt; 'date', ); </code></pre>
[ { "answer_id": 245344, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>For meta_query, tax_query, the array is a nested array because the meta_query accepts optional relations :</p>\n\n<p>so, you need to change the given meta_query to :</p>\n\n<pre><code>$query_args['meta_query'] = array(\n //'relation' =&gt; 'OR', // Optional, defaults to \"AND\"\n array(\n 'key' =&gt; '_start_date',\n 'value' =&gt; array($end_date, $start_date),\n 'compare' =&gt; 'BETWEEN',\n 'type' =&gt; 'date',\n )\n);\n</code></pre>\n\n<p>I've commented the relation close, you don't need it with this query.</p>\n\n<p>hope it helps you. </p>\n" }, { "answer_id": 245345, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>If you want to compare dates in a MySQL statement, you should store dates and times using <strong>MySQL datetime format</strong>: YYYY-MM-DD HH:MM:SS (PHP format <code>Y-m-d H:i:s</code>)</p>\n\n<p>Then, you can compare dates easily, and <code>'type' =&gt; 'date'</code> in the meta query argument should work as expected:</p>\n\n<pre><code>$start_date = date('Y-m-d', strtotime($date.\" +15 days\"));\n$end_date = date('Y-m-d',strtotime($date.\" -15 days\"));\n$query_args['meta_query'][] = array(\n 'key' =&gt; '_start_date',\n 'value' =&gt; array($end_date, $start_date),\n 'compare' =&gt; 'BETWEEN',\n 'type' =&gt; 'date',\n );\n</code></pre>\n\n<p>If you need to display the date and/or time in a different format, just convert it before display it.</p>\n\n<p>For example, you can use <a href=\"https://developer.wordpress.org/reference/functions/date_i18n/\" rel=\"nofollow noreferrer\"><code>date_i18n()</code></a> to display a localized date, based on WordPress language configuration, in the format you want. For exmple:</p>\n\n<pre><code>$post_id= 45;\n$start_date = get_post_meta( $post_id. '_start_date', true );\n// Format 15 October 2016 = d F Y\n// See http://php.net/manual/en/function.date.php\necho date_i18n( 'd F Y', strtotime( $start_date ) );\n</code></pre>\n\n<p>Or, if you want to get the date format set in WordPress configuration:</p>\n\n<pre><code>echo date_i18n( get_option( 'date_format' ), strtotime( $start_date ) );\n</code></pre>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245343", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70011/" ]
I want to filter posts using dates stored in the post meta table. Here is an image that shows how the meta data is being stored: [![Date meta data](https://i.stack.imgur.com/VwvRL.png)](https://i.stack.imgur.com/VwvRL.png) I want to filter records between the start date and end date. Here is my query which is not working: ``` $start_date = date('d-m-Y',strtotime($date." +15 days")); $end_date = date('d-m-Y',strtotime($date." -15 days")); $query_args['meta_query'][] = array( 'key' => '_start_date', 'value' => array($end_date, $start_date), 'compare' => 'BETWEEN', 'type' => 'date', ); ```
If you want to compare dates in a MySQL statement, you should store dates and times using **MySQL datetime format**: YYYY-MM-DD HH:MM:SS (PHP format `Y-m-d H:i:s`) Then, you can compare dates easily, and `'type' => 'date'` in the meta query argument should work as expected: ``` $start_date = date('Y-m-d', strtotime($date." +15 days")); $end_date = date('Y-m-d',strtotime($date." -15 days")); $query_args['meta_query'][] = array( 'key' => '_start_date', 'value' => array($end_date, $start_date), 'compare' => 'BETWEEN', 'type' => 'date', ); ``` If you need to display the date and/or time in a different format, just convert it before display it. For example, you can use [`date_i18n()`](https://developer.wordpress.org/reference/functions/date_i18n/) to display a localized date, based on WordPress language configuration, in the format you want. For exmple: ``` $post_id= 45; $start_date = get_post_meta( $post_id. '_start_date', true ); // Format 15 October 2016 = d F Y // See http://php.net/manual/en/function.date.php echo date_i18n( 'd F Y', strtotime( $start_date ) ); ``` Or, if you want to get the date format set in WordPress configuration: ``` echo date_i18n( get_option( 'date_format' ), strtotime( $start_date ) ); ```
245,349
<p>My host has a high speed NGINX cluster.</p> <p>I'd like to load my CSS, JS and media files from this cluster. I've followed <a href="https://www.tsohost.com/knowledge-base/article/495/speed-up-serving-static-content" rel="nofollow noreferrer">these steps</a> and added the new static domain via my DNS.</p> <p>The new DNS settings have propagated successfully and I can access my static files like so <a href="http://static.example.com/wp-content/themes/mytheme/style.css" rel="nofollow noreferrer">http://static.example.com/wp-content/themes/mytheme/style.css</a>.</p> <p>To begin with, I would like to change the media upload URL. I have tried to add the following snippet to <code>wp-config.php</code> before <code>require_once(ABSPATH.’wp-settings.php’);</code></p> <pre><code>/** Path to NGINX cluster */ define( 'UPLOADS', ''.'http://static.example.com/wp-content/uploads' ); </code></pre> <p>When saving the above snippet to <code>wp-config.php</code> and refreshing the site, my media files (images) are loading from the following URL:</p> <pre><code>http://www.example.com/http://static.example.com/wp-content/uploads/2016/11/image-name.jpg </code></pre> <p>As you can see, the root URL is loading before the static URL. What's the correct way to set the new upload path? Should I also perform a search and replace for the previous uploads?</p> <p>I also assume that I change my JS and CSS paths in <code>functions.php</code>, like so?:</p> <pre><code>// Before wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array(), '20161025', false ); // After wp_enqueue_script('script', 'http://static.example.com/wp-content/themes/mytheme/js/script.js', array(), '20161025', false ); </code></pre>
[ { "answer_id": 245804, "author": "Sam", "author_id": 37548, "author_profile": "https://wordpress.stackexchange.com/users/37548", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://wordpress.stackexchange.com/questions/77960/wordpress-3-5-setting-custom-full-url-path-to-files-in-the-media-library\">This answer</a> has solved the problem.</p>\n\n<p>You need to add this to your <code>functions.php</code> file.</p>\n\n<pre><code>/**\n* Custom media upload URL\n* @link https://wordpress.stackexchange.com/questions/77960/wordpress-3-5-setting-custom-full-url-path-to-files-in-the-media-library\n*/\nadd_filter( 'pre_option_upload_url_path', 'upload_url' );\n\nfunction upload_url() {\n return 'http://static.yourdomain.com/wp-content/uploads';\n}\n</code></pre>\n\n<p>There's no need to add the original snippet to <code>wp-config.php</code>.</p>\n" }, { "answer_id": 263629, "author": "user3114253", "author_id": 76325, "author_profile": "https://wordpress.stackexchange.com/users/76325", "pm_score": 2, "selected": false, "text": "<p>The easiest way to tell WordPress to use a sub domain (or another domain) by defining a globals variable in your config.php file.</p>\n\n<pre><code>define('WP_CONTENT_URL', 'http://static.yourdomain.com');\n</code></pre>\n\n<p>Put this at the very beginning of the config file otherwise it may not work. This will update the url of all resource in wp-content directory.</p>\n\n<blockquote>\n <p>Read more about it on <a href=\"https://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants\" rel=\"nofollow noreferrer\">Wordpress Codex</a></p>\n</blockquote>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245349", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37548/" ]
My host has a high speed NGINX cluster. I'd like to load my CSS, JS and media files from this cluster. I've followed [these steps](https://www.tsohost.com/knowledge-base/article/495/speed-up-serving-static-content) and added the new static domain via my DNS. The new DNS settings have propagated successfully and I can access my static files like so <http://static.example.com/wp-content/themes/mytheme/style.css>. To begin with, I would like to change the media upload URL. I have tried to add the following snippet to `wp-config.php` before `require_once(ABSPATH.’wp-settings.php’);` ``` /** Path to NGINX cluster */ define( 'UPLOADS', ''.'http://static.example.com/wp-content/uploads' ); ``` When saving the above snippet to `wp-config.php` and refreshing the site, my media files (images) are loading from the following URL: ``` http://www.example.com/http://static.example.com/wp-content/uploads/2016/11/image-name.jpg ``` As you can see, the root URL is loading before the static URL. What's the correct way to set the new upload path? Should I also perform a search and replace for the previous uploads? I also assume that I change my JS and CSS paths in `functions.php`, like so?: ``` // Before wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array(), '20161025', false ); // After wp_enqueue_script('script', 'http://static.example.com/wp-content/themes/mytheme/js/script.js', array(), '20161025', false ); ```
[This answer](https://wordpress.stackexchange.com/questions/77960/wordpress-3-5-setting-custom-full-url-path-to-files-in-the-media-library) has solved the problem. You need to add this to your `functions.php` file. ``` /** * Custom media upload URL * @link https://wordpress.stackexchange.com/questions/77960/wordpress-3-5-setting-custom-full-url-path-to-files-in-the-media-library */ add_filter( 'pre_option_upload_url_path', 'upload_url' ); function upload_url() { return 'http://static.yourdomain.com/wp-content/uploads'; } ``` There's no need to add the original snippet to `wp-config.php`.
245,364
<p>I'm trying to develop a code to call some Codex functions (<a href="https://codex.wordpress.org/Function_Reference" rel="noreferrer">https://codex.wordpress.org/Function_Reference</a>) the problem is simple, I don't find any doc where read about how to start. </p> <p>I have a PHP file with this line for example: </p> <pre><code>&lt;?php $website = "http://example.com"; $userdata = array( 'user_login' =&gt; 'login_name', 'user_url' =&gt; $website, 'user_pass' =&gt; NULL // When creating an user, `user_pass` is expected. ); $user_id = wp_insert_user( $userdata ) ; //On success if ( ! is_wp_error( $user_id ) ) { echo "User created : ". $user_id; } ?&gt; </code></pre> <p>Where I need to put this code to check if works? Where I need to call it? Must I create a plugin? Can I call those functions from a script in a specific folder? </p> <p>For example, the funcion wp_insert_user is in /wp-includes/user.php, can I call the function just including the script? </p> <pre><code>include('user.php') </code></pre> <p>Where are the rest of the functions? </p> <p>Someone knows an specific manual with a simple doc? I'm getting crazy. </p> <p>This is my first script for a CMS and I don't undertand how it works, but I dont find manuals or simple doc. </p>
[ { "answer_id": 245674, "author": "Leonardo Cavani", "author_id": 106464, "author_profile": "https://wordpress.stackexchange.com/users/106464", "pm_score": 4, "selected": true, "text": "<p>I get the solution. </p>\n\n<p>To call functions from Wordpress from a custom script, you need to import wp-load: </p>\n\n<pre><code>require_once(\"/path/wp-load.php\");\n</code></pre>\n\n<p>Thats all, I can work fine with those functions. I save my own script in the root of my PHP Wordpress and I didn't need a plugin. </p>\n" }, { "answer_id": 319118, "author": "Aman Dhanda", "author_id": 154022, "author_profile": "https://wordpress.stackexchange.com/users/154022", "pm_score": 1, "selected": false, "text": "<p>External files can easily access the wordpress functions. You just need to include the file <code>wp-load.php</code> in your external file.\nThe <code>wp-load.php</code> file is located in root of your wordpress installation.\nExample: Suppose your file is <code>test.php</code> located at root directory of wordpress installation.</p>\n\n<pre><code>&lt;?php\n require_once('wp-load.php');\n // Your custom code\n?&gt;\n</code></pre>\n\n<p>Source: <a href=\"https://webolute.com/blog/wordpress/how-to-access-wordpress-functions-in-external-file\" rel=\"nofollow noreferrer\">How to access WordPress functions in external file</a></p>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106464/" ]
I'm trying to develop a code to call some Codex functions (<https://codex.wordpress.org/Function_Reference>) the problem is simple, I don't find any doc where read about how to start. I have a PHP file with this line for example: ``` <?php $website = "http://example.com"; $userdata = array( 'user_login' => 'login_name', 'user_url' => $website, 'user_pass' => NULL // When creating an user, `user_pass` is expected. ); $user_id = wp_insert_user( $userdata ) ; //On success if ( ! is_wp_error( $user_id ) ) { echo "User created : ". $user_id; } ?> ``` Where I need to put this code to check if works? Where I need to call it? Must I create a plugin? Can I call those functions from a script in a specific folder? For example, the funcion wp\_insert\_user is in /wp-includes/user.php, can I call the function just including the script? ``` include('user.php') ``` Where are the rest of the functions? Someone knows an specific manual with a simple doc? I'm getting crazy. This is my first script for a CMS and I don't undertand how it works, but I dont find manuals or simple doc.
I get the solution. To call functions from Wordpress from a custom script, you need to import wp-load: ``` require_once("/path/wp-load.php"); ``` Thats all, I can work fine with those functions. I save my own script in the root of my PHP Wordpress and I didn't need a plugin.
245,370
<p>I use <a href="https://developer.wordpress.org/reference/functions/add_menu_page/" rel="nofollow noreferrer"><code>add_menu()</code></a>, then I add number of <a href="https://developer.wordpress.org/reference/functions/add_submenu_page/" rel="nofollow noreferrer"><code>add_submenu()</code></a>. </p> <p><strong>CODE</strong></p> <pre><code> add_menu_page( 'Config', 'MDW Config', 'manage_options', 'mdw-config', 'config_general_info', '', 45); add_submenu_page( 'mdw-config', 'General info', 'Info', 'manage_options', 'general-info', 'config_general_info'); add_submenu_page( 'mdw-config', 'Google Analytics Integration', 'Google Analytics', 'manage_options', 'ga-integration', 'config_ga_integration'); </code></pre> <p>And then some more submenus. What it achieves is:</p> <p><a href="https://i.stack.imgur.com/xxZVA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xxZVA.png" alt="enter image description here"></a></p> <p>As you can see, <strong>MDW Config</strong>, which is second argument of <code>add_menu()</code> duplicates, it seems like it's submenu of itself. I'm pretty sure it's possible to avoid it, as for example <em>Appearance</em> menu, which is default one, links directly to it's <em>Themes</em> submenu. </p> <p>What am I doing wrong?</p>
[ { "answer_id": 245374, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>The only way I find it's to do it quickly, is with css</p>\n\n<pre><code>#toplevel_page_bb-plugins .wp-submenu .wp-first-item {\n display: none;\n}\n</code></pre>\n\n<p>Of course, you will replace <code>bb-plugins</code> with your menu slug. And add this in the admin css file of your plugin.</p>\n" }, { "answer_id": 245375, "author": "Sebastian Kaczmarek", "author_id": 100836, "author_profile": "https://wordpress.stackexchange.com/users/100836", "pm_score": 3, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code> add_menu_page( 'MDW Config', 'MDW Config', 'manage_options', 'mdw-config', 'config_general_info', '', 45);\n add_submenu_page( 'mdw-config', 'General info', 'Info', 'manage_options', 'mdw-config', 'config_general_info');\n add_submenu_page( 'mdw-config', 'Google Analytics Integration', 'Google Analytics', 'manage_options', 'ga-integration', 'config_ga_integration');\n</code></pre>\n\n<p>What you have to do is simply overwrite the name of your first submenu page by assigning it to the same <code>menu-slug</code> but with different name.</p>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100795/" ]
I use [`add_menu()`](https://developer.wordpress.org/reference/functions/add_menu_page/), then I add number of [`add_submenu()`](https://developer.wordpress.org/reference/functions/add_submenu_page/). **CODE** ``` add_menu_page( 'Config', 'MDW Config', 'manage_options', 'mdw-config', 'config_general_info', '', 45); add_submenu_page( 'mdw-config', 'General info', 'Info', 'manage_options', 'general-info', 'config_general_info'); add_submenu_page( 'mdw-config', 'Google Analytics Integration', 'Google Analytics', 'manage_options', 'ga-integration', 'config_ga_integration'); ``` And then some more submenus. What it achieves is: [![enter image description here](https://i.stack.imgur.com/xxZVA.png)](https://i.stack.imgur.com/xxZVA.png) As you can see, **MDW Config**, which is second argument of `add_menu()` duplicates, it seems like it's submenu of itself. I'm pretty sure it's possible to avoid it, as for example *Appearance* menu, which is default one, links directly to it's *Themes* submenu. What am I doing wrong?
Try this: ``` add_menu_page( 'MDW Config', 'MDW Config', 'manage_options', 'mdw-config', 'config_general_info', '', 45); add_submenu_page( 'mdw-config', 'General info', 'Info', 'manage_options', 'mdw-config', 'config_general_info'); add_submenu_page( 'mdw-config', 'Google Analytics Integration', 'Google Analytics', 'manage_options', 'ga-integration', 'config_ga_integration'); ``` What you have to do is simply overwrite the name of your first submenu page by assigning it to the same `menu-slug` but with different name.
245,372
<p>I'm looking to apply custom CSS in the admin only for a certain user role, "Contributor" to be exact.</p> <p>Everything I try either seems to have no effect, or produces a 500 error.</p> <p>What I've tried has in the main been loosely based around this:</p> <pre><code>add_action('admin_head', 'custom_admin_css'); function custom_admin_css( ){ global $user; if (isset($user-&gt;roles) &amp;&amp; is_array( $user-&gt;roles ) ) { if( $user-&gt;roles[0] == 'administrator' ) { //Do something } elseif ( $user-&gt;roles[0] == 'editor' ) { //Do something } elseif ( $user-&gt;roles[0] == 'contributor') { echo '&lt;style&gt; CSS &lt;/style&gt;'; } else { //Do something } } } </code></pre>
[ { "answer_id": 245377, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>function wpse245372_admin_user_css() {\n $user = wp_get_current_user();\n if ( in_array( 'administrator', (array) $user-&gt;roles ) ) {\n // Your Admin Stuff\n } elseif ( in_array( 'editor', (array) $user-&gt;roles ) ) {\n // Your Editor Stuff\n } elseif ( in_array( 'contributor', (array) $user-&gt;roles ) ) {\n echo '&lt;style&gt; CSS &lt;/style&gt;';\n } else {\n // What Everyone Else Gets\n }\n}\nadd_action( 'admin_head', 'wpse245372_admin_user_css' );\n</code></pre>\n" }, { "answer_id": 245389, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 5, "selected": true, "text": "<p>Upon request I will write an answer using a function from a suggested answer for the similar question: <a href=\"https://wordpress.stackexchange.com/questions/66834/how-to-target-with-css-admin-elements-according-to-user-role-level\">How to target with css, admin elements according to user role level?</a>.</p>\n\n<p>This function will output classes to the body element for all roles of the current user in the form <code>role-XXXXX</code></p>\n\n<pre><code>function wpa66834_role_admin_body_class( $classes ) {\n global $current_user;\n foreach( $current_user-&gt;roles as $role )\n $classes .= ' role-' . $role;\n return trim( $classes );\n}\nadd_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' );\n</code></pre>\n\n<p>Now the roles can be targeted with css rules like:</p>\n\n<pre><code>#targetElement { \n display: none; \n}\n.role-editor #targetElement { \n display: visible; \n}\n</code></pre>\n\n<p>These CSS rules don't have to be output conditionally. They can be placed for example in any CSS file which is included via <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"noreferrer\">admin_enqueue_scripts</a> action:</p>\n\n<pre><code>function wp245372_admin_enqueue_scripts() {\n wp_enqueue_style( 'my-admin-css', 'path/to/file.css', array(), 0.1);\n}\nadd_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );\n</code></pre>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245372", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56659/" ]
I'm looking to apply custom CSS in the admin only for a certain user role, "Contributor" to be exact. Everything I try either seems to have no effect, or produces a 500 error. What I've tried has in the main been loosely based around this: ``` add_action('admin_head', 'custom_admin_css'); function custom_admin_css( ){ global $user; if (isset($user->roles) && is_array( $user->roles ) ) { if( $user->roles[0] == 'administrator' ) { //Do something } elseif ( $user->roles[0] == 'editor' ) { //Do something } elseif ( $user->roles[0] == 'contributor') { echo '<style> CSS </style>'; } else { //Do something } } } ```
Upon request I will write an answer using a function from a suggested answer for the similar question: [How to target with css, admin elements according to user role level?](https://wordpress.stackexchange.com/questions/66834/how-to-target-with-css-admin-elements-according-to-user-role-level). This function will output classes to the body element for all roles of the current user in the form `role-XXXXX` ``` function wpa66834_role_admin_body_class( $classes ) { global $current_user; foreach( $current_user->roles as $role ) $classes .= ' role-' . $role; return trim( $classes ); } add_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' ); ``` Now the roles can be targeted with css rules like: ``` #targetElement { display: none; } .role-editor #targetElement { display: visible; } ``` These CSS rules don't have to be output conditionally. They can be placed for example in any CSS file which is included via [admin\_enqueue\_scripts](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts) action: ``` function wp245372_admin_enqueue_scripts() { wp_enqueue_style( 'my-admin-css', 'path/to/file.css', array(), 0.1); } add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' ); ```
245,381
<p>I want to make it so when user is logged out/in &amp; viewing another user profile the only see the Contact Seller button &amp; when user is logged in viewing their own profile it shows View Inbox &amp; Edit My Profile buttons. Here is a screensoh that show a user logged in as admin viewing a profile belonging to flamez and seeing the incorrect buttons <a href="https://www.dropbox.com/s/lifcq06y54jol7z/Screenshot%20of%20error.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/lifcq06y54jol7z/Screenshot%20of%20error.png?dl=0</a></p> <p>here is the code i have so far:</p> <pre><code>&lt;style&gt; a.view_inbox_btn:link, a.view_inbox_btn:visited{ background: Green; display: inline-block; padding: 9px 0px 9px 0px; color: #fff; text-align: center; text-decoration: none; border: 1px solid #457D2B; width: 25%; font-size: 23px; font-weight: bold; font-family: 'Alegreya Sans',Arial, Helvetica, sans-serif; border-radius: 3px; margin-left: 5px; margin-top: 52px;} a.view_inbox_btn:hover, a.view_inbox_btn:active { background-color: #4da64d; } a.edit_profile_btn:link, a.edit_profile_btn:visited{ background: #ff7f00; display: inline-block; padding: 9px 0px 9px 0px; color: #fff; text-align: center; text-decoration: none; border: 1px solid #ff7f00; width: 25%; font-size: 23px; font-weight: bold; font-family: 'Alegreya Sans',Arial, Helvetica, sans-serif; border-radius: 3px; margin-left: 11px; margin-top: 17px;} a.edit_profile_btn:hover, a.edit_profile_btn:active { background-color: orange; } a.contact_seller_btn:link, a.contact_seller_btn:visited{ background: Green; display: inline-block; padding: 9px 0px 9px 0px; color: #fff; text-align: center; text-decoration: none; border: 1px solid #457D2B; width: 25%; font-size: 23px; font-weight: bold; font-family: 'Alegreya Sans',Arial, Helvetica, sans-serif; border-radius: 3px; margin-left: 5px; margin-top: 52px;} a.contact_seller_btn:hover, a.contact_seller_btn:active { background-color: #4da64d; } &lt;/style&gt; &lt;?php if (is_user_logged_in() ): ?&gt; &lt;a href="http://enormu.com/marketplace/my-account/private-messages/"class="view_inbox_btn"&gt;View Inbox&lt;/a&gt; &lt;a href="http://enormu.com/marketplace/my-account/personal-information/"class="edit_profile_btn"&gt;Edit Profile&lt;/a&gt; &lt;?php else: ?&gt; &lt;a href="http://enormu.com/marketplace/my-account/private-messages/"class="contact_seller_btn"&gt;Contact Seller&lt;/a&gt; &lt;?php endif ?&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 245377, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>function wpse245372_admin_user_css() {\n $user = wp_get_current_user();\n if ( in_array( 'administrator', (array) $user-&gt;roles ) ) {\n // Your Admin Stuff\n } elseif ( in_array( 'editor', (array) $user-&gt;roles ) ) {\n // Your Editor Stuff\n } elseif ( in_array( 'contributor', (array) $user-&gt;roles ) ) {\n echo '&lt;style&gt; CSS &lt;/style&gt;';\n } else {\n // What Everyone Else Gets\n }\n}\nadd_action( 'admin_head', 'wpse245372_admin_user_css' );\n</code></pre>\n" }, { "answer_id": 245389, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 5, "selected": true, "text": "<p>Upon request I will write an answer using a function from a suggested answer for the similar question: <a href=\"https://wordpress.stackexchange.com/questions/66834/how-to-target-with-css-admin-elements-according-to-user-role-level\">How to target with css, admin elements according to user role level?</a>.</p>\n\n<p>This function will output classes to the body element for all roles of the current user in the form <code>role-XXXXX</code></p>\n\n<pre><code>function wpa66834_role_admin_body_class( $classes ) {\n global $current_user;\n foreach( $current_user-&gt;roles as $role )\n $classes .= ' role-' . $role;\n return trim( $classes );\n}\nadd_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' );\n</code></pre>\n\n<p>Now the roles can be targeted with css rules like:</p>\n\n<pre><code>#targetElement { \n display: none; \n}\n.role-editor #targetElement { \n display: visible; \n}\n</code></pre>\n\n<p>These CSS rules don't have to be output conditionally. They can be placed for example in any CSS file which is included via <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"noreferrer\">admin_enqueue_scripts</a> action:</p>\n\n<pre><code>function wp245372_admin_enqueue_scripts() {\n wp_enqueue_style( 'my-admin-css', 'path/to/file.css', array(), 0.1);\n}\nadd_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );\n</code></pre>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106493/" ]
I want to make it so when user is logged out/in & viewing another user profile the only see the Contact Seller button & when user is logged in viewing their own profile it shows View Inbox & Edit My Profile buttons. Here is a screensoh that show a user logged in as admin viewing a profile belonging to flamez and seeing the incorrect buttons <https://www.dropbox.com/s/lifcq06y54jol7z/Screenshot%20of%20error.png?dl=0> here is the code i have so far: ``` <style> a.view_inbox_btn:link, a.view_inbox_btn:visited{ background: Green; display: inline-block; padding: 9px 0px 9px 0px; color: #fff; text-align: center; text-decoration: none; border: 1px solid #457D2B; width: 25%; font-size: 23px; font-weight: bold; font-family: 'Alegreya Sans',Arial, Helvetica, sans-serif; border-radius: 3px; margin-left: 5px; margin-top: 52px;} a.view_inbox_btn:hover, a.view_inbox_btn:active { background-color: #4da64d; } a.edit_profile_btn:link, a.edit_profile_btn:visited{ background: #ff7f00; display: inline-block; padding: 9px 0px 9px 0px; color: #fff; text-align: center; text-decoration: none; border: 1px solid #ff7f00; width: 25%; font-size: 23px; font-weight: bold; font-family: 'Alegreya Sans',Arial, Helvetica, sans-serif; border-radius: 3px; margin-left: 11px; margin-top: 17px;} a.edit_profile_btn:hover, a.edit_profile_btn:active { background-color: orange; } a.contact_seller_btn:link, a.contact_seller_btn:visited{ background: Green; display: inline-block; padding: 9px 0px 9px 0px; color: #fff; text-align: center; text-decoration: none; border: 1px solid #457D2B; width: 25%; font-size: 23px; font-weight: bold; font-family: 'Alegreya Sans',Arial, Helvetica, sans-serif; border-radius: 3px; margin-left: 5px; margin-top: 52px;} a.contact_seller_btn:hover, a.contact_seller_btn:active { background-color: #4da64d; } </style> <?php if (is_user_logged_in() ): ?> <a href="http://enormu.com/marketplace/my-account/private-messages/"class="view_inbox_btn">View Inbox</a> <a href="http://enormu.com/marketplace/my-account/personal-information/"class="edit_profile_btn">Edit Profile</a> <?php else: ?> <a href="http://enormu.com/marketplace/my-account/private-messages/"class="contact_seller_btn">Contact Seller</a> <?php endif ?> </ul> </div> ```
Upon request I will write an answer using a function from a suggested answer for the similar question: [How to target with css, admin elements according to user role level?](https://wordpress.stackexchange.com/questions/66834/how-to-target-with-css-admin-elements-according-to-user-role-level). This function will output classes to the body element for all roles of the current user in the form `role-XXXXX` ``` function wpa66834_role_admin_body_class( $classes ) { global $current_user; foreach( $current_user->roles as $role ) $classes .= ' role-' . $role; return trim( $classes ); } add_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' ); ``` Now the roles can be targeted with css rules like: ``` #targetElement { display: none; } .role-editor #targetElement { display: visible; } ``` These CSS rules don't have to be output conditionally. They can be placed for example in any CSS file which is included via [admin\_enqueue\_scripts](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts) action: ``` function wp245372_admin_enqueue_scripts() { wp_enqueue_style( 'my-admin-css', 'path/to/file.css', array(), 0.1); } add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' ); ```
245,388
<p>This is what I have now: <a href="https://i.stack.imgur.com/HQu5k.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HQu5k.jpg" alt="enter image description here"></a> I want the video player to take up the whole horizontal space and stretch width 100%. The video should also stay responsive, filling the whole video player area.</p> <p>I fallowed advice in <a href="https://wordpress.stackexchange.com/questions/162008/how-do-i-control-video-media-display-sizing-with-native-wordpress-player">this answer</a> and added this to my functions.php:</p> <pre><code>if ( ! isset( $content_width ) ) { $content_width = 850; } </code></pre> <p>The content width on my template is 850px. But setting the content width didn't help.</p> <p>How to make WordPress native video player width 100%?</p>
[ { "answer_id": 245911, "author": "Azamat", "author_id": 105471, "author_profile": "https://wordpress.stackexchange.com/users/105471", "pm_score": 5, "selected": true, "text": "<p>I added this to my style.css and now the video player is fully responsive!</p>\n\n<pre><code>.wp-video, video.wp-video-shortcode, .mejs-container, .mejs-overlay.load {\n width: 100% !important;\n height: 100% !important;\n}\n.mejs-container {\n padding-top: 56.25%;\n}\n.wp-video, video.wp-video-shortcode {\n max-width: 100% !important;\n}\nvideo.wp-video-shortcode {\n position: relative;\n}\n.mejs-mediaelement {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n}\n.mejs-controls {\n display: none;\n}\n.mejs-overlay-play {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n width: auto !important;\n height: auto !important;\n}\n</code></pre>\n" }, { "answer_id": 371713, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>I know this comes a bit late but I going to leave here in case some one needs a different alternative from the above answer.</p>\n<p>We add the function below to our theme most probably under functions.php or any other included file. The function below wraps the oembed inside the video-container div and below function is the respective CSS for the new class</p>\n<pre><code>/**\n* Add Response code to video embeds in WordPress\n*\n*/\nfunction ns_embed_html( $html ) {\n\n return '&lt;div class=&quot;video-container&quot;&gt;' . $html . '&lt;/div&gt;';\n}\nadd_filter( 'embed_oembed_html', 'ns_embed_html', 10, 3 );\nadd_filter( 'video_embed_html', 'ns_embed_html' ); // Jetpack\n\n// CSS \n.video-container {\n position: relative;\n padding-bottom: 56.25%;\n height: 0;\n overflow: hidden;\n max-width: 1200px;\n margin: 0 auto;\n }\n\n .video-container iframe, .video-container object, .video-container embed, .video-container video {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n width: 100%;\n height: 100%;\n }\n</code></pre>\n" }, { "answer_id": 375617, "author": "Gee S", "author_id": 195366, "author_profile": "https://wordpress.stackexchange.com/users/195366", "pm_score": 2, "selected": false, "text": "<p>It's simple with Wordpress 5</p>\n<p>Just add the following CSS:</p>\n<pre><code>.wp-video { width: 100% !important }\n.wp-video video { width: 100% !important; height: 100% !important; }\n</code></pre>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245388", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105471/" ]
This is what I have now: [![enter image description here](https://i.stack.imgur.com/HQu5k.jpg)](https://i.stack.imgur.com/HQu5k.jpg) I want the video player to take up the whole horizontal space and stretch width 100%. The video should also stay responsive, filling the whole video player area. I fallowed advice in [this answer](https://wordpress.stackexchange.com/questions/162008/how-do-i-control-video-media-display-sizing-with-native-wordpress-player) and added this to my functions.php: ``` if ( ! isset( $content_width ) ) { $content_width = 850; } ``` The content width on my template is 850px. But setting the content width didn't help. How to make WordPress native video player width 100%?
I added this to my style.css and now the video player is fully responsive! ``` .wp-video, video.wp-video-shortcode, .mejs-container, .mejs-overlay.load { width: 100% !important; height: 100% !important; } .mejs-container { padding-top: 56.25%; } .wp-video, video.wp-video-shortcode { max-width: 100% !important; } video.wp-video-shortcode { position: relative; } .mejs-mediaelement { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } .mejs-controls { display: none; } .mejs-overlay-play { top: 0; right: 0; bottom: 0; left: 0; width: auto !important; height: auto !important; } ```
245,399
<p>I'm trying to display different templates in archive.php page. I need to load different article display depending on custom post type. Here is my code: </p> <pre><code>&lt;?php if(is_singular('libri')) :?&gt; &lt;?php // WP_Query arguments $args = array ( 'post_type' =&gt; 'libri', ); // The Query $query = new WP_Query( $args ); // The Loop if ( $query-&gt;have_posts() ) { while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); the_title(); } } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;?php endif; ?&gt; &lt;?php get_footer();?&gt; </code></pre> <p>Anyway the page doesn't display anything. How can I get rid of this problem? </p> <p>Thanks!</p>
[ { "answer_id": 245401, "author": "wscourge", "author_id": 100795, "author_profile": "https://wordpress.stackexchange.com/users/100795", "pm_score": 0, "selected": false, "text": "<p>You use <a href=\"https://codex.wordpress.org/Function_Reference/is_singular\" rel=\"nofollow noreferrer\"><code>is_singular()</code></a> which is never going to return <code>true</code> on archive page, as <a href=\"https://wordpress.stackexchange.com/users/736/tom-j-nowell\">@Tom J Nowell</a> pointed out in the comment. So what you need to do for <code>query</code> to execute is to remove that condition.</p>\n" }, { "answer_id": 245404, "author": "czerspalace", "author_id": 47406, "author_profile": "https://wordpress.stackexchange.com/users/47406", "pm_score": 3, "selected": true, "text": "<p><code>is_singular</code> will return false on an archive page. If you wanted to check if you are on an archive for a post type, you would use <code>is_post_type_archive( 'libri' )</code> , or you can create an <code>archive-{post_type}.php</code> file, which on this case would be <code>archive-libri.php</code></p>\n\n<p>References: <a href=\"https://codex.wordpress.org/Post_Type_Templates\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Post_Type_Templates</a> <a href=\"https://codex.wordpress.org/Conditional_Tags#A_Single_Post_Page\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Conditional_Tags#A_Single_Post_Page</a></p>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103072/" ]
I'm trying to display different templates in archive.php page. I need to load different article display depending on custom post type. Here is my code: ``` <?php if(is_singular('libri')) :?> <?php // WP_Query arguments $args = array ( 'post_type' => 'libri', ); // The Query $query = new WP_Query( $args ); // The Loop if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); the_title(); } } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ?> <?php else : ?> <?php endif; ?> <?php get_footer();?> ``` Anyway the page doesn't display anything. How can I get rid of this problem? Thanks!
`is_singular` will return false on an archive page. If you wanted to check if you are on an archive for a post type, you would use `is_post_type_archive( 'libri' )` , or you can create an `archive-{post_type}.php` file, which on this case would be `archive-libri.php` References: <https://codex.wordpress.org/Post_Type_Templates> <https://codex.wordpress.org/Conditional_Tags#A_Single_Post_Page>