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
313,124
<p>For my wordpress website plain permalinks are not working. The post url is changing but when we click on the post its not redirecting to the post page. It will be in the home page itself.</p> <p>For example:</p> <pre><code>http://example.com/?p=14523 </code></pre> <p>If I change the permalinks to other custom formats, it works correctly and showing the posts page. For example:</p> <pre><code>http://example.com/2018/09/01/postname/ </code></pre> <p>I tried creating a new <code>.htaccess</code> file after changing the permalinks to plain. Still not working.</p>
[ { "answer_id": 313131, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 2, "selected": true, "text": "<p>Plain permalinks of the form <code>/?p=14523</code> (or <code>/index.php?p=14523</code>) don't necessarily need any <code>.htaccess</code> file since they don't require mod_rewrite to rewrite the URL (unlike the the <em>custom permalinks</em> you mention).</p>\n\n<p>However, for a URL of the form <code>/?p=14523</code> (as opposed to <code>/index.php?p=14523</code>), where you don't explicitly state the index document (ie. <code>index.php</code>) in the URL then the <code>DirectoryIndex</code> must be correctly set on your server. This can be achieved in <code>.htaccess</code> using the following directive:</p>\n\n<pre><code>DirectoryIndex index.php\n</code></pre>\n\n<p>Normally, this is set by default on most servers, but sometimes it is not.</p>\n" }, { "answer_id": 313152, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 0, "selected": false, "text": "<p>delete .htaccess completely and reset permalinks, I have faced similar incidents it did the trick.</p>\n" } ]
2018/09/02
[ "https://wordpress.stackexchange.com/questions/313124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149810/" ]
For my wordpress website plain permalinks are not working. The post url is changing but when we click on the post its not redirecting to the post page. It will be in the home page itself. For example: ``` http://example.com/?p=14523 ``` If I change the permalinks to other custom formats, it works correctly and showing the posts page. For example: ``` http://example.com/2018/09/01/postname/ ``` I tried creating a new `.htaccess` file after changing the permalinks to plain. Still not working.
Plain permalinks of the form `/?p=14523` (or `/index.php?p=14523`) don't necessarily need any `.htaccess` file since they don't require mod\_rewrite to rewrite the URL (unlike the the *custom permalinks* you mention). However, for a URL of the form `/?p=14523` (as opposed to `/index.php?p=14523`), where you don't explicitly state the index document (ie. `index.php`) in the URL then the `DirectoryIndex` must be correctly set on your server. This can be achieved in `.htaccess` using the following directive: ``` DirectoryIndex index.php ``` Normally, this is set by default on most servers, but sometimes it is not.
313,180
<p>The goal is to make my hidden Wordpress site go from <a href="http://example.com/subdir" rel="nofollow noreferrer">http://example.com/subdir</a> (which I have now) to replace the olde site at <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a> (which is what I want when I take my WP site live). In previous questions this article came up in regard to changing the URLs: <a href="https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory" rel="nofollow noreferrer">https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory</a></p> <p>My old example.com URL points to the old html site while the /subdir Wordpress site is new and improved. The plan is to institute an instant and permanent switch to the Wordpress site in the subdirectory, but to use the example.com main directory as the link.</p> <p>The problem I have is that there are a lot of links within my wordpress site to <a href="http://example.com/subdir/page1" rel="nofollow noreferrer">http://example.com/subdir/page1</a> and <a href="http://example.com/subdir/page2" rel="nofollow noreferrer">http://example.com/subdir/page2</a> and so on. Will that be a nightmare to clean up manually or will link change to become <a href="http://example.com/page1" rel="nofollow noreferrer">http://example.com/page1</a> once the switch is made, making the "/subdir" mention completely disappear? Is there any software or a plugin that can just do a global URL update across my site so every <a href="http://example.com/subdir/page" rel="nofollow noreferrer">http://example.com/subdir/page</a> just becomes <a href="http://example.com/page" rel="nofollow noreferrer">http://example.com/page</a> automatically?</p> <p>I'm getting nervous as it comes time to take it live and I've never done this kind of thing before. Please let me know what I can expect when everything changes over and what will make it as easy as possible. Thank you!</p>
[ { "answer_id": 313181, "author": "Petr Cibulka", "author_id": 28718, "author_profile": "https://wordpress.stackexchange.com/users/28718", "pm_score": 2, "selected": true, "text": "<p>You can search and replace every occurence of \"<a href=\"http://example.com/subdir\" rel=\"nofollow noreferrer\">http://example.com/subdir</a>\" in the database with \"<a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a>\". </p>\n\n<p>If you're comfortable with <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">WP-CLI</a>, <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">there is command for that</a>:</p>\n\n<pre><code>$ wp search-replace 'http://example.com/subdir' 'http://example.com'\n</code></pre>\n\n<p>If not, you can use some plugin for that. Some possible would be:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">WP Migrate DB</a></li>\n<li><a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better Search Replace</a></li>\n</ul>\n" }, { "answer_id": 313182, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Another choice is to just set the domain to the new folder. This is done in your hosting Cpanel, under domains and/or add-on domains. Check your hosting's help pages for how to direct a domain to a folder other than the 'root' folder (often called 'public_html').</p>\n\n<p>Otherwise, you will need to copy all files from the subdir folder to the root - all WP files, themes, plugins, custom code, media, etc. Then you will need to do a search/replace of the old url to new url. I use the \"Better Search and Replace\" plugin to do this. </p>\n\n<p>So it might be easier just to use your hosting processes to point the domain to the new folder.</p>\n" } ]
2018/09/03
[ "https://wordpress.stackexchange.com/questions/313180", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147934/" ]
The goal is to make my hidden Wordpress site go from <http://example.com/subdir> (which I have now) to replace the olde site at <http://example.com> (which is what I want when I take my WP site live). In previous questions this article came up in regard to changing the URLs: <https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory> My old example.com URL points to the old html site while the /subdir Wordpress site is new and improved. The plan is to institute an instant and permanent switch to the Wordpress site in the subdirectory, but to use the example.com main directory as the link. The problem I have is that there are a lot of links within my wordpress site to <http://example.com/subdir/page1> and <http://example.com/subdir/page2> and so on. Will that be a nightmare to clean up manually or will link change to become <http://example.com/page1> once the switch is made, making the "/subdir" mention completely disappear? Is there any software or a plugin that can just do a global URL update across my site so every <http://example.com/subdir/page> just becomes <http://example.com/page> automatically? I'm getting nervous as it comes time to take it live and I've never done this kind of thing before. Please let me know what I can expect when everything changes over and what will make it as easy as possible. Thank you!
You can search and replace every occurence of "<http://example.com/subdir>" in the database with "<http://example.com>". If you're comfortable with [WP-CLI](https://wp-cli.org/), [there is command for that](https://developer.wordpress.org/cli/commands/search-replace/): ``` $ wp search-replace 'http://example.com/subdir' 'http://example.com' ``` If not, you can use some plugin for that. Some possible would be: * [WP Migrate DB](https://wordpress.org/plugins/wp-migrate-db/) * [Better Search Replace](https://wordpress.org/plugins/better-search-replace/)
313,234
<p>As the title says, I want to create a different permalink structure for posts belonging to a certain category, in my case, the name is "ICO". I've found this piece of code on StackExchange, but it doesn't really do anything for me, contrary to the OPs feedback.</p> <p>The code is:</p> <pre><code>//Rewrite URLs for "ICO" category add_filter( 'post_link', 'custom_permalink', 10, 3 ); function custom_permalink( $permalink, $post, $leavename ) { // Get the category for the post $category = get_the_category($post-&gt;ID); if ( !empty($category) &amp;&amp; $category[0]-&gt;cat_name == "ICO" ) { $cat_name = strtolower($category[0]-&gt;cat_name); $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post-&gt;post_name .'/' ) ); } return $permalink; } add_action( 'init', 'custom_rewrite_rules' ); function custom_rewrite_rules() { add_rewrite_rule( 'ico/([^/]+)(?:/([0-9]+))?/?$', 'index.php?category_name=ico&amp;name=$matches[1]&amp;page=$matches[2]', 'top' // The rule position; either 'top' or 'bottom' (default). ); } </code></pre> <p>All posts from that category, present on the homepage do not have their URL changed, the default URL structure is the same www.site.com/post_name/</p> <p>However, I noticed that on some widgets, in a list with posts from that category, some of the posts have their URL changed, some do not. There isn't any difference between them, they have the same categories. Even if I go on that URL /ico/post_name/ it works and if I delete /ico/ and go on the default permalink structure, it works as well, making it a duplicate URL for the same post.</p> <p>What have I done wrong?</p> <p>Edit: I also tried this piece of code, same effect, not working</p> <pre><code>add_filter( 'post_link', 'custom_permalink', 10, 3 ); function custom_permalink( $permalink, $post, $leavename ) { // Get the categories for the post $category = get_the_category($post-&gt;ID); if ( !empty($category) &amp;&amp; $category[0]-&gt;cat_name == "ICO" ) { $cat_name = strtolower($category[0]-&gt;cat_name); $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post-&gt;post_name .'/' ) ); } return $permalink; } add_action('generate_rewrite_rules', 'custom_rewrite_rules'); function custom_rewrite_rules( $wp_rewrite ) { // This rule will will match the post id in %postname%-%post_id% struture $new_rules['ico/^([^/]*)/?'] = 'index.php?p=$matches[1]'; $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules; return $wp_rewrite; } </code></pre>
[ { "answer_id": 354491, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>(I know this is a late answer, so the original poster has probably moved on from this. But I am posting an answer to this in hopes that it will help later users solve their issue, should they happen along to this question.)</p>\n\n<p>The first step is understanding how email works in WordPress. WP will use <code>wp_mail()</code> to send messages, and this is essentially a wrapper for PHP's <code>mail()</code>.</p>\n\n<p>The default \"from\" address will be an email address configured based on your site's setup. And <strong>unless specifically configured to do otherwise, the message will be sent using the web server's emailer.</strong></p>\n\n<blockquote>\n <p>My host is also not handling the email for this domain, since I have\n my MX records at the registrar pointed to G-Suite.</p>\n</blockquote>\n\n<p>That's not actually a true statement. Where emails from WP are sent from/through has nothing to do with your domain's MX records. These are two totally separate things.</p>\n\n<p>Now, that being said, you <em>can</em> configure WP to utilize your external email account (in this case, G-Suite). But that's not automatic.</p>\n\n<p>There are two ways to do it. One approach is to use an SMTP plugin. There are many of these available, and a search of the wordpress.org plugin repository will yield several good possibilities.</p>\n\n<p>There are simple approaches to do it without a plugin as well. All you need to do is <a href=\"https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/\" rel=\"nofollow noreferrer\">define your email account information so that the mailer can connect to it</a>. </p>\n\n<p>So to come back around to the initial issue - \"the user is not receiving the email with the confirmation link\" - it is possible that your emails are not being sent by your host.</p>\n\n<p>(Note that when/if they are sent through an SMTP account, you generally will be able to look in your sent folder to confirm an email was sent. With your web host's email server, which undoubtedly is what is being used in this situation, you may or may not have access to the sending queue to review whether an email was sent.)</p>\n\n<p>There could be <a href=\"http://www.butlerblog.com/2013/09/24/troubleshooting-the-wp_mail-function\" rel=\"nofollow noreferrer\">a number of reasons why an email was not sent or received</a>. But configuring your setup to use your SMTP account will negate most of those possibilities and make it easier to solve other possibilities.</p>\n" }, { "answer_id": 361479, "author": "user26529", "author_id": 149520, "author_profile": "https://wordpress.stackexchange.com/users/149520", "pm_score": 0, "selected": false, "text": "<p>This was a long time ago, but I think I remember my solution being reinstalling Wordpress as a regular site instead of a multisite (it turned out that I didn't need it to be a multisite). Obviously that's doesn't get to the actual root of the problem, but just posting here in case it's useful to someone else.</p>\n" } ]
2018/09/03
[ "https://wordpress.stackexchange.com/questions/313234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146931/" ]
As the title says, I want to create a different permalink structure for posts belonging to a certain category, in my case, the name is "ICO". I've found this piece of code on StackExchange, but it doesn't really do anything for me, contrary to the OPs feedback. The code is: ``` //Rewrite URLs for "ICO" category add_filter( 'post_link', 'custom_permalink', 10, 3 ); function custom_permalink( $permalink, $post, $leavename ) { // Get the category for the post $category = get_the_category($post->ID); if ( !empty($category) && $category[0]->cat_name == "ICO" ) { $cat_name = strtolower($category[0]->cat_name); $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) ); } return $permalink; } add_action( 'init', 'custom_rewrite_rules' ); function custom_rewrite_rules() { add_rewrite_rule( 'ico/([^/]+)(?:/([0-9]+))?/?$', 'index.php?category_name=ico&name=$matches[1]&page=$matches[2]', 'top' // The rule position; either 'top' or 'bottom' (default). ); } ``` All posts from that category, present on the homepage do not have their URL changed, the default URL structure is the same www.site.com/post\_name/ However, I noticed that on some widgets, in a list with posts from that category, some of the posts have their URL changed, some do not. There isn't any difference between them, they have the same categories. Even if I go on that URL /ico/post\_name/ it works and if I delete /ico/ and go on the default permalink structure, it works as well, making it a duplicate URL for the same post. What have I done wrong? Edit: I also tried this piece of code, same effect, not working ``` add_filter( 'post_link', 'custom_permalink', 10, 3 ); function custom_permalink( $permalink, $post, $leavename ) { // Get the categories for the post $category = get_the_category($post->ID); if ( !empty($category) && $category[0]->cat_name == "ICO" ) { $cat_name = strtolower($category[0]->cat_name); $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) ); } return $permalink; } add_action('generate_rewrite_rules', 'custom_rewrite_rules'); function custom_rewrite_rules( $wp_rewrite ) { // This rule will will match the post id in %postname%-%post_id% struture $new_rules['ico/^([^/]*)/?'] = 'index.php?p=$matches[1]'; $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; return $wp_rewrite; } ```
(I know this is a late answer, so the original poster has probably moved on from this. But I am posting an answer to this in hopes that it will help later users solve their issue, should they happen along to this question.) The first step is understanding how email works in WordPress. WP will use `wp_mail()` to send messages, and this is essentially a wrapper for PHP's `mail()`. The default "from" address will be an email address configured based on your site's setup. And **unless specifically configured to do otherwise, the message will be sent using the web server's emailer.** > > My host is also not handling the email for this domain, since I have > my MX records at the registrar pointed to G-Suite. > > > That's not actually a true statement. Where emails from WP are sent from/through has nothing to do with your domain's MX records. These are two totally separate things. Now, that being said, you *can* configure WP to utilize your external email account (in this case, G-Suite). But that's not automatic. There are two ways to do it. One approach is to use an SMTP plugin. There are many of these available, and a search of the wordpress.org plugin repository will yield several good possibilities. There are simple approaches to do it without a plugin as well. All you need to do is [define your email account information so that the mailer can connect to it](https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/). So to come back around to the initial issue - "the user is not receiving the email with the confirmation link" - it is possible that your emails are not being sent by your host. (Note that when/if they are sent through an SMTP account, you generally will be able to look in your sent folder to confirm an email was sent. With your web host's email server, which undoubtedly is what is being used in this situation, you may or may not have access to the sending queue to review whether an email was sent.) There could be [a number of reasons why an email was not sent or received](http://www.butlerblog.com/2013/09/24/troubleshooting-the-wp_mail-function). But configuring your setup to use your SMTP account will negate most of those possibilities and make it easier to solve other possibilities.
313,245
<p>I've a query like this:</p> <pre><code>&lt;ul&gt; &lt;?php $the_query = new WP_Query( array( 'cat' =&gt; '1', 'posts_per_page' =&gt; 5 ) ); ?&gt; &lt;?php while ($the_query -&gt; have_posts()) : $the_query -&gt; the_post(); ?&gt; &lt;li&gt; &lt;?php if ( has_post_thumbnail()) : ?&gt; &lt;?php the_post_thumbnail(array(230,163)); ?&gt; &lt;?php endif; ?&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; &lt;/ul&gt; </code></pre> <p><a href="https://i.stack.imgur.com/pzzyV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pzzyV.png" alt="Example: https://prnt.sc/kq4nha"></a></p> <p>How can I show thumbnail the last added post?</p>
[ { "answer_id": 354491, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>(I know this is a late answer, so the original poster has probably moved on from this. But I am posting an answer to this in hopes that it will help later users solve their issue, should they happen along to this question.)</p>\n\n<p>The first step is understanding how email works in WordPress. WP will use <code>wp_mail()</code> to send messages, and this is essentially a wrapper for PHP's <code>mail()</code>.</p>\n\n<p>The default \"from\" address will be an email address configured based on your site's setup. And <strong>unless specifically configured to do otherwise, the message will be sent using the web server's emailer.</strong></p>\n\n<blockquote>\n <p>My host is also not handling the email for this domain, since I have\n my MX records at the registrar pointed to G-Suite.</p>\n</blockquote>\n\n<p>That's not actually a true statement. Where emails from WP are sent from/through has nothing to do with your domain's MX records. These are two totally separate things.</p>\n\n<p>Now, that being said, you <em>can</em> configure WP to utilize your external email account (in this case, G-Suite). But that's not automatic.</p>\n\n<p>There are two ways to do it. One approach is to use an SMTP plugin. There are many of these available, and a search of the wordpress.org plugin repository will yield several good possibilities.</p>\n\n<p>There are simple approaches to do it without a plugin as well. All you need to do is <a href=\"https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/\" rel=\"nofollow noreferrer\">define your email account information so that the mailer can connect to it</a>. </p>\n\n<p>So to come back around to the initial issue - \"the user is not receiving the email with the confirmation link\" - it is possible that your emails are not being sent by your host.</p>\n\n<p>(Note that when/if they are sent through an SMTP account, you generally will be able to look in your sent folder to confirm an email was sent. With your web host's email server, which undoubtedly is what is being used in this situation, you may or may not have access to the sending queue to review whether an email was sent.)</p>\n\n<p>There could be <a href=\"http://www.butlerblog.com/2013/09/24/troubleshooting-the-wp_mail-function\" rel=\"nofollow noreferrer\">a number of reasons why an email was not sent or received</a>. But configuring your setup to use your SMTP account will negate most of those possibilities and make it easier to solve other possibilities.</p>\n" }, { "answer_id": 361479, "author": "user26529", "author_id": 149520, "author_profile": "https://wordpress.stackexchange.com/users/149520", "pm_score": 0, "selected": false, "text": "<p>This was a long time ago, but I think I remember my solution being reinstalling Wordpress as a regular site instead of a multisite (it turned out that I didn't need it to be a multisite). Obviously that's doesn't get to the actual root of the problem, but just posting here in case it's useful to someone else.</p>\n" } ]
2018/09/03
[ "https://wordpress.stackexchange.com/questions/313245", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149891/" ]
I've a query like this: ``` <ul> <?php $the_query = new WP_Query( array( 'cat' => '1', 'posts_per_page' => 5 ) ); ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <li> <?php if ( has_post_thumbnail()) : ?> <?php the_post_thumbnail(array(230,163)); ?> <?php endif; ?> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li> <?php endwhile; wp_reset_postdata(); ?> </ul> ``` [![Example: https://prnt.sc/kq4nha](https://i.stack.imgur.com/pzzyV.png)](https://i.stack.imgur.com/pzzyV.png) How can I show thumbnail the last added post?
(I know this is a late answer, so the original poster has probably moved on from this. But I am posting an answer to this in hopes that it will help later users solve their issue, should they happen along to this question.) The first step is understanding how email works in WordPress. WP will use `wp_mail()` to send messages, and this is essentially a wrapper for PHP's `mail()`. The default "from" address will be an email address configured based on your site's setup. And **unless specifically configured to do otherwise, the message will be sent using the web server's emailer.** > > My host is also not handling the email for this domain, since I have > my MX records at the registrar pointed to G-Suite. > > > That's not actually a true statement. Where emails from WP are sent from/through has nothing to do with your domain's MX records. These are two totally separate things. Now, that being said, you *can* configure WP to utilize your external email account (in this case, G-Suite). But that's not automatic. There are two ways to do it. One approach is to use an SMTP plugin. There are many of these available, and a search of the wordpress.org plugin repository will yield several good possibilities. There are simple approaches to do it without a plugin as well. All you need to do is [define your email account information so that the mailer can connect to it](https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/). So to come back around to the initial issue - "the user is not receiving the email with the confirmation link" - it is possible that your emails are not being sent by your host. (Note that when/if they are sent through an SMTP account, you generally will be able to look in your sent folder to confirm an email was sent. With your web host's email server, which undoubtedly is what is being used in this situation, you may or may not have access to the sending queue to review whether an email was sent.) There could be [a number of reasons why an email was not sent or received](http://www.butlerblog.com/2013/09/24/troubleshooting-the-wp_mail-function). But configuring your setup to use your SMTP account will negate most of those possibilities and make it easier to solve other possibilities.
313,247
<p>I have added a custom post status of rejected, working just fine.</p> <p>I want to add the post status to the body of the post when it is being previewed. In order to style a front end information box seen by the admin.</p>
[ { "answer_id": 313248, "author": "Scott", "author_id": 111485, "author_profile": "https://wordpress.stackexchange.com/users/111485", "pm_score": 2, "selected": true, "text": "<p>You'll have to use the <code>body_class</code> hook in the <code>functions.php</code> file of your theme in combination with <code>get_post_status()</code> function. Like the following:</p>\n\n<pre><code>add_filter( 'body_class', 'custom_class' );\nfunction custom_class( $classes ) {\n if ( get_post_status() == 'rejected' ) {\n $classes[] = 'rejected';\n }\n return $classes;\n}\n</code></pre>\n" }, { "answer_id": 393052, "author": "gwc", "author_id": 130854, "author_profile": "https://wordpress.stackexchange.com/users/130854", "pm_score": 0, "selected": false, "text": "<p>This is a little late to the party, but for those who might be interested, this can be accomplished without custom code. There is a plugin in the WordPress repository called <a href=\"https://wordpress.org/plugins/wp247-body-classes/\" rel=\"nofollow noreferrer\">WP247 Body Classes</a>. You can use the <strong>Custom Classes</strong> section to add your own custom body classes. In this case, simply adding the following line of code will give you a body class called <code>is-poststat-?</code> where <code>?</code> will be the post status.</p>\n<pre><code>$classes[] = 'is-poststat-' . get_post_status();\n</code></pre>\n<p>Then you can tailor your pages using CSS and checking for <code>body.is-poststat-publish</code> or <code>body.is-poststat-rejected</code>.</p>\n<p>Hope this helps someone.</p>\n" } ]
2018/09/03
[ "https://wordpress.stackexchange.com/questions/313247", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125332/" ]
I have added a custom post status of rejected, working just fine. I want to add the post status to the body of the post when it is being previewed. In order to style a front end information box seen by the admin.
You'll have to use the `body_class` hook in the `functions.php` file of your theme in combination with `get_post_status()` function. Like the following: ``` add_filter( 'body_class', 'custom_class' ); function custom_class( $classes ) { if ( get_post_status() == 'rejected' ) { $classes[] = 'rejected'; } return $classes; } ```
313,290
<p>I'd like to enable this plugin <a href="https://responsivevoice.com/wordpress-text-to-speech-plugin/" rel="nofollow noreferrer">https://responsivevoice.com/wordpress-text-to-speech-plugin/</a> as default for every article's body in my wordpress site.</p> <p>I need to edit my article template and the final result should be </p> <pre><code>[responsivevoice voice="UK English Female" buttontext="Listen to this"] The body article [/responsivevoice] </code></pre> <p>Do you have some hints? Thanks!</p>
[ { "answer_id": 313307, "author": "SmurfXXX", "author_id": 149929, "author_profile": "https://wordpress.stackexchange.com/users/149929", "pm_score": 1, "selected": false, "text": "<p>Thanks to @kero I have implemented this code:</p>\n\n<pre><code>&lt;?php echo do_shortcode('[responsivevoice voice=\"Italian Female\" buttontext=\"Ascolta\"]'.'&lt;br&gt;'.$bodyContent.'[/responsivevoice]'); ?&gt;\n</code></pre>\n\n<p>The $bodyContent variable contains the HTML value of the article's body, obtained using this function: <a href=\"http://www.web-templates.nu/2008/08/31/get_the_content-with-formatting/index.html\" rel=\"nofollow noreferrer\">http://www.web-templates.nu/2008/08/31/get_the_content-with-formatting/index.html</a></p>\n\n<pre><code>&lt;?php $bodyContent = get_the_content_with_formatting(); ?&gt;\n</code></pre>\n" }, { "answer_id": 313314, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>According to the link you posted, just using the shortcode <code>[responsivevoice_button]</code> will add a button that speaks all the content. You shouldn't need to wrap it with a shortcode.</p>\n\n<p>Their example (emphasis mine):</p>\n\n<blockquote>\n <p>Add this shortcode to your page or post to speak the <strong>entire page</strong></p>\n\n<pre><code>[responsivevoice_button voice=\"UK English Female\" buttontext=\"Listen to Post\"]\n</code></pre>\n</blockquote>\n" } ]
2018/09/04
[ "https://wordpress.stackexchange.com/questions/313290", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149929/" ]
I'd like to enable this plugin <https://responsivevoice.com/wordpress-text-to-speech-plugin/> as default for every article's body in my wordpress site. I need to edit my article template and the final result should be ``` [responsivevoice voice="UK English Female" buttontext="Listen to this"] The body article [/responsivevoice] ``` Do you have some hints? Thanks!
Thanks to @kero I have implemented this code: ``` <?php echo do_shortcode('[responsivevoice voice="Italian Female" buttontext="Ascolta"]'.'<br>'.$bodyContent.'[/responsivevoice]'); ?> ``` The $bodyContent variable contains the HTML value of the article's body, obtained using this function: <http://www.web-templates.nu/2008/08/31/get_the_content-with-formatting/index.html> ``` <?php $bodyContent = get_the_content_with_formatting(); ?> ```
313,294
<p>I've setup the multisite on a fresh installation of WordPress.</p> <p>Then I created some other websites, so, in the end, I have something like this</p> <ul> <li><a href="http://example.com" rel="nofollow noreferrer">http://example.com</a></li> <li><a href="http://site1.example.com" rel="nofollow noreferrer">http://site1.example.com</a></li> <li><a href="http://site2.example.com" rel="nofollow noreferrer">http://site2.example.com</a></li> <li><a href="http://site3.example.com" rel="nofollow noreferrer">http://site3.example.com</a></li> </ul> <p>I have then installed an SSL digital certificate, so I changed the URLs of the websites to match the HTTPS scheme:</p> <ul> <li><a href="http://example.com" rel="nofollow noreferrer">http://example.com</a></li> <li></li> <li></li> <li></li> </ul> <p>To change the scheme I gone to <code>Sites &gt; All Sites</code>, then clicked on each site and in tab "Information" (the first one) I simply changed the scheme and saved.</p> <p>This worked.</p> <p><strong>The only site left without the <code>https</code> is <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>: for this, in fact, I have cannot change the URL.</strong></p> <p>If I go to <code>Sites &gt; All Sites</code> and click on it, in fact, in the first tab "Information" the URL is not editable and is in the form <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>, without the https scheme.</p> <p>How can I change it?</p> <p>I'd like to change it now, before I start to install plugins and write articles.</p> <p>Any suggestions?</p>
[ { "answer_id": 313384, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 2, "selected": true, "text": "<p>I would suggest editing the <code>wp-config.php</code> file, and adding:</p>\n\n<pre><code>define('WP_HOME','https://example.com');\ndefine('WP_SITEURL','https://example.com');\n</code></pre>\n\n<p><strong>However for multisite</strong> <a href=\"https://codex.wordpress.org/Moving_WordPress#Moving_WordPress_Multisite\" rel=\"nofollow noreferrer\">here</a> it says you should edit <code>DOMAIN_CURRENT_SITE</code> and <code>PATH_CURRENT_SITE</code>, if there is such thing defined in a multisite wp-config.</p>\n\n<p>First suggestion is based on this <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">article</a>.</p>\n" }, { "answer_id": 355888, "author": "Jesus Camarena", "author_id": 180706, "author_profile": "https://wordpress.stackexchange.com/users/180706", "pm_score": 2, "selected": false, "text": "<p>I would just:</p>\n<ol>\n<li>Comment out the multisite code in wp-config.php</li>\n<li>Login again to WP</li>\n<li>Go back to settings and reading as if a single site.</li>\n<li>change http to https</li>\n<li>uncomment multisite code in wp-config.php</li>\n<li>Proceed as normal</li>\n</ol>\n<p>Done</p>\n" }, { "answer_id": 382467, "author": "Mark Vickers", "author_id": 151218, "author_profile": "https://wordpress.stackexchange.com/users/151218", "pm_score": 0, "selected": false, "text": "<p>It worked for me!</p>\n<p>In fact, I just had to temporarily change:</p>\n<pre><code>define('MULTISITE', true);\n</code></pre>\n<p>to</p>\n<pre><code>define('MULTISITE', false);\n</code></pre>\n" }, { "answer_id": 397594, "author": "Stef Williams", "author_id": 83756, "author_profile": "https://wordpress.stackexchange.com/users/83756", "pm_score": 1, "selected": false, "text": "<p>It seems some updates to WP core have improved things.\nI had a warning in Site Health, saying that the site wasn't configured to use HTTPS.\n'Click here to fix it' it said. So I did, and now the site uses https.\nYour mileage may vary but it's by far the easiest thing to try first.</p>\n" } ]
2018/09/04
[ "https://wordpress.stackexchange.com/questions/313294", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57145/" ]
I've setup the multisite on a fresh installation of WordPress. Then I created some other websites, so, in the end, I have something like this * <http://example.com> * <http://site1.example.com> * <http://site2.example.com> * <http://site3.example.com> I have then installed an SSL digital certificate, so I changed the URLs of the websites to match the HTTPS scheme: * <http://example.com> * * * To change the scheme I gone to `Sites > All Sites`, then clicked on each site and in tab "Information" (the first one) I simply changed the scheme and saved. This worked. **The only site left without the `https` is <http://example.com>: for this, in fact, I have cannot change the URL.** If I go to `Sites > All Sites` and click on it, in fact, in the first tab "Information" the URL is not editable and is in the form <http://example.com>, without the https scheme. How can I change it? I'd like to change it now, before I start to install plugins and write articles. Any suggestions?
I would suggest editing the `wp-config.php` file, and adding: ``` define('WP_HOME','https://example.com'); define('WP_SITEURL','https://example.com'); ``` **However for multisite** [here](https://codex.wordpress.org/Moving_WordPress#Moving_WordPress_Multisite) it says you should edit `DOMAIN_CURRENT_SITE` and `PATH_CURRENT_SITE`, if there is such thing defined in a multisite wp-config. First suggestion is based on this [article](https://codex.wordpress.org/Changing_The_Site_URL).
313,419
<p>I'd like to get it so that all of my sites have a different color admin bar. Dev Staging and Production. I use Git to push my code.</p> <p>Any help would be appreciated.</p>
[ { "answer_id": 313420, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You can use a filter to set the admin color scheme, which includes colors for the admin bar:</p>\n\n<pre><code>&lt;?php // add a filter\nadd_filter('get_user_option_admin_color', 'wpse_313419_conditional_admin_color');\n// \nfunction wpse_313419_conditional_admin_color($result) {\n // Dev: use 'light' color scheme\n if(get_site_url() == 'http://dev.example.com') {\n return 'light';\n // Staging: use 'blue' color scheme\n } elseif(get_site_url() == 'http://staging.example.com') {\n return 'blue';\n // Production (all other cases): use 'sunrise' color scheme\n } else {\n return 'sunrise';\n }\n} ?&gt;\n</code></pre>\n\n<p>You can see the 8 built-in color schemes by editing a user's profile and viewing the \"Admin Color Scheme\" options at the top. You just use them as all-lowercase. The filter overrides any individual users' preferences and enforces the color scheme of your choice. If you like, you can also create your own custom color schemes.</p>\n\n<p>If your Site URLs change often, you could take an additional step - when the theme is activated, save the environment as an Option, and then you can pull it using <code>get_option</code> instead of <code>get_site_url</code>.</p>\n\n<p>Finally, if you want to just use a plugin to handle all this for you, there is at least one ready-made solution in the WP plugin repository.</p>\n" }, { "answer_id": 313709, "author": "MikeSchinkel", "author_id": 89, "author_profile": "https://wordpress.stackexchange.com/users/89", "pm_score": 1, "selected": false, "text": "<p>Fortunately the solution you want is actually quite simple. Just use the <code>'wp_before_admin_bar_render'</code> action hook and output CSS to change the <code>color</code> and <code>background</code> of the HTML element with the <code>id</code> of <code>wpadminbar</code>.</p>\n\n<p>Below is a bit of code you can save into a file in your theme and <code>require()</code> from your theme's <code>functions.php</code> file, add a plugin header and use as a plugin, add to an existing plugin and <code>require()</code> it, or simply copy into <code>/mu-plugins</code> and WordPress will load it automatically. </p>\n\n<p>But be sure to modify the <code>_get_color_pair()</code> function to return a different color pair depending on which host is doing the loading:</p>\n\n<pre><code>&lt;?php\n\nclass WPSE_313419 {\n static function on_load() {\n add_action(\n 'wp_before_admin_bar_render',\n [ __CLASS__, '_wp_before_admin_bar_render_99' ],\n 99\n );\n }\n\n static function _wp_before_admin_bar_render_99() {\n $color_pair = self::_get_color_pair();\n $html = &lt;&lt;&lt;HTML\n&lt;style type=\"text/css\"&gt;\n #wpadminbar{color:{$color_pair-&gt;color};background:{$color_pair-&gt;background};}\n&lt;/style&gt;\nHTML;\n echo $html;\n }\n\n /**\n * Modify this function to return the colors you want\n * based on the value of get_site_url() or based on\n * a constant defined in each host's /wp-config.php.\n *\n * @return object\n */\n private static function _get_color_pair() {\n return (object)array(\n 'color' =&gt; 'white',\n 'background' =&gt; 'red',\n );\n }\n}\nWPSE_313419::on_load();\n</code></pre>\n\n<p>Any questions? Just ask.</p>\n\n<p>Hope this helps. </p>\n\n<p>-Mike</p>\n" } ]
2018/09/05
[ "https://wordpress.stackexchange.com/questions/313419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65294/" ]
I'd like to get it so that all of my sites have a different color admin bar. Dev Staging and Production. I use Git to push my code. Any help would be appreciated.
You can use a filter to set the admin color scheme, which includes colors for the admin bar: ``` <?php // add a filter add_filter('get_user_option_admin_color', 'wpse_313419_conditional_admin_color'); // function wpse_313419_conditional_admin_color($result) { // Dev: use 'light' color scheme if(get_site_url() == 'http://dev.example.com') { return 'light'; // Staging: use 'blue' color scheme } elseif(get_site_url() == 'http://staging.example.com') { return 'blue'; // Production (all other cases): use 'sunrise' color scheme } else { return 'sunrise'; } } ?> ``` You can see the 8 built-in color schemes by editing a user's profile and viewing the "Admin Color Scheme" options at the top. You just use them as all-lowercase. The filter overrides any individual users' preferences and enforces the color scheme of your choice. If you like, you can also create your own custom color schemes. If your Site URLs change often, you could take an additional step - when the theme is activated, save the environment as an Option, and then you can pull it using `get_option` instead of `get_site_url`. Finally, if you want to just use a plugin to handle all this for you, there is at least one ready-made solution in the WP plugin repository.
313,424
<p>I have setup wordpress on my server, and after some time I've changed the domain name of the installation. However, all of the old urls within the site point to the old domain. <strong>How can I change old urls to match the new domain without breaking the database?</strong></p> <p>Here's what I did: I went to settings -> general I've changed the <code>site url</code> and <code>wordpress address (url)</code>.</p> <p>The directory in which the wordpress installation is residing stayed the same.</p> <p>How do I change all the old link? I was recommended using the UpdraftPlus migration feature, but I don't see how would this affect the old links. I'd use <code>wp search-replace</code> i.e. wp cli, but I'm not sure if that tool will change all GUIDs (I've read that GUID should not be changed, but I'm not sure if I need to).</p> <p><strong>For future visitors:</strong> I've resolved the issue using wp-cli:</p> <pre><code>wp search-replace 'example.net' 'example.com' --skip-columns=guid </code></pre> <p>Use <code>--dry-run</code> for the sake of your sanity.</p>
[ { "answer_id": 313426, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>You could use CLI. No reason to have any references to the old domain.</p>\n\n<p>Another option I recommend is using Search &amp; Replace DB, a free tool by Interconnect, to replace any instances of the host name in the database. It will handle setting the serialized data correctly for you.</p>\n\n<p>First make sure that your wp-config is for the right database.</p>\n\n<p>You need to go into your new database and change the site url and home url to the new address. I suggest NOT doing this through phpmyadmin though as it will cause some problems.</p>\n\n<p>Go get this tool: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a></p>\n\n<p>Upload it into your www/ folder. (I usually rename the search and replace folder to SRDB.)</p>\n\n<p>now navigate to your site with the SRDB at the end. (www.example.com/SRDB)and the top two lines you'll see a search field and a replace field. (if you get a db connection error here, double check the wp-config to ensure that it has the right credentials). </p>\n\n<p>In the search place your old site address.</p>\n\n<p>in the replace field place your new url.</p>\n\n<p>hit live live run.</p>\n\n<p>ONLY do this after ensuring you're on your new url and that SRDB is loaded into your new database.</p>\n\n<p>Remove the SRDB folder when you are done.</p>\n" }, { "answer_id": 313432, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>The plugin I use to change URLs in the WP database is \"Better Search and Replace\" - has worked for me each time, and is easy to use. <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a></p>\n\n<p>You can do it manually in phpMyAdmin or the CLI, but that can be more difficult to do right. </p>\n\n<p>Backup your database first, though, no matter which method you use.</p>\n" }, { "answer_id": 313433, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 3, "selected": true, "text": "<p>Two possible easy ways to replace Old website URL to New Website URL:</p>\n\n<p><strong>1/ Directly replace in SQL file:</strong>\nExport the database and open SQL file. Manually find and replace old website URL with new website URL. Once replace is done, save and import database again.</p>\n\n<p><strong>2/ Use Migrate DB plugin:</strong>\nUse the third-party WordPress plugin '<strong>WP Migrate DB</strong>' and find &amp; replace both website URL and file path as shown in below screenshot. You can also replace other website data like admin email using this plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-migrate-db/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/lNxnp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lNxnp.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/09/05
[ "https://wordpress.stackexchange.com/questions/313424", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140043/" ]
I have setup wordpress on my server, and after some time I've changed the domain name of the installation. However, all of the old urls within the site point to the old domain. **How can I change old urls to match the new domain without breaking the database?** Here's what I did: I went to settings -> general I've changed the `site url` and `wordpress address (url)`. The directory in which the wordpress installation is residing stayed the same. How do I change all the old link? I was recommended using the UpdraftPlus migration feature, but I don't see how would this affect the old links. I'd use `wp search-replace` i.e. wp cli, but I'm not sure if that tool will change all GUIDs (I've read that GUID should not be changed, but I'm not sure if I need to). **For future visitors:** I've resolved the issue using wp-cli: ``` wp search-replace 'example.net' 'example.com' --skip-columns=guid ``` Use `--dry-run` for the sake of your sanity.
Two possible easy ways to replace Old website URL to New Website URL: **1/ Directly replace in SQL file:** Export the database and open SQL file. Manually find and replace old website URL with new website URL. Once replace is done, save and import database again. **2/ Use Migrate DB plugin:** Use the third-party WordPress plugin '**WP Migrate DB**' and find & replace both website URL and file path as shown in below screenshot. You can also replace other website data like admin email using this plugin. <https://wordpress.org/plugins/wp-migrate-db/> [![enter image description here](https://i.stack.imgur.com/lNxnp.jpg)](https://i.stack.imgur.com/lNxnp.jpg)
313,442
<p>I am having a search result page for custom post type. I want to have a ajax sorting feature. Eg sort the post by taxonomy without reloading the page. A very basic example will help. Thanks <a href="https://i.stack.imgur.com/gdk1Y.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gdk1Y.jpg" alt="enter image description here"></a></p> <p>The Search Form :</p> <pre><code>&lt;form id="cptsearch" action="/" method="get"&gt; &lt;input type="text" name="s" /&gt; &lt;input type="hidden" name="post_type" value="lat" /&gt; &lt;input id="searchsubmit" type="submit" alt="Search" value="Search" /&gt; &lt;/form&gt; </code></pre> <p>Template Chooser :</p> <pre><code>function template_chooser($template) { global $wp_query; $post_type = get_query_var('post_type'); if( $wp_query-&gt;is_search &amp;&amp; $post_type == 'lat' ) { return locate_template('page_lat.php'); } return $template; } add_filter('template_include', 'template_chooser'); </code></pre> <p><strong>This is the output template page_lat.php</strong> : </p> <p>Search Results (Currently only prints title and post type : </p> <pre><code>if($_GET['s'] &amp;&amp; !empty($_GET['s'])){ $text =$_GET['s']; } ?&gt; &lt;div class="container"&gt; &lt;?php $args = array( 'post_per_page'=&gt; -1, 's'=&gt;$text ); $query= new WP_Query($args); while($query-&gt;have_posts()): $query-&gt;the_post(); ?&gt; &lt;div&gt; &lt;h5&gt;&lt;?php the_title(); ?&gt;&lt;/h5&gt; &lt;strong&gt; &lt;?php echo get_post_type(); ?&gt; &lt;/strong&gt; &lt;/div&gt; &lt;?php endwhile; wp_reset_query(); ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 313426, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>You could use CLI. No reason to have any references to the old domain.</p>\n\n<p>Another option I recommend is using Search &amp; Replace DB, a free tool by Interconnect, to replace any instances of the host name in the database. It will handle setting the serialized data correctly for you.</p>\n\n<p>First make sure that your wp-config is for the right database.</p>\n\n<p>You need to go into your new database and change the site url and home url to the new address. I suggest NOT doing this through phpmyadmin though as it will cause some problems.</p>\n\n<p>Go get this tool: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a></p>\n\n<p>Upload it into your www/ folder. (I usually rename the search and replace folder to SRDB.)</p>\n\n<p>now navigate to your site with the SRDB at the end. (www.example.com/SRDB)and the top two lines you'll see a search field and a replace field. (if you get a db connection error here, double check the wp-config to ensure that it has the right credentials). </p>\n\n<p>In the search place your old site address.</p>\n\n<p>in the replace field place your new url.</p>\n\n<p>hit live live run.</p>\n\n<p>ONLY do this after ensuring you're on your new url and that SRDB is loaded into your new database.</p>\n\n<p>Remove the SRDB folder when you are done.</p>\n" }, { "answer_id": 313432, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>The plugin I use to change URLs in the WP database is \"Better Search and Replace\" - has worked for me each time, and is easy to use. <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/better-search-replace/</a></p>\n\n<p>You can do it manually in phpMyAdmin or the CLI, but that can be more difficult to do right. </p>\n\n<p>Backup your database first, though, no matter which method you use.</p>\n" }, { "answer_id": 313433, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 3, "selected": true, "text": "<p>Two possible easy ways to replace Old website URL to New Website URL:</p>\n\n<p><strong>1/ Directly replace in SQL file:</strong>\nExport the database and open SQL file. Manually find and replace old website URL with new website URL. Once replace is done, save and import database again.</p>\n\n<p><strong>2/ Use Migrate DB plugin:</strong>\nUse the third-party WordPress plugin '<strong>WP Migrate DB</strong>' and find &amp; replace both website URL and file path as shown in below screenshot. You can also replace other website data like admin email using this plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-migrate-db/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/lNxnp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lNxnp.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/09/05
[ "https://wordpress.stackexchange.com/questions/313442", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am having a search result page for custom post type. I want to have a ajax sorting feature. Eg sort the post by taxonomy without reloading the page. A very basic example will help. Thanks [![enter image description here](https://i.stack.imgur.com/gdk1Y.jpg)](https://i.stack.imgur.com/gdk1Y.jpg) The Search Form : ``` <form id="cptsearch" action="/" method="get"> <input type="text" name="s" /> <input type="hidden" name="post_type" value="lat" /> <input id="searchsubmit" type="submit" alt="Search" value="Search" /> </form> ``` Template Chooser : ``` function template_chooser($template) { global $wp_query; $post_type = get_query_var('post_type'); if( $wp_query->is_search && $post_type == 'lat' ) { return locate_template('page_lat.php'); } return $template; } add_filter('template_include', 'template_chooser'); ``` **This is the output template page\_lat.php** : Search Results (Currently only prints title and post type : ``` if($_GET['s'] && !empty($_GET['s'])){ $text =$_GET['s']; } ?> <div class="container"> <?php $args = array( 'post_per_page'=> -1, 's'=>$text ); $query= new WP_Query($args); while($query->have_posts()): $query->the_post(); ?> <div> <h5><?php the_title(); ?></h5> <strong> <?php echo get_post_type(); ?> </strong> </div> <?php endwhile; wp_reset_query(); ?> </div> ```
Two possible easy ways to replace Old website URL to New Website URL: **1/ Directly replace in SQL file:** Export the database and open SQL file. Manually find and replace old website URL with new website URL. Once replace is done, save and import database again. **2/ Use Migrate DB plugin:** Use the third-party WordPress plugin '**WP Migrate DB**' and find & replace both website URL and file path as shown in below screenshot. You can also replace other website data like admin email using this plugin. <https://wordpress.org/plugins/wp-migrate-db/> [![enter image description here](https://i.stack.imgur.com/lNxnp.jpg)](https://i.stack.imgur.com/lNxnp.jpg)
313,453
<p>I want to display list of custom taxonomies as a dropdown list.</p> <p>I've found the solution here, @alexufo 's answer</p> <p><a href="https://wordpress.stackexchange.com/questions/50077/display-a-custom-taxonomy-as-a-dropdown-on-the-edit-posts-page/148965#148965">Display a custom taxonomy as a dropdown on the edit posts page</a></p> <p>But the problem with that is that when i publish the post with selected taxonomy it creates another taxonomy automatically. </p> <p>I can't comment on his answer as i don't have 50 reputation. </p> <p>here's my code</p> <pre><code>function realty_type() { $args = array( 'show_ui' =&gt; true, 'meta_box_cb' =&gt; 'drop_cat', ); register_taxonomy( 'realty_type', array( 'my-CPT' ), $args ); } // Hook into the 'init' action add_action( 'init', 'realty_type', 0 ); function drop_cat( $post, $box ) { $defaults = array('taxonomy' =&gt; 'category'); if ( !isset($box['args']) || !is_array($box['args']) ) $args = array(); else $args = $box['args']; extract( wp_parse_args($args, $defaults), EXTR_SKIP ); $tax = get_taxonomy($taxonomy); ?&gt; &lt;div id="taxonomy-&lt;?php echo $taxonomy; ?&gt;" class="acf-taxonomy-field categorydiv"&gt; &lt;?php $name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']'; echo "&lt;input type='hidden' name='{$name}[]' value='0' /&gt;"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks. ?&gt; &lt;? $term_obj = wp_get_object_terms($post-&gt;ID, $taxonomy ); //_log($term_obj[0]-&gt;term_id)?&gt; &lt;ul id="&lt;?php echo $taxonomy; ?&gt;checklist" data-wp-lists="list:&lt;?php echo $taxonomy?&gt;" class="categorychecklist form-no-clear"&gt; &lt;?php //wp_terms_checklist($post-&gt;ID, array( 'taxonomy' =&gt; $taxonomy) ) ?&gt; &lt;/ul&gt; &lt;?php wp_dropdown_categories( array( 'taxonomy' =&gt; $taxonomy, 'hide_empty' =&gt; 0, 'name' =&gt; "{$name}[]", 'selected' =&gt; $term_obj[0]-&gt;term_id, 'orderby' =&gt; 'name', 'hierarchical' =&gt; 0, 'show_option_none' =&gt; '&amp;mdash;' ) ); ?&gt; &lt;/div&gt; &lt;?php } </code></pre>
[ { "answer_id": 313468, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 2, "selected": false, "text": "<p>Below is the easiest solution I use for displaying custom taxonomy as the dropdown instead of checkboxes.</p>\n\n<p>1/ Use third party WordPress plugin 'ACF' to create the taxonomy 'Relational' field type and display it as dropdown as shown in below screenshot.</p>\n\n<p><a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/advanced-custom-fields/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/IJmzN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IJmzN.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Y44qr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y44qr.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>For displaying taxonomy selected you can refer documentation of ACF for relational taxonomy field type.</p>\n\n<p><a href=\"https://www.advancedcustomfields.com/resources/taxonomy/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/taxonomy/</a></p>\n\n<p>2/ Hide taxonomy checkbox by simply adding 'meta_box_cb' as 'false' when registering your custom taxonomy.</p>\n\n<p>Hope this helps..!!</p>\n" }, { "answer_id": 313552, "author": "Mais_Cule", "author_id": 148290, "author_profile": "https://wordpress.stackexchange.com/users/148290", "pm_score": 2, "selected": true, "text": "<p>Finally I found the solution after some trials and error.</p>\n\n<p>In the registering taxonomy arguments, I just had to set <code>'hierarchical' =&gt; true</code> for it to stop incrementing taxonomy and keep adding taxonomy automatically.</p>\n\n<p>I'm not sure as to why that was causing the problem after going through documents, If anyone knows the reason please explain. </p>\n\n<pre><code>function realty_type() {\n\n $args = array(\n 'show_ui' =&gt; true,\n 'meta_box_cb' =&gt; 'drop_cat',\n 'hierarchical' =&gt; true\n );\n\n register_taxonomy( 'realty_type', array( 'YOUR_POST_TYPE' ), $args ); \n }\n\n // Hook into the 'init' action\n add_action( 'init', 'realty_type', 0 );\n</code></pre>\n" } ]
2018/09/05
[ "https://wordpress.stackexchange.com/questions/313453", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148290/" ]
I want to display list of custom taxonomies as a dropdown list. I've found the solution here, @alexufo 's answer [Display a custom taxonomy as a dropdown on the edit posts page](https://wordpress.stackexchange.com/questions/50077/display-a-custom-taxonomy-as-a-dropdown-on-the-edit-posts-page/148965#148965) But the problem with that is that when i publish the post with selected taxonomy it creates another taxonomy automatically. I can't comment on his answer as i don't have 50 reputation. here's my code ``` function realty_type() { $args = array( 'show_ui' => true, 'meta_box_cb' => 'drop_cat', ); register_taxonomy( 'realty_type', array( 'my-CPT' ), $args ); } // Hook into the 'init' action add_action( 'init', 'realty_type', 0 ); function drop_cat( $post, $box ) { $defaults = array('taxonomy' => 'category'); if ( !isset($box['args']) || !is_array($box['args']) ) $args = array(); else $args = $box['args']; extract( wp_parse_args($args, $defaults), EXTR_SKIP ); $tax = get_taxonomy($taxonomy); ?> <div id="taxonomy-<?php echo $taxonomy; ?>" class="acf-taxonomy-field categorydiv"> <?php $name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']'; echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks. ?> <? $term_obj = wp_get_object_terms($post->ID, $taxonomy ); //_log($term_obj[0]->term_id)?> <ul id="<?php echo $taxonomy; ?>checklist" data-wp-lists="list:<?php echo $taxonomy?>" class="categorychecklist form-no-clear"> <?php //wp_terms_checklist($post->ID, array( 'taxonomy' => $taxonomy) ) ?> </ul> <?php wp_dropdown_categories( array( 'taxonomy' => $taxonomy, 'hide_empty' => 0, 'name' => "{$name}[]", 'selected' => $term_obj[0]->term_id, 'orderby' => 'name', 'hierarchical' => 0, 'show_option_none' => '&mdash;' ) ); ?> </div> <?php } ```
Finally I found the solution after some trials and error. In the registering taxonomy arguments, I just had to set `'hierarchical' => true` for it to stop incrementing taxonomy and keep adding taxonomy automatically. I'm not sure as to why that was causing the problem after going through documents, If anyone knows the reason please explain. ``` function realty_type() { $args = array( 'show_ui' => true, 'meta_box_cb' => 'drop_cat', 'hierarchical' => true ); register_taxonomy( 'realty_type', array( 'YOUR_POST_TYPE' ), $args ); } // Hook into the 'init' action add_action( 'init', 'realty_type', 0 ); ```
313,520
<p>I am trying to get the page title to show up inside various h1, h2 and p tags that i have part of the page template - so that when the template is applied to a page it will make the current page's page title appear wherever I add a shortcode or whatever is needed to pull the page title. When I add the following i am getting a blank...</p> <p>Here's what I mean: I want "Find the best " to basically pull the page title so that if the title is video games it will display as "Find the best video games"</p> <pre><code>&lt;h1 class="btx-heading-text btx-secondary-font btx-s-text-color btx-s- text-border" style="padding-right:25%; padding-bottom:5%; letter- spacing:-2px;"&gt;&lt;span style="color: rgb(0, 0, 0);"&gt;Find the best&amp;nbsp; &lt;/span&gt;&lt;span style="color: rgb(126, 131, 142);"&gt;&lt;?php get_the_title() ? &gt;&lt;/span&gt;&lt;/h1&gt; </code></pre> <p>Currently, I only get the following "Find the best"</p>
[ { "answer_id": 313521, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p><code>get_the_title()</code> does not output anything - it's meant for being saved to a variable. Use just <code>the_title();</code> in its place - that way it will be output. :)</p>\n" }, { "answer_id": 313533, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>You could also use ...</p>\n\n<pre><code>&lt;?php echo get_the_title() ? \n&gt;&lt;/span&gt;&lt;/h1&gt;\n</code></pre>\n" } ]
2018/09/06
[ "https://wordpress.stackexchange.com/questions/313520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150112/" ]
I am trying to get the page title to show up inside various h1, h2 and p tags that i have part of the page template - so that when the template is applied to a page it will make the current page's page title appear wherever I add a shortcode or whatever is needed to pull the page title. When I add the following i am getting a blank... Here's what I mean: I want "Find the best " to basically pull the page title so that if the title is video games it will display as "Find the best video games" ``` <h1 class="btx-heading-text btx-secondary-font btx-s-text-color btx-s- text-border" style="padding-right:25%; padding-bottom:5%; letter- spacing:-2px;"><span style="color: rgb(0, 0, 0);">Find the best&nbsp; </span><span style="color: rgb(126, 131, 142);"><?php get_the_title() ? ></span></h1> ``` Currently, I only get the following "Find the best"
`get_the_title()` does not output anything - it's meant for being saved to a variable. Use just `the_title();` in its place - that way it will be output. :)
313,553
<p>I'm using the PODS WordPress Framework which is amazing.</p> <p>I created a template with one of the fields publishing the date of an event which is done through a simple 'magic tag' like this </p> <pre><code>{@date_of_event} </code></pre> <p>This publishes the date in this format: <strong>September, 15th 2018</strong></p> <p>What I need to do is change the format of the date being published into a numeric version which I can do by passing the value into <em>my own function.</em></p> <p>That would be done like this:</p> <pre><code>{@start_date,MY_FUNCTION} </code></pre> <p>So, to do this I need to create a function in my functions.php file like this:</p> <pre><code>function MY_FUNCTION ($input) { return "New Input" . $input; } </code></pre> <p>Now, the php time date format that I need is like this: </p> <pre><code>Y/m/d </code></pre> <p>So - <strong>my question</strong> - how do I insert this into the function above?</p> <p>Thanks for all help and direction on this!</p>
[ { "answer_id": 313561, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>You can use the PHP's <a href=\"http://php.net/manual/en/function.strtotime.php\" rel=\"nofollow noreferrer\"><code>strtotime()</code></a> and WordPress's <a href=\"http://developer.wordpress.org/reference/functions/date_i18n/\" rel=\"nofollow noreferrer\"><code>date_i18n()</code></a> functions:</p>\n\n<pre><code>function MY_FUNCTION( $input ) {\n // Removes commas so that we'll get the proper timestamp. Otherwise, the\n // strtotime() function would return FALSE.\n $input = str_replace( ',', '', $input );\n\n // Retrieve the UNIX timestamp of the date.\n $timestamp = @strtotime( $input );\n\n // Returns the date in *localized* format.\n return date_i18n( 'Y/m/d', $timestamp );\n}\n</code></pre>\n\n<p><code>MY_FUNCTION( 'September, 15th 2018' )</code>, for example, would give you <code>2018/09/15</code>.</p>\n" }, { "answer_id": 313566, "author": "Quasel", "author_id": 67092, "author_profile": "https://wordpress.stackexchange.com/users/67092", "pm_score": 0, "selected": false, "text": "<p>If you don't need the date in a different format somewhere else:\nit's far easier go into pods admin -> edit -> choose your pod / field </p>\n\n<p>Go into Advance Field Options fill in your Choice into \"Date format for display\"</p>\n" } ]
2018/09/07
[ "https://wordpress.stackexchange.com/questions/313553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
I'm using the PODS WordPress Framework which is amazing. I created a template with one of the fields publishing the date of an event which is done through a simple 'magic tag' like this ``` {@date_of_event} ``` This publishes the date in this format: **September, 15th 2018** What I need to do is change the format of the date being published into a numeric version which I can do by passing the value into *my own function.* That would be done like this: ``` {@start_date,MY_FUNCTION} ``` So, to do this I need to create a function in my functions.php file like this: ``` function MY_FUNCTION ($input) { return "New Input" . $input; } ``` Now, the php time date format that I need is like this: ``` Y/m/d ``` So - **my question** - how do I insert this into the function above? Thanks for all help and direction on this!
You can use the PHP's [`strtotime()`](http://php.net/manual/en/function.strtotime.php) and WordPress's [`date_i18n()`](http://developer.wordpress.org/reference/functions/date_i18n/) functions: ``` function MY_FUNCTION( $input ) { // Removes commas so that we'll get the proper timestamp. Otherwise, the // strtotime() function would return FALSE. $input = str_replace( ',', '', $input ); // Retrieve the UNIX timestamp of the date. $timestamp = @strtotime( $input ); // Returns the date in *localized* format. return date_i18n( 'Y/m/d', $timestamp ); } ``` `MY_FUNCTION( 'September, 15th 2018' )`, for example, would give you `2018/09/15`.
313,619
<p>I've inherited a theme and am trying to get my head around a plugin failure.</p> <p>There is an index.php file in the root of the theme, is that the first file wordpress will look at when it attempts to resolve the homepage or maybe it is something else? </p> <p>All files in the the root are as follows:</p> <pre><code>404.php archive-jetpack-testimonial.php archive.php assets comments.php footer.php front-page.php functions.php header-front.php header.php inc index.php page.php rtl.css screenshot.png search.php secure.php sidebar.php single.php style.css style.css.map template--standard.php </code></pre> <p>With which file does wordpress begin?</p>
[ { "answer_id": 313625, "author": "Andy P", "author_id": 150184, "author_profile": "https://wordpress.stackexchange.com/users/150184", "pm_score": 4, "selected": true, "text": "<p>If it's the home page, WordPress will look for the following files in this order and use the first one it finds:</p>\n\n<pre><code>1. front-page.php\n2. home.php\n3. index.php\n</code></pre>\n\n<p>WordPress template hierarchy is described in detail here:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n\n<blockquote>\n <p>This article explains how WordPress determines which template file(s) to use on individual pages. If you want to customize an existing WordPress theme it will help you decide which template file needs to be edited.</p>\n</blockquote>\n" }, { "answer_id": 406683, "author": "deepyes02", "author_id": 223072, "author_profile": "https://wordpress.stackexchange.com/users/223072", "pm_score": 0, "selected": false, "text": "<p>I think the more logical path is this:</p>\n<ol>\n<li>style.css</li>\n<li>functions.php</li>\n<li>index.php</li>\n</ol>\n" } ]
2018/09/07
[ "https://wordpress.stackexchange.com/questions/313619", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71456/" ]
I've inherited a theme and am trying to get my head around a plugin failure. There is an index.php file in the root of the theme, is that the first file wordpress will look at when it attempts to resolve the homepage or maybe it is something else? All files in the the root are as follows: ``` 404.php archive-jetpack-testimonial.php archive.php assets comments.php footer.php front-page.php functions.php header-front.php header.php inc index.php page.php rtl.css screenshot.png search.php secure.php sidebar.php single.php style.css style.css.map template--standard.php ``` With which file does wordpress begin?
If it's the home page, WordPress will look for the following files in this order and use the first one it finds: ``` 1. front-page.php 2. home.php 3. index.php ``` WordPress template hierarchy is described in detail here: <https://developer.wordpress.org/themes/basics/template-hierarchy/> > > This article explains how WordPress determines which template file(s) to use on individual pages. If you want to customize an existing WordPress theme it will help you decide which template file needs to be edited. > > >
313,630
<p>I am following this <a href="https://codex.wordpress.org/Function_Reference/register_taxonomy" rel="nofollow noreferrer">link</a> and copy pasted the below code in my functions.php file</p> <pre><code>&lt;?php // hook into the init action and call create_book_taxonomies when it fires add_action( 'init', 'create_book_taxonomies' ); // create two taxonomies, genres and writers for the post type "book" function create_book_taxonomies() { // Add new taxonomy, make it hierarchical (like categories) $labels = array( 'name' =&gt; _x( 'Genres', 'taxonomy general name', 'textdomain' ), 'singular_name' =&gt; _x( 'Genre', 'taxonomy singular name', 'textdomain' ), 'search_items' =&gt; __( 'Search Genres', 'textdomain' ), 'all_items' =&gt; __( 'All Genres', 'textdomain' ), 'parent_item' =&gt; __( 'Parent Genre', 'textdomain' ), 'parent_item_colon' =&gt; __( 'Parent Genre:', 'textdomain' ), 'edit_item' =&gt; __( 'Edit Genre', 'textdomain' ), 'update_item' =&gt; __( 'Update Genre', 'textdomain' ), 'add_new_item' =&gt; __( 'Add New Genre', 'textdomain' ), 'new_item_name' =&gt; __( 'New Genre Name', 'textdomain' ), 'menu_name' =&gt; __( 'Genre', 'textdomain' ), ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'genre' ), ); register_taxonomy( 'genre', array( 'book' ), $args ); // Add new taxonomy, NOT hierarchical (like tags) $labels = array( 'name' =&gt; _x( 'Writers', 'taxonomy general name', 'textdomain' ), 'singular_name' =&gt; _x( 'Writer', 'taxonomy singular name', 'textdomain' ), 'search_items' =&gt; __( 'Search Writers', 'textdomain' ), 'popular_items' =&gt; __( 'Popular Writers', 'textdomain' ), 'all_items' =&gt; __( 'All Writers', 'textdomain' ), 'parent_item' =&gt; null, 'parent_item_colon' =&gt; null, 'edit_item' =&gt; __( 'Edit Writer', 'textdomain' ), 'update_item' =&gt; __( 'Update Writer', 'textdomain' ), 'add_new_item' =&gt; __( 'Add New Writer', 'textdomain' ), 'new_item_name' =&gt; __( 'New Writer Name', 'textdomain' ), 'separate_items_with_commas' =&gt; __( 'Separate writers with commas', 'textdomain' ), 'add_or_remove_items' =&gt; __( 'Add or remove writers', 'textdomain' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used writers', 'textdomain' ), 'not_found' =&gt; __( 'No writers found.', 'textdomain' ), 'menu_name' =&gt; __( 'Writers', 'textdomain' ), ); $args = array( 'hierarchical' =&gt; false, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'writer' ), ); register_taxonomy( 'writer', 'book', $args ); } ?&gt; </code></pre> <p>But i dont see the taxonomy created in my wp-admin panel. I am on version 4.9.8 Is there anything i am missing out.</p> <p><strong>EDIT 1</strong> I copy pasted the code and still i do not see any taxonomy. In my understanding the init function is not called...</p> <p>For example I tried an echo before and after the function</p> <pre><code>function wpdocs_codex_book_init() { echo "&lt;h1&gt;Book&lt;/h1&gt;"; //I dont see the Book text in h1 tags in admin panel echo "&lt;h1&gt;Book&lt;/h1&gt;"; //I see the Book text in h1 tags in admin panel function wpdocs_codex_book_init() { </code></pre>
[ { "answer_id": 313625, "author": "Andy P", "author_id": 150184, "author_profile": "https://wordpress.stackexchange.com/users/150184", "pm_score": 4, "selected": true, "text": "<p>If it's the home page, WordPress will look for the following files in this order and use the first one it finds:</p>\n\n<pre><code>1. front-page.php\n2. home.php\n3. index.php\n</code></pre>\n\n<p>WordPress template hierarchy is described in detail here:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n\n<blockquote>\n <p>This article explains how WordPress determines which template file(s) to use on individual pages. If you want to customize an existing WordPress theme it will help you decide which template file needs to be edited.</p>\n</blockquote>\n" }, { "answer_id": 406683, "author": "deepyes02", "author_id": 223072, "author_profile": "https://wordpress.stackexchange.com/users/223072", "pm_score": 0, "selected": false, "text": "<p>I think the more logical path is this:</p>\n<ol>\n<li>style.css</li>\n<li>functions.php</li>\n<li>index.php</li>\n</ol>\n" } ]
2018/09/07
[ "https://wordpress.stackexchange.com/questions/313630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131473/" ]
I am following this [link](https://codex.wordpress.org/Function_Reference/register_taxonomy) and copy pasted the below code in my functions.php file ``` <?php // hook into the init action and call create_book_taxonomies when it fires add_action( 'init', 'create_book_taxonomies' ); // create two taxonomies, genres and writers for the post type "book" function create_book_taxonomies() { // Add new taxonomy, make it hierarchical (like categories) $labels = array( 'name' => _x( 'Genres', 'taxonomy general name', 'textdomain' ), 'singular_name' => _x( 'Genre', 'taxonomy singular name', 'textdomain' ), 'search_items' => __( 'Search Genres', 'textdomain' ), 'all_items' => __( 'All Genres', 'textdomain' ), 'parent_item' => __( 'Parent Genre', 'textdomain' ), 'parent_item_colon' => __( 'Parent Genre:', 'textdomain' ), 'edit_item' => __( 'Edit Genre', 'textdomain' ), 'update_item' => __( 'Update Genre', 'textdomain' ), 'add_new_item' => __( 'Add New Genre', 'textdomain' ), 'new_item_name' => __( 'New Genre Name', 'textdomain' ), 'menu_name' => __( 'Genre', 'textdomain' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'genre' ), ); register_taxonomy( 'genre', array( 'book' ), $args ); // Add new taxonomy, NOT hierarchical (like tags) $labels = array( 'name' => _x( 'Writers', 'taxonomy general name', 'textdomain' ), 'singular_name' => _x( 'Writer', 'taxonomy singular name', 'textdomain' ), 'search_items' => __( 'Search Writers', 'textdomain' ), 'popular_items' => __( 'Popular Writers', 'textdomain' ), 'all_items' => __( 'All Writers', 'textdomain' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Writer', 'textdomain' ), 'update_item' => __( 'Update Writer', 'textdomain' ), 'add_new_item' => __( 'Add New Writer', 'textdomain' ), 'new_item_name' => __( 'New Writer Name', 'textdomain' ), 'separate_items_with_commas' => __( 'Separate writers with commas', 'textdomain' ), 'add_or_remove_items' => __( 'Add or remove writers', 'textdomain' ), 'choose_from_most_used' => __( 'Choose from the most used writers', 'textdomain' ), 'not_found' => __( 'No writers found.', 'textdomain' ), 'menu_name' => __( 'Writers', 'textdomain' ), ); $args = array( 'hierarchical' => false, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'update_count_callback' => '_update_post_term_count', 'query_var' => true, 'rewrite' => array( 'slug' => 'writer' ), ); register_taxonomy( 'writer', 'book', $args ); } ?> ``` But i dont see the taxonomy created in my wp-admin panel. I am on version 4.9.8 Is there anything i am missing out. **EDIT 1** I copy pasted the code and still i do not see any taxonomy. In my understanding the init function is not called... For example I tried an echo before and after the function ``` function wpdocs_codex_book_init() { echo "<h1>Book</h1>"; //I dont see the Book text in h1 tags in admin panel echo "<h1>Book</h1>"; //I see the Book text in h1 tags in admin panel function wpdocs_codex_book_init() { ```
If it's the home page, WordPress will look for the following files in this order and use the first one it finds: ``` 1. front-page.php 2. home.php 3. index.php ``` WordPress template hierarchy is described in detail here: <https://developer.wordpress.org/themes/basics/template-hierarchy/> > > This article explains how WordPress determines which template file(s) to use on individual pages. If you want to customize an existing WordPress theme it will help you decide which template file needs to be edited. > > >
313,663
<p>For the default taxonomy i.e category , I want custom permalinks with </p> <pre><code>i) base = "post/c" and ii) without any parent slug </code></pre> <p>For eg: if I have categories </p> <pre><code>cat-a subcat-a1 subcat-a2 cat-b subcat-a2 subcat-a2 </code></pre> <p>so I want permalinks like </p> <p>example.com/post/c/cat-a example.com/post/c/subcat-a1 example.com/post/c/subcat-a2 example.com/post/c/cat-b example.com/post/c/subcat-b1 example.com/post/c/subcat-b2</p> <p>I am using the following code .. I solves the issue (ii) but not issue (i) i.e base 'post/c'</p> <pre><code>add_filter('term_link', 'ojasya_no_term_parents', 1000, 3); function ojasya_no_term_parents($url, $term, $taxonomy) { if($taxonomy == 'category'){ $term_nicename = $term-&gt;slug; $url = trailingslashit(get_option( 'home' )) . user_trailingslashit( $term_nicename, 'category' ); } return $url; } // Add our custom post cat rewrite rules add_filter('rewrite_rules_array', 'ojasya_no_category_parents_rewrite_rules'); function ojasya_no_category_parents_rewrite_rules($rules) { $new_rules = array(); $terms = get_terms( array( 'taxonomy' =&gt; 'category', 'post_type' =&gt; 'post', 'hide_empty' =&gt; false, )); if($terms &amp;&amp; !is_wp_error($terms)){ foreach ($terms as $term){ $term_slug = $term-&gt;slug; $new_rules[$term_slug.'/?$'] = 'index.php?category='.$term_slug; $new_rules[$term_slug.'/page/([0-9]{1,})/?$'] = 'index.php?category='.$term_slug.'&amp;paged=$matches[1]'; $new_rules[$term_slug.'/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category='.$term_slug.'&amp;feed=$matches[1]'; } } return $new_rules + $rules; } </code></pre> <p>Please help me out on this . Thanks in advance</p>
[ { "answer_id": 314075, "author": "David Corp", "author_id": 129246, "author_profile": "https://wordpress.stackexchange.com/users/129246", "pm_score": -1, "selected": false, "text": "<p>if you will add post id in url anywhere then it will easy otherwise your post title must be unique. So get whole post by title and use <code>add_rewrite_rule</code> function. </p>\n" }, { "answer_id": 314358, "author": "noahmason", "author_id": 142015, "author_profile": "https://wordpress.stackexchange.com/users/142015", "pm_score": 1, "selected": false, "text": "<p>All you have to do to achieve this is to modify the <code>category</code> taxonomy arguments by using <code>register_taxonomy()</code> again at the <code>init</code> hook after the <code>category</code> taxonomy has been registered. This can be done with any taxonomy as in the following snippet.</p>\n\n<p><strong>Code for Taxonomies in General (Code for this use case below):</strong></p>\n\n<pre><code>function mytheme_change_category_args() {\n\n // Get the taxonomy.\n $category = get_taxonomy( 'category' );\n\n // change the rewrite slug on the taxonomy itself.\n // Note that if your permalink structure is currently \n // \"/post/%postname%\", this should be changed to \"c\", and \n // \"with_front\" should be set to \"true\".\n $category-&gt;rewrite['slug'] = 'post/c'; \n\n // do not use the text that comes before the first \n // rewrite tag (%...%) in the permalink settings, unless the\n // setting is \"/post/%postname%\" as explained above. \n $category-&gt;rewrite['with_front'] = false; \n\n // Keep the category hierarchical, but make the permalinks flat.\n $category-&gt;rewrite['hierarchical'] = false;\n\n // register_taxonomy() is used to create OR modify a taxonomy. \n // make sure the taxonomy object is cast to an array.\n register_taxonomy( 'category', 'post', (array) $category ); \n\n}\n\n// Make sure this happens after the original tax is init. Priority 10 is fine.\nadd_action( 'init', 'mytheme_change_category_args', 10 );\n</code></pre>\n\n<p><strong>Note:</strong></p>\n\n<p>Go to <code>Settings-&gt;Permalinks</code>and hit \"Save Changes\" to flush the rewrite rules. No need to filter term links, add rewrite rules, or anything else.</p>\n\n<hr>\n\n<p><strong>To answer your question specifically:</strong></p>\n\n<p>In order to do this with the core WP taxonomies like <code>category</code> and <code>post_tag</code>, we have to keep in mind the Category and Tag permalink settings at <code>Settings-&gt;Permalinks</code> Which the above example does not. The best way to do this is actually the simplest way too.</p>\n\n<p><strong>Code for this use case:</strong></p>\n\n<p><strong>Option 1:</strong></p>\n\n<pre><code>function mytheme_change_category_args() {\n\n $category = get_taxonomy( 'category' );\n $post_tag = get_taxonomy( 'post_tag' );\n\n $category-&gt;rewrite['hierarchical'] = false;\n $category-&gt;rewrite['with_front'] = false;\n $post_tag-&gt;rewrite['with_front'] = false;\n\n register_taxonomy( 'category', 'post', (array) $category ); \n register_taxonomy( 'post_tag', 'post', (array) $post_tag ); \n\n}\n\nadd_action( 'init', 'mytheme_change_category_args', 50 );\n</code></pre>\n\n<p>All you have to do is set <code>category</code> to non-hierarchical permalinks, and set <code>with_front</code> to false on both <code>category</code> and <code>post_tag</code>. then set your permalinks at <code>Settings-&gt;Permalinks</code> as in the image below <strong>;)</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/cxl4R.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cxl4R.png\" alt=\"Cat Tag Permalinks\"></a></p>\n\n<p><strong>Option 2:</strong></p>\n\n<pre><code>function mytheme_change_category_args() {\n\n $category = get_taxonomy( 'category' );\n $post_tag = get_taxonomy( 'post_tag' );\n\n $category-&gt;rewrite['hierarchical'] = false;\n $category-&gt;rewrite['with_front'] = true;\n $post_tag-&gt;rewrite['with_front'] = true;\n\n register_taxonomy( 'category', 'post', (array) $category ); \n register_taxonomy( 'post_tag', 'post', (array) $post_tag ); \n\n}\n\nadd_action( 'init', 'mytheme_change_category_args', 50 );\n</code></pre>\n\n<p>In this case, what you have to do is set <code>category</code> to non-hierarchical permalinks (as in Option 1), and set <code>with_front</code> to true on both <code>category</code> and <code>post_tag</code>. Then, set your permalinks at <code>Settings-&gt;Permalinks</code> as in the image below, keeping in mind that any plain text tags that you place before the first rewrite tag (<code>%...%</code>) of the POST PERMALINK setting will appear before the cat/tag permalink base. <strong>If this is set to <code>/post/%...%/%...%/%...%/</code>, this is the best option, for sure.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/bJ2vP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bJ2vP.png\" alt=\"Permalink Settings Screen Shot\"></a></p>\n" } ]
2018/09/08
[ "https://wordpress.stackexchange.com/questions/313663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55034/" ]
For the default taxonomy i.e category , I want custom permalinks with ``` i) base = "post/c" and ii) without any parent slug ``` For eg: if I have categories ``` cat-a subcat-a1 subcat-a2 cat-b subcat-a2 subcat-a2 ``` so I want permalinks like example.com/post/c/cat-a example.com/post/c/subcat-a1 example.com/post/c/subcat-a2 example.com/post/c/cat-b example.com/post/c/subcat-b1 example.com/post/c/subcat-b2 I am using the following code .. I solves the issue (ii) but not issue (i) i.e base 'post/c' ``` add_filter('term_link', 'ojasya_no_term_parents', 1000, 3); function ojasya_no_term_parents($url, $term, $taxonomy) { if($taxonomy == 'category'){ $term_nicename = $term->slug; $url = trailingslashit(get_option( 'home' )) . user_trailingslashit( $term_nicename, 'category' ); } return $url; } // Add our custom post cat rewrite rules add_filter('rewrite_rules_array', 'ojasya_no_category_parents_rewrite_rules'); function ojasya_no_category_parents_rewrite_rules($rules) { $new_rules = array(); $terms = get_terms( array( 'taxonomy' => 'category', 'post_type' => 'post', 'hide_empty' => false, )); if($terms && !is_wp_error($terms)){ foreach ($terms as $term){ $term_slug = $term->slug; $new_rules[$term_slug.'/?$'] = 'index.php?category='.$term_slug; $new_rules[$term_slug.'/page/([0-9]{1,})/?$'] = 'index.php?category='.$term_slug.'&paged=$matches[1]'; $new_rules[$term_slug.'/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category='.$term_slug.'&feed=$matches[1]'; } } return $new_rules + $rules; } ``` Please help me out on this . Thanks in advance
All you have to do to achieve this is to modify the `category` taxonomy arguments by using `register_taxonomy()` again at the `init` hook after the `category` taxonomy has been registered. This can be done with any taxonomy as in the following snippet. **Code for Taxonomies in General (Code for this use case below):** ``` function mytheme_change_category_args() { // Get the taxonomy. $category = get_taxonomy( 'category' ); // change the rewrite slug on the taxonomy itself. // Note that if your permalink structure is currently // "/post/%postname%", this should be changed to "c", and // "with_front" should be set to "true". $category->rewrite['slug'] = 'post/c'; // do not use the text that comes before the first // rewrite tag (%...%) in the permalink settings, unless the // setting is "/post/%postname%" as explained above. $category->rewrite['with_front'] = false; // Keep the category hierarchical, but make the permalinks flat. $category->rewrite['hierarchical'] = false; // register_taxonomy() is used to create OR modify a taxonomy. // make sure the taxonomy object is cast to an array. register_taxonomy( 'category', 'post', (array) $category ); } // Make sure this happens after the original tax is init. Priority 10 is fine. add_action( 'init', 'mytheme_change_category_args', 10 ); ``` **Note:** Go to `Settings->Permalinks`and hit "Save Changes" to flush the rewrite rules. No need to filter term links, add rewrite rules, or anything else. --- **To answer your question specifically:** In order to do this with the core WP taxonomies like `category` and `post_tag`, we have to keep in mind the Category and Tag permalink settings at `Settings->Permalinks` Which the above example does not. The best way to do this is actually the simplest way too. **Code for this use case:** **Option 1:** ``` function mytheme_change_category_args() { $category = get_taxonomy( 'category' ); $post_tag = get_taxonomy( 'post_tag' ); $category->rewrite['hierarchical'] = false; $category->rewrite['with_front'] = false; $post_tag->rewrite['with_front'] = false; register_taxonomy( 'category', 'post', (array) $category ); register_taxonomy( 'post_tag', 'post', (array) $post_tag ); } add_action( 'init', 'mytheme_change_category_args', 50 ); ``` All you have to do is set `category` to non-hierarchical permalinks, and set `with_front` to false on both `category` and `post_tag`. then set your permalinks at `Settings->Permalinks` as in the image below **;)** [![Cat Tag Permalinks](https://i.stack.imgur.com/cxl4R.png)](https://i.stack.imgur.com/cxl4R.png) **Option 2:** ``` function mytheme_change_category_args() { $category = get_taxonomy( 'category' ); $post_tag = get_taxonomy( 'post_tag' ); $category->rewrite['hierarchical'] = false; $category->rewrite['with_front'] = true; $post_tag->rewrite['with_front'] = true; register_taxonomy( 'category', 'post', (array) $category ); register_taxonomy( 'post_tag', 'post', (array) $post_tag ); } add_action( 'init', 'mytheme_change_category_args', 50 ); ``` In this case, what you have to do is set `category` to non-hierarchical permalinks (as in Option 1), and set `with_front` to true on both `category` and `post_tag`. Then, set your permalinks at `Settings->Permalinks` as in the image below, keeping in mind that any plain text tags that you place before the first rewrite tag (`%...%`) of the POST PERMALINK setting will appear before the cat/tag permalink base. **If this is set to `/post/%...%/%...%/%...%/`, this is the best option, for sure.** [![Permalink Settings Screen Shot](https://i.stack.imgur.com/bJ2vP.png)](https://i.stack.imgur.com/bJ2vP.png)
313,726
<p>I'm creating a plugin and I've put:</p> <pre><code>define ('WPLANG', 'it_IT'); </code></pre> <p>into <code>wp-config.php</code> file.</p> <p>After plugin Name in the Header of the Plugin declaration:</p> <pre><code>* Text Domain: endpoint * Domain Path: /languages/ </code></pre> <p>For the load domain:</p> <pre><code>add_action( 'plugins_loaded', 'myplugin_load_textdomain' ); function myplugin_load_textdomain() { load_plugin_textdomain( 'endpoint', false, dirname( __FILE__ ) . '/languages/' ); } </code></pre> <p>In languages I created pot, po and mo file with this names: <code>end-point.pot</code>, <code>end-point-it_IT.po</code> and <code>end-point-it_IT.mo</code>.</p> <p>I switched to Italian but nothing is changed.</p> <p>Any help?</p>
[ { "answer_id": 313743, "author": "Salvio", "author_id": 106644, "author_profile": "https://wordpress.stackexchange.com/users/106644", "pm_score": 0, "selected": false, "text": "<p>Ok I made a mistake with dirname (<strong>FILE</strong>) . /languages/ and the fact that debuggin via load_plugin_textdomain I saw that it create the file name by the domaèn passed as argument to the function.</p>\n\n<p>Thanks anyway.</p>\n" }, { "answer_id": 313957, "author": "Tim", "author_id": 48306, "author_profile": "https://wordpress.stackexchange.com/users/48306", "pm_score": 1, "selected": false, "text": "<p>1) Presuming you're running WordPress 4.x. The <code>WPLANG</code> constant does nothing. WordPress 3 and below defined the default language in <code>wp-config.php</code> but since WordPress 4 setting your site language is done via the General Settings page in your admin area. Go to <em>Settings > General</em> and scroll to the bottom where is says \"Site Language\" next to a dropdown list.</p>\n\n<p>2) The argument <code>dirname(__FILE__).'/languages/'</code> is wrong as this should be a relative path. Use <code>dirname(plugin_basename(__FILE__)).'/languages/'</code> </p>\n" } ]
2018/09/09
[ "https://wordpress.stackexchange.com/questions/313726", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106644/" ]
I'm creating a plugin and I've put: ``` define ('WPLANG', 'it_IT'); ``` into `wp-config.php` file. After plugin Name in the Header of the Plugin declaration: ``` * Text Domain: endpoint * Domain Path: /languages/ ``` For the load domain: ``` add_action( 'plugins_loaded', 'myplugin_load_textdomain' ); function myplugin_load_textdomain() { load_plugin_textdomain( 'endpoint', false, dirname( __FILE__ ) . '/languages/' ); } ``` In languages I created pot, po and mo file with this names: `end-point.pot`, `end-point-it_IT.po` and `end-point-it_IT.mo`. I switched to Italian but nothing is changed. Any help?
1) Presuming you're running WordPress 4.x. The `WPLANG` constant does nothing. WordPress 3 and below defined the default language in `wp-config.php` but since WordPress 4 setting your site language is done via the General Settings page in your admin area. Go to *Settings > General* and scroll to the bottom where is says "Site Language" next to a dropdown list. 2) The argument `dirname(__FILE__).'/languages/'` is wrong as this should be a relative path. Use `dirname(plugin_basename(__FILE__)).'/languages/'`
313,795
<p>I am trying to extend the Gutenberg <code>core/gallery</code> block to add some new functionality to my image gallery on the frontend. I have created a separate plugin to handle this task. I have registered my script with the following code:</p> <pre><code>function mt_enqueue_gutenberg(){ wp_enqueue_script( 'mt-gallery-block', plugins_url( 'gallery-block.js',__FILE__), array( 'wp-blocks', 'wp-i18n', 'wp-element' ) ); //Script and stylesheet loaded on frontend only if(!is_admin()){ wp_enqueue_script( 'mt-gallery-frontend-script', plugins_url( 'gallery.js', __FILE__), array( 'mt-gallery-block' ) ); wp_enqueue_style( 'mt-gallery-frontend-style', plugins_url( 'gallery.css', __FILE__), array( 'mt-gallery-block' ) ); } } add_action( 'enqueue_block_editor_assets', 'mt_enqueue_gutenberg'); </code></pre> <p>In my <code>gallery-block.js</code> file I am using the <code>blocks.getSaveElement</code> filter to edit the block’s <code>HTML</code>-output to the frontend.</p> <pre><code>//Filter hook wp.hooks.addFilter( 'blocks.getSaveElement', 'wpse-298225', mt_gallerySaveElement ) function mt_gallerySaveElement( element, blockType, attributes ) { //returns the element without changing it, if it is not the gallery block if ( blockType.name !== 'core/gallery' ) { return element; } //Creates div element with nested img's var newElement = wp.element.createElement( 'div', { 'className': 'gallery-grid', 'data-total-slides': attributes.images.length }, //Loops through each image in the gallery and creates an img-element attributes.images.map( function( image, index ) { return wp.element.createElement( 'img', { 'src': image.url, 'alt': image.alt, 'className': 'gallery-item', 'data-slide-no': index, 'data-caption': image.caption[0] } ) } ) ) return newElement } </code></pre> <p>Everything works as it is supposed to except when I reload the Gutenberg editor. When I reload the page I get a validation error and I am not allowed to edit the gallery block. (See screenshots below)</p> <p><a href="https://i.stack.imgur.com/gAMdp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gAMdp.png" alt="Gallery block - before and after reload"></a></p> <p>Below I have provided a screenshot of the console log after I reloaded the page: </p> <p><a href="https://i.stack.imgur.com/6N9Wy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6N9Wy.png" alt="Validation error - console log"></a></p> <p>I am pretty sure the error occurs because my output does not correspond to the expected structure of the gallery, and thus WordPress does not see any images inside the gallery block when I reload the page.</p> <p><strong>So, my question is: How can I fix this validation error?</strong></p> <p><strong>Assuming the error is caused by the difference between my <code>HTML</code> structure and the expected gallery structure: How can I make Gutenberg recognize my <code>HTML</code> structure as a gallery?</strong></p> <p>Any suggestions would be highly appreciated. </p>
[ { "answer_id": 313969, "author": "Andreas", "author_id": 150311, "author_profile": "https://wordpress.stackexchange.com/users/150311", "pm_score": 5, "selected": true, "text": "<p><strong>Answering my own question:</strong></p>\n\n<p>As suggested by <a href=\"https://wordpress.stackexchange.com/users/102815/webelaine\">WebElaine</a> I created a completely new block to fix the problem. \nTo make this task easier, I used <a href=\"https://github.com/ahmadawais/create-guten-block\" rel=\"noreferrer\">create-guten-block by Ahmad Awais</a>, which is pretty easy to set up.</p>\n\n<p>In init.php I made sure to enqueue my JavaScript and extra CSS for the frontend. This should be straight forward. I recommend reading the <a href=\"https://css-tricks.com/learning-gutenberg-1-series-intro/\" rel=\"noreferrer\">Learning Gutenberg series on css-tricks.com</a>. It was a great help for me getting started.</p>\n\n<p>The important part is how I created the gallery block. In block.js (created by create-guten-block) I have destructured <code>MediaUpload</code> from <code>wp.editor</code>, and <code>Button</code> from <code>wp.components</code>.</p>\n\n<pre><code>const { MediaUpload } = wp.editor; //Import MediaUpload from wp.editor\nconst { Button } = wp.components; //Import Button from wp.components\n</code></pre>\n\n<p>I register the block with a title, an icon, a category, some keywords and an images attribute with the type array. This will contain the images from the gallery</p>\n\n<pre><code> registerBlockType( 'cgb/block-my-test-block', {\n title: __( 'MT - Gallery' ), // Block title.\n icon: 'format-gallery', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.\n category: 'common', // Block category\n keywords: [ //Keywords\n __('materialtheme'),\n __('photos'),\n __('images')\n ],\n attributes: { //Attributes\n images : { //Images array\n type: 'array',\n }\n},\n</code></pre>\n\n<p>My edit function (the part of the block shown in the editor) looks like this:</p>\n\n<pre><code>edit({ attributes, className, setAttributes }) {\n\n //Destructuring the images array attribute\n const {images = []} = attributes;\n\n\n // This removes an image from the gallery\n const removeImage = (removeImage) =&gt; {\n //filter the images\n const newImages = images.filter( (image) =&gt; {\n //If the current image is equal to removeImage the image will be returnd\n if(image.id != removeImage.id) {\n return image;\n }\n });\n\n //Saves the new state\n setAttributes({\n images:newImages,\n })\n }\n\n\n //Displays the images\n const displayImages = (images) =&gt; {\n return (\n //Loops throug the images\n images.map( (image) =&gt; {\n return (\n &lt;div className=\"gallery-item-container\"&gt;\n &lt;img className='gallery-item' src={image.url} key={ images.id } /&gt;\n &lt;div className='remove-item' onClick={() =&gt; removeImage(image)}&gt;&lt;span class=\"dashicons dashicons-trash\"&gt;&lt;/span&gt;&lt;/div&gt;\n &lt;div className='caption-text'&gt;{image.caption[0]}&lt;/div&gt;\n &lt;/div&gt;\n )\n })\n\n )\n }\n\n //JSX to return\n return (\n &lt;div&gt;\n &lt;div className=\"gallery-grid\"&gt;\n {displayImages(images)}\n &lt;/div&gt;\n &lt;br/&gt;\n &lt;MediaUpload\n onSelect={(media) =&gt; {setAttributes({images: [...images, ...media]});}}\n type=\"image\"\n multiple={true}\n value={images}\n render={({open}) =&gt; (\n &lt;Button className=\"select-images-button is-button is-default is-large\" onClick={open}&gt;\n Add images\n &lt;/Button&gt;\n )}\n /&gt;\n &lt;/div&gt;\n\n );\n },\n</code></pre>\n\n<p>Here I make use of the <code>MediaUpload</code> and <code>Button</code> object.\nNotice that I have set <code>multiple</code> to <code>true</code>, which allows me to select multiple images. To select multiple images this way, you must hold down <kbd>CTRL</kbd> like you would do selecting multiple files in File Explorer (on Windows).</p>\n\n<p>In my save function I map the images and add the desired attributes to the <code>img</code>-tag.</p>\n\n<pre><code>save({attributes}) {\n //Destructuring the images array attribute\n const { images = [] } = attributes;\n\n // Displays the images\n const displayImages = (images) =&gt; {\n return (\n images.map( (image,index) =&gt; {\n return (\n &lt;img\n className='gallery-item'\n key={images.id}\n src={image.url}\n data-slide-no={index}\n data-caption={image.caption[0]}\n alt={image.alt}\n /&gt;\n )\n })\n )\n }\n\n //JSX to return\n return (\n &lt;div&gt;\n &lt;div className=\"gallery-grid\" data-total-slides={images.length}&gt;{ displayImages(images) }&lt;/div&gt;\n &lt;/div&gt;\n );\n\n},\n</code></pre>\n\n<p>My complete code from block.js looks like this:</p>\n\n<pre><code>/**\n * BLOCK: my-test-block\n *\n * Registering a basic block with Gutenberg.\n * Simple block, renders and saves the same content without any interactivity.\n */\n\nimport './style.scss';\nimport './editor.scss';\n\nconst { __ } = wp.i18n; // Import __() from wp.i18n\nconst { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks\nconst { MediaUpload } = wp.editor; //Import MediaUpload from wp.editor\nconst { Button } = wp.components; //Import Button from wp.components\n\n\n/**\n * Register: aa Gutenberg Block.\n *\n * Registers a new block provided a unique name and an object defining its\n * behavior. Once registered, the block is made editor as an option to any\n * editor interface where blocks are implemented.\n *\n * @link https://wordpress.org/gutenberg/handbook/block-api/\n * @param {string} name Block name.\n * @param {Object} settings Block settings.\n * @return {?WPBlock} The block, if it has been successfully\n * registered; otherwise `undefined`.\n */\n\nregisterBlockType( 'cgb/block-my-test-block', {\n title: __( 'MT - Gallery' ), // Block title.\n icon: 'format-gallery', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.\n category: 'common', // Block category\n keywords: [ //Keywords\n __('materialtheme'),\n __('photos'),\n __('images')\n ],\n attributes: { //Attributes\n images : { //Images array\n type: 'array',\n }\n},\n\n /**\n * The edit function describes the structure of your block in the context of the editor.\n * This represents what the editor will render when the block is used.\n *\n * The \"edit\" property must be a valid function.\n *\n * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/\n */\n edit({ attributes, className, setAttributes }) {\n\n //Destructuring the images array attribute\n const {images = []} = attributes;\n\n\n // This removes an image from the gallery\n const removeImage = (removeImage) =&gt; {\n //filter the images\n const newImages = images.filter( (image) =&gt; {\n //If the current image is equal to removeImage the image will be returnd\n if(image.id != removeImage.id) {\n return image;\n }\n });\n\n //Saves the new state\n setAttributes({\n images:newImages,\n })\n }\n\n\n //Displays the images\n const displayImages = (images) =&gt; {\n return (\n //Loops throug the images\n images.map( (image) =&gt; {\n return (\n &lt;div className=\"gallery-item-container\"&gt;\n &lt;img className='gallery-item' src={image.url} key={ images.id } /&gt;\n &lt;div className='remove-item' onClick={() =&gt; removeImage(image)}&gt;&lt;span class=\"dashicons dashicons-trash\"&gt;&lt;/span&gt;&lt;/div&gt;\n &lt;div className='caption-text'&gt;{image.caption[0]}&lt;/div&gt;\n &lt;/div&gt;\n )\n })\n\n )\n }\n\n //JSX to return\n return (\n &lt;div&gt;\n &lt;div className=\"gallery-grid\"&gt;\n {displayImages(images)}\n &lt;/div&gt;\n &lt;br/&gt;\n &lt;MediaUpload\n onSelect={(media) =&gt; {setAttributes({images: [...images, ...media]});}}\n type=\"image\"\n multiple={true}\n value={images}\n render={({open}) =&gt; (\n &lt;Button className=\"select-images-button is-button is-default is-large\" onClick={open}&gt;\n Add images\n &lt;/Button&gt;\n )}\n /&gt;\n &lt;/div&gt;\n\n );\n },\n\n /**\n * The save function defines the way in which the different attributes should be combined\n * into the final markup, which is then serialized by Gutenberg into post_content.\n *\n * The \"save\" property must be specified and must be a valid function.\n *\n * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/\n */\n save({attributes}) {\n //Destructuring the images array attribute\n const { images = [] } = attributes;\n\n // Displays the images\n const displayImages = (images) =&gt; {\n return (\n images.map( (image,index) =&gt; {\n return (\n &lt;img\n className='gallery-item'\n key={images.id}\n src={image.url}\n data-slide-no={index}\n data-caption={image.caption[0]}\n alt={image.alt}\n /&gt;\n )\n })\n )\n }\n\n //JSX to return\n return (\n &lt;div&gt;\n &lt;div className=\"gallery-grid\" data-total-slides={images.length}&gt;{ displayImages(images) }&lt;/div&gt;\n &lt;/div&gt;\n );\n\n },\n} );\n</code></pre>\n\n<p>After adding some styling my gallery looks like this in the editor:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9j8K6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9j8K6.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 391663, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 1, "selected": false, "text": "<p>2 years later <a href=\"https://wordpress.stackexchange.com/a/313969/102683\">https://wordpress.stackexchange.com/a/313969/102683</a> is still the ultimate answer.</p>\n<p>UPDATING with the new way to import the WordPress components.</p>\n<pre><code>import { __ } from '@wordpress/i18n';\nimport { MediaUpload } from '@wordpress/block-editor';\nimport { Button } from '@wordpress/components';\nimport { registerBlockType } from '@wordpress/blocks';\n</code></pre>\n" } ]
2018/09/10
[ "https://wordpress.stackexchange.com/questions/313795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150311/" ]
I am trying to extend the Gutenberg `core/gallery` block to add some new functionality to my image gallery on the frontend. I have created a separate plugin to handle this task. I have registered my script with the following code: ``` function mt_enqueue_gutenberg(){ wp_enqueue_script( 'mt-gallery-block', plugins_url( 'gallery-block.js',__FILE__), array( 'wp-blocks', 'wp-i18n', 'wp-element' ) ); //Script and stylesheet loaded on frontend only if(!is_admin()){ wp_enqueue_script( 'mt-gallery-frontend-script', plugins_url( 'gallery.js', __FILE__), array( 'mt-gallery-block' ) ); wp_enqueue_style( 'mt-gallery-frontend-style', plugins_url( 'gallery.css', __FILE__), array( 'mt-gallery-block' ) ); } } add_action( 'enqueue_block_editor_assets', 'mt_enqueue_gutenberg'); ``` In my `gallery-block.js` file I am using the `blocks.getSaveElement` filter to edit the block’s `HTML`-output to the frontend. ``` //Filter hook wp.hooks.addFilter( 'blocks.getSaveElement', 'wpse-298225', mt_gallerySaveElement ) function mt_gallerySaveElement( element, blockType, attributes ) { //returns the element without changing it, if it is not the gallery block if ( blockType.name !== 'core/gallery' ) { return element; } //Creates div element with nested img's var newElement = wp.element.createElement( 'div', { 'className': 'gallery-grid', 'data-total-slides': attributes.images.length }, //Loops through each image in the gallery and creates an img-element attributes.images.map( function( image, index ) { return wp.element.createElement( 'img', { 'src': image.url, 'alt': image.alt, 'className': 'gallery-item', 'data-slide-no': index, 'data-caption': image.caption[0] } ) } ) ) return newElement } ``` Everything works as it is supposed to except when I reload the Gutenberg editor. When I reload the page I get a validation error and I am not allowed to edit the gallery block. (See screenshots below) [![Gallery block - before and after reload](https://i.stack.imgur.com/gAMdp.png)](https://i.stack.imgur.com/gAMdp.png) Below I have provided a screenshot of the console log after I reloaded the page: [![Validation error - console log](https://i.stack.imgur.com/6N9Wy.png)](https://i.stack.imgur.com/6N9Wy.png) I am pretty sure the error occurs because my output does not correspond to the expected structure of the gallery, and thus WordPress does not see any images inside the gallery block when I reload the page. **So, my question is: How can I fix this validation error?** **Assuming the error is caused by the difference between my `HTML` structure and the expected gallery structure: How can I make Gutenberg recognize my `HTML` structure as a gallery?** Any suggestions would be highly appreciated.
**Answering my own question:** As suggested by [WebElaine](https://wordpress.stackexchange.com/users/102815/webelaine) I created a completely new block to fix the problem. To make this task easier, I used [create-guten-block by Ahmad Awais](https://github.com/ahmadawais/create-guten-block), which is pretty easy to set up. In init.php I made sure to enqueue my JavaScript and extra CSS for the frontend. This should be straight forward. I recommend reading the [Learning Gutenberg series on css-tricks.com](https://css-tricks.com/learning-gutenberg-1-series-intro/). It was a great help for me getting started. The important part is how I created the gallery block. In block.js (created by create-guten-block) I have destructured `MediaUpload` from `wp.editor`, and `Button` from `wp.components`. ``` const { MediaUpload } = wp.editor; //Import MediaUpload from wp.editor const { Button } = wp.components; //Import Button from wp.components ``` I register the block with a title, an icon, a category, some keywords and an images attribute with the type array. This will contain the images from the gallery ``` registerBlockType( 'cgb/block-my-test-block', { title: __( 'MT - Gallery' ), // Block title. icon: 'format-gallery', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/. category: 'common', // Block category keywords: [ //Keywords __('materialtheme'), __('photos'), __('images') ], attributes: { //Attributes images : { //Images array type: 'array', } }, ``` My edit function (the part of the block shown in the editor) looks like this: ``` edit({ attributes, className, setAttributes }) { //Destructuring the images array attribute const {images = []} = attributes; // This removes an image from the gallery const removeImage = (removeImage) => { //filter the images const newImages = images.filter( (image) => { //If the current image is equal to removeImage the image will be returnd if(image.id != removeImage.id) { return image; } }); //Saves the new state setAttributes({ images:newImages, }) } //Displays the images const displayImages = (images) => { return ( //Loops throug the images images.map( (image) => { return ( <div className="gallery-item-container"> <img className='gallery-item' src={image.url} key={ images.id } /> <div className='remove-item' onClick={() => removeImage(image)}><span class="dashicons dashicons-trash"></span></div> <div className='caption-text'>{image.caption[0]}</div> </div> ) }) ) } //JSX to return return ( <div> <div className="gallery-grid"> {displayImages(images)} </div> <br/> <MediaUpload onSelect={(media) => {setAttributes({images: [...images, ...media]});}} type="image" multiple={true} value={images} render={({open}) => ( <Button className="select-images-button is-button is-default is-large" onClick={open}> Add images </Button> )} /> </div> ); }, ``` Here I make use of the `MediaUpload` and `Button` object. Notice that I have set `multiple` to `true`, which allows me to select multiple images. To select multiple images this way, you must hold down `CTRL` like you would do selecting multiple files in File Explorer (on Windows). In my save function I map the images and add the desired attributes to the `img`-tag. ``` save({attributes}) { //Destructuring the images array attribute const { images = [] } = attributes; // Displays the images const displayImages = (images) => { return ( images.map( (image,index) => { return ( <img className='gallery-item' key={images.id} src={image.url} data-slide-no={index} data-caption={image.caption[0]} alt={image.alt} /> ) }) ) } //JSX to return return ( <div> <div className="gallery-grid" data-total-slides={images.length}>{ displayImages(images) }</div> </div> ); }, ``` My complete code from block.js looks like this: ``` /** * BLOCK: my-test-block * * Registering a basic block with Gutenberg. * Simple block, renders and saves the same content without any interactivity. */ import './style.scss'; import './editor.scss'; const { __ } = wp.i18n; // Import __() from wp.i18n const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks const { MediaUpload } = wp.editor; //Import MediaUpload from wp.editor const { Button } = wp.components; //Import Button from wp.components /** * Register: aa Gutenberg Block. * * Registers a new block provided a unique name and an object defining its * behavior. Once registered, the block is made editor as an option to any * editor interface where blocks are implemented. * * @link https://wordpress.org/gutenberg/handbook/block-api/ * @param {string} name Block name. * @param {Object} settings Block settings. * @return {?WPBlock} The block, if it has been successfully * registered; otherwise `undefined`. */ registerBlockType( 'cgb/block-my-test-block', { title: __( 'MT - Gallery' ), // Block title. icon: 'format-gallery', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/. category: 'common', // Block category keywords: [ //Keywords __('materialtheme'), __('photos'), __('images') ], attributes: { //Attributes images : { //Images array type: 'array', } }, /** * The edit function describes the structure of your block in the context of the editor. * This represents what the editor will render when the block is used. * * The "edit" property must be a valid function. * * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/ */ edit({ attributes, className, setAttributes }) { //Destructuring the images array attribute const {images = []} = attributes; // This removes an image from the gallery const removeImage = (removeImage) => { //filter the images const newImages = images.filter( (image) => { //If the current image is equal to removeImage the image will be returnd if(image.id != removeImage.id) { return image; } }); //Saves the new state setAttributes({ images:newImages, }) } //Displays the images const displayImages = (images) => { return ( //Loops throug the images images.map( (image) => { return ( <div className="gallery-item-container"> <img className='gallery-item' src={image.url} key={ images.id } /> <div className='remove-item' onClick={() => removeImage(image)}><span class="dashicons dashicons-trash"></span></div> <div className='caption-text'>{image.caption[0]}</div> </div> ) }) ) } //JSX to return return ( <div> <div className="gallery-grid"> {displayImages(images)} </div> <br/> <MediaUpload onSelect={(media) => {setAttributes({images: [...images, ...media]});}} type="image" multiple={true} value={images} render={({open}) => ( <Button className="select-images-button is-button is-default is-large" onClick={open}> Add images </Button> )} /> </div> ); }, /** * The save function defines the way in which the different attributes should be combined * into the final markup, which is then serialized by Gutenberg into post_content. * * The "save" property must be specified and must be a valid function. * * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/ */ save({attributes}) { //Destructuring the images array attribute const { images = [] } = attributes; // Displays the images const displayImages = (images) => { return ( images.map( (image,index) => { return ( <img className='gallery-item' key={images.id} src={image.url} data-slide-no={index} data-caption={image.caption[0]} alt={image.alt} /> ) }) ) } //JSX to return return ( <div> <div className="gallery-grid" data-total-slides={images.length}>{ displayImages(images) }</div> </div> ); }, } ); ``` After adding some styling my gallery looks like this in the editor: [![enter image description here](https://i.stack.imgur.com/9j8K6.png)](https://i.stack.imgur.com/9j8K6.png)
313,818
<p>I am experiencing a small problem and I have tried several solutions, but none of them has worked unfortunately. Perhaps somebody has a clue why :-)</p> <p>I am using the Syntax theme from Automattic which has its own language file, but it also uses the default Wordpress core language file to display some words in the frontend of my theme.</p> <p>I have set the language to Dutch (nl_NL) and one word is not translated properly, namely the word 'Aside' which is translated in 'Aside' as well. However, this is not a Dutch word and I'd like to change it into 'Notities'. </p> <p>I have tried these three solutions, but they all did not work :-( Perhaps it has something to do with the fact that the original word 'Aside' is translated in 'Aside' as well in the Wordpress core language file? I am just guessing :-)</p> <ol> <li><a href="https://wordpress.stackexchange.com/questions/188332/override-default-wordpress-core-translation">Option 1 that did not work</a></li> <li><a href="https://stackoverflow.com/questions/16403052/wordpress-change-default-translation">Option 2 idem.</a></li> <li><a href="https://wordpress.org/plugins/quick-localization/" rel="nofollow noreferrer">Option 3 by using the plugin 'Quick Localization'</a></li> </ol> <p>This is the script that resides in wp-includes/post-formats.php that relates to the display of the word 'Aside' in the frontend of my website:</p> <pre><code> function get_post_format_strings() { $strings = array( 'aside' =&gt; _x( 'Aside', 'Post format' ), ); return $strings; } </code></pre> <p>I hope someone has a bright idea. I would appreciate it very much. </p> <p>Thank you and regards, Bark</p>
[ { "answer_id": 313820, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": -1, "selected": false, "text": "<p>This will help:</p>\n\n<pre><code>&lt;?php\nadd_filter( 'gettext', 'added_translation', 20, 3 );\n\nfunction added_translation( $text )\n{\n // Search for the string and replace it with translation\n $text = str_replace( 'Aside', 'Aan de kant', $text );\n\n return $text;\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\">More about <code>gettext</code> filter</a>.</p>\n" }, { "answer_id": 313879, "author": "Tim", "author_id": 48306, "author_profile": "https://wordpress.stackexchange.com/users/48306", "pm_score": 2, "selected": true, "text": "<p>Correcting the answer given by Max. To use this approach, the filter you need is <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> because your string is translated via <code>_x()</code> not <code>__()</code>.</p>\n\n<p>Note that the filtered argument passed is the <strong>translation</strong>, so you should check the source string (<code>$text</code> and <code>$context</code>) to ensure you're filtering the correct item.</p>\n\n<pre><code>add_filter( 'gettext_with_context', 'added_translation', 20, 4 );\n\nfunction added_translation( $translation, $text, $context, $domain )\n{\n if( 'Aside' === $text &amp;&amp; 'Post format' === $context ){\n $translation = 'Aan de kant';\n }\n return $translation;\n}\n</code></pre>\n\n<p>Up to you exactly how you detect the string and whether you also check to see if Dutch is the current locale. However this filter does work and should work regardless if the theme you're using.</p>\n\n<p>If you're making a lot of string improvements I recommend using a translation file loaded <strong>in addition</strong> to the installed translations. <a href=\"https://localise.biz/wordpress/plugin/custom-translations\" rel=\"nofollow noreferrer\">Example guide here</a> using Loco Translate to add your own custom file. (Disclosure: my plugin)</p>\n" } ]
2018/09/10
[ "https://wordpress.stackexchange.com/questions/313818", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150132/" ]
I am experiencing a small problem and I have tried several solutions, but none of them has worked unfortunately. Perhaps somebody has a clue why :-) I am using the Syntax theme from Automattic which has its own language file, but it also uses the default Wordpress core language file to display some words in the frontend of my theme. I have set the language to Dutch (nl\_NL) and one word is not translated properly, namely the word 'Aside' which is translated in 'Aside' as well. However, this is not a Dutch word and I'd like to change it into 'Notities'. I have tried these three solutions, but they all did not work :-( Perhaps it has something to do with the fact that the original word 'Aside' is translated in 'Aside' as well in the Wordpress core language file? I am just guessing :-) 1. [Option 1 that did not work](https://wordpress.stackexchange.com/questions/188332/override-default-wordpress-core-translation) 2. [Option 2 idem.](https://stackoverflow.com/questions/16403052/wordpress-change-default-translation) 3. [Option 3 by using the plugin 'Quick Localization'](https://wordpress.org/plugins/quick-localization/) This is the script that resides in wp-includes/post-formats.php that relates to the display of the word 'Aside' in the frontend of my website: ``` function get_post_format_strings() { $strings = array( 'aside' => _x( 'Aside', 'Post format' ), ); return $strings; } ``` I hope someone has a bright idea. I would appreciate it very much. Thank you and regards, Bark
Correcting the answer given by Max. To use this approach, the filter you need is [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) because your string is translated via `_x()` not `__()`. Note that the filtered argument passed is the **translation**, so you should check the source string (`$text` and `$context`) to ensure you're filtering the correct item. ``` add_filter( 'gettext_with_context', 'added_translation', 20, 4 ); function added_translation( $translation, $text, $context, $domain ) { if( 'Aside' === $text && 'Post format' === $context ){ $translation = 'Aan de kant'; } return $translation; } ``` Up to you exactly how you detect the string and whether you also check to see if Dutch is the current locale. However this filter does work and should work regardless if the theme you're using. If you're making a lot of string improvements I recommend using a translation file loaded **in addition** to the installed translations. [Example guide here](https://localise.biz/wordpress/plugin/custom-translations) using Loco Translate to add your own custom file. (Disclosure: my plugin)
313,824
<p>I would like to add a pagination to my wordpress theme. However, for me it is not so easy because my theme is built from the plugin "<em>AT Posts Column</em>", which displays the latest posts on the main page. I would like to add pagination to this plugin :).</p> <p>I tried to insert a pagination plugin and paste the code for displaying at the end in the file below. It is true that the pagination appeared, but when I was going to the next page, only the link changed at www.website.com/page/2. Please help :).</p> <p>My website is <a href="http://consolezone.pl" rel="nofollow noreferrer">http://consolezone.pl</a></p> <p>Plugin file "<em>AT Posts Column</em>":</p> <pre><code>&lt;?php /** * Custom columns of category with various options * * @package Acme Themes * @subpackage SuperNews */ if ( ! class_exists( 'Supernews_posts_col' ) ) { /** * Class for adding widget * * @package Acme Themes * @subpackage SuperNews_posts_col * @since 1.0.0 */ class Supernews_posts_col extends WP_Widget { /*defaults values for fields*/ private $defaults = array( 'supernews_cat_title' =&gt; '', 'supernews_cat' =&gt; -1, 'supernews_enable_posts_featured' =&gt; 1, 'supernews_post_col_first_featured_image_layout' =&gt; 'large', 'supernews_post_col_normal_image_layout' =&gt; 'large' ); function __construct() { parent::__construct( /*Base ID of your widget*/ 'supernews_posts_col', /*Widget name will appear in UI*/ __('AT Posts Column', 'supernews'), /*Widget description*/ array( 'description' =&gt; __( 'Show posts from selected category', 'supernews' ), ) ); } /*Widget Backend*/ public function form( $instance ) { $instance = wp_parse_args( (array) $instance, $this-&gt;defaults); $supernews_col_posts_title = esc_attr( $instance['supernews_cat_title'] ); $supernews_selected_cat = esc_attr( $instance['supernews_cat'] ); $supernews_enable_posts_featured = esc_attr( $instance['supernews_enable_posts_featured'] ); /*first featured image*/ $supernews_post_col_first_featured_image_layout = $instance['supernews_post_col_first_featured_image_layout']; /*normal featured image*/ $supernews_post_col_normal_image_layout = $instance['supernews_post_col_normal_image_layout']; $choices = supernews_get_image_sizes_options(); ?&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'supernews_cat_title' ); ?&gt;"&gt;&lt;?php _e( 'Title:', 'supernews' ); ?&gt;&lt;/label&gt; &lt;input class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'supernews_cat_title' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'supernews_cat_title' ); ?&gt;" type="text" value="&lt;?php echo $supernews_col_posts_title; ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id('supernews_cat'); ?&gt;"&gt;&lt;?php esc_html_e('Select Category', 'supernews'); ?&gt;&lt;/label&gt; &lt;?php $supernews_dropown_cat = array( 'show_option_none' =&gt; __('From Recent Posts','supernews'), 'orderby' =&gt; 'name', 'order' =&gt; 'asc', 'show_count' =&gt; 1, 'hide_empty' =&gt; 1, 'echo' =&gt; 1, 'selected' =&gt; $supernews_selected_cat, 'hierarchical' =&gt; 1, 'name' =&gt; $this-&gt;get_field_name('supernews_cat'), 'id' =&gt; $this-&gt;get_field_name('supernews_cat'), 'class' =&gt; 'widefat', 'taxonomy' =&gt; 'category', 'hide_if_empty' =&gt; false, ); wp_dropdown_categories($supernews_dropown_cat); ?&gt; &lt;/p&gt; &lt;p&gt; &lt;input class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'supernews_enable_posts_featured' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'supernews_enable_posts_featured' ); ?&gt;" type="checkbox" &lt;?php checked( 1, esc_attr( $supernews_enable_posts_featured ), 1 ); ?&gt;/&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'supernews_enable_posts_featured' ); ?&gt;"&gt;&lt;?php esc_html_e( 'Enable Posts Featured' ,'supernews'); ?&gt;&lt;/label&gt; &lt;br /&gt; &lt;/p&gt; &lt;p&gt; &lt;small&gt;&lt;?php esc_html_e( 'Note: Some of the features only work in "Home main content area" due to minimum width in other areas.' ,'supernews'); ?&gt;&lt;/small&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'supernews_post_col_first_featured_image_layout' ); ?&gt;"&gt; &lt;?php _e( 'First Featured Post Image', 'supernews' ); ?&gt; &lt;br /&gt; &lt;small&gt;&lt;?php _e( 'Enable First Post Featured to work this layout', 'supernews' ); ?&gt;&lt;/small&gt; &lt;/label&gt; &lt;select class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'supernews_post_col_first_featured_image_layout' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'supernews_post_col_first_featured_image_layout' ); ?&gt;"&gt; &lt;?php foreach( $choices as $key =&gt; $supernews_column_array ){ echo ' &lt;option value="'.$key.'" '.selected( $supernews_post_col_first_featured_image_layout, $key, 0).'&gt;'.$supernews_column_array.'&lt;/option&gt;'; } ?&gt; &lt;/select&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'supernews_post_col_normal_image_layout' ); ?&gt;"&gt; &lt;?php _e( 'Normal Featured Post Image', 'supernews' ); ?&gt; &lt;br /&gt; &lt;small&gt;&lt;?php _e( 'Enable First Post Featured to work this layout', 'supernews' ); ?&gt;&lt;/small&gt; &lt;/label&gt; &lt;select class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'supernews_post_col_normal_image_layout' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'supernews_post_col_normal_image_layout' ); ?&gt;"&gt; &lt;?php foreach( $choices as $key =&gt; $supernews_column_array ){ echo ' &lt;option value="'.$key.'" '.selected( $supernews_post_col_normal_image_layout, $key, 0). '&gt;'.$supernews_column_array.'&lt;/option&gt;'; } ?&gt; &lt;/select&gt; &lt;/p&gt; &lt;?php } /** * Function to Updating widget replacing old instances with new * * @access public * @since 1.0.0 * * @param array $new_instance new arrays value * @param array $old_instance old arrays value * @return array * */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['supernews_cat_title'] = ( isset( $new_instance['supernews_cat_title'] ) ) ? sanitize_text_field( $new_instance['supernews_cat_title'] ) : ''; $instance['supernews_cat'] = ( isset( $new_instance['supernews_cat'] ) ) ? esc_attr( $new_instance['supernews_cat'] ) : ''; $instance['supernews_enable_posts_featured'] = isset($new_instance['supernews_enable_posts_featured'])? 1 : 0; $instance['supernews_post_col_first_featured_image_layout'] = isset($new_instance['supernews_post_col_first_featured_image_layout'])? esc_attr( $new_instance['supernews_post_col_first_featured_image_layout'] ) : 'large'; $instance['supernews_post_col_normal_image_layout'] = isset($new_instance['supernews_post_col_normal_image_layout'])? esc_attr( $new_instance['supernews_post_col_normal_image_layout'] ) : 'large'; return $instance; } /** * Function to Creating widget front-end. This is where the action happens * * @access public * @since 1.0.0 * * @param array $args widget setting * @param array $instance saved values * @return void * */ public function widget($args, $instance) { if( isset( $args['id'] )){ $supernews_sidebar_id = $args['id']; } else{ $supernews_sidebar_id = 'supernews-home'; } $instance = wp_parse_args( (array) $instance, $this-&gt;defaults); $supernews_selected_cat = esc_attr( $instance['supernews_cat'] ); /*Main title*/ $supernews_col_posts_title = !empty( $instance['supernews_cat_title'] ) ? esc_attr( $instance['supernews_cat_title'] ) : get_cat_name($supernews_selected_cat); $supernews_col_posts_title = apply_filters( 'widget_title', $supernews_col_posts_title, $instance, $this-&gt;id_base ); $supernews_enable_posts_featured = esc_attr( $instance['supernews_enable_posts_featured'] ); /*first featured post layout*/ $supernews_post_col_first_featured_image_layout = esc_attr( $instance['supernews_post_col_first_featured_image_layout'] ); /*normal featured image*/ $supernews_post_col_normal_image_layout = esc_attr( $instance['supernews_post_col_normal_image_layout'] ); /** * Filter the arguments for the Recent Posts widget. * * @since 1.0.0 * * @see WP_Query * */ $supernews_number = 32; $supernews_cat_post_args = array( 'posts_per_page' =&gt; $supernews_number, 'no_found_rows' =&gt; true, 'post_status' =&gt; 'publish', 'ignore_sticky_posts' =&gt; true ); if( -1 != $supernews_selected_cat ){ $supernews_cat_post_args['cat'] = $supernews_selected_cat; } $supernews_featured_query = new WP_Query($supernews_cat_post_args); if ($supernews_featured_query-&gt;have_posts()) : echo $args['before_widget']; if ( !empty( $supernews_col_posts_title ) ){ if( -1 != $supernews_selected_cat ){ echo "&lt;div class='at-cat-color-wrap-".$supernews_selected_cat."'&gt;"; } echo $args['before_title'] . $supernews_col_posts_title . $args['after_title']; if( -1 != $supernews_selected_cat ){ echo "&lt;/div&gt;"; } } $supernews_post_col_layout_class = ''; if( 1 == $supernews_enable_posts_featured ){ $supernews_post_col_layout_class = ' featured-posts'; } ?&gt; &lt;div class="featured-entries-col &lt;?php echo esc_attr( $supernews_post_col_layout_class ); ?&gt; &lt;?php echo esc_attr( $supernews_sidebar_id ); ?&gt;"&gt; &lt;?php $supernews_featured_index = 1; while ( $supernews_featured_query-&gt;have_posts() ) :$supernews_featured_query-&gt;the_post(); $thumb = $supernews_post_col_normal_image_layout; $supernews_list_classes = 'acme-col-2'; $supernews_words = 21; if( $supernews_featured_index % 2 == 1 ){ echo "&lt;div class='clearfix'&gt;&lt;/div&gt;"; $supernews_list_classes .= ' odd'; } if( 1 == $supernews_enable_posts_featured ){ if( $supernews_featured_index &lt;= 2 ){ $supernews_list_classes .= ' first-two'; $thumb = $supernews_post_col_first_featured_image_layout; } else{ $supernews_list_classes .= ' small-posts'; $thumb = $supernews_post_col_normal_image_layout; } } ?&gt; &lt;div class="&lt;?php echo esc_attr( $supernews_list_classes ); ?&gt;"&gt; &lt;!--post thumbnal options--&gt; &lt;div class="post-thumb"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php if( has_post_thumbnail() ): the_post_thumbnail( $thumb ); else: ?&gt; &lt;div class="no-image-widgets"&gt; &lt;?php the_title( sprintf( '&lt;h2 class="caption-title"&gt;&lt;a href="%s" rel="bookmark"&gt;', esc_url( get_permalink() ) ), '&lt;/a&gt;&lt;/h2&gt;' ); if( !get_the_title() ){ the_date( '', sprintf( '&lt;h2 class="caption-title"&gt;&lt;a href="%s" rel="bookmark"&gt;', esc_url( get_permalink() ) ), '&lt;/a&gt;&lt;/h2&gt;' ); } ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;/a&gt; &lt;?php if(1 == $supernews_enable_posts_featured ){ if( $supernews_featured_index &lt;= 2 ){ supernews_list_category(); } } else{ supernews_list_category(); } ?&gt; &lt;/div&gt;&lt;!-- .post-thumb--&gt; &lt;div class="post-content"&gt; &lt;div class="entry-header"&gt; &lt;?php the_title( sprintf( '&lt;h3 class="entry-title"&gt;&lt;a href="%s" rel="bookmark"&gt;', esc_url( get_permalink() ) ), '&lt;/a&gt;&lt;/h3&gt;' ); ?&gt; &lt;div class="entry-meta"&gt; &lt;?php if ( 'post' === get_post_type() ) : supernews_posted_on(); endif; supernews_entry_footer(); ?&gt; &lt;/div&gt;&lt;!-- .entry-meta --&gt; &lt;/div&gt;&lt;!-- .entry-header --&gt; &lt;?php if(1 == $supernews_enable_posts_featured ){ if( $supernews_featured_index &lt;= 2 ){ ?&gt; &lt;div class="entry-content"&gt; &lt;?php $content = supernews_words_count( get_the_excerpt(), $supernews_words ); echo '&lt;div class="details"&gt;'.esc_html( $content ).'&lt;/div&gt;'; ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php } } else{ ?&gt; &lt;div class="entry-content"&gt; &lt;?php $content = supernews_words_count( get_the_excerpt(), $supernews_words ); echo '&lt;div class="details"&gt;'.esc_html( $content ).do_shortcode('[post-views]'),'&lt;/div&gt;'; ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $supernews_featured_index++; endwhile; ?&gt; &lt;/div&gt; &lt;?php echo $args['after_widget']; echo "&lt;div class='clearfix'&gt;&lt;/div&gt;"; // Reset the global $the_post as this query will have stomped on it wp_reset_postdata(); endif; } } } if ( ! function_exists( 'supernews_posts_col' ) ) : /** * Function to Register and load the widget * * @since 1.0.0 * * @param null * @return void * */ function supernews_posts_col() { register_widget( 'Supernews_posts_col' ); } endif; add_action( 'widgets_init', 'supernews_posts_col' ); </code></pre>
[ { "answer_id": 313820, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": -1, "selected": false, "text": "<p>This will help:</p>\n\n<pre><code>&lt;?php\nadd_filter( 'gettext', 'added_translation', 20, 3 );\n\nfunction added_translation( $text )\n{\n // Search for the string and replace it with translation\n $text = str_replace( 'Aside', 'Aan de kant', $text );\n\n return $text;\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\">More about <code>gettext</code> filter</a>.</p>\n" }, { "answer_id": 313879, "author": "Tim", "author_id": 48306, "author_profile": "https://wordpress.stackexchange.com/users/48306", "pm_score": 2, "selected": true, "text": "<p>Correcting the answer given by Max. To use this approach, the filter you need is <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> because your string is translated via <code>_x()</code> not <code>__()</code>.</p>\n\n<p>Note that the filtered argument passed is the <strong>translation</strong>, so you should check the source string (<code>$text</code> and <code>$context</code>) to ensure you're filtering the correct item.</p>\n\n<pre><code>add_filter( 'gettext_with_context', 'added_translation', 20, 4 );\n\nfunction added_translation( $translation, $text, $context, $domain )\n{\n if( 'Aside' === $text &amp;&amp; 'Post format' === $context ){\n $translation = 'Aan de kant';\n }\n return $translation;\n}\n</code></pre>\n\n<p>Up to you exactly how you detect the string and whether you also check to see if Dutch is the current locale. However this filter does work and should work regardless if the theme you're using.</p>\n\n<p>If you're making a lot of string improvements I recommend using a translation file loaded <strong>in addition</strong> to the installed translations. <a href=\"https://localise.biz/wordpress/plugin/custom-translations\" rel=\"nofollow noreferrer\">Example guide here</a> using Loco Translate to add your own custom file. (Disclosure: my plugin)</p>\n" } ]
2018/09/10
[ "https://wordpress.stackexchange.com/questions/313824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150377/" ]
I would like to add a pagination to my wordpress theme. However, for me it is not so easy because my theme is built from the plugin "*AT Posts Column*", which displays the latest posts on the main page. I would like to add pagination to this plugin :). I tried to insert a pagination plugin and paste the code for displaying at the end in the file below. It is true that the pagination appeared, but when I was going to the next page, only the link changed at www.website.com/page/2. Please help :). My website is <http://consolezone.pl> Plugin file "*AT Posts Column*": ``` <?php /** * Custom columns of category with various options * * @package Acme Themes * @subpackage SuperNews */ if ( ! class_exists( 'Supernews_posts_col' ) ) { /** * Class for adding widget * * @package Acme Themes * @subpackage SuperNews_posts_col * @since 1.0.0 */ class Supernews_posts_col extends WP_Widget { /*defaults values for fields*/ private $defaults = array( 'supernews_cat_title' => '', 'supernews_cat' => -1, 'supernews_enable_posts_featured' => 1, 'supernews_post_col_first_featured_image_layout' => 'large', 'supernews_post_col_normal_image_layout' => 'large' ); function __construct() { parent::__construct( /*Base ID of your widget*/ 'supernews_posts_col', /*Widget name will appear in UI*/ __('AT Posts Column', 'supernews'), /*Widget description*/ array( 'description' => __( 'Show posts from selected category', 'supernews' ), ) ); } /*Widget Backend*/ public function form( $instance ) { $instance = wp_parse_args( (array) $instance, $this->defaults); $supernews_col_posts_title = esc_attr( $instance['supernews_cat_title'] ); $supernews_selected_cat = esc_attr( $instance['supernews_cat'] ); $supernews_enable_posts_featured = esc_attr( $instance['supernews_enable_posts_featured'] ); /*first featured image*/ $supernews_post_col_first_featured_image_layout = $instance['supernews_post_col_first_featured_image_layout']; /*normal featured image*/ $supernews_post_col_normal_image_layout = $instance['supernews_post_col_normal_image_layout']; $choices = supernews_get_image_sizes_options(); ?> <p> <label for="<?php echo $this->get_field_id( 'supernews_cat_title' ); ?>"><?php _e( 'Title:', 'supernews' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'supernews_cat_title' ); ?>" name="<?php echo $this->get_field_name( 'supernews_cat_title' ); ?>" type="text" value="<?php echo $supernews_col_posts_title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('supernews_cat'); ?>"><?php esc_html_e('Select Category', 'supernews'); ?></label> <?php $supernews_dropown_cat = array( 'show_option_none' => __('From Recent Posts','supernews'), 'orderby' => 'name', 'order' => 'asc', 'show_count' => 1, 'hide_empty' => 1, 'echo' => 1, 'selected' => $supernews_selected_cat, 'hierarchical' => 1, 'name' => $this->get_field_name('supernews_cat'), 'id' => $this->get_field_name('supernews_cat'), 'class' => 'widefat', 'taxonomy' => 'category', 'hide_if_empty' => false, ); wp_dropdown_categories($supernews_dropown_cat); ?> </p> <p> <input class="widefat" id="<?php echo $this->get_field_id( 'supernews_enable_posts_featured' ); ?>" name="<?php echo $this->get_field_name( 'supernews_enable_posts_featured' ); ?>" type="checkbox" <?php checked( 1, esc_attr( $supernews_enable_posts_featured ), 1 ); ?>/> <label for="<?php echo $this->get_field_id( 'supernews_enable_posts_featured' ); ?>"><?php esc_html_e( 'Enable Posts Featured' ,'supernews'); ?></label> <br /> </p> <p> <small><?php esc_html_e( 'Note: Some of the features only work in "Home main content area" due to minimum width in other areas.' ,'supernews'); ?></small> </p> <p> <label for="<?php echo $this->get_field_id( 'supernews_post_col_first_featured_image_layout' ); ?>"> <?php _e( 'First Featured Post Image', 'supernews' ); ?> <br /> <small><?php _e( 'Enable First Post Featured to work this layout', 'supernews' ); ?></small> </label> <select class="widefat" id="<?php echo $this->get_field_id( 'supernews_post_col_first_featured_image_layout' ); ?>" name="<?php echo $this->get_field_name( 'supernews_post_col_first_featured_image_layout' ); ?>"> <?php foreach( $choices as $key => $supernews_column_array ){ echo ' <option value="'.$key.'" '.selected( $supernews_post_col_first_featured_image_layout, $key, 0).'>'.$supernews_column_array.'</option>'; } ?> </select> </p> <p> <label for="<?php echo $this->get_field_id( 'supernews_post_col_normal_image_layout' ); ?>"> <?php _e( 'Normal Featured Post Image', 'supernews' ); ?> <br /> <small><?php _e( 'Enable First Post Featured to work this layout', 'supernews' ); ?></small> </label> <select class="widefat" id="<?php echo $this->get_field_id( 'supernews_post_col_normal_image_layout' ); ?>" name="<?php echo $this->get_field_name( 'supernews_post_col_normal_image_layout' ); ?>"> <?php foreach( $choices as $key => $supernews_column_array ){ echo ' <option value="'.$key.'" '.selected( $supernews_post_col_normal_image_layout, $key, 0). '>'.$supernews_column_array.'</option>'; } ?> </select> </p> <?php } /** * Function to Updating widget replacing old instances with new * * @access public * @since 1.0.0 * * @param array $new_instance new arrays value * @param array $old_instance old arrays value * @return array * */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['supernews_cat_title'] = ( isset( $new_instance['supernews_cat_title'] ) ) ? sanitize_text_field( $new_instance['supernews_cat_title'] ) : ''; $instance['supernews_cat'] = ( isset( $new_instance['supernews_cat'] ) ) ? esc_attr( $new_instance['supernews_cat'] ) : ''; $instance['supernews_enable_posts_featured'] = isset($new_instance['supernews_enable_posts_featured'])? 1 : 0; $instance['supernews_post_col_first_featured_image_layout'] = isset($new_instance['supernews_post_col_first_featured_image_layout'])? esc_attr( $new_instance['supernews_post_col_first_featured_image_layout'] ) : 'large'; $instance['supernews_post_col_normal_image_layout'] = isset($new_instance['supernews_post_col_normal_image_layout'])? esc_attr( $new_instance['supernews_post_col_normal_image_layout'] ) : 'large'; return $instance; } /** * Function to Creating widget front-end. This is where the action happens * * @access public * @since 1.0.0 * * @param array $args widget setting * @param array $instance saved values * @return void * */ public function widget($args, $instance) { if( isset( $args['id'] )){ $supernews_sidebar_id = $args['id']; } else{ $supernews_sidebar_id = 'supernews-home'; } $instance = wp_parse_args( (array) $instance, $this->defaults); $supernews_selected_cat = esc_attr( $instance['supernews_cat'] ); /*Main title*/ $supernews_col_posts_title = !empty( $instance['supernews_cat_title'] ) ? esc_attr( $instance['supernews_cat_title'] ) : get_cat_name($supernews_selected_cat); $supernews_col_posts_title = apply_filters( 'widget_title', $supernews_col_posts_title, $instance, $this->id_base ); $supernews_enable_posts_featured = esc_attr( $instance['supernews_enable_posts_featured'] ); /*first featured post layout*/ $supernews_post_col_first_featured_image_layout = esc_attr( $instance['supernews_post_col_first_featured_image_layout'] ); /*normal featured image*/ $supernews_post_col_normal_image_layout = esc_attr( $instance['supernews_post_col_normal_image_layout'] ); /** * Filter the arguments for the Recent Posts widget. * * @since 1.0.0 * * @see WP_Query * */ $supernews_number = 32; $supernews_cat_post_args = array( 'posts_per_page' => $supernews_number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true ); if( -1 != $supernews_selected_cat ){ $supernews_cat_post_args['cat'] = $supernews_selected_cat; } $supernews_featured_query = new WP_Query($supernews_cat_post_args); if ($supernews_featured_query->have_posts()) : echo $args['before_widget']; if ( !empty( $supernews_col_posts_title ) ){ if( -1 != $supernews_selected_cat ){ echo "<div class='at-cat-color-wrap-".$supernews_selected_cat."'>"; } echo $args['before_title'] . $supernews_col_posts_title . $args['after_title']; if( -1 != $supernews_selected_cat ){ echo "</div>"; } } $supernews_post_col_layout_class = ''; if( 1 == $supernews_enable_posts_featured ){ $supernews_post_col_layout_class = ' featured-posts'; } ?> <div class="featured-entries-col <?php echo esc_attr( $supernews_post_col_layout_class ); ?> <?php echo esc_attr( $supernews_sidebar_id ); ?>"> <?php $supernews_featured_index = 1; while ( $supernews_featured_query->have_posts() ) :$supernews_featured_query->the_post(); $thumb = $supernews_post_col_normal_image_layout; $supernews_list_classes = 'acme-col-2'; $supernews_words = 21; if( $supernews_featured_index % 2 == 1 ){ echo "<div class='clearfix'></div>"; $supernews_list_classes .= ' odd'; } if( 1 == $supernews_enable_posts_featured ){ if( $supernews_featured_index <= 2 ){ $supernews_list_classes .= ' first-two'; $thumb = $supernews_post_col_first_featured_image_layout; } else{ $supernews_list_classes .= ' small-posts'; $thumb = $supernews_post_col_normal_image_layout; } } ?> <div class="<?php echo esc_attr( $supernews_list_classes ); ?>"> <!--post thumbnal options--> <div class="post-thumb"> <a href="<?php the_permalink(); ?>"> <?php if( has_post_thumbnail() ): the_post_thumbnail( $thumb ); else: ?> <div class="no-image-widgets"> <?php the_title( sprintf( '<h2 class="caption-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); if( !get_the_title() ){ the_date( '', sprintf( '<h2 class="caption-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); } ?> </div> <?php endif; ?> </a> <?php if(1 == $supernews_enable_posts_featured ){ if( $supernews_featured_index <= 2 ){ supernews_list_category(); } } else{ supernews_list_category(); } ?> </div><!-- .post-thumb--> <div class="post-content"> <div class="entry-header"> <?php the_title( sprintf( '<h3 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h3>' ); ?> <div class="entry-meta"> <?php if ( 'post' === get_post_type() ) : supernews_posted_on(); endif; supernews_entry_footer(); ?> </div><!-- .entry-meta --> </div><!-- .entry-header --> <?php if(1 == $supernews_enable_posts_featured ){ if( $supernews_featured_index <= 2 ){ ?> <div class="entry-content"> <?php $content = supernews_words_count( get_the_excerpt(), $supernews_words ); echo '<div class="details">'.esc_html( $content ).'</div>'; ?> </div><!-- .entry-content --> <?php } } else{ ?> <div class="entry-content"> <?php $content = supernews_words_count( get_the_excerpt(), $supernews_words ); echo '<div class="details">'.esc_html( $content ).do_shortcode('[post-views]'),'</div>'; ?> </div><!-- .entry-content --> <?php } ?> </div> </div> <?php $supernews_featured_index++; endwhile; ?> </div> <?php echo $args['after_widget']; echo "<div class='clearfix'></div>"; // Reset the global $the_post as this query will have stomped on it wp_reset_postdata(); endif; } } } if ( ! function_exists( 'supernews_posts_col' ) ) : /** * Function to Register and load the widget * * @since 1.0.0 * * @param null * @return void * */ function supernews_posts_col() { register_widget( 'Supernews_posts_col' ); } endif; add_action( 'widgets_init', 'supernews_posts_col' ); ```
Correcting the answer given by Max. To use this approach, the filter you need is [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) because your string is translated via `_x()` not `__()`. Note that the filtered argument passed is the **translation**, so you should check the source string (`$text` and `$context`) to ensure you're filtering the correct item. ``` add_filter( 'gettext_with_context', 'added_translation', 20, 4 ); function added_translation( $translation, $text, $context, $domain ) { if( 'Aside' === $text && 'Post format' === $context ){ $translation = 'Aan de kant'; } return $translation; } ``` Up to you exactly how you detect the string and whether you also check to see if Dutch is the current locale. However this filter does work and should work regardless if the theme you're using. If you're making a lot of string improvements I recommend using a translation file loaded **in addition** to the installed translations. [Example guide here](https://localise.biz/wordpress/plugin/custom-translations) using Loco Translate to add your own custom file. (Disclosure: my plugin)
313,848
<p>Please I have a very slow query on my wordpress search, checking the processes it takes upto 40sec to execute using <code>SHOW FULL PROCESSLIST;</code> below is a sample of query</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '%Industreet%') OR (wp_posts.post_excerpt LIKE '%Industreet%') OR (wp_posts.post_content LIKE '%Industreet%'))) AND (wp_posts.post_password = '') AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_title LIKE '%Industreet%' DESC, wp_posts.post_date DESC LIMIT 0, 25 </code></pre> <p>I have tried my best to fix this, but nothing is working out. though I have a total post of 120k on my site. I really need help.</p> <p>Thanks in advance</p>
[ { "answer_id": 320315, "author": "markdwhite", "author_id": 106523, "author_profile": "https://wordpress.stackexchange.com/users/106523", "pm_score": 2, "selected": true, "text": "<p>This is the query generated by the internal search function on Wordpress.</p>\n\n<p>It is criticised for being inefficient, and there are a few drop-in replacements available as plugins. You may be able to find something that helps you by doing more research around these. For example:</p>\n\n<p><a href=\"https://themeisle.com/blog/improve-internal-search-in-wordpress/\" rel=\"nofollow noreferrer\">https://themeisle.com/blog/improve-internal-search-in-wordpress/</a></p>\n\n<p><a href=\"https://winningwp.com/best-wordpress-search-plugins/\" rel=\"nofollow noreferrer\">https://winningwp.com/best-wordpress-search-plugins/</a></p>\n\n<p>I don't have a specific recommendation to offer as I'm just digging into this myself, hence having to link elsewhere.</p>\n" }, { "answer_id": 331064, "author": "WowPress.host", "author_id": 135591, "author_profile": "https://wordpress.stackexchange.com/users/135591", "pm_score": 0, "selected": false, "text": "<p>Search functionality WordPress queries are slow by it's nature unfortunately, since it can use only SQL and it's not designed for full-text searches. The only working solution when your database becomes large enough is to use search engine software instead and call it from inside WordPress using some plugin.</p>\n\n<p>One another free drop-in replacement we've made is <a href=\"https://wordpress.org/plugins/wow-fulltext-search/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wow-fulltext-search/</a></p>\n" } ]
2018/09/11
[ "https://wordpress.stackexchange.com/questions/313848", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128519/" ]
Please I have a very slow query on my wordpress search, checking the processes it takes upto 40sec to execute using `SHOW FULL PROCESSLIST;` below is a sample of query ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '%Industreet%') OR (wp_posts.post_excerpt LIKE '%Industreet%') OR (wp_posts.post_content LIKE '%Industreet%'))) AND (wp_posts.post_password = '') AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_title LIKE '%Industreet%' DESC, wp_posts.post_date DESC LIMIT 0, 25 ``` I have tried my best to fix this, but nothing is working out. though I have a total post of 120k on my site. I really need help. Thanks in advance
This is the query generated by the internal search function on Wordpress. It is criticised for being inefficient, and there are a few drop-in replacements available as plugins. You may be able to find something that helps you by doing more research around these. For example: <https://themeisle.com/blog/improve-internal-search-in-wordpress/> <https://winningwp.com/best-wordpress-search-plugins/> I don't have a specific recommendation to offer as I'm just digging into this myself, hence having to link elsewhere.
313,884
<p>I am having an issue with my WordPress nav menu. It is currently looking like this : <a href="https://i.stack.imgur.com/lvxTm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lvxTm.png" alt="Wordpress Problem"></a></p> <p>I am trying to make my bootstrap 3.3.7 (think that's the right version) menu work and that is the error. The line of code i am using is:</p> <pre><code>&lt;?php wp_nav_menu(array( 'theme-location' =&gt; 'main_menu' ) ); ?&gt; </code></pre> <p>and my <code>functions.php</code> has this code:</p> <pre><code>function register_my_menus() { register_nav_menus( array( 'main_menu' =&gt; __( 'Primary Menu' ), 'footer_menu' =&gt; __('Footer Menu') ); ) } add_action( 'init', 'register_my_menus' ); </code></pre> <p>I have read that the problem can be solved with walkernav but when trying to use it, it does not work any help?</p> <p>EDIT: My Header.php </p> <pre><code>&lt;nav class="navbar navbar-default" role="navigation"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar top-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar middle-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar bottom-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="&lt;?php coldstar_the_page_link( 'front-page.php' ); ?&gt;"&gt; &lt;img src="&lt;?php bloginfo('template_url'); ?&gt;/images/companylogo.png" class="img-responsive hidden-md" alt="Bed Centre Grimsby Logo"&gt; &lt;img src="&lt;?php bloginfo('template_url'); ?&gt;/images/logo.png" class="img-responsive hidden-lg hidden-sm hidden-xs" alt=""&gt; &lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="navbar-collapse collapse"&gt; &lt;ul class="top-contact hidden-xs hidden-sm"&gt; &lt;li class="phone"&gt; &lt;span class="icon"&gt;&lt;/span&gt; 01472 267660 &lt;/li&gt; &lt;li class="email"&gt; &lt;span class="icon"&gt;&lt;/span&gt; &lt;a href="mailto:[email protected]"&gt;[email protected]&lt;/a&gt; &lt;/li&gt; &lt;li class="facebook"&gt; &lt;a href="https://www.facebook.com/Bedcentregrimsby/" target="_blank"&gt;&lt;img src="http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png"&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class="nav navbar-nav navbar-right"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'depth' =&gt; 1, // 1 = with dropdowns, 0 = no dropdowns. 'container' =&gt; 'div', 'container_class' =&gt; 'collapse navbar-collapse', 'container_id' =&gt; 'bs-example-navbar-collapse-1', 'menu_class' =&gt; 'navbar-nav mr-auto', 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', 'walker' =&gt; new WP_Bootstrap_Navwalker() ) ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- END container --&gt; &lt;/nav&gt; &lt;div class="feature-nav"&gt; &lt;div class="container"&gt; &lt;div class="col-xs-12 col-sm-4 col-md-4 delivery"&gt; &lt;div class="icon"&gt;&lt;/div&gt; &lt;div class="text"&gt; &lt;p&gt;FREE Local Delivery&lt;span&gt;We deliver for FREE within a distance of 8 miles.&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-4 col-md-4 parking"&gt; &lt;div class="icon"&gt;&lt;/div&gt; &lt;div class="text"&gt; &lt;p&gt;FREE Parking&lt;span&gt;Our carpark is free for our customers.&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-4 col-md-4 disability"&gt; &lt;div class="icon"&gt;&lt;/div&gt; &lt;div class="text"&gt; &lt;p&gt;Wheelchair Friendly&lt;span&gt;Our store is accessible for wheelchairs. &lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>EDIT2: This is how it should perform in html</p> <pre><code>&lt;nav class="navbar navbar-default" role="navigation"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar top-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar middle-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar bottom-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="&lt;?php coldstar_the_page_link( 'front-page.php' ); ?&gt;"&gt; &lt;img src="&lt;?php bloginfo('template_url'); ?&gt;/images/companylogo.png" class="img-responsive hidden-md" alt="Bed Centre Grimsby Logo"&gt; &lt;img src="&lt;?php bloginfo('template_url'); ?&gt;/images/logo.png" class="img-responsive hidden-lg hidden-sm hidden-xs" alt=""&gt; &lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="navbar-collapse collapse"&gt; &lt;ul class="top-contact hidden-xs hidden-sm"&gt; &lt;li class="phone"&gt; &lt;span class="icon"&gt;&lt;/span&gt; 01472 267660 &lt;/li&gt; &lt;li class="email"&gt; &lt;span class="icon"&gt;&lt;/span&gt; &lt;a href="mailto:[email protected]"&gt;[email protected]&lt;/a&gt; &lt;/li&gt; &lt;li class="facebook"&gt; &lt;a href="https://www.facebook.com/Bedcentregrimsby/" target="_blank"&gt;&lt;img src="http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png"&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li class="current"&gt;&lt;a href="localhost:81"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/about-us"&gt;About Us&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;Our Products&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Bedsteads&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Bedsteads&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Bedsteads&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Bedsteads&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Bedsteads&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Bedsteads&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="/bed-guide"&gt;Bed Guide&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/reviews"&gt;Reviews&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/news"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/contact-us"&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre>
[ { "answer_id": 313891, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You have implemented the menu in wrong way, that's why it's not working.</p>\n\n<p>WordPress has provided a detailed documentation on creating menu. You have to go through that first.\n<a href=\"https://developer.wordpress.org/themes/functionality/navigation-menus/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/functionality/navigation-menus/</a></p>\n\n<p>After implementing that properly then go for walker class. I have not worked with bootstrap 3.3.7 but letting you know that bootstap 4x works fine, seems you have the walker class for version 3x.. you can use that.</p>\n\n<p>Use below link for Bootstrap 4x:\n<a href=\"https://github.com/wp-bootstrap/wp-bootstrap-navwalker\" rel=\"nofollow noreferrer\">https://github.com/wp-bootstrap/wp-bootstrap-navwalker</a></p>\n\n<p>Here is a tutorial :\n<a href=\"https://code.tutsplus.com/tutorials/how-to-integrate-a-bootstrap-navbar-into-a-wordpress-theme--wp-33410\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-integrate-a-bootstrap-navbar-into-a-wordpress-theme--wp-33410</a></p>\n\n<pre><code>&lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', \n 'depth' =&gt; 1, \n 'container' =&gt; 'div', \n 'container_class' =&gt; 'collapse navbar-collapse', \n 'container_id' =&gt; 'bs-example-navbar-collapse-1', \n 'menu_class' =&gt; 'navbar-nav mr-auto', \n 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', \n 'walker' =&gt; new WP_Bootstrap_Navwalker() ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 313920, "author": "benny-ben", "author_id": 135157, "author_profile": "https://wordpress.stackexchange.com/users/135157", "pm_score": 2, "selected": false, "text": "<p>You can try this way:</p>\n\n<pre><code>&lt;nav class=\"navbar navbar-default\" role=\"navigation\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"navbar-header\"&gt;\n\n &lt;button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\"&gt;\n &lt;span class=\"sr-only\"&gt;Toggle navigation&lt;/span&gt;\n &lt;span class=\"icon-bar top-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar middle-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar bottom-bar\"&gt;&lt;/span&gt;\n &lt;/button&gt;\n\n &lt;a class=\"navbar-brand\" href=\"&lt;?php coldstar_the_page_link( 'front-page.php' ); ?&gt;\"&gt;\n &lt;img src=\"&lt;?php bloginfo('template_url'); ?&gt;/images/companylogo.png\" class=\"img-responsive hidden-md\" alt=\"Bed Centre Grimsby Logo\"&gt;\n &lt;img src=\"&lt;?php bloginfo('template_url'); ?&gt;/images/logo.png\" class=\"img-responsive hidden-lg hidden-sm hidden-xs\" alt=\"\"&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n\n &lt;div id=\"navbar\" class=\"navbar-collapse collapse\"&gt;\n &lt;ul class=\"top-contact hidden-xs hidden-sm\"&gt;\n &lt;li class=\"phone\"&gt;\n &lt;span class=\"icon\"&gt;&lt;/span&gt;\n 01472 267660\n &lt;/li&gt;\n &lt;li class=\"email\"&gt;\n &lt;span class=\"icon\"&gt;&lt;/span&gt; &lt;a href=\"mailto:[email protected]\"&gt;[email protected]&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=\"facebook\"&gt;\n &lt;a href=\"https://www.facebook.com/Bedcentregrimsby/\" target=\"_blank\"&gt;&lt;img src=\"http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png\"&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;?php\n wp_nav_menu( array(\n 'container' =&gt; false,\n 'menu_id' =&gt; 'joey-ireland',\n 'menu_class' =&gt; 'nav navbar-nav navbar-right',\n 'items_wrap' =&gt; '&lt;ul id=\"%1$s\" class=\"%2$s\"&gt;%3$s&lt;/ul&gt;',\n 'theme_location' =&gt; 'primary', // must match in register_nav_menus\n 'depth' =&gt; 5,\n 'fallback_cb' =&gt; false,\n 'walker' =&gt; new Joey_Bootstrap_Walker(),\n ));\n\nclass Joey_Bootstrap_Walker extends Walker_Nav_Menu {\n\n function start_lvl(&amp;$output, $depth = 0, $args = Array() ) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"\\n$indent&lt;ul class=\\\"dropdown-menu\\\"&gt;\\n\";\n }\n\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';\n\n $has_child = false;\n if ( $args-&gt;walker-&gt;has_children !== false ) {\n $has_child = true;\n }\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );\n\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n\n // Check our custom has_children property.\n $class_drop = '';\n if ( $has_child ) {\n $class_drop = $class_names !== '' ? ' dropdown' : 'dropdown';\n }\n\n if ( $class_names ) {\n $class_names = ' class=\"' . esc_attr( $class_names ) . $class_drop . '\"';\n } else {\n $class_names = $class_drop !== '' ? ' class=\"' . $class_drop . '\"' : '';\n }\n\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n $output .= $indent . '&lt;li' . $id . $class_names .'&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n if ( $has_child === true ) {\n $attributes .= ' class=\"dropdown-toggle\" data-toggle=\"dropdown\"';\n }\n\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n\n $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a'. $attributes .'&gt;';\n $item_output .= $args-&gt;link_before . $title . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n}\n ?&gt;\n\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/nav&gt;\n&lt;div class=\"feature-nav\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"col-xs-12 col-sm-4 col-md-4 delivery\"&gt;\n &lt;div class=\"icon\"&gt;&lt;/div&gt;\n &lt;div class=\"text\"&gt;\n &lt;p&gt;FREE Local Delivery&lt;span&gt;We deliver for FREE within a distance of 8 miles.&lt;/span&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-12 col-sm-4 col-md-4 parking\"&gt;\n &lt;div class=\"icon\"&gt;&lt;/div&gt;\n &lt;div class=\"text\"&gt;\n &lt;p&gt;FREE Parking&lt;span&gt;Our carpark is free for our customers.&lt;/span&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-12 col-sm-4 col-md-4 disability\"&gt;\n &lt;div class=\"icon\"&gt;&lt;/div&gt;\n &lt;div class=\"text\"&gt;\n &lt;p&gt;Wheelchair Friendly&lt;span&gt;Our store is accessible for wheelchairs. &lt;/span&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><br /><hr /></p>\n\n<p>For documentation, see here:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/register_nav_menu\" rel=\"nofollow noreferrer\">register_nav_menu</a> - <em>Registers a single custom Navigation Menu in the custom menu editor</em></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a> - <em>Displays a navigation menu.</em></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/\" rel=\"nofollow noreferrer\">Walker_Nav_Menu</a>: - <em>Core class used to implement an HTML list of nav menu items.</em>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/start_lvl/\" rel=\"nofollow noreferrer\">Walker::start_lvl</a> - <em>Starts the list before the elements are added.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/end_lvl/\" rel=\"nofollow noreferrer\">Walker::end_lvl</a> - <em>Ends the list of after the elements are added.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/start_el/\" rel=\"nofollow noreferrer\">Walker::start_el</a> - <em>Starts the element output.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/end_el/\" rel=\"nofollow noreferrer\">Walker::end_el</a> - <em>Ends the element output, if needed.</em></li>\n</ul></li>\n</ul>\n" } ]
2018/09/11
[ "https://wordpress.stackexchange.com/questions/313884", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150429/" ]
I am having an issue with my WordPress nav menu. It is currently looking like this : [![Wordpress Problem](https://i.stack.imgur.com/lvxTm.png)](https://i.stack.imgur.com/lvxTm.png) I am trying to make my bootstrap 3.3.7 (think that's the right version) menu work and that is the error. The line of code i am using is: ``` <?php wp_nav_menu(array( 'theme-location' => 'main_menu' ) ); ?> ``` and my `functions.php` has this code: ``` function register_my_menus() { register_nav_menus( array( 'main_menu' => __( 'Primary Menu' ), 'footer_menu' => __('Footer Menu') ); ) } add_action( 'init', 'register_my_menus' ); ``` I have read that the problem can be solved with walkernav but when trying to use it, it does not work any help? EDIT: My Header.php ``` <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <a class="navbar-brand" href="<?php coldstar_the_page_link( 'front-page.php' ); ?>"> <img src="<?php bloginfo('template_url'); ?>/images/companylogo.png" class="img-responsive hidden-md" alt="Bed Centre Grimsby Logo"> <img src="<?php bloginfo('template_url'); ?>/images/logo.png" class="img-responsive hidden-lg hidden-sm hidden-xs" alt=""> </a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="top-contact hidden-xs hidden-sm"> <li class="phone"> <span class="icon"></span> 01472 267660 </li> <li class="email"> <span class="icon"></span> <a href="mailto:[email protected]">[email protected]</a> </li> <li class="facebook"> <a href="https://www.facebook.com/Bedcentregrimsby/" target="_blank"><img src="http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png"></a> </li> </ul> <div class="nav navbar-nav navbar-right"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => 1, // 1 = with dropdowns, 0 = no dropdowns. 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'navbar-nav mr-auto', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker() ) ); ?> </div> </div> </div> <!-- END container --> </nav> <div class="feature-nav"> <div class="container"> <div class="col-xs-12 col-sm-4 col-md-4 delivery"> <div class="icon"></div> <div class="text"> <p>FREE Local Delivery<span>We deliver for FREE within a distance of 8 miles.</span></p> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 parking"> <div class="icon"></div> <div class="text"> <p>FREE Parking<span>Our carpark is free for our customers.</span></p> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 disability"> <div class="icon"></div> <div class="text"> <p>Wheelchair Friendly<span>Our store is accessible for wheelchairs. </span></p> </div> </div> </div> </div> ``` EDIT2: This is how it should perform in html ``` <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <a class="navbar-brand" href="<?php coldstar_the_page_link( 'front-page.php' ); ?>"> <img src="<?php bloginfo('template_url'); ?>/images/companylogo.png" class="img-responsive hidden-md" alt="Bed Centre Grimsby Logo"> <img src="<?php bloginfo('template_url'); ?>/images/logo.png" class="img-responsive hidden-lg hidden-sm hidden-xs" alt=""> </a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="top-contact hidden-xs hidden-sm"> <li class="phone"> <span class="icon"></span> 01472 267660 </li> <li class="email"> <span class="icon"></span> <a href="mailto:[email protected]">[email protected]</a> </li> <li class="facebook"> <a href="https://www.facebook.com/Bedcentregrimsby/" target="_blank"><img src="http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png"></a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="current"><a href="localhost:81">Home</a></li> <li><a href="/about-us">About Us</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Our Products</a> <ul class="dropdown-menu"> <li><a href="#">Bedsteads</a></li> <li><a href="#">Bedsteads</a></li> <li><a href="#">Bedsteads</a></li> <li><a href="#">Bedsteads</a></li> <li><a href="#">Bedsteads</a></li> <li><a href="#">Bedsteads</a></li> </ul> </li> <li><a href="/bed-guide">Bed Guide</a></li> <li><a href="/reviews">Reviews</a></li> <li><a href="/news">News</a></li> <li><a href="/contact-us">Contact Us</a></li> </ul> </div> </nav> ```
You can try this way: ``` <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <a class="navbar-brand" href="<?php coldstar_the_page_link( 'front-page.php' ); ?>"> <img src="<?php bloginfo('template_url'); ?>/images/companylogo.png" class="img-responsive hidden-md" alt="Bed Centre Grimsby Logo"> <img src="<?php bloginfo('template_url'); ?>/images/logo.png" class="img-responsive hidden-lg hidden-sm hidden-xs" alt=""> </a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="top-contact hidden-xs hidden-sm"> <li class="phone"> <span class="icon"></span> 01472 267660 </li> <li class="email"> <span class="icon"></span> <a href="mailto:[email protected]">[email protected]</a> </li> <li class="facebook"> <a href="https://www.facebook.com/Bedcentregrimsby/" target="_blank"><img src="http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png"></a> </li> </ul> <?php wp_nav_menu( array( 'container' => false, 'menu_id' => 'joey-ireland', 'menu_class' => 'nav navbar-nav navbar-right', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'theme_location' => 'primary', // must match in register_nav_menus 'depth' => 5, 'fallback_cb' => false, 'walker' => new Joey_Bootstrap_Walker(), )); class Joey_Bootstrap_Walker extends Walker_Nav_Menu { function start_lvl(&$output, $depth = 0, $args = Array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"dropdown-menu\">\n"; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = ( $depth ) ? str_repeat( $t, $depth ) : ''; $has_child = false; if ( $args->walker->has_children !== false ) { $has_child = true; } $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth ); $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); // Check our custom has_children property. $class_drop = ''; if ( $has_child ) { $class_drop = $class_names !== '' ? ' dropdown' : 'dropdown'; } if ( $class_names ) { $class_names = ' class="' . esc_attr( $class_names ) . $class_drop . '"'; } else { $class_names = $class_drop !== '' ? ' class="' . $class_drop . '"' : ''; } $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $class_names .'>'; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } if ( $has_child === true ) { $attributes .= ' class="dropdown-toggle" data-toggle="dropdown"'; } $title = apply_filters( 'the_title', $item->title, $item->ID ); $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . $title . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ?> </div> </div> </nav> <div class="feature-nav"> <div class="container"> <div class="col-xs-12 col-sm-4 col-md-4 delivery"> <div class="icon"></div> <div class="text"> <p>FREE Local Delivery<span>We deliver for FREE within a distance of 8 miles.</span></p> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 parking"> <div class="icon"></div> <div class="text"> <p>FREE Parking<span>Our carpark is free for our customers.</span></p> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 disability"> <div class="icon"></div> <div class="text"> <p>Wheelchair Friendly<span>Our store is accessible for wheelchairs. </span></p> </div> </div> </div> </div> ``` --- For documentation, see here: * [register\_nav\_menu](https://codex.wordpress.org/Function_Reference/register_nav_menu) - *Registers a single custom Navigation Menu in the custom menu editor* --- * [wp\_nav\_menu](https://developer.wordpress.org/reference/functions/wp_nav_menu/) - *Displays a navigation menu.* --- * [Walker\_Nav\_Menu](https://developer.wordpress.org/reference/classes/walker_nav_menu/): - *Core class used to implement an HTML list of nav menu items.* + [Walker::start\_lvl](https://developer.wordpress.org/reference/classes/walker_nav_menu/start_lvl/) - *Starts the list before the elements are added.* + [Walker::end\_lvl](https://developer.wordpress.org/reference/classes/walker_nav_menu/end_lvl/) - *Ends the list of after the elements are added.* + [Walker::start\_el](https://developer.wordpress.org/reference/classes/walker_nav_menu/start_el/) - *Starts the element output.* + [Walker::end\_el](https://developer.wordpress.org/reference/classes/walker_nav_menu/end_el/) - *Ends the element output, if needed.*
313,902
<p>I tried to develop a simple Wordpress plugin which shows a bootstrap modal and unfortunately I failed.</p> <p>The modal opens shortly but disappears directly again. This happens because the template Avada already loads something similar to Bootstrap. This leads to the conflict because Bootstrap is loaded multiple times.</p> <p>I have no solution for this problem. I would like to use Bootstrap in my plugin independent of the template used.</p> <p>If other plugin's developers included Bootstrap, every Bootstrap files will be loaded twice (or more). What if the user is using an old version of Bootstrap for a theme or a plugin?</p> <p>Is there any way to include Bootstrap the right way so it does not create a conflict? </p> <p>I hope you can help me.</p> <pre><code> &lt;?php /* * Plugin Name: Bootstrap Modal Test * Plugin URI: http:// * Description: This is a short description of what the plugin does. It's displayed in the WordPress admin area. * Version: 1.0.0 * Author: Test * Author URI: http:// */ function enqueue_scripts() { wp_register_script( 'bootstrap_js', plugins_url( 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js' ) ); wp_enqueue_script( 'bootstrap_js' ); wp_register_script( 'jQuery', plugins_url( 'https://code.jquery.com/jquery-3.3.1.slim.min.js' ) ); wp_enqueue_script( 'jQuery' ); } add_action( 'wp_enqueue_scripts', 'enqueue_scripts'); function enqueue_styles() { wp_enqueue_style( 'bootstrap_css', plugins_url('https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css') ); } add_action( 'wp_enqueue_scripts', 'enqueue_styles'); add_shortcode('modal_test', 'modal_test_frontend'); function modal_test_frontend() { ?&gt; &lt;div class="container"&gt; &lt;h2&gt;Modal Example&lt;/h2&gt; &lt;!-- Trigger the modal with a button --&gt; &lt;button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"&gt;Open Modal&lt;/button&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="myModal" role="dialog"&gt; &lt;div class="modal-dialog"&gt; &lt;!-- Modal content--&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt; &lt;h4 class="modal-title"&gt;Modal Header&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Some text in the modal.&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } </code></pre>
[ { "answer_id": 313891, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You have implemented the menu in wrong way, that's why it's not working.</p>\n\n<p>WordPress has provided a detailed documentation on creating menu. You have to go through that first.\n<a href=\"https://developer.wordpress.org/themes/functionality/navigation-menus/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/functionality/navigation-menus/</a></p>\n\n<p>After implementing that properly then go for walker class. I have not worked with bootstrap 3.3.7 but letting you know that bootstap 4x works fine, seems you have the walker class for version 3x.. you can use that.</p>\n\n<p>Use below link for Bootstrap 4x:\n<a href=\"https://github.com/wp-bootstrap/wp-bootstrap-navwalker\" rel=\"nofollow noreferrer\">https://github.com/wp-bootstrap/wp-bootstrap-navwalker</a></p>\n\n<p>Here is a tutorial :\n<a href=\"https://code.tutsplus.com/tutorials/how-to-integrate-a-bootstrap-navbar-into-a-wordpress-theme--wp-33410\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/tutorials/how-to-integrate-a-bootstrap-navbar-into-a-wordpress-theme--wp-33410</a></p>\n\n<pre><code>&lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', \n 'depth' =&gt; 1, \n 'container' =&gt; 'div', \n 'container_class' =&gt; 'collapse navbar-collapse', \n 'container_id' =&gt; 'bs-example-navbar-collapse-1', \n 'menu_class' =&gt; 'navbar-nav mr-auto', \n 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', \n 'walker' =&gt; new WP_Bootstrap_Navwalker() ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 313920, "author": "benny-ben", "author_id": 135157, "author_profile": "https://wordpress.stackexchange.com/users/135157", "pm_score": 2, "selected": false, "text": "<p>You can try this way:</p>\n\n<pre><code>&lt;nav class=\"navbar navbar-default\" role=\"navigation\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"navbar-header\"&gt;\n\n &lt;button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\"&gt;\n &lt;span class=\"sr-only\"&gt;Toggle navigation&lt;/span&gt;\n &lt;span class=\"icon-bar top-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar middle-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar bottom-bar\"&gt;&lt;/span&gt;\n &lt;/button&gt;\n\n &lt;a class=\"navbar-brand\" href=\"&lt;?php coldstar_the_page_link( 'front-page.php' ); ?&gt;\"&gt;\n &lt;img src=\"&lt;?php bloginfo('template_url'); ?&gt;/images/companylogo.png\" class=\"img-responsive hidden-md\" alt=\"Bed Centre Grimsby Logo\"&gt;\n &lt;img src=\"&lt;?php bloginfo('template_url'); ?&gt;/images/logo.png\" class=\"img-responsive hidden-lg hidden-sm hidden-xs\" alt=\"\"&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n\n &lt;div id=\"navbar\" class=\"navbar-collapse collapse\"&gt;\n &lt;ul class=\"top-contact hidden-xs hidden-sm\"&gt;\n &lt;li class=\"phone\"&gt;\n &lt;span class=\"icon\"&gt;&lt;/span&gt;\n 01472 267660\n &lt;/li&gt;\n &lt;li class=\"email\"&gt;\n &lt;span class=\"icon\"&gt;&lt;/span&gt; &lt;a href=\"mailto:[email protected]\"&gt;[email protected]&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=\"facebook\"&gt;\n &lt;a href=\"https://www.facebook.com/Bedcentregrimsby/\" target=\"_blank\"&gt;&lt;img src=\"http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png\"&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;?php\n wp_nav_menu( array(\n 'container' =&gt; false,\n 'menu_id' =&gt; 'joey-ireland',\n 'menu_class' =&gt; 'nav navbar-nav navbar-right',\n 'items_wrap' =&gt; '&lt;ul id=\"%1$s\" class=\"%2$s\"&gt;%3$s&lt;/ul&gt;',\n 'theme_location' =&gt; 'primary', // must match in register_nav_menus\n 'depth' =&gt; 5,\n 'fallback_cb' =&gt; false,\n 'walker' =&gt; new Joey_Bootstrap_Walker(),\n ));\n\nclass Joey_Bootstrap_Walker extends Walker_Nav_Menu {\n\n function start_lvl(&amp;$output, $depth = 0, $args = Array() ) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"\\n$indent&lt;ul class=\\\"dropdown-menu\\\"&gt;\\n\";\n }\n\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';\n\n $has_child = false;\n if ( $args-&gt;walker-&gt;has_children !== false ) {\n $has_child = true;\n }\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );\n\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n\n // Check our custom has_children property.\n $class_drop = '';\n if ( $has_child ) {\n $class_drop = $class_names !== '' ? ' dropdown' : 'dropdown';\n }\n\n if ( $class_names ) {\n $class_names = ' class=\"' . esc_attr( $class_names ) . $class_drop . '\"';\n } else {\n $class_names = $class_drop !== '' ? ' class=\"' . $class_drop . '\"' : '';\n }\n\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n $output .= $indent . '&lt;li' . $id . $class_names .'&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n if ( $has_child === true ) {\n $attributes .= ' class=\"dropdown-toggle\" data-toggle=\"dropdown\"';\n }\n\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n\n $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a'. $attributes .'&gt;';\n $item_output .= $args-&gt;link_before . $title . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n}\n ?&gt;\n\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/nav&gt;\n&lt;div class=\"feature-nav\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"col-xs-12 col-sm-4 col-md-4 delivery\"&gt;\n &lt;div class=\"icon\"&gt;&lt;/div&gt;\n &lt;div class=\"text\"&gt;\n &lt;p&gt;FREE Local Delivery&lt;span&gt;We deliver for FREE within a distance of 8 miles.&lt;/span&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-12 col-sm-4 col-md-4 parking\"&gt;\n &lt;div class=\"icon\"&gt;&lt;/div&gt;\n &lt;div class=\"text\"&gt;\n &lt;p&gt;FREE Parking&lt;span&gt;Our carpark is free for our customers.&lt;/span&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-12 col-sm-4 col-md-4 disability\"&gt;\n &lt;div class=\"icon\"&gt;&lt;/div&gt;\n &lt;div class=\"text\"&gt;\n &lt;p&gt;Wheelchair Friendly&lt;span&gt;Our store is accessible for wheelchairs. &lt;/span&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><br /><hr /></p>\n\n<p>For documentation, see here:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/register_nav_menu\" rel=\"nofollow noreferrer\">register_nav_menu</a> - <em>Registers a single custom Navigation Menu in the custom menu editor</em></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a> - <em>Displays a navigation menu.</em></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/\" rel=\"nofollow noreferrer\">Walker_Nav_Menu</a>: - <em>Core class used to implement an HTML list of nav menu items.</em>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/start_lvl/\" rel=\"nofollow noreferrer\">Walker::start_lvl</a> - <em>Starts the list before the elements are added.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/end_lvl/\" rel=\"nofollow noreferrer\">Walker::end_lvl</a> - <em>Ends the list of after the elements are added.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/start_el/\" rel=\"nofollow noreferrer\">Walker::start_el</a> - <em>Starts the element output.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/end_el/\" rel=\"nofollow noreferrer\">Walker::end_el</a> - <em>Ends the element output, if needed.</em></li>\n</ul></li>\n</ul>\n" } ]
2018/09/11
[ "https://wordpress.stackexchange.com/questions/313902", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150443/" ]
I tried to develop a simple Wordpress plugin which shows a bootstrap modal and unfortunately I failed. The modal opens shortly but disappears directly again. This happens because the template Avada already loads something similar to Bootstrap. This leads to the conflict because Bootstrap is loaded multiple times. I have no solution for this problem. I would like to use Bootstrap in my plugin independent of the template used. If other plugin's developers included Bootstrap, every Bootstrap files will be loaded twice (or more). What if the user is using an old version of Bootstrap for a theme or a plugin? Is there any way to include Bootstrap the right way so it does not create a conflict? I hope you can help me. ``` <?php /* * Plugin Name: Bootstrap Modal Test * Plugin URI: http:// * Description: This is a short description of what the plugin does. It's displayed in the WordPress admin area. * Version: 1.0.0 * Author: Test * Author URI: http:// */ function enqueue_scripts() { wp_register_script( 'bootstrap_js', plugins_url( 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js' ) ); wp_enqueue_script( 'bootstrap_js' ); wp_register_script( 'jQuery', plugins_url( 'https://code.jquery.com/jquery-3.3.1.slim.min.js' ) ); wp_enqueue_script( 'jQuery' ); } add_action( 'wp_enqueue_scripts', 'enqueue_scripts'); function enqueue_styles() { wp_enqueue_style( 'bootstrap_css', plugins_url('https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css') ); } add_action( 'wp_enqueue_scripts', 'enqueue_styles'); add_shortcode('modal_test', 'modal_test_frontend'); function modal_test_frontend() { ?> <div class="container"> <h2>Modal Example</h2> <!-- Trigger the modal with a button --> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <?php } ```
You can try this way: ``` <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <a class="navbar-brand" href="<?php coldstar_the_page_link( 'front-page.php' ); ?>"> <img src="<?php bloginfo('template_url'); ?>/images/companylogo.png" class="img-responsive hidden-md" alt="Bed Centre Grimsby Logo"> <img src="<?php bloginfo('template_url'); ?>/images/logo.png" class="img-responsive hidden-lg hidden-sm hidden-xs" alt=""> </a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="top-contact hidden-xs hidden-sm"> <li class="phone"> <span class="icon"></span> 01472 267660 </li> <li class="email"> <span class="icon"></span> <a href="mailto:[email protected]">[email protected]</a> </li> <li class="facebook"> <a href="https://www.facebook.com/Bedcentregrimsby/" target="_blank"><img src="http://beta.bedcentregrimsby.co.uk/wp-content/themes/bedcentregrimsby/assets/images/facebook-logo.png"></a> </li> </ul> <?php wp_nav_menu( array( 'container' => false, 'menu_id' => 'joey-ireland', 'menu_class' => 'nav navbar-nav navbar-right', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'theme_location' => 'primary', // must match in register_nav_menus 'depth' => 5, 'fallback_cb' => false, 'walker' => new Joey_Bootstrap_Walker(), )); class Joey_Bootstrap_Walker extends Walker_Nav_Menu { function start_lvl(&$output, $depth = 0, $args = Array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"dropdown-menu\">\n"; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = ( $depth ) ? str_repeat( $t, $depth ) : ''; $has_child = false; if ( $args->walker->has_children !== false ) { $has_child = true; } $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth ); $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); // Check our custom has_children property. $class_drop = ''; if ( $has_child ) { $class_drop = $class_names !== '' ? ' dropdown' : 'dropdown'; } if ( $class_names ) { $class_names = ' class="' . esc_attr( $class_names ) . $class_drop . '"'; } else { $class_names = $class_drop !== '' ? ' class="' . $class_drop . '"' : ''; } $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $class_names .'>'; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } if ( $has_child === true ) { $attributes .= ' class="dropdown-toggle" data-toggle="dropdown"'; } $title = apply_filters( 'the_title', $item->title, $item->ID ); $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . $title . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ?> </div> </div> </nav> <div class="feature-nav"> <div class="container"> <div class="col-xs-12 col-sm-4 col-md-4 delivery"> <div class="icon"></div> <div class="text"> <p>FREE Local Delivery<span>We deliver for FREE within a distance of 8 miles.</span></p> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 parking"> <div class="icon"></div> <div class="text"> <p>FREE Parking<span>Our carpark is free for our customers.</span></p> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 disability"> <div class="icon"></div> <div class="text"> <p>Wheelchair Friendly<span>Our store is accessible for wheelchairs. </span></p> </div> </div> </div> </div> ``` --- For documentation, see here: * [register\_nav\_menu](https://codex.wordpress.org/Function_Reference/register_nav_menu) - *Registers a single custom Navigation Menu in the custom menu editor* --- * [wp\_nav\_menu](https://developer.wordpress.org/reference/functions/wp_nav_menu/) - *Displays a navigation menu.* --- * [Walker\_Nav\_Menu](https://developer.wordpress.org/reference/classes/walker_nav_menu/): - *Core class used to implement an HTML list of nav menu items.* + [Walker::start\_lvl](https://developer.wordpress.org/reference/classes/walker_nav_menu/start_lvl/) - *Starts the list before the elements are added.* + [Walker::end\_lvl](https://developer.wordpress.org/reference/classes/walker_nav_menu/end_lvl/) - *Ends the list of after the elements are added.* + [Walker::start\_el](https://developer.wordpress.org/reference/classes/walker_nav_menu/start_el/) - *Starts the element output.* + [Walker::end\_el](https://developer.wordpress.org/reference/classes/walker_nav_menu/end_el/) - *Ends the element output, if needed.*
313,934
<p>Please see my shortcode script below (which is intended to print the next 15 minute time interval, eg if the current time is 9:01pm, it would print 9:15pm).</p> <p>I have managed to produce the correct output, however because I am <code>echo</code>ing the <code>&lt;span id="webinartime"&gt;&lt;/span&gt;</code> HTML, the dynamic content is showing up at the top of my WordPress content area, not in the location I type the shortcode.</p> <p>I understand after reading that I need to <code>return</code> my value to get it to appear in the right place... However, <code>return</code>ing ends the function, and so I miss out on including the javascript that will ultimately insert my correct time value (the javascript is necessary to retrieve the user's local time).</p> <p>I'm wondering if there is a way to have two functions in the shortcode, or nest them somehow... change my approach, etc?</p> <pre><code>&lt;?php add_shortcode( 'now_plus_15_min', 'now_plus_15_min' ); function now_plus_15_min() { // get current date &amp; time $current_date = date('d-M-Y g:i:s A'); $current_time = strtotime($current_date); // create new date &amp; time that is the nearest next 15 minute interval $frac = 900; $r = $current_time % $frac; $new_time = $current_time + ($frac-$r); $new_date = date('d-M-Y g:i:s A', $new_time); // insert HTML which will be later affected by javascript // this part is the issue! I need to return this, not echo... // but returning ends the function before javascript can be run... echo '&lt;span id="webinartime"&gt;&lt;/span&gt;'; echo "\n"; // Modify the PHP new date &amp; time to match the user's local time // and insert it into above HTML echo "&lt;script&gt; var date = new Date('" . $new_date . " UTC'); var NextWebinarTime = date.toLocaleString(); console.log(NextWebinarTime); document.getElementById('webinartime').innerHTML = NextWebinarTime; &lt;/script&gt; "; } ?&gt; </code></pre>
[ { "answer_id": 313935, "author": "Jazibobs", "author_id": 37192, "author_profile": "https://wordpress.stackexchange.com/users/37192", "pm_score": 3, "selected": true, "text": "<p>What you should do is create a variable to store all of the HTML data you wish to output with your shortcode then use <code>return</code>. Your code would look something like this: </p>\n\n<pre><code>&lt;?php\n// insert HTML which will be later affected by javascript\n// this part is the issue! I need to return this, not echo...\n// but returning ends the function before javascript can be run...\n$html_out = '&lt;span id=\"webinartime\"&gt;&lt;/span&gt;';\n$html_out .= \"\\n\";\n\n// Modify the PHP new date &amp; time to match the user's local time\n// and insert it into above HTML\n$html_out .= \"&lt;script&gt;\nvar date = new Date('\" . $new_date . \" UTC');\nvar NextWebinarTime = date.toLocaleString();\nconsole.log(NextWebinarTime);\ndocument.getElementById('webinartime').innerHTML = NextWebinarTime;\n&lt;/script&gt;\n\";\n\nreturn $html_out;\n\n}\n?&gt;\n</code></pre>\n\n<p>However, if you require JavaScript as part of your response the best WordPress practice would be to enqueue the script. You can learn more about that here:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a></p>\n\n<p>Moreover, as another user has already pointed out there is no need to make use of JavaScript for this shortcode. PHP is more than capable of completing all of the required calculations you need to output to the user.</p>\n" }, { "answer_id": 313936, "author": "Rajesh Kakkad", "author_id": 147821, "author_profile": "https://wordpress.stackexchange.com/users/147821", "pm_score": -1, "selected": false, "text": "<p>Result of shortcode will appear after entire code of that shortcode is processed. \n<p>PHP can do what you are trying to do through javascript as it is just adding information to an element. As both calculations are ready through PHP processing, you can just echo full 'webinartime' element without handing over that job to javascript. From your content where you used the element div or span etc, you can remove from there and let the PHP code display it already filled with the calculations.\n<p>Hope I understood your situation right from your description.</p>\n" }, { "answer_id": 313938, "author": "ville6000", "author_id": 62041, "author_profile": "https://wordpress.stackexchange.com/users/62041", "pm_score": 1, "selected": false, "text": "<p>Add <code>ob_start()</code> on top your function and add <code>return ob_get_clean()</code> at the last row of your function.</p>\n\n<pre><code>function this_is_example() {\n ob_start();\n echo \"stuff\";\n return ob_get_clean();\n}\n</code></pre>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/313934", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10663/" ]
Please see my shortcode script below (which is intended to print the next 15 minute time interval, eg if the current time is 9:01pm, it would print 9:15pm). I have managed to produce the correct output, however because I am `echo`ing the `<span id="webinartime"></span>` HTML, the dynamic content is showing up at the top of my WordPress content area, not in the location I type the shortcode. I understand after reading that I need to `return` my value to get it to appear in the right place... However, `return`ing ends the function, and so I miss out on including the javascript that will ultimately insert my correct time value (the javascript is necessary to retrieve the user's local time). I'm wondering if there is a way to have two functions in the shortcode, or nest them somehow... change my approach, etc? ``` <?php add_shortcode( 'now_plus_15_min', 'now_plus_15_min' ); function now_plus_15_min() { // get current date & time $current_date = date('d-M-Y g:i:s A'); $current_time = strtotime($current_date); // create new date & time that is the nearest next 15 minute interval $frac = 900; $r = $current_time % $frac; $new_time = $current_time + ($frac-$r); $new_date = date('d-M-Y g:i:s A', $new_time); // insert HTML which will be later affected by javascript // this part is the issue! I need to return this, not echo... // but returning ends the function before javascript can be run... echo '<span id="webinartime"></span>'; echo "\n"; // Modify the PHP new date & time to match the user's local time // and insert it into above HTML echo "<script> var date = new Date('" . $new_date . " UTC'); var NextWebinarTime = date.toLocaleString(); console.log(NextWebinarTime); document.getElementById('webinartime').innerHTML = NextWebinarTime; </script> "; } ?> ```
What you should do is create a variable to store all of the HTML data you wish to output with your shortcode then use `return`. Your code would look something like this: ``` <?php // insert HTML which will be later affected by javascript // this part is the issue! I need to return this, not echo... // but returning ends the function before javascript can be run... $html_out = '<span id="webinartime"></span>'; $html_out .= "\n"; // Modify the PHP new date & time to match the user's local time // and insert it into above HTML $html_out .= "<script> var date = new Date('" . $new_date . " UTC'); var NextWebinarTime = date.toLocaleString(); console.log(NextWebinarTime); document.getElementById('webinartime').innerHTML = NextWebinarTime; </script> "; return $html_out; } ?> ``` However, if you require JavaScript as part of your response the best WordPress practice would be to enqueue the script. You can learn more about that here: <https://developer.wordpress.org/reference/functions/wp_enqueue_script/> Moreover, as another user has already pointed out there is no need to make use of JavaScript for this shortcode. PHP is more than capable of completing all of the required calculations you need to output to the user.
313,951
<p>I tried uploading after installing different plugins. Even added a filter to functions.php file.</p> <pre><code> function add_svg_to_upload_mimes( $upload_mimes ) { $upload_mimes['svg'] = 'image/svg+xml'; $upload_mimes['svgz'] = 'image/svg+xml'; return $upload_mimes; } add_filter( 'upload_mimes', 'add_svg_to_upload_mimes', 10, 1 ); </code></pre> <p>But still uploading an SVG gives the following error. <a href="https://i.stack.imgur.com/Ulx1O.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Ulx1O.jpg" alt="SVG upload error"></a></p>
[ { "answer_id": 314050, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 4, "selected": true, "text": "<p>This question had me scratching my head. Yeah, how come WordPress doesn't support this natively? And then I found out. </p>\n\n<p>You asked how to upload SVG in WordPress 4.9.8 (the current version at the time of writing). You mention that you \"tried uploading after installing different plugins\". You don't say which plugins, nor whether they relate to SVG.</p>\n\n<p>As I understand the situation, the safest, most appropriate, answer at this time is to use <a href=\"https://wordpress.org/plugins/safe-svg/\" rel=\"noreferrer\">SVF Safe</a> (a plugin written for this very purpose) by Darrell Doyle. If this plugin doesn't work for you, then I'd suggest that you have a conflict elsewhere, and you should follow the usual procedures for resolving that. Personally, if this plugin didn't work for me then I'd give up on the notion of uploading SVGs.</p>\n\n<p>If you haven't already done so, may I suggest reading \"<a href=\"https://bjornjohansen.no/svg-in-wordpress\" rel=\"noreferrer\">SVG Uploads in WordPress - the inconvenient truth</a>\" by Bjorn Johansen and/or \"<a href=\"https://kinsta.com/blog/wordpress-svg/\" rel=\"noreferrer\">How to Safely Enable WordPress SVG Support - 2 Simple Clicks</a>\" by Brian Jackson. At least you should know what you are letting yourself in for.</p>\n" }, { "answer_id": 332088, "author": "Rana umer", "author_id": 163461, "author_profile": "https://wordpress.stackexchange.com/users/163461", "pm_score": 2, "selected": false, "text": "<pre><code>//add SVG to allowed file uploads\nfunction add_file_types_to_uploads($file_types){\n\n $new_filetypes = array();\n $new_filetypes['svg'] = 'image/svg+xml';\n $file_types = array_merge($file_types, $new_filetypes );\n\n return $file_types;\n}\nadd_action('upload_mimes', 'add_file_types_to_uploads');\n</code></pre>\n" }, { "answer_id": 343724, "author": "Suraj Rathod", "author_id": 141555, "author_profile": "https://wordpress.stackexchange.com/users/141555", "pm_score": 2, "selected": false, "text": "<p>After adding <strong>upload_mimes</strong> action still anyone facing issue then add this in your wp-config.php file</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n" }, { "answer_id": 345480, "author": "Syed Figar Ali Jaffri", "author_id": 67550, "author_profile": "https://wordpress.stackexchange.com/users/67550", "pm_score": 3, "selected": false, "text": "<p>@rana-umer your code is correct just remove the \"+xml\" after 'image/svg'.</p>\n\n<pre><code>//add SVG to allowed file uploads\nfunction add_file_types_to_uploads($file_types){\n\n $new_filetypes = array();\n $new_filetypes['svg'] = 'image/svg';\n $file_types = array_merge($file_types, $new_filetypes );\n\n return $file_types; \n} \nadd_action('upload_mimes', 'add_file_types_to_uploads');\n</code></pre>\n" }, { "answer_id": 366004, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>The first function is to check the WordPress and add support on WP version lower than 4.8. The second function is to register the mime file type(SVG) and the last one is to fix the thumbnails on media library.</p>\n\n<pre><code> /**\n * Add svg support\n *\n */\nadd_filter( 'wp_check_filetype_and_ext', function( $data, $file, $filename, $mimes) {\n global $wp_version;\n if( $wp_version == '4.7' || ( (float) $wp_version &lt; 4.7 ) ) {\n return $data;\n }\n $filetype = wp_check_filetype( $filename, $mimes );\n return [\n 'ext' =&gt; $filetype['ext'],\n 'type' =&gt; $filetype['type'],\n 'proper_filename' =&gt; $data['proper_filename']\n ];\n}, 10, 4 );\n\nfunction ns_mime_types( $mimes ){\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n}\nadd_filter( 'upload_mimes', 'ns_mime_types' );\n\nfunction ns_fix_svg() {\n echo '&lt;style type=\"text/css\"&gt;.attachment-266x266, .thumbnail img { width: 100% !important; height: auto !important;} &lt;/style&gt;';\n}\nadd_action( 'admin_head', 'ns_fix_svg' );\n</code></pre>\n" }, { "answer_id": 374781, "author": "Mr.Hosseini", "author_id": 147413, "author_profile": "https://wordpress.stackexchange.com/users/147413", "pm_score": 0, "selected": false, "text": "<p>Add this hooks , i tested on wp 5.3 it works :</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Allow SVG\nadd_filter('wp_check_filetype_and_ext', function ($data, $file, $filename, $mimes) {\n\n if (!$data['type']) {\n $wp_filetype = wp_check_filetype($filename, $mimes);\n $ext = $wp_filetype['ext'];\n $type = $wp_filetype['type'];\n $proper_filename = $filename;\n if ($type &amp;&amp; 0 === strpos($type, 'image/') &amp;&amp; $ext !== 'svg') {\n $ext = $type = false;\n }\n $data['ext'] = $ext;\n $data['type'] = $type;\n $data['proper_filename'] = $proper_filename;\n }\n return $data;\n\n\n}, 10, 4);\n\n\nadd_filter('upload_mimes', function ($mimes) {\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n});\n\n\nadd_action('admin_head', function () {\n echo '&lt;style type=&quot;text/css&quot;&gt;\n .media-icon img[src$=&quot;.svg&quot;], img[src$=&quot;.svg&quot;].attachment-post-thumbnail {\n width: 100% !important;\n height: auto !important;\n }&lt;/style&gt;';\n});\n</code></pre>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/313951", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101809/" ]
I tried uploading after installing different plugins. Even added a filter to functions.php file. ``` function add_svg_to_upload_mimes( $upload_mimes ) { $upload_mimes['svg'] = 'image/svg+xml'; $upload_mimes['svgz'] = 'image/svg+xml'; return $upload_mimes; } add_filter( 'upload_mimes', 'add_svg_to_upload_mimes', 10, 1 ); ``` But still uploading an SVG gives the following error. [![SVG upload error](https://i.stack.imgur.com/Ulx1O.jpg)](https://i.stack.imgur.com/Ulx1O.jpg)
This question had me scratching my head. Yeah, how come WordPress doesn't support this natively? And then I found out. You asked how to upload SVG in WordPress 4.9.8 (the current version at the time of writing). You mention that you "tried uploading after installing different plugins". You don't say which plugins, nor whether they relate to SVG. As I understand the situation, the safest, most appropriate, answer at this time is to use [SVF Safe](https://wordpress.org/plugins/safe-svg/) (a plugin written for this very purpose) by Darrell Doyle. If this plugin doesn't work for you, then I'd suggest that you have a conflict elsewhere, and you should follow the usual procedures for resolving that. Personally, if this plugin didn't work for me then I'd give up on the notion of uploading SVGs. If you haven't already done so, may I suggest reading "[SVG Uploads in WordPress - the inconvenient truth](https://bjornjohansen.no/svg-in-wordpress)" by Bjorn Johansen and/or "[How to Safely Enable WordPress SVG Support - 2 Simple Clicks](https://kinsta.com/blog/wordpress-svg/)" by Brian Jackson. At least you should know what you are letting yourself in for.
313,967
<p>I have a save post hook that looks like this, it should download youtube thumbnail to wp-includes/uploads base on video id provided. But it doesnt save anything.</p> <pre><code> add_filter( 'save_post', function () { $video_id = 'VSB4wGIdDwo'; $path_to_save_thumbnails = '/wp-includes/upload/'; $ch = curl_init(); $thubnail_types = array('0', '1', '2', '3','default', 'sddefault', 'mqdefault', 'hqdefault', 'maxresdefault'); foreach($thubnail_types as $type) { $youtube_thumb_url = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg'; echo "Downloading thumbnail [$type]." . PHP_EOL; curl_setopt($ch, CURLOPT_URL, $youtube_thumb_url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $image = curl_exec($ch); $info = curl_getinfo($ch); if($info['http_code'] == 200) { file_put_contents($path_to_save_thumbnails.$type.'.jpg', $image); } } }); </code></pre>
[ { "answer_id": 314050, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 4, "selected": true, "text": "<p>This question had me scratching my head. Yeah, how come WordPress doesn't support this natively? And then I found out. </p>\n\n<p>You asked how to upload SVG in WordPress 4.9.8 (the current version at the time of writing). You mention that you \"tried uploading after installing different plugins\". You don't say which plugins, nor whether they relate to SVG.</p>\n\n<p>As I understand the situation, the safest, most appropriate, answer at this time is to use <a href=\"https://wordpress.org/plugins/safe-svg/\" rel=\"noreferrer\">SVF Safe</a> (a plugin written for this very purpose) by Darrell Doyle. If this plugin doesn't work for you, then I'd suggest that you have a conflict elsewhere, and you should follow the usual procedures for resolving that. Personally, if this plugin didn't work for me then I'd give up on the notion of uploading SVGs.</p>\n\n<p>If you haven't already done so, may I suggest reading \"<a href=\"https://bjornjohansen.no/svg-in-wordpress\" rel=\"noreferrer\">SVG Uploads in WordPress - the inconvenient truth</a>\" by Bjorn Johansen and/or \"<a href=\"https://kinsta.com/blog/wordpress-svg/\" rel=\"noreferrer\">How to Safely Enable WordPress SVG Support - 2 Simple Clicks</a>\" by Brian Jackson. At least you should know what you are letting yourself in for.</p>\n" }, { "answer_id": 332088, "author": "Rana umer", "author_id": 163461, "author_profile": "https://wordpress.stackexchange.com/users/163461", "pm_score": 2, "selected": false, "text": "<pre><code>//add SVG to allowed file uploads\nfunction add_file_types_to_uploads($file_types){\n\n $new_filetypes = array();\n $new_filetypes['svg'] = 'image/svg+xml';\n $file_types = array_merge($file_types, $new_filetypes );\n\n return $file_types;\n}\nadd_action('upload_mimes', 'add_file_types_to_uploads');\n</code></pre>\n" }, { "answer_id": 343724, "author": "Suraj Rathod", "author_id": 141555, "author_profile": "https://wordpress.stackexchange.com/users/141555", "pm_score": 2, "selected": false, "text": "<p>After adding <strong>upload_mimes</strong> action still anyone facing issue then add this in your wp-config.php file</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n" }, { "answer_id": 345480, "author": "Syed Figar Ali Jaffri", "author_id": 67550, "author_profile": "https://wordpress.stackexchange.com/users/67550", "pm_score": 3, "selected": false, "text": "<p>@rana-umer your code is correct just remove the \"+xml\" after 'image/svg'.</p>\n\n<pre><code>//add SVG to allowed file uploads\nfunction add_file_types_to_uploads($file_types){\n\n $new_filetypes = array();\n $new_filetypes['svg'] = 'image/svg';\n $file_types = array_merge($file_types, $new_filetypes );\n\n return $file_types; \n} \nadd_action('upload_mimes', 'add_file_types_to_uploads');\n</code></pre>\n" }, { "answer_id": 366004, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>The first function is to check the WordPress and add support on WP version lower than 4.8. The second function is to register the mime file type(SVG) and the last one is to fix the thumbnails on media library.</p>\n\n<pre><code> /**\n * Add svg support\n *\n */\nadd_filter( 'wp_check_filetype_and_ext', function( $data, $file, $filename, $mimes) {\n global $wp_version;\n if( $wp_version == '4.7' || ( (float) $wp_version &lt; 4.7 ) ) {\n return $data;\n }\n $filetype = wp_check_filetype( $filename, $mimes );\n return [\n 'ext' =&gt; $filetype['ext'],\n 'type' =&gt; $filetype['type'],\n 'proper_filename' =&gt; $data['proper_filename']\n ];\n}, 10, 4 );\n\nfunction ns_mime_types( $mimes ){\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n}\nadd_filter( 'upload_mimes', 'ns_mime_types' );\n\nfunction ns_fix_svg() {\n echo '&lt;style type=\"text/css\"&gt;.attachment-266x266, .thumbnail img { width: 100% !important; height: auto !important;} &lt;/style&gt;';\n}\nadd_action( 'admin_head', 'ns_fix_svg' );\n</code></pre>\n" }, { "answer_id": 374781, "author": "Mr.Hosseini", "author_id": 147413, "author_profile": "https://wordpress.stackexchange.com/users/147413", "pm_score": 0, "selected": false, "text": "<p>Add this hooks , i tested on wp 5.3 it works :</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Allow SVG\nadd_filter('wp_check_filetype_and_ext', function ($data, $file, $filename, $mimes) {\n\n if (!$data['type']) {\n $wp_filetype = wp_check_filetype($filename, $mimes);\n $ext = $wp_filetype['ext'];\n $type = $wp_filetype['type'];\n $proper_filename = $filename;\n if ($type &amp;&amp; 0 === strpos($type, 'image/') &amp;&amp; $ext !== 'svg') {\n $ext = $type = false;\n }\n $data['ext'] = $ext;\n $data['type'] = $type;\n $data['proper_filename'] = $proper_filename;\n }\n return $data;\n\n\n}, 10, 4);\n\n\nadd_filter('upload_mimes', function ($mimes) {\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n});\n\n\nadd_action('admin_head', function () {\n echo '&lt;style type=&quot;text/css&quot;&gt;\n .media-icon img[src$=&quot;.svg&quot;], img[src$=&quot;.svg&quot;].attachment-post-thumbnail {\n width: 100% !important;\n height: auto !important;\n }&lt;/style&gt;';\n});\n</code></pre>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/313967", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150431/" ]
I have a save post hook that looks like this, it should download youtube thumbnail to wp-includes/uploads base on video id provided. But it doesnt save anything. ``` add_filter( 'save_post', function () { $video_id = 'VSB4wGIdDwo'; $path_to_save_thumbnails = '/wp-includes/upload/'; $ch = curl_init(); $thubnail_types = array('0', '1', '2', '3','default', 'sddefault', 'mqdefault', 'hqdefault', 'maxresdefault'); foreach($thubnail_types as $type) { $youtube_thumb_url = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg'; echo "Downloading thumbnail [$type]." . PHP_EOL; curl_setopt($ch, CURLOPT_URL, $youtube_thumb_url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $image = curl_exec($ch); $info = curl_getinfo($ch); if($info['http_code'] == 200) { file_put_contents($path_to_save_thumbnails.$type.'.jpg', $image); } } }); ```
This question had me scratching my head. Yeah, how come WordPress doesn't support this natively? And then I found out. You asked how to upload SVG in WordPress 4.9.8 (the current version at the time of writing). You mention that you "tried uploading after installing different plugins". You don't say which plugins, nor whether they relate to SVG. As I understand the situation, the safest, most appropriate, answer at this time is to use [SVF Safe](https://wordpress.org/plugins/safe-svg/) (a plugin written for this very purpose) by Darrell Doyle. If this plugin doesn't work for you, then I'd suggest that you have a conflict elsewhere, and you should follow the usual procedures for resolving that. Personally, if this plugin didn't work for me then I'd give up on the notion of uploading SVGs. If you haven't already done so, may I suggest reading "[SVG Uploads in WordPress - the inconvenient truth](https://bjornjohansen.no/svg-in-wordpress)" by Bjorn Johansen and/or "[How to Safely Enable WordPress SVG Support - 2 Simple Clicks](https://kinsta.com/blog/wordpress-svg/)" by Brian Jackson. At least you should know what you are letting yourself in for.
313,975
<p>I have this mail notification for new post.</p> <p>All the new post contain arround 100 words and no pictures, so I would like to include in the notification the post content and if is possible, the number of words in the post.</p> <p>Anybody could help me? </p> <p>Thanks for all</p> <pre><code> /* avisar al admin*/ function submit_send_email ($post) { $user_info = get_userdata ($post-&gt;post_author); $strTo = array ('[email protected]'); $strSubject = 'Your website name: ' . $user_info-&gt;user_nicename . ' submitted a post'; $strMessage = 'A post "' . $post-&gt;post_title . '" by ' . $user_info-&gt;user_nicename . ' was submitted for review at ' . wp_get_shortlink ($post-&gt;ID) . '&amp;preview=true. Please proof.'; wp_mail( $strTo, $strSubject, $strMessage ); } add_action('future_to_pending', 'submit_send_email'); add_action('new_to_pending', 'submit_send_email'); add_action('draft_to_pending', 'submit_send_email'); add_action('auto-draft_to_pending', 'submit_send_email'); </code></pre>
[ { "answer_id": 314050, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 4, "selected": true, "text": "<p>This question had me scratching my head. Yeah, how come WordPress doesn't support this natively? And then I found out. </p>\n\n<p>You asked how to upload SVG in WordPress 4.9.8 (the current version at the time of writing). You mention that you \"tried uploading after installing different plugins\". You don't say which plugins, nor whether they relate to SVG.</p>\n\n<p>As I understand the situation, the safest, most appropriate, answer at this time is to use <a href=\"https://wordpress.org/plugins/safe-svg/\" rel=\"noreferrer\">SVF Safe</a> (a plugin written for this very purpose) by Darrell Doyle. If this plugin doesn't work for you, then I'd suggest that you have a conflict elsewhere, and you should follow the usual procedures for resolving that. Personally, if this plugin didn't work for me then I'd give up on the notion of uploading SVGs.</p>\n\n<p>If you haven't already done so, may I suggest reading \"<a href=\"https://bjornjohansen.no/svg-in-wordpress\" rel=\"noreferrer\">SVG Uploads in WordPress - the inconvenient truth</a>\" by Bjorn Johansen and/or \"<a href=\"https://kinsta.com/blog/wordpress-svg/\" rel=\"noreferrer\">How to Safely Enable WordPress SVG Support - 2 Simple Clicks</a>\" by Brian Jackson. At least you should know what you are letting yourself in for.</p>\n" }, { "answer_id": 332088, "author": "Rana umer", "author_id": 163461, "author_profile": "https://wordpress.stackexchange.com/users/163461", "pm_score": 2, "selected": false, "text": "<pre><code>//add SVG to allowed file uploads\nfunction add_file_types_to_uploads($file_types){\n\n $new_filetypes = array();\n $new_filetypes['svg'] = 'image/svg+xml';\n $file_types = array_merge($file_types, $new_filetypes );\n\n return $file_types;\n}\nadd_action('upload_mimes', 'add_file_types_to_uploads');\n</code></pre>\n" }, { "answer_id": 343724, "author": "Suraj Rathod", "author_id": 141555, "author_profile": "https://wordpress.stackexchange.com/users/141555", "pm_score": 2, "selected": false, "text": "<p>After adding <strong>upload_mimes</strong> action still anyone facing issue then add this in your wp-config.php file</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n" }, { "answer_id": 345480, "author": "Syed Figar Ali Jaffri", "author_id": 67550, "author_profile": "https://wordpress.stackexchange.com/users/67550", "pm_score": 3, "selected": false, "text": "<p>@rana-umer your code is correct just remove the \"+xml\" after 'image/svg'.</p>\n\n<pre><code>//add SVG to allowed file uploads\nfunction add_file_types_to_uploads($file_types){\n\n $new_filetypes = array();\n $new_filetypes['svg'] = 'image/svg';\n $file_types = array_merge($file_types, $new_filetypes );\n\n return $file_types; \n} \nadd_action('upload_mimes', 'add_file_types_to_uploads');\n</code></pre>\n" }, { "answer_id": 366004, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>The first function is to check the WordPress and add support on WP version lower than 4.8. The second function is to register the mime file type(SVG) and the last one is to fix the thumbnails on media library.</p>\n\n<pre><code> /**\n * Add svg support\n *\n */\nadd_filter( 'wp_check_filetype_and_ext', function( $data, $file, $filename, $mimes) {\n global $wp_version;\n if( $wp_version == '4.7' || ( (float) $wp_version &lt; 4.7 ) ) {\n return $data;\n }\n $filetype = wp_check_filetype( $filename, $mimes );\n return [\n 'ext' =&gt; $filetype['ext'],\n 'type' =&gt; $filetype['type'],\n 'proper_filename' =&gt; $data['proper_filename']\n ];\n}, 10, 4 );\n\nfunction ns_mime_types( $mimes ){\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n}\nadd_filter( 'upload_mimes', 'ns_mime_types' );\n\nfunction ns_fix_svg() {\n echo '&lt;style type=\"text/css\"&gt;.attachment-266x266, .thumbnail img { width: 100% !important; height: auto !important;} &lt;/style&gt;';\n}\nadd_action( 'admin_head', 'ns_fix_svg' );\n</code></pre>\n" }, { "answer_id": 374781, "author": "Mr.Hosseini", "author_id": 147413, "author_profile": "https://wordpress.stackexchange.com/users/147413", "pm_score": 0, "selected": false, "text": "<p>Add this hooks , i tested on wp 5.3 it works :</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Allow SVG\nadd_filter('wp_check_filetype_and_ext', function ($data, $file, $filename, $mimes) {\n\n if (!$data['type']) {\n $wp_filetype = wp_check_filetype($filename, $mimes);\n $ext = $wp_filetype['ext'];\n $type = $wp_filetype['type'];\n $proper_filename = $filename;\n if ($type &amp;&amp; 0 === strpos($type, 'image/') &amp;&amp; $ext !== 'svg') {\n $ext = $type = false;\n }\n $data['ext'] = $ext;\n $data['type'] = $type;\n $data['proper_filename'] = $proper_filename;\n }\n return $data;\n\n\n}, 10, 4);\n\n\nadd_filter('upload_mimes', function ($mimes) {\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n});\n\n\nadd_action('admin_head', function () {\n echo '&lt;style type=&quot;text/css&quot;&gt;\n .media-icon img[src$=&quot;.svg&quot;], img[src$=&quot;.svg&quot;].attachment-post-thumbnail {\n width: 100% !important;\n height: auto !important;\n }&lt;/style&gt;';\n});\n</code></pre>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/313975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150466/" ]
I have this mail notification for new post. All the new post contain arround 100 words and no pictures, so I would like to include in the notification the post content and if is possible, the number of words in the post. Anybody could help me? Thanks for all ``` /* avisar al admin*/ function submit_send_email ($post) { $user_info = get_userdata ($post->post_author); $strTo = array ('[email protected]'); $strSubject = 'Your website name: ' . $user_info->user_nicename . ' submitted a post'; $strMessage = 'A post "' . $post->post_title . '" by ' . $user_info->user_nicename . ' was submitted for review at ' . wp_get_shortlink ($post->ID) . '&preview=true. Please proof.'; wp_mail( $strTo, $strSubject, $strMessage ); } add_action('future_to_pending', 'submit_send_email'); add_action('new_to_pending', 'submit_send_email'); add_action('draft_to_pending', 'submit_send_email'); add_action('auto-draft_to_pending', 'submit_send_email'); ```
This question had me scratching my head. Yeah, how come WordPress doesn't support this natively? And then I found out. You asked how to upload SVG in WordPress 4.9.8 (the current version at the time of writing). You mention that you "tried uploading after installing different plugins". You don't say which plugins, nor whether they relate to SVG. As I understand the situation, the safest, most appropriate, answer at this time is to use [SVF Safe](https://wordpress.org/plugins/safe-svg/) (a plugin written for this very purpose) by Darrell Doyle. If this plugin doesn't work for you, then I'd suggest that you have a conflict elsewhere, and you should follow the usual procedures for resolving that. Personally, if this plugin didn't work for me then I'd give up on the notion of uploading SVGs. If you haven't already done so, may I suggest reading "[SVG Uploads in WordPress - the inconvenient truth](https://bjornjohansen.no/svg-in-wordpress)" by Bjorn Johansen and/or "[How to Safely Enable WordPress SVG Support - 2 Simple Clicks](https://kinsta.com/blog/wordpress-svg/)" by Brian Jackson. At least you should know what you are letting yourself in for.
313,993
<p>I have a membership site. I need to disable the admin bar for the subscribers.</p> <p>I have used this code below:</p> <pre><code>add_action('after_setup_theme', 'remove_admin_bar'); function remove_admin_bar() { if (!current_user_can('administrator') &amp;&amp; !is_admin()) { show_admin_bar(false); } } </code></pre> <p>which removes the admin bar from the frontend for the subscriber, but when they go to their profile page wp-admin/profile.php, the admin bar is still showing there.</p> <p>I am using Paid Membership Pro plugin which I think made the code not working on the backend for subscribers.</p> <p>Also, I have used this code to remove the admin bar from everywhere:</p> <pre><code>if (!function_exists('disableAdminBar')) { function disableAdminBar(){ remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 ); function remove_admin_bar_style_backend() { echo '&lt;style&gt;body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }&lt;/style&gt;'; } add_filter('admin_head','remove_admin_bar_style_backend'); } } add_filter('admin_head','remove_admin_bar_style_backend'); </code></pre> <p>But this code is also not working.</p> <p>I just want to remove the admin bar for the subscribers from both the frontend and backend pages.</p> <p>Is there any specific code I am missing? I am using <strong>Paid membership Pro</strong>.</p> <p>Thank you for helping.</p>
[ { "answer_id": 314000, "author": "Gonçalo Figueiredo", "author_id": 150305, "author_profile": "https://wordpress.stackexchange.com/users/150305", "pm_score": -1, "selected": true, "text": "<p>I did a quick research on this and I don't think you can with a function, as said in the <a href=\"https://codex.wordpress.org/Administration_Screens#Toolbar\" rel=\"nofollow noreferrer\">codex</a>.</p>\n\n<blockquote>\n <p>Note: It is no longer possible to hide the Toolbar when viewing the Administration Screens, but users can disable it on the front-end of the site in their Profile screen.</p>\n</blockquote>\n\n<p>Disabling in the frontend results in the same as you've already done.</p>\n\n<p>I would suggest hiding it with css.</p>\n\n<pre><code>#wpadminbar {\n display: none;\n}\nhtml {\n padding-top: 0; // Move up the page's content by the bar's height\n}\n</code></pre>\n" }, { "answer_id": 319899, "author": "Jason Coleman", "author_id": 3652, "author_profile": "https://wordpress.stackexchange.com/users/3652", "pm_score": 1, "selected": false, "text": "<p>The PMPro team made a plugin to do this:\n<a href=\"https://wordpress.org/plugins/hide-admin-bar-from-non-admins/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/hide-admin-bar-from-non-admins/</a></p>\n\n<p>The includes the PHP and CSS code needed to fully hide the admin bar:\n<a href=\"https://plugins.svn.wordpress.org/hide-admin-bar-from-non-admins/trunk/hide-admin-bar-from-non-admins.php\" rel=\"nofollow noreferrer\">https://plugins.svn.wordpress.org/hide-admin-bar-from-non-admins/trunk/hide-admin-bar-from-non-admins.php</a></p>\n\n<pre><code>function habfna_hide_admin_bar_settings()\n{\n?&gt;\n &lt;style type=\"text/css\"&gt;\n .show-admin-bar {\n display: none;\n }\n &lt;/style&gt;\n&lt;?php\n}\nfunction habfna_disable_admin_bar()\n{\n if(!current_user_can('administrator'))\n {\n add_filter( 'show_admin_bar', '__return_false' );\n add_action( 'admin_print_scripts-profile.php', 'habfna_hide_admin_bar_settings' );\n }\n}\nadd_action('init', 'habfna_disable_admin_bar', 9);\n</code></pre>\n" }, { "answer_id": 343377, "author": "Deepak", "author_id": 136901, "author_profile": "https://wordpress.stackexchange.com/users/136901", "pm_score": 2, "selected": false, "text": "<p>To hide admin bar from non admin users, add the following code to you functions.php file</p>\n\n<pre><code>// show admin bar only for admins\nif (!current_user_can('manage_options')) {\n add_filter('show_admin_bar', '__return_false');\n}\n// show admin bar only for admins and editors\nif (!current_user_can('edit_posts')) {\n add_filter('show_admin_bar', '__return_false');\n}\n</code></pre>\n" }, { "answer_id": 359032, "author": "mica", "author_id": 26610, "author_profile": "https://wordpress.stackexchange.com/users/26610", "pm_score": 1, "selected": false, "text": "<p>I had to do the same but keep the bar for editors &amp; admins but remove for others roles. I did it like that :</p>\n\n<p><em>in <code>functions.php</code></em></p>\n\n<pre><code>function check_user_role($roles, $user_id = null) {\n if ($user_id) $user = get_userdata($user_id);\n else $user = wp_get_current_user();\n if (empty($user)) return false;\n\n foreach ($user-&gt;roles as $role) {\n if (in_array($role, $roles)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p><em>also in <code>functions.php</code></em></p>\n\n<pre><code>// show admin bar only for admins and editors\nif (!check_user_role(array('administrator','editor'))) {\n add_filter('show_admin_bar', '__return_false');\n}\n</code></pre>\n" }, { "answer_id": 396147, "author": "John Doe", "author_id": 78806, "author_profile": "https://wordpress.stackexchange.com/users/78806", "pm_score": 0, "selected": false, "text": "<p><code>show_admin_bar(false)</code> doesn't work on backend pages. You'll have to remove the admin bar hooks if you want to remove them from the backend.</p>\n<pre><code>function remove_admin_bar_hooks() {\n \n // Removes the hooks that render the admin bar.\n remove_action('template_redirect','_wp_admin_bar_init', 0);\n remove_action('admin_init','_wp_admin_bar_init');\n remove_action('before_signup_header','_wp_admin_bar_init');\n remove_action('activate_header','_wp_admin_bar_init');\n remove_action('wp_body_open','wp_admin_bar_render',0);\n remove_action('wp_footer','wp_admin_bar_render',1000);\n remove_action('in_admin_header', 'wp_admin_bar_render', 0);\n \n // Removes the admin bar class from the body tag.\n add_filter('body_class',function($wp_classes, $extra_classes) {\n // Deletes the admin-bar class from the arrays if present.\n return array_diff( \n array_merge( $wp_classes, (array) $extra_classes ), \n array('admin-bar')\n );\n },10000,2);\n}\n</code></pre>\n<p>You can refer to this article for more information: <a href=\"https://blog.terresquall.com/2021/09/remove-the-admin-bar-on-the-wordpress-admin-backend/\" rel=\"nofollow noreferrer\">https://blog.terresquall.com/2021/09/remove-the-admin-bar-on-the-wordpress-admin-backend/</a></p>\n" }, { "answer_id": 401153, "author": "arsenkrylov", "author_id": 217743, "author_profile": "https://wordpress.stackexchange.com/users/217743", "pm_score": 0, "selected": false, "text": "<pre><code>// Disable admin topbar for all roles except admins:\nadd_action('after_setup_theme', 'remove_admin_bar');\n\nfunction remove_admin_bar() {\nif (!current_user_can('administrator') &amp;&amp; !is_admin()) {\n show_admin_bar(false);\n}\n</code></pre>\n<p>}</p>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/313993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126766/" ]
I have a membership site. I need to disable the admin bar for the subscribers. I have used this code below: ``` add_action('after_setup_theme', 'remove_admin_bar'); function remove_admin_bar() { if (!current_user_can('administrator') && !is_admin()) { show_admin_bar(false); } } ``` which removes the admin bar from the frontend for the subscriber, but when they go to their profile page wp-admin/profile.php, the admin bar is still showing there. I am using Paid Membership Pro plugin which I think made the code not working on the backend for subscribers. Also, I have used this code to remove the admin bar from everywhere: ``` if (!function_exists('disableAdminBar')) { function disableAdminBar(){ remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 ); function remove_admin_bar_style_backend() { echo '<style>body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }</style>'; } add_filter('admin_head','remove_admin_bar_style_backend'); } } add_filter('admin_head','remove_admin_bar_style_backend'); ``` But this code is also not working. I just want to remove the admin bar for the subscribers from both the frontend and backend pages. Is there any specific code I am missing? I am using **Paid membership Pro**. Thank you for helping.
I did a quick research on this and I don't think you can with a function, as said in the [codex](https://codex.wordpress.org/Administration_Screens#Toolbar). > > Note: It is no longer possible to hide the Toolbar when viewing the Administration Screens, but users can disable it on the front-end of the site in their Profile screen. > > > Disabling in the frontend results in the same as you've already done. I would suggest hiding it with css. ``` #wpadminbar { display: none; } html { padding-top: 0; // Move up the page's content by the bar's height } ```
313,995
<p>I am building a static landing page on WordPress root folder, and I need to import some shortcodes from an existing page located in <code>wp-content</code> directory.</p> <p>What I do is import with <code>$post = get_post($post_id)</code> the post containing my shortcode, then I extract it -></p> <blockquote> <p>$output = apply_filters( 'the_content', $post->post_content );</p> </blockquote> <p>Finally I do -></p> <blockquote> <p>echo do_shortcode($output);</p> </blockquote> <p>The issue here is that on the page I got displayed only the raw format of the shortcode, like <code>[shortcode]</code>;</p> <p>There is a way to convert shortcodes into plain html so my page can display it correctly or I am missing some <code>require/include</code> somewhere? I already added <code>define( 'WP_USE_THEMES', false ); require "wp-load.php";</code></p>
[ { "answer_id": 314000, "author": "Gonçalo Figueiredo", "author_id": 150305, "author_profile": "https://wordpress.stackexchange.com/users/150305", "pm_score": -1, "selected": true, "text": "<p>I did a quick research on this and I don't think you can with a function, as said in the <a href=\"https://codex.wordpress.org/Administration_Screens#Toolbar\" rel=\"nofollow noreferrer\">codex</a>.</p>\n\n<blockquote>\n <p>Note: It is no longer possible to hide the Toolbar when viewing the Administration Screens, but users can disable it on the front-end of the site in their Profile screen.</p>\n</blockquote>\n\n<p>Disabling in the frontend results in the same as you've already done.</p>\n\n<p>I would suggest hiding it with css.</p>\n\n<pre><code>#wpadminbar {\n display: none;\n}\nhtml {\n padding-top: 0; // Move up the page's content by the bar's height\n}\n</code></pre>\n" }, { "answer_id": 319899, "author": "Jason Coleman", "author_id": 3652, "author_profile": "https://wordpress.stackexchange.com/users/3652", "pm_score": 1, "selected": false, "text": "<p>The PMPro team made a plugin to do this:\n<a href=\"https://wordpress.org/plugins/hide-admin-bar-from-non-admins/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/hide-admin-bar-from-non-admins/</a></p>\n\n<p>The includes the PHP and CSS code needed to fully hide the admin bar:\n<a href=\"https://plugins.svn.wordpress.org/hide-admin-bar-from-non-admins/trunk/hide-admin-bar-from-non-admins.php\" rel=\"nofollow noreferrer\">https://plugins.svn.wordpress.org/hide-admin-bar-from-non-admins/trunk/hide-admin-bar-from-non-admins.php</a></p>\n\n<pre><code>function habfna_hide_admin_bar_settings()\n{\n?&gt;\n &lt;style type=\"text/css\"&gt;\n .show-admin-bar {\n display: none;\n }\n &lt;/style&gt;\n&lt;?php\n}\nfunction habfna_disable_admin_bar()\n{\n if(!current_user_can('administrator'))\n {\n add_filter( 'show_admin_bar', '__return_false' );\n add_action( 'admin_print_scripts-profile.php', 'habfna_hide_admin_bar_settings' );\n }\n}\nadd_action('init', 'habfna_disable_admin_bar', 9);\n</code></pre>\n" }, { "answer_id": 343377, "author": "Deepak", "author_id": 136901, "author_profile": "https://wordpress.stackexchange.com/users/136901", "pm_score": 2, "selected": false, "text": "<p>To hide admin bar from non admin users, add the following code to you functions.php file</p>\n\n<pre><code>// show admin bar only for admins\nif (!current_user_can('manage_options')) {\n add_filter('show_admin_bar', '__return_false');\n}\n// show admin bar only for admins and editors\nif (!current_user_can('edit_posts')) {\n add_filter('show_admin_bar', '__return_false');\n}\n</code></pre>\n" }, { "answer_id": 359032, "author": "mica", "author_id": 26610, "author_profile": "https://wordpress.stackexchange.com/users/26610", "pm_score": 1, "selected": false, "text": "<p>I had to do the same but keep the bar for editors &amp; admins but remove for others roles. I did it like that :</p>\n\n<p><em>in <code>functions.php</code></em></p>\n\n<pre><code>function check_user_role($roles, $user_id = null) {\n if ($user_id) $user = get_userdata($user_id);\n else $user = wp_get_current_user();\n if (empty($user)) return false;\n\n foreach ($user-&gt;roles as $role) {\n if (in_array($role, $roles)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p><em>also in <code>functions.php</code></em></p>\n\n<pre><code>// show admin bar only for admins and editors\nif (!check_user_role(array('administrator','editor'))) {\n add_filter('show_admin_bar', '__return_false');\n}\n</code></pre>\n" }, { "answer_id": 396147, "author": "John Doe", "author_id": 78806, "author_profile": "https://wordpress.stackexchange.com/users/78806", "pm_score": 0, "selected": false, "text": "<p><code>show_admin_bar(false)</code> doesn't work on backend pages. You'll have to remove the admin bar hooks if you want to remove them from the backend.</p>\n<pre><code>function remove_admin_bar_hooks() {\n \n // Removes the hooks that render the admin bar.\n remove_action('template_redirect','_wp_admin_bar_init', 0);\n remove_action('admin_init','_wp_admin_bar_init');\n remove_action('before_signup_header','_wp_admin_bar_init');\n remove_action('activate_header','_wp_admin_bar_init');\n remove_action('wp_body_open','wp_admin_bar_render',0);\n remove_action('wp_footer','wp_admin_bar_render',1000);\n remove_action('in_admin_header', 'wp_admin_bar_render', 0);\n \n // Removes the admin bar class from the body tag.\n add_filter('body_class',function($wp_classes, $extra_classes) {\n // Deletes the admin-bar class from the arrays if present.\n return array_diff( \n array_merge( $wp_classes, (array) $extra_classes ), \n array('admin-bar')\n );\n },10000,2);\n}\n</code></pre>\n<p>You can refer to this article for more information: <a href=\"https://blog.terresquall.com/2021/09/remove-the-admin-bar-on-the-wordpress-admin-backend/\" rel=\"nofollow noreferrer\">https://blog.terresquall.com/2021/09/remove-the-admin-bar-on-the-wordpress-admin-backend/</a></p>\n" }, { "answer_id": 401153, "author": "arsenkrylov", "author_id": 217743, "author_profile": "https://wordpress.stackexchange.com/users/217743", "pm_score": 0, "selected": false, "text": "<pre><code>// Disable admin topbar for all roles except admins:\nadd_action('after_setup_theme', 'remove_admin_bar');\n\nfunction remove_admin_bar() {\nif (!current_user_can('administrator') &amp;&amp; !is_admin()) {\n show_admin_bar(false);\n}\n</code></pre>\n<p>}</p>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/313995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150510/" ]
I am building a static landing page on WordPress root folder, and I need to import some shortcodes from an existing page located in `wp-content` directory. What I do is import with `$post = get_post($post_id)` the post containing my shortcode, then I extract it -> > > $output = apply\_filters( 'the\_content', $post->post\_content ); > > > Finally I do -> > > echo do\_shortcode($output); > > > The issue here is that on the page I got displayed only the raw format of the shortcode, like `[shortcode]`; There is a way to convert shortcodes into plain html so my page can display it correctly or I am missing some `require/include` somewhere? I already added `define( 'WP_USE_THEMES', false ); require "wp-load.php";`
I did a quick research on this and I don't think you can with a function, as said in the [codex](https://codex.wordpress.org/Administration_Screens#Toolbar). > > Note: It is no longer possible to hide the Toolbar when viewing the Administration Screens, but users can disable it on the front-end of the site in their Profile screen. > > > Disabling in the frontend results in the same as you've already done. I would suggest hiding it with css. ``` #wpadminbar { display: none; } html { padding-top: 0; // Move up the page's content by the bar's height } ```
314,011
<p>I used to have a working custom query for location on this <strong>local</strong> link:</p> <pre><code>http://website.local/catalogue/?location=968&amp;floor=1 </code></pre> <p>but, the server that I had to move to (Linux) it appears that is not supporting Permalinks->Post name (<a href="http://10.8.10.9/sample-post/" rel="nofollow noreferrer">http://10.8.10.9/sample-post/</a>) only the default Plain (<a href="http://10.8.10.9/?p=123" rel="nofollow noreferrer">http://10.8.10.9/?p=123</a>), so I the link changed to this: </p> <pre><code>http://10.8.10.9/?page_id=1774/?location=968&amp;floor=1 </code></pre> <p>The problem is: location does not work anymore, but floor does. I guess that's because I have basically <strong>two</strong> <strong>"?"</strong> on the link. </p> <p>How can I resolve this frustrating issue? Any suggestion is highly appreciated. </p> <p>Thanks in advance!</p>
[ { "answer_id": 314012, "author": "Marc", "author_id": 71657, "author_profile": "https://wordpress.stackexchange.com/users/71657", "pm_score": 0, "selected": false, "text": "<p>Your link needs to be <code>http://10.8.10.9/?page_id=1774&amp;location=968&amp;floor=1</code> having multiple <code>?</code> within your request is the problem.</p>\n" }, { "answer_id": 314014, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": 1, "selected": false, "text": "<p>I think you should really try to make the permalinks work on your server. It seldom fails. Have you checked all your server settings are correct, and have you visited the permalink page after updating, so that the cache is flushed?</p>\n\n<p>Otherwise you would have to have <code>http://10.8.10.9/?page_id=1774&amp;location=968&amp;floor=1</code> and that would work too.</p>\n\n<p>I'd really try to get the permalink issue fixed first though. It should work on any server really.</p>\n" } ]
2018/09/12
[ "https://wordpress.stackexchange.com/questions/314011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150200/" ]
I used to have a working custom query for location on this **local** link: ``` http://website.local/catalogue/?location=968&floor=1 ``` but, the server that I had to move to (Linux) it appears that is not supporting Permalinks->Post name (<http://10.8.10.9/sample-post/>) only the default Plain (<http://10.8.10.9/?p=123>), so I the link changed to this: ``` http://10.8.10.9/?page_id=1774/?location=968&floor=1 ``` The problem is: location does not work anymore, but floor does. I guess that's because I have basically **two** **"?"** on the link. How can I resolve this frustrating issue? Any suggestion is highly appreciated. Thanks in advance!
I think you should really try to make the permalinks work on your server. It seldom fails. Have you checked all your server settings are correct, and have you visited the permalink page after updating, so that the cache is flushed? Otherwise you would have to have `http://10.8.10.9/?page_id=1774&location=968&floor=1` and that would work too. I'd really try to get the permalink issue fixed first though. It should work on any server really.
314,064
<p>I use the Theme Twenty Seventeen in WordPress to create my website. Here all pages are one below the other seen on the frontpage. Now I added a new page, but this is not listed on the frontpage. I can only reach it by clicking on it on the menu.</p> <p>How can I also list that page on the frontpage? Please explain step by step cause I'm not experienced in creating websites.</p>
[ { "answer_id": 314082, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>On the frontpage (and on other archives) only posts are listed by default. If you want to add new article and make it visible on that list, you should publish it as a post.</p>\n\n<p>On the other hand, the pages are more static articles that are not listed on archive pages - it makes no sense to put \"Contact\" page on such list. So you can access them from navigation menus and so on.</p>\n\n<p>PS. You can modify this behavior and make pages to show on archive pages, but it will involve some coding - and I don't think there is a need for such steps in this case.</p>\n" }, { "answer_id": 314111, "author": "DHL17", "author_id": 125227, "author_profile": "https://wordpress.stackexchange.com/users/125227", "pm_score": 2, "selected": false, "text": "<p>In Twenty Seventeen you can only add 4 page in front-page section. see image below </p>\n\n<p><a href=\"https://i.stack.imgur.com/Crfqj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Crfqj.png\" alt=\"enter image description here\"></a></p>\n\n<p>See <code>Appearance</code>=> <code>Customize</code> => <code>Theme Options</code></p>\n\n<p><strong>Update</strong> </p>\n\n<p>You can add extra section with filter <code>twentyseventeen_front_page_sections</code> add this code in <code>functions.php</code></p>\n\n<pre><code>function tws_custom_front_sections( $num_sections )\n {\n return 5; //Change this number to change the number of the sections.\n }\nadd_filter( 'twentyseventeen_front_page_sections', 'tws_custom_front_sections' );\n</code></pre>\n" } ]
2018/09/13
[ "https://wordpress.stackexchange.com/questions/314064", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150554/" ]
I use the Theme Twenty Seventeen in WordPress to create my website. Here all pages are one below the other seen on the frontpage. Now I added a new page, but this is not listed on the frontpage. I can only reach it by clicking on it on the menu. How can I also list that page on the frontpage? Please explain step by step cause I'm not experienced in creating websites.
In Twenty Seventeen you can only add 4 page in front-page section. see image below [![enter image description here](https://i.stack.imgur.com/Crfqj.png)](https://i.stack.imgur.com/Crfqj.png) See `Appearance`=> `Customize` => `Theme Options` **Update** You can add extra section with filter `twentyseventeen_front_page_sections` add this code in `functions.php` ``` function tws_custom_front_sections( $num_sections ) { return 5; //Change this number to change the number of the sections. } add_filter( 'twentyseventeen_front_page_sections', 'tws_custom_front_sections' ); ```
314,083
<p>I have get the following array from my database using mysql query in PHP. What is way to print the specific item (e.g: <code>staff_name</code> and <code>coupon</code>)? </p> <pre><code>{"items":[{"ca_id":1,"appointment_date":"2018-07-02 08:00:00","service_name":"Eye check-up","service_price":50,"service_tax":0,"wait_listed":false,"deposit_format":null,"number_of_persons":"1","units":"1","duration":"3600","staff_name":"Mc Miltony","extras":[]}],"coupon":null,"subtotal":{"price":50,"deposit":0},"customer":"Mr Jhon","tax_in_price":"excluded","tax_paid":"5.00"} </code></pre>
[ { "answer_id": 314085, "author": "David Corp", "author_id": 129246, "author_profile": "https://wordpress.stackexchange.com/users/129246", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\n$results = '{\"items\":[{\"ca_id\":1,\"appointment_date\":\"2018-07-02 08:00:00\",\"service_name\":\"Eye check-up\",\"service_price\":50,\"service_tax\":0,\"wait_listed\":false,\"deposit_format\":null,\"number_of_persons\":\"1\",\"units\":\"1\",\"duration\":\"3600\",\"staff_name\":\"Mc Miltony\",\"extras\":[]}],\"coupon\":null,\"subtotal\":{\"price\":50,\"deposit\":0},\"customer\":\"Mr Jhon\",\"tax_in_price\":\"excluded\",\"tax_paid\":\"5.00\"}';\n$object = json_decode( $results );\n$staff_name = $object-&gt;items[0]-&gt;staff_name;\n$coupon = $object-&gt;coupon;\n?&gt;\n</code></pre>\n" }, { "answer_id": 314090, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>Not really a WordPress question, but I'll bite.</p>\n\n<p>That data is <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON\" rel=\"nofollow noreferrer\">JSON</a>. To manipulate it with PHP you need to decode it with <a href=\"http://php.net/manual/en/function.json-decode.php\" rel=\"nofollow noreferrer\"><code>json_decode()</code></a>. Then you can treat it as a PHP object. </p>\n\n<p>So to access the values you'd mention, and assuming the JSON is in a variable named <code>$json</code>:</p>\n\n<pre><code>$object = json_decode( $json );\n$staff_name = $object-&gt;items[0]-&gt;staff_name;\n$coupon = $object-&gt;coupon;\n</code></pre>\n" } ]
2018/09/13
[ "https://wordpress.stackexchange.com/questions/314083", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115840/" ]
I have get the following array from my database using mysql query in PHP. What is way to print the specific item (e.g: `staff_name` and `coupon`)? ``` {"items":[{"ca_id":1,"appointment_date":"2018-07-02 08:00:00","service_name":"Eye check-up","service_price":50,"service_tax":0,"wait_listed":false,"deposit_format":null,"number_of_persons":"1","units":"1","duration":"3600","staff_name":"Mc Miltony","extras":[]}],"coupon":null,"subtotal":{"price":50,"deposit":0},"customer":"Mr Jhon","tax_in_price":"excluded","tax_paid":"5.00"} ```
Not really a WordPress question, but I'll bite. That data is [JSON](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON). To manipulate it with PHP you need to decode it with [`json_decode()`](http://php.net/manual/en/function.json-decode.php). Then you can treat it as a PHP object. So to access the values you'd mention, and assuming the JSON is in a variable named `$json`: ``` $object = json_decode( $json ); $staff_name = $object->items[0]->staff_name; $coupon = $object->coupon; ```
314,089
<p>I inadvertently posted a duplicate of this question in the other stackexchange - but it was MISTAKENLY marked as duplicated and solved by a different question answered using deprecated code </p> <p>So I will reask in the Wordpress forum where there may be more expertise</p> <p>I'm trying to combine functions - and don't know how it is done</p> <p>I'm successfully using get_sites to produce a list of WP Multisite subsites.</p> <p>I'm hoping to also pull get_custom_logo to display the logo, and get_bloginfo for things like $site_description = get_bloginfo( 'description' );</p> <p>just don't know how to merge the gets. this is working</p> <pre><code>/** get sites */ function make_list_shortcode() { $subsites = get_sites( [ 'public' =&gt; 1, 'number' =&gt; 500, 'orderby' =&gt; 'last_updated', 'order' =&gt; 'DESC', ] ); if ( ! empty ( $subsites ) ) { $html = '&lt;ul class="icon-bullets-greater"&gt;'; foreach( $subsites as $subsite ) { $subsite_id = $subsite-&gt;blog_id; $subsite_name = get_blog_details( $subsite_id )-&gt;blogname; $subsite_link = get_blog_details( $subsite_id )-&gt;siteurl; $subsite_domain = get_blog_details( $subsite_id )-&gt;domain; $subsite_path = get_blog_details( $subsite_id )-&gt;path; $html .= '&lt;li style="list-style: none!important;" class="site-' . $subsite_id . '" &gt;&lt;a href="' . $subsite_link . '" target="_blank"&gt;' . $subsite_name . '&lt;/a&gt; at ' . $subsite_domain . '' . $subsite_path . ' &lt;/li&gt;'; } $html .= '&lt;/ul&gt;'; return $html; } } add_shortcode('list_sites', 'make_list_shortcode'); </code></pre> <p>appreciate any help, thanks</p>
[ { "answer_id": 314102, "author": "Ittikorn S.", "author_id": 68069, "author_profile": "https://wordpress.stackexchange.com/users/68069", "pm_score": 0, "selected": false, "text": "<p>I assumed the theme you are using on multi-site is supporting the Theme Logo feature. Then you could simply use <strong>get_theme_mod('custom_logo')</strong>. Please note that the <strong>custom_logo</strong> is named by the theme developer, some themes may be different than others. </p>\n\n<pre><code>&lt;?php\n/** get sites */\n\nfunction make_list_shortcode()\n {\n $subsites = get_sites(['public' =&gt; 1, 'number' =&gt; 500, 'orderby' =&gt; 'last_updated', 'order' =&gt; 'DESC', ]);\n if (!empty($subsites))\n {\n $html = '&lt;ul class=\"icon-bullets-greater\"&gt;';\n foreach($subsites as $subsite)\n {\n $subsite_id = $subsite-&gt;blog_id;\n $subsite_name = get_blog_details($subsite_id)-&gt;blogname;\n $subsite_link = get_blog_details($subsite_id)-&gt;siteurl;\n $subsite_domain = get_blog_details($subsite_id)-&gt;domain;\n $subsite_path = get_blog_details($subsite_id)-&gt;path;\n\n // Switch to Blog\n switch_to_blog( $subsite-&gt;blog_id );\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n $logo = wp_get_attachment_image_src( $custom_logo_id , 'full' );\n\n // Added the image tag and src path\n $html.= '&lt;li style=\"list-style: none!important;\" class=\"site-' . $subsite_id . '\" &gt;&lt;img src=\"'.$logo.'\" /&gt;&lt;a href=\"' . $subsite_link . '\" target=\"_blank\"&gt;' . $subsite_name . '&lt;/a&gt; at ' . $subsite_domain . '' . $subsite_path . ' &lt;/li&gt;';\n }\n\n $html.= '&lt;/ul&gt;';\n return $html;\n }\n }\n\nadd_shortcode('list_sites', 'make_list_shortcode');\n</code></pre>\n" }, { "answer_id": 314142, "author": "Trip Vendors Inc", "author_id": 121961, "author_profile": "https://wordpress.stackexchange.com/users/121961", "pm_score": 1, "selected": false, "text": "<p>modifying to this, works thanks</p>\n\n<p>// Switch to Blog\n switch_to_blog( $subsite->blog_id );\n $site_description = get_bloginfo( 'description' );\n restore_current_blog();</p>\n\n<p>still working on calling the logos</p>\n" } ]
2018/09/13
[ "https://wordpress.stackexchange.com/questions/314089", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121961/" ]
I inadvertently posted a duplicate of this question in the other stackexchange - but it was MISTAKENLY marked as duplicated and solved by a different question answered using deprecated code So I will reask in the Wordpress forum where there may be more expertise I'm trying to combine functions - and don't know how it is done I'm successfully using get\_sites to produce a list of WP Multisite subsites. I'm hoping to also pull get\_custom\_logo to display the logo, and get\_bloginfo for things like $site\_description = get\_bloginfo( 'description' ); just don't know how to merge the gets. this is working ``` /** get sites */ function make_list_shortcode() { $subsites = get_sites( [ 'public' => 1, 'number' => 500, 'orderby' => 'last_updated', 'order' => 'DESC', ] ); if ( ! empty ( $subsites ) ) { $html = '<ul class="icon-bullets-greater">'; foreach( $subsites as $subsite ) { $subsite_id = $subsite->blog_id; $subsite_name = get_blog_details( $subsite_id )->blogname; $subsite_link = get_blog_details( $subsite_id )->siteurl; $subsite_domain = get_blog_details( $subsite_id )->domain; $subsite_path = get_blog_details( $subsite_id )->path; $html .= '<li style="list-style: none!important;" class="site-' . $subsite_id . '" ><a href="' . $subsite_link . '" target="_blank">' . $subsite_name . '</a> at ' . $subsite_domain . '' . $subsite_path . ' </li>'; } $html .= '</ul>'; return $html; } } add_shortcode('list_sites', 'make_list_shortcode'); ``` appreciate any help, thanks
modifying to this, works thanks // Switch to Blog switch\_to\_blog( $subsite->blog\_id ); $site\_description = get\_bloginfo( 'description' ); restore\_current\_blog(); still working on calling the logos
314,097
<p>I'm a novice at Wordpress and i'm pretty sure what i'm looking for is really easy. I have an issue with a function that doesn't work :</p> <pre><code> function user_homepage() { if ( is_user_logged_in() ) { $args = array( 'field' =&gt; 25, ); $user_homepage = bp_profile_field_data( $args ); if ($user_homepage == 'Sports') { $redirect_to = home_url('/sports/'); wp_redirect( $redirect_to ); exit; } else if ($user_homepage == 'Tech') { $redirect_to = home_url('/tech/'); wp_redirect( $redirect_to ); exit; } } } add_filter('login_redirect','user_homepage',10,3); </code></pre> <p><strong>Updated version, still doesn't work</strong></p> <pre><code>function redirect_user_homepage() { global $bp; if ( is_user_logged_in() &amp;&amp; is_front_page() ) { $args = array( 'field' =&gt; 25, 'user_id' =&gt; bp_loggedin_user_id() ); $user_homepage = bp_profile_field_data($args); if ($user_homepage == "All") { wp_redirect( home_url() ); exit; } elseif ($user_homepage == "Sports") { wp_redirect( home_url('/sports/') ); exit; } elseif ($user_homepage == "Tech") { wp_redirect( home_url('/tech/') ); exit; } } } add_action( 'template_redirect', 'redirect_user_homepage'); </code></pre> <p>As you can see i want to redirect my users based on a custom field i created in Buddypress. But more than that i don't want them to simply be redirected after login, i want them to be redirect to this page when they go to the website homepage.</p> <p>Any help would be greatly appreciated! Thanks!</p>
[ { "answer_id": 314102, "author": "Ittikorn S.", "author_id": 68069, "author_profile": "https://wordpress.stackexchange.com/users/68069", "pm_score": 0, "selected": false, "text": "<p>I assumed the theme you are using on multi-site is supporting the Theme Logo feature. Then you could simply use <strong>get_theme_mod('custom_logo')</strong>. Please note that the <strong>custom_logo</strong> is named by the theme developer, some themes may be different than others. </p>\n\n<pre><code>&lt;?php\n/** get sites */\n\nfunction make_list_shortcode()\n {\n $subsites = get_sites(['public' =&gt; 1, 'number' =&gt; 500, 'orderby' =&gt; 'last_updated', 'order' =&gt; 'DESC', ]);\n if (!empty($subsites))\n {\n $html = '&lt;ul class=\"icon-bullets-greater\"&gt;';\n foreach($subsites as $subsite)\n {\n $subsite_id = $subsite-&gt;blog_id;\n $subsite_name = get_blog_details($subsite_id)-&gt;blogname;\n $subsite_link = get_blog_details($subsite_id)-&gt;siteurl;\n $subsite_domain = get_blog_details($subsite_id)-&gt;domain;\n $subsite_path = get_blog_details($subsite_id)-&gt;path;\n\n // Switch to Blog\n switch_to_blog( $subsite-&gt;blog_id );\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n $logo = wp_get_attachment_image_src( $custom_logo_id , 'full' );\n\n // Added the image tag and src path\n $html.= '&lt;li style=\"list-style: none!important;\" class=\"site-' . $subsite_id . '\" &gt;&lt;img src=\"'.$logo.'\" /&gt;&lt;a href=\"' . $subsite_link . '\" target=\"_blank\"&gt;' . $subsite_name . '&lt;/a&gt; at ' . $subsite_domain . '' . $subsite_path . ' &lt;/li&gt;';\n }\n\n $html.= '&lt;/ul&gt;';\n return $html;\n }\n }\n\nadd_shortcode('list_sites', 'make_list_shortcode');\n</code></pre>\n" }, { "answer_id": 314142, "author": "Trip Vendors Inc", "author_id": 121961, "author_profile": "https://wordpress.stackexchange.com/users/121961", "pm_score": 1, "selected": false, "text": "<p>modifying to this, works thanks</p>\n\n<p>// Switch to Blog\n switch_to_blog( $subsite->blog_id );\n $site_description = get_bloginfo( 'description' );\n restore_current_blog();</p>\n\n<p>still working on calling the logos</p>\n" } ]
2018/09/13
[ "https://wordpress.stackexchange.com/questions/314097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150574/" ]
I'm a novice at Wordpress and i'm pretty sure what i'm looking for is really easy. I have an issue with a function that doesn't work : ``` function user_homepage() { if ( is_user_logged_in() ) { $args = array( 'field' => 25, ); $user_homepage = bp_profile_field_data( $args ); if ($user_homepage == 'Sports') { $redirect_to = home_url('/sports/'); wp_redirect( $redirect_to ); exit; } else if ($user_homepage == 'Tech') { $redirect_to = home_url('/tech/'); wp_redirect( $redirect_to ); exit; } } } add_filter('login_redirect','user_homepage',10,3); ``` **Updated version, still doesn't work** ``` function redirect_user_homepage() { global $bp; if ( is_user_logged_in() && is_front_page() ) { $args = array( 'field' => 25, 'user_id' => bp_loggedin_user_id() ); $user_homepage = bp_profile_field_data($args); if ($user_homepage == "All") { wp_redirect( home_url() ); exit; } elseif ($user_homepage == "Sports") { wp_redirect( home_url('/sports/') ); exit; } elseif ($user_homepage == "Tech") { wp_redirect( home_url('/tech/') ); exit; } } } add_action( 'template_redirect', 'redirect_user_homepage'); ``` As you can see i want to redirect my users based on a custom field i created in Buddypress. But more than that i don't want them to simply be redirected after login, i want them to be redirect to this page when they go to the website homepage. Any help would be greatly appreciated! Thanks!
modifying to this, works thanks // Switch to Blog switch\_to\_blog( $subsite->blog\_id ); $site\_description = get\_bloginfo( 'description' ); restore\_current\_blog(); still working on calling the logos
314,101
<p>I'm trying to show all the posts on a page with an audio player in it and for that I'm looping through posts in the following manner:</p> <pre><code>&lt;?php $posts = get_posts(); $ID; foreach( $posts as $item) { global $post; $post_id = $item-&gt;ID; $file_id = get_post_meta($post_id, 'sound_s', true); $file_url = wp_get_attachment_url( $file_id ); $attr = array( 'src' =&gt; $file_url, 'loop' =&gt; '', 'autoplay' =&gt; '', 'preload' =&gt; 'none' ); echo wp_audio_shortcode( $attr ); $ID = $file_id; var_dump($file_id); } ?&gt; </code></pre> <p>But trying to echo or var_dump $file_id is returning in null due to which my audio player can not be shown. And yeah there's no mistake in meta key and $post_id is also returning currect value. So please tell me why is this happening?</p>
[ { "answer_id": 314104, "author": "Ittikorn S.", "author_id": 68069, "author_profile": "https://wordpress.stackexchange.com/users/68069", "pm_score": -1, "selected": false, "text": "<p>Have you try to change the third attributes of <strong>get_post_meta()</strong> to <strong>false</strong></p>\n\n<pre><code>$file_id = get_post_meta($post_id, 'sound_s', false);\n</code></pre>\n\n<p>and then access your variable by</p>\n\n<pre><code>var_dump($file_id[0]);\n</code></pre>\n" }, { "answer_id": 314202, "author": "Krishna Joshi", "author_id": 150621, "author_profile": "https://wordpress.stackexchange.com/users/150621", "pm_score": 0, "selected": false, "text": "<p>Please try below code and check if '<strong>sound_s</strong>' key exists in the array or not</p>\n\n<pre><code>$file_id = get_post_meta($post_id);\necho \"&lt;pre&gt;\";\nprint_r( $file_id );\nexit;\n</code></pre>\n" } ]
2018/09/13
[ "https://wordpress.stackexchange.com/questions/314101", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150425/" ]
I'm trying to show all the posts on a page with an audio player in it and for that I'm looping through posts in the following manner: ``` <?php $posts = get_posts(); $ID; foreach( $posts as $item) { global $post; $post_id = $item->ID; $file_id = get_post_meta($post_id, 'sound_s', true); $file_url = wp_get_attachment_url( $file_id ); $attr = array( 'src' => $file_url, 'loop' => '', 'autoplay' => '', 'preload' => 'none' ); echo wp_audio_shortcode( $attr ); $ID = $file_id; var_dump($file_id); } ?> ``` But trying to echo or var\_dump $file\_id is returning in null due to which my audio player can not be shown. And yeah there's no mistake in meta key and $post\_id is also returning currect value. So please tell me why is this happening?
Please try below code and check if '**sound\_s**' key exists in the array or not ``` $file_id = get_post_meta($post_id); echo "<pre>"; print_r( $file_id ); exit; ```
314,151
<p>Example:</p> <p>If I have a parent category 1 with child categories 2,3,4 etc</p> <p>instead of a call like this:</p> <pre><code>/wp/v2/posts?categories=1,2,3,4 </code></pre> <p>i want a call like this (imaging code)</p> <pre><code>/wp/v2/posts?categories=1&amp;includeallchilds=true </code></pre> <p>that will include all articles from the child and sub-child of 1.</p> <p>how is this possible? I don't want my application make 2 api calls to find all childs of the categories of 1..</p> <p>this query can done what i need, but i cant include this on rest api call,</p> <pre><code>$args = array( 'post_type' =&gt; 'post', 'order' =&gt; 'DESC', 'posts_per_page' =&gt; 100, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; '1', ), ), ); </code></pre>
[ { "answer_id": 314152, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>WP can already do this out of the box thanks to the <code>include_children</code> parameter of <code>tax_query</code> which is true by default.</p>\n<p>While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.</p>\n<p><a href=\"https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/\" rel=\"nofollow noreferrer\">Here's an example taken from the official Make WP blog</a>, just do something like this:</p>\n<pre><code>const query = {\n categories: {\n terms: [ 3, 5, 7 ],\n include_children: true,\n },\n};\nwp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );\n</code></pre>\n<p>Which generates a URL that looks like this:</p>\n<pre><code>/wp-json/wp/v2/posts?categories[terms][0]=3&amp;categories[terms][1]=5&amp;categories[terms][2]=7&amp;categories[include_children]=true&amp;_locale=user\n</code></pre>\n<p>Notice</p>\n" }, { "answer_id": 397628, "author": "Luka Juras", "author_id": 194476, "author_profile": "https://wordpress.stackexchange.com/users/194476", "pm_score": 1, "selected": false, "text": "<p>Just stumble on this because I was looking for the solution to same issue.\nDon't know if it was changed but it no longer works (if ever was).\nNow, you have to make call to categories endpoint <code>/categories?parent=&quot;parent_cat_id&quot;</code> in order to get list of child categories, then feed that info into another call (posts) <code>/posts?categories=&quot;1,2,3,4..&quot;&amp;...</code></p>\n" }, { "answer_id": 412543, "author": "Shameer ", "author_id": 159560, "author_profile": "https://wordpress.stackexchange.com/users/159560", "pm_score": 0, "selected": false, "text": "<p>as Tom mentioned in the previous answer, append these queries to the rest API query. for me, it working.</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?page=1&amp;per_page=10&amp;categories[terms][0]=&lt;category_id&gt;&amp;categories[include_children]=true\n</code></pre>\n<p>Replace <code>&lt;category_id&gt;</code> with your actual category id</p>\n" } ]
2018/09/13
[ "https://wordpress.stackexchange.com/questions/314151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134864/" ]
Example: If I have a parent category 1 with child categories 2,3,4 etc instead of a call like this: ``` /wp/v2/posts?categories=1,2,3,4 ``` i want a call like this (imaging code) ``` /wp/v2/posts?categories=1&includeallchilds=true ``` that will include all articles from the child and sub-child of 1. how is this possible? I don't want my application make 2 api calls to find all childs of the categories of 1.. this query can done what i need, but i cant include this on rest api call, ``` $args = array( 'post_type' => 'post', 'order' => 'DESC', 'posts_per_page' => 100, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => '1', ), ), ); ```
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. [Here's an example taken from the official Make WP blog](https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/), just do something like this: ``` const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); ``` Which generates a URL that looks like this: ``` /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user ``` Notice
314,160
<p>I am looking for a way to replace all links on images. Currently when a user clicks an image it links to the source file. </p> <p>What I want it to do is to ink to: example.com/editor=12&amp;image=filename.jpg So every that encloses an should link to that site with the image filename so it can be loaded in an editor.</p> <p>First, I tried to replace the links with ajax, but that does not work with lazy load and also seems less practical. The second thing I tried is to filter the $content of the post. But with that I can only replace the /wp-content/uploads/ part. I can’t filter for the first part (http://) which leads to also all src being replaced and no image shows up at all. </p> <p>Is there any way to do this by hooks maybe? </p> <p>Kind regards Patrick</p> <p>Update: So this works for images added as single image, however it seems not to work on gallery shortcode even if the priority is 12 and short-codes are already executed.</p> <pre><code>add_filter('the_content', 'my_content_filter', 12); function my_content_filter($content) { if ( is_single() ) $content = str_replace('&lt;a href="https://example.com/wp-content/uploads/','&lt;a href="https://example.com/?editor=82&amp;image=',$content); return $content; } </code></pre>
[ { "answer_id": 314152, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>WP can already do this out of the box thanks to the <code>include_children</code> parameter of <code>tax_query</code> which is true by default.</p>\n<p>While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.</p>\n<p><a href=\"https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/\" rel=\"nofollow noreferrer\">Here's an example taken from the official Make WP blog</a>, just do something like this:</p>\n<pre><code>const query = {\n categories: {\n terms: [ 3, 5, 7 ],\n include_children: true,\n },\n};\nwp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );\n</code></pre>\n<p>Which generates a URL that looks like this:</p>\n<pre><code>/wp-json/wp/v2/posts?categories[terms][0]=3&amp;categories[terms][1]=5&amp;categories[terms][2]=7&amp;categories[include_children]=true&amp;_locale=user\n</code></pre>\n<p>Notice</p>\n" }, { "answer_id": 397628, "author": "Luka Juras", "author_id": 194476, "author_profile": "https://wordpress.stackexchange.com/users/194476", "pm_score": 1, "selected": false, "text": "<p>Just stumble on this because I was looking for the solution to same issue.\nDon't know if it was changed but it no longer works (if ever was).\nNow, you have to make call to categories endpoint <code>/categories?parent=&quot;parent_cat_id&quot;</code> in order to get list of child categories, then feed that info into another call (posts) <code>/posts?categories=&quot;1,2,3,4..&quot;&amp;...</code></p>\n" }, { "answer_id": 412543, "author": "Shameer ", "author_id": 159560, "author_profile": "https://wordpress.stackexchange.com/users/159560", "pm_score": 0, "selected": false, "text": "<p>as Tom mentioned in the previous answer, append these queries to the rest API query. for me, it working.</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?page=1&amp;per_page=10&amp;categories[terms][0]=&lt;category_id&gt;&amp;categories[include_children]=true\n</code></pre>\n<p>Replace <code>&lt;category_id&gt;</code> with your actual category id</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150609/" ]
I am looking for a way to replace all links on images. Currently when a user clicks an image it links to the source file. What I want it to do is to ink to: example.com/editor=12&image=filename.jpg So every that encloses an should link to that site with the image filename so it can be loaded in an editor. First, I tried to replace the links with ajax, but that does not work with lazy load and also seems less practical. The second thing I tried is to filter the $content of the post. But with that I can only replace the /wp-content/uploads/ part. I can’t filter for the first part (http://) which leads to also all src being replaced and no image shows up at all. Is there any way to do this by hooks maybe? Kind regards Patrick Update: So this works for images added as single image, however it seems not to work on gallery shortcode even if the priority is 12 and short-codes are already executed. ``` add_filter('the_content', 'my_content_filter', 12); function my_content_filter($content) { if ( is_single() ) $content = str_replace('<a href="https://example.com/wp-content/uploads/','<a href="https://example.com/?editor=82&image=',$content); return $content; } ```
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. [Here's an example taken from the official Make WP blog](https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/), just do something like this: ``` const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); ``` Which generates a URL that looks like this: ``` /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user ``` Notice
314,165
<p>I tried to customize my WordPress theme but it shows this error.</p> <blockquote> <p>Your theme has 2 widget areas, but this particular page doesn’t display them. You can navigate to other pages on your site while using the Customizer to view > and edit the widgets displayed on those pages.</p> </blockquote> <p>First, there didn't show widget area so I Add this code for that then it shows widget and but now show the above error.</p> <pre><code>if (function_exists("register_sidebar")) { register_sidebar(); } </code></pre> <p>This is my function.php file how can I solve this issue. Do I want to change any other page?</p> <pre><code>&lt;?php /** * Enqueues scripts and styles. * */ if (function_exists("register_sidebar")) { register_sidebar(); } function umk_enque_scripts() { wp_enqueue_style( 'normalize-style', get_template_directory_uri() . '/css/normal.css' ); wp_enqueue_style( 'umkthemes-style', get_stylesheet_uri() ); wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/css/custom.css' ); wp_enqueue_style( 'landmark', get_template_directory_uri() . '/css/landmark-map.css' ); // wp_enqueue_script( 'umkthemes-script', get_template_directory_uri(). '/js/responsiveslides.min.js', array( 'jquery' ), '1.0' ); } add_action( 'wp_enqueue_scripts', 'umk_enque_scripts' ); function umkthemes_setup() { add_theme_support ('menus'); add_theme_support( 'post-thumbnails' ); // set_post_thumbnail_size( 273 , 146 ); register_nav_menus( array( 'primary_menu' =&gt; 'Main navigation', ) ); } add_action( 'after_setup_theme', 'umkthemes_setup' ); // Our custom post type function function create_posttype() { register_post_type( 'sale', // CPT Options array( 'labels' =&gt; array( 'name' =&gt; __( 'Sale' ), 'singular_name' =&gt; __( 'Sale' ), 'all_items' =&gt; __('All Sales', 'umkthemes'), /* the all items menu item */ 'add_new' =&gt; __('Add New Sale', 'umkthemes'), /* The add new menu item */ 'add_new_item' =&gt; __('Add New Sale', 'umkthemes'), /* Add New Display Title */ 'edit' =&gt; __( 'Edit', 'jointstheme' ), /* Edit Dialog */ 'edit_item' =&gt; __('Edit Sale', 'umkthemes'), /* Edit Display Title */ 'new_item' =&gt; __('New Sale', 'umkthemes'), /* New Display Title */ 'view_item' =&gt; __('View Sale', 'umkthemes'), /* View Display Title */ 'search_items' =&gt; __('Search Sale', 'umkthemes'), /* Search Custom Type Title */ ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'sale'), 'supports' =&gt; array( 'title', 'editor', 'thumbnail', ) ) ); } // Hooking up our function to theme setup add_action( 'init', 'create_posttype' ); </code></pre>
[ { "answer_id": 314152, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>WP can already do this out of the box thanks to the <code>include_children</code> parameter of <code>tax_query</code> which is true by default.</p>\n<p>While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.</p>\n<p><a href=\"https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/\" rel=\"nofollow noreferrer\">Here's an example taken from the official Make WP blog</a>, just do something like this:</p>\n<pre><code>const query = {\n categories: {\n terms: [ 3, 5, 7 ],\n include_children: true,\n },\n};\nwp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );\n</code></pre>\n<p>Which generates a URL that looks like this:</p>\n<pre><code>/wp-json/wp/v2/posts?categories[terms][0]=3&amp;categories[terms][1]=5&amp;categories[terms][2]=7&amp;categories[include_children]=true&amp;_locale=user\n</code></pre>\n<p>Notice</p>\n" }, { "answer_id": 397628, "author": "Luka Juras", "author_id": 194476, "author_profile": "https://wordpress.stackexchange.com/users/194476", "pm_score": 1, "selected": false, "text": "<p>Just stumble on this because I was looking for the solution to same issue.\nDon't know if it was changed but it no longer works (if ever was).\nNow, you have to make call to categories endpoint <code>/categories?parent=&quot;parent_cat_id&quot;</code> in order to get list of child categories, then feed that info into another call (posts) <code>/posts?categories=&quot;1,2,3,4..&quot;&amp;...</code></p>\n" }, { "answer_id": 412543, "author": "Shameer ", "author_id": 159560, "author_profile": "https://wordpress.stackexchange.com/users/159560", "pm_score": 0, "selected": false, "text": "<p>as Tom mentioned in the previous answer, append these queries to the rest API query. for me, it working.</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?page=1&amp;per_page=10&amp;categories[terms][0]=&lt;category_id&gt;&amp;categories[include_children]=true\n</code></pre>\n<p>Replace <code>&lt;category_id&gt;</code> with your actual category id</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150614/" ]
I tried to customize my WordPress theme but it shows this error. > > Your theme has 2 widget areas, but this particular page doesn’t display them. > You can navigate to other pages on your site while using the Customizer to view > and edit the widgets displayed on those pages. > > > First, there didn't show widget area so I Add this code for that then it shows widget and but now show the above error. ``` if (function_exists("register_sidebar")) { register_sidebar(); } ``` This is my function.php file how can I solve this issue. Do I want to change any other page? ``` <?php /** * Enqueues scripts and styles. * */ if (function_exists("register_sidebar")) { register_sidebar(); } function umk_enque_scripts() { wp_enqueue_style( 'normalize-style', get_template_directory_uri() . '/css/normal.css' ); wp_enqueue_style( 'umkthemes-style', get_stylesheet_uri() ); wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/css/custom.css' ); wp_enqueue_style( 'landmark', get_template_directory_uri() . '/css/landmark-map.css' ); // wp_enqueue_script( 'umkthemes-script', get_template_directory_uri(). '/js/responsiveslides.min.js', array( 'jquery' ), '1.0' ); } add_action( 'wp_enqueue_scripts', 'umk_enque_scripts' ); function umkthemes_setup() { add_theme_support ('menus'); add_theme_support( 'post-thumbnails' ); // set_post_thumbnail_size( 273 , 146 ); register_nav_menus( array( 'primary_menu' => 'Main navigation', ) ); } add_action( 'after_setup_theme', 'umkthemes_setup' ); // Our custom post type function function create_posttype() { register_post_type( 'sale', // CPT Options array( 'labels' => array( 'name' => __( 'Sale' ), 'singular_name' => __( 'Sale' ), 'all_items' => __('All Sales', 'umkthemes'), /* the all items menu item */ 'add_new' => __('Add New Sale', 'umkthemes'), /* The add new menu item */ 'add_new_item' => __('Add New Sale', 'umkthemes'), /* Add New Display Title */ 'edit' => __( 'Edit', 'jointstheme' ), /* Edit Dialog */ 'edit_item' => __('Edit Sale', 'umkthemes'), /* Edit Display Title */ 'new_item' => __('New Sale', 'umkthemes'), /* New Display Title */ 'view_item' => __('View Sale', 'umkthemes'), /* View Display Title */ 'search_items' => __('Search Sale', 'umkthemes'), /* Search Custom Type Title */ ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'sale'), 'supports' => array( 'title', 'editor', 'thumbnail', ) ) ); } // Hooking up our function to theme setup add_action( 'init', 'create_posttype' ); ```
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. [Here's an example taken from the official Make WP blog](https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/), just do something like this: ``` const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); ``` Which generates a URL that looks like this: ``` /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user ``` Notice
314,172
<p>I'm relatively new to working with wordpress and php in general, so I'd like to know if someone can help me with this.</p> <p>I have a custom query that looks like this</p> <pre><code>&lt;?php $args = array( //argumentos 'numberposts' =&gt; -1, 'post_type' =&gt; 'cdts', 'meta_key' =&gt; 'cargo', 'meta_value' =&gt; 'p' ); $the_query = new WP_Query( $args ); //custom query ?&gt; &lt;?php if( $the_query-&gt;have_posts()): //loop do wordpress ?&gt; &lt;ul class="lista_candidatos"&gt; &lt;?php while( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_field('link'); ?&gt;"&gt; &lt;?php the_field('nome'); ?&gt; &lt;?php the_field('numero_partido'); ?&gt; (&lt;?php the_field('sigla_partido'); ?&gt;) &lt;/a&gt; &lt;p class="ano_cand"&gt;&lt;?php the_field('ano_candidatura'); ?&gt;&lt;/p&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;?php else : ?&gt; &lt;p class="err_no_candidato"&gt;Sem candidatos cadastrados.&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); //restaura os queries do wp ?&gt; </code></pre> <p>And I have an ACF field that's called "ano_candidatura". I'd like to know if there is a way to make different things with different "ano_candidatura", like creating different tabs for each value.</p> <p>Maybe I'm doing something wrong I try to do, for example,</p> <pre><code>&lt;?php if( the_field('ano_candidatura') == '2018'): ?&gt; </code></pre> <p>because when I do this, it just prints '2018' to the page.</p> <p>So, is there a way I can create different html for different the_field values and equal html to equivalent values?</p>
[ { "answer_id": 314152, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>WP can already do this out of the box thanks to the <code>include_children</code> parameter of <code>tax_query</code> which is true by default.</p>\n<p>While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.</p>\n<p><a href=\"https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/\" rel=\"nofollow noreferrer\">Here's an example taken from the official Make WP blog</a>, just do something like this:</p>\n<pre><code>const query = {\n categories: {\n terms: [ 3, 5, 7 ],\n include_children: true,\n },\n};\nwp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );\n</code></pre>\n<p>Which generates a URL that looks like this:</p>\n<pre><code>/wp-json/wp/v2/posts?categories[terms][0]=3&amp;categories[terms][1]=5&amp;categories[terms][2]=7&amp;categories[include_children]=true&amp;_locale=user\n</code></pre>\n<p>Notice</p>\n" }, { "answer_id": 397628, "author": "Luka Juras", "author_id": 194476, "author_profile": "https://wordpress.stackexchange.com/users/194476", "pm_score": 1, "selected": false, "text": "<p>Just stumble on this because I was looking for the solution to same issue.\nDon't know if it was changed but it no longer works (if ever was).\nNow, you have to make call to categories endpoint <code>/categories?parent=&quot;parent_cat_id&quot;</code> in order to get list of child categories, then feed that info into another call (posts) <code>/posts?categories=&quot;1,2,3,4..&quot;&amp;...</code></p>\n" }, { "answer_id": 412543, "author": "Shameer ", "author_id": 159560, "author_profile": "https://wordpress.stackexchange.com/users/159560", "pm_score": 0, "selected": false, "text": "<p>as Tom mentioned in the previous answer, append these queries to the rest API query. for me, it working.</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?page=1&amp;per_page=10&amp;categories[terms][0]=&lt;category_id&gt;&amp;categories[include_children]=true\n</code></pre>\n<p>Replace <code>&lt;category_id&gt;</code> with your actual category id</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314172", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150618/" ]
I'm relatively new to working with wordpress and php in general, so I'd like to know if someone can help me with this. I have a custom query that looks like this ``` <?php $args = array( //argumentos 'numberposts' => -1, 'post_type' => 'cdts', 'meta_key' => 'cargo', 'meta_value' => 'p' ); $the_query = new WP_Query( $args ); //custom query ?> <?php if( $the_query->have_posts()): //loop do wordpress ?> <ul class="lista_candidatos"> <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?> <li> <a href="<?php the_field('link'); ?>"> <?php the_field('nome'); ?> <?php the_field('numero_partido'); ?> (<?php the_field('sigla_partido'); ?>) </a> <p class="ano_cand"><?php the_field('ano_candidatura'); ?></p> </li> <?php endwhile; ?> </ul> <?php else : ?> <p class="err_no_candidato">Sem candidatos cadastrados.</p> <?php endif; ?> <?php wp_reset_query(); //restaura os queries do wp ?> ``` And I have an ACF field that's called "ano\_candidatura". I'd like to know if there is a way to make different things with different "ano\_candidatura", like creating different tabs for each value. Maybe I'm doing something wrong I try to do, for example, ``` <?php if( the_field('ano_candidatura') == '2018'): ?> ``` because when I do this, it just prints '2018' to the page. So, is there a way I can create different html for different the\_field values and equal html to equivalent values?
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. [Here's an example taken from the official Make WP blog](https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/), just do something like this: ``` const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); ``` Which generates a URL that looks like this: ``` /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user ``` Notice
314,175
<p>I have a custom post type called 'Bookmark'.</p> <p>When users add a new Bookmark in the Admin, the title of the page is <h1>Add a new Page</h1></p> <p>Is there a hook (filter) to change this title to <h1>Add a new Bookmark</h1></p>
[ { "answer_id": 314152, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>WP can already do this out of the box thanks to the <code>include_children</code> parameter of <code>tax_query</code> which is true by default.</p>\n<p>While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.</p>\n<p><a href=\"https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/\" rel=\"nofollow noreferrer\">Here's an example taken from the official Make WP blog</a>, just do something like this:</p>\n<pre><code>const query = {\n categories: {\n terms: [ 3, 5, 7 ],\n include_children: true,\n },\n};\nwp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );\n</code></pre>\n<p>Which generates a URL that looks like this:</p>\n<pre><code>/wp-json/wp/v2/posts?categories[terms][0]=3&amp;categories[terms][1]=5&amp;categories[terms][2]=7&amp;categories[include_children]=true&amp;_locale=user\n</code></pre>\n<p>Notice</p>\n" }, { "answer_id": 397628, "author": "Luka Juras", "author_id": 194476, "author_profile": "https://wordpress.stackexchange.com/users/194476", "pm_score": 1, "selected": false, "text": "<p>Just stumble on this because I was looking for the solution to same issue.\nDon't know if it was changed but it no longer works (if ever was).\nNow, you have to make call to categories endpoint <code>/categories?parent=&quot;parent_cat_id&quot;</code> in order to get list of child categories, then feed that info into another call (posts) <code>/posts?categories=&quot;1,2,3,4..&quot;&amp;...</code></p>\n" }, { "answer_id": 412543, "author": "Shameer ", "author_id": 159560, "author_profile": "https://wordpress.stackexchange.com/users/159560", "pm_score": 0, "selected": false, "text": "<p>as Tom mentioned in the previous answer, append these queries to the rest API query. for me, it working.</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?page=1&amp;per_page=10&amp;categories[terms][0]=&lt;category_id&gt;&amp;categories[include_children]=true\n</code></pre>\n<p>Replace <code>&lt;category_id&gt;</code> with your actual category id</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314175", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17248/" ]
I have a custom post type called 'Bookmark'. When users add a new Bookmark in the Admin, the title of the page is Add a new Page ============== Is there a hook (filter) to change this title to Add a new Bookmark ==================
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. [Here's an example taken from the official Make WP blog](https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/), just do something like this: ``` const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); ``` Which generates a URL that looks like this: ``` /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user ``` Notice
314,182
<p><a href="https://i.stack.imgur.com/81kJk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/81kJk.png" alt="enter image description here"></a></p> <p>I am trying to get map from address but there are appear some error like <strong>You have exceeded your request quota for this API</strong> in my console so can anyone help me to fix this.</p> <p>My Javascript code look like below so please check and let me know if i am doing something wrong...</p> <p>Thanks!</p> <pre><code> &lt;?php $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&amp;sensor=false'); $output = json_decode($geocode); //Store values in variable //print_r($output); if($output-&gt;status == 'OK'){ // Check if address is available or not $latitude = $output-&gt;results[0]-&gt;geometry-&gt;location-&gt;lat; //Returns Latitude $longitude = $output-&gt;results[0]-&gt;geometry-&gt;location-&gt;lng; // Returns Longitude } else { echo "Sorry we can't find this location.Check the details again!"; } ?&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function () { // Define the latitude and longitude positions var latitude = parseFloat("&lt;?php echo $latitude; ?&gt;"); // Latitude get from above variable var longitude = parseFloat("&lt;?php echo $longitude; ?&gt;"); // Longitude from same var latlngPos = new google.maps.LatLng(latitude, longitude); // Set up options for the Google map var myOptions = { zoom: 14, center: latlngPos, mapTypeId: google.maps.MapTypeId.ROADMAP, zoomControlOptions: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE } }; // Define the map map = new google.maps.Map(document.getElementById("map"), myOptions); // Add the marker var marker = new google.maps.Marker({ position: latlngPos, map: map, title: "Your Location" }); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 314152, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>WP can already do this out of the box thanks to the <code>include_children</code> parameter of <code>tax_query</code> which is true by default.</p>\n<p>While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms.</p>\n<p><a href=\"https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/\" rel=\"nofollow noreferrer\">Here's an example taken from the official Make WP blog</a>, just do something like this:</p>\n<pre><code>const query = {\n categories: {\n terms: [ 3, 5, 7 ],\n include_children: true,\n },\n};\nwp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } );\n</code></pre>\n<p>Which generates a URL that looks like this:</p>\n<pre><code>/wp-json/wp/v2/posts?categories[terms][0]=3&amp;categories[terms][1]=5&amp;categories[terms][2]=7&amp;categories[include_children]=true&amp;_locale=user\n</code></pre>\n<p>Notice</p>\n" }, { "answer_id": 397628, "author": "Luka Juras", "author_id": 194476, "author_profile": "https://wordpress.stackexchange.com/users/194476", "pm_score": 1, "selected": false, "text": "<p>Just stumble on this because I was looking for the solution to same issue.\nDon't know if it was changed but it no longer works (if ever was).\nNow, you have to make call to categories endpoint <code>/categories?parent=&quot;parent_cat_id&quot;</code> in order to get list of child categories, then feed that info into another call (posts) <code>/posts?categories=&quot;1,2,3,4..&quot;&amp;...</code></p>\n" }, { "answer_id": 412543, "author": "Shameer ", "author_id": 159560, "author_profile": "https://wordpress.stackexchange.com/users/159560", "pm_score": 0, "selected": false, "text": "<p>as Tom mentioned in the previous answer, append these queries to the rest API query. for me, it working.</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?page=1&amp;per_page=10&amp;categories[terms][0]=&lt;category_id&gt;&amp;categories[include_children]=true\n</code></pre>\n<p>Replace <code>&lt;category_id&gt;</code> with your actual category id</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314182", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143123/" ]
[![enter image description here](https://i.stack.imgur.com/81kJk.png)](https://i.stack.imgur.com/81kJk.png) I am trying to get map from address but there are appear some error like **You have exceeded your request quota for this API** in my console so can anyone help me to fix this. My Javascript code look like below so please check and let me know if i am doing something wrong... Thanks! ``` <?php $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false'); $output = json_decode($geocode); //Store values in variable //print_r($output); if($output->status == 'OK'){ // Check if address is available or not $latitude = $output->results[0]->geometry->location->lat; //Returns Latitude $longitude = $output->results[0]->geometry->location->lng; // Returns Longitude } else { echo "Sorry we can't find this location.Check the details again!"; } ?> <script type="text/javascript"> jQuery(document).ready(function () { // Define the latitude and longitude positions var latitude = parseFloat("<?php echo $latitude; ?>"); // Latitude get from above variable var longitude = parseFloat("<?php echo $longitude; ?>"); // Longitude from same var latlngPos = new google.maps.LatLng(latitude, longitude); // Set up options for the Google map var myOptions = { zoom: 14, center: latlngPos, mapTypeId: google.maps.MapTypeId.ROADMAP, zoomControlOptions: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE } }; // Define the map map = new google.maps.Map(document.getElementById("map"), myOptions); // Add the marker var marker = new google.maps.Marker({ position: latlngPos, map: map, title: "Your Location" }); }); </script> ```
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. [Here's an example taken from the official Make WP blog](https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/), just do something like this: ``` const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); ``` Which generates a URL that looks like this: ``` /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user ``` Notice
314,220
<p>I have searched endlessly for this but I am yet to find a solution.</p> <p>I have found ways to add custom classes through functions but can't seem to achieve through woocommerce where a custom class is added on the single product page when a product is out of stock.</p> <p>Any pointers would be much appreciated.</p>
[ { "answer_id": 314223, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": true, "text": "<pre><code>add_filter('body_class', 'SE_314220_custom_outofstock_class');\n\n function SE_314220_custom_outofstock_class ($classes) {\n\n global $post;\n if($post-&gt;post_type !=\"product\")\n return $classes;\n $product = wc_get_product( $post-&gt;ID );\n if($product-&gt;get_stock_quantity() ==0)\n $classes[] = 'OUT-OF-STOCK';\n return $classes;\n}\n</code></pre>\n" }, { "answer_id": 392668, "author": "Mego", "author_id": 169097, "author_profile": "https://wordpress.stackexchange.com/users/169097", "pm_score": 1, "selected": false, "text": "<p>I have updated the code from @Adnrea Somovigo and customize it, to display body classes, based on stock_status, not on stock_quantity. So this should work also for in-stock, on-backorder and out-of-stock stock statuses.</p>\n<p>Stock quantity is not the correct parameter, because backorder products could have negative quantity (for example -6 pieces on stock) and products with 0 pieces could be either out-of-stock, or on-backorder.</p>\n<pre><code>add_filter('body_class', 'lava_stock_class');\n\n function lava_stock_class($classes) {\n global $post;\n if($post-&gt;post_type !=&quot;product&quot;)\n return $classes;\n $product = wc_get_product( $post-&gt;ID );\n if($product-&gt;get_stock_status() == 'outofstock') {\n $classes[] = 'outofstock';\n } elseif($product-&gt;get_stock_status() == 'onbackorder') {\n $classes[] = 'onbackorder';\n } else {\n $classes[] = 'instock';\n }\n\n return $classes; \n}\n</code></pre>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94286/" ]
I have searched endlessly for this but I am yet to find a solution. I have found ways to add custom classes through functions but can't seem to achieve through woocommerce where a custom class is added on the single product page when a product is out of stock. Any pointers would be much appreciated.
``` add_filter('body_class', 'SE_314220_custom_outofstock_class'); function SE_314220_custom_outofstock_class ($classes) { global $post; if($post->post_type !="product") return $classes; $product = wc_get_product( $post->ID ); if($product->get_stock_quantity() ==0) $classes[] = 'OUT-OF-STOCK'; return $classes; } ```
314,240
<p>I'm creating a WordPress child theme based on an existing parent theme, and I'd like to have any same-named file I put in my child theme directory take priority over the file in the parent theme directory. I thought this was how parent/child theming was set up in WP but I have hit a bump.</p> <p>According to the <a href="https://codex.wordpress.org/Child_Themes#Template_Files" rel="nofollow noreferrer">WordPress codex on Child Themes</a>, it says:</p> <blockquote> <p><strong>Template Files</strong> <br> If you want to change more than just the stylesheet, your child theme can override any file in the parent theme: simply include a file of the same name in the child theme directory, and it will override the equivalent file in the parent theme directory when your site loads.</p> </blockquote> <p>In one of my files (header.php), there is an include that looks like this:</p> <pre><code>include get_parent_theme_file_path("folder/file.php") </code></pre> <p>Even though I have a duplicate-named-but-modified version of that file.php in my child theme, it still uses the version in my parent theme. According to the same codex, their recommendation for targeting a child theme file specifically is to use get_stylesheet_directory(), so it would look like this:</p> <pre><code>include (get_stylesheet_directory()."/folder/file.php"); </code></pre> <p>I understand that the purpose of a function called "get_parent_theme_file_path()" is to ignore the parent/child relationship and just get the parent theme version, so without replacing that with a function that explicitly gets a file in my child theme (ie. get_stylesheet_directory), <strong>is there a way I can have some sort of universal get_path() function that checks for child first, if it doesn't exist, get parent version?</strong> </p> <p>By the way, I read <a href="https://wordpress.stackexchange.com/questions/257597/get-parent-theme-file-path-vs-get-template-directory/257613">this Q&amp;A on "get_parent_theme_file_path vs. get_template_directory"</a>, but their solution was to use parent_theme_file filters, but that isn't dynamic, and would require me to write a filter function for every child file I want it to use.</p> <p>Thanks for your help. </p>
[ { "answer_id": 314241, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>This is essentially what <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\"><code>locate_template()</code></a> does.</p>\n<blockquote>\n<p>Searches in the STYLESHEETPATH (child) before TEMPLATEPATH (parent) and <code>wp-includes/theme-compat</code> so that themes which inherit from a parent theme can just overload one file.</p>\n</blockquote>\n" }, { "answer_id": 314249, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>There is a function for this since 4.7: <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"noreferrer\"><code>get_theme_file_path()</code></a></p>\n\n<blockquote>\n <p>Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.</p>\n</blockquote>\n\n<p>So if you do this:</p>\n\n<pre><code>include get_theme_file_path( 'folder/file.php' );\n</code></pre>\n\n<p><code>folder/file.php</code> will be loaded from the child theme, if it exists, otherwise the parent theme.</p>\n\n<p>This doesn't work for <code>get_stylesheet_directory()</code>, because the actual file path is not passed to <code>get_stylesheet_directory()</code>, so it has no way of knowing what file to look for.</p>\n\n<p>The equivalent function for URLs is <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"noreferrer\"><code>get_theme_file_uri()</code></a>. This will get the URL for a file if it exists in the child theme, otherwise it will get it for the file in the parent theme.</p>\n\n<p>Each function has a matching version that only searches the parent theme:</p>\n\n<pre><code>get_parent_theme_file_path();\nget_parent_theme_file_uri();\n</code></pre>\n\n<p>For templates, you should use <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"noreferrer\"><code>get_template_part()</code></a>. This lets you include PHP files that can be replaced by child themes, with some extra features, like an optional suffix to the name.</p>\n\n<p>PS: The Codex is somewhat outdated. Unless a specific article has yet to be ported over, the developer documentation you should use is at <a href=\"https://developer.wordpress.org/themes/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/</a>.</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2080/" ]
I'm creating a WordPress child theme based on an existing parent theme, and I'd like to have any same-named file I put in my child theme directory take priority over the file in the parent theme directory. I thought this was how parent/child theming was set up in WP but I have hit a bump. According to the [WordPress codex on Child Themes](https://codex.wordpress.org/Child_Themes#Template_Files), it says: > > **Template Files** > > If you want to change more than just the stylesheet, > your child theme can override any file in the parent theme: simply > include a file of the same name in the child theme directory, and it > will override the equivalent file in the parent theme directory when > your site loads. > > > In one of my files (header.php), there is an include that looks like this: ``` include get_parent_theme_file_path("folder/file.php") ``` Even though I have a duplicate-named-but-modified version of that file.php in my child theme, it still uses the version in my parent theme. According to the same codex, their recommendation for targeting a child theme file specifically is to use get\_stylesheet\_directory(), so it would look like this: ``` include (get_stylesheet_directory()."/folder/file.php"); ``` I understand that the purpose of a function called "get\_parent\_theme\_file\_path()" is to ignore the parent/child relationship and just get the parent theme version, so without replacing that with a function that explicitly gets a file in my child theme (ie. get\_stylesheet\_directory), **is there a way I can have some sort of universal get\_path() function that checks for child first, if it doesn't exist, get parent version?** By the way, I read [this Q&A on "get\_parent\_theme\_file\_path vs. get\_template\_directory"](https://wordpress.stackexchange.com/questions/257597/get-parent-theme-file-path-vs-get-template-directory/257613), but their solution was to use parent\_theme\_file filters, but that isn't dynamic, and would require me to write a filter function for every child file I want it to use. Thanks for your help.
This is essentially what [`locate_template()`](https://developer.wordpress.org/reference/functions/locate_template/) does. > > Searches in the STYLESHEETPATH (child) before TEMPLATEPATH (parent) and `wp-includes/theme-compat` so that themes which inherit from a parent theme can just overload one file. > > >
314,242
<p>I have a Gravity Form that on submission sends the data to a third party API. It is connecting with the following code and saving the data through the API. However, I'm now trying to figure out how to only send the Admin notification email if the API response comes back as a fail or anything other than status code 201.</p> <pre><code>add_action( 'gform_after_submission_1', 'post_to_third_party', 10, 2 ); function post_to_third_party( $entry, $form ) { $post_url = 'http://thirdpartyapiurl.com'; $headers = array( 'Cache-Control' =&gt; 'no-cache', 'session-id' =&gt; '123456789101112' ); $body = '{ "Sales_Doc_Type": "QUOTE", "Sales_Doc_ID": "CGRV", "Sales_Batch": "WEB QUOTES", "Customer_Num": "00", "Customer_Name": "'.rgar( $entry, '1' ).'", "Price_Level": "SHOP 3", "Shipping_Method": "GROUND FREIGHT", "Tax_Schedule": "TBD", "Warehouse_Code": "CG1", "Sales_Person_ID": "HOUSE ACCOUNT", "Sales_Territory": "RV1", "Payment_Terms": "PREPAYMENT", "Created_By": "API USER", "Web_Site": "", "UserFieldData": [ "WEB FORM", "CERT FUNDS", "'.rgar( $entry, '1' ).'", "'.rgar( $entry, '98.1' ).'", "'.rgar( $entry, '98.2' ).'", "'.rgar( $entry, '98.3' ).'", "'.rgar( $entry, '98.4' ).'", "'.rgar( $entry, '98.5' ).'", "'.rgar( $entry, '98.6' ).'", "'.rgar( $entry, '98.7' ).'", "'.rgar( $entry, '3' ).'", "'.rgar( $entry, '6' ).'", "'.rgar( $entry, '8' ).'", "'.rgar( $entry, '9' ).'", "'.rgar( $entry, '11.1' ).'", "'.rgar( $entry, '99.1' ).'", "'.rgar( $entry, '99.2' ).'", "'.rgar( $entry, '99.3' ).'", "'.rgar( $entry, '99.4' ).'", "'.rgar( $entry, '99.5' ).'", "'.rgar( $entry, '99.6' ).'", "'.rgar( $entry, '99.7' ).'", "'.rgar( $entry, '16' ).'", "'.rgar( $entry, '18' ).'", "'.rgar( $entry, '19' ).'", "'.rgar( $entry, '20' ).'", "'.rgar( $entry, '22' ).'", "'.rgar( $entry, '90' ).'", "'.rgar( $entry, '24' ).'", "'.rgar( $entry, '25' ).'", "'.rgar( $entry, '94' ).'", "'.rgar( $entry, '27' ).'", "'.rgar( $entry, '28' ).'", "'.rgar( $entry, '93' ).'", "'.rgar( $entry, '95' ).'", "'.rgar( $entry, '51' ).'", "'.rgar( $entry, '115' ).'", "'.rgar( $entry, '77' ).'", "'.rgar( $entry, '76' ).'", "'.rgar( $entry, '49' ).'", "", "'.rgar( $entry, '114' ).'", "'.rgar( $entry, '50' ).'", "'.rgar( $entry, '69' ).'", "'.rgar( $entry, '70' ).'", "'.rgar( $entry, '73' ).'", "'.rgar( $entry, '55' ).'", "'.rgar( $entry, '56' ).'", "'.rgar( $entry, '46' ).'", "'.rgar( $entry, '48' ).'", "'.rgar( $entry, '57' ).'", "'.rgar( $entry, '58' ).'", "'.rgar( $entry, '62' ).'", "'.rgar( $entry, '64' ).'", "'.rgar( $entry, '65' ).'", "'.rgar( $entry, '66' ).'", "'.rgar( $entry, '80' ).'", "'.base64_encode(rgar( $entry, '82' )).'", "'.base64_encode(rgar( $entry, '85' )).'", "'.base64_encode(rgar( $entry, '86' )).'", "'.base64_encode(rgar( $entry, '89' )).'", "'.base64_encode(rgar( $entry, '88' )).'", "'.base64_encode(rgar( $entry, '87' )).'", "'.rgar( $entry, '91' ).'", "" ], "UserFieldNames": [ "CGRV_Sales_Originating_Source", "CGRV_Payment_Type", "CGRV_QTE_Contact", "JAJ_Ship_Address_Line_1", "JAJ_Ship_Address_Line_2", "JAJ_Ship_Address_Line_3", "JAJ_Ship_City", "JAJ_Ship_State", "JAJ_Ship_Zip", "JAJ_Ship_Country", "JAJ_Ship_Phone_1", "JAJ_Ship_Email_To", "JAJ_Ship_Contact_Person", "JAJ_Customer_Website", "JAJ_Residential", "JAJ_Bill_Address_Line_1", "JAJ_Bill_Address_Line_2", "JAJ_Bill_Address_Line_3", "JAJ_Bill_City", "JAJ_Bill_State", "JAJ_Bill_Zip", "JAJ_Bill_Country", "JAJ_Bill_Phone_1", "JAJ_Bill_Fax", "JAJ_Bill_Email_To", "JAJ_Bill_Contact_Person", "CGRV_QTE_Application_Inquiry", "CGRV_QTE_Year", "CGRV_QTE_Make", "CGRV_QTE_Model", "CGRV_QTE_Part_Number", "CGRV_QTE_Qty_Needed", "CGRV_QTE_SideNeeded", "JAJ_VIN", "CGRV_QTE_WshldNums", "CGRV_QTE_Wshld_Mfg", "CGRV_QTE_DOT_Number", "CGRV_QTE_Height", "CGRV_QTE_Width", "CGRV_QTE_Ceramicv1", "", "CGRV_QTE_Color", "CGRV_QTE_Installation", "CGRV_QTE_SG_Window_Side", "CGRV_QTE_SG_Window_Loc", "CGRV_QTE_SG_Quote_Needed_For", "CGRV_QTE_SG_Frame_Color", "CGRV_QTE_SG_Glass_Color", "CGRV_QTE_SG_Frame_Height", "CGRV_QTE_SG_Frame_Width", "CGRV_QTE_SG_Glass_Height", "CGRV_QTE_SG_Glass_Width", "CGRV_QTE_SG_Emergency_Exit", "CGRV_QTE_SG_Window_Movement", "CGRV_QTE_SG_Glass_Pane", "CGRV_QTE_SG_Frame_Corners", "CGRV_QTE_SG_Additional_Info", "JAJ_File_Attachment_01", "JAJ_File_Attachment_02", "JAJ_File_Attachment_03", "JAJ_File_Attachment_04", "JAJ_File_Attachment_05", "JAJ_File_Attachment_06", "JAJ_Referred_By", "JAJ_Referred_By_Other_Defined" ] }'; GFCommon::log_debug( 'gform_after_submission: body =&gt; ' . print_r( $body, true ) ); $request = new WP_Http(); $response = $request-&gt;post( $post_url, array( 'headers' =&gt; $headers, 'body' =&gt; $body ) ); GFCommon::log_debug( 'gform_after_submission: response =&gt; ' . print_r( $response, true ) ); } </code></pre> <p>I also have a Gravity Form Addon plugin that I've been working on that has an option in the Notification area to select the "Third Party" api and control the email notification instead of Gravity Forms sending it automatically. I just can't figure out how to control the admin notification email based on the response from the API.</p> <pre><code>GFForms::include_addon_framework(); class GFApiNotificationAddOn extends GFAddOn { protected $_version = GF_API_NOTIFICATION_ADDON_VERSION; protected $_min_gravityforms_version = '1.9'; protected $_slug = 'apinotificationaddon'; protected $_path = 'apinotificationaddon/apinotificationaddon.php'; protected $_full_path = __FILE__; protected $_title = 'Gravity Forms Admin Notification Add-On'; protected $_short_title = 'Admin Notification Add-On'; /** * @var object $_instance If available, contains an instance of this class. */ private static $_instance = null; /** * Returns an instance of this class, and stores it in the $_instance property. * * @return object $_instance An instance of this class. */ public static function get_instance() { if ( self::$_instance == null ) { self::$_instance = new self(); } return self::$_instance; } /** * Plugin starting point. Handles hooks, loading of language files and PayPal delayed payment support. */ public function init() { parent::init(); add_filter( 'gform_notification_services', array( $this, 'add_notification_service' ) ); add_filter( 'gform_pre_send_email', array( $this, 'api_fail_send_email' ), 19, 3 ); } /** * Add the new notification service. * * @param array $services The notification services. * * @return array */ public function add_notification_service( $services ) { $services['api_fail_email'] = array( 'label' =&gt; esc_html__( 'Third Party API Notice', 'apinotificationaddon' ), 'image' =&gt; $this-&gt;get_base_url() . '/images/icon.png', ); return $services; } public function api_fail_send_email( $email, $message_format, $notification ) { global $response; // If the notification is not assigned to this service, return the email. if ( rgar( $notification, 'service' ) !== 'api_fail_email' ) { return $email; } // If the email has already been aborted, return the email. if ( $email['abort_email'] ) { $this-&gt;log_debug( __METHOD__ . '(): Not sending email because the notification has already been aborted by another Add-On.' ); return $email; } $result = $this-&gt;send_email( $email, $message_format, $notification ); if ( $result ) { // The service successfully sent the email; prevent WordPress and other add-ons from also sending the email. $email['abort_email'] = true; } return $email; } /** * Send the email via the new service. * * @param array $email The email properties. * @param string $message_format The message format, html or text. * @param array $notification The Notification object which produced the current email. * * @return bool */ public function send_email( $email, $message_format, $notification ) { // pass the email to the service return $result; } public function init_admin() { parent::init_admin(); add_filter( 'gform_tooltips', array( $this, 'tooltips' ) ); add_action( 'gform_field_appearance_settings', array( $this, 'field_appearance_settings' ), 10, 2 ); } // # SCRIPTS &amp; STYLES ----------------------------------------------------------------------------------------------- /** * Include my_script.js when the form contains a 'simple' type field. * * @return array */ public function scripts() { $scripts = array( array( 'handle' =&gt; 'my_script_js', 'src' =&gt; $this-&gt;get_base_url() . '/js/my_script.js', 'version' =&gt; $this-&gt;_version, 'deps' =&gt; array( 'jquery' ), 'enqueue' =&gt; array( array( 'field_types' =&gt; array( 'simple' ) ), ), ), ); return array_merge( parent::scripts(), $scripts ); } /** * Include my_styles.css when the form contains a 'simple' type field. * * @return array */ public function styles() { $styles = array( array( 'handle' =&gt; 'my_styles_css', 'src' =&gt; $this-&gt;get_base_url() . '/css/my_styles.css', 'version' =&gt; $this-&gt;_version, 'enqueue' =&gt; array( array( 'field_types' =&gt; array( 'simple' ) ) ) ) ); return array_merge( parent::styles(), $styles ); } } </code></pre> <p>I can use the following to get the response code after the submission</p> <pre><code>$status = wp_remote_retrieve_response_code( $response ); </code></pre>
[ { "answer_id": 314241, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>This is essentially what <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\"><code>locate_template()</code></a> does.</p>\n<blockquote>\n<p>Searches in the STYLESHEETPATH (child) before TEMPLATEPATH (parent) and <code>wp-includes/theme-compat</code> so that themes which inherit from a parent theme can just overload one file.</p>\n</blockquote>\n" }, { "answer_id": 314249, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>There is a function for this since 4.7: <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"noreferrer\"><code>get_theme_file_path()</code></a></p>\n\n<blockquote>\n <p>Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.</p>\n</blockquote>\n\n<p>So if you do this:</p>\n\n<pre><code>include get_theme_file_path( 'folder/file.php' );\n</code></pre>\n\n<p><code>folder/file.php</code> will be loaded from the child theme, if it exists, otherwise the parent theme.</p>\n\n<p>This doesn't work for <code>get_stylesheet_directory()</code>, because the actual file path is not passed to <code>get_stylesheet_directory()</code>, so it has no way of knowing what file to look for.</p>\n\n<p>The equivalent function for URLs is <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"noreferrer\"><code>get_theme_file_uri()</code></a>. This will get the URL for a file if it exists in the child theme, otherwise it will get it for the file in the parent theme.</p>\n\n<p>Each function has a matching version that only searches the parent theme:</p>\n\n<pre><code>get_parent_theme_file_path();\nget_parent_theme_file_uri();\n</code></pre>\n\n<p>For templates, you should use <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"noreferrer\"><code>get_template_part()</code></a>. This lets you include PHP files that can be replaced by child themes, with some extra features, like an optional suffix to the name.</p>\n\n<p>PS: The Codex is somewhat outdated. Unless a specific article has yet to be ported over, the developer documentation you should use is at <a href=\"https://developer.wordpress.org/themes/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/</a>.</p>\n" } ]
2018/09/14
[ "https://wordpress.stackexchange.com/questions/314242", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81422/" ]
I have a Gravity Form that on submission sends the data to a third party API. It is connecting with the following code and saving the data through the API. However, I'm now trying to figure out how to only send the Admin notification email if the API response comes back as a fail or anything other than status code 201. ``` add_action( 'gform_after_submission_1', 'post_to_third_party', 10, 2 ); function post_to_third_party( $entry, $form ) { $post_url = 'http://thirdpartyapiurl.com'; $headers = array( 'Cache-Control' => 'no-cache', 'session-id' => '123456789101112' ); $body = '{ "Sales_Doc_Type": "QUOTE", "Sales_Doc_ID": "CGRV", "Sales_Batch": "WEB QUOTES", "Customer_Num": "00", "Customer_Name": "'.rgar( $entry, '1' ).'", "Price_Level": "SHOP 3", "Shipping_Method": "GROUND FREIGHT", "Tax_Schedule": "TBD", "Warehouse_Code": "CG1", "Sales_Person_ID": "HOUSE ACCOUNT", "Sales_Territory": "RV1", "Payment_Terms": "PREPAYMENT", "Created_By": "API USER", "Web_Site": "", "UserFieldData": [ "WEB FORM", "CERT FUNDS", "'.rgar( $entry, '1' ).'", "'.rgar( $entry, '98.1' ).'", "'.rgar( $entry, '98.2' ).'", "'.rgar( $entry, '98.3' ).'", "'.rgar( $entry, '98.4' ).'", "'.rgar( $entry, '98.5' ).'", "'.rgar( $entry, '98.6' ).'", "'.rgar( $entry, '98.7' ).'", "'.rgar( $entry, '3' ).'", "'.rgar( $entry, '6' ).'", "'.rgar( $entry, '8' ).'", "'.rgar( $entry, '9' ).'", "'.rgar( $entry, '11.1' ).'", "'.rgar( $entry, '99.1' ).'", "'.rgar( $entry, '99.2' ).'", "'.rgar( $entry, '99.3' ).'", "'.rgar( $entry, '99.4' ).'", "'.rgar( $entry, '99.5' ).'", "'.rgar( $entry, '99.6' ).'", "'.rgar( $entry, '99.7' ).'", "'.rgar( $entry, '16' ).'", "'.rgar( $entry, '18' ).'", "'.rgar( $entry, '19' ).'", "'.rgar( $entry, '20' ).'", "'.rgar( $entry, '22' ).'", "'.rgar( $entry, '90' ).'", "'.rgar( $entry, '24' ).'", "'.rgar( $entry, '25' ).'", "'.rgar( $entry, '94' ).'", "'.rgar( $entry, '27' ).'", "'.rgar( $entry, '28' ).'", "'.rgar( $entry, '93' ).'", "'.rgar( $entry, '95' ).'", "'.rgar( $entry, '51' ).'", "'.rgar( $entry, '115' ).'", "'.rgar( $entry, '77' ).'", "'.rgar( $entry, '76' ).'", "'.rgar( $entry, '49' ).'", "", "'.rgar( $entry, '114' ).'", "'.rgar( $entry, '50' ).'", "'.rgar( $entry, '69' ).'", "'.rgar( $entry, '70' ).'", "'.rgar( $entry, '73' ).'", "'.rgar( $entry, '55' ).'", "'.rgar( $entry, '56' ).'", "'.rgar( $entry, '46' ).'", "'.rgar( $entry, '48' ).'", "'.rgar( $entry, '57' ).'", "'.rgar( $entry, '58' ).'", "'.rgar( $entry, '62' ).'", "'.rgar( $entry, '64' ).'", "'.rgar( $entry, '65' ).'", "'.rgar( $entry, '66' ).'", "'.rgar( $entry, '80' ).'", "'.base64_encode(rgar( $entry, '82' )).'", "'.base64_encode(rgar( $entry, '85' )).'", "'.base64_encode(rgar( $entry, '86' )).'", "'.base64_encode(rgar( $entry, '89' )).'", "'.base64_encode(rgar( $entry, '88' )).'", "'.base64_encode(rgar( $entry, '87' )).'", "'.rgar( $entry, '91' ).'", "" ], "UserFieldNames": [ "CGRV_Sales_Originating_Source", "CGRV_Payment_Type", "CGRV_QTE_Contact", "JAJ_Ship_Address_Line_1", "JAJ_Ship_Address_Line_2", "JAJ_Ship_Address_Line_3", "JAJ_Ship_City", "JAJ_Ship_State", "JAJ_Ship_Zip", "JAJ_Ship_Country", "JAJ_Ship_Phone_1", "JAJ_Ship_Email_To", "JAJ_Ship_Contact_Person", "JAJ_Customer_Website", "JAJ_Residential", "JAJ_Bill_Address_Line_1", "JAJ_Bill_Address_Line_2", "JAJ_Bill_Address_Line_3", "JAJ_Bill_City", "JAJ_Bill_State", "JAJ_Bill_Zip", "JAJ_Bill_Country", "JAJ_Bill_Phone_1", "JAJ_Bill_Fax", "JAJ_Bill_Email_To", "JAJ_Bill_Contact_Person", "CGRV_QTE_Application_Inquiry", "CGRV_QTE_Year", "CGRV_QTE_Make", "CGRV_QTE_Model", "CGRV_QTE_Part_Number", "CGRV_QTE_Qty_Needed", "CGRV_QTE_SideNeeded", "JAJ_VIN", "CGRV_QTE_WshldNums", "CGRV_QTE_Wshld_Mfg", "CGRV_QTE_DOT_Number", "CGRV_QTE_Height", "CGRV_QTE_Width", "CGRV_QTE_Ceramicv1", "", "CGRV_QTE_Color", "CGRV_QTE_Installation", "CGRV_QTE_SG_Window_Side", "CGRV_QTE_SG_Window_Loc", "CGRV_QTE_SG_Quote_Needed_For", "CGRV_QTE_SG_Frame_Color", "CGRV_QTE_SG_Glass_Color", "CGRV_QTE_SG_Frame_Height", "CGRV_QTE_SG_Frame_Width", "CGRV_QTE_SG_Glass_Height", "CGRV_QTE_SG_Glass_Width", "CGRV_QTE_SG_Emergency_Exit", "CGRV_QTE_SG_Window_Movement", "CGRV_QTE_SG_Glass_Pane", "CGRV_QTE_SG_Frame_Corners", "CGRV_QTE_SG_Additional_Info", "JAJ_File_Attachment_01", "JAJ_File_Attachment_02", "JAJ_File_Attachment_03", "JAJ_File_Attachment_04", "JAJ_File_Attachment_05", "JAJ_File_Attachment_06", "JAJ_Referred_By", "JAJ_Referred_By_Other_Defined" ] }'; GFCommon::log_debug( 'gform_after_submission: body => ' . print_r( $body, true ) ); $request = new WP_Http(); $response = $request->post( $post_url, array( 'headers' => $headers, 'body' => $body ) ); GFCommon::log_debug( 'gform_after_submission: response => ' . print_r( $response, true ) ); } ``` I also have a Gravity Form Addon plugin that I've been working on that has an option in the Notification area to select the "Third Party" api and control the email notification instead of Gravity Forms sending it automatically. I just can't figure out how to control the admin notification email based on the response from the API. ``` GFForms::include_addon_framework(); class GFApiNotificationAddOn extends GFAddOn { protected $_version = GF_API_NOTIFICATION_ADDON_VERSION; protected $_min_gravityforms_version = '1.9'; protected $_slug = 'apinotificationaddon'; protected $_path = 'apinotificationaddon/apinotificationaddon.php'; protected $_full_path = __FILE__; protected $_title = 'Gravity Forms Admin Notification Add-On'; protected $_short_title = 'Admin Notification Add-On'; /** * @var object $_instance If available, contains an instance of this class. */ private static $_instance = null; /** * Returns an instance of this class, and stores it in the $_instance property. * * @return object $_instance An instance of this class. */ public static function get_instance() { if ( self::$_instance == null ) { self::$_instance = new self(); } return self::$_instance; } /** * Plugin starting point. Handles hooks, loading of language files and PayPal delayed payment support. */ public function init() { parent::init(); add_filter( 'gform_notification_services', array( $this, 'add_notification_service' ) ); add_filter( 'gform_pre_send_email', array( $this, 'api_fail_send_email' ), 19, 3 ); } /** * Add the new notification service. * * @param array $services The notification services. * * @return array */ public function add_notification_service( $services ) { $services['api_fail_email'] = array( 'label' => esc_html__( 'Third Party API Notice', 'apinotificationaddon' ), 'image' => $this->get_base_url() . '/images/icon.png', ); return $services; } public function api_fail_send_email( $email, $message_format, $notification ) { global $response; // If the notification is not assigned to this service, return the email. if ( rgar( $notification, 'service' ) !== 'api_fail_email' ) { return $email; } // If the email has already been aborted, return the email. if ( $email['abort_email'] ) { $this->log_debug( __METHOD__ . '(): Not sending email because the notification has already been aborted by another Add-On.' ); return $email; } $result = $this->send_email( $email, $message_format, $notification ); if ( $result ) { // The service successfully sent the email; prevent WordPress and other add-ons from also sending the email. $email['abort_email'] = true; } return $email; } /** * Send the email via the new service. * * @param array $email The email properties. * @param string $message_format The message format, html or text. * @param array $notification The Notification object which produced the current email. * * @return bool */ public function send_email( $email, $message_format, $notification ) { // pass the email to the service return $result; } public function init_admin() { parent::init_admin(); add_filter( 'gform_tooltips', array( $this, 'tooltips' ) ); add_action( 'gform_field_appearance_settings', array( $this, 'field_appearance_settings' ), 10, 2 ); } // # SCRIPTS & STYLES ----------------------------------------------------------------------------------------------- /** * Include my_script.js when the form contains a 'simple' type field. * * @return array */ public function scripts() { $scripts = array( array( 'handle' => 'my_script_js', 'src' => $this->get_base_url() . '/js/my_script.js', 'version' => $this->_version, 'deps' => array( 'jquery' ), 'enqueue' => array( array( 'field_types' => array( 'simple' ) ), ), ), ); return array_merge( parent::scripts(), $scripts ); } /** * Include my_styles.css when the form contains a 'simple' type field. * * @return array */ public function styles() { $styles = array( array( 'handle' => 'my_styles_css', 'src' => $this->get_base_url() . '/css/my_styles.css', 'version' => $this->_version, 'enqueue' => array( array( 'field_types' => array( 'simple' ) ) ) ) ); return array_merge( parent::styles(), $styles ); } } ``` I can use the following to get the response code after the submission ``` $status = wp_remote_retrieve_response_code( $response ); ```
This is essentially what [`locate_template()`](https://developer.wordpress.org/reference/functions/locate_template/) does. > > Searches in the STYLESHEETPATH (child) before TEMPLATEPATH (parent) and `wp-includes/theme-compat` so that themes which inherit from a parent theme can just overload one file. > > >
314,296
<p>Not sure what I'm doing wrong here. I am a beginner coder, but I've tried a lot of things already:</p> <p>I'm trying to print the_content from the post_parent of an image. Here's what I'm using right now. I am able to post the title, but not the content (all I can succeed in printing content-wise is the image's content (which is actually the image's 'description' which is not what I'm looking for.</p> <pre><code>&lt;?php echo wp_get_attachment_image( $post-&gt;ID, 'post-image' ); ?&gt; &lt;h4 class="attach-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt; &lt;p&gt; &lt;a href="&lt;?php echo get_permalink( $post-&gt;post_parent ); ?&gt;" title="&lt;?php esc_attr( printf( __( 'Return to %s', APP_TD ), get_the_title( $post-&gt;post_parent ) ) ); ?&gt;" rel="gallery"&gt; &lt;?php printf( '&lt;span class="meta-nav"&gt;' . __( '&amp;larr; Return to %s', APP_TD ) . '&lt;/span&gt;', get_the_title( $post-&gt;post_parent ) ); ?&gt; &lt;/a&gt; &lt;/p&gt; &lt;p&gt; &lt;a href="&lt;?php echo get_permalink( $post-&gt;post_parent ); ?&gt;" the_content="&lt;?php esc_attr( printf( __( 'Return to %s', APP_TD ), get_the_content( $post-&gt;post_parent ) ) ); ?&gt;" rel="gallery"&gt; &lt;?php printf( '&lt;span class="meta-nav"&gt;' . __( '&amp;larr; Return to %s', APP_TD ) . '&lt;/span&gt;', get_the_content( $post-&gt;post_parent ) ); ?&gt; &lt;/a&gt; &lt;/p&gt; </code></pre> <p>The first 2 pieces of code work correctly, but the last paragraph is where I want to pull the content. But this code just prints the description of the image itself rather than the post_parent's content.</p>
[ { "answer_id": 314241, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>This is essentially what <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\"><code>locate_template()</code></a> does.</p>\n<blockquote>\n<p>Searches in the STYLESHEETPATH (child) before TEMPLATEPATH (parent) and <code>wp-includes/theme-compat</code> so that themes which inherit from a parent theme can just overload one file.</p>\n</blockquote>\n" }, { "answer_id": 314249, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>There is a function for this since 4.7: <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"noreferrer\"><code>get_theme_file_path()</code></a></p>\n\n<blockquote>\n <p>Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.</p>\n</blockquote>\n\n<p>So if you do this:</p>\n\n<pre><code>include get_theme_file_path( 'folder/file.php' );\n</code></pre>\n\n<p><code>folder/file.php</code> will be loaded from the child theme, if it exists, otherwise the parent theme.</p>\n\n<p>This doesn't work for <code>get_stylesheet_directory()</code>, because the actual file path is not passed to <code>get_stylesheet_directory()</code>, so it has no way of knowing what file to look for.</p>\n\n<p>The equivalent function for URLs is <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"noreferrer\"><code>get_theme_file_uri()</code></a>. This will get the URL for a file if it exists in the child theme, otherwise it will get it for the file in the parent theme.</p>\n\n<p>Each function has a matching version that only searches the parent theme:</p>\n\n<pre><code>get_parent_theme_file_path();\nget_parent_theme_file_uri();\n</code></pre>\n\n<p>For templates, you should use <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"noreferrer\"><code>get_template_part()</code></a>. This lets you include PHP files that can be replaced by child themes, with some extra features, like an optional suffix to the name.</p>\n\n<p>PS: The Codex is somewhat outdated. Unless a specific article has yet to be ported over, the developer documentation you should use is at <a href=\"https://developer.wordpress.org/themes/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/</a>.</p>\n" } ]
2018/09/15
[ "https://wordpress.stackexchange.com/questions/314296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95192/" ]
Not sure what I'm doing wrong here. I am a beginner coder, but I've tried a lot of things already: I'm trying to print the\_content from the post\_parent of an image. Here's what I'm using right now. I am able to post the title, but not the content (all I can succeed in printing content-wise is the image's content (which is actually the image's 'description' which is not what I'm looking for. ``` <?php echo wp_get_attachment_image( $post->ID, 'post-image' ); ?> <h4 class="attach-title"><?php the_title(); ?></h4> <p> <a href="<?php echo get_permalink( $post->post_parent ); ?>" title="<?php esc_attr( printf( __( 'Return to %s', APP_TD ), get_the_title( $post->post_parent ) ) ); ?>" rel="gallery"> <?php printf( '<span class="meta-nav">' . __( '&larr; Return to %s', APP_TD ) . '</span>', get_the_title( $post->post_parent ) ); ?> </a> </p> <p> <a href="<?php echo get_permalink( $post->post_parent ); ?>" the_content="<?php esc_attr( printf( __( 'Return to %s', APP_TD ), get_the_content( $post->post_parent ) ) ); ?>" rel="gallery"> <?php printf( '<span class="meta-nav">' . __( '&larr; Return to %s', APP_TD ) . '</span>', get_the_content( $post->post_parent ) ); ?> </a> </p> ``` The first 2 pieces of code work correctly, but the last paragraph is where I want to pull the content. But this code just prints the description of the image itself rather than the post\_parent's content.
This is essentially what [`locate_template()`](https://developer.wordpress.org/reference/functions/locate_template/) does. > > Searches in the STYLESHEETPATH (child) before TEMPLATEPATH (parent) and `wp-includes/theme-compat` so that themes which inherit from a parent theme can just overload one file. > > >
314,325
<p>I am using <code>wordpress 4.9.8</code> and <code>PHP 7.1.8</code> I have added a button to the new post screen:</p> <p><a href="https://i.stack.imgur.com/eiQbM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eiQbM.png" alt="enter image description here"></a></p> <p>I am trying to trigger the button the following way:</p> <pre><code>add_action( 'media_buttons', 'add_my_media_button', 99 ); function add_my_media_button() { $post = $GLOBALS['post_ID']; echo "&lt;a href='#' id='insert-my-media' data-post-id='{$post}' class='button'&gt;Own content&lt;/a&gt;"; } add_action( 'wp_ajax_my_action', 'updateContent' ); function updateContent() { $post_id = intval( $_POST['post_id'] ); wp_die(); // this is required to terminate immediately and return a proper response $post = array( 'ID' =&gt; $post_id, 'post_content' =&gt; 'Insert this content', ); // Update the post into the database wp_update_post( $post ); } add_action( 'admin_footer', 'my_media_button_script' ); function my_media_button_script() { ?&gt; &lt;script&gt; jQuery(document).ready(function ($) { $('#insert-my-media').click(function () { var post_id = $(this).attr('data-post-id'); var data = { 'action': 'updateContent', 'post_id': post_id }; console.log("test: " + ajaxurl) console.log(data) // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(ajaxurl, data, function (response) { alert('Got this from the server: ' + response); }); }); }); &lt;/script&gt; &lt;?php } </code></pre> <p>However, when pressing submit I get:</p> <p><a href="https://i.stack.imgur.com/eiQbM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eiQbM.png" alt="enter image description here"></a></p> <p>Any suggestions why I get this error.</p> <p>The above code was partly taken from the official <a href="https://codex.wordpress.org/AJAX_in_Plugins" rel="nofollow noreferrer">reference</a>.</p>
[ { "answer_id": 343221, "author": "Ahadul", "author_id": 147734, "author_profile": "https://wordpress.stackexchange.com/users/147734", "pm_score": 2, "selected": true, "text": "<p>Remove this line </p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'updateContent' );\n</code></pre>\n\n<p>Add this two Line</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_updateContent', 'updateContent' );\nadd_action( 'wp_ajax_updateContent', 'updateContent' );\n</code></pre>\n\n<p>hopefully it will solve your issue</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)</a></p>\n" }, { "answer_id": 343239, "author": "vikas jain", "author_id": 172136, "author_profile": "https://wordpress.stackexchange.com/users/172136", "pm_score": -1, "selected": false, "text": "<p>Replace this\n<strong>add_action( 'wp_ajax_my_action', 'updateContent' );</strong></p>\n\n<p>with </p>\n\n<p><strong>add_action( 'wp_ajax_updateContent', 'updateContent' );\nadd_action( 'wp_ajax_nopriv_updateContent', 'updateContent' );</strong></p>\n\n<p>Happy codeing</p>\n" } ]
2018/09/16
[ "https://wordpress.stackexchange.com/questions/314325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48703/" ]
I am using `wordpress 4.9.8` and `PHP 7.1.8` I have added a button to the new post screen: [![enter image description here](https://i.stack.imgur.com/eiQbM.png)](https://i.stack.imgur.com/eiQbM.png) I am trying to trigger the button the following way: ``` add_action( 'media_buttons', 'add_my_media_button', 99 ); function add_my_media_button() { $post = $GLOBALS['post_ID']; echo "<a href='#' id='insert-my-media' data-post-id='{$post}' class='button'>Own content</a>"; } add_action( 'wp_ajax_my_action', 'updateContent' ); function updateContent() { $post_id = intval( $_POST['post_id'] ); wp_die(); // this is required to terminate immediately and return a proper response $post = array( 'ID' => $post_id, 'post_content' => 'Insert this content', ); // Update the post into the database wp_update_post( $post ); } add_action( 'admin_footer', 'my_media_button_script' ); function my_media_button_script() { ?> <script> jQuery(document).ready(function ($) { $('#insert-my-media').click(function () { var post_id = $(this).attr('data-post-id'); var data = { 'action': 'updateContent', 'post_id': post_id }; console.log("test: " + ajaxurl) console.log(data) // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(ajaxurl, data, function (response) { alert('Got this from the server: ' + response); }); }); }); </script> <?php } ``` However, when pressing submit I get: [![enter image description here](https://i.stack.imgur.com/eiQbM.png)](https://i.stack.imgur.com/eiQbM.png) Any suggestions why I get this error. The above code was partly taken from the official [reference](https://codex.wordpress.org/AJAX_in_Plugins).
Remove this line ``` add_action( 'wp_ajax_my_action', 'updateContent' ); ``` Add this two Line ``` add_action( 'wp_ajax_nopriv_updateContent', 'updateContent' ); add_action( 'wp_ajax_updateContent', 'updateContent' ); ``` hopefully it will solve your issue <https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)>
314,370
<p>I regularly need to create a batch of posts of a custom post type, with names and meta values that follow a regular pattern. This seems like a perfect canditate for using wp-cli, but so far it hasn't worked.</p> <p>Using wp-cli, if I enter:</p> <pre><code>wp post create --post_title='test' --post_status='draft' post_type='class_notes' </code></pre> <p>I get an error:</p> <blockquote> <p>Unable to read content from 'post_type=class_notes'.</p> </blockquote> <p>However wp-cli is definitely able to connect to this post type, as the following returns a proper list of labels and capabilities:</p> <pre><code>wp post-type get 'class_notes' </code></pre> <p>Is it the case that I simply cannot create a post with a custom post type using wp-cli?</p>
[ { "answer_id": 314375, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 3, "selected": true, "text": "<p>It should probably be </p>\n\n<p><code>wp post create --post_title='test' --post_status='draft' --post_type='class_notes'</code> </p>\n\n<p>(note the two <code>--</code> that mark it as a command option)</p>\n" }, { "answer_id": 400738, "author": "Sébastien Serre", "author_id": 62892, "author_profile": "https://wordpress.stackexchange.com/users/62892", "pm_score": 0, "selected": false, "text": "<p>You can also use <a href=\"https://developer.wordpress.org/cli/commands/post/generate/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/post/generate/</a> to generate how posts you need (for testing purpose for example)</p>\n" } ]
2018/09/17
[ "https://wordpress.stackexchange.com/questions/314370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34991/" ]
I regularly need to create a batch of posts of a custom post type, with names and meta values that follow a regular pattern. This seems like a perfect canditate for using wp-cli, but so far it hasn't worked. Using wp-cli, if I enter: ``` wp post create --post_title='test' --post_status='draft' post_type='class_notes' ``` I get an error: > > Unable to read content from 'post\_type=class\_notes'. > > > However wp-cli is definitely able to connect to this post type, as the following returns a proper list of labels and capabilities: ``` wp post-type get 'class_notes' ``` Is it the case that I simply cannot create a post with a custom post type using wp-cli?
It should probably be `wp post create --post_title='test' --post_status='draft' --post_type='class_notes'` (note the two `--` that mark it as a command option)
314,371
<p>After the update regarding the GDPR, WordPress now has an option named <em>"Privacy Policy"</em> under the settings, which you can use a page to be used as your privacy policy page. </p> <p>How can I get the ID or the permalink for this page to use in my theme or plugin?</p>
[ { "answer_id": 314372, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": false, "text": "<p>WordPress stores the page id for the privacy policy page in the <code>options</code> table. To get the value, you can use:</p>\n\n<pre><code>$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );\n\nif( $privacy_policy_page ) {\n $permalink = esc_url( get_permalink( $privacy_policy_page ) );\n}\n</code></pre>\n\n<p>The <code>$privacy_policy_page</code> variable holds the ID of the privacy policy page.</p>\n" }, { "answer_id": 314397, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<p>These functions are available since 4.9.6 for the <em>privacy policy</em> url and link:</p>\n\n<ul>\n<li><code>get_privacy_policy_url</code>() - filterable with the <code>privacy_policy_url</code> filter.</li>\n<li><code>get_the_privacy_policy_link()</code> - filterable with the <code>the_privacy_policy_link</code> filter.</li>\n<li><code>the_privacy_policy_link()</code> - wrapper that outputs <code>get_the_privacy_policy_link()</code>.</li>\n</ul>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/43850\" rel=\"noreferrer\">#43850</a></p>\n" } ]
2018/09/17
[ "https://wordpress.stackexchange.com/questions/314371", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
After the update regarding the GDPR, WordPress now has an option named *"Privacy Policy"* under the settings, which you can use a page to be used as your privacy policy page. How can I get the ID or the permalink for this page to use in my theme or plugin?
WordPress stores the page id for the privacy policy page in the `options` table. To get the value, you can use: ``` $privacy_policy_page = get_option( 'wp_page_for_privacy_policy' ); if( $privacy_policy_page ) { $permalink = esc_url( get_permalink( $privacy_policy_page ) ); } ``` The `$privacy_policy_page` variable holds the ID of the privacy policy page.
314,377
<p>I have taxonomy="local", Term: ABC (parent) - HCM - Q1 - Q2 - Q3</p> <p>I used code in single_post_type: <code>&lt;?php echo get_the_term_list(get_the_ID(), 'local', '', ', ', ''); ?&gt;</code> but it display by letter (ABC,HCM,Q1,Q2,Q3). I want display child first->parent: Q1,Q2,Q3,HCM,ABC Please help me !!! thanks <a href="https://i.stack.imgur.com/qOFIL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qOFIL.jpg" alt="Pic"></a></p>
[ { "answer_id": 314372, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": false, "text": "<p>WordPress stores the page id for the privacy policy page in the <code>options</code> table. To get the value, you can use:</p>\n\n<pre><code>$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );\n\nif( $privacy_policy_page ) {\n $permalink = esc_url( get_permalink( $privacy_policy_page ) );\n}\n</code></pre>\n\n<p>The <code>$privacy_policy_page</code> variable holds the ID of the privacy policy page.</p>\n" }, { "answer_id": 314397, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<p>These functions are available since 4.9.6 for the <em>privacy policy</em> url and link:</p>\n\n<ul>\n<li><code>get_privacy_policy_url</code>() - filterable with the <code>privacy_policy_url</code> filter.</li>\n<li><code>get_the_privacy_policy_link()</code> - filterable with the <code>the_privacy_policy_link</code> filter.</li>\n<li><code>the_privacy_policy_link()</code> - wrapper that outputs <code>get_the_privacy_policy_link()</code>.</li>\n</ul>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/43850\" rel=\"noreferrer\">#43850</a></p>\n" } ]
2018/09/17
[ "https://wordpress.stackexchange.com/questions/314377", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124366/" ]
I have taxonomy="local", Term: ABC (parent) - HCM - Q1 - Q2 - Q3 I used code in single\_post\_type: `<?php echo get_the_term_list(get_the_ID(), 'local', '', ', ', ''); ?>` but it display by letter (ABC,HCM,Q1,Q2,Q3). I want display child first->parent: Q1,Q2,Q3,HCM,ABC Please help me !!! thanks [![Pic](https://i.stack.imgur.com/qOFIL.jpg)](https://i.stack.imgur.com/qOFIL.jpg)
WordPress stores the page id for the privacy policy page in the `options` table. To get the value, you can use: ``` $privacy_policy_page = get_option( 'wp_page_for_privacy_policy' ); if( $privacy_policy_page ) { $permalink = esc_url( get_permalink( $privacy_policy_page ) ); } ``` The `$privacy_policy_page` variable holds the ID of the privacy policy page.
314,398
<p>I am working on a tournament website. When you register you have the role "Member" and you can create a CPT " team".</p> <p>I created a "TeamAdmin" role with capabilities to <code>edit_published_posts</code>, so the TeamAdmin can change the team name, for example.</p> <p>My question is how to toggle the role on the submit button, for example on the team's creation switch the role switch to "TeamAdmin"?</p>
[ { "answer_id": 314372, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": false, "text": "<p>WordPress stores the page id for the privacy policy page in the <code>options</code> table. To get the value, you can use:</p>\n\n<pre><code>$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );\n\nif( $privacy_policy_page ) {\n $permalink = esc_url( get_permalink( $privacy_policy_page ) );\n}\n</code></pre>\n\n<p>The <code>$privacy_policy_page</code> variable holds the ID of the privacy policy page.</p>\n" }, { "answer_id": 314397, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<p>These functions are available since 4.9.6 for the <em>privacy policy</em> url and link:</p>\n\n<ul>\n<li><code>get_privacy_policy_url</code>() - filterable with the <code>privacy_policy_url</code> filter.</li>\n<li><code>get_the_privacy_policy_link()</code> - filterable with the <code>the_privacy_policy_link</code> filter.</li>\n<li><code>the_privacy_policy_link()</code> - wrapper that outputs <code>get_the_privacy_policy_link()</code>.</li>\n</ul>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/43850\" rel=\"noreferrer\">#43850</a></p>\n" } ]
2018/09/17
[ "https://wordpress.stackexchange.com/questions/314398", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150756/" ]
I am working on a tournament website. When you register you have the role "Member" and you can create a CPT " team". I created a "TeamAdmin" role with capabilities to `edit_published_posts`, so the TeamAdmin can change the team name, for example. My question is how to toggle the role on the submit button, for example on the team's creation switch the role switch to "TeamAdmin"?
WordPress stores the page id for the privacy policy page in the `options` table. To get the value, you can use: ``` $privacy_policy_page = get_option( 'wp_page_for_privacy_policy' ); if( $privacy_policy_page ) { $permalink = esc_url( get_permalink( $privacy_policy_page ) ); } ``` The `$privacy_policy_page` variable holds the ID of the privacy policy page.
314,413
<p>I cannot hide this menu here (see picture) and I don't what else to do, please help. Apparently, I cannot find the correct hook to do achieve that.</p> <p>example: </p> <pre><code>add_action( 'wp_loaded', 'hide_guest_authors_link_from_backend'); function hide_guest_authors_link_from_backend() { ?&gt; &lt;script&gt; document.querySelector("li a[href='users.php?page=view-guest-authors']").style.display = 'none'; &lt;/script&gt; &lt;?php } ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/wupD5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wupD5.png" alt="enter image description here"></a></p>
[ { "answer_id": 314372, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": false, "text": "<p>WordPress stores the page id for the privacy policy page in the <code>options</code> table. To get the value, you can use:</p>\n\n<pre><code>$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );\n\nif( $privacy_policy_page ) {\n $permalink = esc_url( get_permalink( $privacy_policy_page ) );\n}\n</code></pre>\n\n<p>The <code>$privacy_policy_page</code> variable holds the ID of the privacy policy page.</p>\n" }, { "answer_id": 314397, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<p>These functions are available since 4.9.6 for the <em>privacy policy</em> url and link:</p>\n\n<ul>\n<li><code>get_privacy_policy_url</code>() - filterable with the <code>privacy_policy_url</code> filter.</li>\n<li><code>get_the_privacy_policy_link()</code> - filterable with the <code>the_privacy_policy_link</code> filter.</li>\n<li><code>the_privacy_policy_link()</code> - wrapper that outputs <code>get_the_privacy_policy_link()</code>.</li>\n</ul>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/43850\" rel=\"noreferrer\">#43850</a></p>\n" } ]
2018/09/17
[ "https://wordpress.stackexchange.com/questions/314413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150200/" ]
I cannot hide this menu here (see picture) and I don't what else to do, please help. Apparently, I cannot find the correct hook to do achieve that. example: ``` add_action( 'wp_loaded', 'hide_guest_authors_link_from_backend'); function hide_guest_authors_link_from_backend() { ?> <script> document.querySelector("li a[href='users.php?page=view-guest-authors']").style.display = 'none'; </script> <?php } ?> ``` [![enter image description here](https://i.stack.imgur.com/wupD5.png)](https://i.stack.imgur.com/wupD5.png)
WordPress stores the page id for the privacy policy page in the `options` table. To get the value, you can use: ``` $privacy_policy_page = get_option( 'wp_page_for_privacy_policy' ); if( $privacy_policy_page ) { $permalink = esc_url( get_permalink( $privacy_policy_page ) ); } ``` The `$privacy_policy_page` variable holds the ID of the privacy policy page.
314,479
<p>I am facing a challenge. I need to check if Woocommerce Order Number will equal Post ID. I know that this is true like 90% of times, but I need bulletproof way to check this. See example where this is not true and Order number and Post ID do differ:</p> <p><a href="https://i.stack.imgur.com/m8E5S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m8E5S.png" alt="woocommerce different order number and post ID"></a></p> <p>Things to consider:</p> <ul> <li>My plugin may be installed at a time where no orders are created in Woocommerce yet</li> <li>I found this occasion on wordpress multisite, but I know that there are also plugins for sequential order numbers. And there is a lot of them, so I cannot just check for existence of one or two plugins.</li> <li>I need to know this because I am developing a plugin to check payments made manually by the customers. So I know that the payment will be identified by Order Number and <strong>not</strong> by Order ID (which is always equal to Post ID)</li> </ul> <p><strong>Edit: Expected business flow of my plugin</strong></p> <p>The plugin I have developed is "offline payments" for bank account payment. So, the flow is this:</p> <ol> <li>User selects products and decides to pay for them via "Bank account" payment gateway (one of default gateways in Woocommerce)</li> <li>User will see bank account and order <strong>number</strong> to pay (In my case Order number 84)</li> <li>User will send money to given bank account, specifying the order number (In Czech this field is called "variable symbol")</li> <li>The plugin connects to the bank via API and queries all transactions on given bank account</li> <li>What I need to decide = If payment is received with order number 84, it means that Order ID 7257 (see picture above) is paid. </li> </ol> <p>In most of the sites applies that Order ID == Order Number. However here not and I need to have logic how to decide this. So far I am just thinking about adding a checkbox to the plugin...</p> <p>Thanks a lot for any ideas</p>
[ { "answer_id": 314372, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": false, "text": "<p>WordPress stores the page id for the privacy policy page in the <code>options</code> table. To get the value, you can use:</p>\n\n<pre><code>$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );\n\nif( $privacy_policy_page ) {\n $permalink = esc_url( get_permalink( $privacy_policy_page ) );\n}\n</code></pre>\n\n<p>The <code>$privacy_policy_page</code> variable holds the ID of the privacy policy page.</p>\n" }, { "answer_id": 314397, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<p>These functions are available since 4.9.6 for the <em>privacy policy</em> url and link:</p>\n\n<ul>\n<li><code>get_privacy_policy_url</code>() - filterable with the <code>privacy_policy_url</code> filter.</li>\n<li><code>get_the_privacy_policy_link()</code> - filterable with the <code>the_privacy_policy_link</code> filter.</li>\n<li><code>the_privacy_policy_link()</code> - wrapper that outputs <code>get_the_privacy_policy_link()</code>.</li>\n</ul>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/43850\" rel=\"noreferrer\">#43850</a></p>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314479", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10575/" ]
I am facing a challenge. I need to check if Woocommerce Order Number will equal Post ID. I know that this is true like 90% of times, but I need bulletproof way to check this. See example where this is not true and Order number and Post ID do differ: [![woocommerce different order number and post ID](https://i.stack.imgur.com/m8E5S.png)](https://i.stack.imgur.com/m8E5S.png) Things to consider: * My plugin may be installed at a time where no orders are created in Woocommerce yet * I found this occasion on wordpress multisite, but I know that there are also plugins for sequential order numbers. And there is a lot of them, so I cannot just check for existence of one or two plugins. * I need to know this because I am developing a plugin to check payments made manually by the customers. So I know that the payment will be identified by Order Number and **not** by Order ID (which is always equal to Post ID) **Edit: Expected business flow of my plugin** The plugin I have developed is "offline payments" for bank account payment. So, the flow is this: 1. User selects products and decides to pay for them via "Bank account" payment gateway (one of default gateways in Woocommerce) 2. User will see bank account and order **number** to pay (In my case Order number 84) 3. User will send money to given bank account, specifying the order number (In Czech this field is called "variable symbol") 4. The plugin connects to the bank via API and queries all transactions on given bank account 5. What I need to decide = If payment is received with order number 84, it means that Order ID 7257 (see picture above) is paid. In most of the sites applies that Order ID == Order Number. However here not and I need to have logic how to decide this. So far I am just thinking about adding a checkbox to the plugin... Thanks a lot for any ideas
WordPress stores the page id for the privacy policy page in the `options` table. To get the value, you can use: ``` $privacy_policy_page = get_option( 'wp_page_for_privacy_policy' ); if( $privacy_policy_page ) { $permalink = esc_url( get_permalink( $privacy_policy_page ) ); } ``` The `$privacy_policy_page` variable holds the ID of the privacy policy page.
314,485
<p><strong>Problem:</strong></p> <p>I do not want to develop (new features) of a wordpress site on production. So I set up an <strong>staging server</strong> where the same installation of wordpress is running on.</p> <p>So while I develop on the staging server on new features, there is content added on production by some other users. Furthermore we use a page builder -> some design is also modified. (We also do some front-end work and using the page builder for some functionalities)</p> <p>This means, that I cannot simply overwrite the production site with the staging site when the new features are ready - cause I would lose the content which was added (Primarily the ones in the database)</p> <p>How can I achive that? So the key requirements are:</p> <p>1) Developing on new features on staging</p> <p>2) User can add content and change design (with page builder) on live</p> <p>(I found similar questions, but none of them made me happy :/ )</p>
[ { "answer_id": 314372, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": false, "text": "<p>WordPress stores the page id for the privacy policy page in the <code>options</code> table. To get the value, you can use:</p>\n\n<pre><code>$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );\n\nif( $privacy_policy_page ) {\n $permalink = esc_url( get_permalink( $privacy_policy_page ) );\n}\n</code></pre>\n\n<p>The <code>$privacy_policy_page</code> variable holds the ID of the privacy policy page.</p>\n" }, { "answer_id": 314397, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": false, "text": "<p>These functions are available since 4.9.6 for the <em>privacy policy</em> url and link:</p>\n\n<ul>\n<li><code>get_privacy_policy_url</code>() - filterable with the <code>privacy_policy_url</code> filter.</li>\n<li><code>get_the_privacy_policy_link()</code> - filterable with the <code>the_privacy_policy_link</code> filter.</li>\n<li><code>the_privacy_policy_link()</code> - wrapper that outputs <code>get_the_privacy_policy_link()</code>.</li>\n</ul>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/43850\" rel=\"noreferrer\">#43850</a></p>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129760/" ]
**Problem:** I do not want to develop (new features) of a wordpress site on production. So I set up an **staging server** where the same installation of wordpress is running on. So while I develop on the staging server on new features, there is content added on production by some other users. Furthermore we use a page builder -> some design is also modified. (We also do some front-end work and using the page builder for some functionalities) This means, that I cannot simply overwrite the production site with the staging site when the new features are ready - cause I would lose the content which was added (Primarily the ones in the database) How can I achive that? So the key requirements are: 1) Developing on new features on staging 2) User can add content and change design (with page builder) on live (I found similar questions, but none of them made me happy :/ )
WordPress stores the page id for the privacy policy page in the `options` table. To get the value, you can use: ``` $privacy_policy_page = get_option( 'wp_page_for_privacy_policy' ); if( $privacy_policy_page ) { $permalink = esc_url( get_permalink( $privacy_policy_page ) ); } ``` The `$privacy_policy_page` variable holds the ID of the privacy policy page.
314,494
<p>I'm trying to submit a form in wordpress with ajax. But after the first submision the page itself is called again. </p> <p>My Form</p> <pre><code>&lt;form class="et_pb_contact_form clearfix" method="post" action="" id="loginform"&gt; &lt;p class="et_pb_contact_field et_pb_contact_field_0 et_pb_contact_field_last" data-id="mail" data-type="input"&gt; &lt;label for="et_pb_contact_mail_1" class="et_pb_contact_form_label"&gt;E-Mail-Adresse&lt;/label&gt; &lt;input type="email" name="mail" id="mail" value="" placeholder="E-Mail-Adresse" required=""/&gt; &lt;/p&gt; &lt;p class="et_pb_contact_field et_pb_contact_field_1 et_pb_contact_field_last" data-id="pw" data-type="input"&gt; &lt;label for="et_pb_contact_pw_1" class="et_pb_contact_form_label"&gt;Passwort&lt;/label&gt; &lt;input type="password" name="pw" id="pw" value="" placeholder="Passwort" /&gt; &lt;/p&gt; &lt;div class="et_contact_bottom_container"&gt; &lt;button type="submit" class="et_pb_contact_submit et_pb_button"&gt;Einloggen&lt;/button&gt; &lt;/div&gt; </code></pre> <p></p> <p>Javascript:</p> <pre><code>jQuery(document).ready(function() { jQuery(document).on('submit', '#loginform' ,function(e) { e.preventDefault(); jQuery.ajax({ type: "POST", url: 'backend_login.php', data: jQuery(this).serialize(), success: function(data) { if (data === 'true') { window.location = 'main.php'; } else if (data.indexOf("Fehler") !== -1) { alert(data); } else { jQuery('#loginnote').fadeIn(); } } }); }); }); </code></pre> <p>If I open the page ([domain]/login) and hit the Submit Button the first two XHR occur of which the first one is correct. But where does the second XHR come from, and how to prevent from this? After the site is new loaded and I hit the submit button again, only the correct and third XHR occur. </p> <p><a href="https://i.stack.imgur.com/PyVpA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PyVpA.png" alt="enter image description here"></a></p>
[ { "answer_id": 314495, "author": "Toheeb", "author_id": 130853, "author_profile": "https://wordpress.stackexchange.com/users/130853", "pm_score": -1, "selected": false, "text": "<p>Remove this line of code\n<code>window.location = 'main.php';</code></p>\n\n<p>Then it's better you use this</p>\n\n<pre><code>jQuery('#loginform').on('submit',function(e) {e.preventDefault();.....});\n</code></pre>\n\n<p>Than this that you have</p>\n\n<pre><code>jQuery(document).on('submit', '#loginform' ,function(e) {....})\n</code></pre>\n" }, { "answer_id": 314515, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 0, "selected": false, "text": "<p>To solve this, you need to unbind the event that triggers the second AJAX request. You need to make sure that your <code>unbind()</code> function is called <em>after</em> the event binding has occurred.</p>\n\n<p>So why not just load it in the footer? One reason is that the other script that binds the event might be loading in the footer, too.</p>\n\n<p>To control the loading order of scripts, you can actually use the <code>dependencies</code> parameter of <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_scripts()</a>. You just need to know the handler of the script that you wish do add as a dependency:</p>\n\n<pre><code>wp_enqueue_script( 'my-handler', 'script.js', array( 'another-script-handler' ) );\n</code></pre>\n\n<p><code>my-handler</code> is now depending upon and is therefore loaded <em>after</em> <code>another-script-handler</code>.</p>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314494", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150815/" ]
I'm trying to submit a form in wordpress with ajax. But after the first submision the page itself is called again. My Form ``` <form class="et_pb_contact_form clearfix" method="post" action="" id="loginform"> <p class="et_pb_contact_field et_pb_contact_field_0 et_pb_contact_field_last" data-id="mail" data-type="input"> <label for="et_pb_contact_mail_1" class="et_pb_contact_form_label">E-Mail-Adresse</label> <input type="email" name="mail" id="mail" value="" placeholder="E-Mail-Adresse" required=""/> </p> <p class="et_pb_contact_field et_pb_contact_field_1 et_pb_contact_field_last" data-id="pw" data-type="input"> <label for="et_pb_contact_pw_1" class="et_pb_contact_form_label">Passwort</label> <input type="password" name="pw" id="pw" value="" placeholder="Passwort" /> </p> <div class="et_contact_bottom_container"> <button type="submit" class="et_pb_contact_submit et_pb_button">Einloggen</button> </div> ``` Javascript: ``` jQuery(document).ready(function() { jQuery(document).on('submit', '#loginform' ,function(e) { e.preventDefault(); jQuery.ajax({ type: "POST", url: 'backend_login.php', data: jQuery(this).serialize(), success: function(data) { if (data === 'true') { window.location = 'main.php'; } else if (data.indexOf("Fehler") !== -1) { alert(data); } else { jQuery('#loginnote').fadeIn(); } } }); }); }); ``` If I open the page ([domain]/login) and hit the Submit Button the first two XHR occur of which the first one is correct. But where does the second XHR come from, and how to prevent from this? After the site is new loaded and I hit the submit button again, only the correct and third XHR occur. [![enter image description here](https://i.stack.imgur.com/PyVpA.png)](https://i.stack.imgur.com/PyVpA.png)
To solve this, you need to unbind the event that triggers the second AJAX request. You need to make sure that your `unbind()` function is called *after* the event binding has occurred. So why not just load it in the footer? One reason is that the other script that binds the event might be loading in the footer, too. To control the loading order of scripts, you can actually use the `dependencies` parameter of [wp\_enqueue\_scripts()](https://developer.wordpress.org/reference/functions/wp_enqueue_script/). You just need to know the handler of the script that you wish do add as a dependency: ``` wp_enqueue_script( 'my-handler', 'script.js', array( 'another-script-handler' ) ); ``` `my-handler` is now depending upon and is therefore loaded *after* `another-script-handler`.
314,503
<p>I am trying to override a plugin's built in avatar with the default WP avatar. The plugin's filter is this:</p> <pre><code>add_filter( "idea_push_change_user_image", "idea_push_change_user_image_callback", 10, 1 ); function idea_push_change_user_image_callback( $userId ) { return "https://cdn.britannica.com/55/174255-004-9A4971E9.jpg"; } </code></pre> <p>I tried replacing that with 'get_avatar' but it ends up with a broken jpg image</p> <pre><code>add_filter( "idea_push_change_user_image", "idea_push_change_user_image_callback", 10, 1 ); function idea_push_change_user_image_callback( $userId ) { return get_avatar( get_the_author_meta( 'ID' ), 32 ); } </code></pre> <p>Any ideas how to fix, thanks</p> <p>UPDATE:</p> <p>Thanks for answers, this has helped. Turns out I needed to pull another plugins (Ultimate Member) avatar not the default:</p> <pre><code>add_filter( "idea_push_change_user_image", "idea_push_change_user_image_callback", 10, 1 ); function idea_push_change_user_image_callback( $userId ) { return um_get_user_avatar_url(); } </code></pre> <p>What's weird is it's only working/visible to the logged in user, not visible to anyone else. </p>
[ { "answer_id": 314505, "author": "Krishna Joshi", "author_id": 150621, "author_profile": "https://wordpress.stackexchange.com/users/150621", "pm_score": 2, "selected": true, "text": "<p>Replace the below line your code</p>\n\n<pre><code>return get_avatar( get_the_author_meta( 'ID' ), 32 ); \n</code></pre>\n\n<p>to</p>\n\n<pre><code>return get_avatar_url( get_the_author_meta( 'ID' ) ); \n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 314579, "author": "JJ100", "author_id": 150825, "author_profile": "https://wordpress.stackexchange.com/users/150825", "pm_score": 0, "selected": false, "text": "<p>This code fixed it. Had to get the UM avatar:</p>\n\n<pre><code>add_filter( \"idea_push_change_user_image\", \n \"idea_push_change_user_image_callback\", 10, 1 ); \nfunction \n idea_push_change_user_image_callback( $userId ) \n{ return um_get_user_avatar_url($userId ); }\n</code></pre>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150825/" ]
I am trying to override a plugin's built in avatar with the default WP avatar. The plugin's filter is this: ``` add_filter( "idea_push_change_user_image", "idea_push_change_user_image_callback", 10, 1 ); function idea_push_change_user_image_callback( $userId ) { return "https://cdn.britannica.com/55/174255-004-9A4971E9.jpg"; } ``` I tried replacing that with 'get\_avatar' but it ends up with a broken jpg image ``` add_filter( "idea_push_change_user_image", "idea_push_change_user_image_callback", 10, 1 ); function idea_push_change_user_image_callback( $userId ) { return get_avatar( get_the_author_meta( 'ID' ), 32 ); } ``` Any ideas how to fix, thanks UPDATE: Thanks for answers, this has helped. Turns out I needed to pull another plugins (Ultimate Member) avatar not the default: ``` add_filter( "idea_push_change_user_image", "idea_push_change_user_image_callback", 10, 1 ); function idea_push_change_user_image_callback( $userId ) { return um_get_user_avatar_url(); } ``` What's weird is it's only working/visible to the logged in user, not visible to anyone else.
Replace the below line your code ``` return get_avatar( get_the_author_meta( 'ID' ), 32 ); ``` to ``` return get_avatar_url( get_the_author_meta( 'ID' ) ); ``` Hope this helps.
314,509
<pre><code>//Register new product taxonomy - Authors function register_author_taxonomy() { $labels = array( 'name' =&gt; __( 'Author', 'taxonomy general name' ), 'singular_name' =&gt; __( 'Author', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Authors' ), 'all_items' =&gt; __( 'All Authors' ), 'parent_item' =&gt; __( 'Parent Author' ), 'parent_item_colon' =&gt; __( 'Parent Author:' ), 'edit_item' =&gt; __( 'Edit Author' ), 'update_item' =&gt; __( 'Update Author' ), 'add_new_item' =&gt; __( 'Add New Author' ), 'new_item_name' =&gt; __( 'New Author Name' ), 'menu_name' =&gt; __( 'Authors' ), ); $args = array( 'public' =&gt; true, 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'authors', 'with_front' =&gt; true, ), 'show_admin_column' =&gt; true ); register_taxonomy("product_author", array("product"), $args ); } add_action( 'init', 'register_author_taxonomy' ); // Register new product taxonomy - Publisher function register_publisher_taxonomy() { $labels = array( 'name' =&gt; __( 'Publisher', 'taxonomy general name' ), 'singular_name' =&gt; __( 'Publisher', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Publishers' ), 'all_items' =&gt; __( 'All Publishers' ), 'parent_item' =&gt; __( 'Parent Publisher' ), 'parent_item_colon' =&gt; __( 'Parent Publisher:' ), 'edit_item' =&gt; __( 'Edit Publisher' ), 'update_item' =&gt; __( 'Update Publisher' ), 'add_new_item' =&gt; __( 'Add New Publisher' ), 'new_item_name' =&gt; __( 'New Publisher Name' ), 'menu_name' =&gt; __( 'Publishers' ), ); $args = array( 'public' =&gt; true, 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'publishers', 'with_front' =&gt; true, ), 'show_admin_column' =&gt; true ); register_taxonomy("product_publisher", array("product"), $args ); } add_action( 'init', 'register_publisher_taxonomy' ); // Add Custom Taxonomies to Product Pages add_action('woocommerce_single_product_summary', 'custom_taxonomy_description', 10 ); function custom_taxonomy_description() { if (is_product) { $authors = get_the_terms( $post-&gt;ID , 'product_author' ); foreach ( $authors as $author ) { $author_link = get_term_link( $author, 'product_author' ); $publishers = get_the_terms( $post-&gt;ID , 'product_publisher' ); foreach ( $publishers as $publisher ) { $publisher_link = get_term_link( $publisher, 'product_publisher' ); if( is_wp_error( $author_link, $publisher_link ) ) continue; echo '&lt;br&gt;'. '&lt;div class="before-content"&gt;'. 'Author: '.'&lt;a href="' . $author_link . '"&gt;' . $author-&gt;name . '&lt;/a&gt;'. '&lt;br&gt;'. 'Publisher: '.'&lt;a href="' . $publisher_link . '"&gt;' . $publisher-&gt;name . '&lt;/a&gt;'.'&lt;/div&gt;'. '&lt;br&gt;'; } </code></pre> <p>I'm trying to add some custom taxonomies to my woocommerce products, essentially a book shop so I want author, publisher etc. I'd like these displayed on the product page all of which the above code is doing, however when either custom taxonomy is empty I get an error messaged displayed. </p> <p>Just wondering if anyone had some sort of if ( ! empty () ) solution that would display nothing when the taxonomy is empty.</p> <p>The code I'm using is pretty hobbled together from lots of other different posts so any ideas to streamline that would be appreciated too!</p> <p>Also, not sure if this is relevant or not but I'm using the Genesis Framework on Wordpress.</p> <p>Thanks in advance!</p>
[ { "answer_id": 314519, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 1, "selected": false, "text": "<p><code>get_the_terms()</code> returns <code>FALSE</code> if there are no terms in the taxonomy, so you could check for that. </p>\n\n<pre><code>$authors = get_the_terms( $post-&gt;ID , 'product_author' );\nif ( FALSE != $authors ) :\n // Do something\nendif;\n</code></pre>\n\n<p>If you want to avoid displaying empty terms, ie. terms that have no objects attached to them, use <code>get_terms()</code> instead, because you can pass a parameter to filter them:</p>\n\n<pre><code>$terms = get_terms( \n array(\n 'object_ids' =&gt; $post-&gt;ID,\n 'taxonomy' =&gt; 'product_author',\n 'hide_empty' =&gt; TRUE,\n) );\n</code></pre>\n" }, { "answer_id": 314528, "author": "shanedaly001", "author_id": 150832, "author_profile": "https://wordpress.stackexchange.com/users/150832", "pm_score": 0, "selected": false, "text": "<p>The error message I was getting was an invalid foreach statement when the array was empty.</p>\n\n<p>So the quick solve for me was to just put in a check that the array wasn't empty before executing anything. </p>\n\n<pre><code>if (!empty ($authors)) {\n</code></pre>\n\n<p>Thanks for the input, really appreciate it!</p>\n\n<p>If I manage to tidy it up at all I'll post the full code later.</p>\n\n<p>Thanks again!</p>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314509", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150832/" ]
``` //Register new product taxonomy - Authors function register_author_taxonomy() { $labels = array( 'name' => __( 'Author', 'taxonomy general name' ), 'singular_name' => __( 'Author', 'taxonomy singular name' ), 'search_items' => __( 'Search Authors' ), 'all_items' => __( 'All Authors' ), 'parent_item' => __( 'Parent Author' ), 'parent_item_colon' => __( 'Parent Author:' ), 'edit_item' => __( 'Edit Author' ), 'update_item' => __( 'Update Author' ), 'add_new_item' => __( 'Add New Author' ), 'new_item_name' => __( 'New Author Name' ), 'menu_name' => __( 'Authors' ), ); $args = array( 'public' => true, 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'authors', 'with_front' => true, ), 'show_admin_column' => true ); register_taxonomy("product_author", array("product"), $args ); } add_action( 'init', 'register_author_taxonomy' ); // Register new product taxonomy - Publisher function register_publisher_taxonomy() { $labels = array( 'name' => __( 'Publisher', 'taxonomy general name' ), 'singular_name' => __( 'Publisher', 'taxonomy singular name' ), 'search_items' => __( 'Search Publishers' ), 'all_items' => __( 'All Publishers' ), 'parent_item' => __( 'Parent Publisher' ), 'parent_item_colon' => __( 'Parent Publisher:' ), 'edit_item' => __( 'Edit Publisher' ), 'update_item' => __( 'Update Publisher' ), 'add_new_item' => __( 'Add New Publisher' ), 'new_item_name' => __( 'New Publisher Name' ), 'menu_name' => __( 'Publishers' ), ); $args = array( 'public' => true, 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'publishers', 'with_front' => true, ), 'show_admin_column' => true ); register_taxonomy("product_publisher", array("product"), $args ); } add_action( 'init', 'register_publisher_taxonomy' ); // Add Custom Taxonomies to Product Pages add_action('woocommerce_single_product_summary', 'custom_taxonomy_description', 10 ); function custom_taxonomy_description() { if (is_product) { $authors = get_the_terms( $post->ID , 'product_author' ); foreach ( $authors as $author ) { $author_link = get_term_link( $author, 'product_author' ); $publishers = get_the_terms( $post->ID , 'product_publisher' ); foreach ( $publishers as $publisher ) { $publisher_link = get_term_link( $publisher, 'product_publisher' ); if( is_wp_error( $author_link, $publisher_link ) ) continue; echo '<br>'. '<div class="before-content">'. 'Author: '.'<a href="' . $author_link . '">' . $author->name . '</a>'. '<br>'. 'Publisher: '.'<a href="' . $publisher_link . '">' . $publisher->name . '</a>'.'</div>'. '<br>'; } ``` I'm trying to add some custom taxonomies to my woocommerce products, essentially a book shop so I want author, publisher etc. I'd like these displayed on the product page all of which the above code is doing, however when either custom taxonomy is empty I get an error messaged displayed. Just wondering if anyone had some sort of if ( ! empty () ) solution that would display nothing when the taxonomy is empty. The code I'm using is pretty hobbled together from lots of other different posts so any ideas to streamline that would be appreciated too! Also, not sure if this is relevant or not but I'm using the Genesis Framework on Wordpress. Thanks in advance!
`get_the_terms()` returns `FALSE` if there are no terms in the taxonomy, so you could check for that. ``` $authors = get_the_terms( $post->ID , 'product_author' ); if ( FALSE != $authors ) : // Do something endif; ``` If you want to avoid displaying empty terms, ie. terms that have no objects attached to them, use `get_terms()` instead, because you can pass a parameter to filter them: ``` $terms = get_terms( array( 'object_ids' => $post->ID, 'taxonomy' => 'product_author', 'hide_empty' => TRUE, ) ); ```
314,539
<p>I am trying to modify css.</p> <p><a href="https://i.stack.imgur.com/9mrmi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9mrmi.jpg" alt="enter image description here"></a></p> <p>I tried to modify the css with below code but does seems to work. if i try to change the color it works.</p> <pre><code> #poststuff #post-body.columns-2 { margin-right: 300px; display:flex important; flex-direction:column !important; } </code></pre> <p>It seems to work in if i modify directly form the chrome developer.</p> <pre><code>function wpdocs_selectively_enqueue_admin_script( $hook ) { if ( 'toplevel_page_kita-general-settings' != $hook ) { return; } // wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'myscript.js', array(), '1.0' ); wp_enqueue_style( 'kita_options_page', get_template_directory_uri() . '/css/kita-admin.css' ); } add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' ); </code></pre>
[ { "answer_id": 314541, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 3, "selected": true, "text": "<p>If its just that one style you want to edit, you could try...</p>\n\n<pre><code>add_action('admin_head', 'admin_styles');\n\nfunction admin_styles() {\n echo '&lt;style&gt;\n #poststuff #post-body.columns-2 {\n margin-right: 300px;\n dispay:flex important;\n flex-direction:column !important;\n }\n &lt;/style&gt;';\n}\n</code></pre>\n\n<p>Or add a separate stylesheet with something like this...</p>\n\n<pre><code>add_action('admin_head', 'admin_styles');\n\nfunction admin_styles() {\n echo '&lt;link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" media=\"all\" /&gt;';\n}\n</code></pre>\n" }, { "answer_id": 412457, "author": "borma425", "author_id": 228670, "author_profile": "https://wordpress.stackexchange.com/users/228670", "pm_score": 0, "selected": false, "text": "<p>My Best Way using <code>wp_enqueue_style</code> you can use random <code>$version</code> to avoid cache browser.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function admin_styles() { \n $ver = rand();\n wp_enqueue_style(\n 'adminStyle', \n get_template_directory_uri() . '/assets/css/admin.css',\n [],\n $ver\n );\n}\n\n</code></pre>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am trying to modify css. [![enter image description here](https://i.stack.imgur.com/9mrmi.jpg)](https://i.stack.imgur.com/9mrmi.jpg) I tried to modify the css with below code but does seems to work. if i try to change the color it works. ``` #poststuff #post-body.columns-2 { margin-right: 300px; display:flex important; flex-direction:column !important; } ``` It seems to work in if i modify directly form the chrome developer. ``` function wpdocs_selectively_enqueue_admin_script( $hook ) { if ( 'toplevel_page_kita-general-settings' != $hook ) { return; } // wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'myscript.js', array(), '1.0' ); wp_enqueue_style( 'kita_options_page', get_template_directory_uri() . '/css/kita-admin.css' ); } add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' ); ```
If its just that one style you want to edit, you could try... ``` add_action('admin_head', 'admin_styles'); function admin_styles() { echo '<style> #poststuff #post-body.columns-2 { margin-right: 300px; dispay:flex important; flex-direction:column !important; } </style>'; } ``` Or add a separate stylesheet with something like this... ``` add_action('admin_head', 'admin_styles'); function admin_styles() { echo '<link rel="stylesheet" href="style.css" type="text/css" media="all" />'; } ```
314,549
<p>I have a wordpress site with the 10 latest posts shown on the homepage.</p> <p>I need to modify some text (because of duplicate content) on homepage but not on post page.</p> <p>I try to modify the following line in index.php like this :</p> <pre><code>php the_content(Read more ...'); php the_content(Read more ...') . $content = str_replace('XXX', 'YYY'); </code></pre> <p>But it's not working and i can't find a solution.</p> <p>Can anybody help? Thank you.</p>
[ { "answer_id": 314557, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p><code>the_content(Read more ...')</code> echoes the stuff straight out so you can't modify it with <code>str_replace</code> after the fact.</p>\n\n<p>If you wanna use <code>str_replace</code> you need to do something along the lines of</p>\n\n<pre><code> $content = get_the_content( 'Read more ...' );\n $content = apply_filters( 'the_content', $content );\n $content = str_replace( ']]&gt;', ']]&amp;gt;', $content );\n $content = str_replace( 'xxx', 'yyy', $content );\n echo $content;\n</code></pre>\n\n<p>and replace xxx and yyy with the real stuff ofc.</p>\n" }, { "answer_id": 314581, "author": "Sylvie Hochepied", "author_id": 150855, "author_profile": "https://wordpress.stackexchange.com/users/150855", "pm_score": -1, "selected": false, "text": "<p>I found the solution here is the working code : </p>\n\n<pre><code> $content = get_the_content( 'Read more ...' );\n $content = str_replace( 'XXX', 'YYY', $content );\n echo apply_filters( 'the_content', $content );\n</code></pre>\n\n<p>Thank you.</p>\n" } ]
2018/09/18
[ "https://wordpress.stackexchange.com/questions/314549", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150855/" ]
I have a wordpress site with the 10 latest posts shown on the homepage. I need to modify some text (because of duplicate content) on homepage but not on post page. I try to modify the following line in index.php like this : ``` php the_content(Read more ...'); php the_content(Read more ...') . $content = str_replace('XXX', 'YYY'); ``` But it's not working and i can't find a solution. Can anybody help? Thank you.
`the_content(Read more ...')` echoes the stuff straight out so you can't modify it with `str_replace` after the fact. If you wanna use `str_replace` you need to do something along the lines of ``` $content = get_the_content( 'Read more ...' ); $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); $content = str_replace( 'xxx', 'yyy', $content ); echo $content; ``` and replace xxx and yyy with the real stuff ofc.
314,572
<p>I have created a local WordPress 4.9.8 setup with PHP 7 inside a Fedora running machine. When I try to upload media into the WordPress admin, it keeps saying that </p> <blockquote> <p>The uploaded file could not be moved to wp-content/uploads/</p> </blockquote> <p>I have given full(777) file permission for content/uploads directory but still, I get the same error.</p> <p>Finally, I tried to create the directory structure manually and place the media file by myself as follows </p> <blockquote> <p>/var/www/html/test-jp/wp-content/uploads/2018/09/1024-xxxxx-logo.png</p> </blockquote> <p>What may be the reason?</p>
[ { "answer_id": 314557, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p><code>the_content(Read more ...')</code> echoes the stuff straight out so you can't modify it with <code>str_replace</code> after the fact.</p>\n\n<p>If you wanna use <code>str_replace</code> you need to do something along the lines of</p>\n\n<pre><code> $content = get_the_content( 'Read more ...' );\n $content = apply_filters( 'the_content', $content );\n $content = str_replace( ']]&gt;', ']]&amp;gt;', $content );\n $content = str_replace( 'xxx', 'yyy', $content );\n echo $content;\n</code></pre>\n\n<p>and replace xxx and yyy with the real stuff ofc.</p>\n" }, { "answer_id": 314581, "author": "Sylvie Hochepied", "author_id": 150855, "author_profile": "https://wordpress.stackexchange.com/users/150855", "pm_score": -1, "selected": false, "text": "<p>I found the solution here is the working code : </p>\n\n<pre><code> $content = get_the_content( 'Read more ...' );\n $content = str_replace( 'XXX', 'YYY', $content );\n echo apply_filters( 'the_content', $content );\n</code></pre>\n\n<p>Thank you.</p>\n" } ]
2018/09/19
[ "https://wordpress.stackexchange.com/questions/314572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150871/" ]
I have created a local WordPress 4.9.8 setup with PHP 7 inside a Fedora running machine. When I try to upload media into the WordPress admin, it keeps saying that > > The uploaded file could not be moved to wp-content/uploads/ > > > I have given full(777) file permission for content/uploads directory but still, I get the same error. Finally, I tried to create the directory structure manually and place the media file by myself as follows > > /var/www/html/test-jp/wp-content/uploads/2018/09/1024-xxxxx-logo.png > > > What may be the reason?
`the_content(Read more ...')` echoes the stuff straight out so you can't modify it with `str_replace` after the fact. If you wanna use `str_replace` you need to do something along the lines of ``` $content = get_the_content( 'Read more ...' ); $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); $content = str_replace( 'xxx', 'yyy', $content ); echo $content; ``` and replace xxx and yyy with the real stuff ofc.
314,580
<p>I have created taxonomy, but I want to use different post template for the taxonomy, how can I do it?</p> <pre><code>function create_topics_hierarchical_taxonomy() { // Add new taxonomy, make it hierarchical like categories //first do the translations part for GUI $labels = array( 'name' =&gt; _x( 'cars', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'cars', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Topics' ), 'all_items' =&gt; __( 'All Topics' ), 'parent_item' =&gt; __( 'Parent Topic' ), 'parent_item_colon' =&gt; __( 'Parent Topic:' ), 'edit_item' =&gt; __( 'Edit Topic' ), 'update_item' =&gt; __( 'Update Topic' ), 'add_new_item' =&gt; __( 'Add New Topic' ), 'new_item_name' =&gt; __( 'New Topic Name' ), 'menu_name' =&gt; __( 'cars' ), ); // Now register the taxonomy register_taxonomy('cars',array('post'), array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'cars' ), )); </code></pre>
[ { "answer_id": 314583, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 1, "selected": false, "text": "<p>You can create taxonomy template like <code>taxonomy-[Your-texonomy].php</code> in your theme folder.</p>\n" }, { "answer_id": 314585, "author": "sakshi ranga", "author_id": 150580, "author_profile": "https://wordpress.stackexchange.com/users/150580", "pm_score": 0, "selected": false, "text": "<p>You can create via archive-cars.php - That will display all cars info \nand if you want single template then you have to use your post type in file . </p>\n\n<p>single-{post_type}.php </p>\n\n<p>for more information you can review WP template Hierarchy\n<a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n" } ]
2018/09/19
[ "https://wordpress.stackexchange.com/questions/314580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150876/" ]
I have created taxonomy, but I want to use different post template for the taxonomy, how can I do it? ``` function create_topics_hierarchical_taxonomy() { // Add new taxonomy, make it hierarchical like categories //first do the translations part for GUI $labels = array( 'name' => _x( 'cars', 'taxonomy general name' ), 'singular_name' => _x( 'cars', 'taxonomy singular name' ), 'search_items' => __( 'Search Topics' ), 'all_items' => __( 'All Topics' ), 'parent_item' => __( 'Parent Topic' ), 'parent_item_colon' => __( 'Parent Topic:' ), 'edit_item' => __( 'Edit Topic' ), 'update_item' => __( 'Update Topic' ), 'add_new_item' => __( 'Add New Topic' ), 'new_item_name' => __( 'New Topic Name' ), 'menu_name' => __( 'cars' ), ); // Now register the taxonomy register_taxonomy('cars',array('post'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'cars' ), )); ```
You can create taxonomy template like `taxonomy-[Your-texonomy].php` in your theme folder.
314,593
<p>I would like to change the &quot;Customer new account&quot; email.</p> <p>In this line:</p> <pre class="lang-php prettyprint-override"><code>&lt;p&gt;&lt;?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '&lt;strong&gt;' . esc_html( $user_login ) . '&lt;/strong&gt;' ); ?&gt;&lt;/p&gt; </code></pre> <p>I would like to change the parameter %2$s, instead of showing the username I would like to show the email address.</p> <p>What parameter should I use to show the email address?</p> <p>This is the complete customer-new-account.php :</p> <pre class="lang-php prettyprint-override"><code>&lt;?php /** * Customer new account email * * This template can be overridden by copying it to yourtheme/woocommerce/emails/customer-new-account.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you * (the theme developer) will need to copy the new files to your theme to * maintain compatibility. We try to do this as little as possible, but it does * happen. When this occurs the version of the template file will be bumped and * the readme will list any important changes. * * @see https://docs.woocommerce.com/document/template-structure/ * @author WooThemes * @package WooCommerce/Templates/Emails * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } ?&gt; &lt;?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?&gt; &lt;p&gt;&lt;?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '&lt;strong&gt;' . esc_html( $user_login ) . '&lt;/strong&gt;' ); ?&gt;&lt;/p&gt; &lt;?php if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) &amp;&amp; $password_generated ) : ?&gt; &lt;p&gt;&lt;?php printf( __( 'Your password has been automatically generated: %s', 'woocommerce' ), '&lt;strong&gt;' . esc_html( $user_pass ) . '&lt;/strong&gt;' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;p&gt;&lt;?php printf( __( 'You can access your account area to view your orders and change your password here: %s.', 'woocommerce' ), make_clickable( esc_url( wc_get_page_permalink( 'myaccount' ) ) ) ); ?&gt;&lt;/p&gt; &lt;?php do_action( 'woocommerce_email_footer', $email ); </code></pre> <p>Thanks for the support!</p>
[ { "answer_id": 314594, "author": "Fabian Marz", "author_id": 77421, "author_profile": "https://wordpress.stackexchange.com/users/77421", "pm_score": 1, "selected": false, "text": "<p>The simplest one is to copy the mail template to your theme folder into <code>path/to/your/theme/woocommerce/emails/customer-new-account.php</code> and adjust the argument from <code>user_login</code> to <code>user_email</code>.</p>\n" }, { "answer_id": 355100, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": 0, "selected": false, "text": "<p>You can use session variable.</p>\n\n<p>For example,</p>\n\n<ul>\n<li>start session in functions.php</li>\n<li>After submitting my account form store user email in that session variable.</li>\n<li>Display session variable in the alert box &amp; unset within same page.</li>\n</ul>\n" }, { "answer_id": 397073, "author": "brynzovskii", "author_id": 137906, "author_profile": "https://wordpress.stackexchange.com/users/137906", "pm_score": 0, "selected": false, "text": "<p><strong>$user_email</strong> variable is accessible inside Customer new account email template.\n<a href=\"https://woocommerce.github.io/code-reference/files/woocommerce-includes-emails-class-wc-email-customer-new-account.html#source-view.38\" rel=\"nofollow noreferrer\">Class WC_Email_Customer_New_Account file</a></p>\n" } ]
2018/09/19
[ "https://wordpress.stackexchange.com/questions/314593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150887/" ]
I would like to change the "Customer new account" email. In this line: ```php <p><?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '<strong>' . esc_html( $user_login ) . '</strong>' ); ?></p> ``` I would like to change the parameter %2$s, instead of showing the username I would like to show the email address. What parameter should I use to show the email address? This is the complete customer-new-account.php : ```php <?php /** * Customer new account email * * This template can be overridden by copying it to yourtheme/woocommerce/emails/customer-new-account.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you * (the theme developer) will need to copy the new files to your theme to * maintain compatibility. We try to do this as little as possible, but it does * happen. When this occurs the version of the template file will be bumped and * the readme will list any important changes. * * @see https://docs.woocommerce.com/document/template-structure/ * @author WooThemes * @package WooCommerce/Templates/Emails * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } ?> <?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?> <p><?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '<strong>' . esc_html( $user_login ) . '</strong>' ); ?></p> <?php if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) && $password_generated ) : ?> <p><?php printf( __( 'Your password has been automatically generated: %s', 'woocommerce' ), '<strong>' . esc_html( $user_pass ) . '</strong>' ); ?></p> <?php endif; ?> <p><?php printf( __( 'You can access your account area to view your orders and change your password here: %s.', 'woocommerce' ), make_clickable( esc_url( wc_get_page_permalink( 'myaccount' ) ) ) ); ?></p> <?php do_action( 'woocommerce_email_footer', $email ); ``` Thanks for the support!
The simplest one is to copy the mail template to your theme folder into `path/to/your/theme/woocommerce/emails/customer-new-account.php` and adjust the argument from `user_login` to `user_email`.
314,595
<p>My client shows his 5 most recent posts (excerpts) on the homepage followed by a "read more" link. On archive page he does not want to display the 5 most recent post again but posts from #6 to #20.</p> <p>How can I do this?</p>
[ { "answer_id": 314596, "author": "Adarsh", "author_id": 143452, "author_profile": "https://wordpress.stackexchange.com/users/143452", "pm_score": 2, "selected": false, "text": "<p>Add offset in the query and give value as 5 so, the first 5 will be skipped.</p>\n\n<p>Below is code snippet for the same</p>\n\n<pre><code>$custom_args = array('post_type' =&gt; 'your custom post type name',\n'posts_per_page' =&gt; '20',\n'orderby' =&gt; 'id',\n'offset'=&gt;5,\n'order' =&gt; 'ASC',);\n$custom_query = get_posts($custom_args);\n foreach ($custom_query as $value) {\n //your data\n }\n</code></pre>\n" }, { "answer_id": 314598, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 1, "selected": false, "text": "<p>You can filter the original archive query:</p>\n\n<pre><code>function my_archive_query( $query ) {\n if ( $query-&gt;is_archive() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'offset', 5 );\n $query-&gt;set( 'posts_per_page', 20 );\n }\n}\n\nadd_action( 'pre_get_posts', 'my_archive_query' );\n</code></pre>\n\n<p>More info: </p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">pre_get_posts filter</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/is_archive\" rel=\"nofollow noreferrer\">is_archive conditional tag</a></p>\n" } ]
2018/09/19
[ "https://wordpress.stackexchange.com/questions/314595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150890/" ]
My client shows his 5 most recent posts (excerpts) on the homepage followed by a "read more" link. On archive page he does not want to display the 5 most recent post again but posts from #6 to #20. How can I do this?
Add offset in the query and give value as 5 so, the first 5 will be skipped. Below is code snippet for the same ``` $custom_args = array('post_type' => 'your custom post type name', 'posts_per_page' => '20', 'orderby' => 'id', 'offset'=>5, 'order' => 'ASC',); $custom_query = get_posts($custom_args); foreach ($custom_query as $value) { //your data } ```
314,632
<p>I'm trying to add pagination to my archive template. If I use the same code as on my main blog template it doesn't filter results based on the tag in the URL, instead it simply shows all posts. Probably obvious to most but clearly I'm missing something.</p> <p>I've managed to get the archive page showing just the relevant posts using the following code (but this contains no pagination):</p> <pre><code>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="col span_1_of_1 border_bottom"&gt; &lt;h3 class="subtitle no_margin_bottom"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;p class="blog_meta_information date"&gt; Author: &lt;a href="&lt;?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?&gt;"&gt;&lt;?php the_author(); ?&gt;&lt;/a&gt; &amp;nbsp;&amp;nbsp;|&amp;nbsp;&amp;nbsp; Date: &lt;?php the_time('jS F Y') ?&gt; &lt;?php if(has_tag()) { ?&gt; &lt;br&gt; Tags: &lt;?php the_tags( '',', ','' ); ?&gt; &lt;?php } else {} ?&gt; &lt;/p&gt; &lt;p&gt;&lt;?php the_field('introduction'); ?&gt;&lt;/p&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Read more&lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; </code></pre> <p>I've also got my main blog working with pagination using the following code:</p> <pre><code>&lt;?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $custom_args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 10, 'paged' =&gt; $paged ); $custom_query = new WP_Query( $custom_args ); ?&gt; &lt;?php if( $custom_query-&gt;have_posts() ) : while( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post(); ?&gt; &lt;div class="col span_1_of_1 border_bottom"&gt; &lt;h3 class="subtitle no_margin_bottom"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;p class="blog_meta_information date"&gt; Author: &lt;a href="&lt;?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?&gt;"&gt;&lt;?php the_author(); ?&gt;&lt;/a&gt; &amp;nbsp;&amp;nbsp;|&amp;nbsp;&amp;nbsp; Date: &lt;?php the_time('jS F Y') ?&gt; &lt;?php if(has_tag()) { ?&gt; &lt;br&gt; Tags: &lt;?php the_tags( '',', ','' ); ?&gt; &lt;?php } else {} ?&gt; &lt;/p&gt; &lt;p&gt;&lt;?php the_field('introduction'); ?&gt;&lt;/p&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Read more&lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; &lt;!-- PAGINATION --&gt; &lt;?php if (function_exists(custom_pagination)) { custom_pagination($custom_query-&gt;max_num_pages,"",$paged); } ?&gt; </code></pre> <p>The above also uses the following code from my functions.php file:</p> <pre><code>// PAGINATION function custom_pagination($numpages = '', $pagerange = '', $paged='') { if (empty($pagerange)) { $pagerange = 2; } /** * This first part of our function is a fallback * for custom pagination inside a regular loop that * uses the global $paged and global $wp_query variables. * * It's good because we can now override default pagination * in our theme, and use this function in default queries * and custom queries. */ global $paged; if (empty($paged)) { $paged = 1; } if ($numpages == '') { global $wp_query; $numpages = $wp_query-&gt;max_num_pages; if(!$numpages) { $numpages = 1; } } /** * We construct the pagination arguments to enter into our paginate_links * function. */ $pagination_args = array( 'base' =&gt; get_pagenum_link(1) . '%_%', 'format' =&gt; 'page/%#%', 'total' =&gt; $numpages, 'current' =&gt; $paged, 'show_all' =&gt; False, 'end_size' =&gt; 1, 'mid_size' =&gt; $pagerange, 'prev_next' =&gt; True, 'prev_text' =&gt; __('&amp;laquo;'), 'next_text' =&gt; __('&amp;raquo;'), 'type' =&gt; 'plain', 'add_args' =&gt; false, 'add_fragment' =&gt; '' ); $paginate_links = paginate_links($pagination_args); if ($paginate_links) { echo "&lt;div class='custom-pagination'&gt;"; echo "&lt;span class='page-numbers page-num'&gt;Page " . $paged . " of " . $numpages . "&lt;/span&gt; "; echo $paginate_links; echo "&lt;/div&gt;"; } } </code></pre> <p>Anyone know how I can add make this pagination also work with my archive template?</p> <p>Thanks in advance,</p> <p>Tom</p>
[ { "answer_id": 314637, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 2, "selected": false, "text": "<p>Since 4.1.0, WordPress introduce <code>the_posts_pagination</code> to handle number paginate link. I use it all the time, and it just works. With any custom post type. You'll want to use that function after the <code>while</code> loop.</p>\n\n<p>See: <a href=\"https://developer.wordpress.org/reference/functions/the_posts_pagination/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_posts_pagination/</a></p>\n" }, { "answer_id": 314706, "author": "Tom Perkins", "author_id": 108074, "author_profile": "https://wordpress.stackexchange.com/users/108074", "pm_score": 0, "selected": false, "text": "<p>Just a quick update on this one: I chose to use the WP-PageNavi plugin (<a href=\"https://en-gb.wordpress.org/plugins/wp-pagenavi/\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/wp-pagenavi/</a>) on the archives page and leave the main blog using the custom pagination which does the job perfectly.</p>\n" } ]
2018/09/19
[ "https://wordpress.stackexchange.com/questions/314632", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108074/" ]
I'm trying to add pagination to my archive template. If I use the same code as on my main blog template it doesn't filter results based on the tag in the URL, instead it simply shows all posts. Probably obvious to most but clearly I'm missing something. I've managed to get the archive page showing just the relevant posts using the following code (but this contains no pagination): ``` <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="col span_1_of_1 border_bottom"> <h3 class="subtitle no_margin_bottom"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p class="blog_meta_information date"> Author: <a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?>"><?php the_author(); ?></a> &nbsp;&nbsp;|&nbsp;&nbsp; Date: <?php the_time('jS F Y') ?> <?php if(has_tag()) { ?> <br> Tags: <?php the_tags( '',', ','' ); ?> <?php } else {} ?> </p> <p><?php the_field('introduction'); ?></p> <a href="<?php the_permalink(); ?>">Read more</a> </div> <?php endwhile; endif; wp_reset_postdata(); ?> ``` I've also got my main blog working with pagination using the following code: ``` <?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $custom_args = array( 'post_type' => 'post', 'posts_per_page' => 10, 'paged' => $paged ); $custom_query = new WP_Query( $custom_args ); ?> <?php if( $custom_query->have_posts() ) : while( $custom_query->have_posts() ) : $custom_query->the_post(); ?> <div class="col span_1_of_1 border_bottom"> <h3 class="subtitle no_margin_bottom"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p class="blog_meta_information date"> Author: <a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?>"><?php the_author(); ?></a> &nbsp;&nbsp;|&nbsp;&nbsp; Date: <?php the_time('jS F Y') ?> <?php if(has_tag()) { ?> <br> Tags: <?php the_tags( '',', ','' ); ?> <?php } else {} ?> </p> <p><?php the_field('introduction'); ?></p> <a href="<?php the_permalink(); ?>">Read more</a> </div> <?php endwhile; endif; wp_reset_postdata(); ?> <!-- PAGINATION --> <?php if (function_exists(custom_pagination)) { custom_pagination($custom_query->max_num_pages,"",$paged); } ?> ``` The above also uses the following code from my functions.php file: ``` // PAGINATION function custom_pagination($numpages = '', $pagerange = '', $paged='') { if (empty($pagerange)) { $pagerange = 2; } /** * This first part of our function is a fallback * for custom pagination inside a regular loop that * uses the global $paged and global $wp_query variables. * * It's good because we can now override default pagination * in our theme, and use this function in default queries * and custom queries. */ global $paged; if (empty($paged)) { $paged = 1; } if ($numpages == '') { global $wp_query; $numpages = $wp_query->max_num_pages; if(!$numpages) { $numpages = 1; } } /** * We construct the pagination arguments to enter into our paginate_links * function. */ $pagination_args = array( 'base' => get_pagenum_link(1) . '%_%', 'format' => 'page/%#%', 'total' => $numpages, 'current' => $paged, 'show_all' => False, 'end_size' => 1, 'mid_size' => $pagerange, 'prev_next' => True, 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'type' => 'plain', 'add_args' => false, 'add_fragment' => '' ); $paginate_links = paginate_links($pagination_args); if ($paginate_links) { echo "<div class='custom-pagination'>"; echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> "; echo $paginate_links; echo "</div>"; } } ``` Anyone know how I can add make this pagination also work with my archive template? Thanks in advance, Tom
Since 4.1.0, WordPress introduce `the_posts_pagination` to handle number paginate link. I use it all the time, and it just works. With any custom post type. You'll want to use that function after the `while` loop. See: <https://developer.wordpress.org/reference/functions/the_posts_pagination/>
314,633
<pre><code>function set_primary_on_publish ($post_id) { global $post; $categories = get_the_terms( $post-&gt;ID, 'category' ); // wrapper to hide any errors from top level categories or products without category if ( $categories &amp;&amp; ! is_wp_error( $category ) ) : // loop through each cat foreach($categories as $category) : // get the children (if any) of the current cat $children = get_categories( array ('taxonomy' =&gt; 'category', 'parent' =&gt; $category-&gt;term_id )); if ( count($children) == 0 ) { $childid = $category-&gt;term_id; update_post_meta($post-&gt;ID,'_yoast_wpseo_primary_category',$childid); } endforeach; endif; } add_action( 'save_post', 'set_primary_on_publish', 10, 2 ); add_action( 'edit', 'set_primary_on_publish', 10, 2 ); add_action( 'wp_insert_post', 'set_primary_on_publish', 10, 2 ); </code></pre> <p>I'm trying to save the deepest child category as the primary category in the Yoast SEO plugin however the above doesn't seem to do the job.</p> <p>Anyone who can help me out on this?</p> <p>Best regards, Dylan Smit</p>
[ { "answer_id": 325830, "author": "Sergey Harchevnikov", "author_id": 159195, "author_profile": "https://wordpress.stackexchange.com/users/159195", "pm_score": 1, "selected": false, "text": "<p>Try instead </p>\n\n<pre><code>update_post_meta($post-&gt;ID,'_yoast_wpseo_primary_category',$childid); \n</code></pre>\n\n<p>Use below function:</p>\n\n<pre><code>function wpseoPrimaryTerm($taxonomy, $postID, $term){\n\n if ( class_exists('WPSEO_Primary_Term') ) {\n // Set primary term.\n $primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID);\n $primaryTermObject-&gt;set_primary_term($term);\n\n // Save primary term.\n $primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin();\n $primaryTermObjectAdmin-&gt;save_primary_terms($postID);\n }else{\n echo 'Class WPSEO does not exit';\n }\n}\n</code></pre>\n\n<p>Where <code>$taxonomy - taxonomy name, $PostID - $post-&gt;ID, $term - $childid</code></p>\n" }, { "answer_id": 343594, "author": "chrismaaz", "author_id": 23365, "author_profile": "https://wordpress.stackexchange.com/users/23365", "pm_score": 0, "selected": false, "text": "<p>You need to change <code>product</code> to <code>product_cat</code> and <code>_yoast_wpseo_primary_category</code> to <code>_yoast_wpseo_primary_product_cat</code> for it to work. When saving or updating a product it will grab the deepest <code>product_id</code> and set it as the <code>product_id</code> in the <code>wp_postmeta</code> table.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function set_primary_on_publish ($post_ID) {\n global $post;\n\n $categories = get_the_terms( $post-&gt;ID, 'product_cat' ); \n\n // wrapper to hide any errors from top level categories or products without category\n if ( $categories &amp;&amp; ! is_wp_error( $category ) ) :\n\n // loop through each cat\n foreach($categories as $category) :\n\n // get the children (if any) of the current cat\n $children = get_categories( array ('taxonomy' =&gt; 'product_cat', 'parent' =&gt; $category-&gt;term_id ));\n\n if ( count($children) == 0 ) {\n $childid = $category-&gt;term_id;\n update_post_meta($post-&gt;ID,'_yoast_wpseo_primary_product_cat',$childid);\n }\n endforeach;\n endif;\n}\n</code></pre>\n" } ]
2018/09/19
[ "https://wordpress.stackexchange.com/questions/314633", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102035/" ]
``` function set_primary_on_publish ($post_id) { global $post; $categories = get_the_terms( $post->ID, 'category' ); // wrapper to hide any errors from top level categories or products without category if ( $categories && ! is_wp_error( $category ) ) : // loop through each cat foreach($categories as $category) : // get the children (if any) of the current cat $children = get_categories( array ('taxonomy' => 'category', 'parent' => $category->term_id )); if ( count($children) == 0 ) { $childid = $category->term_id; update_post_meta($post->ID,'_yoast_wpseo_primary_category',$childid); } endforeach; endif; } add_action( 'save_post', 'set_primary_on_publish', 10, 2 ); add_action( 'edit', 'set_primary_on_publish', 10, 2 ); add_action( 'wp_insert_post', 'set_primary_on_publish', 10, 2 ); ``` I'm trying to save the deepest child category as the primary category in the Yoast SEO plugin however the above doesn't seem to do the job. Anyone who can help me out on this? Best regards, Dylan Smit
Try instead ``` update_post_meta($post->ID,'_yoast_wpseo_primary_category',$childid); ``` Use below function: ``` function wpseoPrimaryTerm($taxonomy, $postID, $term){ if ( class_exists('WPSEO_Primary_Term') ) { // Set primary term. $primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID); $primaryTermObject->set_primary_term($term); // Save primary term. $primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin(); $primaryTermObjectAdmin->save_primary_terms($postID); }else{ echo 'Class WPSEO does not exit'; } } ``` Where `$taxonomy - taxonomy name, $PostID - $post->ID, $term - $childid`
314,684
<p>I have a slider revolution where in there are four revolution sliders. </p> <p>Now the current scenario is the 2nd slider is been activated, but i want to deactivate the 2nd slider and activate first slider</p> <p>The screenshot is shown below <a href="https://i.stack.imgur.com/fZF3V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fZF3V.png" alt="Screenshots"></a></p> <p>In the above screen shot #3 Retrax video is activated but i need #1 Mainslider to be activate</p>
[ { "answer_id": 325830, "author": "Sergey Harchevnikov", "author_id": 159195, "author_profile": "https://wordpress.stackexchange.com/users/159195", "pm_score": 1, "selected": false, "text": "<p>Try instead </p>\n\n<pre><code>update_post_meta($post-&gt;ID,'_yoast_wpseo_primary_category',$childid); \n</code></pre>\n\n<p>Use below function:</p>\n\n<pre><code>function wpseoPrimaryTerm($taxonomy, $postID, $term){\n\n if ( class_exists('WPSEO_Primary_Term') ) {\n // Set primary term.\n $primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID);\n $primaryTermObject-&gt;set_primary_term($term);\n\n // Save primary term.\n $primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin();\n $primaryTermObjectAdmin-&gt;save_primary_terms($postID);\n }else{\n echo 'Class WPSEO does not exit';\n }\n}\n</code></pre>\n\n<p>Where <code>$taxonomy - taxonomy name, $PostID - $post-&gt;ID, $term - $childid</code></p>\n" }, { "answer_id": 343594, "author": "chrismaaz", "author_id": 23365, "author_profile": "https://wordpress.stackexchange.com/users/23365", "pm_score": 0, "selected": false, "text": "<p>You need to change <code>product</code> to <code>product_cat</code> and <code>_yoast_wpseo_primary_category</code> to <code>_yoast_wpseo_primary_product_cat</code> for it to work. When saving or updating a product it will grab the deepest <code>product_id</code> and set it as the <code>product_id</code> in the <code>wp_postmeta</code> table.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function set_primary_on_publish ($post_ID) {\n global $post;\n\n $categories = get_the_terms( $post-&gt;ID, 'product_cat' ); \n\n // wrapper to hide any errors from top level categories or products without category\n if ( $categories &amp;&amp; ! is_wp_error( $category ) ) :\n\n // loop through each cat\n foreach($categories as $category) :\n\n // get the children (if any) of the current cat\n $children = get_categories( array ('taxonomy' =&gt; 'product_cat', 'parent' =&gt; $category-&gt;term_id ));\n\n if ( count($children) == 0 ) {\n $childid = $category-&gt;term_id;\n update_post_meta($post-&gt;ID,'_yoast_wpseo_primary_product_cat',$childid);\n }\n endforeach;\n endif;\n}\n</code></pre>\n" } ]
2018/09/20
[ "https://wordpress.stackexchange.com/questions/314684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150954/" ]
I have a slider revolution where in there are four revolution sliders. Now the current scenario is the 2nd slider is been activated, but i want to deactivate the 2nd slider and activate first slider The screenshot is shown below [![Screenshots](https://i.stack.imgur.com/fZF3V.png)](https://i.stack.imgur.com/fZF3V.png) In the above screen shot #3 Retrax video is activated but i need #1 Mainslider to be activate
Try instead ``` update_post_meta($post->ID,'_yoast_wpseo_primary_category',$childid); ``` Use below function: ``` function wpseoPrimaryTerm($taxonomy, $postID, $term){ if ( class_exists('WPSEO_Primary_Term') ) { // Set primary term. $primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID); $primaryTermObject->set_primary_term($term); // Save primary term. $primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin(); $primaryTermObjectAdmin->save_primary_terms($postID); }else{ echo 'Class WPSEO does not exit'; } } ``` Where `$taxonomy - taxonomy name, $PostID - $post->ID, $term - $childid`
314,698
<p>How can I change the tag contents of individual Wordpress posts?</p> <p>I want to add a meta tag for keyword. I use Yoast SEO but even though I specify the focus keyword, no keyword is added in the meta tag of the page's HTML.</p> <p>Please help me with this or suggest alternatives.</p> <p>Do I need to use costume fields? If so, how?</p>
[ { "answer_id": 314700, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 2, "selected": false, "text": "<p>I would <a href=\"https://yoast.com/meta-keywords/\" rel=\"nofollow noreferrer\">read this article</a>, its from Yoast. I don't think you are understanding what the focus keyword feature does. This article talks about that as well as how adding the keyword meta tag is a waste of time (in most cases).</p>\n\n<p>I wouldn't worry about adding it BUT if you still want to I would add a custom field. This is easiest done with <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">ACF</a>. You can easily create a text field and have it show on every page. Then in your header.php just add something like this...</p>\n\n<pre><code> &lt;meta name=\"keywords\" content=\"&lt;?php the_field('my_field'); ?&gt;\"&gt;\n</code></pre>\n" }, { "answer_id": 314709, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Unless you truly need the extra functionality in ACF, just use Core's built-in custom fields - just go to the top of the page, Screen Options, and make sure they're showing. Then carefully make sure to name the field the same thing every time. You should also be sure to create a child theme rather than editing your existing one, so your code doesn't get overwritten when your theme updates, and then make the call conditional, so if you haven't added any keywords no empty meta tag is added. This code will also allow you to add multiple keywords.</p>\n\n<p>Assuming your custom field's name is <code>meta_keywords</code>:</p>\n\n<pre><code>&lt;?php\n// false returns all values\n$keywords = get_post_meta($post-&gt;ID, 'meta_keywords', false);\n// if any were found\nif(count($keywords) &gt; 0) {\n // convert the array to comma-separated string and output\n $all_keywords = implode(',', $keywords); ?&gt;\n &lt;meta name=\"keywords\" content=\"&lt;?php echo $all_keywords; ?&gt;\"&gt;&lt;?php\n}\n// otherwise don't output meta keywords tag at all\n?&gt;\n</code></pre>\n" } ]
2018/09/20
[ "https://wordpress.stackexchange.com/questions/314698", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149467/" ]
How can I change the tag contents of individual Wordpress posts? I want to add a meta tag for keyword. I use Yoast SEO but even though I specify the focus keyword, no keyword is added in the meta tag of the page's HTML. Please help me with this or suggest alternatives. Do I need to use costume fields? If so, how?
I would [read this article](https://yoast.com/meta-keywords/), its from Yoast. I don't think you are understanding what the focus keyword feature does. This article talks about that as well as how adding the keyword meta tag is a waste of time (in most cases). I wouldn't worry about adding it BUT if you still want to I would add a custom field. This is easiest done with [ACF](https://www.advancedcustomfields.com/). You can easily create a text field and have it show on every page. Then in your header.php just add something like this... ``` <meta name="keywords" content="<?php the_field('my_field'); ?>"> ```
314,701
<p>How can I remove "View Details" link from plugins listing in Admin panel without change in WordPress core files.</p> <p><a href="https://i.stack.imgur.com/yPuw5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yPuw5.png" alt="enter image description here"></a></p>
[ { "answer_id": 314707, "author": "Aparna_29", "author_id": 84165, "author_profile": "https://wordpress.stackexchange.com/users/84165", "pm_score": 1, "selected": false, "text": "<p>Try following code:</p>\n\n<pre><code>add_filter('plugin_row_meta','fun_hide_view_details',10,4);\nfunction fun_hide_view_details($plugin_meta, $plugin_file, $plugin_data, $status)\n{\n if($plugin_data['slug'] == 'YOUR_PLUGIN_SLUG')\n unset($plugin_meta[2]);\n return $plugin_meta;\n}\n</code></pre>\n" }, { "answer_id": 348942, "author": "Ram kumar", "author_id": 175366, "author_profile": "https://wordpress.stackexchange.com/users/175366", "pm_score": 0, "selected": false, "text": "<p>Change the plugin name to something unique. If I can remember correctly, this is all that is needed. Just a note though, adhere to any special licence requirements there may be from the original author. Don't make code yours if you did nkot write it, always leave some credit to the author :-) </p>\n" } ]
2018/09/20
[ "https://wordpress.stackexchange.com/questions/314701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143123/" ]
How can I remove "View Details" link from plugins listing in Admin panel without change in WordPress core files. [![enter image description here](https://i.stack.imgur.com/yPuw5.png)](https://i.stack.imgur.com/yPuw5.png)
Try following code: ``` add_filter('plugin_row_meta','fun_hide_view_details',10,4); function fun_hide_view_details($plugin_meta, $plugin_file, $plugin_data, $status) { if($plugin_data['slug'] == 'YOUR_PLUGIN_SLUG') unset($plugin_meta[2]); return $plugin_meta; } ```
314,805
<p>I have 2 registration forms, default one on <code>/wp-login.php?action=register</code> for "recruiter" users, other one on <code>/wp-login.php?action=register&amp;type=candidat</code> for "candidates" users</p> <p>My problem is that on candidate form, the form tag still has <code>/wp-login.php?action=register</code> as the action URL, and I want it to be <code>/wp-login.php?action=register&amp;type=candidat</code></p> <p>I tried updating wp-login.php file but if I update Wordpress in the future, my code will be overwritten</p> <p>I've tried other topics recommanding to use 'register_url' hook but it doesn't seem to work</p>
[ { "answer_id": 314820, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": true, "text": "<p>You could do something like this:</p>\n\n<pre><code>&lt;?php\n\nadd_action( 'register_form', function() {\n $get_type = filter_input( INPUT_GET, 'type', FILTER_SANITIZE_STRING );\n\n if ( ! $get_type ) {\n return;\n }\n?&gt;\n&lt;input type=\"hidden\" name=\"type\" value=\"&lt;?php echo esc_attr( $get_type ); ?&gt;\" /&gt;\n&lt;?php\n});\n</code></pre>\n\n<p>This will add the <code>type</code> parameter as a hidden field on the form if it is set in the GET query string.</p>\n" }, { "answer_id": 314821, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 0, "selected": false, "text": "<p>I went a different route than the other answer, a modification of the registration URL through the site_url filter, I've tested it, and it works.</p>\n\n<pre><code>function my_verify_registration_type( $url, $path, $scheme, $blog_id ) {\n if ( $scheme == 'login_post' ) {\n if ( strpos( $url, '?action=register' ) !== false &amp;&amp; !empty( $_REQUEST['type'] ) ) {\n $url = esc_url( add_query_arg( 'type', sanitize_text_field( $_REQUEST['type'] ), $url ) );\n }\n }\n return $url;\n}\nadd_filter( 'site_url', 'my_verify_registration_type', 10, 4 );\n</code></pre>\n" } ]
2018/09/21
[ "https://wordpress.stackexchange.com/questions/314805", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151041/" ]
I have 2 registration forms, default one on `/wp-login.php?action=register` for "recruiter" users, other one on `/wp-login.php?action=register&type=candidat` for "candidates" users My problem is that on candidate form, the form tag still has `/wp-login.php?action=register` as the action URL, and I want it to be `/wp-login.php?action=register&type=candidat` I tried updating wp-login.php file but if I update Wordpress in the future, my code will be overwritten I've tried other topics recommanding to use 'register\_url' hook but it doesn't seem to work
You could do something like this: ``` <?php add_action( 'register_form', function() { $get_type = filter_input( INPUT_GET, 'type', FILTER_SANITIZE_STRING ); if ( ! $get_type ) { return; } ?> <input type="hidden" name="type" value="<?php echo esc_attr( $get_type ); ?>" /> <?php }); ``` This will add the `type` parameter as a hidden field on the form if it is set in the GET query string.
314,807
<p>I need to use validation is_single('wordpress') in file functions.php. </p> <p>But the function is_single() does not work in the file functions.php. </p> <p>What can I do so that I can use is_single() in file functions.php?</p> <p>If more, then:</p> <p>I'm doing a check, its single page or not. </p> <p>And for single page I am set custom function..</p> <p>Please help me someone.</p>
[ { "answer_id": 314819, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": -1, "selected": true, "text": "<p><code>is_single</code> most likely only works inside of <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a>, and <code>functions.php</code> loads before you're in The Loop.</p>\n\n<p>You could try something like this:</p>\n\n<pre><code>add_action( 'wp_head', function(){\n var_dump(is_single());\n});\n</code></pre>\n\n<p>And now you see that <code>is_single()</code> returns <code>true</code>.</p>\n\n<p>EDIT: I was probably off for suggesting it only works inside The Loop, but there's definitely better places for <code>is_single</code> than in <code>functions.php</code>, and if you're checking the \"singleness\" of a page, wait until you're in the request proper, or the template, to use it.</p>\n" }, { "answer_id": 314834, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 2, "selected": false, "text": "<p>Fresh from the Codex:</p>\n<blockquote>\n<p>Warning: You can only use conditional query tags after the posts_selection action hook in WordPress (the wp action hook is the first one through which you can use these conditionals). <strong>For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.</strong></p>\n<p>However: if you have a reference to the query object (for example, from within the parse_query or pre_get_posts hooks), you can use the WP_Query conditional methods (eg: $query-&gt;is_search())</p>\n</blockquote>\n<p><a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Conditional_Tags</a></p>\n" } ]
2018/09/21
[ "https://wordpress.stackexchange.com/questions/314807", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137220/" ]
I need to use validation is\_single('wordpress') in file functions.php. But the function is\_single() does not work in the file functions.php. What can I do so that I can use is\_single() in file functions.php? If more, then: I'm doing a check, its single page or not. And for single page I am set custom function.. Please help me someone.
`is_single` most likely only works inside of [The Loop](https://codex.wordpress.org/The_Loop), and `functions.php` loads before you're in The Loop. You could try something like this: ``` add_action( 'wp_head', function(){ var_dump(is_single()); }); ``` And now you see that `is_single()` returns `true`. EDIT: I was probably off for suggesting it only works inside The Loop, but there's definitely better places for `is_single` than in `functions.php`, and if you're checking the "singleness" of a page, wait until you're in the request proper, or the template, to use it.
314,815
<p>I have a big site with several plugins that take up memory, a lot of requests to the server, etc. I've maxxed out my hosting to help account for this, but are there optimum PHP and Wordpress settings for big heavy site, or just optimum PHP base settings for Wordpress period.</p> <p>Here are my current settings:</p> <pre><code>allow_url_fopen = Disabled allow_url_include = Disabled display_errors = Enabled enable_dl = Disabled file_uploads = Enabled max_execution_time = 600 max_input_time = 400 max_input_vars = 10000 memory_limit = 128M session.save_path = (blank) upload_max_filesize = 2M </code></pre>
[ { "answer_id": 314819, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": -1, "selected": true, "text": "<p><code>is_single</code> most likely only works inside of <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a>, and <code>functions.php</code> loads before you're in The Loop.</p>\n\n<p>You could try something like this:</p>\n\n<pre><code>add_action( 'wp_head', function(){\n var_dump(is_single());\n});\n</code></pre>\n\n<p>And now you see that <code>is_single()</code> returns <code>true</code>.</p>\n\n<p>EDIT: I was probably off for suggesting it only works inside The Loop, but there's definitely better places for <code>is_single</code> than in <code>functions.php</code>, and if you're checking the \"singleness\" of a page, wait until you're in the request proper, or the template, to use it.</p>\n" }, { "answer_id": 314834, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 2, "selected": false, "text": "<p>Fresh from the Codex:</p>\n<blockquote>\n<p>Warning: You can only use conditional query tags after the posts_selection action hook in WordPress (the wp action hook is the first one through which you can use these conditionals). <strong>For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.</strong></p>\n<p>However: if you have a reference to the query object (for example, from within the parse_query or pre_get_posts hooks), you can use the WP_Query conditional methods (eg: $query-&gt;is_search())</p>\n</blockquote>\n<p><a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Conditional_Tags</a></p>\n" } ]
2018/09/21
[ "https://wordpress.stackexchange.com/questions/314815", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150825/" ]
I have a big site with several plugins that take up memory, a lot of requests to the server, etc. I've maxxed out my hosting to help account for this, but are there optimum PHP and Wordpress settings for big heavy site, or just optimum PHP base settings for Wordpress period. Here are my current settings: ``` allow_url_fopen = Disabled allow_url_include = Disabled display_errors = Enabled enable_dl = Disabled file_uploads = Enabled max_execution_time = 600 max_input_time = 400 max_input_vars = 10000 memory_limit = 128M session.save_path = (blank) upload_max_filesize = 2M ```
`is_single` most likely only works inside of [The Loop](https://codex.wordpress.org/The_Loop), and `functions.php` loads before you're in The Loop. You could try something like this: ``` add_action( 'wp_head', function(){ var_dump(is_single()); }); ``` And now you see that `is_single()` returns `true`. EDIT: I was probably off for suggesting it only works inside The Loop, but there's definitely better places for `is_single` than in `functions.php`, and if you're checking the "singleness" of a page, wait until you're in the request proper, or the template, to use it.
314,864
<p>I'm combining multiple queries for a loop using the following method:</p> <pre><code>function order_by_date( $a, $b ) { return strcmp( $b-&gt;post_date, $a-&gt;post_date ); } // get the posts for the first query $q1_args = array( // args for the first query ); $q1_posts = get_posts( $q1_args ); // get the posts for the second query $q2_args = array( // args for the second query ); $q2_posts= get_posts( $q2_args ); // Merge the post arrays together, and sort by date using the order_by_date function $final_posts = array_merge( $q1_posts, $q2_posts ); usort( $final_posts, 'order_by_date' ); // Loop over the posts and use setup_postdata to format for template tag usage foreach ( $final_posts as $key =&gt; $post ) { setup_postdata( $post ); // Now we can use template tags as if this was in a normal WP loop the_title('&lt;h2&gt;','&lt;/h2&gt;'); the_content(); } </code></pre> <p>This works fine, but when I try to remove duplicates, I get nothing (no errors either):</p> <pre><code>// This is my code for trying to remove the duplicates $final_posts = array_unique( array_merge( $q1_posts, $q2_posts ) ); </code></pre> <p>Any ideas on what could be going wrong?</p>
[ { "answer_id": 314867, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 2, "selected": true, "text": "<p>It will work with the <code>SORT_REGULAR</code> flag:</p>\n\n<p><code>array_unique( array_merge( $q1_posts, $q2_posts ), SORT_REGULAR );</code></p>\n" }, { "answer_id": 314868, "author": "Best Dev Tutorials", "author_id": 145165, "author_profile": "https://wordpress.stackexchange.com/users/145165", "pm_score": 0, "selected": false, "text": "<p>Thanks to Michael's answer, I used an alternative method:</p>\n\n<p>Before the loop, create an array:</p>\n\n<pre><code>$do_not_duplicate = array(); // set an array for catching duplicates\n</code></pre>\n\n<p>Then inside the loop, add the post id to the array, and skip over it if it is already in it:</p>\n\n<pre><code>if (in_array($postID, $do_not_duplicate)) {\n continue; // if its already been through it, dont display it\n }\n$do_not_duplicate[] = $postID; // add the id to the array\n</code></pre>\n" } ]
2018/09/22
[ "https://wordpress.stackexchange.com/questions/314864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145165/" ]
I'm combining multiple queries for a loop using the following method: ``` function order_by_date( $a, $b ) { return strcmp( $b->post_date, $a->post_date ); } // get the posts for the first query $q1_args = array( // args for the first query ); $q1_posts = get_posts( $q1_args ); // get the posts for the second query $q2_args = array( // args for the second query ); $q2_posts= get_posts( $q2_args ); // Merge the post arrays together, and sort by date using the order_by_date function $final_posts = array_merge( $q1_posts, $q2_posts ); usort( $final_posts, 'order_by_date' ); // Loop over the posts and use setup_postdata to format for template tag usage foreach ( $final_posts as $key => $post ) { setup_postdata( $post ); // Now we can use template tags as if this was in a normal WP loop the_title('<h2>','</h2>'); the_content(); } ``` This works fine, but when I try to remove duplicates, I get nothing (no errors either): ``` // This is my code for trying to remove the duplicates $final_posts = array_unique( array_merge( $q1_posts, $q2_posts ) ); ``` Any ideas on what could be going wrong?
It will work with the `SORT_REGULAR` flag: `array_unique( array_merge( $q1_posts, $q2_posts ), SORT_REGULAR );`
314,886
<p>I am adding custom admin filters for my custom post types. I am a bit confused about how to go with the <code>parse_query</code> filter in order to have my posts filtered based on 2 or more filters.</p> <p>Initially for 1 filter, I can do:</p> <pre><code>$query-&gt;query_vars['meta_key'] = 'city'; $query-&gt;query_vars['meta_value'] = $cityId; $query-&gt;query_vars['meta_compare'] = '='; </code></pre> <p>and I will get my filtered results.</p> <p>I am wondering, if WP would accept more meta_keys/values for the query_vars... </p> <p>I am trying to set a <code>meta_query</code> and below is what I have done - but it doesn't work. </p> <pre><code>add_filter( 'parse_query', 'wpr_manager_filter' ); function wpr_manager_filter($query) { global $page; $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( is_admin() &amp;&amp; 'properties' == $current_page &amp;&amp; 'edit.php' == $page ) { $metaQuery = array(); if (isset( $_GET['city-filter'] ) &amp;&amp; $_GET['city-filter'] != '-1') { $cityId = (int)$_GET['city-filter']; $metaQuery['relation'] = 'AND'; $metaQuery[] = array( 'meta_key' =&gt; 'city', 'meta_value' =&gt; $cityId, 'meta_compare' =&gt; '=' ); // $query-&gt;query_vars['meta_key'] = 'city'; // $query-&gt;query_vars['meta_value'] = $cityId; // $query-&gt;query_vars['meta_compare'] = '='; } if (isset( $_GET['visibility-filter'] ) &amp;&amp; $_GET['visibility-filter'] != '-1') { $visibility = (int)$_GET['visibility-filter']; $metaQuery[2] = array( 'meta_key' =&gt; 'visibility', 'meta_value' =&gt; $visibility, 'meta_compare' =&gt; '=' ); } $query-&gt;meta_query = $metaQuery; } } </code></pre> <p>It has been a long day, and I have just start getting more familiar with deeper WP concepts, so any kind of help that will push me forward and will explain me what I am doing wrong it would be greatly appreciated.</p>
[ { "answer_id": 314895, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 0, "selected": false, "text": "<p>The problem is in the end of your code: <code>$query-&gt;meta_query = $metaQuery;</code>. </p>\n\n<p><code>meta_query</code> is a property of <code>$query_var</code> array. So the coreect one should be:</p>\n\n<pre><code>$query-&gt;query_vars['meta_query'] = $metaQuery;\n</code></pre>\n" }, { "answer_id": 314902, "author": "FFrewin", "author_id": 43534, "author_profile": "https://wordpress.stackexchange.com/users/43534", "pm_score": 2, "selected": true, "text": "<p>This is my final working piece of code:</p>\n\n<pre><code>function wpr_manager_filter($query) {\n global $pagenow;\n global $typenow;\n\n $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';\n\n if ( is_admin()\n &amp;&amp; 'properties' == $typenow\n &amp;&amp; 'edit.php' == $pagenow\n )\n {\n $queryParamsCounter = 0;\n if (isset( $_GET['city-filter'] ) &amp;&amp; $_GET['city-filter'] != '-1')\n {\n $cityId = (int)$_GET['city-filter'];\n $queryParamsCounter++;\n }\n if (isset( $_GET['visibility-filter'] ) &amp;&amp; $_GET['visibility-filter'] != '-1')\n {\n $queryParamsCounter++;\n $visibility = (int)$_GET['visibility-filter'];\n }\n\n $meta_query = array();\n\n if ($queryParamsCounter &gt; 1) {\n $meta_query['relation'] = 'AND';\n }\n\n if (isset($cityId)) {\n $meta_query[] = array(\n 'key' =&gt; 'city',\n 'value' =&gt; $cityId,\n 'compare' =&gt; '=',\n 'type' =&gt; 'NUMERIC',\n );\n }\n if (isset($visibility)) {\n $meta_query[] = array(\n 'key' =&gt; 'visibility',\n 'value' =&gt; $visibility,\n 'compare' =&gt; '=',\n 'type' =&gt; 'NUMERIC',\n );\n }\n\n $query-&gt;set( 'meta_query', $meta_query);\n }\n}\n</code></pre>\n\n<p>May someone else find it useful in the future.</p>\n" } ]
2018/09/23
[ "https://wordpress.stackexchange.com/questions/314886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43534/" ]
I am adding custom admin filters for my custom post types. I am a bit confused about how to go with the `parse_query` filter in order to have my posts filtered based on 2 or more filters. Initially for 1 filter, I can do: ``` $query->query_vars['meta_key'] = 'city'; $query->query_vars['meta_value'] = $cityId; $query->query_vars['meta_compare'] = '='; ``` and I will get my filtered results. I am wondering, if WP would accept more meta\_keys/values for the query\_vars... I am trying to set a `meta_query` and below is what I have done - but it doesn't work. ``` add_filter( 'parse_query', 'wpr_manager_filter' ); function wpr_manager_filter($query) { global $page; $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( is_admin() && 'properties' == $current_page && 'edit.php' == $page ) { $metaQuery = array(); if (isset( $_GET['city-filter'] ) && $_GET['city-filter'] != '-1') { $cityId = (int)$_GET['city-filter']; $metaQuery['relation'] = 'AND'; $metaQuery[] = array( 'meta_key' => 'city', 'meta_value' => $cityId, 'meta_compare' => '=' ); // $query->query_vars['meta_key'] = 'city'; // $query->query_vars['meta_value'] = $cityId; // $query->query_vars['meta_compare'] = '='; } if (isset( $_GET['visibility-filter'] ) && $_GET['visibility-filter'] != '-1') { $visibility = (int)$_GET['visibility-filter']; $metaQuery[2] = array( 'meta_key' => 'visibility', 'meta_value' => $visibility, 'meta_compare' => '=' ); } $query->meta_query = $metaQuery; } } ``` It has been a long day, and I have just start getting more familiar with deeper WP concepts, so any kind of help that will push me forward and will explain me what I am doing wrong it would be greatly appreciated.
This is my final working piece of code: ``` function wpr_manager_filter($query) { global $pagenow; global $typenow; $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( is_admin() && 'properties' == $typenow && 'edit.php' == $pagenow ) { $queryParamsCounter = 0; if (isset( $_GET['city-filter'] ) && $_GET['city-filter'] != '-1') { $cityId = (int)$_GET['city-filter']; $queryParamsCounter++; } if (isset( $_GET['visibility-filter'] ) && $_GET['visibility-filter'] != '-1') { $queryParamsCounter++; $visibility = (int)$_GET['visibility-filter']; } $meta_query = array(); if ($queryParamsCounter > 1) { $meta_query['relation'] = 'AND'; } if (isset($cityId)) { $meta_query[] = array( 'key' => 'city', 'value' => $cityId, 'compare' => '=', 'type' => 'NUMERIC', ); } if (isset($visibility)) { $meta_query[] = array( 'key' => 'visibility', 'value' => $visibility, 'compare' => '=', 'type' => 'NUMERIC', ); } $query->set( 'meta_query', $meta_query); } } ``` May someone else find it useful in the future.
314,919
<p>I am removing jQuery migrate in WordPress in this way:</p> <pre><code>add_filter( 'wp_default_scripts', 'remove_jquery_migrate' ); function remove_jquery_migrate( &amp;$scripts ){ if(!is_admin()){ $scripts-&gt;remove( 'jquery'); $scripts-&gt;add( 'jquery', false, array( 'jquery-core' ), '1.2.1'); } } </code></pre> <p>I'm confused at how you set the <code>in_footer</code> property with the <a href="https://developer.wordpress.org/reference/classes/WP_Dependencies/add/" rel="nofollow noreferrer">WP_Dependencies::add</a> function, I tried the below but it didn't work:</p> <pre><code>$scripts-&gt;add( 'jquery', false, array( 'jquery-core' ), '1.2.1', ['in_footer' =&gt; true]); </code></pre> <p>What is the correct way to do this?</p>
[ { "answer_id": 315117, "author": "Ian", "author_id": 96731, "author_profile": "https://wordpress.stackexchange.com/users/96731", "pm_score": 1, "selected": false, "text": "<p>That is correct but you did supply a new source.</p>\n\n<p>Replace:</p>\n\n<pre><code>$scripts-&gt;add( 'jquery', false, array( 'jquery-core' ), '1.2.1', ['in_footer' =&gt; true]);\n</code></pre>\n\n<p>With: </p>\n\n<pre><code>$scripts-&gt;add( 'jquery', 'http://new-url/', array( 'jquery-core' ), '1.2.1', ['in_footer' =&gt; true]);\n</code></pre>\n" }, { "answer_id": 315138, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": false, "text": "<p>There is much safer way of removing <code>jquery-migrate</code>... Your code is almost correct, but first you remove jQuery and then add it again. If dependencies for jQuery will change, then your code will cause problems.</p>\n\n<p>But you don't have to remove script to change its dependencies. You can do exactly that:</p>\n\n<pre><code>function remove_jquery_migrate( $scripts ) {\n if ( ! is_admin() &amp;&amp; isset( $scripts-&gt;registered['jquery'] ) ) {\n $script = $scripts-&gt;registered['jquery'];\n\n if ( $script-&gt;deps ) {\n $script-&gt;deps = array_diff( $script-&gt;deps, array( 'jquery-migrate' ) );\n }\n }\n} \nadd_action( 'wp_default_scripts', 'remove_jquery_migrate' );\n</code></pre>\n\n<p>It's much safer, since we remove only one dependency that we want to be removed.</p>\n\n<p>And if you want to move jQuery to footer, then you can use this code:</p>\n\n<pre><code>function remove_jquery_migrate( $scripts ) {\n if ( ! is_admin() &amp;&amp; isset( $scripts-&gt;registered['jquery'] ) ) {\n $script = $scripts-&gt;registered['jquery'];\n\n if ( $script-&gt;deps ) {\n $script-&gt;deps = array_diff( $script-&gt;deps, array( 'jquery-migrate' ) );\n }\n\n $scripts-&gt;add_data( 'jquery', 'group', 1 );\n $scripts-&gt;add_data( 'jquery-core', 'group', 1 );\n }\n} \nadd_action( 'wp_default_scripts', 'remove_jquery_migrate' );\n</code></pre>\n\n<p>Again - we don't remove any scripts and add our own, but modify existing scripts only, so it's much more secure approach.</p>\n" } ]
2018/09/23
[ "https://wordpress.stackexchange.com/questions/314919", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1839/" ]
I am removing jQuery migrate in WordPress in this way: ``` add_filter( 'wp_default_scripts', 'remove_jquery_migrate' ); function remove_jquery_migrate( &$scripts ){ if(!is_admin()){ $scripts->remove( 'jquery'); $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1'); } } ``` I'm confused at how you set the `in_footer` property with the [WP\_Dependencies::add](https://developer.wordpress.org/reference/classes/WP_Dependencies/add/) function, I tried the below but it didn't work: ``` $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1', ['in_footer' => true]); ``` What is the correct way to do this?
There is much safer way of removing `jquery-migrate`... Your code is almost correct, but first you remove jQuery and then add it again. If dependencies for jQuery will change, then your code will cause problems. But you don't have to remove script to change its dependencies. You can do exactly that: ``` function remove_jquery_migrate( $scripts ) { if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) { $script = $scripts->registered['jquery']; if ( $script->deps ) { $script->deps = array_diff( $script->deps, array( 'jquery-migrate' ) ); } } } add_action( 'wp_default_scripts', 'remove_jquery_migrate' ); ``` It's much safer, since we remove only one dependency that we want to be removed. And if you want to move jQuery to footer, then you can use this code: ``` function remove_jquery_migrate( $scripts ) { if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) { $script = $scripts->registered['jquery']; if ( $script->deps ) { $script->deps = array_diff( $script->deps, array( 'jquery-migrate' ) ); } $scripts->add_data( 'jquery', 'group', 1 ); $scripts->add_data( 'jquery-core', 'group', 1 ); } } add_action( 'wp_default_scripts', 'remove_jquery_migrate' ); ``` Again - we don't remove any scripts and add our own, but modify existing scripts only, so it's much more secure approach.
314,966
<p>I would like to write some arguments for my query and both need to be true. I am having trouble with the Syntax.</p> <p>'meta_key' => $campaign_type, </p> <p>'meta_value' => $Campaign_ID,</p> <p><strong>AND</strong></p> <p>'meta_key' => 'organisation',</p> <p>'meta_value' => $userOrg,</p> <p>Below is my query code:</p> <pre><code>$args = array ( 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'meta_key' =&gt; $campaign_type, 'meta_value' =&gt; $Campaign_ID, 'compare' =&gt; '=' ), array( 'meta_key' =&gt; 'organisation', 'meta_value' =&gt; $userOrg, 'compare' =&gt; '=' ) )); </code></pre> <p>Thank you.</p>
[ { "answer_id": 314926, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You need to have a lot of traffic for naive protocol based optimizations to be effective, and even then it is not obvious that you can gain much even when it does kick in.</p>\n\n<p>Most people will be first time users of your site, and browser have only a limited space to store information about the last update time of all the pages a user visited.</p>\n\n<p>But even if you actually get such a request, how exactly do you know when was the last update? The best answer to that question that wordpress has is the publish time of the latest published post, which might not represent at all when a theme change, or any other setting change happened. But even for such a naive assumption, you still need to load wordpress and do at least two DB queries. You will probably get some improvement, but not as much as using an object cache or page cache in the first place.</p>\n\n<p>And in the real world, most of the slowness is because of the JS/CSS/media on the page, and if it is not cached (and unless you are facebook, it is unlikely t be cached), your page will still load slow even if the \"last published\" thing did work.</p>\n" }, { "answer_id": 315572, "author": "GaryL", "author_id": 151126, "author_profile": "https://wordpress.stackexchange.com/users/151126", "pm_score": 0, "selected": false, "text": "<p>I'm answering my own question. Perhaps it will be useful for someone else.</p>\n\n<p><strong>Short answer</strong>: You can short-circuit the page generation process via <a href=\"https://codex.wordpress.org/Function_Reference/wp_die\" rel=\"nofollow noreferrer\">wp_die()</a> or <a href=\"https://developer.wordpress.org/reference/functions/wp_send_json/\" rel=\"nofollow noreferrer\">wp_send_json()</a>. </p>\n\n<p>But since I don't want to send a 500 status it eliminates wp_die(), and since I want to send html not json, it eliminates wp_send_json(). So instead, I copied &amp; modified the <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/functions.php#L3179\" rel=\"nofollow noreferrer\">wp_send_json() source</a> to produce the following:</p>\n\n<pre><code>function wp_send_html( $response = null, $status_code = null ) {\n @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );\n if ( null !== $status_code ) {\n status_header( $status_code );\n }\n if ($response) {\n echo $response; \n }\n die;\n};\n</code></pre>\n\n<p>In my code, after I determine the request is unchanged from the prior request, I call:</p>\n\n<pre><code>wp_send_html(null, 304);\n</code></pre>\n\n<p>... which sends a 304 response including any html response headers that have setup, and an empty body.</p>\n\n<p><strong>Result: ~75% page load time savings</strong></p>\n\n<p>In the single post places that I'm using this, I've decreased response times from about 4-5 secs, down to 1.0-1.3 seconds.</p>\n\n<p><strong>Longer answer:</strong></p>\n\n<p>From @Mark's post, the primary things I need to consider are the post last change, and the last change for any theme or other global element. I am only handling only single page/post pages, and I've added a <code>$MIN_UPD_DATE</code> global at the top of my functions.php with I'll update when I do global/style changes (yeah, I know that's a little kludgey).</p>\n\n<p>My more complete code in my functions.php is as follows:</p>\n\n<pre><code>// Update this on sitewide changes\n$MIN_UPD_DATE = DateTime::createFromFormat('M d Y H:i:s', 'Sep 01 2018 01:01:01');\n\n// For web pages and single post pages - note the last changed date\n // Thanks to: https://wordpress.stackexchange.com/questions/172966/if-modified-since-http-header\n // This will support clients sending HTTP header: If-Modified-Since \nfunction handle_modified_since_header() {\n global $MIN_UPD_DATE;\n //Check if we are in a single post of any type (archive pages have no modified date)\n\n if( is_singular() ) { // excludes multi-post pages\n $post_id = get_queried_object_id();\n if( $post_id ) {\n header(\"Cache-Control: public\"); \n // inherited/default was: Cache-Control: no-cache, must-revalidate, max-age=0\n\n $postModTime = new DateTime(get_the_modified_time('D, d M Y H:i:s', $post_id));\n if ($MIN_UPD_DATE &gt; $postModTime) {\n $postModTime = $MIN_UPD_DATE;\n };\n header(\"Last-Modified: \" . $postModTime-&gt;format(\"D, d M Y H:i:s\") . \" GMT\" );\n return true; // can use modified date to expire page\n }\n }\n return false; // can NOT use modified date to expire page\n};\n\n// Checks single post &amp; page entries for a Post Modified Date \n// after the http request header: IF_MODIFIED_SINCE\n// or after the MIN_UPD_DATE\n// else, on any missing elements, assumes that request is expired.\nfunction is_request_expired() {\n global $MIN_UPD_DATE;\n $MOD_SINCE = 'HTTP_IF_MODIFIED_SINCE';\n $DATE_FMT = 'D, d M Y H:i:s O';\n $postModTime = null;\n $isExpired = true;\n $httpLastUpdate = null;\n\n if (!isset( $_SERVER[$MOD_SINCE] )) { // Quit on no http last mod date\n return $isExpired;\n };\n\n $httpLastUpdate = DateTime::createFromFormat($DATE_FMT, $_SERVER[$MOD_SINCE]);\n if (!$httpLastUpdate) { // Quit on can't decode last mod date\n return $isExpired;\n }\n\n $post_id = get_queried_object_id(); // Get Post last modified date\n if( $post_id ) {\n $postModTime = new DateTime(get_the_modified_time('D, d M Y H:i:s', $post_id));\n };\n\n if ($postModTime) {\n // http last-mod-date is before post-list-mod-date or before min-upd-date\n $isExpired = ($httpLastUpdate &lt; $postModTime) || ($httpLastUpdate &lt; $MIN_UPD_DATE);\n };\n return $isExpired;\n}\n\nfunction send_on_not_expired_single( $wp_query ) { \n if ($_SERVER['REQUEST_METHOD']!=='GET') { // ignore for non-GET requests\n return $wp_query;\n }\n\n $use_modified_since_rule = handle_modified_since_header(); // conditionally set Last-Modified http header\n if ($use_modified_since_rule) {\n $is_expired = is_request_expired();\n if (!$is_expired) {\n wp_send_html(null, 304);\n };\n };\n return $wp_query;\n}\nadd_filter( 'parse_query', 'send_on_not_expired_single', 200);\n\n/**\n * Send an HTML response back to an html request.\n * patterned on the v4.9.8 WP codex wp_save_json\n * from: https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/functions.php#L3179\n *\n * @param mixed $response Variable (usually an array or object),\n * then print and die.\n * @param int $status_code The HTTP status code to output.\n */\nfunction wp_send_html( $response = null, $status_code = null ) {\n @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );\n if ( null !== $status_code ) {\n status_header( $status_code );\n }\n if ($response) {\n echo wp_json_encode( $response ); \n }\n die;\n};\n</code></pre>\n\n<p>As a final note, per some comments/suggestions, I did review some caching plug-in's. Although some of them do have very good 'last-modifed-date' checking/updating logic (which I don't) for when the site presentation is updated, the ones that I reviewed either specifically exclude logged in users from caching, or have significant limitations for logged in users which eliminate their usefulness for my focus.</p>\n" } ]
2018/09/24
[ "https://wordpress.stackexchange.com/questions/314966", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93209/" ]
I would like to write some arguments for my query and both need to be true. I am having trouble with the Syntax. 'meta\_key' => $campaign\_type, 'meta\_value' => $Campaign\_ID, **AND** 'meta\_key' => 'organisation', 'meta\_value' => $userOrg, Below is my query code: ``` $args = array ( 'meta_query' => array( 'relation' => 'AND', array( 'meta_key' => $campaign_type, 'meta_value' => $Campaign_ID, 'compare' => '=' ), array( 'meta_key' => 'organisation', 'meta_value' => $userOrg, 'compare' => '=' ) )); ``` Thank you.
You need to have a lot of traffic for naive protocol based optimizations to be effective, and even then it is not obvious that you can gain much even when it does kick in. Most people will be first time users of your site, and browser have only a limited space to store information about the last update time of all the pages a user visited. But even if you actually get such a request, how exactly do you know when was the last update? The best answer to that question that wordpress has is the publish time of the latest published post, which might not represent at all when a theme change, or any other setting change happened. But even for such a naive assumption, you still need to load wordpress and do at least two DB queries. You will probably get some improvement, but not as much as using an object cache or page cache in the first place. And in the real world, most of the slowness is because of the JS/CSS/media on the page, and if it is not cached (and unless you are facebook, it is unlikely t be cached), your page will still load slow even if the "last published" thing did work.
314,986
<p>As the title states i have tried it with the htaccess file to change the maximum upload size and nothing i have even created a php.ini file in the root of the wordpress folder and still nothing can some here please help me.</p>
[ { "answer_id": 314987, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 0, "selected": false, "text": "<p>Try to create <strong>.user.ini</strong> in root</p>\n\n<pre><code>upload_max_filesize = 500M\npost_max_size = 256M\nmemory_limit = 500M\nmax_execution_time = 300\nmax_input_vars = 500M\n</code></pre>\n\n<p>Hope this will help!</p>\n" }, { "answer_id": 314988, "author": "Adarsh", "author_id": 143452, "author_profile": "https://wordpress.stackexchange.com/users/143452", "pm_score": 0, "selected": false, "text": "<pre><code>@ini_set( 'upload_max_size' , '64M' );\n@ini_set( 'post_max_size', '64M');\n@ini_set( 'max_execution_time', '300' );\n</code></pre>\n\n<p>Add this in function.php i think this will works</p>\n" }, { "answer_id": 314992, "author": "djwayne1985", "author_id": 151167, "author_profile": "https://wordpress.stackexchange.com/users/151167", "pm_score": 0, "selected": false, "text": "<p>i have fixed the problem it was a setting within apache itself i had to change sorry if i have messed you about it wasn't intentional just happy to have it sorted now</p>\n" }, { "answer_id": 315122, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 1, "selected": false, "text": "<p>php.ini should be in the /wp-admin/ folder, not the root. Also, I've had success using a combination of the following in my /wp-admin/php.ini file AND a directive to increase the memory in my wp-config.php file, increased memory is needed when uploading larger files.</p>\n\n<p>Put something like this in your php.ini file (change values as you need to):</p>\n\n<pre><code> memory=512MB\n post_max_size=20MB\n upload_max_filesize=50MB\n</code></pre>\n\n<p>Then in your wp-config.php file, add something like this:</p>\n\n<pre><code> define('WP_MEMORY_LIMIT', '512M');\n</code></pre>\n\n<p>The upper memory limit doesn't need to be the same in both, but I find it works best when it is the same.</p>\n" } ]
2018/09/24
[ "https://wordpress.stackexchange.com/questions/314986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151167/" ]
As the title states i have tried it with the htaccess file to change the maximum upload size and nothing i have even created a php.ini file in the root of the wordpress folder and still nothing can some here please help me.
php.ini should be in the /wp-admin/ folder, not the root. Also, I've had success using a combination of the following in my /wp-admin/php.ini file AND a directive to increase the memory in my wp-config.php file, increased memory is needed when uploading larger files. Put something like this in your php.ini file (change values as you need to): ``` memory=512MB post_max_size=20MB upload_max_filesize=50MB ``` Then in your wp-config.php file, add something like this: ``` define('WP_MEMORY_LIMIT', '512M'); ``` The upper memory limit doesn't need to be the same in both, but I find it works best when it is the same.
314,993
<p>Due to some important hardware failure, the <code>wp_options</code> table of one of my WP sites became corrupted, but everything else is okay (WP files and other tables). Obviously the site does not work because of this, and I had no backups.</p> <p>What would be the best way to repair this? How can I create a fresh <code>wp_options</code> table for my WP version?</p>
[ { "answer_id": 314994, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Uh oh, that's an important table. You might have lost a bunch of options, but you can still repair the database. WordPress allows a repair mode, which you can repair the database.</p>\n\n<p>Open the <code>wp-config.php</code> file using FTP, and add this line before the <code>ABSPATH</code>:</p>\n\n<pre><code>define( 'WP_ALLOW_REPAIR', true );\n</code></pre>\n\n<p>now head over to :</p>\n\n<pre><code>http://yourdomain.com/wp-admin/maint/repair.php\n</code></pre>\n\n<p>Follow the steps to repair your broken database.</p>\n" }, { "answer_id": 315123, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 1, "selected": false, "text": "<p>Your last suggestion (question?) is the right way to go, especially since you've already dropped that table.</p>\n\n<p>Install a fresh version of WP into a new database (same version as your existing site), the export that table only from the new install and import it into your existing database.</p>\n\n<p>Then BE SURE to set the two options that are critical, which is the blog URL and home URL, while you're still in phpMyAdmin, all other options can be set via the /wp-admin/ back-end when you can access it. </p>\n" } ]
2018/09/24
[ "https://wordpress.stackexchange.com/questions/314993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151169/" ]
Due to some important hardware failure, the `wp_options` table of one of my WP sites became corrupted, but everything else is okay (WP files and other tables). Obviously the site does not work because of this, and I had no backups. What would be the best way to repair this? How can I create a fresh `wp_options` table for my WP version?
Uh oh, that's an important table. You might have lost a bunch of options, but you can still repair the database. WordPress allows a repair mode, which you can repair the database. Open the `wp-config.php` file using FTP, and add this line before the `ABSPATH`: ``` define( 'WP_ALLOW_REPAIR', true ); ``` now head over to : ``` http://yourdomain.com/wp-admin/maint/repair.php ``` Follow the steps to repair your broken database.
315,000
<p>I've searched everywhere on the internet and tried to code it myself I want to change the default "Select A Category" placeholder text to "Select A Sub Category" so far I have tried this but it's not working:</p> <p>function _category_dropdown_filter( $list_args ) { $list_args['show_option_none'] = __('Select A Sub Category'); return $list_args; } add_filter( 'woocommerce_product_categories_widget_arg' , '_category_dropdown_filter' );</p> <p>Also, I have even tried to edit this file here but I see no "Select A Category" woocommerce/includes/widgets/class-wc-widget-product-categories.php</p>
[ { "answer_id": 315002, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 0, "selected": false, "text": "<p>Try to using <code>apply_filters</code> in your functions.php</p>\n\n<pre><code>apply_filters( 'woocommerce_product_categories_widget_args','art_architecture_textbooks' );\nfunction art_architecture_textbooks( $cat_args ) {\n $cat_args['show_option_none'] = __('Art &amp; Architecture');\n return $cat_args;\n}\n</code></pre>\n\n<p>Learn more <strong><a href=\"https://siteorigin.com/thread/change-category-widget-default-text-select-a-category/\" rel=\"nofollow noreferrer\">https://siteorigin.com/thread/change-category-widget-default-text-select-a-category/</a></strong></p>\n" }, { "answer_id": 330436, "author": "MandyS", "author_id": 162358, "author_profile": "https://wordpress.stackexchange.com/users/162358", "pm_score": 2, "selected": false, "text": "<p>This worked for me:</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', function( $html, $args ) {\n if ( $args['taxonomy'] === 'product_cat' ) {\n $html = str_replace( '&lt;select', '&lt;select data-placeholder=\"New Placeholder\"', $html );\n }\n return $html;\n}, 10, 2);\n</code></pre>\n" } ]
2018/09/24
[ "https://wordpress.stackexchange.com/questions/315000", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151177/" ]
I've searched everywhere on the internet and tried to code it myself I want to change the default "Select A Category" placeholder text to "Select A Sub Category" so far I have tried this but it's not working: function \_category\_dropdown\_filter( $list\_args ) { $list\_args['show\_option\_none'] = \_\_('Select A Sub Category'); return $list\_args; } add\_filter( 'woocommerce\_product\_categories\_widget\_arg' , '\_category\_dropdown\_filter' ); Also, I have even tried to edit this file here but I see no "Select A Category" woocommerce/includes/widgets/class-wc-widget-product-categories.php
This worked for me: ``` add_filter( 'wp_dropdown_cats', function( $html, $args ) { if ( $args['taxonomy'] === 'product_cat' ) { $html = str_replace( '<select', '<select data-placeholder="New Placeholder"', $html ); } return $html; }, 10, 2); ```
315,067
<p>I have below code for contact form 7. Usually I use <code>autocomplete="off"</code> for html input field. However not able to figure out how to do the same for contact form 7 </p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-md-6"&gt; [text* FirstName placeholder "First Name"] &lt;/div&gt; &lt;div class="col-md-6"&gt; [text* LastName placeholder "Last Name"] &lt;/div&gt; &lt;div class="col-md-12"&gt; [email* EmailAddress placeholder "Email Address"] &lt;/div&gt; &lt;div class="col-md-12"&gt; [text* desc placeholder "Tell us a bit about yourself..."] &lt;/div&gt; &lt;div class="col-md-12"&gt; [submit "Submit"] &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 315083, "author": "Aravona", "author_id": 49852, "author_profile": "https://wordpress.stackexchange.com/users/49852", "pm_score": 3, "selected": false, "text": "<p>According to the question and answer from the developer placed here: <a href=\"https://wordpress.org/support/topic/autocomplete-off-3/\" rel=\"noreferrer\">https://wordpress.org/support/topic/autocomplete-off-3/</a></p>\n\n<p>You just need to add the <code>autocomplete:off</code> option to the shortcode:</p>\n\n<p><code>[email your-email autocomplete:off \"[email protected]\"]</code></p>\n\n<p>Though if the plugin has not been updated as stated in that question to use autocomplete:false Chrome may ignore it still. If it doesn't work yet you may need to raise support with the plugin author. Autocomplete was added to this plugin in version 4.5.</p>\n" }, { "answer_id": 342515, "author": "Arnis Juraga", "author_id": 91844, "author_profile": "https://wordpress.stackexchange.com/users/91844", "pm_score": 4, "selected": true, "text": "<p>Autocomplete tag in form settings does not work anymore (as today Contact Form 7 plugin version <code>5.1.3</code>.</p>\n<p>The only solution which worked for me was to add custom attributes thanks to <a href=\"https://stackoverflow.com/a/46316728/1720476\">https://stackoverflow.com/a/46316728/1720476</a>.</p>\n<p>E.g. if You have <code>FirstName</code> and <code>LastName</code> fields, where You want to disable autocomplete.</p>\n<p>Add this into <code>functions.php</code> file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );\nfunction imp_wpcf7_form_elements( $content ) {\n $str_pos = strpos( $content, 'name=&quot;FirstName&quot;' );\n if ($str_pos) {\n $content = substr_replace( $content, ' autocomplete=&quot;both&quot; autocomplete=&quot;off&quot; ', $str_pos, 0 ); \n }\n\n $str_pos = strpos( $content, 'name=&quot;LastName&quot;' );\n if ($str_pos) {\n $content = substr_replace( $content, ' autocomplete=&quot;both&quot; autocomplete=&quot;off&quot; ', $str_pos, 0 );\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 354260, "author": "abasteris", "author_id": 166788, "author_profile": "https://wordpress.stackexchange.com/users/166788", "pm_score": 2, "selected": false, "text": "<p>The suggested answer by Arnis works if you are using the same form throughout your whole site, however, it will inject text in forms which don't have all the fields targeted in your functions.php file.</p>\n\n<p>For a new suggested solution:</p>\n\n<p>Setting the input or textarea \"autocomplete\" attribute to a random variable that is not a standard value seems to do the trick as of December 2019 for Chrome, not sure why the native CF7 option to disable autocomplete hasn't been updated.</p>\n\n<p>You can define this attribute with a simple jQuery line like:</p>\n\n<pre><code>$(\"input.wpcf7-form-control, textarea.wpcf7-form-control\").attr(\"autocomplete\", \"negative\");\n</code></pre>\n\n<p>This targets the default class for CF7 fields.</p>\n\n<p>Edit: forgot to mention, this requires knowledge on where to add custom js scripts, most premium themes support a custom JS section or just add the line to your child theme's main js file.</p>\n" } ]
2018/09/25
[ "https://wordpress.stackexchange.com/questions/315067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122253/" ]
I have below code for contact form 7. Usually I use `autocomplete="off"` for html input field. However not able to figure out how to do the same for contact form 7 ``` <div class="row"> <div class="col-md-6"> [text* FirstName placeholder "First Name"] </div> <div class="col-md-6"> [text* LastName placeholder "Last Name"] </div> <div class="col-md-12"> [email* EmailAddress placeholder "Email Address"] </div> <div class="col-md-12"> [text* desc placeholder "Tell us a bit about yourself..."] </div> <div class="col-md-12"> [submit "Submit"] </div> </div> ```
Autocomplete tag in form settings does not work anymore (as today Contact Form 7 plugin version `5.1.3`. The only solution which worked for me was to add custom attributes thanks to <https://stackoverflow.com/a/46316728/1720476>. E.g. if You have `FirstName` and `LastName` fields, where You want to disable autocomplete. Add this into `functions.php` file: ```php add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' ); function imp_wpcf7_form_elements( $content ) { $str_pos = strpos( $content, 'name="FirstName"' ); if ($str_pos) { $content = substr_replace( $content, ' autocomplete="both" autocomplete="off" ', $str_pos, 0 ); } $str_pos = strpos( $content, 'name="LastName"' ); if ($str_pos) { $content = substr_replace( $content, ' autocomplete="both" autocomplete="off" ', $str_pos, 0 ); } return $content; } ```
315,072
<p>New Uploaded Code:</p> <pre><code>&lt;div class="col-sm-3 col-sm-pull-9 sidebar"&gt; &lt;div class="list-group products box"&gt; &lt;h4&gt;Product Range&lt;/h4&gt; &lt;?php $terms = get_the_terms( $post-&gt;ID, 'product_cat' ); foreach ( $terms as $term ){ $category_name = $term-&gt;name; $parent_category_id = $term-&gt;term_id; $categories=get_categories(array( 'parent' =&gt; $category_id )); $children = get_terms( 'product_cat', array( 'parent' =&gt; $parent_category_id, 'hide_empty' =&gt; false ) ); foreach( $children as $subcat ){ ?&gt; &lt;a href="&lt;?php get_term_link( $subcat-&gt;slug, 'product_cat' ); ?&gt;" class="list-group-item"&gt;&lt;?php echo $subcat-&gt;name; ?&gt;&lt;/a&gt; &lt;?php } } ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 315083, "author": "Aravona", "author_id": 49852, "author_profile": "https://wordpress.stackexchange.com/users/49852", "pm_score": 3, "selected": false, "text": "<p>According to the question and answer from the developer placed here: <a href=\"https://wordpress.org/support/topic/autocomplete-off-3/\" rel=\"noreferrer\">https://wordpress.org/support/topic/autocomplete-off-3/</a></p>\n\n<p>You just need to add the <code>autocomplete:off</code> option to the shortcode:</p>\n\n<p><code>[email your-email autocomplete:off \"[email protected]\"]</code></p>\n\n<p>Though if the plugin has not been updated as stated in that question to use autocomplete:false Chrome may ignore it still. If it doesn't work yet you may need to raise support with the plugin author. Autocomplete was added to this plugin in version 4.5.</p>\n" }, { "answer_id": 342515, "author": "Arnis Juraga", "author_id": 91844, "author_profile": "https://wordpress.stackexchange.com/users/91844", "pm_score": 4, "selected": true, "text": "<p>Autocomplete tag in form settings does not work anymore (as today Contact Form 7 plugin version <code>5.1.3</code>.</p>\n<p>The only solution which worked for me was to add custom attributes thanks to <a href=\"https://stackoverflow.com/a/46316728/1720476\">https://stackoverflow.com/a/46316728/1720476</a>.</p>\n<p>E.g. if You have <code>FirstName</code> and <code>LastName</code> fields, where You want to disable autocomplete.</p>\n<p>Add this into <code>functions.php</code> file:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );\nfunction imp_wpcf7_form_elements( $content ) {\n $str_pos = strpos( $content, 'name=&quot;FirstName&quot;' );\n if ($str_pos) {\n $content = substr_replace( $content, ' autocomplete=&quot;both&quot; autocomplete=&quot;off&quot; ', $str_pos, 0 ); \n }\n\n $str_pos = strpos( $content, 'name=&quot;LastName&quot;' );\n if ($str_pos) {\n $content = substr_replace( $content, ' autocomplete=&quot;both&quot; autocomplete=&quot;off&quot; ', $str_pos, 0 );\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 354260, "author": "abasteris", "author_id": 166788, "author_profile": "https://wordpress.stackexchange.com/users/166788", "pm_score": 2, "selected": false, "text": "<p>The suggested answer by Arnis works if you are using the same form throughout your whole site, however, it will inject text in forms which don't have all the fields targeted in your functions.php file.</p>\n\n<p>For a new suggested solution:</p>\n\n<p>Setting the input or textarea \"autocomplete\" attribute to a random variable that is not a standard value seems to do the trick as of December 2019 for Chrome, not sure why the native CF7 option to disable autocomplete hasn't been updated.</p>\n\n<p>You can define this attribute with a simple jQuery line like:</p>\n\n<pre><code>$(\"input.wpcf7-form-control, textarea.wpcf7-form-control\").attr(\"autocomplete\", \"negative\");\n</code></pre>\n\n<p>This targets the default class for CF7 fields.</p>\n\n<p>Edit: forgot to mention, this requires knowledge on where to add custom js scripts, most premium themes support a custom JS section or just add the line to your child theme's main js file.</p>\n" } ]
2018/09/25
[ "https://wordpress.stackexchange.com/questions/315072", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150429/" ]
New Uploaded Code: ``` <div class="col-sm-3 col-sm-pull-9 sidebar"> <div class="list-group products box"> <h4>Product Range</h4> <?php $terms = get_the_terms( $post->ID, 'product_cat' ); foreach ( $terms as $term ){ $category_name = $term->name; $parent_category_id = $term->term_id; $categories=get_categories(array( 'parent' => $category_id )); $children = get_terms( 'product_cat', array( 'parent' => $parent_category_id, 'hide_empty' => false ) ); foreach( $children as $subcat ){ ?> <a href="<?php get_term_link( $subcat->slug, 'product_cat' ); ?>" class="list-group-item"><?php echo $subcat->name; ?></a> <?php } } ?> </div> ```
Autocomplete tag in form settings does not work anymore (as today Contact Form 7 plugin version `5.1.3`. The only solution which worked for me was to add custom attributes thanks to <https://stackoverflow.com/a/46316728/1720476>. E.g. if You have `FirstName` and `LastName` fields, where You want to disable autocomplete. Add this into `functions.php` file: ```php add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' ); function imp_wpcf7_form_elements( $content ) { $str_pos = strpos( $content, 'name="FirstName"' ); if ($str_pos) { $content = substr_replace( $content, ' autocomplete="both" autocomplete="off" ', $str_pos, 0 ); } $str_pos = strpos( $content, 'name="LastName"' ); if ($str_pos) { $content = substr_replace( $content, ' autocomplete="both" autocomplete="off" ', $str_pos, 0 ); } return $content; } ```
315,086
<p>I've searched a lot to find out how I can add a custom row inside the total costs in my WooCommerce shop and checked out the hooks but can't find the solution. This is what I've tried:</p> <pre><code>add_filter( 'woocommerce_get_order_item_totals', 'bbloomer_add_recurring_row_email', 10, 2 ); function bbloomer_add_recurring_row_email( $total_rows, $myorder_obj ) { $total_rows['recurr_not'] = array( 'label' =&gt; __( 'Rec:', 'woocommerce' ), 'value' =&gt; 'blabla' ); return $total_rows; } </code></pre> <p>But this only adds the row to the total rows in the recipe email. I need to change my total row, add a new row with a name and a value calculated from the cart subtotal field. </p> <p>This is how I need it:</p> <p><a href="https://i.stack.imgur.com/9lt4S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9lt4S.png" alt="enter image description here"></a></p> <p>Do you now how to to this? I have no plan. Thanks for your help!</p>
[ { "answer_id": 315087, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": -1, "selected": false, "text": "<p>Try This:</p>\n\n<pre><code> // Add a custom field before single add to cart\nadd_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );\nfunction custom_product_price_field(){\n echo '&lt;div class=\"custom-text text\"&gt;\n &lt;p&gt;Extra Charge ('.get_woocommerce_currency_symbol().'):&lt;/p&gt;\n &lt;input type=\"text\" name=\"custom_price\" value=\"\" placeholder=\"e.g. 10\" title=\"Custom Text\" class=\"custom_price text_custom text\"&gt;\n &lt;/div&gt;';\n}\n\n// Get custom field value, calculate new item price, save it as custom cart item data\nadd_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );\nfunction add_custom_field_data( $cart_item_data, $product_id ){\n if (! isset($_POST['custom_price']))\n return $cart_item_data;\n\n $custom_price = (float) sanitize_text_field( $_POST['custom_price'] );\n if( empty($custom_price) )\n return $cart_item_data;\n\n $product = wc_get_product($product_id); // The WC_Product Object\n $base_price = (float) $product-&gt;get_regular_price(); // Product reg price\n\n // New price calculation\n $new_price = $base_price + $custom_price;\n\n // Set the custom amount in cart object\n $cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;\n $cart_item_data['custom_data']['new_price'] = (float) $new_price;\n $cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() ); // Make each item unique\n\n return $cart_item_data;\n}\n\n// Set the new calculated cart item price\nadd_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );\nfunction extra_price_add_custom_price( $cart ) {\n if ( is_admin() &amp;&amp; !defined('DOING_AJAX') )\n return;\n\n foreach ( $cart-&gt;get_cart() as $cart_item ) {\n if( isset($cart_item['custom_data']['new_price']) )\n $cart_item['data']-&gt;set_price( (float) $cart_item['custom_data']['new_price'] );\n }\n}\n\n// Display cart item custom price details\nadd_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3 );\nfunction display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){\n if( isset($cart_item['custom_data']['extra_charge']) ) {\n $product = $cart_item['data'];\n $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' =&gt; $product-&gt;get_regular_price() ) ) );\n $product_price .= '&lt;br&gt;' . wc_price( $cart_item['custom_data']['extra_charge'] ).'&amp;nbsp;';\n $product_price .= __(\"Extra Charge\", \"woocommerce\" );\n }\n return $product_price;\n}\n</code></pre>\n\n<p>Code goes in <code>function.php</code> file\n<a href=\"https://i.stack.imgur.com/uz9a5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uz9a5.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 368205, "author": "Prateek Tyagi", "author_id": 189340, "author_profile": "https://wordpress.stackexchange.com/users/189340", "pm_score": 1, "selected": false, "text": "<p>Its too late but it can still help to others who are looking for the same :</p>\n\n<p>Copy \"plugins\\woocommerce\\templates\\cart\\cart-totals.php\" to <br>\n\"your-theme\\woocommerce\\templates\\cart\\cart-totals.php\"</p>\n\n<p>Open \"your-theme\\woocommerce\\templates\\cart\\cart-totals.php\" and add the following line inside the table tag</p>\n\n<pre><code>&lt;?php do_action( 'woocommerce_cart_totals_custom_text' ); ?&gt;\n</code></pre>\n\n<p>Then open your function.php and add the following:</p>\n\n<pre><code>add_action( 'woocommerce_cart_totals_custom_text', 'action_woocommerce_cart_totals_before_shipping', 10, 0 ); \n\nfunction action_woocommerce_cart_totals_before_shipping( ) {\n echo \"&lt;tr class='cart-subtotal'&gt;&lt;th&gt;Title&lt;/th&gt;&lt;td&gt;Text&lt;/td&gt;&lt;/tr&gt;\";\n}\n</code></pre>\n\n<p>Here is the result</p>\n\n<p><a href=\"https://i.stack.imgur.com/QxcMr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QxcMr.png\" alt=\"enter image description here\"></a></p>\n" } ]
2018/09/25
[ "https://wordpress.stackexchange.com/questions/315086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151233/" ]
I've searched a lot to find out how I can add a custom row inside the total costs in my WooCommerce shop and checked out the hooks but can't find the solution. This is what I've tried: ``` add_filter( 'woocommerce_get_order_item_totals', 'bbloomer_add_recurring_row_email', 10, 2 ); function bbloomer_add_recurring_row_email( $total_rows, $myorder_obj ) { $total_rows['recurr_not'] = array( 'label' => __( 'Rec:', 'woocommerce' ), 'value' => 'blabla' ); return $total_rows; } ``` But this only adds the row to the total rows in the recipe email. I need to change my total row, add a new row with a name and a value calculated from the cart subtotal field. This is how I need it: [![enter image description here](https://i.stack.imgur.com/9lt4S.png)](https://i.stack.imgur.com/9lt4S.png) Do you now how to to this? I have no plan. Thanks for your help!
Its too late but it can still help to others who are looking for the same : Copy "plugins\woocommerce\templates\cart\cart-totals.php" to "your-theme\woocommerce\templates\cart\cart-totals.php" Open "your-theme\woocommerce\templates\cart\cart-totals.php" and add the following line inside the table tag ``` <?php do_action( 'woocommerce_cart_totals_custom_text' ); ?> ``` Then open your function.php and add the following: ``` add_action( 'woocommerce_cart_totals_custom_text', 'action_woocommerce_cart_totals_before_shipping', 10, 0 ); function action_woocommerce_cart_totals_before_shipping( ) { echo "<tr class='cart-subtotal'><th>Title</th><td>Text</td></tr>"; } ``` Here is the result [![enter image description here](https://i.stack.imgur.com/QxcMr.png)](https://i.stack.imgur.com/QxcMr.png)
315,146
<p>I'm trying to make a loop that does the following,</p> <p>The first post is a different column size, and every post under that is a col 6.</p> <p>I'm using bootstrap. this image shows what i'm trying to accomplish. So each NEW posts shows at the top in the full column and everytime you create a new post it pushes down into the 1/2 columns.</p> <p><a href="https://i.stack.imgur.com/jLCBQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jLCBQ.png" alt="enter image description here"></a></p>
[ { "answer_id": 315087, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": -1, "selected": false, "text": "<p>Try This:</p>\n\n<pre><code> // Add a custom field before single add to cart\nadd_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );\nfunction custom_product_price_field(){\n echo '&lt;div class=\"custom-text text\"&gt;\n &lt;p&gt;Extra Charge ('.get_woocommerce_currency_symbol().'):&lt;/p&gt;\n &lt;input type=\"text\" name=\"custom_price\" value=\"\" placeholder=\"e.g. 10\" title=\"Custom Text\" class=\"custom_price text_custom text\"&gt;\n &lt;/div&gt;';\n}\n\n// Get custom field value, calculate new item price, save it as custom cart item data\nadd_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );\nfunction add_custom_field_data( $cart_item_data, $product_id ){\n if (! isset($_POST['custom_price']))\n return $cart_item_data;\n\n $custom_price = (float) sanitize_text_field( $_POST['custom_price'] );\n if( empty($custom_price) )\n return $cart_item_data;\n\n $product = wc_get_product($product_id); // The WC_Product Object\n $base_price = (float) $product-&gt;get_regular_price(); // Product reg price\n\n // New price calculation\n $new_price = $base_price + $custom_price;\n\n // Set the custom amount in cart object\n $cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;\n $cart_item_data['custom_data']['new_price'] = (float) $new_price;\n $cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() ); // Make each item unique\n\n return $cart_item_data;\n}\n\n// Set the new calculated cart item price\nadd_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );\nfunction extra_price_add_custom_price( $cart ) {\n if ( is_admin() &amp;&amp; !defined('DOING_AJAX') )\n return;\n\n foreach ( $cart-&gt;get_cart() as $cart_item ) {\n if( isset($cart_item['custom_data']['new_price']) )\n $cart_item['data']-&gt;set_price( (float) $cart_item['custom_data']['new_price'] );\n }\n}\n\n// Display cart item custom price details\nadd_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3 );\nfunction display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){\n if( isset($cart_item['custom_data']['extra_charge']) ) {\n $product = $cart_item['data'];\n $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' =&gt; $product-&gt;get_regular_price() ) ) );\n $product_price .= '&lt;br&gt;' . wc_price( $cart_item['custom_data']['extra_charge'] ).'&amp;nbsp;';\n $product_price .= __(\"Extra Charge\", \"woocommerce\" );\n }\n return $product_price;\n}\n</code></pre>\n\n<p>Code goes in <code>function.php</code> file\n<a href=\"https://i.stack.imgur.com/uz9a5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uz9a5.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 368205, "author": "Prateek Tyagi", "author_id": 189340, "author_profile": "https://wordpress.stackexchange.com/users/189340", "pm_score": 1, "selected": false, "text": "<p>Its too late but it can still help to others who are looking for the same :</p>\n\n<p>Copy \"plugins\\woocommerce\\templates\\cart\\cart-totals.php\" to <br>\n\"your-theme\\woocommerce\\templates\\cart\\cart-totals.php\"</p>\n\n<p>Open \"your-theme\\woocommerce\\templates\\cart\\cart-totals.php\" and add the following line inside the table tag</p>\n\n<pre><code>&lt;?php do_action( 'woocommerce_cart_totals_custom_text' ); ?&gt;\n</code></pre>\n\n<p>Then open your function.php and add the following:</p>\n\n<pre><code>add_action( 'woocommerce_cart_totals_custom_text', 'action_woocommerce_cart_totals_before_shipping', 10, 0 ); \n\nfunction action_woocommerce_cart_totals_before_shipping( ) {\n echo \"&lt;tr class='cart-subtotal'&gt;&lt;th&gt;Title&lt;/th&gt;&lt;td&gt;Text&lt;/td&gt;&lt;/tr&gt;\";\n}\n</code></pre>\n\n<p>Here is the result</p>\n\n<p><a href=\"https://i.stack.imgur.com/QxcMr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QxcMr.png\" alt=\"enter image description here\"></a></p>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315146", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151273/" ]
I'm trying to make a loop that does the following, The first post is a different column size, and every post under that is a col 6. I'm using bootstrap. this image shows what i'm trying to accomplish. So each NEW posts shows at the top in the full column and everytime you create a new post it pushes down into the 1/2 columns. [![enter image description here](https://i.stack.imgur.com/jLCBQ.png)](https://i.stack.imgur.com/jLCBQ.png)
Its too late but it can still help to others who are looking for the same : Copy "plugins\woocommerce\templates\cart\cart-totals.php" to "your-theme\woocommerce\templates\cart\cart-totals.php" Open "your-theme\woocommerce\templates\cart\cart-totals.php" and add the following line inside the table tag ``` <?php do_action( 'woocommerce_cart_totals_custom_text' ); ?> ``` Then open your function.php and add the following: ``` add_action( 'woocommerce_cart_totals_custom_text', 'action_woocommerce_cart_totals_before_shipping', 10, 0 ); function action_woocommerce_cart_totals_before_shipping( ) { echo "<tr class='cart-subtotal'><th>Title</th><td>Text</td></tr>"; } ``` Here is the result [![enter image description here](https://i.stack.imgur.com/QxcMr.png)](https://i.stack.imgur.com/QxcMr.png)
315,156
<p>I'm trying to add a dropdown to Wordpress core blocks to select a data attribute that will be added to the front-end (e.g. data-attr="value-from-dropdown").</p> <p>I think the solution is to add a custom attribute to the core blocks, set it in the back-end and pass it to the front-end, but I can't for the life of me figure out how to add a new attribute to a core block. This here is the closest I've gotten, but this just lets me create a dropdown, running props.setAttribute() inside doesn't work.</p> <p><a href="https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#editor-blockedit" rel="noreferrer">https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#editor-blockedit</a></p> <p>Is there anything I can do, or is the functionality just not there yet?</p>
[ { "answer_id": 315520, "author": "Ashiquzzaman Kiron", "author_id": 78505, "author_profile": "https://wordpress.stackexchange.com/users/78505", "pm_score": 2, "selected": false, "text": "<p>First inside the edit function declare a variable with your dropdown option -</p>\n\n<pre><code>const linkOptions = [\n { value: 'small', label: __( 'Small' ) },\n { value: 'normal', label: __( 'Normal' ) },\n { value: 'medium', label: __( 'Medium' ) },\n { value: 'large', label: __( 'Large' ) },\n ];\n</code></pre>\n\n<p>I'm assuming you will be showing the dropdown option in the Sidebar panel. Here's the code for panelbody and how to get the dropdown value -</p>\n\n<pre><code>&lt;PanelBody&gt;\n &lt;SelectControl\n label={ __( 'Size' ) }\n value={ size }\n options={ linkOptions.map( ({ value, label }) =&gt; ( {\n value: value,\n label: label,\n } ) ) }\n onChange={ ( newSize ) =&gt; { setAttributes( { size: newSize } ) } }\n /&gt;\n&lt;/PanelBody&gt;\n</code></pre>\n\n<p>This will show a dropdown panel in the Inspector area, notice I'm using (ES6)Map function to iterate over the values and corresponding labels. Now, comes the RichText Component where you call the HTML nodes -</p>\n\n<pre><code>&lt;RichText\n tagName={ 'span' }\n placeholder={ __( 'Enter Text' ) }\n value={ text }\n onChange={ (text) =&gt; setAttributes( { text: text } ) }\n formattingControls={ [ 'bold', 'italic', 'strikethrough' ] }\n className={`button-${size}`} /*ES6 Template Literals*/\n isSelected={ isSelected }\n keepPlaceholderOnFocus\n/&gt;\n</code></pre>\n\n<p>Notice, Depending upon the dropdown option. Button size gets attached to the HTML node classname. Now in the editor stylesheet, Add couple of css class and properties -</p>\n\n<pre><code>button-small\nbutton-normal\nbutton-medium\nbutton-large\n</code></pre>\n\n<p>For the save function -</p>\n\n<pre><code>const save = ( props ) =&gt; {\n\n const { size } = props.attributes;\n\n\n return (\n &lt;div className={ `ubutton-${size}` }&gt;\n\n &lt;/div&gt;\n );\n}\n</code></pre>\n" }, { "answer_id": 339151, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 3, "selected": false, "text": "<p>You can add a custom attribute to any registered block by using the <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-registerblocktype\" rel=\"noreferrer\"><code>blocks.registerBlockType</code></a> filter. </p>\n\n<pre><code>/**\n * Filter the attributes for all blocks to add custom ones\n *\n * Name can be used to only add the new attribute to a certain block.\n *\n * @param settings\n * @param name\n * @returns {*}\n */\nfunction addCustomAttributes( settings, name ) {\n if ( settings.attributes ) {\n\n settings.attributes.customAttribute = {\n type: 'string',\n default: ''\n };\n\n settings.attributes.anotherCustomAttribute = {\n type: 'boolean',\n default: false\n };\n }\n return settings;\n}\n\naddFilter( 'blocks.registerBlockType', 'namespace/filterBlockAttributes', addCustomAttributes );\n</code></pre>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151276/" ]
I'm trying to add a dropdown to Wordpress core blocks to select a data attribute that will be added to the front-end (e.g. data-attr="value-from-dropdown"). I think the solution is to add a custom attribute to the core blocks, set it in the back-end and pass it to the front-end, but I can't for the life of me figure out how to add a new attribute to a core block. This here is the closest I've gotten, but this just lets me create a dropdown, running props.setAttribute() inside doesn't work. <https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#editor-blockedit> Is there anything I can do, or is the functionality just not there yet?
You can add a custom attribute to any registered block by using the [`blocks.registerBlockType`](https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-registerblocktype) filter. ``` /** * Filter the attributes for all blocks to add custom ones * * Name can be used to only add the new attribute to a certain block. * * @param settings * @param name * @returns {*} */ function addCustomAttributes( settings, name ) { if ( settings.attributes ) { settings.attributes.customAttribute = { type: 'string', default: '' }; settings.attributes.anotherCustomAttribute = { type: 'boolean', default: false }; } return settings; } addFilter( 'blocks.registerBlockType', 'namespace/filterBlockAttributes', addCustomAttributes ); ```
315,160
<p>I'm developing a wordpress plugin for a project. I'm expected to manage other plugins in this plugin. For example, I will be able to install Akismet over my plugin. I have done things like install, activating, deactivating. But I could not delete the plugin.</p> <p>I can also delete direct attachment files, but I don't want to. I should use as many wordpress functions as possible.</p> <pre><code>delete_plugins('litespeed-cache/litespeed-cache.php') </code></pre> <p>This function does not work. I tried to integrate this function, but it was very complicated. Can you help me?</p> <p><strong>--EDİT--</strong></p> <p>I'm sorry, I didn't pay attention. There is another problem right now. I wrote a new plugin and it worked fine when I added the following code.</p> <pre><code>register_activation_hook( __FILE__, 'index' ); function index() { delete_plugins( [ 'litespeed-cache/litespeed-cache.php', ] ); } </code></pre> <p>But it didn't work on my own plugin.</p> <p><code> add_action('exampleUninstallPlugin','exampleUninstallPlugin'); function exampleUninstallPlugin($plugins){ delete_plugins($plugins); } add_action( 'rest_api_init', 'customTestFunction' ); function customTestFunction() { register_rest_route( 'turhost/rest', '/api', array( 'methods' => 'POST', 'callback' => 'show_fields' ) ); } function show_fields( $request ) { $parameters = json_decode( base64_decode( $request->get_param( 'data' ) ), true ); if ( $parameters['action'] == "uninstallInstalledPlugin" ) { do_action('turhostUninstallPlugin',[ 'litespeed-cache/litespeed-cache.php' ]); } } </code></p>
[ { "answer_id": 315520, "author": "Ashiquzzaman Kiron", "author_id": 78505, "author_profile": "https://wordpress.stackexchange.com/users/78505", "pm_score": 2, "selected": false, "text": "<p>First inside the edit function declare a variable with your dropdown option -</p>\n\n<pre><code>const linkOptions = [\n { value: 'small', label: __( 'Small' ) },\n { value: 'normal', label: __( 'Normal' ) },\n { value: 'medium', label: __( 'Medium' ) },\n { value: 'large', label: __( 'Large' ) },\n ];\n</code></pre>\n\n<p>I'm assuming you will be showing the dropdown option in the Sidebar panel. Here's the code for panelbody and how to get the dropdown value -</p>\n\n<pre><code>&lt;PanelBody&gt;\n &lt;SelectControl\n label={ __( 'Size' ) }\n value={ size }\n options={ linkOptions.map( ({ value, label }) =&gt; ( {\n value: value,\n label: label,\n } ) ) }\n onChange={ ( newSize ) =&gt; { setAttributes( { size: newSize } ) } }\n /&gt;\n&lt;/PanelBody&gt;\n</code></pre>\n\n<p>This will show a dropdown panel in the Inspector area, notice I'm using (ES6)Map function to iterate over the values and corresponding labels. Now, comes the RichText Component where you call the HTML nodes -</p>\n\n<pre><code>&lt;RichText\n tagName={ 'span' }\n placeholder={ __( 'Enter Text' ) }\n value={ text }\n onChange={ (text) =&gt; setAttributes( { text: text } ) }\n formattingControls={ [ 'bold', 'italic', 'strikethrough' ] }\n className={`button-${size}`} /*ES6 Template Literals*/\n isSelected={ isSelected }\n keepPlaceholderOnFocus\n/&gt;\n</code></pre>\n\n<p>Notice, Depending upon the dropdown option. Button size gets attached to the HTML node classname. Now in the editor stylesheet, Add couple of css class and properties -</p>\n\n<pre><code>button-small\nbutton-normal\nbutton-medium\nbutton-large\n</code></pre>\n\n<p>For the save function -</p>\n\n<pre><code>const save = ( props ) =&gt; {\n\n const { size } = props.attributes;\n\n\n return (\n &lt;div className={ `ubutton-${size}` }&gt;\n\n &lt;/div&gt;\n );\n}\n</code></pre>\n" }, { "answer_id": 339151, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 3, "selected": false, "text": "<p>You can add a custom attribute to any registered block by using the <a href=\"https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-registerblocktype\" rel=\"noreferrer\"><code>blocks.registerBlockType</code></a> filter. </p>\n\n<pre><code>/**\n * Filter the attributes for all blocks to add custom ones\n *\n * Name can be used to only add the new attribute to a certain block.\n *\n * @param settings\n * @param name\n * @returns {*}\n */\nfunction addCustomAttributes( settings, name ) {\n if ( settings.attributes ) {\n\n settings.attributes.customAttribute = {\n type: 'string',\n default: ''\n };\n\n settings.attributes.anotherCustomAttribute = {\n type: 'boolean',\n default: false\n };\n }\n return settings;\n}\n\naddFilter( 'blocks.registerBlockType', 'namespace/filterBlockAttributes', addCustomAttributes );\n</code></pre>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151283/" ]
I'm developing a wordpress plugin for a project. I'm expected to manage other plugins in this plugin. For example, I will be able to install Akismet over my plugin. I have done things like install, activating, deactivating. But I could not delete the plugin. I can also delete direct attachment files, but I don't want to. I should use as many wordpress functions as possible. ``` delete_plugins('litespeed-cache/litespeed-cache.php') ``` This function does not work. I tried to integrate this function, but it was very complicated. Can you help me? **--EDİT--** I'm sorry, I didn't pay attention. There is another problem right now. I wrote a new plugin and it worked fine when I added the following code. ``` register_activation_hook( __FILE__, 'index' ); function index() { delete_plugins( [ 'litespeed-cache/litespeed-cache.php', ] ); } ``` But it didn't work on my own plugin. `add_action('exampleUninstallPlugin','exampleUninstallPlugin'); function exampleUninstallPlugin($plugins){ delete_plugins($plugins); } add_action( 'rest_api_init', 'customTestFunction' ); function customTestFunction() { register_rest_route( 'turhost/rest', '/api', array( 'methods' => 'POST', 'callback' => 'show_fields' ) ); } function show_fields( $request ) { $parameters = json_decode( base64_decode( $request->get_param( 'data' ) ), true ); if ( $parameters['action'] == "uninstallInstalledPlugin" ) { do_action('turhostUninstallPlugin',[ 'litespeed-cache/litespeed-cache.php' ]); } }`
You can add a custom attribute to any registered block by using the [`blocks.registerBlockType`](https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-registerblocktype) filter. ``` /** * Filter the attributes for all blocks to add custom ones * * Name can be used to only add the new attribute to a certain block. * * @param settings * @param name * @returns {*} */ function addCustomAttributes( settings, name ) { if ( settings.attributes ) { settings.attributes.customAttribute = { type: 'string', default: '' }; settings.attributes.anotherCustomAttribute = { type: 'boolean', default: false }; } return settings; } addFilter( 'blocks.registerBlockType', 'namespace/filterBlockAttributes', addCustomAttributes ); ```
315,164
<p>I have added a custom metabox that holds string from a <strong>textarea</strong> in database. Now if I just simply echo the meta box like this:</p> <pre><code>$post_meta = get_post_meta($pid); $answer = $post_meta["answer"][0]; echo $answer; </code></pre> <p>the html tags would be escaped and the text would appear like this:</p> <pre><code>blah blah blah &lt;ul&gt;&lt;li&gt;blah blah&lt;/li&gt;&lt;li&gt;blah&lt;/li&gt;&lt;/ul&gt; </code></pre> <p>As you see the html tags get escaped and they appear as string so I use php like this:</p> <pre><code>$answer = html_entity_decode($answer); </code></pre> <p>Now the html tags work as they are expected but there remains one problem. In order to get the line breaks from the database I add another line like this:</p> <pre><code> $answer = nl2br($answer); </code></pre> <p>which solves the problem with line breaks but add a new line break between each li tags. </p> <p>Any idea how to resolve this? I need line breaks but at the same time would want to avoid adding a line break between li tags.</p> <p><strong>UPDATE</strong>: for the moment I added this line of php after nl2br and I got the result</p> <pre><code> $answer = preg_replace("!&lt;/li&gt;[\s\S]{1,100}?&lt;!", "&lt;/li&gt;&lt;", $answer); </code></pre> <p>But I don't think this is the right way to go.</p>
[ { "answer_id": 315169, "author": "Adnan", "author_id": 90281, "author_profile": "https://wordpress.stackexchange.com/users/90281", "pm_score": -1, "selected": false, "text": "<p>Why don't you use <code>&lt;?php esc_textarea( $answer ); ?&gt;</code> </p>\n" }, { "answer_id": 315197, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p>To add line-breaks inside <code>&lt;textarea&gt;</code> (but not on front-end output), use this inside <code>textarea</code>:</p>\n\n<pre><code>echo str_replace('&lt;/li&gt;',\"&lt;/li&gt;\\r\\n\", $answer);\n</code></pre>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144876/" ]
I have added a custom metabox that holds string from a **textarea** in database. Now if I just simply echo the meta box like this: ``` $post_meta = get_post_meta($pid); $answer = $post_meta["answer"][0]; echo $answer; ``` the html tags would be escaped and the text would appear like this: ``` blah blah blah <ul><li>blah blah</li><li>blah</li></ul> ``` As you see the html tags get escaped and they appear as string so I use php like this: ``` $answer = html_entity_decode($answer); ``` Now the html tags work as they are expected but there remains one problem. In order to get the line breaks from the database I add another line like this: ``` $answer = nl2br($answer); ``` which solves the problem with line breaks but add a new line break between each li tags. Any idea how to resolve this? I need line breaks but at the same time would want to avoid adding a line break between li tags. **UPDATE**: for the moment I added this line of php after nl2br and I got the result ``` $answer = preg_replace("!</li>[\s\S]{1,100}?<!", "</li><", $answer); ``` But I don't think this is the right way to go.
To add line-breaks inside `<textarea>` (but not on front-end output), use this inside `textarea`: ``` echo str_replace('</li>',"</li>\r\n", $answer); ```
315,176
<p>I need to capture the current page id, execute some conditional script in footer, in my own plugin function hooks to <code>wp_footer</code>.</p> <p>Here is my plugin code, but page id returning wrong value?</p> <pre><code>&lt;?php /* Plugin Name: My Plugin Author: GS Version: 1.1 */ Function footer_page_id() { global $post; echo '&lt;div&gt; page_id:'.$post-&gt;ID.'&lt;/div&gt;';// output wrong value global $wp_query; echo 'page_id:'.get_the_ID();// output wrong value echo 'post_id:'.$wp_query-&gt;post-&gt;ID; // output wrong value echo 'page_id:'.$wp_query-&gt;get_queried_object_id(); // output always 0 echo'&lt;/br&gt;';exit; } add_action('wp_footer', ' footer_page_id '); ?&gt; </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 315169, "author": "Adnan", "author_id": 90281, "author_profile": "https://wordpress.stackexchange.com/users/90281", "pm_score": -1, "selected": false, "text": "<p>Why don't you use <code>&lt;?php esc_textarea( $answer ); ?&gt;</code> </p>\n" }, { "answer_id": 315197, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p>To add line-breaks inside <code>&lt;textarea&gt;</code> (but not on front-end output), use this inside <code>textarea</code>:</p>\n\n<pre><code>echo str_replace('&lt;/li&gt;',\"&lt;/li&gt;\\r\\n\", $answer);\n</code></pre>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125604/" ]
I need to capture the current page id, execute some conditional script in footer, in my own plugin function hooks to `wp_footer`. Here is my plugin code, but page id returning wrong value? ``` <?php /* Plugin Name: My Plugin Author: GS Version: 1.1 */ Function footer_page_id() { global $post; echo '<div> page_id:'.$post->ID.'</div>';// output wrong value global $wp_query; echo 'page_id:'.get_the_ID();// output wrong value echo 'post_id:'.$wp_query->post->ID; // output wrong value echo 'page_id:'.$wp_query->get_queried_object_id(); // output always 0 echo'</br>';exit; } add_action('wp_footer', ' footer_page_id '); ?> ``` Thanks in advance.
To add line-breaks inside `<textarea>` (but not on front-end output), use this inside `textarea`: ``` echo str_replace('</li>',"</li>\r\n", $answer); ```
315,187
<p>I am having this weird problem. Everytime I save a draft, the sidebar's black area appears and overlaps the editor making the editor unusable. It also attempts to save the draft repetitively and the only way to get out of it is to refresh the page. Kindly refer to the following image. <a href="https://i.stack.imgur.com/ZaShS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZaShS.png" alt="inspecting it revealed nothing odd though"></a></p> <p>Anyone knows how to fix this? </p>
[ { "answer_id": 315282, "author": "Mubashar Aftab", "author_id": 27507, "author_profile": "https://wordpress.stackexchange.com/users/27507", "pm_score": 0, "selected": false, "text": "<p>Okay, I found out! It was caused by WP Native Articles' Premium plug-in. I'm now talking to the developer and if there is anything concrete, I will update here.</p>\n" }, { "answer_id": 315409, "author": "OzTheGreat", "author_id": 76899, "author_profile": "https://wordpress.stackexchange.com/users/76899", "pm_score": 2, "selected": true, "text": "<p>author of WP Native Articles here. This is normally a problem with other plugins incorrectly messing around with tag incorrectly and preventing it from setting the correct URL. If you save this code below as a separate file, upload it as a plugin and activate it it should fix it.</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: WPNA Editor Fix\n * Description: Fix the base URL meta field that other plugins break.\n * Author: OzTheGreat (WPArtisan)\n * Author URI: https://wpartisan.me\n * Version: 1.0.1\n * Plugin URI: https://wp-native-articles.com\n *\n * @package wpna-editor-fix\n */\n\nadd_action( 'admin_footer-post.php', 'wpna_custom_fix_base_url' );\nadd_action( 'admin_footer-post-new.php', 'wpna_custom_fix_base_url' );\n\nfunction wpna_custom_fix_base_url(){\n ?&gt;\n &lt;script&gt;\n if ( window.history.replaceState ) {\n var bases = document.getElementsByTagName('base');\n if (bases.length &gt; 0) {\n bases[0].href = document.getElementById( 'wp-admin-canonical' ).href + window.location.hash;\n }\n }\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315187", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27507/" ]
I am having this weird problem. Everytime I save a draft, the sidebar's black area appears and overlaps the editor making the editor unusable. It also attempts to save the draft repetitively and the only way to get out of it is to refresh the page. Kindly refer to the following image. [![inspecting it revealed nothing odd though](https://i.stack.imgur.com/ZaShS.png)](https://i.stack.imgur.com/ZaShS.png) Anyone knows how to fix this?
author of WP Native Articles here. This is normally a problem with other plugins incorrectly messing around with tag incorrectly and preventing it from setting the correct URL. If you save this code below as a separate file, upload it as a plugin and activate it it should fix it. ``` <?php /** * Plugin Name: WPNA Editor Fix * Description: Fix the base URL meta field that other plugins break. * Author: OzTheGreat (WPArtisan) * Author URI: https://wpartisan.me * Version: 1.0.1 * Plugin URI: https://wp-native-articles.com * * @package wpna-editor-fix */ add_action( 'admin_footer-post.php', 'wpna_custom_fix_base_url' ); add_action( 'admin_footer-post-new.php', 'wpna_custom_fix_base_url' ); function wpna_custom_fix_base_url(){ ?> <script> if ( window.history.replaceState ) { var bases = document.getElementsByTagName('base'); if (bases.length > 0) { bases[0].href = document.getElementById( 'wp-admin-canonical' ).href + window.location.hash; } } </script> <?php } ```
315,192
<p>I need a function that replaces the price in WooCommerce with "Request a quote". On my site's homepage I just need the text, but on the product page (which is a custom product from my travel theme) I need it to be a button.</p> <p>How can I have 2 functions, one that only works on Home and the other one that works in the rest of the site?</p> <p>In functions.php, something like:</p> <p><strong>IF IS_HOME:</strong></p> <pre><code>add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); function custom_call_for_price() { return 'Request a quote'; } </code></pre> <p><strong>AND IF IS_NOT_HOME:</strong></p> <pre><code>add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); function custom_call_for_price() { $html .= '&lt;a href="#"&gt;&lt;input value="Request a quote" type="submit"&gt;&lt;/a&gt;'; return $html; } </code></pre> <p>Can it be done? Thanks!</p>
[ { "answer_id": 315196, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 2, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>function your_function() \n{\n if ( is_front_page() ) {\n $output = ...\n }\n else{\n $output = ...\n }\n return $output;\n}\n</code></pre>\n\n<p>p.s. It's not needed to use <code>is_home()</code>. Whoever needs the technical details, see <a href=\"https://developer.wordpress.org/reference/classes/wp_query/is_front_page/\" rel=\"nofollow noreferrer\"><code>is_front_page</code></a> and <a href=\"https://developer.wordpress.org/reference/classes/wp_query/is_home/\" rel=\"nofollow noreferrer\"><code>is_home</code></a></p>\n" }, { "answer_id": 315203, "author": "Saran", "author_id": 25868, "author_profile": "https://wordpress.stackexchange.com/users/25868", "pm_score": 0, "selected": false, "text": "<p>You can try below code</p>\n\n<pre><code>function sv_change_product_price_display( $price ) {\n\n if(is_home() || is_front_page()){\n\n $price ='&lt;button&gt;Request Quote&lt;/button&gt;';\n }\n\n return $price;\n}\nadd_filter( 'woocommerce_get_price_html', 'sv_change_product_price_display' );\n</code></pre>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315192", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101024/" ]
I need a function that replaces the price in WooCommerce with "Request a quote". On my site's homepage I just need the text, but on the product page (which is a custom product from my travel theme) I need it to be a button. How can I have 2 functions, one that only works on Home and the other one that works in the rest of the site? In functions.php, something like: **IF IS\_HOME:** ``` add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); function custom_call_for_price() { return 'Request a quote'; } ``` **AND IF IS\_NOT\_HOME:** ``` add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); function custom_call_for_price() { $html .= '<a href="#"><input value="Request a quote" type="submit"></a>'; return $html; } ``` Can it be done? Thanks!
Use this: ``` function your_function() { if ( is_front_page() ) { $output = ... } else{ $output = ... } return $output; } ``` p.s. It's not needed to use `is_home()`. Whoever needs the technical details, see [`is_front_page`](https://developer.wordpress.org/reference/classes/wp_query/is_front_page/) and [`is_home`](https://developer.wordpress.org/reference/classes/wp_query/is_home/)
315,246
<p>I use <a href="http://github.com/jjgrainger/PostTypes/" rel="nofollow noreferrer">http://github.com/jjgrainger/PostTypes/</a> to register my custom post types and ACF to add custom fields to my custom post and I want to include in my wp-json response all registered fields per post and I do the following</p> <pre><code>$options = [ 'supports' =&gt; array('revisions'), 'has_archive' =&gt; false, 'show_in_rest' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; __('teachers', 'teachers')), 'capability_type' =&gt; 'post', 'rest_base' =&gt; 'teachers', 'query_var' =&gt; true, 'rest_controller_class' =&gt; 'WP_REST_Posts_Controller', ]; $teachers = new PostType('teacher', $options); $locations = new Taxonomy('location'); $levels = new Taxonomy('level'); $teachers-&gt;filters(['first_name', 'last_name']); $teachers-&gt;columns()-&gt;hide(['title', 'date']); $teachers-&gt;columns()-&gt;add([ 'first_name' =&gt; __('First Name'), 'last_name' =&gt; __('Last Name'), ]); $teachers-&gt;taxonomy('location'); $teachers-&gt;taxonomy('level'); $teachers-&gt;columns()-&gt;populate('first_name', function ($column, $post_id) { echo get_post_meta($post_id, 'first_name')[0]; }); $teachers-&gt;columns()-&gt;populate('last_name', function ($column, $post_id) { echo get_post_meta($post_id, 'last_name')[0]; }); $levels-&gt;columns()-&gt;add([ 'level' =&gt; __('Level'), ]); $levels-&gt;register(); $locations-&gt;register(); $teachers-&gt;register(); </code></pre> <p>but in wp-json response I do not have any custom fields, than I tried after googling adding the following filter</p> <pre><code>function my_rest_prepare_post($data, $post, $request) { dd($data); $_data = $data-&gt;data; $fields = get_fields($post-&gt;ID); foreach ($fields as $key =&gt; $value){ $_data[$key] = get_field($key, $post-&gt;ID); } $data-&gt;data = $_data; return $data; } add_filter("rest_prepare_teacher", 'my_rest_prepare_post', 10, 3); </code></pre> <p>but in this case I get a Fatal Error</p> <pre><code>Fatal error&lt;/b&gt;: Uncaught Error: Call to a member function get_links() on null in </code></pre> <p>How can I reflect in wp-json response on a custom post type all related custom field values?</p> <p><strong>Update</strong></p> <p>I forgot to mention that on top of wordpress I use wordplate with sage and after tracking down <code>rest_prepare_{$post_type}</code> method I got to this point, which is working in my case</p> <pre><code>add_filter("rest_prepare_teacher", function($post) { $_data = $post-&gt;data; $fields = get_fields($_data['id']); foreach ($fields as $key =&gt; $value){ $_data[$key] = get_field($key, $_data['id']); } $post-&gt;data = $_data; return $post; }); </code></pre>
[ { "answer_id": 342701, "author": "Adrian Barbosa", "author_id": 171706, "author_profile": "https://wordpress.stackexchange.com/users/171706", "pm_score": 2, "selected": false, "text": "<p>I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the <code>functions.php</code> file you have to add the next code: </p>\n\n<pre><code>//Custom acf endpoint;\nfunction my_endpoint( $request_data ) {\n\n // setup query argument\n $args = array(\n 'post_type' =&gt; 'my_post_type',\n 'posts_per_page' =&gt; -1\n );\n\n // get posts\n $posts = get_posts($args);\n\n // add custom field data to posts array \n foreach ($posts as $key =&gt; $post) {\n $posts[$key]-&gt;acf = get_fields($post-&gt;ID);\n $posts[$key]-&gt;link = get_permalink($post-&gt;ID);\n $posts[$key]-&gt;image = get_the_post_thumbnail_url($post-&gt;ID);\n }\n return $posts;\n}\n\n// register the endpoint;\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'my_endpoint/v1', '/my_post_type/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'my_endpoint',\n )\n );\n}\n</code></pre>\n\n<p>Credits to: <a href=\"https://clarencepearson.com/advanced-custom-fields-rest-api/\" rel=\"nofollow noreferrer\">https://clarencepearson.com/advanced-custom-fields-rest-api/</a></p>\n" }, { "answer_id": 396639, "author": "virtualLast", "author_id": 78147, "author_profile": "https://wordpress.stackexchange.com/users/78147", "pm_score": 0, "selected": false, "text": "<p>This answer inspired me to find my solution - I wanted to post it here in case it helps someone in the future:</p>\n<pre><code>use WP_Post;\nuse WP_REST_Request;\nuse WP_REST_Response;\n\nclass PreparePostAcfData\n{\n public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response\n {\n $data = $response-&gt;get_data();\n $fieldsData = get_fields($post-&gt;ID);\n if(is_array($data['acf']) &amp;&amp; is_array($fieldsData)) {\n $data['acf'] = array_merge($data['acf'], $fieldsData);\n }\n $response-&gt;set_data($data);\n\n return $response;\n }\n}\n</code></pre>\n<p>and then you can attach that to any custom post type using one of the wordpress rest api filters</p>\n<pre><code>$this-&gt;loader-&gt;add_filter('rest_prepare_advice_zone', $plugin_public-&gt;preparePostAcfData, 'preparePostAcfData', 99, 3);\n</code></pre>\n<p>The only thing to note really is that I had all ready defined <code>$data['acf']</code> earlier in the request cycle but you could quite easily swap out the array check for if exists or whatever seems relevant. Have a read of the wordpress filter being used <a href=\"https://developer.wordpress.org/reference/hooks/rest_prepare_this-post_type/\" rel=\"nofollow noreferrer\">rest_prepare_POST_TYPE</a></p>\n<p>cheers</p>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315246", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23759/" ]
I use <http://github.com/jjgrainger/PostTypes/> to register my custom post types and ACF to add custom fields to my custom post and I want to include in my wp-json response all registered fields per post and I do the following ``` $options = [ 'supports' => array('revisions'), 'has_archive' => false, 'show_in_rest' => true, 'rewrite' => array('slug' => __('teachers', 'teachers')), 'capability_type' => 'post', 'rest_base' => 'teachers', 'query_var' => true, 'rest_controller_class' => 'WP_REST_Posts_Controller', ]; $teachers = new PostType('teacher', $options); $locations = new Taxonomy('location'); $levels = new Taxonomy('level'); $teachers->filters(['first_name', 'last_name']); $teachers->columns()->hide(['title', 'date']); $teachers->columns()->add([ 'first_name' => __('First Name'), 'last_name' => __('Last Name'), ]); $teachers->taxonomy('location'); $teachers->taxonomy('level'); $teachers->columns()->populate('first_name', function ($column, $post_id) { echo get_post_meta($post_id, 'first_name')[0]; }); $teachers->columns()->populate('last_name', function ($column, $post_id) { echo get_post_meta($post_id, 'last_name')[0]; }); $levels->columns()->add([ 'level' => __('Level'), ]); $levels->register(); $locations->register(); $teachers->register(); ``` but in wp-json response I do not have any custom fields, than I tried after googling adding the following filter ``` function my_rest_prepare_post($data, $post, $request) { dd($data); $_data = $data->data; $fields = get_fields($post->ID); foreach ($fields as $key => $value){ $_data[$key] = get_field($key, $post->ID); } $data->data = $_data; return $data; } add_filter("rest_prepare_teacher", 'my_rest_prepare_post', 10, 3); ``` but in this case I get a Fatal Error ``` Fatal error</b>: Uncaught Error: Call to a member function get_links() on null in ``` How can I reflect in wp-json response on a custom post type all related custom field values? **Update** I forgot to mention that on top of wordpress I use wordplate with sage and after tracking down `rest_prepare_{$post_type}` method I got to this point, which is working in my case ``` add_filter("rest_prepare_teacher", function($post) { $_data = $post->data; $fields = get_fields($_data['id']); foreach ($fields as $key => $value){ $_data[$key] = get_field($key, $_data['id']); } $post->data = $_data; return $post; }); ```
I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the `functions.php` file you have to add the next code: ``` //Custom acf endpoint; function my_endpoint( $request_data ) { // setup query argument $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => -1 ); // get posts $posts = get_posts($args); // add custom field data to posts array foreach ($posts as $key => $post) { $posts[$key]->acf = get_fields($post->ID); $posts[$key]->link = get_permalink($post->ID); $posts[$key]->image = get_the_post_thumbnail_url($post->ID); } return $posts; } // register the endpoint; add_action( 'rest_api_init', function () { register_rest_route( 'my_endpoint/v1', '/my_post_type/', array( 'methods' => 'GET', 'callback' => 'my_endpoint', ) ); } ``` Credits to: <https://clarencepearson.com/advanced-custom-fields-rest-api/>
315,251
<p>After much troubleshooting and searching, I think I finally understand how to get The Loop going. Except I can't seem to get it to actually loop!</p> <p>I have created a Child theme, and added a <code>functions.php</code> file in there with this code:</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_style = 'grow-thinkup-style-minimal'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version') ); } function show_posts(){ if (is_page("test-1")){ if (have_posts()){ echo "You have posts!"; while (have_posts()){ the_post(); echo("This is " . the_title()); } } } } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); add_action('wp', 'show_posts'); ?&gt; </code></pre> <p>The idea is that I have a <strong>page</strong>, titled <code>test-1</code> (<code>www.example.com/test-1</code>). If that URL is visited, I would like to list all the <strong>posts</strong> I have in my Wordpress.</p> <p>All the current code does is show <code>the_title()</code> for <code>test-1</code>. Not my <strong>post</strong> pages. It also doesn't seem to be pulling the information from <code>the_post()</code>, i.e. <code>the_title()</code>.</p> <p>Here's what I see when I visit <code>www.example.com/test-1</code>: <a href="https://i.stack.imgur.com/6FW7C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6FW7C.jpg" alt="enter image description here"></a></p> <p>Is the reason it's not showing other information is that I have this in <code>functions.php</code>? I'm very new to WordPress so I'm still learning how their file system works, so that may be the issue? </p> <p>Again, end of the day I'd like a <strong>page</strong> to simply have all <strong>posts</strong> listed using The Loop.</p> <p>FYI here's how my files are located:</p> <ul> <li><code>.../wp-content/themes/grow-minimal-child/</code> [this has style.css, index.php, and functions.php with the code shown above]</li> </ul>
[ { "answer_id": 342701, "author": "Adrian Barbosa", "author_id": 171706, "author_profile": "https://wordpress.stackexchange.com/users/171706", "pm_score": 2, "selected": false, "text": "<p>I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the <code>functions.php</code> file you have to add the next code: </p>\n\n<pre><code>//Custom acf endpoint;\nfunction my_endpoint( $request_data ) {\n\n // setup query argument\n $args = array(\n 'post_type' =&gt; 'my_post_type',\n 'posts_per_page' =&gt; -1\n );\n\n // get posts\n $posts = get_posts($args);\n\n // add custom field data to posts array \n foreach ($posts as $key =&gt; $post) {\n $posts[$key]-&gt;acf = get_fields($post-&gt;ID);\n $posts[$key]-&gt;link = get_permalink($post-&gt;ID);\n $posts[$key]-&gt;image = get_the_post_thumbnail_url($post-&gt;ID);\n }\n return $posts;\n}\n\n// register the endpoint;\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'my_endpoint/v1', '/my_post_type/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'my_endpoint',\n )\n );\n}\n</code></pre>\n\n<p>Credits to: <a href=\"https://clarencepearson.com/advanced-custom-fields-rest-api/\" rel=\"nofollow noreferrer\">https://clarencepearson.com/advanced-custom-fields-rest-api/</a></p>\n" }, { "answer_id": 396639, "author": "virtualLast", "author_id": 78147, "author_profile": "https://wordpress.stackexchange.com/users/78147", "pm_score": 0, "selected": false, "text": "<p>This answer inspired me to find my solution - I wanted to post it here in case it helps someone in the future:</p>\n<pre><code>use WP_Post;\nuse WP_REST_Request;\nuse WP_REST_Response;\n\nclass PreparePostAcfData\n{\n public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response\n {\n $data = $response-&gt;get_data();\n $fieldsData = get_fields($post-&gt;ID);\n if(is_array($data['acf']) &amp;&amp; is_array($fieldsData)) {\n $data['acf'] = array_merge($data['acf'], $fieldsData);\n }\n $response-&gt;set_data($data);\n\n return $response;\n }\n}\n</code></pre>\n<p>and then you can attach that to any custom post type using one of the wordpress rest api filters</p>\n<pre><code>$this-&gt;loader-&gt;add_filter('rest_prepare_advice_zone', $plugin_public-&gt;preparePostAcfData, 'preparePostAcfData', 99, 3);\n</code></pre>\n<p>The only thing to note really is that I had all ready defined <code>$data['acf']</code> earlier in the request cycle but you could quite easily swap out the array check for if exists or whatever seems relevant. Have a read of the wordpress filter being used <a href=\"https://developer.wordpress.org/reference/hooks/rest_prepare_this-post_type/\" rel=\"nofollow noreferrer\">rest_prepare_POST_TYPE</a></p>\n<p>cheers</p>\n" } ]
2018/09/26
[ "https://wordpress.stackexchange.com/questions/315251", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147631/" ]
After much troubleshooting and searching, I think I finally understand how to get The Loop going. Except I can't seem to get it to actually loop! I have created a Child theme, and added a `functions.php` file in there with this code: ``` <?php function my_theme_enqueue_styles() { $parent_style = 'grow-thinkup-style-minimal'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } function show_posts(){ if (is_page("test-1")){ if (have_posts()){ echo "You have posts!"; while (have_posts()){ the_post(); echo("This is " . the_title()); } } } } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); add_action('wp', 'show_posts'); ?> ``` The idea is that I have a **page**, titled `test-1` (`www.example.com/test-1`). If that URL is visited, I would like to list all the **posts** I have in my Wordpress. All the current code does is show `the_title()` for `test-1`. Not my **post** pages. It also doesn't seem to be pulling the information from `the_post()`, i.e. `the_title()`. Here's what I see when I visit `www.example.com/test-1`: [![enter image description here](https://i.stack.imgur.com/6FW7C.jpg)](https://i.stack.imgur.com/6FW7C.jpg) Is the reason it's not showing other information is that I have this in `functions.php`? I'm very new to WordPress so I'm still learning how their file system works, so that may be the issue? Again, end of the day I'd like a **page** to simply have all **posts** listed using The Loop. FYI here's how my files are located: * `.../wp-content/themes/grow-minimal-child/` [this has style.css, index.php, and functions.php with the code shown above]
I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the `functions.php` file you have to add the next code: ``` //Custom acf endpoint; function my_endpoint( $request_data ) { // setup query argument $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => -1 ); // get posts $posts = get_posts($args); // add custom field data to posts array foreach ($posts as $key => $post) { $posts[$key]->acf = get_fields($post->ID); $posts[$key]->link = get_permalink($post->ID); $posts[$key]->image = get_the_post_thumbnail_url($post->ID); } return $posts; } // register the endpoint; add_action( 'rest_api_init', function () { register_rest_route( 'my_endpoint/v1', '/my_post_type/', array( 'methods' => 'GET', 'callback' => 'my_endpoint', ) ); } ``` Credits to: <https://clarencepearson.com/advanced-custom-fields-rest-api/>
315,269
<p>I want to add "custom built" to the front of every product title in a certain category.</p> <pre><code>&lt;?php $args = array('post_type' =&gt; 'product', 'tax_query'=&gt; array( array('taxonomy' =&gt; 'product_cat', 'field' =&gt; 'id', 'terms' =&gt; '3439',),), 'posts_per_page' =&gt; -1, ); $loop = new WP_Query( $args ); if ( $loop-&gt;have_posts() ) { while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); $prod_id = get_the_ID(); $my_post = array('ID'=&gt; $prod_id, 'post_title' =&gt; 'custom built', // I want to add 'custom built' not replace the whole title ); wp_update_post( $my_post ); endwhile; } wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 342701, "author": "Adrian Barbosa", "author_id": 171706, "author_profile": "https://wordpress.stackexchange.com/users/171706", "pm_score": 2, "selected": false, "text": "<p>I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the <code>functions.php</code> file you have to add the next code: </p>\n\n<pre><code>//Custom acf endpoint;\nfunction my_endpoint( $request_data ) {\n\n // setup query argument\n $args = array(\n 'post_type' =&gt; 'my_post_type',\n 'posts_per_page' =&gt; -1\n );\n\n // get posts\n $posts = get_posts($args);\n\n // add custom field data to posts array \n foreach ($posts as $key =&gt; $post) {\n $posts[$key]-&gt;acf = get_fields($post-&gt;ID);\n $posts[$key]-&gt;link = get_permalink($post-&gt;ID);\n $posts[$key]-&gt;image = get_the_post_thumbnail_url($post-&gt;ID);\n }\n return $posts;\n}\n\n// register the endpoint;\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'my_endpoint/v1', '/my_post_type/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'my_endpoint',\n )\n );\n}\n</code></pre>\n\n<p>Credits to: <a href=\"https://clarencepearson.com/advanced-custom-fields-rest-api/\" rel=\"nofollow noreferrer\">https://clarencepearson.com/advanced-custom-fields-rest-api/</a></p>\n" }, { "answer_id": 396639, "author": "virtualLast", "author_id": 78147, "author_profile": "https://wordpress.stackexchange.com/users/78147", "pm_score": 0, "selected": false, "text": "<p>This answer inspired me to find my solution - I wanted to post it here in case it helps someone in the future:</p>\n<pre><code>use WP_Post;\nuse WP_REST_Request;\nuse WP_REST_Response;\n\nclass PreparePostAcfData\n{\n public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response\n {\n $data = $response-&gt;get_data();\n $fieldsData = get_fields($post-&gt;ID);\n if(is_array($data['acf']) &amp;&amp; is_array($fieldsData)) {\n $data['acf'] = array_merge($data['acf'], $fieldsData);\n }\n $response-&gt;set_data($data);\n\n return $response;\n }\n}\n</code></pre>\n<p>and then you can attach that to any custom post type using one of the wordpress rest api filters</p>\n<pre><code>$this-&gt;loader-&gt;add_filter('rest_prepare_advice_zone', $plugin_public-&gt;preparePostAcfData, 'preparePostAcfData', 99, 3);\n</code></pre>\n<p>The only thing to note really is that I had all ready defined <code>$data['acf']</code> earlier in the request cycle but you could quite easily swap out the array check for if exists or whatever seems relevant. Have a read of the wordpress filter being used <a href=\"https://developer.wordpress.org/reference/hooks/rest_prepare_this-post_type/\" rel=\"nofollow noreferrer\">rest_prepare_POST_TYPE</a></p>\n<p>cheers</p>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63922/" ]
I want to add "custom built" to the front of every product title in a certain category. ``` <?php $args = array('post_type' => 'product', 'tax_query'=> array( array('taxonomy' => 'product_cat', 'field' => 'id', 'terms' => '3439',),), 'posts_per_page' => -1, ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); $prod_id = get_the_ID(); $my_post = array('ID'=> $prod_id, 'post_title' => 'custom built', // I want to add 'custom built' not replace the whole title ); wp_update_post( $my_post ); endwhile; } wp_reset_postdata(); ?> ```
I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the `functions.php` file you have to add the next code: ``` //Custom acf endpoint; function my_endpoint( $request_data ) { // setup query argument $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => -1 ); // get posts $posts = get_posts($args); // add custom field data to posts array foreach ($posts as $key => $post) { $posts[$key]->acf = get_fields($post->ID); $posts[$key]->link = get_permalink($post->ID); $posts[$key]->image = get_the_post_thumbnail_url($post->ID); } return $posts; } // register the endpoint; add_action( 'rest_api_init', function () { register_rest_route( 'my_endpoint/v1', '/my_post_type/', array( 'methods' => 'GET', 'callback' => 'my_endpoint', ) ); } ``` Credits to: <https://clarencepearson.com/advanced-custom-fields-rest-api/>
315,271
<p>I am having a premium wordpress theme which was hosted in godaddy, but its hosting got expired. I somehow managed to get all the previous files from godaddy by paying a hefty amount of money. but i don't know how to restore my site. currently it is showing "error establishing a database connection". what can be done?</p>
[ { "answer_id": 342701, "author": "Adrian Barbosa", "author_id": 171706, "author_profile": "https://wordpress.stackexchange.com/users/171706", "pm_score": 2, "selected": false, "text": "<p>I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the <code>functions.php</code> file you have to add the next code: </p>\n\n<pre><code>//Custom acf endpoint;\nfunction my_endpoint( $request_data ) {\n\n // setup query argument\n $args = array(\n 'post_type' =&gt; 'my_post_type',\n 'posts_per_page' =&gt; -1\n );\n\n // get posts\n $posts = get_posts($args);\n\n // add custom field data to posts array \n foreach ($posts as $key =&gt; $post) {\n $posts[$key]-&gt;acf = get_fields($post-&gt;ID);\n $posts[$key]-&gt;link = get_permalink($post-&gt;ID);\n $posts[$key]-&gt;image = get_the_post_thumbnail_url($post-&gt;ID);\n }\n return $posts;\n}\n\n// register the endpoint;\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'my_endpoint/v1', '/my_post_type/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'my_endpoint',\n )\n );\n}\n</code></pre>\n\n<p>Credits to: <a href=\"https://clarencepearson.com/advanced-custom-fields-rest-api/\" rel=\"nofollow noreferrer\">https://clarencepearson.com/advanced-custom-fields-rest-api/</a></p>\n" }, { "answer_id": 396639, "author": "virtualLast", "author_id": 78147, "author_profile": "https://wordpress.stackexchange.com/users/78147", "pm_score": 0, "selected": false, "text": "<p>This answer inspired me to find my solution - I wanted to post it here in case it helps someone in the future:</p>\n<pre><code>use WP_Post;\nuse WP_REST_Request;\nuse WP_REST_Response;\n\nclass PreparePostAcfData\n{\n public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response\n {\n $data = $response-&gt;get_data();\n $fieldsData = get_fields($post-&gt;ID);\n if(is_array($data['acf']) &amp;&amp; is_array($fieldsData)) {\n $data['acf'] = array_merge($data['acf'], $fieldsData);\n }\n $response-&gt;set_data($data);\n\n return $response;\n }\n}\n</code></pre>\n<p>and then you can attach that to any custom post type using one of the wordpress rest api filters</p>\n<pre><code>$this-&gt;loader-&gt;add_filter('rest_prepare_advice_zone', $plugin_public-&gt;preparePostAcfData, 'preparePostAcfData', 99, 3);\n</code></pre>\n<p>The only thing to note really is that I had all ready defined <code>$data['acf']</code> earlier in the request cycle but you could quite easily swap out the array check for if exists or whatever seems relevant. Have a read of the wordpress filter being used <a href=\"https://developer.wordpress.org/reference/hooks/rest_prepare_this-post_type/\" rel=\"nofollow noreferrer\">rest_prepare_POST_TYPE</a></p>\n<p>cheers</p>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140116/" ]
I am having a premium wordpress theme which was hosted in godaddy, but its hosting got expired. I somehow managed to get all the previous files from godaddy by paying a hefty amount of money. but i don't know how to restore my site. currently it is showing "error establishing a database connection". what can be done?
I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the `functions.php` file you have to add the next code: ``` //Custom acf endpoint; function my_endpoint( $request_data ) { // setup query argument $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => -1 ); // get posts $posts = get_posts($args); // add custom field data to posts array foreach ($posts as $key => $post) { $posts[$key]->acf = get_fields($post->ID); $posts[$key]->link = get_permalink($post->ID); $posts[$key]->image = get_the_post_thumbnail_url($post->ID); } return $posts; } // register the endpoint; add_action( 'rest_api_init', function () { register_rest_route( 'my_endpoint/v1', '/my_post_type/', array( 'methods' => 'GET', 'callback' => 'my_endpoint', ) ); } ``` Credits to: <https://clarencepearson.com/advanced-custom-fields-rest-api/>
315,295
<p>I want to add a product attribute (wc_create_attribute) &amp; assigned terms (wp_insert_term) via the functions.php.</p> <p>Example:</p> <pre><code>$args = array( 'name' =&gt; "Color", 'slug' =&gt; "color", 'order_by' =&gt; "menu_order", 'has_archives' =&gt; "", ); wc_create_attribute($args); $add = wp_insert_term( "Blue", 'pa_color', array( 'slug' =&gt; "blue" ) ); print_r($add); </code></pre> <p>The <code>wc_create_attribute()</code> works fine, but when the <code>wp_insert_term()</code> runs it throws an error because of “Invalid taxonomy”. When I then reload the page, it works fine because then the taxonomy is not invalid anymore. So it seems that the <code>wp_insert_term()</code> are executed before the create_attribute somehow. I don’t understand why it does not work in one attempt.</p> <p>Maybe you can help me</p>
[ { "answer_id": 342701, "author": "Adrian Barbosa", "author_id": 171706, "author_profile": "https://wordpress.stackexchange.com/users/171706", "pm_score": 2, "selected": false, "text": "<p>I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the <code>functions.php</code> file you have to add the next code: </p>\n\n<pre><code>//Custom acf endpoint;\nfunction my_endpoint( $request_data ) {\n\n // setup query argument\n $args = array(\n 'post_type' =&gt; 'my_post_type',\n 'posts_per_page' =&gt; -1\n );\n\n // get posts\n $posts = get_posts($args);\n\n // add custom field data to posts array \n foreach ($posts as $key =&gt; $post) {\n $posts[$key]-&gt;acf = get_fields($post-&gt;ID);\n $posts[$key]-&gt;link = get_permalink($post-&gt;ID);\n $posts[$key]-&gt;image = get_the_post_thumbnail_url($post-&gt;ID);\n }\n return $posts;\n}\n\n// register the endpoint;\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'my_endpoint/v1', '/my_post_type/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'my_endpoint',\n )\n );\n}\n</code></pre>\n\n<p>Credits to: <a href=\"https://clarencepearson.com/advanced-custom-fields-rest-api/\" rel=\"nofollow noreferrer\">https://clarencepearson.com/advanced-custom-fields-rest-api/</a></p>\n" }, { "answer_id": 396639, "author": "virtualLast", "author_id": 78147, "author_profile": "https://wordpress.stackexchange.com/users/78147", "pm_score": 0, "selected": false, "text": "<p>This answer inspired me to find my solution - I wanted to post it here in case it helps someone in the future:</p>\n<pre><code>use WP_Post;\nuse WP_REST_Request;\nuse WP_REST_Response;\n\nclass PreparePostAcfData\n{\n public function preparePostAcfData(WP_REST_Response $response, WP_Post $post, WP_REST_Request $request): WP_REST_Response\n {\n $data = $response-&gt;get_data();\n $fieldsData = get_fields($post-&gt;ID);\n if(is_array($data['acf']) &amp;&amp; is_array($fieldsData)) {\n $data['acf'] = array_merge($data['acf'], $fieldsData);\n }\n $response-&gt;set_data($data);\n\n return $response;\n }\n}\n</code></pre>\n<p>and then you can attach that to any custom post type using one of the wordpress rest api filters</p>\n<pre><code>$this-&gt;loader-&gt;add_filter('rest_prepare_advice_zone', $plugin_public-&gt;preparePostAcfData, 'preparePostAcfData', 99, 3);\n</code></pre>\n<p>The only thing to note really is that I had all ready defined <code>$data['acf']</code> earlier in the request cycle but you could quite easily swap out the array check for if exists or whatever seems relevant. Have a read of the wordpress filter being used <a href=\"https://developer.wordpress.org/reference/hooks/rest_prepare_this-post_type/\" rel=\"nofollow noreferrer\">rest_prepare_POST_TYPE</a></p>\n<p>cheers</p>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28159/" ]
I want to add a product attribute (wc\_create\_attribute) & assigned terms (wp\_insert\_term) via the functions.php. Example: ``` $args = array( 'name' => "Color", 'slug' => "color", 'order_by' => "menu_order", 'has_archives' => "", ); wc_create_attribute($args); $add = wp_insert_term( "Blue", 'pa_color', array( 'slug' => "blue" ) ); print_r($add); ``` The `wc_create_attribute()` works fine, but when the `wp_insert_term()` runs it throws an error because of “Invalid taxonomy”. When I then reload the page, it works fine because then the taxonomy is not invalid anymore. So it seems that the `wp_insert_term()` are executed before the create\_attribute somehow. I don’t understand why it does not work in one attempt. Maybe you can help me
I really hope that you have managed this issue. In case you don't, this kinda works for me since there is a way to register a custom acf endpoint, in the `functions.php` file you have to add the next code: ``` //Custom acf endpoint; function my_endpoint( $request_data ) { // setup query argument $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => -1 ); // get posts $posts = get_posts($args); // add custom field data to posts array foreach ($posts as $key => $post) { $posts[$key]->acf = get_fields($post->ID); $posts[$key]->link = get_permalink($post->ID); $posts[$key]->image = get_the_post_thumbnail_url($post->ID); } return $posts; } // register the endpoint; add_action( 'rest_api_init', function () { register_rest_route( 'my_endpoint/v1', '/my_post_type/', array( 'methods' => 'GET', 'callback' => 'my_endpoint', ) ); } ``` Credits to: <https://clarencepearson.com/advanced-custom-fields-rest-api/>
315,311
<p>I want to display <em>only</em> the sticky posts on my front page. Right now it's possible to do a setting where the sticky posts are displayed at the top followed by the rest of the posts. I don't want to rest of the posts to show up, so how do I make sure only the sticky posts are shown?</p> <p>Thank you!</p>
[ { "answer_id": 315313, "author": "Krishna Joshi", "author_id": 150621, "author_profile": "https://wordpress.stackexchange.com/users/150621", "pm_score": -1, "selected": false, "text": "<p>Try below steps</p>\n\n<ol>\n<li>Log into your WordPress admin panel.</li>\n<li>Look to the left hand sidebar menu and click the Settings option.</li>\n<li>From the expanded menu, click on the Reading option.</li>\n<li>You are brought to the Reading Settings page. From here, locate the Front page displays section and select the radio button for A static page (select below) .</li>\n<li>Next, select the page you want as your front page from the Front\npage:dropdown.</li>\n<li>Finally, set the Posts page: dropdown to --Select--. This\neffectively removes it from displaying on your site.</li>\n<li>Click on the Save Changes button to activate the new setup.</li>\n</ol>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 315316, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>WordPress saves sticky posts inside the option named <code>sticky_posts</code>. You can retrieve them via <code>get_option('sticky_posts')</code>.</p>\n\n<p>With that knowledge it is possible to change the query to only query for sticky posts, you usually do so via the <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> hook.</p>\n\n<pre><code>add_action('pre_get_posts', 'WPSE_home_only_stickies');\nfunction WPSE_home_only_stickies($query) {\n // only run for homepage &amp; main query\n if ($query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query()) {\n $sticky_posts = get_option('sticky_posts');\n $query-&gt;set('post__in', $sticky_posts);\n }\n}\n</code></pre>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315311", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151369/" ]
I want to display *only* the sticky posts on my front page. Right now it's possible to do a setting where the sticky posts are displayed at the top followed by the rest of the posts. I don't want to rest of the posts to show up, so how do I make sure only the sticky posts are shown? Thank you!
WordPress saves sticky posts inside the option named `sticky_posts`. You can retrieve them via `get_option('sticky_posts')`. With that knowledge it is possible to change the query to only query for sticky posts, you usually do so via the [`pre_get_posts`](https://developer.wordpress.org/reference/hooks/pre_get_posts/) hook. ``` add_action('pre_get_posts', 'WPSE_home_only_stickies'); function WPSE_home_only_stickies($query) { // only run for homepage & main query if ($query->is_home() && $query->is_main_query()) { $sticky_posts = get_option('sticky_posts'); $query->set('post__in', $sticky_posts); } } ```
315,323
<p>I have a unique website type that only requires 10-20 seconds to make a new post. I want my WordPress site to reload the editor page automatically after a new post has been published hence I don't need to click "Add New" button in order to load blank post editor page.</p>
[ { "answer_id": 315313, "author": "Krishna Joshi", "author_id": 150621, "author_profile": "https://wordpress.stackexchange.com/users/150621", "pm_score": -1, "selected": false, "text": "<p>Try below steps</p>\n\n<ol>\n<li>Log into your WordPress admin panel.</li>\n<li>Look to the left hand sidebar menu and click the Settings option.</li>\n<li>From the expanded menu, click on the Reading option.</li>\n<li>You are brought to the Reading Settings page. From here, locate the Front page displays section and select the radio button for A static page (select below) .</li>\n<li>Next, select the page you want as your front page from the Front\npage:dropdown.</li>\n<li>Finally, set the Posts page: dropdown to --Select--. This\neffectively removes it from displaying on your site.</li>\n<li>Click on the Save Changes button to activate the new setup.</li>\n</ol>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 315316, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>WordPress saves sticky posts inside the option named <code>sticky_posts</code>. You can retrieve them via <code>get_option('sticky_posts')</code>.</p>\n\n<p>With that knowledge it is possible to change the query to only query for sticky posts, you usually do so via the <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> hook.</p>\n\n<pre><code>add_action('pre_get_posts', 'WPSE_home_only_stickies');\nfunction WPSE_home_only_stickies($query) {\n // only run for homepage &amp; main query\n if ($query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query()) {\n $sticky_posts = get_option('sticky_posts');\n $query-&gt;set('post__in', $sticky_posts);\n }\n}\n</code></pre>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151377/" ]
I have a unique website type that only requires 10-20 seconds to make a new post. I want my WordPress site to reload the editor page automatically after a new post has been published hence I don't need to click "Add New" button in order to load blank post editor page.
WordPress saves sticky posts inside the option named `sticky_posts`. You can retrieve them via `get_option('sticky_posts')`. With that knowledge it is possible to change the query to only query for sticky posts, you usually do so via the [`pre_get_posts`](https://developer.wordpress.org/reference/hooks/pre_get_posts/) hook. ``` add_action('pre_get_posts', 'WPSE_home_only_stickies'); function WPSE_home_only_stickies($query) { // only run for homepage & main query if ($query->is_home() && $query->is_main_query()) { $sticky_posts = get_option('sticky_posts'); $query->set('post__in', $sticky_posts); } } ```
315,324
<p>I am coding a WordPress plugin that goes on top of WooCommerce. This plugin basically allows WooCommerce to allocate <strong>store credits</strong> to a logged-in customer whenever he makes an order later marked as <code>Completed</code> after payment. These store credits can then be used to offset the cost of a future order that the customer makes. As an example, if I buy $10 worth of items, I might get a $1 store credit. I can use any amount of my store credit to offset future purchases, e.g. I might choose to use $0.50 of my credits to offset my next order by $0.50.</p> <p>I have had no problem finding the hooks to use in WP-Admin to allocate customers their store credits, but I'm having trouble adding hooks to the front-end to allow customers to use their store credits in an order.</p> <p>Currently, I have the following function hooked to the <code>woocommerce_checkout_order_processed</code> action, to record how much store credit the customer is intending to use on an order:</p> <pre><code>function woocommerce_checkout_order_processed($order_id) { $offset_amt = floatval($_POST['use-store-credit']); // This line is a glorified update_post_meta call. Helpers\Order::set_offset_cost_amount($order_id,$offset_amt); } </code></pre> <p>But I think saving it as a meta key seperate from the workings of <code>WP_Order</code> or <code>WP_Cart</code> is a bad idea, because once the order is submitted, I will have to hook onto every page the order is rendered (including the pages in WP-Admin) and manually modify the order total, because the <code>WP_Order</code> will record the total without the store credit offset.</p> <p>I think hooking this store credit offset as a discount or as a negative fee would be better, but <strong>I don't know which hooks to use or where in the process I should do that</strong>. Should I hook it on the cart before checkout, or should I hook it onto the order after checkout?</p>
[ { "answer_id": 315366, "author": "Matt Royal", "author_id": 51860, "author_profile": "https://wordpress.stackexchange.com/users/51860", "pm_score": 3, "selected": true, "text": "<p>I would suggest adding a \"virtual\" coupon to the order which would represent the store credit.</p>\n\n<p>Coupons are applied on the cart page before checkout, this is where I would hook in.</p>\n\n<p>You can use something like the <code>woocommerce_cart_subtotal</code> filter as per my example below:</p>\n\n<pre><code>function royal_woocommerce_filter_checkout_for_coupons( $subtotal, $compound, $cart ) { \n\n // Your logic to get store credit value for a user will go here\n $store_credit = 20;\n\n // We only need to add a store credit coupon if they have store credit\n if($store_credit &gt; 0){\n\n // Setup our virtual coupon\n $coupon_name = 'store-credit';\n $coupon = array($coupon_name =&gt; $store_credit);\n\n // Apply the store credit coupon to the cart &amp; update totals\n $cart-&gt;applied_coupons = array($coupon_name);\n $cart-&gt;set_discount_total($store_credit);\n $cart-&gt;set_total( $cart-&gt;get_subtotal() - $store_credit);\n $cart-&gt;coupon_discount_totals = $coupon;\n }\n\n return $subtotal; \n}\n\nadd_filter( 'woocommerce_cart_subtotal', 'royal_woocommerce_filter_checkout_for_coupons', 10, 3 );\n</code></pre>\n" }, { "answer_id": 366883, "author": "lastant", "author_id": 188299, "author_profile": "https://wordpress.stackexchange.com/users/188299", "pm_score": 3, "selected": false, "text": "<p>The proper way to add a virtual coupon programmatically, without interfering with regular coupons:</p>\n<pre><code>add_action('woocommerce_before_calculate_totals', function(WC_Cart $cart) {\n $cart-&gt;applied_coupons = array_diff($cart-&gt;applied_coupons, ['store-credit']);\n\n // add your conditions for applying the virtual coupon\n $cart-&gt;applied_coupons[] = 'store-credit';\n});\n\n// specify discount data, here give 10% discount\nadd_filter('woocommerce_get_shop_coupon_data', function($false, $data, $coupon) {\n switch($data) {\n case 'store-credit':\n $coupon-&gt;set_virtual(true);\n $coupon-&gt;set_discount_type('percent');\n $coupon-&gt;set_amount(10);\n return $coupon;\n }\n}, 10, 3);\n\n// Optional: remove the 'Coupon:' label\nadd_filter('woocommerce_cart_totals_coupon_html', function($coupon_html, $coupon, $discount_amount_html) {\n if (in_array($coupon-&gt;get_code(), ['store-credit']))\n return $discount_amount_html;\n \n return $coupon_html;\n}, 10, 3);\n\n// Optional: set a custom label\nadd_filter('woocommerce_cart_totals_coupon_label', function($label, $coupon) {\n switch ($coupon-&gt;get_code()) {\n case 'store-credit':\n return 'Store Credit';\n }\n return $label;\n}, 10, 3);\n</code></pre>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315324", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78806/" ]
I am coding a WordPress plugin that goes on top of WooCommerce. This plugin basically allows WooCommerce to allocate **store credits** to a logged-in customer whenever he makes an order later marked as `Completed` after payment. These store credits can then be used to offset the cost of a future order that the customer makes. As an example, if I buy $10 worth of items, I might get a $1 store credit. I can use any amount of my store credit to offset future purchases, e.g. I might choose to use $0.50 of my credits to offset my next order by $0.50. I have had no problem finding the hooks to use in WP-Admin to allocate customers their store credits, but I'm having trouble adding hooks to the front-end to allow customers to use their store credits in an order. Currently, I have the following function hooked to the `woocommerce_checkout_order_processed` action, to record how much store credit the customer is intending to use on an order: ``` function woocommerce_checkout_order_processed($order_id) { $offset_amt = floatval($_POST['use-store-credit']); // This line is a glorified update_post_meta call. Helpers\Order::set_offset_cost_amount($order_id,$offset_amt); } ``` But I think saving it as a meta key seperate from the workings of `WP_Order` or `WP_Cart` is a bad idea, because once the order is submitted, I will have to hook onto every page the order is rendered (including the pages in WP-Admin) and manually modify the order total, because the `WP_Order` will record the total without the store credit offset. I think hooking this store credit offset as a discount or as a negative fee would be better, but **I don't know which hooks to use or where in the process I should do that**. Should I hook it on the cart before checkout, or should I hook it onto the order after checkout?
I would suggest adding a "virtual" coupon to the order which would represent the store credit. Coupons are applied on the cart page before checkout, this is where I would hook in. You can use something like the `woocommerce_cart_subtotal` filter as per my example below: ``` function royal_woocommerce_filter_checkout_for_coupons( $subtotal, $compound, $cart ) { // Your logic to get store credit value for a user will go here $store_credit = 20; // We only need to add a store credit coupon if they have store credit if($store_credit > 0){ // Setup our virtual coupon $coupon_name = 'store-credit'; $coupon = array($coupon_name => $store_credit); // Apply the store credit coupon to the cart & update totals $cart->applied_coupons = array($coupon_name); $cart->set_discount_total($store_credit); $cart->set_total( $cart->get_subtotal() - $store_credit); $cart->coupon_discount_totals = $coupon; } return $subtotal; } add_filter( 'woocommerce_cart_subtotal', 'royal_woocommerce_filter_checkout_for_coupons', 10, 3 ); ```
315,363
<p>I have created a custom post type. Within that I have assigned two custom taxonomies. One (computer) is what I use to drive the template files and slug of page (taxonomy-computer.php). The second (faq-option) is what will categorize all posts associated under the first taxonomy (computer). </p> <p>My issue that I am having is creating some sort of loop to list out the faq-option tax with the associated posts to that. </p> <p>i.e.</p> <p>taxonomy-computer.php (computer)<br> -> faq-option <br> -> post <br> -> post</p> <p>Currently it is listing out each term with the associated post</p> <p>i.e. </p> <p>-> faq-option <br> -> post </p> <p>-> faq-option <br> -> post </p> <p>My main objective is to group the under the respective taxonomy. I also was trying to stay with the main loop rather than create a new query. Now I am open to suggestions here.</p> <pre><code> $terms = get_the_terms( $post-&gt;ID , 'faq-option' ); foreach( $terms as $term ) : foreach( $terms as $term ) : setup_postdata($term); echo '&lt;h3&gt;'.$term-&gt;name. '&lt;/h3&gt;' ; echo '&lt;p&gt;&lt;a href="#"&gt;'.the_title().'&lt;/a&gt;&lt;/p&gt;'; endforeach; wp_reset_postdata(); endforeach; </code></pre> <p>The block of code is being added to the taxonomy-computer.php file. I am also using pre_get_posts to change the amount of ppp as well as the order/orderby.</p> <p>I am stump and open to suggestions.</p> <p>Thank you!</p>
[ { "answer_id": 315357, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>Content in WordPress is inside the WordPress database. </p>\n\n<p>If you have deleted the WP database, then the content is gone. Installing a new WP instance will create a new, mostly blank database.</p>\n\n<p>So, unless you have a backup copy of your database to restore, your content is gone.</p>\n\n<p>Your hosting place may have made a backup of things, including your database. So you might contact them to see if they can restore your databases.</p>\n\n<p>Unless the hosting place has a backup copy (many do), you might be out of luck. Sorry.</p>\n\n<p>(For 'lurkers' ... do you have a backed up / offsite copy of your WordPress database? There are many plugins that will do that for you.)</p>\n" }, { "answer_id": 315359, "author": "Christian Pastor Cruz", "author_id": 142793, "author_profile": "https://wordpress.stackexchange.com/users/142793", "pm_score": 2, "selected": false, "text": "<p>You seem out of luck, my friend, but search your page here: <a href=\"https://web.archive.org/\" rel=\"nofollow noreferrer\">https://web.archive.org/</a> it MAY save your sanity.</p>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115019/" ]
I have created a custom post type. Within that I have assigned two custom taxonomies. One (computer) is what I use to drive the template files and slug of page (taxonomy-computer.php). The second (faq-option) is what will categorize all posts associated under the first taxonomy (computer). My issue that I am having is creating some sort of loop to list out the faq-option tax with the associated posts to that. i.e. taxonomy-computer.php (computer) -> faq-option -> post -> post Currently it is listing out each term with the associated post i.e. -> faq-option -> post -> faq-option -> post My main objective is to group the under the respective taxonomy. I also was trying to stay with the main loop rather than create a new query. Now I am open to suggestions here. ``` $terms = get_the_terms( $post->ID , 'faq-option' ); foreach( $terms as $term ) : foreach( $terms as $term ) : setup_postdata($term); echo '<h3>'.$term->name. '</h3>' ; echo '<p><a href="#">'.the_title().'</a></p>'; endforeach; wp_reset_postdata(); endforeach; ``` The block of code is being added to the taxonomy-computer.php file. I am also using pre\_get\_posts to change the amount of ppp as well as the order/orderby. I am stump and open to suggestions. Thank you!
Content in WordPress is inside the WordPress database. If you have deleted the WP database, then the content is gone. Installing a new WP instance will create a new, mostly blank database. So, unless you have a backup copy of your database to restore, your content is gone. Your hosting place may have made a backup of things, including your database. So you might contact them to see if they can restore your databases. Unless the hosting place has a backup copy (many do), you might be out of luck. Sorry. (For 'lurkers' ... do you have a backed up / offsite copy of your WordPress database? There are many plugins that will do that for you.)
315,369
<p>I'm running a query (200-300 posts), while this might not be for a lot of people / hosts, I just want to optimize wherever I can, given the fact that a lot of things happen when running that particular script, and so, my motivation is optimization.</p> <p>My query is exactly:</p> <pre><code> $args = [ 'post_type' =&gt; 'post', 'orderby' =&gt; 'ASC', 'post__in' =&gt; $post_ids ]; $headers = new \WP_Query( $args ); </code></pre> <p>So I'm asking the database to just give me everything that matches these IDs. But I don't need any meta information, no paging information, no counting of the posts, nothing, just the raw posts, so I was thinking of adding <code>no_found_rows =&gt; true</code> to the query.</p> <p>While this clearly speeds things up, if I think of all the <code>WP_Query</code> I wrote through my system, I rarely need to know pagination or their count.</p> <p><strong>Or don't I?</strong> When there's no pagination, how does the system know to go to the next "batch"?</p> <p>In other, simpler words: is <code>no_found_rows =&gt; true</code> a must-have when querying big lists of posts where you just need to know about all the posts in a given query?</p>
[ { "answer_id": 315379, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>It is not a \"must have\", but you should use it whenever you are not interested in knowing the total amount of post.</p>\n\n<p>Default parameters are pet peeve of mine, and generally I advocate about never letting parameters default to default and instead have a conscious decision per each. This is not about performance per-se but about better control and understanding of how your code works.</p>\n\n<p>Sure it will lead to very verbose function calls, but if you have a pattern that you reuse many time, you can just create a wrapper around <code>WP_Query</code> that will make the code more readable.</p>\n" }, { "answer_id": 315556, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": false, "text": "<p>I'm going to try and answer:</p>\n\n<blockquote>\n <p>Is <code>no_found_rows =&gt; true</code> a must-have when querying big lists of posts where you just need to know about all the posts in a given query?</p>\n</blockquote>\n\n<p>Yes, but you shouldn't be doing that anyway. Fetching large numbers of posts in a single query is bad for numerous reasons:</p>\n\n<ul>\n<li>memory exhaustion - all those post objects take up memory, as do the post meta and terms that get primed when they're fetched</li>\n<li>page generation time - all that priming and querying takes time, as does the actual display of the post and sending the output</li>\n<li>unexpected assumptions - \"there'll only ever be 5 business posts, it's not an issue\", famous last words said a year before an RSS aggregator is piped into that post type, or the business need changes, or an error duplicates every business post by accident, or a botched migration, or a site that was only meant to get minimal traffic blows up huge</li>\n</ul>\n\n<p>If you must, e.g. in a CLI command, fetch the posts in batches of 50 in a do while loop. There are far worse things for performance that can be done, and the example in the original post is already rather fast thanks to <code>post__in</code> and no other options.</p>\n" }, { "answer_id": 363394, "author": "vguerrero", "author_id": 56470, "author_profile": "https://wordpress.stackexchange.com/users/56470", "pm_score": 3, "selected": false, "text": "<p>Your code will run five SQL queries in total.</p>\n\n<p>When setting <code>no_found_rows =&gt; true</code> the first two queries</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID IN (1,49,63,249,72,95,259,207,183,225) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date ASC LIMIT 0, 10\n\nSELECT FOUND_ROWS()\n</code></pre>\n\n<p>will become a single query like</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID IN (1,49,63,249,72,95,259,207,183,225) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date ASC LIMIT 0, 10\n</code></pre>\n\n<p>so yes, <code>no_found_rows</code> will improve performance to some extent.</p>\n\n<blockquote>\n <p>I don't need any meta information, no paging information, no counting of the posts, nothing, just the raw posts</p>\n</blockquote>\n\n<p>In this case, you can further optimize. <code>WP_Query</code> will cache taxonomies by default, but setting <code>update_post_term_cache =&gt; false</code> will skip the following query</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag', 'post_format') AND tr.object_id IN (1, 49, 63, 72, 95, 183, 207, 225, 249, 259) ORDER BY t.name ASC\n</code></pre>\n\n<p>Likewise, setting <code>update_post_meta_cache =&gt; false</code> will avoid <code>WP_Query</code> caching posts metadata and will skip the following query</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN (1,49,63,72,95,183,207,225,249,259) ORDER BY meta_id ASC\n</code></pre>\n\n<p>So we can go from five (5) queries down to two (2) just setting these attributes.</p>\n\n<p>Keep in mind that these optimzations can lead to N+1 problems if afterwards during the loop you actually attempt to display categorization information or any metadata such as post thumbnails, so use them wisely.</p>\n" } ]
2018/09/27
[ "https://wordpress.stackexchange.com/questions/315369", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143406/" ]
I'm running a query (200-300 posts), while this might not be for a lot of people / hosts, I just want to optimize wherever I can, given the fact that a lot of things happen when running that particular script, and so, my motivation is optimization. My query is exactly: ``` $args = [ 'post_type' => 'post', 'orderby' => 'ASC', 'post__in' => $post_ids ]; $headers = new \WP_Query( $args ); ``` So I'm asking the database to just give me everything that matches these IDs. But I don't need any meta information, no paging information, no counting of the posts, nothing, just the raw posts, so I was thinking of adding `no_found_rows => true` to the query. While this clearly speeds things up, if I think of all the `WP_Query` I wrote through my system, I rarely need to know pagination or their count. **Or don't I?** When there's no pagination, how does the system know to go to the next "batch"? In other, simpler words: is `no_found_rows => true` a must-have when querying big lists of posts where you just need to know about all the posts in a given query?
I'm going to try and answer: > > Is `no_found_rows => true` a must-have when querying big lists of posts where you just need to know about all the posts in a given query? > > > Yes, but you shouldn't be doing that anyway. Fetching large numbers of posts in a single query is bad for numerous reasons: * memory exhaustion - all those post objects take up memory, as do the post meta and terms that get primed when they're fetched * page generation time - all that priming and querying takes time, as does the actual display of the post and sending the output * unexpected assumptions - "there'll only ever be 5 business posts, it's not an issue", famous last words said a year before an RSS aggregator is piped into that post type, or the business need changes, or an error duplicates every business post by accident, or a botched migration, or a site that was only meant to get minimal traffic blows up huge If you must, e.g. in a CLI command, fetch the posts in batches of 50 in a do while loop. There are far worse things for performance that can be done, and the example in the original post is already rather fast thanks to `post__in` and no other options.
315,383
<p>I see Yoast stores the snippet variables in the database. I'd like to get their values and ship them via the WP REST API. I'd also like to keep the Admin functionality for Administrators and the default settings for scalability. </p> <p>I'm shipping the values off to a different application, but I can't ship the placeholders. </p> <p>They can obviously get parsed because that's how they display in the frontend. I just don't see how to do it. </p> <p>In the database you can see: </p> <pre><code>_yoast_wpseo_title %%title%% %%page%% %%sep%% %%sitename%% </code></pre> <p>On the front end you can see:</p> <pre><code>&lt;title&gt;About - Cool Site Name&lt;/title&gt; </code></pre>
[ { "answer_id": 315393, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>Yoast's SEO plugin has a <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">nice API</a>. You can probably get this with a filter like </p>\n\n<pre><code>add_filter( 'wpseo_options', function ( $arr ) {\n return $arr;\n} );\n</code></pre>\n" }, { "answer_id": 315437, "author": "Josh Smith", "author_id": 29089, "author_profile": "https://wordpress.stackexchange.com/users/29089", "pm_score": 1, "selected": true, "text": "<p>Basically this is the answer I was looking for from this question: </p>\n\n<pre><code>function yoastVariableToTitle( $post_id ) {\n $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true );\n $title = strstr( $yoast_title, '%%', true );\n if ( empty( $title ) ) {\n $title = get_the_title( $post_id );\n }\n $wpseo_titles = get_option( 'wpseo_titles' );\n\n $sep_options = WPSEO_Option_Titles::get_instance()-&gt;get_separator_options();\n if ( isset( $wpseo_titles['separator'] ) &amp;&amp; isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {\n $sep = $sep_options[ $wpseo_titles['separator'] ];\n } else {\n $sep = '-'; //setting default separator if Admin didn't set it from backed\n }\n\n $site_title = get_bloginfo( 'name' );\n\n $meta_title = $title . ' ' . $sep . ' ' . $site_title;\n\n return $meta_title;\n} \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti\">https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti</a></p>\n" }, { "answer_id": 332369, "author": "baskin", "author_id": 163582, "author_profile": "https://wordpress.stackexchange.com/users/163582", "pm_score": 2, "selected": false, "text": "<p>Ok here is how I parsed the snippets in case anyone else needs to know</p>\n\n<pre><code>$id = get_the_ID();\n\n$post = get_post( $id, ARRAY_A );\n$yoast_title = get_post_meta( $id, '_yoast_wpseo_title', true );\n$yoast_desc = get_post_meta( $id, '_yoast_wpseo_metadesc', true );\n\n$metatitle_val = wpseo_replace_vars($yoast_title, $post );\n$metatitle_val = apply_filters( 'wpseo_title', $metatitle_val );\n\n$metadesc_val = wpseo_replace_vars($yoast_desc, $post );\n$metadesc_val = apply_filters( 'wpseo_metadesc', $metadesc_val );\n\necho $metatitle_val;\necho \"&lt;br&gt;\";\necho $metadesc_val;\n</code></pre>\n" } ]
2018/09/28
[ "https://wordpress.stackexchange.com/questions/315383", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29089/" ]
I see Yoast stores the snippet variables in the database. I'd like to get their values and ship them via the WP REST API. I'd also like to keep the Admin functionality for Administrators and the default settings for scalability. I'm shipping the values off to a different application, but I can't ship the placeholders. They can obviously get parsed because that's how they display in the frontend. I just don't see how to do it. In the database you can see: ``` _yoast_wpseo_title %%title%% %%page%% %%sep%% %%sitename%% ``` On the front end you can see: ``` <title>About - Cool Site Name</title> ```
Basically this is the answer I was looking for from this question: ``` function yoastVariableToTitle( $post_id ) { $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true ); $title = strstr( $yoast_title, '%%', true ); if ( empty( $title ) ) { $title = get_the_title( $post_id ); } $wpseo_titles = get_option( 'wpseo_titles' ); $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options(); if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) { $sep = $sep_options[ $wpseo_titles['separator'] ]; } else { $sep = '-'; //setting default separator if Admin didn't set it from backed } $site_title = get_bloginfo( 'name' ); $meta_title = $title . ' ' . $sep . ' ' . $site_title; return $meta_title; } ``` <https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti>
315,399
<p>To increase the loading speed, I would like to only enable Event Manager plugin on the pages where it's actually used. For that, I wrote this piece of code:</p> <pre><code>// deregister unnecessary plugin scripts: function my_deregister() { if ( !is_page('events') ) { wp_deregister_script( 'events-manager' ); } } add_action( 'wp_print_scripts', 'my_deregister', 100 ); </code></pre> <p>However, the problem is that this event plugin creates a single page for each event and it needs to be enabled on those sub-pages, too. Apparently, each generated page is named differently. For instance, <strong>www.mysite.com/events/EventNameEventDate</strong>. </p> <p>So I would like to have the plugin disabled on all pages except for 'events' and its sub-pages (of which I will obviously not always know the count and names). The <strong>is_page()</strong> works fine for the Events page but how do I modify it so that it recognises its sub-pages and enables the plugin scripts on them, too? </p> <p><em>This was just a plugin specific example for easier understanding of the problem, but the question is generic and plugin independent.</em></p>
[ { "answer_id": 315393, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>Yoast's SEO plugin has a <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">nice API</a>. You can probably get this with a filter like </p>\n\n<pre><code>add_filter( 'wpseo_options', function ( $arr ) {\n return $arr;\n} );\n</code></pre>\n" }, { "answer_id": 315437, "author": "Josh Smith", "author_id": 29089, "author_profile": "https://wordpress.stackexchange.com/users/29089", "pm_score": 1, "selected": true, "text": "<p>Basically this is the answer I was looking for from this question: </p>\n\n<pre><code>function yoastVariableToTitle( $post_id ) {\n $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true );\n $title = strstr( $yoast_title, '%%', true );\n if ( empty( $title ) ) {\n $title = get_the_title( $post_id );\n }\n $wpseo_titles = get_option( 'wpseo_titles' );\n\n $sep_options = WPSEO_Option_Titles::get_instance()-&gt;get_separator_options();\n if ( isset( $wpseo_titles['separator'] ) &amp;&amp; isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {\n $sep = $sep_options[ $wpseo_titles['separator'] ];\n } else {\n $sep = '-'; //setting default separator if Admin didn't set it from backed\n }\n\n $site_title = get_bloginfo( 'name' );\n\n $meta_title = $title . ' ' . $sep . ' ' . $site_title;\n\n return $meta_title;\n} \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti\">https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti</a></p>\n" }, { "answer_id": 332369, "author": "baskin", "author_id": 163582, "author_profile": "https://wordpress.stackexchange.com/users/163582", "pm_score": 2, "selected": false, "text": "<p>Ok here is how I parsed the snippets in case anyone else needs to know</p>\n\n<pre><code>$id = get_the_ID();\n\n$post = get_post( $id, ARRAY_A );\n$yoast_title = get_post_meta( $id, '_yoast_wpseo_title', true );\n$yoast_desc = get_post_meta( $id, '_yoast_wpseo_metadesc', true );\n\n$metatitle_val = wpseo_replace_vars($yoast_title, $post );\n$metatitle_val = apply_filters( 'wpseo_title', $metatitle_val );\n\n$metadesc_val = wpseo_replace_vars($yoast_desc, $post );\n$metadesc_val = apply_filters( 'wpseo_metadesc', $metadesc_val );\n\necho $metatitle_val;\necho \"&lt;br&gt;\";\necho $metadesc_val;\n</code></pre>\n" } ]
2018/09/28
[ "https://wordpress.stackexchange.com/questions/315399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122123/" ]
To increase the loading speed, I would like to only enable Event Manager plugin on the pages where it's actually used. For that, I wrote this piece of code: ``` // deregister unnecessary plugin scripts: function my_deregister() { if ( !is_page('events') ) { wp_deregister_script( 'events-manager' ); } } add_action( 'wp_print_scripts', 'my_deregister', 100 ); ``` However, the problem is that this event plugin creates a single page for each event and it needs to be enabled on those sub-pages, too. Apparently, each generated page is named differently. For instance, **www.mysite.com/events/EventNameEventDate**. So I would like to have the plugin disabled on all pages except for 'events' and its sub-pages (of which I will obviously not always know the count and names). The **is\_page()** works fine for the Events page but how do I modify it so that it recognises its sub-pages and enables the plugin scripts on them, too? *This was just a plugin specific example for easier understanding of the problem, but the question is generic and plugin independent.*
Basically this is the answer I was looking for from this question: ``` function yoastVariableToTitle( $post_id ) { $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true ); $title = strstr( $yoast_title, '%%', true ); if ( empty( $title ) ) { $title = get_the_title( $post_id ); } $wpseo_titles = get_option( 'wpseo_titles' ); $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options(); if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) { $sep = $sep_options[ $wpseo_titles['separator'] ]; } else { $sep = '-'; //setting default separator if Admin didn't set it from backed } $site_title = get_bloginfo( 'name' ); $meta_title = $title . ' ' . $sep . ' ' . $site_title; return $meta_title; } ``` <https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti>
315,406
<p>I have a website it's contains a lot of news, i have to list this news in one PHP file , now i want to insert each news in wordPress as a Post.. what is the best practice way to do that (the news are more than 100 articles) , how can i build manually the XML file so i can import it in WordPress ? or what is the post insert function , so i can call it in PHP file ..?</p> <p>the news are here : <a href="https://www.steuerlex24.de/steuerkanzlei-koerfer/information_steuer-news" rel="nofollow noreferrer">https://www.steuerlex24.de/steuerkanzlei-koerfer/information_steuer-news</a></p> <p>there is an API to export the news in XML file.</p> <p>Thanks a lot</p>
[ { "answer_id": 315393, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>Yoast's SEO plugin has a <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">nice API</a>. You can probably get this with a filter like </p>\n\n<pre><code>add_filter( 'wpseo_options', function ( $arr ) {\n return $arr;\n} );\n</code></pre>\n" }, { "answer_id": 315437, "author": "Josh Smith", "author_id": 29089, "author_profile": "https://wordpress.stackexchange.com/users/29089", "pm_score": 1, "selected": true, "text": "<p>Basically this is the answer I was looking for from this question: </p>\n\n<pre><code>function yoastVariableToTitle( $post_id ) {\n $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true );\n $title = strstr( $yoast_title, '%%', true );\n if ( empty( $title ) ) {\n $title = get_the_title( $post_id );\n }\n $wpseo_titles = get_option( 'wpseo_titles' );\n\n $sep_options = WPSEO_Option_Titles::get_instance()-&gt;get_separator_options();\n if ( isset( $wpseo_titles['separator'] ) &amp;&amp; isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {\n $sep = $sep_options[ $wpseo_titles['separator'] ];\n } else {\n $sep = '-'; //setting default separator if Admin didn't set it from backed\n }\n\n $site_title = get_bloginfo( 'name' );\n\n $meta_title = $title . ' ' . $sep . ' ' . $site_title;\n\n return $meta_title;\n} \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti\">https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti</a></p>\n" }, { "answer_id": 332369, "author": "baskin", "author_id": 163582, "author_profile": "https://wordpress.stackexchange.com/users/163582", "pm_score": 2, "selected": false, "text": "<p>Ok here is how I parsed the snippets in case anyone else needs to know</p>\n\n<pre><code>$id = get_the_ID();\n\n$post = get_post( $id, ARRAY_A );\n$yoast_title = get_post_meta( $id, '_yoast_wpseo_title', true );\n$yoast_desc = get_post_meta( $id, '_yoast_wpseo_metadesc', true );\n\n$metatitle_val = wpseo_replace_vars($yoast_title, $post );\n$metatitle_val = apply_filters( 'wpseo_title', $metatitle_val );\n\n$metadesc_val = wpseo_replace_vars($yoast_desc, $post );\n$metadesc_val = apply_filters( 'wpseo_metadesc', $metadesc_val );\n\necho $metatitle_val;\necho \"&lt;br&gt;\";\necho $metadesc_val;\n</code></pre>\n" } ]
2018/09/28
[ "https://wordpress.stackexchange.com/questions/315406", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151424/" ]
I have a website it's contains a lot of news, i have to list this news in one PHP file , now i want to insert each news in wordPress as a Post.. what is the best practice way to do that (the news are more than 100 articles) , how can i build manually the XML file so i can import it in WordPress ? or what is the post insert function , so i can call it in PHP file ..? the news are here : <https://www.steuerlex24.de/steuerkanzlei-koerfer/information_steuer-news> there is an API to export the news in XML file. Thanks a lot
Basically this is the answer I was looking for from this question: ``` function yoastVariableToTitle( $post_id ) { $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true ); $title = strstr( $yoast_title, '%%', true ); if ( empty( $title ) ) { $title = get_the_title( $post_id ); } $wpseo_titles = get_option( 'wpseo_titles' ); $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options(); if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) { $sep = $sep_options[ $wpseo_titles['separator'] ]; } else { $sep = '-'; //setting default separator if Admin didn't set it from backed } $site_title = get_bloginfo( 'name' ); $meta_title = $title . ' ' . $sep . ' ' . $site_title; return $meta_title; } ``` <https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti>