qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
343,563
<p>I have tried adding a file inside my <code>header.php</code>, but it will not load correctly. I get this error:</p> <blockquote> <p>Fatal error: Uncaught Error: Call to undefined function get_tempalte_part()</p> </blockquote> <p>Here is my markup in my <code>header.php</code>:</p> <pre><code>&lt;html class="m-0"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;title&gt;*TITLE*&lt;/title&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt; &gt; &lt;section id="header" class="container-fluid no-gutters"&gt; &lt;?php if( is_page( 'blog' ) ) { get_template_part( 'inc/fd-', 'blog' ); } else { get_tempalte_part( 'inc/fd-', 'default' ); } ?&gt; &lt;?php if( is_search() ) { fd_title_search(); } else if( is_product() || is_account_page() || is_page( 'contact-us' ) || is_page( 'shipping' ) || is_page( 'privacy' ) || is_page( 'terms' ) || is_page( 'faq' ) || is_page( 'about-us' ) || is_page( 'home' ) ) { echo ''; } else if( is_product_category() ) { fd_title_product_category(); } else if( is_shop() ) { fd_title_shop(); } else if( is_page( 'wishlist' ) ) { fd_title_wishlist(); } else { fd_title_default(); } ?&gt; &lt;/section&gt; </code></pre> <p>I am trying to load <code>fd-blog.php</code> if it is the 'Blog' page, otherwise load the <code>fd-default.php</code>, but I keep getting an error, no matter what I try! What am I doing wrong?</p>
[ { "answer_id": 343564, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You've spelt it wrong: <code>get_tempalte_part</code>, \"tempalte\", needs to be <code>get_template_part()</code>.</p>\n" }, { "answer_id": 343566, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>This is just a supplement to the other answer.</p>\n\n<blockquote>\n <p>I am trying to load <code>fd-blog.php</code> if it is the 'Blog' page, otherwise\n load the <code>fd-default.php</code></p>\n</blockquote>\n\n<p>To actually load the template file, you should remove the dash (<code>-</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>get_template_part( 'inc/fd', 'blog' ); // loads inc/fd-blog.php\nget_template_part( 'inc/fd', 'default' ); // loads inc/fd-default.php\n</code></pre>\n\n<p>So just <code>inc/fd</code>, and here's the relevant code in <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example when you call get_template_part( 'inc/fd', 'blog' ), $name below is 'blog'.\nif ( '' !== $name ) {\n $templates[] = \"{$slug}-{$name}.php\";\n}\n</code></pre>\n" } ]
2019/07/24
[ "https://wordpress.stackexchange.com/questions/343563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124452/" ]
I have tried adding a file inside my `header.php`, but it will not load correctly. I get this error: > > Fatal error: Uncaught Error: Call to undefined function > get\_tempalte\_part() > > > Here is my markup in my `header.php`: ``` <html class="m-0"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>*TITLE*</title> <?php wp_head(); ?> </head> <body <?php body_class(); ?> > <section id="header" class="container-fluid no-gutters"> <?php if( is_page( 'blog' ) ) { get_template_part( 'inc/fd-', 'blog' ); } else { get_tempalte_part( 'inc/fd-', 'default' ); } ?> <?php if( is_search() ) { fd_title_search(); } else if( is_product() || is_account_page() || is_page( 'contact-us' ) || is_page( 'shipping' ) || is_page( 'privacy' ) || is_page( 'terms' ) || is_page( 'faq' ) || is_page( 'about-us' ) || is_page( 'home' ) ) { echo ''; } else if( is_product_category() ) { fd_title_product_category(); } else if( is_shop() ) { fd_title_shop(); } else if( is_page( 'wishlist' ) ) { fd_title_wishlist(); } else { fd_title_default(); } ?> </section> ``` I am trying to load `fd-blog.php` if it is the 'Blog' page, otherwise load the `fd-default.php`, but I keep getting an error, no matter what I try! What am I doing wrong?
This is just a supplement to the other answer. > > I am trying to load `fd-blog.php` if it is the 'Blog' page, otherwise > load the `fd-default.php` > > > To actually load the template file, you should remove the dash (`-`): ```php get_template_part( 'inc/fd', 'blog' ); // loads inc/fd-blog.php get_template_part( 'inc/fd', 'default' ); // loads inc/fd-default.php ``` So just `inc/fd`, and here's the relevant code in [get\_template\_part](https://developer.wordpress.org/reference/functions/get_template_part/): ```php // Example when you call get_template_part( 'inc/fd', 'blog' ), $name below is 'blog'. if ( '' !== $name ) { $templates[] = "{$slug}-{$name}.php"; } ```
343,595
<p>I have copied a wordpress instance from production to my local. After getting the public side of the site up - public homepage, pages, and blog posts -, I cannot access /wp-admin/ because that url always redirects to the / homepage. I have tried:</p> <ul> <li>Updating the siteurl and home to "<a href="https://tk.local" rel="nofollow noreferrer">https://tk.local</a>" (homepage and posts work fine)</li> <li>Implementing a local self-signed ssl cert (in case it was an https problem.)</li> <li>Switched to 2019 theme (theme works, but problem still persists)</li> <li>Setting debug constants in wp-config.php </li> <li>Removing debug constants in wp-config.php</li> <li>Moved the plugins directory aside, replaced with /plugins containing only index.php</li> </ul> <p>Here is a curl of wp-admin:</p> <pre><code>curl -Ik https://tk.local/wp-admin/ HTTP/1.1 301 Moved Permanently Server: nginx/1.16.0 Date: Wed, 24 Jul 2019 17:27:39 GMT Content-Type: text/html; charset=UTF-8 Connection: keep-alive X-Powered-By: PHP/5.6.40 X-Redirect-By: WordPress Location: https://tk.local/ Last-Modified: Wed, 24 Jul 2019 17:27:39 GMT Expires: Wed, 24 Jul 2019 18:27:39 GMT Pragma: public Cache-Control: max-age=3600, public ETag: "d41d8cd98f00b204e9800998ecf8427e" Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: DENY X-Content-Type-Options: nosniff X-uri: /wp-admin/ </code></pre> <p>Obviously on the production copy the wp-admin url works. Throughout it all, it 301 redirects from <code>https://tk.local/wp-admin to https://tk.local/</code> How can I prevent it from redirecting?</p>
[ { "answer_id": 343946, "author": "Justin Waulters", "author_id": 137235, "author_profile": "https://wordpress.stackexchange.com/users/137235", "pm_score": 1, "selected": false, "text": "<p>Please try going into the local database and looking in the <code>options</code> table for the home and site url. Make sure these values correctly reference the local site URL.</p>\n\n<p>Alternatively, in your local wp-config.php file you could try defining the home and site url constants like this:</p>\n\n<pre><code>define( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n</code></pre>\n" }, { "answer_id": 343950, "author": "Kzqai", "author_id": 38029, "author_profile": "https://wordpress.stackexchange.com/users/38029", "pm_score": 3, "selected": true, "text": "<p>In my case, it ended up being some kind of adverse interaction in the nginx wordpress config that I had. Something about not passing along the naked arguments:</p>\n\n<pre><code> location / {\noriginal line: try_files $uri @php;\nnew line: try_files $uri $uri/ /index.php?$args;\n }\n</code></pre>\n\n<p>And the associated upstream was wrong. Used the config suggested here: <a href=\"https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/\" rel=\"nofollow noreferrer\">https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/</a>\nFor a simpler wordpress nginx config and that solved it.</p>\n" }, { "answer_id": 343973, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 1, "selected": false, "text": "<ul>\n<li><p>Look into <code>.htaccess</code>, there might be set some specific urls/directories, which you might need to remove/change, like:</p>\n\n<p>RewriteBase /subdir/</p></li>\n<li><p>Also, in phpmyadmin, check <code>wp-options</code> first and second rows, there should be needed similarly modified site-url .</p></li>\n<li><p>If MultiSite, then change that in <code>wp-config</code> too.</p></li>\n</ul>\n" } ]
2019/07/24
[ "https://wordpress.stackexchange.com/questions/343595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38029/" ]
I have copied a wordpress instance from production to my local. After getting the public side of the site up - public homepage, pages, and blog posts -, I cannot access /wp-admin/ because that url always redirects to the / homepage. I have tried: * Updating the siteurl and home to "<https://tk.local>" (homepage and posts work fine) * Implementing a local self-signed ssl cert (in case it was an https problem.) * Switched to 2019 theme (theme works, but problem still persists) * Setting debug constants in wp-config.php * Removing debug constants in wp-config.php * Moved the plugins directory aside, replaced with /plugins containing only index.php Here is a curl of wp-admin: ``` curl -Ik https://tk.local/wp-admin/ HTTP/1.1 301 Moved Permanently Server: nginx/1.16.0 Date: Wed, 24 Jul 2019 17:27:39 GMT Content-Type: text/html; charset=UTF-8 Connection: keep-alive X-Powered-By: PHP/5.6.40 X-Redirect-By: WordPress Location: https://tk.local/ Last-Modified: Wed, 24 Jul 2019 17:27:39 GMT Expires: Wed, 24 Jul 2019 18:27:39 GMT Pragma: public Cache-Control: max-age=3600, public ETag: "d41d8cd98f00b204e9800998ecf8427e" Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: DENY X-Content-Type-Options: nosniff X-uri: /wp-admin/ ``` Obviously on the production copy the wp-admin url works. Throughout it all, it 301 redirects from `https://tk.local/wp-admin to https://tk.local/` How can I prevent it from redirecting?
In my case, it ended up being some kind of adverse interaction in the nginx wordpress config that I had. Something about not passing along the naked arguments: ``` location / { original line: try_files $uri @php; new line: try_files $uri $uri/ /index.php?$args; } ``` And the associated upstream was wrong. Used the config suggested here: <https://www.nginx.com/resources/wiki/start/topics/recipes/wordpress/> For a simpler wordpress nginx config and that solved it.
343,598
<p><a href="https://developers.google.com/tag-manager/quickstart" rel="nofollow noreferrer">GTM documentation</a> says to include two snippets, 1 after <code>&lt;head&gt;</code> opening tag and 1 after <code>&lt;body&gt;</code> opening tag. Initially I was adding the snippets in my child's header.php file. I wanted to drop that method and use plain JS instead, mainly because of parent theme updates.</p> <p>I wrote the code below to use in functions.php, but it doesn't work and I can't figure what I'm doing wrong. </p> <p><strong>Edit</strong> : error I'm getting is <code>Uncaught TypeError: Cannot read property 'insertBefore' of null</code> for <code>document.body.insertBefore(el, document.body.firstChild);</code></p> <pre><code>&lt;?php add_action( 'wp_head', 'webplus_hook_gtm' ); function webplus_hook_gtm() { ?&gt; &lt;script type="text/javascript"&gt; var para = document.createElement("script"); var t = document.createTextNode( "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-XXXX');" ); para.appendChild(t); document.head.insertBefore(para, document.head.firstChild); var el = document.createElement("noscript"); var ifrm = document.createElement("iframe"); ifrm.setAttribute( "src", "https://www.googletagmanager.com/ns.html?id=GTM-XXXX" ); ifrm.setAttribute("height", "0"); ifrm.setAttribute("width", "0"); ifrm.setAttribute("style", "display:none;visibility:hidden"); el.appendChild(ifrm); document.body.insertBefore(el, document.body.firstChild); &lt;/script&gt; &lt;?php }; </code></pre> <p>Your help would be greatly appreciated, TIA.</p>
[ { "answer_id": 343620, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>The problem is that your code is inside the <code>&lt;head&gt;</code> element, but the code is trying to access <code>document.body</code> which won't exist at the time that your script is run. If I recall correctly you're <em>supposed</em> to place this code immediately after the opening <code>&lt;body&gt;</code> tag. To do this from functions.php your theme needs to support the <a href=\"https://make.wordpress.org/themes/2019/03/29/addition-of-new-wp_body_open-hook/\" rel=\"nofollow noreferrer\">new <code>wp_body_open()</code> hook</a>.</p>\n\n<p><strong>header.php:</strong></p>\n\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n&lt;?php wp_body_open(); ?&gt;\n</code></pre>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>add_action( 'wp_body_open', 'webplus_hook_gtm' );\n</code></pre>\n" }, { "answer_id": 343662, "author": "JackLinkers", "author_id": 135723, "author_profile": "https://wordpress.stackexchange.com/users/135723", "pm_score": 0, "selected": false, "text": "<p>Thanks for all your contributions which helped me to understand my mistake and solve my issue, especially @Krzysiek Dróżdż for the hint and @Jacob for partial solution with the action. This is my working final code :</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> &lt;?php\n\n add_action( 'wp_head', 'webplus_hook_gtm' );\n function webplus_hook_gtm() {\n ?&gt;\n &lt;script&gt;\n var para = document.createElement(\"script\");\n var t = document.createTextNode(\n \"(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-XXXX');\"\n );\n para.appendChild(t);\n document.head.insertBefore(para, document.head.firstChild);\n &lt;/script&gt;\n &lt;?php\n };\n\n add_action( 'wp_body_open', 'webplus_hook_gtm_noscript' );\n function webplus_hook_gtm_noscript() {\n ?&gt;\n &lt;script&gt;\n var el = document.createElement(\"noscript\");\n var ifrm = document.createElement(\"iframe\");\n ifrm.setAttribute(\n \"src\",\n \"https://www.googletagmanager.com/ns.html?id=GTM-XXXX\"\n );\n ifrm.setAttribute(\"height\", \"0\");\n ifrm.setAttribute(\"width\", \"0\");\n ifrm.setAttribute(\"style\", \"display:none;visibility:hidden\");\n el.appendChild(ifrm);\n document.body.insertBefore(el, document.body.firstChild);\n &lt;/script&gt;\n &lt;?php\n };\n</code></pre>\n" } ]
2019/07/24
[ "https://wordpress.stackexchange.com/questions/343598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135723/" ]
[GTM documentation](https://developers.google.com/tag-manager/quickstart) says to include two snippets, 1 after `<head>` opening tag and 1 after `<body>` opening tag. Initially I was adding the snippets in my child's header.php file. I wanted to drop that method and use plain JS instead, mainly because of parent theme updates. I wrote the code below to use in functions.php, but it doesn't work and I can't figure what I'm doing wrong. **Edit** : error I'm getting is `Uncaught TypeError: Cannot read property 'insertBefore' of null` for `document.body.insertBefore(el, document.body.firstChild);` ``` <?php add_action( 'wp_head', 'webplus_hook_gtm' ); function webplus_hook_gtm() { ?> <script type="text/javascript"> var para = document.createElement("script"); var t = document.createTextNode( "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-XXXX');" ); para.appendChild(t); document.head.insertBefore(para, document.head.firstChild); var el = document.createElement("noscript"); var ifrm = document.createElement("iframe"); ifrm.setAttribute( "src", "https://www.googletagmanager.com/ns.html?id=GTM-XXXX" ); ifrm.setAttribute("height", "0"); ifrm.setAttribute("width", "0"); ifrm.setAttribute("style", "display:none;visibility:hidden"); el.appendChild(ifrm); document.body.insertBefore(el, document.body.firstChild); </script> <?php }; ``` Your help would be greatly appreciated, TIA.
The problem is that your code is inside the `<head>` element, but the code is trying to access `document.body` which won't exist at the time that your script is run. If I recall correctly you're *supposed* to place this code immediately after the opening `<body>` tag. To do this from functions.php your theme needs to support the [new `wp_body_open()` hook](https://make.wordpress.org/themes/2019/03/29/addition-of-new-wp_body_open-hook/). **header.php:** ``` <body <?php body_class(); ?>> <?php wp_body_open(); ?> ``` **functions.php** ``` add_action( 'wp_body_open', 'webplus_hook_gtm' ); ```
343,673
<p>It almost work correctly, but alwas return the same menu name: On home all menu elements name home on contact all menu elements name contact</p> <pre><code>function max_title_length( $title ) { global $post; $id = ($post-&gt;ID); $title = get_post( $id )-&gt;post_title; $max = 20; if( strlen( $title ) &gt; $max ) { return substr( $title, 0, $max ). " &amp;hellip;"; } else { return $title; } } add_filter( 'the_title', 'max_title_length'); </code></pre>
[ { "answer_id": 343676, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>It's because you're not using the filter correctly. The <code>the_title</code> filter passes the title to be filtered as the <code>$title</code> argument, but you're overwriting it with this code:</p>\n\n<pre><code>global $post;\n$id = ($post-&gt;ID);\n$title = get_post( $id )-&gt;post_title;\n</code></pre>\n\n<p>That code's completely unnecessary because the title is already available in your function:</p>\n\n<pre><code>function max_title_length( $title ) {\n</code></pre>\n\n<p>So simply remove those lines to filter the correct title:</p>\n\n<pre><code>function max_title_length( $title ) {\n $max = 20;\n\n if ( strlen( $title ) &gt; $max ) {\n return substr( $title, 0, $max ) . ' &amp;hellip;'; \n } else {\n return $title;\n }\n}\nadd_filter( 'the_title', 'max_title_length' );\n</code></pre>\n\n<p>Just be aware that &mdash; as you've experienced &mdash; the <code>the_title</code> filter applies to all titles, including posts, pages, and <em>menu items</em>. So if you only want your code to apply to titles output within The Loop, you can use the <code>in_the_loop()</code> function:</p>\n\n<pre><code>function max_title_length( $title ) {\n $max = 20;\n\n if ( in_the_loop() &amp;&amp; strlen( $title ) &gt; $max ) {\n return substr( $title, 0, $max ) . ' &amp;hellip;'; \n } else {\n return $title;\n }\n}\nadd_filter( 'the_title', 'max_title_length' );\n</code></pre>\n" }, { "answer_id": 343760, "author": "DenFunk", "author_id": 172538, "author_profile": "https://wordpress.stackexchange.com/users/172538", "pm_score": -1, "selected": false, "text": "<pre><code>function max_title_length( $title ) { \n $max = 20;\n if ( strlen( $title ) &gt; $max ) {\n $title = substr( $title, 0, $max ) . ' &amp;hellip;'; \n }\n return $title;\n}\nadd_filter( 'the_title', 'max_title_length' );\n</code></pre>\n" }, { "answer_id": 343978, "author": "ncti", "author_id": 171954, "author_profile": "https://wordpress.stackexchange.com/users/171954", "pm_score": 0, "selected": false, "text": "<pre><code>function max_title_length($title) {\n if(is_front_page()){\n $max = 8; \n }\n elseif(is_single()){\n $max = 5;\n }\n else{\n $max = 15;\n }\n\n\n if (strlen( $title ) &gt; $max ) {\n return substr( $title, 0, $max ) . ' &amp;hellip;'; \n } else {\n return $title;\n }\n}\nadd_filter( 'the_title', 'max_title_length' );\n</code></pre>\n\n<p>it still cut the menu title. in_the_loop() function not working.</p>\n" } ]
2019/07/25
[ "https://wordpress.stackexchange.com/questions/343673", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171954/" ]
It almost work correctly, but alwas return the same menu name: On home all menu elements name home on contact all menu elements name contact ``` function max_title_length( $title ) { global $post; $id = ($post->ID); $title = get_post( $id )->post_title; $max = 20; if( strlen( $title ) > $max ) { return substr( $title, 0, $max ). " &hellip;"; } else { return $title; } } add_filter( 'the_title', 'max_title_length'); ```
It's because you're not using the filter correctly. The `the_title` filter passes the title to be filtered as the `$title` argument, but you're overwriting it with this code: ``` global $post; $id = ($post->ID); $title = get_post( $id )->post_title; ``` That code's completely unnecessary because the title is already available in your function: ``` function max_title_length( $title ) { ``` So simply remove those lines to filter the correct title: ``` function max_title_length( $title ) { $max = 20; if ( strlen( $title ) > $max ) { return substr( $title, 0, $max ) . ' &hellip;'; } else { return $title; } } add_filter( 'the_title', 'max_title_length' ); ``` Just be aware that — as you've experienced — the `the_title` filter applies to all titles, including posts, pages, and *menu items*. So if you only want your code to apply to titles output within The Loop, you can use the `in_the_loop()` function: ``` function max_title_length( $title ) { $max = 20; if ( in_the_loop() && strlen( $title ) > $max ) { return substr( $title, 0, $max ) . ' &hellip;'; } else { return $title; } } add_filter( 'the_title', 'max_title_length' ); ```
343,778
<p>So this is not a transferrable question to other sites out there, but I am creating a Wordpress multisite for internal use at our office and instead of duplicating the theme CSS, JS, and other assets I created it all into one MU-Plugin.</p> <p>I know this is not standard practice, but I am the only one managing the sites, and it is more a set up and forget.</p> <p>At the moment I am currently calling on a <code>base.css</code> that has some normalisation and then any unique css is being called from:</p> <pre><code>$themeName = wp_get_theme()-&gt;get('TextDomain'); $themeName = get_template(); wp_enqueue_style( 'solo_css', network_home_url( $themeName . '.css'), array( 'main_css' ), globalVersion ); </code></pre> <p>However, because I am manually doing al this, and hoping to expand the multisite soon to other ventures internally I don't want to create a <code>solo_css</code> file for each of the new sites.</p> <p>Is there a way to create the file in the plugin folder on theme activation? Again, I know it's not recommended practices or transferable, but something make the repetitive nature easier.</p>
[ { "answer_id": 343786, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": 1, "selected": false, "text": "<p>Take a look at <code>after_switch_theme</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>But I would use hooks to insert the css for example in <code>wp_head</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory\" rel=\"nofollow noreferrer\">This link</a> helps you get the directory of the theme, so you can create the css afterwards.</p>\n" }, { "answer_id": 343836, "author": "markb", "author_id": 17411, "author_profile": "https://wordpress.stackexchange.com/users/17411", "pm_score": 1, "selected": true, "text": "<p>@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was).</p>\n\n<pre><code>function default_css_dir() { \n $themeName = wp_get_theme()-&gt;get('TextDomain');\n $themeName = get_template();\n $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' );\n\n if( !file_exists($cssPathway) ) {\n $fileCSS = fopen( $cssPathway, 'wb' );\n fwrite( $fileCSS, '' );\n fclose( $fileCSS );\n }\n}\n</code></pre>\n\n<p>Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.</p>\n" } ]
2019/07/27
[ "https://wordpress.stackexchange.com/questions/343778", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17411/" ]
So this is not a transferrable question to other sites out there, but I am creating a Wordpress multisite for internal use at our office and instead of duplicating the theme CSS, JS, and other assets I created it all into one MU-Plugin. I know this is not standard practice, but I am the only one managing the sites, and it is more a set up and forget. At the moment I am currently calling on a `base.css` that has some normalisation and then any unique css is being called from: ``` $themeName = wp_get_theme()->get('TextDomain'); $themeName = get_template(); wp_enqueue_style( 'solo_css', network_home_url( $themeName . '.css'), array( 'main_css' ), globalVersion ); ``` However, because I am manually doing al this, and hoping to expand the multisite soon to other ventures internally I don't want to create a `solo_css` file for each of the new sites. Is there a way to create the file in the plugin folder on theme activation? Again, I know it's not recommended practices or transferable, but something make the repetitive nature easier.
@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was). ``` function default_css_dir() { $themeName = wp_get_theme()->get('TextDomain'); $themeName = get_template(); $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' ); if( !file_exists($cssPathway) ) { $fileCSS = fopen( $cssPathway, 'wb' ); fwrite( $fileCSS, '' ); fclose( $fileCSS ); } } ``` Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.
343,841
<p>I have multi author wordpress site and every author can publish posts from two different post types . i want to display author post count by post type in author.php . According to codex.wordpress i used this code: but it displays total post count instead of author post count.</p> <pre><code>&lt;?php echo 'Number of posts published by user: ' . count_user_posts( $userid , "book" ); ?&gt; </code></pre>
[ { "answer_id": 343786, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": 1, "selected": false, "text": "<p>Take a look at <code>after_switch_theme</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>But I would use hooks to insert the css for example in <code>wp_head</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory\" rel=\"nofollow noreferrer\">This link</a> helps you get the directory of the theme, so you can create the css afterwards.</p>\n" }, { "answer_id": 343836, "author": "markb", "author_id": 17411, "author_profile": "https://wordpress.stackexchange.com/users/17411", "pm_score": 1, "selected": true, "text": "<p>@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was).</p>\n\n<pre><code>function default_css_dir() { \n $themeName = wp_get_theme()-&gt;get('TextDomain');\n $themeName = get_template();\n $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' );\n\n if( !file_exists($cssPathway) ) {\n $fileCSS = fopen( $cssPathway, 'wb' );\n fwrite( $fileCSS, '' );\n fclose( $fileCSS );\n }\n}\n</code></pre>\n\n<p>Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.</p>\n" } ]
2019/07/28
[ "https://wordpress.stackexchange.com/questions/343841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172323/" ]
I have multi author wordpress site and every author can publish posts from two different post types . i want to display author post count by post type in author.php . According to codex.wordpress i used this code: but it displays total post count instead of author post count. ``` <?php echo 'Number of posts published by user: ' . count_user_posts( $userid , "book" ); ?> ```
@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was). ``` function default_css_dir() { $themeName = wp_get_theme()->get('TextDomain'); $themeName = get_template(); $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' ); if( !file_exists($cssPathway) ) { $fileCSS = fopen( $cssPathway, 'wb' ); fwrite( $fileCSS, '' ); fclose( $fileCSS ); } } ``` Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.
343,850
<p>New to MAMP, but had no issues with installation and viewing the WordPress site I pulled down from my server. However, can’t figure out to log into the admin side of my site. Here’s what I’ve tried, and the results:</p> <p>Setting: Web Server > Document Root > Sites</p> <ol> <li><p>localhost:8888 = displays website with no issues </p></li> <li><p><a href="http://localhost:8888/wp-admin/" rel="nofollow noreferrer">http://localhost:8888/wp-admin/</a> = Not Found page</p></li> <li><p>Both localhost:8888/mysitename/wp-admin/ and <a href="http://localhost:8888/mysitename/wp-admin" rel="nofollow noreferrer">http://localhost:8888/mysitename/wp-admin</a> redirects to <a href="https://localhost:8888/mysitename/wp-admin/" rel="nofollow noreferrer">https://localhost:8888/mysitename/wp-admin/</a> then Secure Connection Failed An error occurred during a connection to localhost:8888. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG</p></li> </ol> <p>Everything I’ve read makes it sound easier than this. What am I missing?</p>
[ { "answer_id": 343786, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": 1, "selected": false, "text": "<p>Take a look at <code>after_switch_theme</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>But I would use hooks to insert the css for example in <code>wp_head</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory\" rel=\"nofollow noreferrer\">This link</a> helps you get the directory of the theme, so you can create the css afterwards.</p>\n" }, { "answer_id": 343836, "author": "markb", "author_id": 17411, "author_profile": "https://wordpress.stackexchange.com/users/17411", "pm_score": 1, "selected": true, "text": "<p>@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was).</p>\n\n<pre><code>function default_css_dir() { \n $themeName = wp_get_theme()-&gt;get('TextDomain');\n $themeName = get_template();\n $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' );\n\n if( !file_exists($cssPathway) ) {\n $fileCSS = fopen( $cssPathway, 'wb' );\n fwrite( $fileCSS, '' );\n fclose( $fileCSS );\n }\n}\n</code></pre>\n\n<p>Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.</p>\n" } ]
2019/07/28
[ "https://wordpress.stackexchange.com/questions/343850", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153797/" ]
New to MAMP, but had no issues with installation and viewing the WordPress site I pulled down from my server. However, can’t figure out to log into the admin side of my site. Here’s what I’ve tried, and the results: Setting: Web Server > Document Root > Sites 1. localhost:8888 = displays website with no issues 2. <http://localhost:8888/wp-admin/> = Not Found page 3. Both localhost:8888/mysitename/wp-admin/ and <http://localhost:8888/mysitename/wp-admin> redirects to <https://localhost:8888/mysitename/wp-admin/> then Secure Connection Failed An error occurred during a connection to localhost:8888. SSL received a record that exceeded the maximum permissible length. Error code: SSL\_ERROR\_RX\_RECORD\_TOO\_LONG Everything I’ve read makes it sound easier than this. What am I missing?
@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was). ``` function default_css_dir() { $themeName = wp_get_theme()->get('TextDomain'); $themeName = get_template(); $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' ); if( !file_exists($cssPathway) ) { $fileCSS = fopen( $cssPathway, 'wb' ); fwrite( $fileCSS, '' ); fclose( $fileCSS ); } } ``` Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.
343,936
<p>I want to add more links in my menu.</p> <p>duvacon.de ---> you see only the "categories", I want also add the links of my footer menu to the header.</p> <p>This code is for the header menu, now I want to add a link for "contact", "chat"... in the header</p> <pre><code>&lt;div class="menu"&gt; &lt;a class="btn"&gt;&lt;?php _e("Categories", "myfriv"); ?&gt; &lt;span class="icon icon-angle-down"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="actions"&gt; &lt;?php wp_list_categories('orderby=name&amp;title_li='); ?&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 343786, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": 1, "selected": false, "text": "<p>Take a look at <code>after_switch_theme</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>But I would use hooks to insert the css for example in <code>wp_head</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory\" rel=\"nofollow noreferrer\">This link</a> helps you get the directory of the theme, so you can create the css afterwards.</p>\n" }, { "answer_id": 343836, "author": "markb", "author_id": 17411, "author_profile": "https://wordpress.stackexchange.com/users/17411", "pm_score": 1, "selected": true, "text": "<p>@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was).</p>\n\n<pre><code>function default_css_dir() { \n $themeName = wp_get_theme()-&gt;get('TextDomain');\n $themeName = get_template();\n $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' );\n\n if( !file_exists($cssPathway) ) {\n $fileCSS = fopen( $cssPathway, 'wb' );\n fwrite( $fileCSS, '' );\n fclose( $fileCSS );\n }\n}\n</code></pre>\n\n<p>Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.</p>\n" } ]
2019/07/29
[ "https://wordpress.stackexchange.com/questions/343936", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172659/" ]
I want to add more links in my menu. duvacon.de ---> you see only the "categories", I want also add the links of my footer menu to the header. This code is for the header menu, now I want to add a link for "contact", "chat"... in the header ``` <div class="menu"> <a class="btn"><?php _e("Categories", "myfriv"); ?> <span class="icon icon-angle-down"></span></a> <ul class="actions"> <?php wp_list_categories('orderby=name&title_li='); ?> </ul> </div> ```
@Кристиян Кацаров is correct in the handling of when to do the function, but I ended up writing something that doesn't use any WP inbuilt functions (which I was hoping there was). ``` function default_css_dir() { $themeName = wp_get_theme()->get('TextDomain'); $themeName = get_template(); $cssPathway = ( ABSPATH . 'wp-content/plugins/pluginname/' . $ThemeName . '.css' ); if( !file_exists($cssPathway) ) { $fileCSS = fopen( $cssPathway, 'wb' ); fwrite( $fileCSS, '' ); fclose( $fileCSS ); } } ``` Again, won't work unless you're 100% sure it won't ever be altered, and the plugin will be active. But internally works wonders.
343,999
<p>I want to migrate my development wordpress site to the production domain. In order to success the migration I found and replace all previous url occurences (<a href="http://localhost" rel="nofollow noreferrer">http://localhost</a>) to the new (<a href="https://mywebsite.com" rel="nofollow noreferrer">https://mywebsite.com</a>). The problem is that old urls cannot be replaced directly in the field <code>option_value</code> of <code>theme_mods_{your theme name}</code> in the table <code>wp_options</code> because data in there are serialized. </p> <p>How can I replace old urls by the new without breaking theme settings ?</p>
[ { "answer_id": 344000, "author": "Louis D.", "author_id": 172615, "author_profile": "https://wordpress.stackexchange.com/users/172615", "pm_score": 1, "selected": true, "text": "<p>It's possible to search and replace old urls to new ones by using <code>maybe_unserialize(get_theme_mods())</code> and <code>get_theme_mod()</code> WP functions and following these steps:</p>\n\n<ol>\n<li>Create a php file in the root folder of your WP installation (same path as <code>wp-load.php</code>).</li>\n<li>Insert the following code :</li>\n</ol>\n\n<pre class=\"lang-php prettyprint-override\"><code>require_once(\"wp-load.php\");\n$r = maybe_unserialize(get_theme_mods());\nforeach ($r as $k =&gt; $v){\n if(!empty($k)){\n $ListOptions[] = $k;\n }\n}\nforeach($ListOptions as $option){\n $str = get_theme_mod($option);\n $str = str_replace('http://localhost', 'https://mywebsite.com', $str);\n $str = str_replace('http:\\\\/\\\\/localhost', 'https:\\\\/\\\\/mediadroit.fr', $str);\n set_theme_mod($option, $str);\n var_dump('|'.$option.': '.get_theme_mod($option).' ===&gt; '.$str);\n echo \"\\n\";\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>Execute the script</li>\n</ol>\n" }, { "answer_id": 344001, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Use the official CLI tool:</p>\n\n<pre><code>wp search-replace 'http://localhost' 'https://yoursitecom'\n</code></pre>\n\n<p>It will automatically deserialize any post meta, options, theme mods, etc and adjust them to match the new URL.</p>\n\n<p>Fundamentally though, it's bad practice to store URLs to images posts and assets in the database. Store the post ID instead, and this problem goes away</p>\n" } ]
2019/07/30
[ "https://wordpress.stackexchange.com/questions/343999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172615/" ]
I want to migrate my development wordpress site to the production domain. In order to success the migration I found and replace all previous url occurences (<http://localhost>) to the new (<https://mywebsite.com>). The problem is that old urls cannot be replaced directly in the field `option_value` of `theme_mods_{your theme name}` in the table `wp_options` because data in there are serialized. How can I replace old urls by the new without breaking theme settings ?
It's possible to search and replace old urls to new ones by using `maybe_unserialize(get_theme_mods())` and `get_theme_mod()` WP functions and following these steps: 1. Create a php file in the root folder of your WP installation (same path as `wp-load.php`). 2. Insert the following code : ```php require_once("wp-load.php"); $r = maybe_unserialize(get_theme_mods()); foreach ($r as $k => $v){ if(!empty($k)){ $ListOptions[] = $k; } } foreach($ListOptions as $option){ $str = get_theme_mod($option); $str = str_replace('http://localhost', 'https://mywebsite.com', $str); $str = str_replace('http:\\/\\/localhost', 'https:\\/\\/mediadroit.fr', $str); set_theme_mod($option, $str); var_dump('|'.$option.': '.get_theme_mod($option).' ===> '.$str); echo "\n"; } ``` 3. Execute the script
344,007
<p>I have my permalink structure for posts set up like this: <code>/%category%/%postname%/</code></p> <p>This generates URLs like this: <code>mysite.io/category/sub-category/post-name</code></p> <p>Thats all fine. However, the <strong>archive page</strong> URLs for <strong>sub</strong>categories are like this: <code>mysite.io/sub-category</code></p> <p>Instead, the URLs for <strong>sub</strong>categories should be like this: <code>mysite.io/category/sub-category</code></p> <p>This category type is actually a custom taxonomy registered by the parent theme. I don't think it is possible to use the permalink settings in the admin dashboard to change the URL structure of this but perhaps there is something I could add to the functions.php to alter the registered taxonomy?</p> <p>I have found this page in WordPress codex and think it might be useful for finding a solution but my WordPress knowledge seems way too limited to understand how: </p> <blockquote> <p>'hierarchical' - true or false allow hierarchical urls (implemented in Version 3.1) - defaults to false</p> </blockquote> <p><a href="https://codex.wordpress.org/Function_Reference/register_taxonomy" rel="nofollow noreferrer">Function Reference/register taxonomy</a></p> <p>Thanks in advance</p>
[ { "answer_id": 344287, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Is there some hook that I can use to alter a taxonomy that has already been registered?</p>\n</blockquote>\n\n<p>Yes, there is the <a href=\"https://developer.wordpress.org/reference/hooks/register_taxonomy_args/\" rel=\"nofollow noreferrer\">register_taxonomy_args</a> filter, which you can use to modify a registered taxonomy.</p>\n\n<pre><code>function prefix_register_taxonomy_args_my_taxonomy( $args, $taxonomy, $object_type ) { \n if ( 'my_taxonomy' !== $taxonomy ) {\n return $args;\n }\n\n $args['hierarchical'] = true; // have descendants, like categories\n\n if ( ! is_array( $args['rewrite'] ) ) {\n $args['rewrite'] = array(\n 'hierarchical' =&gt; true, // allow hierarchical urls, defaults to false\n )\n } \n\n return $args; \n}\nadd_filter( 'register_taxonomy_args', 'prefix_register_taxonomy_args_my_taxonomy', 10, 3 );\n</code></pre>\n" }, { "answer_id": 344289, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": true, "text": "<p>You answered your own question yourself.</p>\n\n<p>You want links to custom categories to look like this</p>\n\n<pre><code>{taxonomy_slug}/{parent_term}/{child_term}/{grandchild_term}/\n</code></pre>\n\n<p>so you should pay attention to two parameters in the <code>register_taxonomy()</code> arguments: <code>hierarchical</code> and <code>rewrite</code>.</p>\n\n<pre><code>$args = [\n 'hierarchical' =&gt; true, // &lt;-- term may have a parent\n 'labels' =&gt; $labels,\n 'rewrite' =&gt; [\n // hierarchical urls, defaults to FALSE\n 'hierarchical' =&gt; true, // &lt;-- \n ] \n];\n</code></pre>\n\n<p>Your custom taxonomy is created by the parent theme, so to change it, use the <a href=\"https://developer.wordpress.org/reference/hooks/register_taxonomy_args/\" rel=\"nofollow noreferrer\"><code>register_taxonomy_args</code></a> filter:</p>\n\n<pre><code>add_filter( 'register_taxonomy_args', 'se344007_mytax_args', 10, 2 );\nfunction se344007_mytax_args( $args, $taxonomy )\n{\n if ( 'mytax' !== $taxonomy ) {\n return $args;\n } \n // it looks like it's already set up by parent theme\n // $args['hierarchical'] = true;\n\n if ( !is_array($args['rewrite']) )\n $args['rewrite'] = [];\n $args['rewrite']['hierarchical'] = true;\n\n return $args; \n}\n</code></pre>\n\n<p>When you register custom taxonomy, the default link to term (custom category) \nis <code>{taxonomy_slug}/{child_term_slug}</code> even if taxonomy is hierarchical, because \nby default, the created links are not hierarchical ( $args['rewrite']['hierarchical'] = false ).</p>\n" }, { "answer_id": 385202, "author": "G3N", "author_id": 203463, "author_profile": "https://wordpress.stackexchange.com/users/203463", "pm_score": 0, "selected": false, "text": "<p>I was having the same problem,</p>\n<p><code>mysite.io/category/sub-category/post-name</code> is what I have for <code>post</code></p>\n<p><code>mysite.io/sub-category</code> is what I want to change</p>\n<p><code>mysite.io/category/sub-category</code> is what I want</p>\n<p>I bet you have put a <code>.</code> at the settings &gt; permalink optional section, remove it and leave it blank and save.\nNow install the plugin <code>No Category Base (WPML)</code> or <a href=\"https://wordpress.org/plugins/no-category-base-wpml/\" rel=\"nofollow noreferrer\">download it</a>.</p>\n<p>And now you can check your link.</p>\n<p>Hope everything works fine there.</p>\n" } ]
2019/07/30
[ "https://wordpress.stackexchange.com/questions/344007", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172709/" ]
I have my permalink structure for posts set up like this: `/%category%/%postname%/` This generates URLs like this: `mysite.io/category/sub-category/post-name` Thats all fine. However, the **archive page** URLs for **sub**categories are like this: `mysite.io/sub-category` Instead, the URLs for **sub**categories should be like this: `mysite.io/category/sub-category` This category type is actually a custom taxonomy registered by the parent theme. I don't think it is possible to use the permalink settings in the admin dashboard to change the URL structure of this but perhaps there is something I could add to the functions.php to alter the registered taxonomy? I have found this page in WordPress codex and think it might be useful for finding a solution but my WordPress knowledge seems way too limited to understand how: > > 'hierarchical' - true or false allow hierarchical urls (implemented > in Version 3.1) - defaults to false > > > [Function Reference/register taxonomy](https://codex.wordpress.org/Function_Reference/register_taxonomy) Thanks in advance
You answered your own question yourself. You want links to custom categories to look like this ``` {taxonomy_slug}/{parent_term}/{child_term}/{grandchild_term}/ ``` so you should pay attention to two parameters in the `register_taxonomy()` arguments: `hierarchical` and `rewrite`. ``` $args = [ 'hierarchical' => true, // <-- term may have a parent 'labels' => $labels, 'rewrite' => [ // hierarchical urls, defaults to FALSE 'hierarchical' => true, // <-- ] ]; ``` Your custom taxonomy is created by the parent theme, so to change it, use the [`register_taxonomy_args`](https://developer.wordpress.org/reference/hooks/register_taxonomy_args/) filter: ``` add_filter( 'register_taxonomy_args', 'se344007_mytax_args', 10, 2 ); function se344007_mytax_args( $args, $taxonomy ) { if ( 'mytax' !== $taxonomy ) { return $args; } // it looks like it's already set up by parent theme // $args['hierarchical'] = true; if ( !is_array($args['rewrite']) ) $args['rewrite'] = []; $args['rewrite']['hierarchical'] = true; return $args; } ``` When you register custom taxonomy, the default link to term (custom category) is `{taxonomy_slug}/{child_term_slug}` even if taxonomy is hierarchical, because by default, the created links are not hierarchical ( $args['rewrite']['hierarchical'] = false ).
344,009
<p>I have a function in the WordPress functions.php file that searches for a condition in user meta and sends an email to a user based on what it finds. I currently use wp_mail() to send the email, and that works. However, I want to use the included PHPMailer class to do this so that I can send the messages via SMTP.</p> <p>I thought I had a solution here: <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init" rel="nofollow noreferrer">https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init</a>, however, this seems to only apply to system generated messages, not for custom messages. </p> <p>At this point I'm just guessing, but I tried this, with no luck (WP stops loading right at this point, no error message):</p> <pre><code>function my_function() { //if things are found send an email global $phpmailer; $phpmailer-&gt;IsSMTP(); $phpmailer-&gt;Host = 'smtp.google.com'; $phpmailer-&gt;Port = '587'; $phpmailer-&gt;SMTPSecure = 'tls'; $phpmailer-&gt;SMTPAuth = true; $phpmailer-&gt;Username = '[email protected]'; $phpmailer-&gt;Password = '11111111'; $phpmailer-&gt;addAddress('[email protected]', 'Joe User'); $phpmailer-&gt;setFrom('[email protected]', 'Mailer'); $phpmailer-&gt;addReplyTo('[email protected]', 'Information'); $phpmailer-&gt;isHTML(true); $phpmailer-&gt;Subject = 'Here is the subject'; $phpmailer-&gt;Body = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; $phpmailer-&gt;send(); // Email sent; function over } </code></pre> <p>FYI, I call this function in the header. I'm not adding it as an action because I want to control where it is used. </p> <p>Is there a way to access the PHPMailer class directly from my function? I suppose i could load PHPMailer separately, but that seems silly. </p>
[ { "answer_id": 351194, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>There's no need to use the PHPMailer class in place of <code>wp_mail()</code>. <code>wp_mail()</code> is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message.</p>\n\n<p>You can access the PHPMailer elements when it is initialized in order to have <code>wp_mail()</code> send through SMTP instead of the web server.</p>\n\n<p>You said you're <em>not</em> adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it.</p>\n\n<p>In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init\" rel=\"nofollow noreferrer\"><code>phpmailer_init</code></a></p>\n\n<p>You can define your settings when PHPMailer is initialized using that hook:</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp_email' );\nfunction send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n</code></pre>\n\n<p>You want your message in HTML. You could set that in <code>wp_mail()</code>'s header argument, but you can/should use the <code>wp_mail_content_type</code> filter for that;</p>\n\n<pre><code>add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n</code></pre>\n\n<p>With your setup properly done, now you're all set to use <code>wp_mail()</code> to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template_redirect' so you do it before headers are sent downstream:</p>\n\n<pre><code>function my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n wp_mail( $to, $subject, $message );\n\n}\n</code></pre>\n\n<p><strong>Update: Alternate (Contained) Method:</strong></p>\n\n<p>So, extending what was outlined above, suppose some these settings are <strong>not</strong> what you ordinarily want for every firing of <code>wp_mail()</code> and that you only wanted these settings for a specific email.</p>\n\n<p>You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the <code>phpmailer_init</code> and <code>wp_mail_content_type</code> hooks are hit when <code>wp_mail()</code> is being run, you <em>could</em> set those hooks within your primary function, run your email, then remove them so you're back to the default.</p>\n\n<pre><code>function send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n\nfunction my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\n add_action( 'phpmailer_init', 'send_smtp_email' );\n\n wp_mail( $to, $subject, $message );\n\n remove_filter( 'wp_mail_content_type','set_my_mail_content_type' )\n remove_action( 'phpmailer_init', 'send_smtp_email' );\n\n}\n</code></pre>\n" }, { "answer_id": 363530, "author": "izaak", "author_id": 185681, "author_profile": "https://wordpress.stackexchange.com/users/185681", "pm_score": 2, "selected": false, "text": "<p>require 'wp-includes/class-phpmailer.php'; fixed my problem, but I used a code to create a pdf and then send it in the same way.</p>\n" } ]
2019/07/30
[ "https://wordpress.stackexchange.com/questions/344009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172712/" ]
I have a function in the WordPress functions.php file that searches for a condition in user meta and sends an email to a user based on what it finds. I currently use wp\_mail() to send the email, and that works. However, I want to use the included PHPMailer class to do this so that I can send the messages via SMTP. I thought I had a solution here: <https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init>, however, this seems to only apply to system generated messages, not for custom messages. At this point I'm just guessing, but I tried this, with no luck (WP stops loading right at this point, no error message): ``` function my_function() { //if things are found send an email global $phpmailer; $phpmailer->IsSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->addAddress('[email protected]', 'Joe User'); $phpmailer->setFrom('[email protected]', 'Mailer'); $phpmailer->addReplyTo('[email protected]', 'Information'); $phpmailer->isHTML(true); $phpmailer->Subject = 'Here is the subject'; $phpmailer->Body = 'This is the HTML message body <b>in bold!</b>'; $phpmailer->send(); // Email sent; function over } ``` FYI, I call this function in the header. I'm not adding it as an action because I want to control where it is used. Is there a way to access the PHPMailer class directly from my function? I suppose i could load PHPMailer separately, but that seems silly.
There's no need to use the PHPMailer class in place of `wp_mail()`. `wp_mail()` is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message. You can access the PHPMailer elements when it is initialized in order to have `wp_mail()` send through SMTP instead of the web server. You said you're *not* adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it. In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - [`phpmailer_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init) You can define your settings when PHPMailer is initialized using that hook: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } ``` You want your message in HTML. You could set that in `wp_mail()`'s header argument, but you can/should use the `wp_mail_content_type` filter for that; ``` add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); function set_my_mail_content_type() { return "text/html"; } ``` With your setup properly done, now you're all set to use `wp_mail()` to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template\_redirect' so you do it before headers are sent downstream: ``` function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; wp_mail( $to, $subject, $message ); } ``` **Update: Alternate (Contained) Method:** So, extending what was outlined above, suppose some these settings are **not** what you ordinarily want for every firing of `wp_mail()` and that you only wanted these settings for a specific email. You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the `phpmailer_init` and `wp_mail_content_type` hooks are hit when `wp_mail()` is being run, you *could* set those hooks within your primary function, run your email, then remove them so you're back to the default. ``` function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } function set_my_mail_content_type() { return "text/html"; } function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); add_action( 'phpmailer_init', 'send_smtp_email' ); wp_mail( $to, $subject, $message ); remove_filter( 'wp_mail_content_type','set_my_mail_content_type' ) remove_action( 'phpmailer_init', 'send_smtp_email' ); } ```
344,063
<p>I have a WordPress post which is accessible via domain.com/test/</p> <p>What I want to be able to do is pass in a parameter using the URL - ie going to domain.com/test/ would load the same page as domain.com/test/ - but in url show the /accommodation/value1/<strong>?m=1</strong> in the browser address bar.</p> <p>I guess another way of putting it would be to say I need to be able to access domain.com/test/ by adding <strong>?m=1</strong> like to the end of the URL.</p>
[ { "answer_id": 351194, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>There's no need to use the PHPMailer class in place of <code>wp_mail()</code>. <code>wp_mail()</code> is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message.</p>\n\n<p>You can access the PHPMailer elements when it is initialized in order to have <code>wp_mail()</code> send through SMTP instead of the web server.</p>\n\n<p>You said you're <em>not</em> adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it.</p>\n\n<p>In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init\" rel=\"nofollow noreferrer\"><code>phpmailer_init</code></a></p>\n\n<p>You can define your settings when PHPMailer is initialized using that hook:</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp_email' );\nfunction send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n</code></pre>\n\n<p>You want your message in HTML. You could set that in <code>wp_mail()</code>'s header argument, but you can/should use the <code>wp_mail_content_type</code> filter for that;</p>\n\n<pre><code>add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n</code></pre>\n\n<p>With your setup properly done, now you're all set to use <code>wp_mail()</code> to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template_redirect' so you do it before headers are sent downstream:</p>\n\n<pre><code>function my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n wp_mail( $to, $subject, $message );\n\n}\n</code></pre>\n\n<p><strong>Update: Alternate (Contained) Method:</strong></p>\n\n<p>So, extending what was outlined above, suppose some these settings are <strong>not</strong> what you ordinarily want for every firing of <code>wp_mail()</code> and that you only wanted these settings for a specific email.</p>\n\n<p>You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the <code>phpmailer_init</code> and <code>wp_mail_content_type</code> hooks are hit when <code>wp_mail()</code> is being run, you <em>could</em> set those hooks within your primary function, run your email, then remove them so you're back to the default.</p>\n\n<pre><code>function send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n\nfunction my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\n add_action( 'phpmailer_init', 'send_smtp_email' );\n\n wp_mail( $to, $subject, $message );\n\n remove_filter( 'wp_mail_content_type','set_my_mail_content_type' )\n remove_action( 'phpmailer_init', 'send_smtp_email' );\n\n}\n</code></pre>\n" }, { "answer_id": 363530, "author": "izaak", "author_id": 185681, "author_profile": "https://wordpress.stackexchange.com/users/185681", "pm_score": 2, "selected": false, "text": "<p>require 'wp-includes/class-phpmailer.php'; fixed my problem, but I used a code to create a pdf and then send it in the same way.</p>\n" } ]
2019/07/31
[ "https://wordpress.stackexchange.com/questions/344063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/160490/" ]
I have a WordPress post which is accessible via domain.com/test/ What I want to be able to do is pass in a parameter using the URL - ie going to domain.com/test/ would load the same page as domain.com/test/ - but in url show the /accommodation/value1/**?m=1** in the browser address bar. I guess another way of putting it would be to say I need to be able to access domain.com/test/ by adding **?m=1** like to the end of the URL.
There's no need to use the PHPMailer class in place of `wp_mail()`. `wp_mail()` is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message. You can access the PHPMailer elements when it is initialized in order to have `wp_mail()` send through SMTP instead of the web server. You said you're *not* adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it. In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - [`phpmailer_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init) You can define your settings when PHPMailer is initialized using that hook: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } ``` You want your message in HTML. You could set that in `wp_mail()`'s header argument, but you can/should use the `wp_mail_content_type` filter for that; ``` add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); function set_my_mail_content_type() { return "text/html"; } ``` With your setup properly done, now you're all set to use `wp_mail()` to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template\_redirect' so you do it before headers are sent downstream: ``` function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; wp_mail( $to, $subject, $message ); } ``` **Update: Alternate (Contained) Method:** So, extending what was outlined above, suppose some these settings are **not** what you ordinarily want for every firing of `wp_mail()` and that you only wanted these settings for a specific email. You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the `phpmailer_init` and `wp_mail_content_type` hooks are hit when `wp_mail()` is being run, you *could* set those hooks within your primary function, run your email, then remove them so you're back to the default. ``` function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } function set_my_mail_content_type() { return "text/html"; } function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); add_action( 'phpmailer_init', 'send_smtp_email' ); wp_mail( $to, $subject, $message ); remove_filter( 'wp_mail_content_type','set_my_mail_content_type' ) remove_action( 'phpmailer_init', 'send_smtp_email' ); } ```
344,071
<p>I was hoping to limit the access that my new team of contributors have through the dashboard; and stumbling this video on YouTube on how to possibly limit this; i thought i'd give it a shot. </p> <ul> <li>Here's a link for reference: <a href="https://www.youtube.com/watch?v=9gUCVWjI6OA" rel="nofollow noreferrer">https://www.youtube.com/watch?v=9gUCVWjI6OA</a></li> </ul> <p>So i went ahead and added the code to my functions.php; and after saving to see the results i had been revoked access to my own editor as admin with full rights. </p> <p>Here is the code i had added:</p> <pre><code>define( 'DISALLOW_FILE_EDIT', true); function remove_menus(){ remove_menu_page( 'index.php' ); //Dashboard remove_menu_page( 'jetpack' ); //Jetpack* // remove_menu_page( 'edit.php' ); //Posts remove_menu_page( 'upload.php' ); //Media remove_menu_page( 'edit.php?post_type=page' ); //Pages remove_menu_page( 'edit-comments.php' ); //Comments remove_menu_page( 'themes.php' ); //Appearance remove_menu_page( 'plugins.php' ); //Plugins remove_menu_page( 'users.php' ); //Users remove_menu_page( 'tools.php' ); //Tools remove_menu_page( 'options-general.php' ); //Settings remove_menu_page( 'wpcf7' ); //contact form } if(current_user_can('administrator')){ add_action( 'admin_menu','remove_menus' ); } </code></pre> <p>Is it possible to rollback or have the entire code removed without completely restarting my entire site again.</p> <p>Thanks, Aaron</p>
[ { "answer_id": 351194, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>There's no need to use the PHPMailer class in place of <code>wp_mail()</code>. <code>wp_mail()</code> is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message.</p>\n\n<p>You can access the PHPMailer elements when it is initialized in order to have <code>wp_mail()</code> send through SMTP instead of the web server.</p>\n\n<p>You said you're <em>not</em> adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it.</p>\n\n<p>In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init\" rel=\"nofollow noreferrer\"><code>phpmailer_init</code></a></p>\n\n<p>You can define your settings when PHPMailer is initialized using that hook:</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp_email' );\nfunction send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n</code></pre>\n\n<p>You want your message in HTML. You could set that in <code>wp_mail()</code>'s header argument, but you can/should use the <code>wp_mail_content_type</code> filter for that;</p>\n\n<pre><code>add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n</code></pre>\n\n<p>With your setup properly done, now you're all set to use <code>wp_mail()</code> to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template_redirect' so you do it before headers are sent downstream:</p>\n\n<pre><code>function my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n wp_mail( $to, $subject, $message );\n\n}\n</code></pre>\n\n<p><strong>Update: Alternate (Contained) Method:</strong></p>\n\n<p>So, extending what was outlined above, suppose some these settings are <strong>not</strong> what you ordinarily want for every firing of <code>wp_mail()</code> and that you only wanted these settings for a specific email.</p>\n\n<p>You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the <code>phpmailer_init</code> and <code>wp_mail_content_type</code> hooks are hit when <code>wp_mail()</code> is being run, you <em>could</em> set those hooks within your primary function, run your email, then remove them so you're back to the default.</p>\n\n<pre><code>function send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n\nfunction my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\n add_action( 'phpmailer_init', 'send_smtp_email' );\n\n wp_mail( $to, $subject, $message );\n\n remove_filter( 'wp_mail_content_type','set_my_mail_content_type' )\n remove_action( 'phpmailer_init', 'send_smtp_email' );\n\n}\n</code></pre>\n" }, { "answer_id": 363530, "author": "izaak", "author_id": 185681, "author_profile": "https://wordpress.stackexchange.com/users/185681", "pm_score": 2, "selected": false, "text": "<p>require 'wp-includes/class-phpmailer.php'; fixed my problem, but I used a code to create a pdf and then send it in the same way.</p>\n" } ]
2019/07/31
[ "https://wordpress.stackexchange.com/questions/344071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172774/" ]
I was hoping to limit the access that my new team of contributors have through the dashboard; and stumbling this video on YouTube on how to possibly limit this; i thought i'd give it a shot. * Here's a link for reference: <https://www.youtube.com/watch?v=9gUCVWjI6OA> So i went ahead and added the code to my functions.php; and after saving to see the results i had been revoked access to my own editor as admin with full rights. Here is the code i had added: ``` define( 'DISALLOW_FILE_EDIT', true); function remove_menus(){ remove_menu_page( 'index.php' ); //Dashboard remove_menu_page( 'jetpack' ); //Jetpack* // remove_menu_page( 'edit.php' ); //Posts remove_menu_page( 'upload.php' ); //Media remove_menu_page( 'edit.php?post_type=page' ); //Pages remove_menu_page( 'edit-comments.php' ); //Comments remove_menu_page( 'themes.php' ); //Appearance remove_menu_page( 'plugins.php' ); //Plugins remove_menu_page( 'users.php' ); //Users remove_menu_page( 'tools.php' ); //Tools remove_menu_page( 'options-general.php' ); //Settings remove_menu_page( 'wpcf7' ); //contact form } if(current_user_can('administrator')){ add_action( 'admin_menu','remove_menus' ); } ``` Is it possible to rollback or have the entire code removed without completely restarting my entire site again. Thanks, Aaron
There's no need to use the PHPMailer class in place of `wp_mail()`. `wp_mail()` is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message. You can access the PHPMailer elements when it is initialized in order to have `wp_mail()` send through SMTP instead of the web server. You said you're *not* adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it. In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - [`phpmailer_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init) You can define your settings when PHPMailer is initialized using that hook: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } ``` You want your message in HTML. You could set that in `wp_mail()`'s header argument, but you can/should use the `wp_mail_content_type` filter for that; ``` add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); function set_my_mail_content_type() { return "text/html"; } ``` With your setup properly done, now you're all set to use `wp_mail()` to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template\_redirect' so you do it before headers are sent downstream: ``` function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; wp_mail( $to, $subject, $message ); } ``` **Update: Alternate (Contained) Method:** So, extending what was outlined above, suppose some these settings are **not** what you ordinarily want for every firing of `wp_mail()` and that you only wanted these settings for a specific email. You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the `phpmailer_init` and `wp_mail_content_type` hooks are hit when `wp_mail()` is being run, you *could* set those hooks within your primary function, run your email, then remove them so you're back to the default. ``` function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } function set_my_mail_content_type() { return "text/html"; } function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); add_action( 'phpmailer_init', 'send_smtp_email' ); wp_mail( $to, $subject, $message ); remove_filter( 'wp_mail_content_type','set_my_mail_content_type' ) remove_action( 'phpmailer_init', 'send_smtp_email' ); } ```
344,148
<p>I'm a noob.</p> <p>I have copied the header.php from the parent theme, I have added some snippets and things work. However, I would like to be able to add those same snippets either using a plugin or via functions.php so when/if the theme is updated, I don't need to redo everything. I've tried many things but none of them work. I wonder if the problem is where the snippets are placed by using a plugin or that the HTML element that I'm trying to modify should be written in a different way... I'm quite lost. </p> <p>I have added these inside the head element:</p> <pre class="lang-php prettyprint-override"><code> &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="wp-content/themes/block-lite_child/js/jquery.backstretch.js"&gt;&lt;/script&gt; </code></pre> <p>and then this to run the script:</p> <pre class="lang-php prettyprint-override"><code> &lt;script&gt;$(".wp-custom-header").backstretch([ // Target your HTML element '/wp-content/themes/block-lite_child/images/01.jpg', // Add in your images '/wp-content/themes/block-lite_child/images/02.jpg', '/wp-content/themes/block-lite_child/images/03.jpg', '/wp-content/themes/block-lite_child/images/04.jpg', '/wp-content/themes/block-lite_child/images/05.jpg', ],{ duration:4000, // Time between transitions fade:1000, // Transition effect });&lt;/script&gt; </code></pre> <p>Finally, here is the full header.php </p> <pre class="lang-php prettyprint-override"><code>&lt;?php /** * The Header for our theme. * Displays all of the &lt;head&gt; section and everything up till &lt;div id="wrap"&gt; * * @package Block Lite * @since Block Lite 1.0 */ ?&gt;&lt;!DOCTYPE html&gt; &lt;html class="no-js" &lt;?php language_attributes(); ?&gt;&gt; &lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11"&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="wp-content/themes/block-lite_child/js/jquery.backstretch.js"&gt;&lt;/script&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; &lt;!-- BEGIN #wrapper --&gt; &lt;div id="wrapper"&gt; &lt;!-- BEGIN #header --&gt; &lt;header id="header"&gt; &lt;!-- BEGIN #nav-bar --&gt; &lt;div id="nav-bar"&gt; &lt;?php if ( is_front_page() ) { ?&gt; &lt;h1 class="site-title"&gt; &lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" rel="home"&gt;&lt;?php echo wp_kses_post( get_bloginfo( 'name' ) ); ?&gt;&lt;/a&gt; &lt;/h1&gt; &lt;?php } else { ?&gt; &lt;p class="site-title"&gt; &lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" rel="home"&gt;&lt;?php echo wp_kses_post( get_bloginfo( 'name' ) ); ?&gt;&lt;/a&gt; &lt;/p&gt; &lt;?php } ?&gt; &lt;?php if ( has_nav_menu( 'main-menu' ) ) { ?&gt; &lt;!-- BEGIN #navigation --&gt; &lt;nav id="navigation" class="navigation-main" role="navigation" aria-label="&lt;?php esc_html_e( 'Primary Navigation', 'block-lite' ); ?&gt;"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'main-menu', 'title_li' =&gt; '', 'depth' =&gt; 4, 'fallback_cb' =&gt; 'wp_page_menu', 'container' =&gt; false, 'menu_class' =&gt; 'menu', 'walker' =&gt; new Aria_Walker_Nav_Menu(), 'items_wrap' =&gt; '&lt;ul id="%1$s" class="%2$s" role="menubar"&gt;%3$s&lt;/ul&gt;', 'link_before' =&gt; '&lt;span&gt;', 'link_after' =&gt; '&lt;/span&gt;', ) ); ?&gt; &lt;!-- END #navigation --&gt; &lt;/nav&gt; &lt;button type="button" id="menu-toggle" class="menu-toggle" href="#sidr"&gt; &lt;svg class="icon-menu-open" version="1.1" id="icon-open" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve"&gt; &lt;rect y="2" width="24" height="2"/&gt; &lt;rect y="11" width="24" height="2"/&gt; &lt;rect y="20" width="24" height="2"/&gt; &lt;/svg&gt; &lt;svg class="icon-menu-close" version="1.1" id="icon-close" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve"&gt; &lt;rect x="0" y="11" transform="matrix(-0.7071 -0.7071 0.7071 -0.7071 12 28.9706)" width="24" height="2"/&gt; &lt;rect x="0" y="11" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 28.9706 12)" width="24" height="2"/&gt; &lt;/svg&gt; &lt;/button&gt; &lt;?php } ?&gt; &lt;!-- END #nav-bar --&gt; &lt;/div&gt; &lt;?php if ( has_custom_header() || has_custom_logo() ) { ?&gt; &lt;?php if ( is_home() || is_archive() || is_search() || is_attachment() ) { ?&gt; &lt;!-- BEGIN #custom-header --&gt; &lt;div id="custom-header"&gt; &lt;!-- BEGIN #masthead--&gt; &lt;div id="masthead"&gt; &lt;div class="header-content"&gt; &lt;?php the_custom_logo(); ?&gt; &lt;?php if ( is_front_page() &amp;&amp; is_home() ) { ?&gt; &lt;h2 class="site-description"&gt;&lt;?php echo html_entity_decode( get_bloginfo( 'description' ) ); ?&gt;&lt;/h2&gt; &lt;?php } else { ?&gt; &lt;p class="site-description"&gt;&lt;?php echo html_entity_decode( get_bloginfo( 'description' ) ); ?&gt;&lt;/p&gt; &lt;?php } ?&gt; &lt;?php if ( have_posts() &amp;&amp; is_category() ) { ?&gt; &lt;h1 class="text-center"&gt;&lt;?php the_archive_title(); ?&gt;&lt;/h1&gt; &lt;?php the_archive_description( '&lt;p class="archive-description"&gt;', '&lt;/p&gt;' ); ?&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;!-- END #masthead--&gt; &lt;/div&gt; &lt;?php if ( is_front_page() &amp;&amp; is_home() ) { ?&gt; &lt;a href="#blog-posts" class="scroll-down scroll"&gt;&lt;i class="fa fa-angle-down" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;?php } ?&gt; &lt;?php the_custom_header_markup(); ?&gt; &lt;script&gt;$(".wp-custom-header").backstretch([ // Target your HTML element '/wp-content/themes/block-lite_child/images/01.jpg', // Add in your images '/wp-content/themes/block-lite_child/images/02.jpg', '/wp-content/themes/block-lite_child/images/03.jpg', '/wp-content/themes/block-lite_child/images/04.jpg', '/wp-content/themes/block-lite_child/images/05.jpg', ],{ duration:4000, // Time between transitions fade:1000, // Transition effect });&lt;/script&gt; &lt;!-- END #custom-header --&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;!-- END #header --&gt; &lt;/header&gt; &lt;!-- BEGIN .container --&gt; &lt;main class="container" role="main"&gt; </code></pre>
[ { "answer_id": 351194, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>There's no need to use the PHPMailer class in place of <code>wp_mail()</code>. <code>wp_mail()</code> is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message.</p>\n\n<p>You can access the PHPMailer elements when it is initialized in order to have <code>wp_mail()</code> send through SMTP instead of the web server.</p>\n\n<p>You said you're <em>not</em> adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it.</p>\n\n<p>In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init\" rel=\"nofollow noreferrer\"><code>phpmailer_init</code></a></p>\n\n<p>You can define your settings when PHPMailer is initialized using that hook:</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp_email' );\nfunction send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n</code></pre>\n\n<p>You want your message in HTML. You could set that in <code>wp_mail()</code>'s header argument, but you can/should use the <code>wp_mail_content_type</code> filter for that;</p>\n\n<pre><code>add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n</code></pre>\n\n<p>With your setup properly done, now you're all set to use <code>wp_mail()</code> to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template_redirect' so you do it before headers are sent downstream:</p>\n\n<pre><code>function my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n wp_mail( $to, $subject, $message );\n\n}\n</code></pre>\n\n<p><strong>Update: Alternate (Contained) Method:</strong></p>\n\n<p>So, extending what was outlined above, suppose some these settings are <strong>not</strong> what you ordinarily want for every firing of <code>wp_mail()</code> and that you only wanted these settings for a specific email.</p>\n\n<p>You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the <code>phpmailer_init</code> and <code>wp_mail_content_type</code> hooks are hit when <code>wp_mail()</code> is being run, you <em>could</em> set those hooks within your primary function, run your email, then remove them so you're back to the default.</p>\n\n<pre><code>function send_smtp_email( $phpmailer ) {\n $phpmailer-&gt;isSMTP();\n $phpmailer-&gt;Host = 'smtp.google.com';\n $phpmailer-&gt;Port = '587';\n $phpmailer-&gt;SMTPSecure = 'tls';\n $phpmailer-&gt;SMTPAuth = true;\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = '11111111';\n $phpmailer-&gt;From = '[email protected]';\n $phpmailer-&gt;FromName = 'From Name';\n $phpmailer-&gt;addReplyTo('[email protected]', 'Information');\n}\n\nfunction set_my_mail_content_type() {\n return \"text/html\";\n}\n\nfunction my_function() {\n\n $to = '[email protected]';\n $subject = 'Here is the subject';\n $message = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; \n\n add_filter( 'wp_mail_content_type','set_my_mail_content_type' );\n add_action( 'phpmailer_init', 'send_smtp_email' );\n\n wp_mail( $to, $subject, $message );\n\n remove_filter( 'wp_mail_content_type','set_my_mail_content_type' )\n remove_action( 'phpmailer_init', 'send_smtp_email' );\n\n}\n</code></pre>\n" }, { "answer_id": 363530, "author": "izaak", "author_id": 185681, "author_profile": "https://wordpress.stackexchange.com/users/185681", "pm_score": 2, "selected": false, "text": "<p>require 'wp-includes/class-phpmailer.php'; fixed my problem, but I used a code to create a pdf and then send it in the same way.</p>\n" } ]
2019/08/01
[ "https://wordpress.stackexchange.com/questions/344148", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133956/" ]
I'm a noob. I have copied the header.php from the parent theme, I have added some snippets and things work. However, I would like to be able to add those same snippets either using a plugin or via functions.php so when/if the theme is updated, I don't need to redo everything. I've tried many things but none of them work. I wonder if the problem is where the snippets are placed by using a plugin or that the HTML element that I'm trying to modify should be written in a different way... I'm quite lost. I have added these inside the head element: ```php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="wp-content/themes/block-lite_child/js/jquery.backstretch.js"></script> ``` and then this to run the script: ```php <script>$(".wp-custom-header").backstretch([ // Target your HTML element '/wp-content/themes/block-lite_child/images/01.jpg', // Add in your images '/wp-content/themes/block-lite_child/images/02.jpg', '/wp-content/themes/block-lite_child/images/03.jpg', '/wp-content/themes/block-lite_child/images/04.jpg', '/wp-content/themes/block-lite_child/images/05.jpg', ],{ duration:4000, // Time between transitions fade:1000, // Transition effect });</script> ``` Finally, here is the full header.php ```php <?php /** * The Header for our theme. * Displays all of the <head> section and everything up till <div id="wrap"> * * @package Block Lite * @since Block Lite 1.0 */ ?><!DOCTYPE html> <html class="no-js" <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="http://gmpg.org/xfn/11"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="wp-content/themes/block-lite_child/js/jquery.backstretch.js"></script> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <!-- BEGIN #wrapper --> <div id="wrapper"> <!-- BEGIN #header --> <header id="header"> <!-- BEGIN #nav-bar --> <div id="nav-bar"> <?php if ( is_front_page() ) { ?> <h1 class="site-title"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php echo wp_kses_post( get_bloginfo( 'name' ) ); ?></a> </h1> <?php } else { ?> <p class="site-title"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php echo wp_kses_post( get_bloginfo( 'name' ) ); ?></a> </p> <?php } ?> <?php if ( has_nav_menu( 'main-menu' ) ) { ?> <!-- BEGIN #navigation --> <nav id="navigation" class="navigation-main" role="navigation" aria-label="<?php esc_html_e( 'Primary Navigation', 'block-lite' ); ?>"> <?php wp_nav_menu( array( 'theme_location' => 'main-menu', 'title_li' => '', 'depth' => 4, 'fallback_cb' => 'wp_page_menu', 'container' => false, 'menu_class' => 'menu', 'walker' => new Aria_Walker_Nav_Menu(), 'items_wrap' => '<ul id="%1$s" class="%2$s" role="menubar">%3$s</ul>', 'link_before' => '<span>', 'link_after' => '</span>', ) ); ?> <!-- END #navigation --> </nav> <button type="button" id="menu-toggle" class="menu-toggle" href="#sidr"> <svg class="icon-menu-open" version="1.1" id="icon-open" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve"> <rect y="2" width="24" height="2"/> <rect y="11" width="24" height="2"/> <rect y="20" width="24" height="2"/> </svg> <svg class="icon-menu-close" version="1.1" id="icon-close" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve"> <rect x="0" y="11" transform="matrix(-0.7071 -0.7071 0.7071 -0.7071 12 28.9706)" width="24" height="2"/> <rect x="0" y="11" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 28.9706 12)" width="24" height="2"/> </svg> </button> <?php } ?> <!-- END #nav-bar --> </div> <?php if ( has_custom_header() || has_custom_logo() ) { ?> <?php if ( is_home() || is_archive() || is_search() || is_attachment() ) { ?> <!-- BEGIN #custom-header --> <div id="custom-header"> <!-- BEGIN #masthead--> <div id="masthead"> <div class="header-content"> <?php the_custom_logo(); ?> <?php if ( is_front_page() && is_home() ) { ?> <h2 class="site-description"><?php echo html_entity_decode( get_bloginfo( 'description' ) ); ?></h2> <?php } else { ?> <p class="site-description"><?php echo html_entity_decode( get_bloginfo( 'description' ) ); ?></p> <?php } ?> <?php if ( have_posts() && is_category() ) { ?> <h1 class="text-center"><?php the_archive_title(); ?></h1> <?php the_archive_description( '<p class="archive-description">', '</p>' ); ?> <?php } ?> </div> <!-- END #masthead--> </div> <?php if ( is_front_page() && is_home() ) { ?> <a href="#blog-posts" class="scroll-down scroll"><i class="fa fa-angle-down" aria-hidden="true"></i></a> <?php } ?> <?php the_custom_header_markup(); ?> <script>$(".wp-custom-header").backstretch([ // Target your HTML element '/wp-content/themes/block-lite_child/images/01.jpg', // Add in your images '/wp-content/themes/block-lite_child/images/02.jpg', '/wp-content/themes/block-lite_child/images/03.jpg', '/wp-content/themes/block-lite_child/images/04.jpg', '/wp-content/themes/block-lite_child/images/05.jpg', ],{ duration:4000, // Time between transitions fade:1000, // Transition effect });</script> <!-- END #custom-header --> </div> <?php } ?> <?php } ?> <!-- END #header --> </header> <!-- BEGIN .container --> <main class="container" role="main"> ```
There's no need to use the PHPMailer class in place of `wp_mail()`. `wp_mail()` is a essentially a wrapper for the class. It just makes an easier way of packaging and sending the message. You can access the PHPMailer elements when it is initialized in order to have `wp_mail()` send through SMTP instead of the web server. You said you're *not* adding as an action to control where it's used, but that's precisely what an action hook is for - it allows you to hook exactly where you want it, when you want it. In this case, all of those PHPMailer elements need to be set when PHPMailer is initialized. There's an action hook for that - [`phpmailer_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init) You can define your settings when PHPMailer is initialized using that hook: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } ``` You want your message in HTML. You could set that in `wp_mail()`'s header argument, but you can/should use the `wp_mail_content_type` filter for that; ``` add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); function set_my_mail_content_type() { return "text/html"; } ``` With your setup properly done, now you're all set to use `wp_mail()` to send your message and you can do it anywhere - I recommend hooking this function to something that makes sense - such as 'template\_redirect' so you do it before headers are sent downstream: ``` function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; wp_mail( $to, $subject, $message ); } ``` **Update: Alternate (Contained) Method:** So, extending what was outlined above, suppose some these settings are **not** what you ordinarily want for every firing of `wp_mail()` and that you only wanted these settings for a specific email. You still would need to break out the settings and hook them appropriately (otherwise they will not process at the right time). Noting that the `phpmailer_init` and `wp_mail_content_type` hooks are hit when `wp_mail()` is being run, you *could* set those hooks within your primary function, run your email, then remove them so you're back to the default. ``` function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.google.com'; $phpmailer->Port = '587'; $phpmailer->SMTPSecure = 'tls'; $phpmailer->SMTPAuth = true; $phpmailer->Username = '[email protected]'; $phpmailer->Password = '11111111'; $phpmailer->From = '[email protected]'; $phpmailer->FromName = 'From Name'; $phpmailer->addReplyTo('[email protected]', 'Information'); } function set_my_mail_content_type() { return "text/html"; } function my_function() { $to = '[email protected]'; $subject = 'Here is the subject'; $message = 'This is the HTML message body <b>in bold!</b>'; add_filter( 'wp_mail_content_type','set_my_mail_content_type' ); add_action( 'phpmailer_init', 'send_smtp_email' ); wp_mail( $to, $subject, $message ); remove_filter( 'wp_mail_content_type','set_my_mail_content_type' ) remove_action( 'phpmailer_init', 'send_smtp_email' ); } ```
344,261
<p>I have this code:</p> <pre><code>$query = "SELECT * FROM $wpdb-&gt;posts INNER JOIN $wpdb-&gt;postmeta ON $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id INNER JOIN $wpdb-&gt;term_relationships ON $wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id WHERE ((post_type = 'projects') OR (post_type = 'post_cost_codes'));"; $results = $wpdb-&gt;query($query); // Takes 1.5 seconds </code></pre> <p>I also tried this:</p> <pre><code>$query = "SELECT * FROM $wpdb-&gt;posts INNER JOIN $wpdb-&gt;postmeta ON $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id INNER JOIN $wpdb-&gt;term_relationships ON $wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id WHERE ((post_type = 'projects') OR (post_type = 'post_cost_codes'));"; $results = $wpdb-&gt;get_results($query); // Still takes 1.5 seconds </code></pre> <p>But when I grab the query and put it in phpmyadmin:</p> <pre><code>(18588 total, Query took 0.0102 seconds.) SELECT * FROM wp_dev_posts, wp_dev_postmeta, wp_dev_term_relationships WHERE ((post_type = 'projects') OR (post_type = 'post_cost_codes')) AND (wp_dev_posts.ID = wp_dev_postmeta.post_id) AND (wp_dev_posts.ID = wp_dev_term_relationships.object_id) // Takes 0.0102 seconds </code></pre> <p>Why do both $wpdb methods take so much longer? The same query is copy and pasted directly on phpmyadmin, it takes the expected amount of time.</p>
[ { "answer_id": 344263, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 0, "selected": false, "text": "<p>The difference is what is returned.</p>\n\n<p>The WPDB <code>query()</code> method returns <code>true</code> for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply <code>false</code> if if there's an error.</p>\n\n<p>The WPDB <code>get_results()</code> method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.</p>\n" }, { "answer_id": 344538, "author": "Justin J James", "author_id": 142560, "author_profile": "https://wordpress.stackexchange.com/users/142560", "pm_score": -1, "selected": false, "text": "<p>Without much luck, I solved my own problems by using get_transient(...) and set_transient(...)</p>\n<p>Note, this is a wordpress-only fix. The first call has someone suffer, but once cached it's a good enough solution for me.</p>\n<p>In my case, it was acceptable since I am fine with storing the result for the entire day. Even 12 hours is fine for me. I'm still looking for answers to the original question since I'm very curious what is going wrong.</p>\n" } ]
2019/08/02
[ "https://wordpress.stackexchange.com/questions/344261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142560/" ]
I have this code: ``` $query = "SELECT * FROM $wpdb->posts INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id INNER JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id WHERE ((post_type = 'projects') OR (post_type = 'post_cost_codes'));"; $results = $wpdb->query($query); // Takes 1.5 seconds ``` I also tried this: ``` $query = "SELECT * FROM $wpdb->posts INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id INNER JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id WHERE ((post_type = 'projects') OR (post_type = 'post_cost_codes'));"; $results = $wpdb->get_results($query); // Still takes 1.5 seconds ``` But when I grab the query and put it in phpmyadmin: ``` (18588 total, Query took 0.0102 seconds.) SELECT * FROM wp_dev_posts, wp_dev_postmeta, wp_dev_term_relationships WHERE ((post_type = 'projects') OR (post_type = 'post_cost_codes')) AND (wp_dev_posts.ID = wp_dev_postmeta.post_id) AND (wp_dev_posts.ID = wp_dev_term_relationships.object_id) // Takes 0.0102 seconds ``` Why do both $wpdb methods take so much longer? The same query is copy and pasted directly on phpmyadmin, it takes the expected amount of time.
The difference is what is returned. The WPDB `query()` method returns `true` for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply `false` if if there's an error. The WPDB `get_results()` method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.
344,308
<p>I have a multisite wordpress installation on aws linux, working perfectly fine. The WP Rest api is also working exactly as it should. Except for one single case.</p> <pre><code>/wp-json/wp/v2/posts?author=&lt;some int&gt; </code></pre> <p>For everything else, including my custom endpoints, and custom params/fields added to the api, it works perfectly. But the moment i add the author part, it returns 404 on all sites. eg:</p> <pre><code>/wp-json/wp/v2/posts?author_exclude=1 //this works /wp-json/wp/v2/posts?page=2 // this also works /wp-json/wp/v2/posts?page=2&amp;author=abc // this also works and returns invalid author /wp-json/wp/v2/posts?page=2&amp;author=1 // this returns 404 page not found </code></pre> <p>From some of the other similar questions, I found that this issue could be due to permalinks, but I am using custom permalinks</p> <pre><code>sitename/%year%/%monthnum%/%day%/%author%/%category%/%postname%/ </code></pre> <p>I have tried changing the permalink to no effect. Another solution I found is to change all the <code>deny</code> to <code>allow</code> in htaccess. I am not well-versed in htaccess, so i have not modified it for fear of causing some security issues. As for other related info, I am also using jwt and disable rest api plugin(with only jwt endpoints enabled).</p> <p>Any help would be appreciated, please.</p>
[ { "answer_id": 344263, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 0, "selected": false, "text": "<p>The difference is what is returned.</p>\n\n<p>The WPDB <code>query()</code> method returns <code>true</code> for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply <code>false</code> if if there's an error.</p>\n\n<p>The WPDB <code>get_results()</code> method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.</p>\n" }, { "answer_id": 344538, "author": "Justin J James", "author_id": 142560, "author_profile": "https://wordpress.stackexchange.com/users/142560", "pm_score": -1, "selected": false, "text": "<p>Without much luck, I solved my own problems by using get_transient(...) and set_transient(...)</p>\n<p>Note, this is a wordpress-only fix. The first call has someone suffer, but once cached it's a good enough solution for me.</p>\n<p>In my case, it was acceptable since I am fine with storing the result for the entire day. Even 12 hours is fine for me. I'm still looking for answers to the original question since I'm very curious what is going wrong.</p>\n" } ]
2019/08/03
[ "https://wordpress.stackexchange.com/questions/344308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171870/" ]
I have a multisite wordpress installation on aws linux, working perfectly fine. The WP Rest api is also working exactly as it should. Except for one single case. ``` /wp-json/wp/v2/posts?author=<some int> ``` For everything else, including my custom endpoints, and custom params/fields added to the api, it works perfectly. But the moment i add the author part, it returns 404 on all sites. eg: ``` /wp-json/wp/v2/posts?author_exclude=1 //this works /wp-json/wp/v2/posts?page=2 // this also works /wp-json/wp/v2/posts?page=2&author=abc // this also works and returns invalid author /wp-json/wp/v2/posts?page=2&author=1 // this returns 404 page not found ``` From some of the other similar questions, I found that this issue could be due to permalinks, but I am using custom permalinks ``` sitename/%year%/%monthnum%/%day%/%author%/%category%/%postname%/ ``` I have tried changing the permalink to no effect. Another solution I found is to change all the `deny` to `allow` in htaccess. I am not well-versed in htaccess, so i have not modified it for fear of causing some security issues. As for other related info, I am also using jwt and disable rest api plugin(with only jwt endpoints enabled). Any help would be appreciated, please.
The difference is what is returned. The WPDB `query()` method returns `true` for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply `false` if if there's an error. The WPDB `get_results()` method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.
344,360
<p>I have set up WP as multisite installation with subdomains. The dashboard for both the site network and each site is working fine, except for the error I get using Block Editor on my parent site. </p> <p>So I have wyamazaki.fi as my main domain, and want to create two websites, one for blog, another for company website using multisite. I have wildcard subdomain set up in cPanel, and redirect seems to be working. </p> <p>Whenever I create/edit page on my main site, the Block editor fails with error saying "Updating Failed". I checked the console on Chrome, and it seems like all the API requests are resulting in 403 error. (404 was when I tested different RewriteBase in .htaccess) <a href="https://i.stack.imgur.com/wdO4c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wdO4c.png" alt="screenshot of chrome console"></a></p> <p>I have checked my .htaccess and they seem to be okay to my eyes. </p> <pre><code>#HTTPS-ohjaus: wyamazaki.fi RewriteEngine On RewriteCond %{HTTP_HOST} ^wyamazaki.fi [NC,OR] RewriteCond %{HTTP_HOST} ^www.wyamazaki.fi [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] #HTTPS-ohjaus loppuu #HTTPS-ohjaus: *.wyamazaki.fi RewriteEngine On RewriteCond %{HTTP_HOST} ^*.wyamazaki.fi [NC,OR] RewriteCond %{HTTP_HOST} ^www.*.wyamazaki.fi [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] #HTTPS-ohjaus loppuu RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] </code></pre> <p>The strange thing is it works just fine for the subdomain child sites (translation.wyamazaki.fi), but the parent site (wyamazaki.fi) gives me 403 whatever I do with page. I'm suspecting issues with server side security, but can't be certain. </p> <p>I could use Classic Editor without the issues above, but it feels like it's ignoring the problem in the long run (block editor doesn't seem to go away in near future, so...) . </p> <p>Another option I have in mind is to use two subdomains and set redirect to one of them to show it for wyamazaki.fi access, but not sure how (I'm still learning apache and php).</p> <p>Any help is appreciated!</p>
[ { "answer_id": 344263, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 0, "selected": false, "text": "<p>The difference is what is returned.</p>\n\n<p>The WPDB <code>query()</code> method returns <code>true</code> for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply <code>false</code> if if there's an error.</p>\n\n<p>The WPDB <code>get_results()</code> method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.</p>\n" }, { "answer_id": 344538, "author": "Justin J James", "author_id": 142560, "author_profile": "https://wordpress.stackexchange.com/users/142560", "pm_score": -1, "selected": false, "text": "<p>Without much luck, I solved my own problems by using get_transient(...) and set_transient(...)</p>\n<p>Note, this is a wordpress-only fix. The first call has someone suffer, but once cached it's a good enough solution for me.</p>\n<p>In my case, it was acceptable since I am fine with storing the result for the entire day. Even 12 hours is fine for me. I'm still looking for answers to the original question since I'm very curious what is going wrong.</p>\n" } ]
2019/08/04
[ "https://wordpress.stackexchange.com/questions/344360", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172988/" ]
I have set up WP as multisite installation with subdomains. The dashboard for both the site network and each site is working fine, except for the error I get using Block Editor on my parent site. So I have wyamazaki.fi as my main domain, and want to create two websites, one for blog, another for company website using multisite. I have wildcard subdomain set up in cPanel, and redirect seems to be working. Whenever I create/edit page on my main site, the Block editor fails with error saying "Updating Failed". I checked the console on Chrome, and it seems like all the API requests are resulting in 403 error. (404 was when I tested different RewriteBase in .htaccess) [![screenshot of chrome console](https://i.stack.imgur.com/wdO4c.png)](https://i.stack.imgur.com/wdO4c.png) I have checked my .htaccess and they seem to be okay to my eyes. ``` #HTTPS-ohjaus: wyamazaki.fi RewriteEngine On RewriteCond %{HTTP_HOST} ^wyamazaki.fi [NC,OR] RewriteCond %{HTTP_HOST} ^www.wyamazaki.fi [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] #HTTPS-ohjaus loppuu #HTTPS-ohjaus: *.wyamazaki.fi RewriteEngine On RewriteCond %{HTTP_HOST} ^*.wyamazaki.fi [NC,OR] RewriteCond %{HTTP_HOST} ^www.*.wyamazaki.fi [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] #HTTPS-ohjaus loppuu RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] ``` The strange thing is it works just fine for the subdomain child sites (translation.wyamazaki.fi), but the parent site (wyamazaki.fi) gives me 403 whatever I do with page. I'm suspecting issues with server side security, but can't be certain. I could use Classic Editor without the issues above, but it feels like it's ignoring the problem in the long run (block editor doesn't seem to go away in near future, so...) . Another option I have in mind is to use two subdomains and set redirect to one of them to show it for wyamazaki.fi access, but not sure how (I'm still learning apache and php). Any help is appreciated!
The difference is what is returned. The WPDB `query()` method returns `true` for CREATE, ALTER, TRUNCATE and DROP queries, an integer of how many results for all other queries, or simply `false` if if there's an error. The WPDB `get_results()` method actually returns the entire result of the query (like you would get running the query in phpMyAdmin). You can return the result as an array or an object, depending on how you want to work with the results.
344,386
<p>I'm using this code to display size attributes below each product on the shop archive page, but it throws the error below. How do I change the code to fix this error? My thoughts the code has depreciated. </p> <pre><code>add_action('woocommerce_after_shop_loop_item_title', 'add_attribute', 5); function add_attribute() { $desired_att = 'Size'; global $product; $product_variable = new WC_Product_Variable($product-&gt;id); $product_variations = $product_variable-&gt;get_available_variations(); $numItems = count($product_variations); echo '&lt;span class="price"&gt;'; if ($numItems == 1) { foreach ($product_variations as $variation) { echo $variation[attributes]['attribute_pa_size']; } } else if ($numItems &gt; 1) { $i = 0; foreach ($product_variations as $variation) { if (++$i === $numItems) { echo $variation[attributes]['attribute_pa_size']; } else { echo $variation[attributes]['attribute_pa_size'] . ", "; } } } echo '&lt;/span&gt;'; } </code></pre> <p>Error Message</p> <pre><code>Notice: id was called incorrectly . Product properties should not be accessed directly. Backtrace: require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/plugins/genesis-connect-woocommerce/templates/taxonomy.php'), genesis, do_action('genesis_loop'), WP_Hook-&gt;do_action, WP_Hook-&gt;apply_filters, genesiswooc_product_taxonomy_loop, genesiswooc_content_product, wc_get_template_part, load_template, require('/plugins/woocommerce/templates/content-product.php'), do_action('woocommerce_after_shop_loop_item_title'), WP_Hook-&gt;do_action, WP_Hook-&gt;apply_filters, add_attribute, WC_Abstract_Legacy_Product-&gt;__get, wc_doing_it_wrong Please see Debugging in WordPress for more information. (This message was added in version 3.0.) in /home/public_html/wp-includes/functions.php on line 4773 </code></pre>
[ { "answer_id": 344400, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>Your code is outdated since WooCommerce 3. <br>\nFirst, you need to target variable products type only to avoid errors on other products types and also <code>$product</code> is already the product object. </p>\n\n<p>Also you can also directly use the <code>WC_Product</code> method <code>get_attribute()</code> and your code will be much more simpler, compact and efficient:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );\nfunction display_size_attribute() {\n global $product;\n\n if ( $product-&gt;is_type('variable') ) {\n $taxonomy = 'pa_size';\n echo '&lt;span class=\"attribute-size\"&gt;' . $product-&gt;get_attribute($taxonomy) . '&lt;/span&gt;';\n }\n}\n</code></pre>\n\n<p><em>Code goes in functions.php file of the active child theme (or active theme).</em> Tested and works.</p>\n" }, { "answer_id": 374461, "author": "Rigal", "author_id": 124738, "author_profile": "https://wordpress.stackexchange.com/users/124738", "pm_score": 0, "selected": false, "text": "<p>You can use a product global object and it's methods in Woocommerce 4.3</p>\n<pre><code>add_action('woocommerce_after_shop_loop_item_title', 'cstm_display_product_category', 5);\n\nfunction cstm_display_product_category()\n{\n global $product;\n $size = $product-&gt;get_attribute('pa_size');\n\n if(isset($size)){\n echo '&lt;div class=&quot;items&quot;&gt;&lt;p&gt;Size: ' . $size . '&lt;/p&gt;&lt;/div&gt;';\n }\n}\n\n</code></pre>\n" } ]
2019/08/05
[ "https://wordpress.stackexchange.com/questions/344386", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118008/" ]
I'm using this code to display size attributes below each product on the shop archive page, but it throws the error below. How do I change the code to fix this error? My thoughts the code has depreciated. ``` add_action('woocommerce_after_shop_loop_item_title', 'add_attribute', 5); function add_attribute() { $desired_att = 'Size'; global $product; $product_variable = new WC_Product_Variable($product->id); $product_variations = $product_variable->get_available_variations(); $numItems = count($product_variations); echo '<span class="price">'; if ($numItems == 1) { foreach ($product_variations as $variation) { echo $variation[attributes]['attribute_pa_size']; } } else if ($numItems > 1) { $i = 0; foreach ($product_variations as $variation) { if (++$i === $numItems) { echo $variation[attributes]['attribute_pa_size']; } else { echo $variation[attributes]['attribute_pa_size'] . ", "; } } } echo '</span>'; } ``` Error Message ``` Notice: id was called incorrectly . Product properties should not be accessed directly. Backtrace: require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/plugins/genesis-connect-woocommerce/templates/taxonomy.php'), genesis, do_action('genesis_loop'), WP_Hook->do_action, WP_Hook->apply_filters, genesiswooc_product_taxonomy_loop, genesiswooc_content_product, wc_get_template_part, load_template, require('/plugins/woocommerce/templates/content-product.php'), do_action('woocommerce_after_shop_loop_item_title'), WP_Hook->do_action, WP_Hook->apply_filters, add_attribute, WC_Abstract_Legacy_Product->__get, wc_doing_it_wrong Please see Debugging in WordPress for more information. (This message was added in version 3.0.) in /home/public_html/wp-includes/functions.php on line 4773 ```
Your code is outdated since WooCommerce 3. First, you need to target variable products type only to avoid errors on other products types and also `$product` is already the product object. Also you can also directly use the `WC_Product` method `get_attribute()` and your code will be much more simpler, compact and efficient: ``` add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 ); function display_size_attribute() { global $product; if ( $product->is_type('variable') ) { $taxonomy = 'pa_size'; echo '<span class="attribute-size">' . $product->get_attribute($taxonomy) . '</span>'; } } ``` *Code goes in functions.php file of the active child theme (or active theme).* Tested and works.
344,393
<p>I'm using Jetpack to lazy load images and wanted to fade in them nicely using CSS. I've tried adding the following CSS in my theme:</p> <pre><code>.jetpack-lazy-image { opacity: 0; -webkit-transition: .3s; transition: .3s; } .jetpack-lazy-image--handled { opacity: 1; } </code></pre> <p>but that doesn’t work. I've also tried to add this to the default WP themes, however, it doesn't work as well. Could someone please let me know what I am missing?</p> <p>Thank you.</p>
[ { "answer_id": 344400, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>Your code is outdated since WooCommerce 3. <br>\nFirst, you need to target variable products type only to avoid errors on other products types and also <code>$product</code> is already the product object. </p>\n\n<p>Also you can also directly use the <code>WC_Product</code> method <code>get_attribute()</code> and your code will be much more simpler, compact and efficient:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );\nfunction display_size_attribute() {\n global $product;\n\n if ( $product-&gt;is_type('variable') ) {\n $taxonomy = 'pa_size';\n echo '&lt;span class=\"attribute-size\"&gt;' . $product-&gt;get_attribute($taxonomy) . '&lt;/span&gt;';\n }\n}\n</code></pre>\n\n<p><em>Code goes in functions.php file of the active child theme (or active theme).</em> Tested and works.</p>\n" }, { "answer_id": 374461, "author": "Rigal", "author_id": 124738, "author_profile": "https://wordpress.stackexchange.com/users/124738", "pm_score": 0, "selected": false, "text": "<p>You can use a product global object and it's methods in Woocommerce 4.3</p>\n<pre><code>add_action('woocommerce_after_shop_loop_item_title', 'cstm_display_product_category', 5);\n\nfunction cstm_display_product_category()\n{\n global $product;\n $size = $product-&gt;get_attribute('pa_size');\n\n if(isset($size)){\n echo '&lt;div class=&quot;items&quot;&gt;&lt;p&gt;Size: ' . $size . '&lt;/p&gt;&lt;/div&gt;';\n }\n}\n\n</code></pre>\n" } ]
2019/08/05
[ "https://wordpress.stackexchange.com/questions/344393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173014/" ]
I'm using Jetpack to lazy load images and wanted to fade in them nicely using CSS. I've tried adding the following CSS in my theme: ``` .jetpack-lazy-image { opacity: 0; -webkit-transition: .3s; transition: .3s; } .jetpack-lazy-image--handled { opacity: 1; } ``` but that doesn’t work. I've also tried to add this to the default WP themes, however, it doesn't work as well. Could someone please let me know what I am missing? Thank you.
Your code is outdated since WooCommerce 3. First, you need to target variable products type only to avoid errors on other products types and also `$product` is already the product object. Also you can also directly use the `WC_Product` method `get_attribute()` and your code will be much more simpler, compact and efficient: ``` add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 ); function display_size_attribute() { global $product; if ( $product->is_type('variable') ) { $taxonomy = 'pa_size'; echo '<span class="attribute-size">' . $product->get_attribute($taxonomy) . '</span>'; } } ``` *Code goes in functions.php file of the active child theme (or active theme).* Tested and works.
344,404
<p>I'm trying to create a custom block but I need some assistance.</p> <p>I'm attempting to setup a <code>&lt;select&gt;</code> in the editor that lists all the posts. I'm not very experienced at the api yet but after reading the docs, it seems that the below line should work to get the posts.</p> <pre><code>wp.api.collections.Posts().fetch() </code></pre> <p>The problem is, however, I'm getting a nice error of:</p> <blockquote> <p>TypeError: Cannot read property 'collections' of undefined</p> </blockquote> <p>How can I get a list of all the posts for selection within the editor, or is it just outside the realm of possibility?</p>
[ { "answer_id": 344416, "author": "Den Pat", "author_id": 103569, "author_profile": "https://wordpress.stackexchange.com/users/103569", "pm_score": 1, "selected": false, "text": "<p>You need to enqueue WP API javascript, You should have added the above code in one of your custom files, suppose your file name is myscript.js</p>\n<p>And you should have enqueued it somewhere, modify that and attach wp-api as a dependency like this :</p>\n<pre><code>wp_enqueue_script( 'my_script', 'path/to/my/myscript.js', array( 'wp-api' ) );\n</code></pre>\n" }, { "answer_id": 344440, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>In addition to loading the <code>wp-api</code> script as mentioned <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/#using\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_enqueue_script( 'wp-api' ); // or use below when enqueueing as dependency\n//wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) );\n</code></pre>\n\n<p>You should also know that each collection is a function (equivalent to a class in PHP), so you need to use the <code>new</code> keyword to instantiate a collection. <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/#collection-examples\" rel=\"nofollow noreferrer\">Example</a>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var postsCollection = new wp.api.collections.Posts();\npostsCollection.fetch( {\n data: { per_page: 2 }\n} ).done( function( posts ){\n console.log( 'Title of the first item is: ' + posts[0].title.rendered );\n} );\n</code></pre>\n\n<p>However, with Gutenberg, you'd likely want to or you can use the <code>api-fetch</code>/<code>wp.apiFetch</code> <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/api-fetch\" rel=\"nofollow noreferrer\">package</a>:</p>\n\n<ol>\n<li><p>Enqueue the <code>wp-api-fetch</code> script:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_enqueue_script( 'wp-api-fetch' ); // or use below when enqueueing as dependency\n//wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api-fetch' ) );\n</code></pre></li>\n<li><p>And just call <code>wp.apiFetch()</code> like so:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.apiFetch( { path: '/wp/v2/posts?per_page=2' } ).then( function( posts ){\n console.log( 'Title of the first item is: ' + posts[0].title.rendered );\n} );\n</code></pre>\n\n<p><code>path</code> is a REST API route like <a href=\"https://developer.wordpress.org/rest-api/reference/posts/#list-posts\" rel=\"nofollow noreferrer\"><code>/wp/v2/posts</code></a> which can optionally be appended with one or more arguments for that specific route.</p></li>\n</ol>\n\n<blockquote>\n <p>How can I get a list of all the posts for selection within the editor</p>\n</blockquote>\n\n<p>If you're on the admin screen for editing or creating a post, then the <code>wp-api-fetch</code> script has already been enqueued <em>if</em> the block editor is enabled for that post. And if you're specifically creating a block, then you can actually use <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/core-data#getEntityRecords\" rel=\"nofollow noreferrer\"><code>getEntityRecords()</code></a> along with <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/data#withSelect\" rel=\"nofollow noreferrer\"><code>withSelect</code></a> (for listening to state changes). See the <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/block-library/src/latest-posts/edit.js\" rel=\"nofollow noreferrer\">Latest Posts block</a> for sample implementation.</p>\n" } ]
2019/08/05
[ "https://wordpress.stackexchange.com/questions/344404", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59902/" ]
I'm trying to create a custom block but I need some assistance. I'm attempting to setup a `<select>` in the editor that lists all the posts. I'm not very experienced at the api yet but after reading the docs, it seems that the below line should work to get the posts. ``` wp.api.collections.Posts().fetch() ``` The problem is, however, I'm getting a nice error of: > > TypeError: Cannot read property 'collections' of undefined > > > How can I get a list of all the posts for selection within the editor, or is it just outside the realm of possibility?
In addition to loading the `wp-api` script as mentioned [here](https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/#using): ```php wp_enqueue_script( 'wp-api' ); // or use below when enqueueing as dependency //wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) ); ``` You should also know that each collection is a function (equivalent to a class in PHP), so you need to use the `new` keyword to instantiate a collection. [Example](https://developer.wordpress.org/rest-api/using-the-rest-api/backbone-javascript-client/#collection-examples): ```js var postsCollection = new wp.api.collections.Posts(); postsCollection.fetch( { data: { per_page: 2 } } ).done( function( posts ){ console.log( 'Title of the first item is: ' + posts[0].title.rendered ); } ); ``` However, with Gutenberg, you'd likely want to or you can use the `api-fetch`/`wp.apiFetch` [package](https://github.com/WordPress/gutenberg/tree/master/packages/api-fetch): 1. Enqueue the `wp-api-fetch` script: ```php wp_enqueue_script( 'wp-api-fetch' ); // or use below when enqueueing as dependency //wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api-fetch' ) ); ``` 2. And just call `wp.apiFetch()` like so: ```js wp.apiFetch( { path: '/wp/v2/posts?per_page=2' } ).then( function( posts ){ console.log( 'Title of the first item is: ' + posts[0].title.rendered ); } ); ``` `path` is a REST API route like [`/wp/v2/posts`](https://developer.wordpress.org/rest-api/reference/posts/#list-posts) which can optionally be appended with one or more arguments for that specific route. > > How can I get a list of all the posts for selection within the editor > > > If you're on the admin screen for editing or creating a post, then the `wp-api-fetch` script has already been enqueued *if* the block editor is enabled for that post. And if you're specifically creating a block, then you can actually use [`getEntityRecords()`](https://github.com/WordPress/gutenberg/tree/master/packages/core-data#getEntityRecords) along with [`withSelect`](https://github.com/WordPress/gutenberg/tree/master/packages/data#withSelect) (for listening to state changes). See the [Latest Posts block](https://github.com/WordPress/gutenberg/blob/master/packages/block-library/src/latest-posts/edit.js) for sample implementation.
344,485
<p>I'm working on a custom gutenberg block, and in the <code>save</code> method, I have dynamically changing HTML in the form of a string.</p> <pre class="lang-js prettyprint-override"><code>element.createElement( 'div', null, contentString, ) </code></pre> <p>The above snippet just outputs the HTML as a string, converting all the symbols to HTML entities (<code>&amp;lt;</code>, <code>&amp;gt;</code>, etc.)</p> <p>How can I go about writing the actual HTML?</p>
[ { "answer_id": 344492, "author": "Vortac", "author_id": 167651, "author_profile": "https://wordpress.stackexchange.com/users/167651", "pm_score": 1, "selected": false, "text": "<p>I haven’t tested it, but you might want to try:</p>\n\n<pre><code>element.createElement(\n 'div',\n null,\n {dangerouslySetInnerHTML: {__html: contentString}},\n)\n</code></pre>\n" }, { "answer_id": 344498, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<p>You can use <a href=\"https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml\" rel=\"noreferrer\"><code>dangerouslysetinnerhtml</code></a>, a special HTML attribute in React:</p>\n\n<blockquote>\n <p><code>dangerouslySetInnerHTML</code> is React’s replacement for using <code>innerHTML</code>\n in the browser DOM. In general, setting HTML from code is risky\n because it’s easy to inadvertently expose your users to a <a href=\"https://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"noreferrer\">cross-site\n scripting (XSS)</a>\n attack. So, you can set HTML directly from React, but you have to type\n out <code>dangerouslySetInnerHTML</code> and pass an object with a <code>__html</code> key,\n to remind yourself that it’s <em>dangerous</em>.</p>\n</blockquote>\n\n<ul>\n<li><p>ES5:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.element.createElement( 'div', {\n dangerouslySetInnerHTML: {\n __html: '&lt;b&gt;HTML&lt;/b&gt; here'\n }\n} );\n</code></pre></li>\n<li><p>JSX+ESNext:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const createMarkup = ( html ) =&gt; { return { __html: html } };\n\nconst my_element = &lt;div dangerouslySetInnerHTML={ createMarkup('&lt;b&gt;HTML&lt;/b&gt; here') }&gt;&lt;/div&gt;;\n</code></pre></li>\n</ul>\n\n<p>Or in Gutenberg, you can use <a href=\"https://developer.wordpress.org/block-editor/packages/packages-element/#RawHTML\" rel=\"noreferrer\"><code>wp.element.RawHTML()</code></a> which basically does the same thing as the snippets above.</p>\n\n<ul>\n<li><p>ES5:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.element.RawHTML( {\n children: '&lt;b&gt;HTML&lt;/b&gt; here'\n} );\n</code></pre></li>\n<li><p>JSX+ESNext:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import { RawHTML } from '@wordpress/element';\n\nconst my_html = 'some dynamic &lt;b&gt;HTML&lt;/b&gt; here!';\n\nconst my_element = &lt;RawHTML&gt;{ my_html }&lt;/RawHTML&gt;;\n</code></pre></li>\n</ul>\n" } ]
2019/08/06
[ "https://wordpress.stackexchange.com/questions/344485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59902/" ]
I'm working on a custom gutenberg block, and in the `save` method, I have dynamically changing HTML in the form of a string. ```js element.createElement( 'div', null, contentString, ) ``` The above snippet just outputs the HTML as a string, converting all the symbols to HTML entities (`&lt;`, `&gt;`, etc.) How can I go about writing the actual HTML?
You can use [`dangerouslysetinnerhtml`](https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml), a special HTML attribute in React: > > `dangerouslySetInnerHTML` is React’s replacement for using `innerHTML` > in the browser DOM. In general, setting HTML from code is risky > because it’s easy to inadvertently expose your users to a [cross-site > scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) > attack. So, you can set HTML directly from React, but you have to type > out `dangerouslySetInnerHTML` and pass an object with a `__html` key, > to remind yourself that it’s *dangerous*. > > > * ES5: ```js wp.element.createElement( 'div', { dangerouslySetInnerHTML: { __html: '<b>HTML</b> here' } } ); ``` * JSX+ESNext: ```js const createMarkup = ( html ) => { return { __html: html } }; const my_element = <div dangerouslySetInnerHTML={ createMarkup('<b>HTML</b> here') }></div>; ``` Or in Gutenberg, you can use [`wp.element.RawHTML()`](https://developer.wordpress.org/block-editor/packages/packages-element/#RawHTML) which basically does the same thing as the snippets above. * ES5: ```js wp.element.RawHTML( { children: '<b>HTML</b> here' } ); ``` * JSX+ESNext: ```js import { RawHTML } from '@wordpress/element'; const my_html = 'some dynamic <b>HTML</b> here!'; const my_element = <RawHTML>{ my_html }</RawHTML>; ```
344,537
<p>I have tried every which way to authenticate a post request.</p> <ol> <li><p>WP User Plugin - As per the <a href="http://wpuserplus.com/blog/doc/wordpress-rest-api-login-user/" rel="nofollow noreferrer">docs</a>, I've logged in at <code>wp-json/wpuser/v1/user/login</code> and received my token. I've passed that token as a header called "Authorization" (also tried "authorization") with my POST request to <code>wp-json/wp/v2/job-listings/</code> I get <code>401: rest_cannot_create</code>. I also tried this with <code>authorization</code> as a parameter, as well as <code>h:authorization</code>, and with an uppercase "A" as well.</p></li> <li><p>JSON API Plugin - Generate nonce with <code>get_nonce/?controller=auth&amp;method=generate_auth_cookie</code>, generate a cookie with <code>auth/generate_auth_cookie</code> using the nonce and credentials, tried to POST with, alternatively, the cookie and the nonce as the value of an <code>X-WP-Nonce</code> header. Both return <code>403: rest_cookie_invalid_nonce</code></p></li> <li><p>Tried adding <code>RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]</code> to my <code>.htacces</code> file and tried the above.</p></li> </ol> <p>I don't want to use the Basic Auth plugin because of its security issues (and believe me, I've tried it in the past to no avail).</p> <p>Please, whatever you do, do not simply link to me to the WP REST API handbook. I have read it and I can't figure out where to get the nonce from, so I'd welcome an actual explanation on that but please don't just link me to that page.</p> <p>I'm happy to add some server code if necessary, but these plugins imply that I shouldn't have to.</p> <p>Please help. Thank you.</p>
[ { "answer_id": 344540, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You don't need plugins for authentication unless you're making a cross domain request, and to get the nonce, you just create it as you would any other nonce.</p>\n\n<p>As the handbook states:</p>\n\n<blockquote>\n <p>For developers making manual Ajax requests, the nonce will need to be passed with each request. <strong>The API uses nonces with the action set to <code>wp_rest</code></strong>. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress.</p>\n</blockquote>\n\n<p>So lets do that:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$nonce = wp_create_nonce( 'wp_rest' );\n</code></pre>\n\n<p>There's nothing special about how the nonce gets created, it's created the same way as every other nonce in WordPress. You would use the same function to put nonces on your action buttons and in your forms to improve security.</p>\n\n<p>Now we just put it in our doc in a way javascript can access it. Luckily the handbook gives us a working code example:</p>\n\n<p><a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/</a></p>\n\n<pre><code>&lt;?php\nwp_localize_script( 'wp-api', 'wpApiSettings', array(\n 'root' =&gt; esc_url_raw( rest_url() ),\n 'nonce' =&gt; wp_create_nonce( 'wp_rest' )\n) );\n</code></pre>\n\n<p>Followed by a working example of using the nonce in jQuery for an authenticated POST request:</p>\n\n<pre><code>$.ajax( {\n url: wpApiSettings.root + 'wp/v2/posts/1',\n method: 'POST',\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );\n },\n data:{\n 'title' : 'Hello Moon'\n }\n} ).done( function ( response ) {\n console.log( response );\n} );\n</code></pre>\n\n<p>If you enqueue the built in backbone based REST library, it will automatically generate the nonce using the same code above.</p>\n\n<p>This will work when combined with a cookie for a logged in user, however, it will not work for requests across domains.</p>\n\n<p>If you're trying to make a REST API request from another website, a CLI app, mobile app, a Node application, etc etc you will need a custom authentication plugin. You will need to consult with their documentation and support avenues though as 3rd party plugin dev support is offtopic on this stack</p>\n" }, { "answer_id": 359275, "author": "OctaviaLo", "author_id": 153787, "author_profile": "https://wordpress.stackexchange.com/users/153787", "pm_score": 0, "selected": false, "text": "<p>If anyone is looking for a solution with Fetch:</p>\n\n<pre><code> window\n.fetch(`${scriptVars.endpoint}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-WP-Nonce': scriptVars.nonce\n },\n credentials: 'same-origin',\n body: JSON.stringify(postData)\n})\n.then(() =&gt; window.alert('success'));\n</code></pre>\n" } ]
2019/08/06
[ "https://wordpress.stackexchange.com/questions/344537", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164858/" ]
I have tried every which way to authenticate a post request. 1. WP User Plugin - As per the [docs](http://wpuserplus.com/blog/doc/wordpress-rest-api-login-user/), I've logged in at `wp-json/wpuser/v1/user/login` and received my token. I've passed that token as a header called "Authorization" (also tried "authorization") with my POST request to `wp-json/wp/v2/job-listings/` I get `401: rest_cannot_create`. I also tried this with `authorization` as a parameter, as well as `h:authorization`, and with an uppercase "A" as well. 2. JSON API Plugin - Generate nonce with `get_nonce/?controller=auth&method=generate_auth_cookie`, generate a cookie with `auth/generate_auth_cookie` using the nonce and credentials, tried to POST with, alternatively, the cookie and the nonce as the value of an `X-WP-Nonce` header. Both return `403: rest_cookie_invalid_nonce` 3. Tried adding `RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]` to my `.htacces` file and tried the above. I don't want to use the Basic Auth plugin because of its security issues (and believe me, I've tried it in the past to no avail). Please, whatever you do, do not simply link to me to the WP REST API handbook. I have read it and I can't figure out where to get the nonce from, so I'd welcome an actual explanation on that but please don't just link me to that page. I'm happy to add some server code if necessary, but these plugins imply that I shouldn't have to. Please help. Thank you.
You don't need plugins for authentication unless you're making a cross domain request, and to get the nonce, you just create it as you would any other nonce. As the handbook states: > > For developers making manual Ajax requests, the nonce will need to be passed with each request. **The API uses nonces with the action set to `wp_rest`**. These can then be passed to the API via the \_wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress. > > > So lets do that: ```php $nonce = wp_create_nonce( 'wp_rest' ); ``` There's nothing special about how the nonce gets created, it's created the same way as every other nonce in WordPress. You would use the same function to put nonces on your action buttons and in your forms to improve security. Now we just put it in our doc in a way javascript can access it. Luckily the handbook gives us a working code example: <https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/> ``` <?php wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) ); ``` Followed by a working example of using the nonce in jQuery for an authenticated POST request: ``` $.ajax( { url: wpApiSettings.root + 'wp/v2/posts/1', method: 'POST', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data:{ 'title' : 'Hello Moon' } } ).done( function ( response ) { console.log( response ); } ); ``` If you enqueue the built in backbone based REST library, it will automatically generate the nonce using the same code above. This will work when combined with a cookie for a logged in user, however, it will not work for requests across domains. If you're trying to make a REST API request from another website, a CLI app, mobile app, a Node application, etc etc you will need a custom authentication plugin. You will need to consult with their documentation and support avenues though as 3rd party plugin dev support is offtopic on this stack
344,557
<p>The following code <a href="https://wordpress.stackexchange.com/a/344400/79855">from a previous answer</a> to one of my questions displays Woocommerce "Size" product attributes below each product on the shop page: </p> <pre><code>add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 ); function display_size_attribute() { global $product; if ( $product-&gt;is_type('variable') ) { $taxonomy = 'pa_size'; echo '&lt;span class="attribute-size"&gt;' . $product-&gt;get_attribute($taxonomy) . '&lt;/span&gt;'; } } </code></pre> <p>How do I change the code to only display "in-stock" items <em>(of product attribute "Size")</em>?</p>
[ { "answer_id": 344561, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>To get only available \"In stock\" displayed sizes, you need something a little more complicated and different:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item_title', 'display_instock_sizes', 5 );\nfunction display_instock_sizes() {\n global $product;\n\n if ( $product-&gt;is_type('variable') ) {\n $taxonomy = 'pa_size'; // The product attribute taxonomy\n $sizes_array = []; // Initializing\n\n // Loop through available variation Ids for the variable product\n foreach( $product-&gt;get_children() as $child_id ) {\n $variation = wc_get_product( $child_id ); // Get the WC_Product_Variation object\n\n if( $variation-&gt;is_purchasable() &amp;&amp; $variation-&gt;is_in_stock() ) {\n $term_name = $variation-&gt;get_attribute( $taxonomy );\n $sizes_array[$term_name] = $term_name;\n }\n }\n\n echo '&lt;span class=\"attribute-size\"&gt;' . implode( ', ', $sizes_array ) . '&lt;/span&gt;';\n }\n}\n</code></pre>\n\n<p><em>Code goes in functions.php file of the active child theme (or active theme).</em> Tested and works.</p>\n" }, { "answer_id": 365558, "author": "Plus Internet", "author_id": 184739, "author_profile": "https://wordpress.stackexchange.com/users/184739", "pm_score": 0, "selected": false, "text": "<p>I would also love to know how to edit the code to include multiple attributes.</p>\n\n<p>For example I have the code working with \"pa_select-size\" attribute but on our footwear category we use pa_shoe-size.</p>\n\n<p>Many thanks,</p>\n\n<p>Luke</p>\n" } ]
2019/08/07
[ "https://wordpress.stackexchange.com/questions/344557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118008/" ]
The following code [from a previous answer](https://wordpress.stackexchange.com/a/344400/79855) to one of my questions displays Woocommerce "Size" product attributes below each product on the shop page: ``` add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 ); function display_size_attribute() { global $product; if ( $product->is_type('variable') ) { $taxonomy = 'pa_size'; echo '<span class="attribute-size">' . $product->get_attribute($taxonomy) . '</span>'; } } ``` How do I change the code to only display "in-stock" items *(of product attribute "Size")*?
To get only available "In stock" displayed sizes, you need something a little more complicated and different: ``` add_action( 'woocommerce_after_shop_loop_item_title', 'display_instock_sizes', 5 ); function display_instock_sizes() { global $product; if ( $product->is_type('variable') ) { $taxonomy = 'pa_size'; // The product attribute taxonomy $sizes_array = []; // Initializing // Loop through available variation Ids for the variable product foreach( $product->get_children() as $child_id ) { $variation = wc_get_product( $child_id ); // Get the WC_Product_Variation object if( $variation->is_purchasable() && $variation->is_in_stock() ) { $term_name = $variation->get_attribute( $taxonomy ); $sizes_array[$term_name] = $term_name; } } echo '<span class="attribute-size">' . implode( ', ', $sizes_array ) . '</span>'; } } ``` *Code goes in functions.php file of the active child theme (or active theme).* Tested and works.
344,562
<p>I am working on this site for my own business and when I create a menu with child links, as per below image, only last child of that drop down menu, it actually clicks and loads a page.</p> <p><a href="https://i.stack.imgur.com/5UYwY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5UYwY.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/IwafX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IwafX.png" alt="enter image description here"></a></p> <p>If I click any of the parent links to that last child '1 gang', none of those will work.</p> <p><a href="https://i.stack.imgur.com/WftQ5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WftQ5.png" alt="enter image description here"></a></p> <p>But if I type the full URL with that path, <a href="http://x.x.x.x/test-products-only/" rel="nofollow noreferrer">http://x.x.x.x/test-products-only/</a> or any of the 2 subsequent child to that, pages load and do show the categories group. </p> <p>So it not like page is disabled, seems that the parents get something like a noclick property or something.</p> <p>I am not touching the code so far as it's just creating a few pages and then the menus from Appearance > Menus.</p> <p>Any advise is appreciated.</p> <p>Cheers.</p>
[ { "answer_id": 344561, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>To get only available \"In stock\" displayed sizes, you need something a little more complicated and different:</p>\n\n<pre><code>add_action( 'woocommerce_after_shop_loop_item_title', 'display_instock_sizes', 5 );\nfunction display_instock_sizes() {\n global $product;\n\n if ( $product-&gt;is_type('variable') ) {\n $taxonomy = 'pa_size'; // The product attribute taxonomy\n $sizes_array = []; // Initializing\n\n // Loop through available variation Ids for the variable product\n foreach( $product-&gt;get_children() as $child_id ) {\n $variation = wc_get_product( $child_id ); // Get the WC_Product_Variation object\n\n if( $variation-&gt;is_purchasable() &amp;&amp; $variation-&gt;is_in_stock() ) {\n $term_name = $variation-&gt;get_attribute( $taxonomy );\n $sizes_array[$term_name] = $term_name;\n }\n }\n\n echo '&lt;span class=\"attribute-size\"&gt;' . implode( ', ', $sizes_array ) . '&lt;/span&gt;';\n }\n}\n</code></pre>\n\n<p><em>Code goes in functions.php file of the active child theme (or active theme).</em> Tested and works.</p>\n" }, { "answer_id": 365558, "author": "Plus Internet", "author_id": 184739, "author_profile": "https://wordpress.stackexchange.com/users/184739", "pm_score": 0, "selected": false, "text": "<p>I would also love to know how to edit the code to include multiple attributes.</p>\n\n<p>For example I have the code working with \"pa_select-size\" attribute but on our footwear category we use pa_shoe-size.</p>\n\n<p>Many thanks,</p>\n\n<p>Luke</p>\n" } ]
2019/08/07
[ "https://wordpress.stackexchange.com/questions/344562", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173119/" ]
I am working on this site for my own business and when I create a menu with child links, as per below image, only last child of that drop down menu, it actually clicks and loads a page. [![enter image description here](https://i.stack.imgur.com/5UYwY.png)](https://i.stack.imgur.com/5UYwY.png) [![enter image description here](https://i.stack.imgur.com/IwafX.png)](https://i.stack.imgur.com/IwafX.png) If I click any of the parent links to that last child '1 gang', none of those will work. [![enter image description here](https://i.stack.imgur.com/WftQ5.png)](https://i.stack.imgur.com/WftQ5.png) But if I type the full URL with that path, <http://x.x.x.x/test-products-only/> or any of the 2 subsequent child to that, pages load and do show the categories group. So it not like page is disabled, seems that the parents get something like a noclick property or something. I am not touching the code so far as it's just creating a few pages and then the menus from Appearance > Menus. Any advise is appreciated. Cheers.
To get only available "In stock" displayed sizes, you need something a little more complicated and different: ``` add_action( 'woocommerce_after_shop_loop_item_title', 'display_instock_sizes', 5 ); function display_instock_sizes() { global $product; if ( $product->is_type('variable') ) { $taxonomy = 'pa_size'; // The product attribute taxonomy $sizes_array = []; // Initializing // Loop through available variation Ids for the variable product foreach( $product->get_children() as $child_id ) { $variation = wc_get_product( $child_id ); // Get the WC_Product_Variation object if( $variation->is_purchasable() && $variation->is_in_stock() ) { $term_name = $variation->get_attribute( $taxonomy ); $sizes_array[$term_name] = $term_name; } } echo '<span class="attribute-size">' . implode( ', ', $sizes_array ) . '</span>'; } } ``` *Code goes in functions.php file of the active child theme (or active theme).* Tested and works.
344,572
<p>Let me start saying that I know a 'tax_query' is faster than 'meta_query'.</p> <p>It's always recommended to use taxonomies over custom meta when filtering by custom data is required, but here I found myself in this situation.</p> <p>I'm creating a Real Estate application where I have this obvious post type 'property'. Each property is supposed to have X number of rooms and bathrooms.</p> <p>Then in my app you can filter properties by range... for example: Show all properties that have from 3 to 18 rooms.</p> <p>The custom field way would be to add a custom field, eg: 'rooms' and then do my query like:</p> <pre class="lang-php prettyprint-override"><code>$args = array( 'post_type' =&gt; 'property', 'meta_query' =&gt; array( 'key' =&gt; 'rooms', 'value' =&gt; array(3,18), 'type' =&gt; 'numeric', 'compare' =&gt; 'BETWEEN', ), ); $query = new WP_Query( $args ); </code></pre> <p>The taxonomy way would be for example to create a custom taxonomy called 'property_rooms', then create the terms like '1', '2', '3', etc.. and do my query by term ID's like:</p> <pre><code>$args = array( 'post_type' =&gt; 'property', 'tax_query' =&gt; array( 'taxonomy' =&gt; 'property_rooms', 'terms' =&gt; array(3,4,5,6,7,8,9,10,11,12,13,14,15...etc) // Just pretend these are the corresponding term id's ) ); $query = new WP_Query( $args ); </code></pre> <p>And here's the question: <strong>Does tax_query beats meta_query even in situations like this?</strong></p> <p>It may be relevant to mention that we could be talking about thousands of properties.</p> <p>Keep in mind sorting by these fields is neither a requirement nor a consideration to trade the speed of the query.</p>
[ { "answer_id": 344575, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>Well, I wouldn't say that <em>\"tax_query beats meta_query\"</em>... They're a little bit different things.</p>\n\n<p>When you perform tax_query, then two JOINS are needed in your SQL query. Meta_query results in only one join (if you search for only one meta).</p>\n\n<p>So when is the tax_query better? For example when you search for posts assigned to multiple taxonomies.</p>\n\n<p>Let's say you want to find properties that have 2 floors, 4 bedrooms, separate kitchen, and a garage. So you're doing a search with multiple conditions based on multiple properties.</p>\n\n<p>In such case:</p>\n\n<ul>\n<li>tax_query will result in an SQL query with just 2 JOINS and multiple conditions in WHERE part.</li>\n<li>meta_query will result in an SQL query with 1 JOIN for every property in your search.</li>\n</ul>\n\n<p>And even worse - tax_query uses proper IDs and keys and in meta_query you'll have to use strings as keys. So yeah - in such case tax_query has to be faster.</p>\n\n<p>But... Tax_queries are really bad choice if:</p>\n\n<ul>\n<li>you need to order by its value (i.e. order properties by their price), </li>\n<li>you search for all values within given range (i.e. search for properties within given price range),</li>\n<li>you have a lot of different values for given property (i.e. price since there will be almost the same number of different prices as properties).</li>\n</ul>\n\n<p>So no - tax_query does not beat meta_query every time. They're different things and you should use them according to your needs.</p>\n" }, { "answer_id": 344576, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Does tax_query beats meta_query even in situations like this?</p>\n</blockquote>\n\n<p>No.</p>\n\n<p>Taxonomies are appropriate if you have a common set of values that are shared by many posts, and you're doing a simple comparison based on whether the post has or does not have a particular value. They are <em>not</em> appropriate if you need to perform numerical or range comparisons, like your example, or if the values are going to be unique for every post.</p>\n\n<p>Here's some examples of what should and should not be a taxonomy on a Real Estate site:</p>\n\n<ul>\n<li>Property type eg. House/Apartment/Townhouse, should be a taxonomy.</li>\n<li>Buy/Rent should be a taxonomy.</li>\n<li>Features eg. Pets allowed/Air conditioning/Dishwasher, should be a taxonomy.</li>\n<li>No. of bedrooms, should be meta.</li>\n<li>No. of parking spaces, should be meta.</li>\n<li>Address, should be meta.</li>\n</ul>\n\n<p>On top of being faster to query, having taxonomies for those properties makes managing them easier in the back-end, and makes generating a list for filtering considerably easier and faster.</p>\n\n<p>However, keep in mind that even if meta is the only viable option for filtering a value, using too many meta queries will really hurt the performance of the query. This is because you are querying based on the <em>value</em> of the meta, rather than an ID, and the value column is not indexed. However, just because it's not indexed doesn't mean it would be appropriate to index it yourself. This is because the meta_value column of wp_postmeta holds vastly different kinds and amounts of data for different things. </p>\n\n<p>If you have a large number of numerical fields that you need to use for filtering, neither post meta nor taxonomies might be appropriate. You might be better off creating a custom table with your own indexes and more appropriate column types. You could then store those values in your custom table, and use the <code>posts_clauses</code>, or <code>posts_join</code>, and <code>posts_where</code> filters to add your own SQL to WP_Query to use your table for more efficient filtering.</p>\n" } ]
2019/08/07
[ "https://wordpress.stackexchange.com/questions/344572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126374/" ]
Let me start saying that I know a 'tax\_query' is faster than 'meta\_query'. It's always recommended to use taxonomies over custom meta when filtering by custom data is required, but here I found myself in this situation. I'm creating a Real Estate application where I have this obvious post type 'property'. Each property is supposed to have X number of rooms and bathrooms. Then in my app you can filter properties by range... for example: Show all properties that have from 3 to 18 rooms. The custom field way would be to add a custom field, eg: 'rooms' and then do my query like: ```php $args = array( 'post_type' => 'property', 'meta_query' => array( 'key' => 'rooms', 'value' => array(3,18), 'type' => 'numeric', 'compare' => 'BETWEEN', ), ); $query = new WP_Query( $args ); ``` The taxonomy way would be for example to create a custom taxonomy called 'property\_rooms', then create the terms like '1', '2', '3', etc.. and do my query by term ID's like: ``` $args = array( 'post_type' => 'property', 'tax_query' => array( 'taxonomy' => 'property_rooms', 'terms' => array(3,4,5,6,7,8,9,10,11,12,13,14,15...etc) // Just pretend these are the corresponding term id's ) ); $query = new WP_Query( $args ); ``` And here's the question: **Does tax\_query beats meta\_query even in situations like this?** It may be relevant to mention that we could be talking about thousands of properties. Keep in mind sorting by these fields is neither a requirement nor a consideration to trade the speed of the query.
> > Does tax\_query beats meta\_query even in situations like this? > > > No. Taxonomies are appropriate if you have a common set of values that are shared by many posts, and you're doing a simple comparison based on whether the post has or does not have a particular value. They are *not* appropriate if you need to perform numerical or range comparisons, like your example, or if the values are going to be unique for every post. Here's some examples of what should and should not be a taxonomy on a Real Estate site: * Property type eg. House/Apartment/Townhouse, should be a taxonomy. * Buy/Rent should be a taxonomy. * Features eg. Pets allowed/Air conditioning/Dishwasher, should be a taxonomy. * No. of bedrooms, should be meta. * No. of parking spaces, should be meta. * Address, should be meta. On top of being faster to query, having taxonomies for those properties makes managing them easier in the back-end, and makes generating a list for filtering considerably easier and faster. However, keep in mind that even if meta is the only viable option for filtering a value, using too many meta queries will really hurt the performance of the query. This is because you are querying based on the *value* of the meta, rather than an ID, and the value column is not indexed. However, just because it's not indexed doesn't mean it would be appropriate to index it yourself. This is because the meta\_value column of wp\_postmeta holds vastly different kinds and amounts of data for different things. If you have a large number of numerical fields that you need to use for filtering, neither post meta nor taxonomies might be appropriate. You might be better off creating a custom table with your own indexes and more appropriate column types. You could then store those values in your custom table, and use the `posts_clauses`, or `posts_join`, and `posts_where` filters to add your own SQL to WP\_Query to use your table for more efficient filtering.
344,791
<p>I currently have a global function in my functions.php file</p> <pre><code>ein_error_log($message) { //push out $message to file... } </code></pre> <p>But I want to start using it in my MU-Plugin directory and it doesn't know it exists. So I assume it's because MU-Plugins folder is read before the theme folder in WordPress's hierarchy, which makes sense. </p> <p>But if the hierarchy is the case, how do I distinguish which MU-Plugin runs first to make sure all other MU-Plugin files can run dependent on said file? </p> <p>-- UPDATE--</p> <p>I have my ein_error_log($message) method transferred into an mu-plugin file. I realized how silly it was to have mu-plugin files dependent on a method inside function.php file. But I still wanted the other mu-plugin files to also use this error logging method. This requires some mu-plugins to have a dependency. Its small, but important to me.</p>
[ { "answer_id": 344575, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>Well, I wouldn't say that <em>\"tax_query beats meta_query\"</em>... They're a little bit different things.</p>\n\n<p>When you perform tax_query, then two JOINS are needed in your SQL query. Meta_query results in only one join (if you search for only one meta).</p>\n\n<p>So when is the tax_query better? For example when you search for posts assigned to multiple taxonomies.</p>\n\n<p>Let's say you want to find properties that have 2 floors, 4 bedrooms, separate kitchen, and a garage. So you're doing a search with multiple conditions based on multiple properties.</p>\n\n<p>In such case:</p>\n\n<ul>\n<li>tax_query will result in an SQL query with just 2 JOINS and multiple conditions in WHERE part.</li>\n<li>meta_query will result in an SQL query with 1 JOIN for every property in your search.</li>\n</ul>\n\n<p>And even worse - tax_query uses proper IDs and keys and in meta_query you'll have to use strings as keys. So yeah - in such case tax_query has to be faster.</p>\n\n<p>But... Tax_queries are really bad choice if:</p>\n\n<ul>\n<li>you need to order by its value (i.e. order properties by their price), </li>\n<li>you search for all values within given range (i.e. search for properties within given price range),</li>\n<li>you have a lot of different values for given property (i.e. price since there will be almost the same number of different prices as properties).</li>\n</ul>\n\n<p>So no - tax_query does not beat meta_query every time. They're different things and you should use them according to your needs.</p>\n" }, { "answer_id": 344576, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Does tax_query beats meta_query even in situations like this?</p>\n</blockquote>\n\n<p>No.</p>\n\n<p>Taxonomies are appropriate if you have a common set of values that are shared by many posts, and you're doing a simple comparison based on whether the post has or does not have a particular value. They are <em>not</em> appropriate if you need to perform numerical or range comparisons, like your example, or if the values are going to be unique for every post.</p>\n\n<p>Here's some examples of what should and should not be a taxonomy on a Real Estate site:</p>\n\n<ul>\n<li>Property type eg. House/Apartment/Townhouse, should be a taxonomy.</li>\n<li>Buy/Rent should be a taxonomy.</li>\n<li>Features eg. Pets allowed/Air conditioning/Dishwasher, should be a taxonomy.</li>\n<li>No. of bedrooms, should be meta.</li>\n<li>No. of parking spaces, should be meta.</li>\n<li>Address, should be meta.</li>\n</ul>\n\n<p>On top of being faster to query, having taxonomies for those properties makes managing them easier in the back-end, and makes generating a list for filtering considerably easier and faster.</p>\n\n<p>However, keep in mind that even if meta is the only viable option for filtering a value, using too many meta queries will really hurt the performance of the query. This is because you are querying based on the <em>value</em> of the meta, rather than an ID, and the value column is not indexed. However, just because it's not indexed doesn't mean it would be appropriate to index it yourself. This is because the meta_value column of wp_postmeta holds vastly different kinds and amounts of data for different things. </p>\n\n<p>If you have a large number of numerical fields that you need to use for filtering, neither post meta nor taxonomies might be appropriate. You might be better off creating a custom table with your own indexes and more appropriate column types. You could then store those values in your custom table, and use the <code>posts_clauses</code>, or <code>posts_join</code>, and <code>posts_where</code> filters to add your own SQL to WP_Query to use your table for more efficient filtering.</p>\n" } ]
2019/08/09
[ "https://wordpress.stackexchange.com/questions/344791", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172849/" ]
I currently have a global function in my functions.php file ``` ein_error_log($message) { //push out $message to file... } ``` But I want to start using it in my MU-Plugin directory and it doesn't know it exists. So I assume it's because MU-Plugins folder is read before the theme folder in WordPress's hierarchy, which makes sense. But if the hierarchy is the case, how do I distinguish which MU-Plugin runs first to make sure all other MU-Plugin files can run dependent on said file? -- UPDATE-- I have my ein\_error\_log($message) method transferred into an mu-plugin file. I realized how silly it was to have mu-plugin files dependent on a method inside function.php file. But I still wanted the other mu-plugin files to also use this error logging method. This requires some mu-plugins to have a dependency. Its small, but important to me.
> > Does tax\_query beats meta\_query even in situations like this? > > > No. Taxonomies are appropriate if you have a common set of values that are shared by many posts, and you're doing a simple comparison based on whether the post has or does not have a particular value. They are *not* appropriate if you need to perform numerical or range comparisons, like your example, or if the values are going to be unique for every post. Here's some examples of what should and should not be a taxonomy on a Real Estate site: * Property type eg. House/Apartment/Townhouse, should be a taxonomy. * Buy/Rent should be a taxonomy. * Features eg. Pets allowed/Air conditioning/Dishwasher, should be a taxonomy. * No. of bedrooms, should be meta. * No. of parking spaces, should be meta. * Address, should be meta. On top of being faster to query, having taxonomies for those properties makes managing them easier in the back-end, and makes generating a list for filtering considerably easier and faster. However, keep in mind that even if meta is the only viable option for filtering a value, using too many meta queries will really hurt the performance of the query. This is because you are querying based on the *value* of the meta, rather than an ID, and the value column is not indexed. However, just because it's not indexed doesn't mean it would be appropriate to index it yourself. This is because the meta\_value column of wp\_postmeta holds vastly different kinds and amounts of data for different things. If you have a large number of numerical fields that you need to use for filtering, neither post meta nor taxonomies might be appropriate. You might be better off creating a custom table with your own indexes and more appropriate column types. You could then store those values in your custom table, and use the `posts_clauses`, or `posts_join`, and `posts_where` filters to add your own SQL to WP\_Query to use your table for more efficient filtering.
344,792
<p>I'm attempting to put together a variable/mixed content carousel block. I'm having issues trying to figure out how to create/delete individual slides in the carousel (using something like rangecontrol).</p> <p>So far I have this:</p> <pre><code>const ALLOWED_BLOCKS = [ 'core/paragraph' ]; const BLOCKS_TEMPLATE = [ [ 'core/columns', {}, [] ], ]; registerBlockType( 'blocks/carousel', { title: __( 'Carousel' ), icon: 'layout', attributes: { count: { type: 'number', }, }, edit( { attributes, setAttributes, className } ) { const onChangeCount = value =&gt; { setAttributes( { count: value } ); }; return [ &lt;InspectorControls key="controls"&gt; &lt;PanelBody&gt; &lt;RangeControl label={ __( 'Slides' ) } value={ attributes.count } onChange={ onChangeCount } min={ 2 } max={ 6 } /&gt; &lt;/PanelBody&gt; &lt;/InspectorControls&gt;, &lt;div className={ className } key="content"&gt; &lt;InnerBlocks template={ BLOCKS_TEMPLATE } allowedBlocks={ ALLOWED_BLOCKS } templateLock="all" /&gt; &lt;/div&gt;, ]; }, save( { attributes } ) { return ( &lt;div&gt; &lt;InnerBlocks.Content /&gt; &lt;/div&gt; ); }, } ); </code></pre> <p>So I'm not entirely sure what I need to allow for creating/deleting the slides via the range. If someone could offer me a rough solution and/or point me at some documentation I'd appreciate it.</p>
[ { "answer_id": 344954, "author": "shramee", "author_id": 92887, "author_profile": "https://wordpress.stackexchange.com/users/92887", "pm_score": 0, "selected": false, "text": "<p>Something like this...</p>\n\nCreating slides elements\n\n<pre><code>const slides = [];\n\nfor ( let i = 0; i &lt; attributes.count; i ++ ) {\n slides.push(\n &lt;li className=\"slide\" key={'slide-' + i}&gt;\n &lt;img src='img-url.jpg'/&gt;\n &lt;/li&gt;\n );\n}\n</code></pre>\n\nAdding slides to block content\n\n<pre><code>&lt;ul classname=\"slides\"&gt;{slides}&lt;/ul&gt;\n</code></pre>\n\n<p>You can use any elements per slides...</p>\n\n<p>And similarly add add additional fields for slide image and stuff if you like and later put them inside <code>InspectorControls</code> element instead of <code>ul</code> like we did for slides.</p>\n" }, { "answer_id": 344975, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 3, "selected": true, "text": "<p>The code from <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/columns\" rel=\"nofollow noreferrer\">core/columns</a> and <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/column\" rel=\"nofollow noreferrer\">core/column</a> blocks are a good example of how to achieve this behaviour. Basically we register 2 block types: Carousel and Slide.</p>\n\n<ul>\n<li><strong>Slide</strong> block type does not appear in the inserter.</li>\n<li><strong>Carousel</strong> block type is the root block which appears in the inserter. Instead of keeping the count of slides in an attribute we listen to getBlocks selector. We use the replaceInnerBlocks action to update the number of slides.</li>\n</ul>\n\n<p>If you need further explanation please let me know.</p>\n\n<pre><code>const { times } = lodash;\nconst { __ } = wp.i18n;\nconst { registerBlockType, createBlock } = wp.blocks;\nconst { PanelBody, RangeControl } = wp.components;\nconst { InnerBlocks, InspectorControls } = wp.blockEditor;\nconst { useDispatch, useSelect } = wp.data;\nconst { Fragment } = wp.element;\n\nregisterBlockType(\"my-plugin/slide\", {\n title: __(\"Slide\"),\n icon: \"carrot\",\n category: \"common\",\n attributes: {},\n supports: { inserter: false },\n edit(props) {\n const { className } = props;\n\n return (\n &lt;div className={className}&gt;\n &lt;InnerBlocks\n allowedBlocks={[\"core/quote\", \"core/gallery\"]}\n templateLock={false}\n /&gt;\n &lt;/div&gt;\n );\n },\n save(props) {\n return (\n &lt;div&gt;\n &lt;InnerBlocks.Content /&gt;\n &lt;/div&gt;\n );\n }\n});\n\nregisterBlockType(\"my-plugin/carousel\", {\n title: __(\"Carousel\"),\n icon: \"layout\",\n category: \"common\",\n attributes: {},\n edit(props) {\n const { className, clientId } = props;\n const { replaceInnerBlocks } = useDispatch(\"core/block-editor\");\n const { slides } = useSelect(select =&gt; ({\n slides: select(\"core/block-editor\").getBlocks(clientId)\n }));\n\n return (\n &lt;div className={className}&gt;\n &lt;InspectorControls&gt;\n &lt;PanelBody&gt;\n &lt;RangeControl\n label={__(\"Slides\")}\n value={slides.length}\n min={2}\n max={6}\n onChange={count =&gt; {\n let inner_blocks = slides;\n\n if (slides.length &lt; count) {\n inner_blocks = [\n ...inner_blocks,\n ...times(count - slides.length, () =&gt;\n createBlock(\"my-plugin/slide\")\n )\n ];\n } else if (slides.length &gt; count) {\n inner_blocks = inner_blocks.slice(0, count);\n }\n\n replaceInnerBlocks(clientId, inner_blocks, false);\n }}\n /&gt;\n &lt;/PanelBody&gt;\n &lt;/InspectorControls&gt;\n &lt;InnerBlocks\n template={[[\"my-plugin/slide\"], [\"my-plugin/slide\"]]}\n allowedBlocks={[\"my-plugin/slide\"]}\n templateLock=\"all\"\n /&gt;\n &lt;/div&gt;\n );\n },\n save(props) {\n return (\n &lt;div&gt;\n &lt;InnerBlocks.Content /&gt;\n &lt;/div&gt;\n );\n }\n});\n</code></pre>\n" } ]
2019/08/09
[ "https://wordpress.stackexchange.com/questions/344792", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98703/" ]
I'm attempting to put together a variable/mixed content carousel block. I'm having issues trying to figure out how to create/delete individual slides in the carousel (using something like rangecontrol). So far I have this: ``` const ALLOWED_BLOCKS = [ 'core/paragraph' ]; const BLOCKS_TEMPLATE = [ [ 'core/columns', {}, [] ], ]; registerBlockType( 'blocks/carousel', { title: __( 'Carousel' ), icon: 'layout', attributes: { count: { type: 'number', }, }, edit( { attributes, setAttributes, className } ) { const onChangeCount = value => { setAttributes( { count: value } ); }; return [ <InspectorControls key="controls"> <PanelBody> <RangeControl label={ __( 'Slides' ) } value={ attributes.count } onChange={ onChangeCount } min={ 2 } max={ 6 } /> </PanelBody> </InspectorControls>, <div className={ className } key="content"> <InnerBlocks template={ BLOCKS_TEMPLATE } allowedBlocks={ ALLOWED_BLOCKS } templateLock="all" /> </div>, ]; }, save( { attributes } ) { return ( <div> <InnerBlocks.Content /> </div> ); }, } ); ``` So I'm not entirely sure what I need to allow for creating/deleting the slides via the range. If someone could offer me a rough solution and/or point me at some documentation I'd appreciate it.
The code from [core/columns](https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/columns) and [core/column](https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/column) blocks are a good example of how to achieve this behaviour. Basically we register 2 block types: Carousel and Slide. * **Slide** block type does not appear in the inserter. * **Carousel** block type is the root block which appears in the inserter. Instead of keeping the count of slides in an attribute we listen to getBlocks selector. We use the replaceInnerBlocks action to update the number of slides. If you need further explanation please let me know. ``` const { times } = lodash; const { __ } = wp.i18n; const { registerBlockType, createBlock } = wp.blocks; const { PanelBody, RangeControl } = wp.components; const { InnerBlocks, InspectorControls } = wp.blockEditor; const { useDispatch, useSelect } = wp.data; const { Fragment } = wp.element; registerBlockType("my-plugin/slide", { title: __("Slide"), icon: "carrot", category: "common", attributes: {}, supports: { inserter: false }, edit(props) { const { className } = props; return ( <div className={className}> <InnerBlocks allowedBlocks={["core/quote", "core/gallery"]} templateLock={false} /> </div> ); }, save(props) { return ( <div> <InnerBlocks.Content /> </div> ); } }); registerBlockType("my-plugin/carousel", { title: __("Carousel"), icon: "layout", category: "common", attributes: {}, edit(props) { const { className, clientId } = props; const { replaceInnerBlocks } = useDispatch("core/block-editor"); const { slides } = useSelect(select => ({ slides: select("core/block-editor").getBlocks(clientId) })); return ( <div className={className}> <InspectorControls> <PanelBody> <RangeControl label={__("Slides")} value={slides.length} min={2} max={6} onChange={count => { let inner_blocks = slides; if (slides.length < count) { inner_blocks = [ ...inner_blocks, ...times(count - slides.length, () => createBlock("my-plugin/slide") ) ]; } else if (slides.length > count) { inner_blocks = inner_blocks.slice(0, count); } replaceInnerBlocks(clientId, inner_blocks, false); }} /> </PanelBody> </InspectorControls> <InnerBlocks template={[["my-plugin/slide"], ["my-plugin/slide"]]} allowedBlocks={["my-plugin/slide"]} templateLock="all" /> </div> ); }, save(props) { return ( <div> <InnerBlocks.Content /> </div> ); } }); ```
344,800
<p>I'm building a block that has, among other things, a FontAwesome icon. I'm currently letting users choose which icon by using a WP <code>&lt;SelectControl&gt;</code>.</p> <p>For individual <code>&lt;option&gt;</code>s, there is a built-in way to add a label. For example:</p> <pre><code>&lt;SelectControl value={ icon } options={[ { label: '', value: 'fa-address-book' } ]} /&gt; </code></pre> <p>Combined with CSS this works great - the dropdown shows the icon itself, making it easy to select for those with good vision. However, I'd like to make this more accessible by adding an <code>aria-label</code> for each <code>&lt;option&gt;</code>.</p> <p>I tried</p> <pre><code>&lt;SelectControl value={ icon } options={[ { label: '', value: 'fa-address-book', 'aria-label': 'Address book' } ]} /&gt; </code></pre> <p>but the <code>aria-label</code> does not actually render. Is there another way to add it?</p> <p>The HTML output I'm looking for:</p> <pre><code>&lt;select id="inspector-select-control-0" class="components-select-control__input"&gt; &lt;option value="fa-address-book" aria-label="Address book"&gt;&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I would also be all right with using a screen reader only class in the label itself, but when I try this</p> <pre><code>&lt;SelectControl value={ icon } options={[ { label: '&lt;span class="show-for-sr"&gt;Address book&lt;/span&gt;', value: 'fa-address-book' } ]} /&gt; </code></pre> <p>the &lt; and &gt; tags show literally in the label rather than creating an actual separate HTML <code>&lt;span&gt;</code>.</p>
[ { "answer_id": 344806, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>Looking at the <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/components/src/select-control/index.js\" rel=\"nofollow noreferrer\">code</a>, right now it's not possible to add anything to an option inside the SelectControl besides a label, a value, an optional disabled keyword, and an id which is automatically generated from the label and value.</p>\n" }, { "answer_id": 344830, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>I agree with Nathan's answer, but you can copy the <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/components/src/select-control/index.js\" rel=\"nofollow noreferrer\">source</a> and create your own <code>SelectControl</code> component based on that source. <a href=\"https://gist.github.com/5ally/29a5b7f3e0c047e654b368ebd10908cb\" rel=\"nofollow noreferrer\">Here's an example</a>, with basically just the <code>aria-label</code> addition:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>&lt;option\n key={ `${ option.label }-${ option.value }-${ index }` }\n value={ option.value }\n disabled={ option.disabled }\n aria-label={ option.ariaLabel || '' }\n&gt;\n { option.label }\n&lt;/option&gt;\n</code></pre>\n\n<p>And a sample <code>index.js</code> file demonstrating usage of the custom <code>SelectControl</code> component:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import SelectControl from './select-control-custom'; // make sure the path is correct\nimport { withState } from '@wordpress/compose';\n\nconst MySelectControl = withState( {\n size: '50%',\n} )( ( { size, setState } ) =&gt; (\n &lt;SelectControl\n label=\"Size\"\n value={ size }\n options={ [\n { label: 'Big', value: '100%', ariaLabel: 'Aria label for Big' },\n { label: 'Medium', value: '50%', ariaLabel: 'Aria label for Medium' },\n { label: 'Small', value: '25%', ariaLabel: 'Aria label for Small' },\n ] }\n /&gt;\n) );\n</code></pre>\n\n<p>I.e. Use the <code>ariaLabel</code> property/key to set the ARIA label. And the above is based on <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/components/src/select-control#usage-1\" rel=\"nofollow noreferrer\">the example here</a>.</p>\n" } ]
2019/08/09
[ "https://wordpress.stackexchange.com/questions/344800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102815/" ]
I'm building a block that has, among other things, a FontAwesome icon. I'm currently letting users choose which icon by using a WP `<SelectControl>`. For individual `<option>`s, there is a built-in way to add a label. For example: ``` <SelectControl value={ icon } options={[ { label: '', value: 'fa-address-book' } ]} /> ``` Combined with CSS this works great - the dropdown shows the icon itself, making it easy to select for those with good vision. However, I'd like to make this more accessible by adding an `aria-label` for each `<option>`. I tried ``` <SelectControl value={ icon } options={[ { label: '', value: 'fa-address-book', 'aria-label': 'Address book' } ]} /> ``` but the `aria-label` does not actually render. Is there another way to add it? The HTML output I'm looking for: ``` <select id="inspector-select-control-0" class="components-select-control__input"> <option value="fa-address-book" aria-label="Address book"></option> </select> ``` I would also be all right with using a screen reader only class in the label itself, but when I try this ``` <SelectControl value={ icon } options={[ { label: '<span class="show-for-sr">Address book</span>', value: 'fa-address-book' } ]} /> ``` the < and > tags show literally in the label rather than creating an actual separate HTML `<span>`.
I agree with Nathan's answer, but you can copy the [source](https://github.com/WordPress/gutenberg/blob/master/packages/components/src/select-control/index.js) and create your own `SelectControl` component based on that source. [Here's an example](https://gist.github.com/5ally/29a5b7f3e0c047e654b368ebd10908cb), with basically just the `aria-label` addition: ```js <option key={ `${ option.label }-${ option.value }-${ index }` } value={ option.value } disabled={ option.disabled } aria-label={ option.ariaLabel || '' } > { option.label } </option> ``` And a sample `index.js` file demonstrating usage of the custom `SelectControl` component: ```js import SelectControl from './select-control-custom'; // make sure the path is correct import { withState } from '@wordpress/compose'; const MySelectControl = withState( { size: '50%', } )( ( { size, setState } ) => ( <SelectControl label="Size" value={ size } options={ [ { label: 'Big', value: '100%', ariaLabel: 'Aria label for Big' }, { label: 'Medium', value: '50%', ariaLabel: 'Aria label for Medium' }, { label: 'Small', value: '25%', ariaLabel: 'Aria label for Small' }, ] } /> ) ); ``` I.e. Use the `ariaLabel` property/key to set the ARIA label. And the above is based on [the example here](https://github.com/WordPress/gutenberg/tree/master/packages/components/src/select-control#usage-1).
344,804
<p>I have a user profile field that I would like to allow users to edit, but I have the backend dashboard/profile disabled. If I only know the meta (dbem_paypal_account), how can I make this work? I've tried a few plugins, but have had no luck so far.</p> <p>Basically, I would like to add a text field onto a page allowing the user to change this particular field. I hope that's clear. Thanks yall!</p>
[ { "answer_id": 344806, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>Looking at the <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/components/src/select-control/index.js\" rel=\"nofollow noreferrer\">code</a>, right now it's not possible to add anything to an option inside the SelectControl besides a label, a value, an optional disabled keyword, and an id which is automatically generated from the label and value.</p>\n" }, { "answer_id": 344830, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>I agree with Nathan's answer, but you can copy the <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/components/src/select-control/index.js\" rel=\"nofollow noreferrer\">source</a> and create your own <code>SelectControl</code> component based on that source. <a href=\"https://gist.github.com/5ally/29a5b7f3e0c047e654b368ebd10908cb\" rel=\"nofollow noreferrer\">Here's an example</a>, with basically just the <code>aria-label</code> addition:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>&lt;option\n key={ `${ option.label }-${ option.value }-${ index }` }\n value={ option.value }\n disabled={ option.disabled }\n aria-label={ option.ariaLabel || '' }\n&gt;\n { option.label }\n&lt;/option&gt;\n</code></pre>\n\n<p>And a sample <code>index.js</code> file demonstrating usage of the custom <code>SelectControl</code> component:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import SelectControl from './select-control-custom'; // make sure the path is correct\nimport { withState } from '@wordpress/compose';\n\nconst MySelectControl = withState( {\n size: '50%',\n} )( ( { size, setState } ) =&gt; (\n &lt;SelectControl\n label=\"Size\"\n value={ size }\n options={ [\n { label: 'Big', value: '100%', ariaLabel: 'Aria label for Big' },\n { label: 'Medium', value: '50%', ariaLabel: 'Aria label for Medium' },\n { label: 'Small', value: '25%', ariaLabel: 'Aria label for Small' },\n ] }\n /&gt;\n) );\n</code></pre>\n\n<p>I.e. Use the <code>ariaLabel</code> property/key to set the ARIA label. And the above is based on <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/components/src/select-control#usage-1\" rel=\"nofollow noreferrer\">the example here</a>.</p>\n" } ]
2019/08/09
[ "https://wordpress.stackexchange.com/questions/344804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170312/" ]
I have a user profile field that I would like to allow users to edit, but I have the backend dashboard/profile disabled. If I only know the meta (dbem\_paypal\_account), how can I make this work? I've tried a few plugins, but have had no luck so far. Basically, I would like to add a text field onto a page allowing the user to change this particular field. I hope that's clear. Thanks yall!
I agree with Nathan's answer, but you can copy the [source](https://github.com/WordPress/gutenberg/blob/master/packages/components/src/select-control/index.js) and create your own `SelectControl` component based on that source. [Here's an example](https://gist.github.com/5ally/29a5b7f3e0c047e654b368ebd10908cb), with basically just the `aria-label` addition: ```js <option key={ `${ option.label }-${ option.value }-${ index }` } value={ option.value } disabled={ option.disabled } aria-label={ option.ariaLabel || '' } > { option.label } </option> ``` And a sample `index.js` file demonstrating usage of the custom `SelectControl` component: ```js import SelectControl from './select-control-custom'; // make sure the path is correct import { withState } from '@wordpress/compose'; const MySelectControl = withState( { size: '50%', } )( ( { size, setState } ) => ( <SelectControl label="Size" value={ size } options={ [ { label: 'Big', value: '100%', ariaLabel: 'Aria label for Big' }, { label: 'Medium', value: '50%', ariaLabel: 'Aria label for Medium' }, { label: 'Small', value: '25%', ariaLabel: 'Aria label for Small' }, ] } /> ) ); ``` I.e. Use the `ariaLabel` property/key to set the ARIA label. And the above is based on [the example here](https://github.com/WordPress/gutenberg/tree/master/packages/components/src/select-control#usage-1).
344,808
<pre><code>$recent_query = new WP_Query(array ( 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1 ) ); //$recent_query-&gt;posts[] = get_post(1480); //$recent_query-&gt;posts[] = get_post(1443); array_unshift($recent_query-&gt;posts, get_post(1480), get_post(1443)); print_r($recent_query-&gt;posts); // The Loop if( $recent_query-&gt;have_posts() ) : ?&gt; &lt;?php while( $recent_query-&gt;have_posts()) : $recent_query-&gt;the_post() ?&gt; [...] </code></pre> <p>I want to add 2 arbitrary posts to my query and loop. either of the above methods will get the posts into <code>$recent_query-&gt;posts</code> </p> <p>Using the <code>$recent_query-&gt;posts[] = get_post(1480);</code> code, the manual posts will be in the array, but wont show up, in the loop.</p> <p>Using <code>array_unshift($recent_query-&gt;posts, get_post(1480), get_post(1443));</code> the orginal posts are deleted and shows only the manual posts, in the loop.</p>
[ { "answer_id": 344812, "author": "Faye", "author_id": 76600, "author_profile": "https://wordpress.stackexchange.com/users/76600", "pm_score": 0, "selected": false, "text": "<p>Okay, so the answer to this I think is to create a new array that combines your post IDs and the specific IDs you're trying to include, probably in the same way you've done there. Then in your query args, you, you use <code>'post__in'=&gt; $ids,</code>.</p>\n\n<p>Just as an example, here we had some posts selected via ACF, then ran them through our WP_Query.</p>\n\n<pre><code> $ids = get_field( 'acf_field_name',);\n\n $args = [\n 'post_type' =&gt; 'posts',\n 'posts_per_page' =&gt; 10,\n 'post__in' =&gt; $ids,\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'post__in',\n ];\n</code></pre>\n\n<p>All you really need to do is grab all your post ids, tack on the two in question, and use that instead of the acf get_field used in my example.</p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 344974, "author": "Doug Cassidy", "author_id": 17881, "author_profile": "https://wordpress.stackexchange.com/users/17881", "pm_score": 1, "selected": false, "text": "<p>The solution is to do two queries and then a third query, to set up the wp_query:</p>\n\n<pre><code>$query1 = new WP_Query(array (\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; $postnumber,\n 'ignore_sticky_posts' =&gt; 1,\n 'cat' =&gt; $category\n) );\n\n$query2 = new WP_Query(array(\n 'post_type' =&gt; 'page',\n 'post__in' =&gt; array(1443,1480)));\n\n$allTheposts = array_merge($query2-&gt;posts,$query1-&gt;posts);\nforeach($allTheposts as $p){\n $ids[] = $p-&gt;ID;\n}\n\n//new query, using post__in parameter\n$recent_query = new WP_Query(array(\n 'post__in' =&gt; $ids, \n 'post_type' =&gt; array('page','post'), \n 'orderby' =&gt; 'post__in'\n));\n</code></pre>\n" } ]
2019/08/09
[ "https://wordpress.stackexchange.com/questions/344808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17881/" ]
``` $recent_query = new WP_Query(array ( 'post_status' => 'publish', 'posts_per_page' => -1 ) ); //$recent_query->posts[] = get_post(1480); //$recent_query->posts[] = get_post(1443); array_unshift($recent_query->posts, get_post(1480), get_post(1443)); print_r($recent_query->posts); // The Loop if( $recent_query->have_posts() ) : ?> <?php while( $recent_query->have_posts()) : $recent_query->the_post() ?> [...] ``` I want to add 2 arbitrary posts to my query and loop. either of the above methods will get the posts into `$recent_query->posts` Using the `$recent_query->posts[] = get_post(1480);` code, the manual posts will be in the array, but wont show up, in the loop. Using `array_unshift($recent_query->posts, get_post(1480), get_post(1443));` the orginal posts are deleted and shows only the manual posts, in the loop.
The solution is to do two queries and then a third query, to set up the wp\_query: ``` $query1 = new WP_Query(array ( 'post_status' => 'publish', 'posts_per_page' => $postnumber, 'ignore_sticky_posts' => 1, 'cat' => $category ) ); $query2 = new WP_Query(array( 'post_type' => 'page', 'post__in' => array(1443,1480))); $allTheposts = array_merge($query2->posts,$query1->posts); foreach($allTheposts as $p){ $ids[] = $p->ID; } //new query, using post__in parameter $recent_query = new WP_Query(array( 'post__in' => $ids, 'post_type' => array('page','post'), 'orderby' => 'post__in' )); ```
344,844
<p>I am planing to show a new price on my woo-commerce product page for all products. This is the installment price per month. I need to show this below the normal price (variable price and simple price) something like this.</p> <p>0% interest installments starting from Rs.3,093</p> <p>where Rs.3,093 is the new price.</p> <p>this is the calculation i tried on W3 schools, and i got the calculation correct.</p> <p>whereas 60000 is the price of the product multiplied by this number 5.15464 divided by 100</p> <p>answer is 3,093 (answer should be rounded off to the nearest integer)</p> <p>I need a custom function for this where i can add to my functions.php</p> <pre><code>&lt;script&gt;var x = myFunction(60000, 5.15464, 100); function myFunction(a, b, c) { return Math.round (a * b / c);}&lt;/script&gt; </code></pre>
[ { "answer_id": 344812, "author": "Faye", "author_id": 76600, "author_profile": "https://wordpress.stackexchange.com/users/76600", "pm_score": 0, "selected": false, "text": "<p>Okay, so the answer to this I think is to create a new array that combines your post IDs and the specific IDs you're trying to include, probably in the same way you've done there. Then in your query args, you, you use <code>'post__in'=&gt; $ids,</code>.</p>\n\n<p>Just as an example, here we had some posts selected via ACF, then ran them through our WP_Query.</p>\n\n<pre><code> $ids = get_field( 'acf_field_name',);\n\n $args = [\n 'post_type' =&gt; 'posts',\n 'posts_per_page' =&gt; 10,\n 'post__in' =&gt; $ids,\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'post__in',\n ];\n</code></pre>\n\n<p>All you really need to do is grab all your post ids, tack on the two in question, and use that instead of the acf get_field used in my example.</p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 344974, "author": "Doug Cassidy", "author_id": 17881, "author_profile": "https://wordpress.stackexchange.com/users/17881", "pm_score": 1, "selected": false, "text": "<p>The solution is to do two queries and then a third query, to set up the wp_query:</p>\n\n<pre><code>$query1 = new WP_Query(array (\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; $postnumber,\n 'ignore_sticky_posts' =&gt; 1,\n 'cat' =&gt; $category\n) );\n\n$query2 = new WP_Query(array(\n 'post_type' =&gt; 'page',\n 'post__in' =&gt; array(1443,1480)));\n\n$allTheposts = array_merge($query2-&gt;posts,$query1-&gt;posts);\nforeach($allTheposts as $p){\n $ids[] = $p-&gt;ID;\n}\n\n//new query, using post__in parameter\n$recent_query = new WP_Query(array(\n 'post__in' =&gt; $ids, \n 'post_type' =&gt; array('page','post'), \n 'orderby' =&gt; 'post__in'\n));\n</code></pre>\n" } ]
2019/08/10
[ "https://wordpress.stackexchange.com/questions/344844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173309/" ]
I am planing to show a new price on my woo-commerce product page for all products. This is the installment price per month. I need to show this below the normal price (variable price and simple price) something like this. 0% interest installments starting from Rs.3,093 where Rs.3,093 is the new price. this is the calculation i tried on W3 schools, and i got the calculation correct. whereas 60000 is the price of the product multiplied by this number 5.15464 divided by 100 answer is 3,093 (answer should be rounded off to the nearest integer) I need a custom function for this where i can add to my functions.php ``` <script>var x = myFunction(60000, 5.15464, 100); function myFunction(a, b, c) { return Math.round (a * b / c);}</script> ```
The solution is to do two queries and then a third query, to set up the wp\_query: ``` $query1 = new WP_Query(array ( 'post_status' => 'publish', 'posts_per_page' => $postnumber, 'ignore_sticky_posts' => 1, 'cat' => $category ) ); $query2 = new WP_Query(array( 'post_type' => 'page', 'post__in' => array(1443,1480))); $allTheposts = array_merge($query2->posts,$query1->posts); foreach($allTheposts as $p){ $ids[] = $p->ID; } //new query, using post__in parameter $recent_query = new WP_Query(array( 'post__in' => $ids, 'post_type' => array('page','post'), 'orderby' => 'post__in' )); ```
344,886
<p>In every post of my custom post type called <code>"announcements"</code> I save the users' ID inside an array which resides in a meta_key called <code>"post_is_read"</code> whenever a user reads an announcement.</p> <p>Just to explain: "post_is_read" contains an array (1, 2, 5, 12, 86, 100) where every number represents a user ID.</p> <p>I achieved this using this code: <a href="https://wordpress.stackexchange.com/a/344315/15801">https://wordpress.stackexchange.com/a/344315/15801</a></p> <p>I am now trying to create a template which will show the posts a user has not read with the following code:</p> <pre><code>$current_user = wp_get_current_user(); $up_an_query_args = array( 'post_type' =&gt; 'announcement', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'date', 'order' =&gt; 'DSC', 'meta_query' =&gt; array( array( 'key' =&gt; 'post_is_read', 'value' =&gt; $current_user-&gt;ID, 'compare' =&gt; 'NOT IN', ) ), ); </code></pre> <p>I have read every related article/answer I've found both on and off wordpress stackexchange and no method worked for me. The most I could get it to work is using <code>'compare' =&gt; 'NOT LIKE'</code> but it messed up the posts being displayed for users having at least a common digit in their IDs (ex between 1, 10, 11... etc) which is something I understand why is happening. </p>
[ { "answer_id": 344929, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": true, "text": "<h2>Revised Answer</h2>\n<p><sup>( PS: I actually wanted to revise this answer long ago, but eventually I kept forgetting to do so. :) )</sup></p>\n<p>So in this revised answer, the main point is the first one below, but I hope the rest also help you:</p>\n<ol>\n<li><p>What you're trying to do is not going to be (easily) possible with the way the IDs are stored, which is serialized such as <code>a:3:{i:0;i:1;i:1;i:10;i:2;i:11;}</code> (for <code>array( 1, 10, 11 )</code>).</p>\n<p>What if the current user ID is 10 and in the meta value, there's an <code>i:10;i:9</code>, i.e. array item keyed 10 with the value (a user ID) of 9 (i.e. <code>$some_variable[10] = 9</code>), but the ID 10 is not actually in the list?</p>\n</li>\n<li><p>So because of the above, you might better off create a custom database table and store the user ID and post ID in their own column.</p>\n<p>And if you want, you can check a simplified <a href=\"https://www.db-fiddle.com/f/wYErkyWw8WpArgNxwbU3o/2\" rel=\"nofollow noreferrer\">example/demo on DB Fiddle</a>.</p>\n</li>\n<li><p>Or you could instead store each user ID in individual post meta named <code>post_is_read</code>. That way, filtering the posts would be easy — but the post meta table would end up being really huge with many, many rows...</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Saving the meta:\nadd_post_meta( 1, 'post_is_read', 10 );\nadd_post_meta( 1, 'post_is_read', 11 );\n\n// Then when filtering the posts:\n$user_id = 10;\n$args = array(\n 'meta_key' =&gt; 'post_is_read',\n 'meta_value' =&gt; $user_id,\n 'meta_compare' =&gt; '!=',\n);\n$query = new WP_Query( $args );\n</code></pre>\n</li>\n<li><p>Or you may use a serialized value, but store the user <em>name/login</em> and not the ID:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Store usernames and not IDs.\n$usernames = array( 'foo', 'user-bar', 'etc_etc' );\n\nupdate_post_meta( 123, 'post_is_read', $usernames );\n</code></pre>\n<p>And then you can use the <code>NOT LIKE</code> comparison like so:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$username = 'user-bar';\n$args = array(\n 'meta_key' =&gt; 'post_is_read',\n 'meta_value' =&gt; '&quot;' . $username . '&quot;', // search for exactly &quot;&lt;username&gt;&quot; (including the quotes)\n 'meta_compare' =&gt; 'NOT LIKE',\n);\n$query = new WP_Query( $args );\n</code></pre>\n</li>\n</ol>\n<h2>Original Answer</h2>\n<p>Please check the <a href=\"https://wordpress.stackexchange.com/posts/344929/revisions\">revisions</a>, but basically in my original answer, I was saying if you'd rather use the user IDs, then you could store them as a comma-separated list like <code>1,10,11</code> and then use the <code>NOT REGEXP</code> comparison:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Saving the meta:\nupdate_post_meta( 1, 'post_is_read', '1,10,11' );\n\n// Then when filtering the posts:\n$user_id = 10;\n$args = array(\n 'meta_key' =&gt; 'post_is_read',\n 'meta_value' =&gt; &quot;(^|,)$user_id(,|$)&quot;,\n 'meta_compare' =&gt; 'NOT REGEXP',\n);\n$query = new WP_Query( $args );\n</code></pre>\n<p>And that did (and still does) work (with WordPress 5.6.1), except that it needs an extra parsing when retrieving the meta value, e.g.:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$ids = get_post_meta( 1, 'post_is_read', true );\n$ids = wp_parse_id_list( $ids ); // convert to array\n</code></pre>\n" }, { "answer_id": 391342, "author": "Nick C", "author_id": 132158, "author_profile": "https://wordpress.stackexchange.com/users/132158", "pm_score": 2, "selected": false, "text": "<p>I store my IDs as strings so this is what I do</p>\n<pre><code>$up_an_query_args = array(\n'post_type' =&gt; 'announcement',\n'post_status' =&gt; 'publish',\n'posts_per_page' =&gt; -1,\n'orderby' =&gt; 'date', \n'order' =&gt; 'DSC',\n'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'post_is_read', \n 'value' =&gt; serialize(strval($current_user-&gt;ID)),\n 'compare' =&gt; 'LIKE', \n )\n),);\n</code></pre>\n<p>The same should work even if you store it as int:</p>\n<pre><code>'value' =&gt; serialize($current_user-&gt;ID)\n</code></pre>\n" } ]
2019/08/11
[ "https://wordpress.stackexchange.com/questions/344886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15801/" ]
In every post of my custom post type called `"announcements"` I save the users' ID inside an array which resides in a meta\_key called `"post_is_read"` whenever a user reads an announcement. Just to explain: "post\_is\_read" contains an array (1, 2, 5, 12, 86, 100) where every number represents a user ID. I achieved this using this code: <https://wordpress.stackexchange.com/a/344315/15801> I am now trying to create a template which will show the posts a user has not read with the following code: ``` $current_user = wp_get_current_user(); $up_an_query_args = array( 'post_type' => 'announcement', 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'DSC', 'meta_query' => array( array( 'key' => 'post_is_read', 'value' => $current_user->ID, 'compare' => 'NOT IN', ) ), ); ``` I have read every related article/answer I've found both on and off wordpress stackexchange and no method worked for me. The most I could get it to work is using `'compare' => 'NOT LIKE'` but it messed up the posts being displayed for users having at least a common digit in their IDs (ex between 1, 10, 11... etc) which is something I understand why is happening.
Revised Answer -------------- ( PS: I actually wanted to revise this answer long ago, but eventually I kept forgetting to do so. :) ) So in this revised answer, the main point is the first one below, but I hope the rest also help you: 1. What you're trying to do is not going to be (easily) possible with the way the IDs are stored, which is serialized such as `a:3:{i:0;i:1;i:1;i:10;i:2;i:11;}` (for `array( 1, 10, 11 )`). What if the current user ID is 10 and in the meta value, there's an `i:10;i:9`, i.e. array item keyed 10 with the value (a user ID) of 9 (i.e. `$some_variable[10] = 9`), but the ID 10 is not actually in the list? 2. So because of the above, you might better off create a custom database table and store the user ID and post ID in their own column. And if you want, you can check a simplified [example/demo on DB Fiddle](https://www.db-fiddle.com/f/wYErkyWw8WpArgNxwbU3o/2). 3. Or you could instead store each user ID in individual post meta named `post_is_read`. That way, filtering the posts would be easy — but the post meta table would end up being really huge with many, many rows... ```php // Saving the meta: add_post_meta( 1, 'post_is_read', 10 ); add_post_meta( 1, 'post_is_read', 11 ); // Then when filtering the posts: $user_id = 10; $args = array( 'meta_key' => 'post_is_read', 'meta_value' => $user_id, 'meta_compare' => '!=', ); $query = new WP_Query( $args ); ``` 4. Or you may use a serialized value, but store the user *name/login* and not the ID: ```php // Store usernames and not IDs. $usernames = array( 'foo', 'user-bar', 'etc_etc' ); update_post_meta( 123, 'post_is_read', $usernames ); ``` And then you can use the `NOT LIKE` comparison like so: ```php $username = 'user-bar'; $args = array( 'meta_key' => 'post_is_read', 'meta_value' => '"' . $username . '"', // search for exactly "<username>" (including the quotes) 'meta_compare' => 'NOT LIKE', ); $query = new WP_Query( $args ); ``` Original Answer --------------- Please check the [revisions](https://wordpress.stackexchange.com/posts/344929/revisions), but basically in my original answer, I was saying if you'd rather use the user IDs, then you could store them as a comma-separated list like `1,10,11` and then use the `NOT REGEXP` comparison: ```php // Saving the meta: update_post_meta( 1, 'post_is_read', '1,10,11' ); // Then when filtering the posts: $user_id = 10; $args = array( 'meta_key' => 'post_is_read', 'meta_value' => "(^|,)$user_id(,|$)", 'meta_compare' => 'NOT REGEXP', ); $query = new WP_Query( $args ); ``` And that did (and still does) work (with WordPress 5.6.1), except that it needs an extra parsing when retrieving the meta value, e.g.: ```php $ids = get_post_meta( 1, 'post_is_read', true ); $ids = wp_parse_id_list( $ids ); // convert to array ```
344,938
<p>I have a weird issue. I deleted a page and permanently deleted in from the trash but I can still get to it. On the deleted page it shows the posts page ("Blog" page). I have cleared the permalinks, cleared my browser cache and I have looked at it in incognito mode but I can still see the page. Other than turning plugins on and off any other ideas would be appreciated. I am also using a custom theme.</p>
[ { "answer_id": 344929, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": true, "text": "<h2>Revised Answer</h2>\n<p><sup>( PS: I actually wanted to revise this answer long ago, but eventually I kept forgetting to do so. :) )</sup></p>\n<p>So in this revised answer, the main point is the first one below, but I hope the rest also help you:</p>\n<ol>\n<li><p>What you're trying to do is not going to be (easily) possible with the way the IDs are stored, which is serialized such as <code>a:3:{i:0;i:1;i:1;i:10;i:2;i:11;}</code> (for <code>array( 1, 10, 11 )</code>).</p>\n<p>What if the current user ID is 10 and in the meta value, there's an <code>i:10;i:9</code>, i.e. array item keyed 10 with the value (a user ID) of 9 (i.e. <code>$some_variable[10] = 9</code>), but the ID 10 is not actually in the list?</p>\n</li>\n<li><p>So because of the above, you might better off create a custom database table and store the user ID and post ID in their own column.</p>\n<p>And if you want, you can check a simplified <a href=\"https://www.db-fiddle.com/f/wYErkyWw8WpArgNxwbU3o/2\" rel=\"nofollow noreferrer\">example/demo on DB Fiddle</a>.</p>\n</li>\n<li><p>Or you could instead store each user ID in individual post meta named <code>post_is_read</code>. That way, filtering the posts would be easy — but the post meta table would end up being really huge with many, many rows...</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Saving the meta:\nadd_post_meta( 1, 'post_is_read', 10 );\nadd_post_meta( 1, 'post_is_read', 11 );\n\n// Then when filtering the posts:\n$user_id = 10;\n$args = array(\n 'meta_key' =&gt; 'post_is_read',\n 'meta_value' =&gt; $user_id,\n 'meta_compare' =&gt; '!=',\n);\n$query = new WP_Query( $args );\n</code></pre>\n</li>\n<li><p>Or you may use a serialized value, but store the user <em>name/login</em> and not the ID:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Store usernames and not IDs.\n$usernames = array( 'foo', 'user-bar', 'etc_etc' );\n\nupdate_post_meta( 123, 'post_is_read', $usernames );\n</code></pre>\n<p>And then you can use the <code>NOT LIKE</code> comparison like so:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$username = 'user-bar';\n$args = array(\n 'meta_key' =&gt; 'post_is_read',\n 'meta_value' =&gt; '&quot;' . $username . '&quot;', // search for exactly &quot;&lt;username&gt;&quot; (including the quotes)\n 'meta_compare' =&gt; 'NOT LIKE',\n);\n$query = new WP_Query( $args );\n</code></pre>\n</li>\n</ol>\n<h2>Original Answer</h2>\n<p>Please check the <a href=\"https://wordpress.stackexchange.com/posts/344929/revisions\">revisions</a>, but basically in my original answer, I was saying if you'd rather use the user IDs, then you could store them as a comma-separated list like <code>1,10,11</code> and then use the <code>NOT REGEXP</code> comparison:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Saving the meta:\nupdate_post_meta( 1, 'post_is_read', '1,10,11' );\n\n// Then when filtering the posts:\n$user_id = 10;\n$args = array(\n 'meta_key' =&gt; 'post_is_read',\n 'meta_value' =&gt; &quot;(^|,)$user_id(,|$)&quot;,\n 'meta_compare' =&gt; 'NOT REGEXP',\n);\n$query = new WP_Query( $args );\n</code></pre>\n<p>And that did (and still does) work (with WordPress 5.6.1), except that it needs an extra parsing when retrieving the meta value, e.g.:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$ids = get_post_meta( 1, 'post_is_read', true );\n$ids = wp_parse_id_list( $ids ); // convert to array\n</code></pre>\n" }, { "answer_id": 391342, "author": "Nick C", "author_id": 132158, "author_profile": "https://wordpress.stackexchange.com/users/132158", "pm_score": 2, "selected": false, "text": "<p>I store my IDs as strings so this is what I do</p>\n<pre><code>$up_an_query_args = array(\n'post_type' =&gt; 'announcement',\n'post_status' =&gt; 'publish',\n'posts_per_page' =&gt; -1,\n'orderby' =&gt; 'date', \n'order' =&gt; 'DSC',\n'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'post_is_read', \n 'value' =&gt; serialize(strval($current_user-&gt;ID)),\n 'compare' =&gt; 'LIKE', \n )\n),);\n</code></pre>\n<p>The same should work even if you store it as int:</p>\n<pre><code>'value' =&gt; serialize($current_user-&gt;ID)\n</code></pre>\n" } ]
2019/08/12
[ "https://wordpress.stackexchange.com/questions/344938", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173374/" ]
I have a weird issue. I deleted a page and permanently deleted in from the trash but I can still get to it. On the deleted page it shows the posts page ("Blog" page). I have cleared the permalinks, cleared my browser cache and I have looked at it in incognito mode but I can still see the page. Other than turning plugins on and off any other ideas would be appreciated. I am also using a custom theme.
Revised Answer -------------- ( PS: I actually wanted to revise this answer long ago, but eventually I kept forgetting to do so. :) ) So in this revised answer, the main point is the first one below, but I hope the rest also help you: 1. What you're trying to do is not going to be (easily) possible with the way the IDs are stored, which is serialized such as `a:3:{i:0;i:1;i:1;i:10;i:2;i:11;}` (for `array( 1, 10, 11 )`). What if the current user ID is 10 and in the meta value, there's an `i:10;i:9`, i.e. array item keyed 10 with the value (a user ID) of 9 (i.e. `$some_variable[10] = 9`), but the ID 10 is not actually in the list? 2. So because of the above, you might better off create a custom database table and store the user ID and post ID in their own column. And if you want, you can check a simplified [example/demo on DB Fiddle](https://www.db-fiddle.com/f/wYErkyWw8WpArgNxwbU3o/2). 3. Or you could instead store each user ID in individual post meta named `post_is_read`. That way, filtering the posts would be easy — but the post meta table would end up being really huge with many, many rows... ```php // Saving the meta: add_post_meta( 1, 'post_is_read', 10 ); add_post_meta( 1, 'post_is_read', 11 ); // Then when filtering the posts: $user_id = 10; $args = array( 'meta_key' => 'post_is_read', 'meta_value' => $user_id, 'meta_compare' => '!=', ); $query = new WP_Query( $args ); ``` 4. Or you may use a serialized value, but store the user *name/login* and not the ID: ```php // Store usernames and not IDs. $usernames = array( 'foo', 'user-bar', 'etc_etc' ); update_post_meta( 123, 'post_is_read', $usernames ); ``` And then you can use the `NOT LIKE` comparison like so: ```php $username = 'user-bar'; $args = array( 'meta_key' => 'post_is_read', 'meta_value' => '"' . $username . '"', // search for exactly "<username>" (including the quotes) 'meta_compare' => 'NOT LIKE', ); $query = new WP_Query( $args ); ``` Original Answer --------------- Please check the [revisions](https://wordpress.stackexchange.com/posts/344929/revisions), but basically in my original answer, I was saying if you'd rather use the user IDs, then you could store them as a comma-separated list like `1,10,11` and then use the `NOT REGEXP` comparison: ```php // Saving the meta: update_post_meta( 1, 'post_is_read', '1,10,11' ); // Then when filtering the posts: $user_id = 10; $args = array( 'meta_key' => 'post_is_read', 'meta_value' => "(^|,)$user_id(,|$)", 'meta_compare' => 'NOT REGEXP', ); $query = new WP_Query( $args ); ``` And that did (and still does) work (with WordPress 5.6.1), except that it needs an extra parsing when retrieving the meta value, e.g.: ```php $ids = get_post_meta( 1, 'post_is_read', true ); $ids = wp_parse_id_list( $ids ); // convert to array ```
344,939
<p>When I try to create a new post with accents width wp-cli (in windows 10 command, I got latest wp-cli)</p> <pre><code>wp post create --post_title="Héllo" --post_type=page --post_content="Héllo world" </code></pre> <p>I got error:</p> <blockquote> <p>"Impossible to insert this post in database"</p> </blockquote> <p>It works fine when I replace the "é" by "e"</p> <pre><code>wp post create --post_title="Hello" --post_type=page --post_content="Hello world" </code></pre> <p>Any idea ?</p>
[ { "answer_id": 344947, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 2, "selected": true, "text": "<p>See <a href=\"https://make.wordpress.org/cli/handbook/common-issues/#cannot-create-a-post-with-latin-characters-in-the-title-on-windows\" rel=\"nofollow noreferrer\">Cannot create a post with Latin characters in the title on Windows</a>.</p>\n\n<blockquote>\n <p>Using UTF-8 in PHP arguments doesn’t work on Windows for PHP &lt;= 7.0,\n however it will work for PHP >= 7.1, as it was fixed as part of\n <a href=\"http://php.net/manual/en/migration71.windows-support.php\" rel=\"nofollow noreferrer\">Support for long and UTF-8 path</a>. A workaround for PHP &lt;= 7.0 is\n to use the <code>--prompt</code> option:</p>\n\n<pre><code>echo \"Perícias Contábeis\" | wp post create --post_type=page --post_status=publish --prompt=post_title\n</code></pre>\n</blockquote>\n\n<p>It looks a bit as if this bug only affects the title. Have you tried that? And the post content doesn't matter? Then the following should work:</p>\n\n<pre><code>echo \"Héllo\" | wp post create --post_type=page --post_content=\"Héllo world\" --prompt=post_title\n</code></pre>\n" }, { "answer_id": 413884, "author": "Christopher", "author_id": 230031, "author_profile": "https://wordpress.stackexchange.com/users/230031", "pm_score": 0, "selected": false, "text": "<p>On Linux/Bash Terminal, you can convert the post title from Latin1 to UTF8 so it can be passed to PHP (it seems to be a PHP problem, not WP-Cli issue)</p>\n<pre><code>myposttitle=$(echo &quot;My làtin commànd&quot; | iconv -f latin1 -t utf-8)\n\nwp-cli post create --post_title=&quot;$myposttitle&quot;\n</code></pre>\n<p>iconv is a Bash command that can convert the encoding of an incoming text and output it to another encoding.</p>\n" } ]
2019/08/12
[ "https://wordpress.stackexchange.com/questions/344939", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135166/" ]
When I try to create a new post with accents width wp-cli (in windows 10 command, I got latest wp-cli) ``` wp post create --post_title="Héllo" --post_type=page --post_content="Héllo world" ``` I got error: > > "Impossible to insert this post in database" > > > It works fine when I replace the "é" by "e" ``` wp post create --post_title="Hello" --post_type=page --post_content="Hello world" ``` Any idea ?
See [Cannot create a post with Latin characters in the title on Windows](https://make.wordpress.org/cli/handbook/common-issues/#cannot-create-a-post-with-latin-characters-in-the-title-on-windows). > > Using UTF-8 in PHP arguments doesn’t work on Windows for PHP <= 7.0, > however it will work for PHP >= 7.1, as it was fixed as part of > [Support for long and UTF-8 path](http://php.net/manual/en/migration71.windows-support.php). A workaround for PHP <= 7.0 is > to use the `--prompt` option: > > > > ``` > echo "Perícias Contábeis" | wp post create --post_type=page --post_status=publish --prompt=post_title > > ``` > > It looks a bit as if this bug only affects the title. Have you tried that? And the post content doesn't matter? Then the following should work: ``` echo "Héllo" | wp post create --post_type=page --post_content="Héllo world" --prompt=post_title ```
344,990
<p>I'm trying include dynamic sidebar to Uncode Theme. I created child template, then I created all files and now I have a piece of code who shows content and sidebar area.</p> <p>In <code>functions.php</code> I created dynamic sidebar:</p> <pre><code>add_action( 'widgets_init', function () { $args = array( 'name' =&gt; __( 'Sidebar Messages Single', 'uncode' ), 'id' =&gt; 'sidebar-messages-single', 'description' =&gt; '', 'class' =&gt; 'dynamic-widget', 'before_widget' =&gt; '&lt;li id="dynamic-sidebar" class="widget"&gt;', 'after_widget' =&gt; '&lt;/li&gt;', 'before_title' =&gt; '&lt;h2 class="widgettitle"&gt;', 'after_title' =&gt; '&lt;/h2&gt;' ); register_sidebar( $args ); }); </code></pre> <p>Then in <code>single-portfolio.php</code> I'm trying include that sidebar.</p> <pre><code> $sidebar_widgets = is_active_sidebar( 'sidebar-messages-single' ) ? dynamic_sidebar( 'sidebar-messages-single' ) : null; $the_content = '&lt;div class="row-container"&gt; &lt;div class="row row-parent' . $row_classes . $limit_content_width . '"&gt; &lt;div class="row-inner"&gt; ' . (($layout === 'sidebar_right') ? $main_content : '') . ' &lt;div class="col-lg-' . $sidebar_size . '"&gt; &lt;div class="uncol style-' . $portfolio_style . $expand_col . $sidebar_padding . (($sidebar_fill === 'on' &amp;&amp; $portfolio_bg_color !== '') ? '' : $sidebar_sticky) . '"&gt; &lt;div class="uncoltable' . (($sidebar_fill === 'on' &amp;&amp; $portfolio_bg_color !== '') ? $sidebar_sticky : '') . '"&gt; &lt;div class="uncell' . $sidebar_inner_padding . '"&gt; &lt;div class="uncont"&gt; &lt;div&gt; ' . $sidebar_widgets . ' &lt;/div&gt; ' . $footer_content . ' &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ' . (($layout === 'sidebar_left') ? $main_content : '') . ' &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;'; </code></pre> <p>It seems to me everything is alright, but when I render page I get this result.</p> <p><a href="https://i.stack.imgur.com/vIikp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vIikp.png" alt="enter image description here"></a> The place where sidebar should be render I get int (one). Whereas sidebar is rendered in another place. </p> <p>At first I thought it is DOM manipulated via JavaScript, but when I debugged and disabled JS it worked the same. </p> <p>Furthermore, when I added normal string to <code>&lt;div&gt;</code> beside variable <code>$sidebar_widget</code>. String rendered in correct place.</p> <p>Thanks a lot for help!</p>
[ { "answer_id": 344947, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 2, "selected": true, "text": "<p>See <a href=\"https://make.wordpress.org/cli/handbook/common-issues/#cannot-create-a-post-with-latin-characters-in-the-title-on-windows\" rel=\"nofollow noreferrer\">Cannot create a post with Latin characters in the title on Windows</a>.</p>\n\n<blockquote>\n <p>Using UTF-8 in PHP arguments doesn’t work on Windows for PHP &lt;= 7.0,\n however it will work for PHP >= 7.1, as it was fixed as part of\n <a href=\"http://php.net/manual/en/migration71.windows-support.php\" rel=\"nofollow noreferrer\">Support for long and UTF-8 path</a>. A workaround for PHP &lt;= 7.0 is\n to use the <code>--prompt</code> option:</p>\n\n<pre><code>echo \"Perícias Contábeis\" | wp post create --post_type=page --post_status=publish --prompt=post_title\n</code></pre>\n</blockquote>\n\n<p>It looks a bit as if this bug only affects the title. Have you tried that? And the post content doesn't matter? Then the following should work:</p>\n\n<pre><code>echo \"Héllo\" | wp post create --post_type=page --post_content=\"Héllo world\" --prompt=post_title\n</code></pre>\n" }, { "answer_id": 413884, "author": "Christopher", "author_id": 230031, "author_profile": "https://wordpress.stackexchange.com/users/230031", "pm_score": 0, "selected": false, "text": "<p>On Linux/Bash Terminal, you can convert the post title from Latin1 to UTF8 so it can be passed to PHP (it seems to be a PHP problem, not WP-Cli issue)</p>\n<pre><code>myposttitle=$(echo &quot;My làtin commànd&quot; | iconv -f latin1 -t utf-8)\n\nwp-cli post create --post_title=&quot;$myposttitle&quot;\n</code></pre>\n<p>iconv is a Bash command that can convert the encoding of an incoming text and output it to another encoding.</p>\n" } ]
2019/08/13
[ "https://wordpress.stackexchange.com/questions/344990", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171603/" ]
I'm trying include dynamic sidebar to Uncode Theme. I created child template, then I created all files and now I have a piece of code who shows content and sidebar area. In `functions.php` I created dynamic sidebar: ``` add_action( 'widgets_init', function () { $args = array( 'name' => __( 'Sidebar Messages Single', 'uncode' ), 'id' => 'sidebar-messages-single', 'description' => '', 'class' => 'dynamic-widget', 'before_widget' => '<li id="dynamic-sidebar" class="widget">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>' ); register_sidebar( $args ); }); ``` Then in `single-portfolio.php` I'm trying include that sidebar. ``` $sidebar_widgets = is_active_sidebar( 'sidebar-messages-single' ) ? dynamic_sidebar( 'sidebar-messages-single' ) : null; $the_content = '<div class="row-container"> <div class="row row-parent' . $row_classes . $limit_content_width . '"> <div class="row-inner"> ' . (($layout === 'sidebar_right') ? $main_content : '') . ' <div class="col-lg-' . $sidebar_size . '"> <div class="uncol style-' . $portfolio_style . $expand_col . $sidebar_padding . (($sidebar_fill === 'on' && $portfolio_bg_color !== '') ? '' : $sidebar_sticky) . '"> <div class="uncoltable' . (($sidebar_fill === 'on' && $portfolio_bg_color !== '') ? $sidebar_sticky : '') . '"> <div class="uncell' . $sidebar_inner_padding . '"> <div class="uncont"> <div> ' . $sidebar_widgets . ' </div> ' . $footer_content . ' </div> </div> </div> </div> </div> ' . (($layout === 'sidebar_left') ? $main_content : '') . ' </div> </div> </div>'; ``` It seems to me everything is alright, but when I render page I get this result. [![enter image description here](https://i.stack.imgur.com/vIikp.png)](https://i.stack.imgur.com/vIikp.png) The place where sidebar should be render I get int (one). Whereas sidebar is rendered in another place. At first I thought it is DOM manipulated via JavaScript, but when I debugged and disabled JS it worked the same. Furthermore, when I added normal string to `<div>` beside variable `$sidebar_widget`. String rendered in correct place. Thanks a lot for help!
See [Cannot create a post with Latin characters in the title on Windows](https://make.wordpress.org/cli/handbook/common-issues/#cannot-create-a-post-with-latin-characters-in-the-title-on-windows). > > Using UTF-8 in PHP arguments doesn’t work on Windows for PHP <= 7.0, > however it will work for PHP >= 7.1, as it was fixed as part of > [Support for long and UTF-8 path](http://php.net/manual/en/migration71.windows-support.php). A workaround for PHP <= 7.0 is > to use the `--prompt` option: > > > > ``` > echo "Perícias Contábeis" | wp post create --post_type=page --post_status=publish --prompt=post_title > > ``` > > It looks a bit as if this bug only affects the title. Have you tried that? And the post content doesn't matter? Then the following should work: ``` echo "Héllo" | wp post create --post_type=page --post_content="Héllo world" --prompt=post_title ```
345,021
<p>I installed a new wordpress project using docker's guide:</p> <pre><code>mkdir my-wordpress-site cd my-wordpress-site ddev config --project-type=php ddev composer create wordpress/skeleton --no-interaction --prefer-dist ddev config --docroot=wp --project-type=wordpress ddev restart </code></pre> <p>All done and I ran the front-end configuration.</p> <p>I am used to running things in windows(xampp) and heard of MAMP for mac. but now I need to use docker and have no clue of how to go about things.</p> <p>Question is: Is there a way I can access my database using Docker? ssh or anything?</p>
[ { "answer_id": 345033, "author": "Andy Mardell", "author_id": 72819, "author_profile": "https://wordpress.stackexchange.com/users/72819", "pm_score": 2, "selected": false, "text": "<h2>PhpMyAdmin</h2>\n\n<p>phpMyAdmin is installed with the commands you ran.</p>\n\n<p>It seems to generate a random port. So do the following:</p>\n\n<p><code>docker ps</code></p>\n\n<p>You should see a line which is called <code>drud/phpmyadmin</code>. Look along the table and you should see the port it's running on. In my case, this was <code>0.0.0.0:32773-&gt;80/tcp</code></p>\n\n<p>So if I go to <a href=\"http://localhost:32773\" rel=\"nofollow noreferrer\">http://localhost:32773</a> I see phpmyadmin, where you can access and edit your database.</p>\n\n<p>PhpMyAdmin is fine to start, but you might want to use a database client to remotely access the database long term:</p>\n\n<h2>Remote access</h2>\n\n<p>If you want to use a database client to connect to your database, there is a similar process. Find out what port your database image is exposing:</p>\n\n<p><code>ps docker</code></p>\n\n<p>See the line called <code>drud/ddev-dbserver</code>? What port is this using? In my case it was <code>127.0.0.1:32782-&gt;3306/tcp</code>.</p>\n\n<p>So to connect to this database I can use port 32782. Again, in my case the details to connect were:</p>\n\n<p>Host: 127.0.0.1\nDatabase: db\nUser: db\nPassword: db\nPort: 32782</p>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 345048, "author": "rfay", "author_id": 173449, "author_profile": "https://wordpress.stackexchange.com/users/173449", "pm_score": 3, "selected": false, "text": "<p>There are ever-so-many ways to access the database. <code>ddev describe</code> will open your eyes to them.</p>\n\n<ul>\n<li>As @Andy Mardell points out, you can use the built-in PHPMyAdmin (link in <code>ddev describe</code>)</li>\n<li>You can also use a mysql client on the host, the port and such for this are also shown in <code>ddev describe</code></li>\n<li>You can also use <code>ddev mysql</code> for direct access to the database (ddev v1.10+)</li>\n<li>On macOS, you can use <code>ddev sequelpro</code> if you have the excellent, free SequelPro installed.</li>\n<li>You can also ssh into either the web container or the db container, <code>ddev ssh</code> or <code>ddev ssh -s db</code> and use the mysql client there.</li>\n<li>You can also use <code>ddev exec mysql</code>, which is really pretty much the same as <code>ddev mysql</code></li>\n</ul>\n\n<p>I hope that's enough ways! :)</p>\n" } ]
2019/08/13
[ "https://wordpress.stackexchange.com/questions/345021", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99178/" ]
I installed a new wordpress project using docker's guide: ``` mkdir my-wordpress-site cd my-wordpress-site ddev config --project-type=php ddev composer create wordpress/skeleton --no-interaction --prefer-dist ddev config --docroot=wp --project-type=wordpress ddev restart ``` All done and I ran the front-end configuration. I am used to running things in windows(xampp) and heard of MAMP for mac. but now I need to use docker and have no clue of how to go about things. Question is: Is there a way I can access my database using Docker? ssh or anything?
There are ever-so-many ways to access the database. `ddev describe` will open your eyes to them. * As @Andy Mardell points out, you can use the built-in PHPMyAdmin (link in `ddev describe`) * You can also use a mysql client on the host, the port and such for this are also shown in `ddev describe` * You can also use `ddev mysql` for direct access to the database (ddev v1.10+) * On macOS, you can use `ddev sequelpro` if you have the excellent, free SequelPro installed. * You can also ssh into either the web container or the db container, `ddev ssh` or `ddev ssh -s db` and use the mysql client there. * You can also use `ddev exec mysql`, which is really pretty much the same as `ddev mysql` I hope that's enough ways! :)
345,036
<p>A visitor visits a page</p> <p>for example: <a href="https://www.example.com/wp-login.php?action=rp&amp;key=abc&amp;login=jim" rel="nofollow noreferrer">https://www.example.com/wp-login.php?action=rp&amp;key=abc&amp;login=jim</a></p> <p>I want to have a block of text that displays only if the URL has ?action=rp</p> <p>and a block of text that displays if the url is naked.</p> <p>There are many content visibility plugins that can control visibility based on role etc.</p> <p>But I can't find one that can control visibility based on a URL parameter.</p> <p>Does one exist? If not, is there another way I can achieve that?</p>
[ { "answer_id": 345174, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/add_shortcode/\" rel=\"nofollow noreferrer\"><code>add_shortcode()</code></a> to register custom Shortcodes for restricting access to certain parts of the post content.</p>\n\n<p>And here's a working example, with specific to your case:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function my_rp_shortcode( $atts = [], $content = '', $tag = '' ) {\n if ( 'if-rp' === $tag ) {\n // Return $content if the URL query string has action=rp.\n return ( isset( $_GET['action'] ) &amp;&amp; 'rp' === $_GET['action'] ) ? $content : '';\n } else { // if-not-rp\n // Return $content if the URL query string doesn't have action=rp.\n return ( empty( $_GET['action'] ) || 'rp' !== $_GET['action'] ) ? $content : '';\n }\n}\nadd_shortcode( 'if-rp', 'my_rp_shortcode' );\nadd_shortcode( 'if-not-rp', 'my_rp_shortcode' );\n</code></pre>\n\n<p>You'd add the code to the theme functions file and use the Shortcodes like so:</p>\n\n<pre><code>[if-rp]\nThis content is shown only if the query string \"action\" is set to \"rp\".\nExample: example.com/login/?action=rp\n[/if-rp]\n\n[if-not-rp]\nThis content is shown only if the query string \"action\" is NOT set or the value is NOT \"rp\".\nExample: example.com/login/?action= (empty \"action\")\nExample 2: example.com/login/ (no \"action\")\n[/if-not-rp]\n</code></pre>\n\n<p>You can change the logic, use two independent Shortcode functions, replace the tags (<code>if-rp</code> and <code>if-not-rp</code>), etc. if you want to. :)</p>\n" }, { "answer_id": 401059, "author": "Richard Good", "author_id": 217663, "author_profile": "https://wordpress.stackexchange.com/users/217663", "pm_score": 0, "selected": false, "text": "<p>If you don't want to use shortcodes you can use enqueue to add custom CSS to the header, add classes to your content and then toggle display none in CSS.</p>\n<p>Add this to your functions.php or custom-functions.php file:</p>\n<pre><code>function wp_89494_enqueue_scripts() {\n if ( isset( $_GET['src'] ) &amp;&amp; 'pc' === $_GET['src'] ) {\n wp_enqueue_style( \n 'wpse_89494_style_1', \n get_stylesheet_directory_uri(). '/pcast.css' \n );\n }\n \n}\n\nadd_action( 'wp_enqueue_scripts', 'wpse_89494_enqueue_scripts' );\n</code></pre>\n<p>Then this to your url:</p>\n<pre><code>/?src=pc\n</code></pre>\n<p>And this to a file pcast.css placed in your child theme folder:</p>\n<pre><code>.stuff-to-hide {display:none !important;}\n</code></pre>\n<p>Inspired by this thread:</p>\n<p><a href=\"https://wordpress.stackexchange.com/questions/89494/how-to-enqueue-the-style-using-wp-enqueue-style\">How to enqueue the style using wp_enqueue_style()</a></p>\n" } ]
2019/08/13
[ "https://wordpress.stackexchange.com/questions/345036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114749/" ]
A visitor visits a page for example: <https://www.example.com/wp-login.php?action=rp&key=abc&login=jim> I want to have a block of text that displays only if the URL has ?action=rp and a block of text that displays if the url is naked. There are many content visibility plugins that can control visibility based on role etc. But I can't find one that can control visibility based on a URL parameter. Does one exist? If not, is there another way I can achieve that?
You can use [`add_shortcode()`](https://developer.wordpress.org/reference/functions/add_shortcode/) to register custom Shortcodes for restricting access to certain parts of the post content. And here's a working example, with specific to your case: ```php function my_rp_shortcode( $atts = [], $content = '', $tag = '' ) { if ( 'if-rp' === $tag ) { // Return $content if the URL query string has action=rp. return ( isset( $_GET['action'] ) && 'rp' === $_GET['action'] ) ? $content : ''; } else { // if-not-rp // Return $content if the URL query string doesn't have action=rp. return ( empty( $_GET['action'] ) || 'rp' !== $_GET['action'] ) ? $content : ''; } } add_shortcode( 'if-rp', 'my_rp_shortcode' ); add_shortcode( 'if-not-rp', 'my_rp_shortcode' ); ``` You'd add the code to the theme functions file and use the Shortcodes like so: ``` [if-rp] This content is shown only if the query string "action" is set to "rp". Example: example.com/login/?action=rp [/if-rp] [if-not-rp] This content is shown only if the query string "action" is NOT set or the value is NOT "rp". Example: example.com/login/?action= (empty "action") Example 2: example.com/login/ (no "action") [/if-not-rp] ``` You can change the logic, use two independent Shortcode functions, replace the tags (`if-rp` and `if-not-rp`), etc. if you want to. :)
345,054
<p>I try to get the value of the source field 'enddate', save it in the variable $enddatevar and write it in the target field 'promote' in the loop by activating the plugin, but the code I added to <a href="https://wordpress.stackexchange.com/questions/270472/assign-update-the-custom-field-value-for-all-posts">this working code</a> doesn't work. Any help would be appreciated.</p> <pre><code>&lt;?php /* Plugin Name: Update MetaData for Posts Description: Enable this plugin to update the metadata for all the posts Author: JackJohansson Version: 1.0 Author URI: http://example.com */ // Run the loop when the plugin is activated register_activation_hook(__FILE__, 'update_my_metadata'); function update_my_metadata(){ $args = array( 'post_type' =&gt; 'touren', // Only get the posts 'post_status' =&gt; 'publish', // Only the posts that are published 'posts_per_page' =&gt; -1 // Get every post ); $posts = get_posts($args); foreach ( $posts as $post ) { // Run a loop and update every meta data //code added to original code $enddatevar = get_post_meta( $post_id, $key = 'enddate', $single = false); //end of code added //'meta_value' used in original code replaced with '$enddatevar' below update_post_meta( $post-&gt;ID, 'promote', '$enddatevar' ); } } ?&gt; </code></pre>
[ { "answer_id": 345068, "author": "Jess_Pinkman", "author_id": 171161, "author_profile": "https://wordpress.stackexchange.com/users/171161", "pm_score": 1, "selected": false, "text": "<pre><code>$enddatevar = get_post_meta( $post_id, $key = 'enddate', $single = false);\n</code></pre>\n\n<p>$post_id is not defined, either declare it beforehand, or use $post->ID.</p>\n\n<pre><code>update_post_meta( $post-&gt;ID, 'promote', '$enddatevar' );\n</code></pre>\n\n<p>'$enddatevar' shouldnt be inside quotes.</p>\n" }, { "answer_id": 345085, "author": "Lukas", "author_id": 173437, "author_profile": "https://wordpress.stackexchange.com/users/173437", "pm_score": 0, "selected": false, "text": "<p>Thanks! I was close to the solution, tried both, but not in combination.\nThus</p>\n\n<pre><code>$enddatevar = get_post_meta( $post-&gt;ID, $key = 'enddate', $single = false);\nupdate_post_meta( $post-&gt;ID, 'promote', $enddatevar );\n</code></pre>\n\n<p>worked.</p>\n" } ]
2019/08/13
[ "https://wordpress.stackexchange.com/questions/345054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173437/" ]
I try to get the value of the source field 'enddate', save it in the variable $enddatevar and write it in the target field 'promote' in the loop by activating the plugin, but the code I added to [this working code](https://wordpress.stackexchange.com/questions/270472/assign-update-the-custom-field-value-for-all-posts) doesn't work. Any help would be appreciated. ``` <?php /* Plugin Name: Update MetaData for Posts Description: Enable this plugin to update the metadata for all the posts Author: JackJohansson Version: 1.0 Author URI: http://example.com */ // Run the loop when the plugin is activated register_activation_hook(__FILE__, 'update_my_metadata'); function update_my_metadata(){ $args = array( 'post_type' => 'touren', // Only get the posts 'post_status' => 'publish', // Only the posts that are published 'posts_per_page' => -1 // Get every post ); $posts = get_posts($args); foreach ( $posts as $post ) { // Run a loop and update every meta data //code added to original code $enddatevar = get_post_meta( $post_id, $key = 'enddate', $single = false); //end of code added //'meta_value' used in original code replaced with '$enddatevar' below update_post_meta( $post->ID, 'promote', '$enddatevar' ); } } ?> ```
``` $enddatevar = get_post_meta( $post_id, $key = 'enddate', $single = false); ``` $post\_id is not defined, either declare it beforehand, or use $post->ID. ``` update_post_meta( $post->ID, 'promote', '$enddatevar' ); ``` '$enddatevar' shouldnt be inside quotes.
345,091
<p>I need to provide some custom menu items in a plugin. I mean people can go to dashboard > appearance > menus and add this custom menu item to any menu location.</p> <p>So I want to know how to add the meta box in that page, how to fill it with options and how to output the content in the front end.</p> <p>I tried searching for long but I'm not finding any good resource on how to manage such a thing. </p> <p>Any help? Any links? Thank you.</p>
[ { "answer_id": 345115, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 1, "selected": false, "text": "<p>This is the slimmed down version of a plugin settings page that I'm working on. Put it in a file and include it in your plugin.</p>\n\n<p>Searching on Google for <strong>add_options_page</strong>, <strong>register_setting</strong>, <strong>add_settings_field</strong> etc. will lead you to the codex entries of WordPress with further descriptions.</p>\n\n<p>The code of the options page below will render 2 checkboxes, with values set to either 0 or 1 / bool true/false.</p>\n\n<p>I'll leave adding text input fields up to you as a little homework, since this is a lot of (free) code.</p>\n\n<p>The HTML/CSS classes is Bootstrap with some special code for a nice checkbox/switch.</p>\n\n<p><em>Please mark the answer as correct if it helped you, thanks.</em></p>\n\n<pre><code>&lt;?php\n/* ============================\n Special Menu Settings Page\n ============================\n*/\n// Add the settings page\nfunction special_menu_admin_menu() { \n add_options_page(\n __('Special menu', 'text-domain'), // Page Title\n __('Special menu', 'text-domain'), // Menu Title\n 'manage_options', // Capability to access it\n 'special-menu-settings', // Menu Slug\n 'html_output_menu_settings_page' // Callback Function\n );\n}\nadd_action('admin_menu', 'special_menu_admin_menu');\n\n// Init the settings, which we want to save\nfunction special_menu_settings_init() {\n\n // ------------------------------------------ Settings\n // Example Setting\n register_setting(\n 'special-menu-settings-group', // Group Name\n 'setting_1' // Settings Name\n );\n\n // Setting 2\n register_setting(\n 'special-menu-settings-group', // Group Name\n 'setting_2' // Settings Name\n );\n\n // ------------------------------------------ Sections\n add_settings_section(\n 'special-menu-settings-section-1', // ID of the Element\n __('Special Menu settings', 'text-domain' ), // Public Name\n '', // Function to print description before actual form\n 'special-menu-settings' // ID of the backend page\n );\n\n // ------------------------------------------- Fields\n\n // Setting 1\n add_settings_field(\n 'setting_1', // Name / ID \n __('Special menu', 'text-domain'), // Public Name\n 'special_menu_setting_1_callback', // Callback Function to print HTML\n 'special-menu-settings', // Name of the settings page, where to put it\n 'special-menu-settings-section-1' // section_where, label_for\n );\n\n // Setting 2\n add_settings_field(\n 'setting_2', // Name / ID \n __('Enable tab 1', 'text-domain'), // Public Name\n 'special_menu_setting_2_callback', // Callback Function to print HTML\n 'special-menu-settings', // Name of the backend page, where to put it\n 'special-menu-settings-section-1' // section_where, label_for\n );\n\n}\nadd_action('admin_init', 'special_menu_settings_init');\n\n// Render the options page in the backend\nfunction html_output_menu_settings_page() { ?&gt;\n &lt;?php\n // In case you need access to the plugin folder path, e.g. use $dir . '/images/whatever.jpg';\n $dir = plugin_dir_path(__FILE__);\n ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h1 class=\"settings-title\"&gt;&lt;?php _e('Special menu settings', 'text-domain'); ?&gt;&lt;/h1&gt;\n &lt;div class=\"container-fluid\"&gt; \n &lt;div class=\"row\"&gt;\n &lt;div class=\"col-xs-12 col-sm-12 col-md-12 col-lg-12\"&gt;\n &lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;?php\n settings_fields('special-menu-settings-group');\n do_settings_sections('special-menu-settings');\n submit_button();\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt; \n &lt;?php\n}\n\n\n// Setting 1 HTML\nfunction special_menu_setting_1_callback() { ?&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col-md-3 text-right\"&gt;\n &lt;div class=\"switch\"&gt;\n &lt;input type=\"checkbox\" class=\"checkbox\" id=\"setting_1\" name=\"setting_1\" value=\"1\" &lt;?php checked(1, get_option('setting_1'), true); ?&gt; /&gt;\n &lt;label for=\"setting_1\" class=\"checkbox-label\"&gt;&lt;/label&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n}\n\n\n// Setting 2 HTML\nfunction special_menu_setting_2_callback() {\n $setting_2 = get_option('setting_2');\n ?&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col text-right\"&gt;\n &lt;div class=\"switch\"&gt;\n &lt;input type=\"checkbox\" class=\"checkbox\" id=\"setting_2\" name=\"setting_2\" value=\"1\" &lt;?php checked(1, get_option('setting_2'), true); ?&gt; /&gt;\n &lt;label for=\"setting_2\" class=\"checkbox-label\"&gt;&lt;/label&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n}\n</code></pre>\n\n<p><strong>Bonus CSS, for the checkbox switch:</strong></p>\n\n<pre><code> // Switch Toggle Checkbox\n.wrap-switch {\n background: #e9ecef;\n padding-top: 7px;\n padding-left: 18px;\n padding-right: 18px;\n border-top: 1px solid #ced4da;\n border-bottom: 1px solid #ced4da;\n}\n\n.switch {\n position: relative;\n float: left;\n width: 55px;\n height: 23px;\n}\n\n.switch:after {\n content: \"\";\n display: table;\n}\n\n.switch input[type=\"checkbox\"] {\n visibility: hidden;\n}\n\n.switch label {\n position: absolute;\n top: 0;\n left: 0;\n width: 55px;\n height: 23px;\n background: tomato;\n border-radius: 50px;\n}\n\n.switch label:after {\n position: absolute;\n top: 1px;\n left: 1px;\n width: 21px;\n height: 21px;\n content: '';\n border-radius: 50px;\n background-color: white;\n transition: all .1s;\n}\n\n.switch input[type=\"checkbox\"]:checked + label:after {\n left: 33px;\n}\n.switch input[type=\"checkbox\"]:checked + label {\n background: lightgreen;\n}\n\n// On/Off Label\n.input-group &gt; .input-group-prepend &gt; .input-group-text {\n border-right: 0;\n}\n.input-group &gt; .input-group-append &gt; .input-group-text {\n border-left: 0;\n}\n</code></pre>\n" }, { "answer_id": 345120, "author": "Makiomar", "author_id": 109616, "author_profile": "https://wordpress.stackexchange.com/users/109616", "pm_score": 0, "selected": false, "text": "<p>You can use <code>add_meta_box</code> and target the <code>nav-menu</code> page. Please check the answer <a href=\"https://stackoverflow.com/a/13924290/7340106\">Here</a></p>\n" } ]
2019/08/14
[ "https://wordpress.stackexchange.com/questions/345091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131331/" ]
I need to provide some custom menu items in a plugin. I mean people can go to dashboard > appearance > menus and add this custom menu item to any menu location. So I want to know how to add the meta box in that page, how to fill it with options and how to output the content in the front end. I tried searching for long but I'm not finding any good resource on how to manage such a thing. Any help? Any links? Thank you.
This is the slimmed down version of a plugin settings page that I'm working on. Put it in a file and include it in your plugin. Searching on Google for **add\_options\_page**, **register\_setting**, **add\_settings\_field** etc. will lead you to the codex entries of WordPress with further descriptions. The code of the options page below will render 2 checkboxes, with values set to either 0 or 1 / bool true/false. I'll leave adding text input fields up to you as a little homework, since this is a lot of (free) code. The HTML/CSS classes is Bootstrap with some special code for a nice checkbox/switch. *Please mark the answer as correct if it helped you, thanks.* ``` <?php /* ============================ Special Menu Settings Page ============================ */ // Add the settings page function special_menu_admin_menu() { add_options_page( __('Special menu', 'text-domain'), // Page Title __('Special menu', 'text-domain'), // Menu Title 'manage_options', // Capability to access it 'special-menu-settings', // Menu Slug 'html_output_menu_settings_page' // Callback Function ); } add_action('admin_menu', 'special_menu_admin_menu'); // Init the settings, which we want to save function special_menu_settings_init() { // ------------------------------------------ Settings // Example Setting register_setting( 'special-menu-settings-group', // Group Name 'setting_1' // Settings Name ); // Setting 2 register_setting( 'special-menu-settings-group', // Group Name 'setting_2' // Settings Name ); // ------------------------------------------ Sections add_settings_section( 'special-menu-settings-section-1', // ID of the Element __('Special Menu settings', 'text-domain' ), // Public Name '', // Function to print description before actual form 'special-menu-settings' // ID of the backend page ); // ------------------------------------------- Fields // Setting 1 add_settings_field( 'setting_1', // Name / ID __('Special menu', 'text-domain'), // Public Name 'special_menu_setting_1_callback', // Callback Function to print HTML 'special-menu-settings', // Name of the settings page, where to put it 'special-menu-settings-section-1' // section_where, label_for ); // Setting 2 add_settings_field( 'setting_2', // Name / ID __('Enable tab 1', 'text-domain'), // Public Name 'special_menu_setting_2_callback', // Callback Function to print HTML 'special-menu-settings', // Name of the backend page, where to put it 'special-menu-settings-section-1' // section_where, label_for ); } add_action('admin_init', 'special_menu_settings_init'); // Render the options page in the backend function html_output_menu_settings_page() { ?> <?php // In case you need access to the plugin folder path, e.g. use $dir . '/images/whatever.jpg'; $dir = plugin_dir_path(__FILE__); ?> <div class="wrap"> <h1 class="settings-title"><?php _e('Special menu settings', 'text-domain'); ?></h1> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <form method="post" action="options.php"> <?php settings_fields('special-menu-settings-group'); do_settings_sections('special-menu-settings'); submit_button(); ?> </form> </div> </div> </div> </div> <?php } // Setting 1 HTML function special_menu_setting_1_callback() { ?> <div class="row"> <div class="col-md-3 text-right"> <div class="switch"> <input type="checkbox" class="checkbox" id="setting_1" name="setting_1" value="1" <?php checked(1, get_option('setting_1'), true); ?> /> <label for="setting_1" class="checkbox-label"></label> </div> </div> </div> <?php } // Setting 2 HTML function special_menu_setting_2_callback() { $setting_2 = get_option('setting_2'); ?> <div class="row"> <div class="col text-right"> <div class="switch"> <input type="checkbox" class="checkbox" id="setting_2" name="setting_2" value="1" <?php checked(1, get_option('setting_2'), true); ?> /> <label for="setting_2" class="checkbox-label"></label> </div> </div> </div> <?php } ``` **Bonus CSS, for the checkbox switch:** ``` // Switch Toggle Checkbox .wrap-switch { background: #e9ecef; padding-top: 7px; padding-left: 18px; padding-right: 18px; border-top: 1px solid #ced4da; border-bottom: 1px solid #ced4da; } .switch { position: relative; float: left; width: 55px; height: 23px; } .switch:after { content: ""; display: table; } .switch input[type="checkbox"] { visibility: hidden; } .switch label { position: absolute; top: 0; left: 0; width: 55px; height: 23px; background: tomato; border-radius: 50px; } .switch label:after { position: absolute; top: 1px; left: 1px; width: 21px; height: 21px; content: ''; border-radius: 50px; background-color: white; transition: all .1s; } .switch input[type="checkbox"]:checked + label:after { left: 33px; } .switch input[type="checkbox"]:checked + label { background: lightgreen; } // On/Off Label .input-group > .input-group-prepend > .input-group-text { border-right: 0; } .input-group > .input-group-append > .input-group-text { border-left: 0; } ```
345,098
<p>Have a parent/child theme setup. The parent theme has a filter I want to remove. How do I remove these filters in the child theme functions?</p> <pre><code>/** --------- */ /** COMMENTS */ /** --------- */ /** FORMAT COMMENT REPLY FIELD */ add_filter('comment_form_field_comment', function () { \XPress::registry()-&gt;loadJS('themehouse/xpress/comment.js'); return '&lt;div data-xf-init="xpress-comment-form"&gt;' . \XPress::getEditorInstance('comment_content', 'comment') . '&lt;/div&gt;'; }, 8); /** READ XF FROALA EDITOR CONTENT ON SAVE */ add_filter('preprocess_comment', function ($data) { $data['comment_content'] = \XPress::getEditorContent('comment_content') ?: $data['comment_content']; if (empty($data['comment_content']) || $data['comment_content'] === 'x') { wp_die(\XPress::xlink()-&gt;phrase('xpress_empty_comment_error'), \XPress::xlink()-&gt;phrase('xpress_empty_comment')); } return $data; }, 99, 1); </code></pre> <p>For example using code like this in our child theme functions:</p> <pre><code>function remove_language_attributes() { remove_filter('language_attributes', 'add_opengraph_doctype'); } add_filter('init', 'remove_language_attributes'); </code></pre>
[ { "answer_id": 345115, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 1, "selected": false, "text": "<p>This is the slimmed down version of a plugin settings page that I'm working on. Put it in a file and include it in your plugin.</p>\n\n<p>Searching on Google for <strong>add_options_page</strong>, <strong>register_setting</strong>, <strong>add_settings_field</strong> etc. will lead you to the codex entries of WordPress with further descriptions.</p>\n\n<p>The code of the options page below will render 2 checkboxes, with values set to either 0 or 1 / bool true/false.</p>\n\n<p>I'll leave adding text input fields up to you as a little homework, since this is a lot of (free) code.</p>\n\n<p>The HTML/CSS classes is Bootstrap with some special code for a nice checkbox/switch.</p>\n\n<p><em>Please mark the answer as correct if it helped you, thanks.</em></p>\n\n<pre><code>&lt;?php\n/* ============================\n Special Menu Settings Page\n ============================\n*/\n// Add the settings page\nfunction special_menu_admin_menu() { \n add_options_page(\n __('Special menu', 'text-domain'), // Page Title\n __('Special menu', 'text-domain'), // Menu Title\n 'manage_options', // Capability to access it\n 'special-menu-settings', // Menu Slug\n 'html_output_menu_settings_page' // Callback Function\n );\n}\nadd_action('admin_menu', 'special_menu_admin_menu');\n\n// Init the settings, which we want to save\nfunction special_menu_settings_init() {\n\n // ------------------------------------------ Settings\n // Example Setting\n register_setting(\n 'special-menu-settings-group', // Group Name\n 'setting_1' // Settings Name\n );\n\n // Setting 2\n register_setting(\n 'special-menu-settings-group', // Group Name\n 'setting_2' // Settings Name\n );\n\n // ------------------------------------------ Sections\n add_settings_section(\n 'special-menu-settings-section-1', // ID of the Element\n __('Special Menu settings', 'text-domain' ), // Public Name\n '', // Function to print description before actual form\n 'special-menu-settings' // ID of the backend page\n );\n\n // ------------------------------------------- Fields\n\n // Setting 1\n add_settings_field(\n 'setting_1', // Name / ID \n __('Special menu', 'text-domain'), // Public Name\n 'special_menu_setting_1_callback', // Callback Function to print HTML\n 'special-menu-settings', // Name of the settings page, where to put it\n 'special-menu-settings-section-1' // section_where, label_for\n );\n\n // Setting 2\n add_settings_field(\n 'setting_2', // Name / ID \n __('Enable tab 1', 'text-domain'), // Public Name\n 'special_menu_setting_2_callback', // Callback Function to print HTML\n 'special-menu-settings', // Name of the backend page, where to put it\n 'special-menu-settings-section-1' // section_where, label_for\n );\n\n}\nadd_action('admin_init', 'special_menu_settings_init');\n\n// Render the options page in the backend\nfunction html_output_menu_settings_page() { ?&gt;\n &lt;?php\n // In case you need access to the plugin folder path, e.g. use $dir . '/images/whatever.jpg';\n $dir = plugin_dir_path(__FILE__);\n ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h1 class=\"settings-title\"&gt;&lt;?php _e('Special menu settings', 'text-domain'); ?&gt;&lt;/h1&gt;\n &lt;div class=\"container-fluid\"&gt; \n &lt;div class=\"row\"&gt;\n &lt;div class=\"col-xs-12 col-sm-12 col-md-12 col-lg-12\"&gt;\n &lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;?php\n settings_fields('special-menu-settings-group');\n do_settings_sections('special-menu-settings');\n submit_button();\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt; \n &lt;?php\n}\n\n\n// Setting 1 HTML\nfunction special_menu_setting_1_callback() { ?&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col-md-3 text-right\"&gt;\n &lt;div class=\"switch\"&gt;\n &lt;input type=\"checkbox\" class=\"checkbox\" id=\"setting_1\" name=\"setting_1\" value=\"1\" &lt;?php checked(1, get_option('setting_1'), true); ?&gt; /&gt;\n &lt;label for=\"setting_1\" class=\"checkbox-label\"&gt;&lt;/label&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n}\n\n\n// Setting 2 HTML\nfunction special_menu_setting_2_callback() {\n $setting_2 = get_option('setting_2');\n ?&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col text-right\"&gt;\n &lt;div class=\"switch\"&gt;\n &lt;input type=\"checkbox\" class=\"checkbox\" id=\"setting_2\" name=\"setting_2\" value=\"1\" &lt;?php checked(1, get_option('setting_2'), true); ?&gt; /&gt;\n &lt;label for=\"setting_2\" class=\"checkbox-label\"&gt;&lt;/label&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n}\n</code></pre>\n\n<p><strong>Bonus CSS, for the checkbox switch:</strong></p>\n\n<pre><code> // Switch Toggle Checkbox\n.wrap-switch {\n background: #e9ecef;\n padding-top: 7px;\n padding-left: 18px;\n padding-right: 18px;\n border-top: 1px solid #ced4da;\n border-bottom: 1px solid #ced4da;\n}\n\n.switch {\n position: relative;\n float: left;\n width: 55px;\n height: 23px;\n}\n\n.switch:after {\n content: \"\";\n display: table;\n}\n\n.switch input[type=\"checkbox\"] {\n visibility: hidden;\n}\n\n.switch label {\n position: absolute;\n top: 0;\n left: 0;\n width: 55px;\n height: 23px;\n background: tomato;\n border-radius: 50px;\n}\n\n.switch label:after {\n position: absolute;\n top: 1px;\n left: 1px;\n width: 21px;\n height: 21px;\n content: '';\n border-radius: 50px;\n background-color: white;\n transition: all .1s;\n}\n\n.switch input[type=\"checkbox\"]:checked + label:after {\n left: 33px;\n}\n.switch input[type=\"checkbox\"]:checked + label {\n background: lightgreen;\n}\n\n// On/Off Label\n.input-group &gt; .input-group-prepend &gt; .input-group-text {\n border-right: 0;\n}\n.input-group &gt; .input-group-append &gt; .input-group-text {\n border-left: 0;\n}\n</code></pre>\n" }, { "answer_id": 345120, "author": "Makiomar", "author_id": 109616, "author_profile": "https://wordpress.stackexchange.com/users/109616", "pm_score": 0, "selected": false, "text": "<p>You can use <code>add_meta_box</code> and target the <code>nav-menu</code> page. Please check the answer <a href=\"https://stackoverflow.com/a/13924290/7340106\">Here</a></p>\n" } ]
2019/08/14
[ "https://wordpress.stackexchange.com/questions/345098", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100439/" ]
Have a parent/child theme setup. The parent theme has a filter I want to remove. How do I remove these filters in the child theme functions? ``` /** --------- */ /** COMMENTS */ /** --------- */ /** FORMAT COMMENT REPLY FIELD */ add_filter('comment_form_field_comment', function () { \XPress::registry()->loadJS('themehouse/xpress/comment.js'); return '<div data-xf-init="xpress-comment-form">' . \XPress::getEditorInstance('comment_content', 'comment') . '</div>'; }, 8); /** READ XF FROALA EDITOR CONTENT ON SAVE */ add_filter('preprocess_comment', function ($data) { $data['comment_content'] = \XPress::getEditorContent('comment_content') ?: $data['comment_content']; if (empty($data['comment_content']) || $data['comment_content'] === 'x') { wp_die(\XPress::xlink()->phrase('xpress_empty_comment_error'), \XPress::xlink()->phrase('xpress_empty_comment')); } return $data; }, 99, 1); ``` For example using code like this in our child theme functions: ``` function remove_language_attributes() { remove_filter('language_attributes', 'add_opengraph_doctype'); } add_filter('init', 'remove_language_attributes'); ```
This is the slimmed down version of a plugin settings page that I'm working on. Put it in a file and include it in your plugin. Searching on Google for **add\_options\_page**, **register\_setting**, **add\_settings\_field** etc. will lead you to the codex entries of WordPress with further descriptions. The code of the options page below will render 2 checkboxes, with values set to either 0 or 1 / bool true/false. I'll leave adding text input fields up to you as a little homework, since this is a lot of (free) code. The HTML/CSS classes is Bootstrap with some special code for a nice checkbox/switch. *Please mark the answer as correct if it helped you, thanks.* ``` <?php /* ============================ Special Menu Settings Page ============================ */ // Add the settings page function special_menu_admin_menu() { add_options_page( __('Special menu', 'text-domain'), // Page Title __('Special menu', 'text-domain'), // Menu Title 'manage_options', // Capability to access it 'special-menu-settings', // Menu Slug 'html_output_menu_settings_page' // Callback Function ); } add_action('admin_menu', 'special_menu_admin_menu'); // Init the settings, which we want to save function special_menu_settings_init() { // ------------------------------------------ Settings // Example Setting register_setting( 'special-menu-settings-group', // Group Name 'setting_1' // Settings Name ); // Setting 2 register_setting( 'special-menu-settings-group', // Group Name 'setting_2' // Settings Name ); // ------------------------------------------ Sections add_settings_section( 'special-menu-settings-section-1', // ID of the Element __('Special Menu settings', 'text-domain' ), // Public Name '', // Function to print description before actual form 'special-menu-settings' // ID of the backend page ); // ------------------------------------------- Fields // Setting 1 add_settings_field( 'setting_1', // Name / ID __('Special menu', 'text-domain'), // Public Name 'special_menu_setting_1_callback', // Callback Function to print HTML 'special-menu-settings', // Name of the settings page, where to put it 'special-menu-settings-section-1' // section_where, label_for ); // Setting 2 add_settings_field( 'setting_2', // Name / ID __('Enable tab 1', 'text-domain'), // Public Name 'special_menu_setting_2_callback', // Callback Function to print HTML 'special-menu-settings', // Name of the backend page, where to put it 'special-menu-settings-section-1' // section_where, label_for ); } add_action('admin_init', 'special_menu_settings_init'); // Render the options page in the backend function html_output_menu_settings_page() { ?> <?php // In case you need access to the plugin folder path, e.g. use $dir . '/images/whatever.jpg'; $dir = plugin_dir_path(__FILE__); ?> <div class="wrap"> <h1 class="settings-title"><?php _e('Special menu settings', 'text-domain'); ?></h1> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <form method="post" action="options.php"> <?php settings_fields('special-menu-settings-group'); do_settings_sections('special-menu-settings'); submit_button(); ?> </form> </div> </div> </div> </div> <?php } // Setting 1 HTML function special_menu_setting_1_callback() { ?> <div class="row"> <div class="col-md-3 text-right"> <div class="switch"> <input type="checkbox" class="checkbox" id="setting_1" name="setting_1" value="1" <?php checked(1, get_option('setting_1'), true); ?> /> <label for="setting_1" class="checkbox-label"></label> </div> </div> </div> <?php } // Setting 2 HTML function special_menu_setting_2_callback() { $setting_2 = get_option('setting_2'); ?> <div class="row"> <div class="col text-right"> <div class="switch"> <input type="checkbox" class="checkbox" id="setting_2" name="setting_2" value="1" <?php checked(1, get_option('setting_2'), true); ?> /> <label for="setting_2" class="checkbox-label"></label> </div> </div> </div> <?php } ``` **Bonus CSS, for the checkbox switch:** ``` // Switch Toggle Checkbox .wrap-switch { background: #e9ecef; padding-top: 7px; padding-left: 18px; padding-right: 18px; border-top: 1px solid #ced4da; border-bottom: 1px solid #ced4da; } .switch { position: relative; float: left; width: 55px; height: 23px; } .switch:after { content: ""; display: table; } .switch input[type="checkbox"] { visibility: hidden; } .switch label { position: absolute; top: 0; left: 0; width: 55px; height: 23px; background: tomato; border-radius: 50px; } .switch label:after { position: absolute; top: 1px; left: 1px; width: 21px; height: 21px; content: ''; border-radius: 50px; background-color: white; transition: all .1s; } .switch input[type="checkbox"]:checked + label:after { left: 33px; } .switch input[type="checkbox"]:checked + label { background: lightgreen; } // On/Off Label .input-group > .input-group-prepend > .input-group-text { border-right: 0; } .input-group > .input-group-append > .input-group-text { border-left: 0; } ```
345,310
<p>I want to make it so that when a user clicks on an image in my site, they are redirected to a specific page. I WAS using a submit button for the redirect, but I want to replace it with a custom-designed icon which I have saved as a png. </p> <p>Here's what I used to have:</p> <pre><code> &lt;form method='post' id='back_button' action=''&gt; &lt;p class='form-submit'&gt; &lt;input name='back_button' type='submit' id='back_button' class='submit button' value= 'Go Back' /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>In <code>functions.php</code>, I have this hooked up like so:</p> <pre><code>if( isset($_POST['back_button'])) redirect_to_team_page(myapp_get_team_uri($_GET['team_id'])); </code></pre> <p>I want to update the back button so that it displays as a <code>.png</code>. I changed my <code>&lt;input&gt;</code> to be an image type, like this:</p> <pre><code> &lt;form method='post' id='back_button' action=''&gt; &lt;p class='form-submit'&gt; &lt;input name='back_button' type='image' id='back_button' src='back.png'/&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>When I do this, I can't seem to get the form to submit anymore. There must be a better approach, but I can't seem to figure it out. </p> <p>Any help would be appreciated! </p>
[ { "answer_id": 345182, "author": "Matthew Brown aka Lord Matt", "author_id": 109240, "author_profile": "https://wordpress.stackexchange.com/users/109240", "pm_score": 0, "selected": false, "text": "<p>The problem that you are going to run into is a fundamental one about how videos on websites work. To watch a video, let's say on youtube, my browser starts downloading the video and shows it to me as it does (this is called streaming) by the time I have watched the entire video, I have also downloaded it. If my browser could not download the video, it would be unable to play it to me.</p>\n\n<p>Every page, image, a and anything else you view in a web browser is downloaded before you can see it.</p>\n\n<p>While there are ways to stop people from keeping a copy after watching a video, there are even more ways for users to get around that. After all, your server already sent them a copy of the video so they could watch it.</p>\n\n<p>The best you can hope for is to make direct video file access very hard and use a streaming-based player without any file-based cache. A sufficiently motivated user will still be able to keep a copy and there is very little you can do about it.</p>\n\n<p>You may be better off finding ways to add value to the viewing on your website experience so that users feel that they would miss out if they cached the video for offline viewing.</p>\n" }, { "answer_id": 364242, "author": "Devstudent", "author_id": 186236, "author_profile": "https://wordpress.stackexchange.com/users/186236", "pm_score": 2, "selected": true, "text": "<p>I found this answer online which responds your question <img src=\"https://i.stack.imgur.com/DCh5n.jpg\" alt=\"enter image description here\"></p>\n" } ]
2019/08/16
[ "https://wordpress.stackexchange.com/questions/345310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147485/" ]
I want to make it so that when a user clicks on an image in my site, they are redirected to a specific page. I WAS using a submit button for the redirect, but I want to replace it with a custom-designed icon which I have saved as a png. Here's what I used to have: ``` <form method='post' id='back_button' action=''> <p class='form-submit'> <input name='back_button' type='submit' id='back_button' class='submit button' value= 'Go Back' /> </p> </form> ``` In `functions.php`, I have this hooked up like so: ``` if( isset($_POST['back_button'])) redirect_to_team_page(myapp_get_team_uri($_GET['team_id'])); ``` I want to update the back button so that it displays as a `.png`. I changed my `<input>` to be an image type, like this: ``` <form method='post' id='back_button' action=''> <p class='form-submit'> <input name='back_button' type='image' id='back_button' src='back.png'/> </p> </form> ``` When I do this, I can't seem to get the form to submit anymore. There must be a better approach, but I can't seem to figure it out. Any help would be appreciated!
I found this answer online which responds your question ![enter image description here](https://i.stack.imgur.com/DCh5n.jpg)
345,335
<p>I've created a custom post type called project for my Wordpress theme, which works fine. Each project has several custom fields, including a set of x and y values that indicate where the project should show on the front page (see the style section of the code below: I know it's not working but I'm showing what I want to achieve in pseudo code).</p> <p>I could display the x value as <code>&lt;?php the_field('x'); ?&gt;</code> and <code>&lt;?php the_field('y'); ?&gt;</code>, as defined by the WordPress's Advanced Custom Field's documentation. However, how do I get the x and y value from PHP to the JavaScript, so I can use them to set the <code>left</code> and <code>top</code> value of the div that indicates where they should be on the front page? </p> <p>Considering that there are many projects and I'm getting different sets of xs and ys in a loop, I'm thinking about writing all the x and y values into an external json file, and then load them back with JavaScript. Is this a feasible option, considering WordPress's structure? Or is there a better option to get these pairs of x and y values from PHP to JavaScript? I know AJAX is always an option, but I'm wondering if there is a simpler way, as I can almost get these exact value pairs in DOM already...</p> <pre><code>&lt;?php $args = array( "post_type" =&gt; "project" ); $projects = new WP_Query($args); while($projects-&gt;have_posts()){ $projects-&gt;the_post(); ?&gt; &lt;a class="project" href="&lt;?php the_permalink(); ?&gt;" style="top:x'px'; left: y'px'"&gt; &lt;p&gt;&lt;?php the_field("title"); ?&gt;&lt;/p&gt; &lt;/a&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 345350, "author": "Rendy de Puniet", "author_id": 130106, "author_profile": "https://wordpress.stackexchange.com/users/130106", "pm_score": 0, "selected": false, "text": "<p>You can use <code>wp_localize_script()</code> function to pass value into js.\nFor example</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );\n\npublic function my_custom_scripts() {\n wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', ['jquery'] );\n wp_localize_script( 'custom-script', 'myScript', [\n 'var_a' =&gt; 'value_a',\n 'var_b' =&gt; 'another value',\n ] );\n}\n</code></pre>\n\n<p>And in your custom_script.js you can get the value like these</p>\n\n<pre><code>console.log(myScript.var_a) // will return `value_a`\nconsole.log(myScript.var_b) // will return `another value`\n</code></pre>\n" }, { "answer_id": 345374, "author": "cbirdsong", "author_id": 134569, "author_profile": "https://wordpress.stackexchange.com/users/134569", "pm_score": 1, "selected": false, "text": "<p>You could output them as inline <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties\" rel=\"nofollow noreferrer\">CSS custom properties</a> instead of left/top, and then use those to set the position in either CSS or Javascript. </p>\n\n<p>PHP: </p>\n\n<pre><code>&lt;a class=\"project\" href=\"&lt;?php the_permalink(); ?&gt;\" style=\"—-x-position: &lt;?php the_field('x'); ?&gt;; —-y-position: &lt;?php the_field('y'); ?&gt;;'\"&gt;\n &lt;p&gt;&lt;?php the_field(\"title\"); ?&gt;&lt;/p&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.project {\n top: var(—-x-position);\n left: var(—-y-position);\n\n /* or CSS grid: */\n grid-row-start: var(—-x-position);\n grid-column-start: var(—-y-position);\n}\n</code></pre>\n\n<p>They’re also accessible in JS, if you need them:</p>\n\n<pre><code>var x_position = element.style.getPropertyValue(\"--x- position\");\n</code></pre>\n\n<p>This will be much more manageable for responsive design since you won’t have to override inline styles with <code>!important</code>, but inputting such specific x/y values is generally a bad idea and you’re probably better off not intermingling presentation quite so directly with your data.</p>\n" } ]
2019/08/17
[ "https://wordpress.stackexchange.com/questions/345335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173574/" ]
I've created a custom post type called project for my Wordpress theme, which works fine. Each project has several custom fields, including a set of x and y values that indicate where the project should show on the front page (see the style section of the code below: I know it's not working but I'm showing what I want to achieve in pseudo code). I could display the x value as `<?php the_field('x'); ?>` and `<?php the_field('y'); ?>`, as defined by the WordPress's Advanced Custom Field's documentation. However, how do I get the x and y value from PHP to the JavaScript, so I can use them to set the `left` and `top` value of the div that indicates where they should be on the front page? Considering that there are many projects and I'm getting different sets of xs and ys in a loop, I'm thinking about writing all the x and y values into an external json file, and then load them back with JavaScript. Is this a feasible option, considering WordPress's structure? Or is there a better option to get these pairs of x and y values from PHP to JavaScript? I know AJAX is always an option, but I'm wondering if there is a simpler way, as I can almost get these exact value pairs in DOM already... ``` <?php $args = array( "post_type" => "project" ); $projects = new WP_Query($args); while($projects->have_posts()){ $projects->the_post(); ?> <a class="project" href="<?php the_permalink(); ?>" style="top:x'px'; left: y'px'"> <p><?php the_field("title"); ?></p> </a> <?php } ?> ```
You could output them as inline [CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) instead of left/top, and then use those to set the position in either CSS or Javascript. PHP: ``` <a class="project" href="<?php the_permalink(); ?>" style="—-x-position: <?php the_field('x'); ?>; —-y-position: <?php the_field('y'); ?>;'"> <p><?php the_field("title"); ?></p> </a> ``` CSS: ``` .project { top: var(—-x-position); left: var(—-y-position); /* or CSS grid: */ grid-row-start: var(—-x-position); grid-column-start: var(—-y-position); } ``` They’re also accessible in JS, if you need them: ``` var x_position = element.style.getPropertyValue("--x- position"); ``` This will be much more manageable for responsive design since you won’t have to override inline styles with `!important`, but inputting such specific x/y values is generally a bad idea and you’re probably better off not intermingling presentation quite so directly with your data.
345,359
<p>I installed the hestia theme from the themes listed in the dashboard. All other themes worked fine but this one causes Wordpress to crash and I am unable to login though, interestingly, I can view the hestia demo site installed on my system. </p> <p>So what do I need to do to be able to log in to Wordpress or remove the hestia theme or fix the error? Here is the error on all pages other than the hestia demo:</p> <blockquote> <p>Fatal error: Uncaught Error: Call to undefined function filter_var() in /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/includes/admin/class-am-deactivation-survey.php:88<br> Stack trace: #0 /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/includes/admin/class-am-deactivation-survey.php(53): AM_Deactivation_Survey->is_dev_url()<br> #1 /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/src/WPForms.php(298): AM_Deactivation_Survey->__construct('WPForms', 'wpforms-lite')<br> #2 /usr/local/www/wordpress/wp-includes/class-wp-hook.php(286): WPForms\WPForms->objects('')<br> #3 /usr/local/www/wordpress/wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters(NULL, Array)<br> #4 /usr/local/www/wordpress/wp-includes/plugin.php(465): WP_Hook->do_action(Array)<br> #5 /usr/local/www/wordpress/wp-settings.php(394): do_action('plugins_loaded') #6 /usr/local/www/wordpress/wp-config.php(93): require_once('/usr/local/www/...')<br> #7 /usr/local/www/wordpress/wp-load.php(37): require_once('/usr/local/www/...')<br> #8 /usr/local/www/wordpress/wp-ad in /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/includes/admin/class-am-deactivation-survey.php on line 88 </p> <p>The site is experiencing technical difficulties. Please check your site admin email inbox for instructions.</p> </blockquote> <p>EDIT: Elsewhere I read that I can go to wp-content/themes and remove the theme folder but that did not fix anything.</p>
[ { "answer_id": 345350, "author": "Rendy de Puniet", "author_id": 130106, "author_profile": "https://wordpress.stackexchange.com/users/130106", "pm_score": 0, "selected": false, "text": "<p>You can use <code>wp_localize_script()</code> function to pass value into js.\nFor example</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );\n\npublic function my_custom_scripts() {\n wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', ['jquery'] );\n wp_localize_script( 'custom-script', 'myScript', [\n 'var_a' =&gt; 'value_a',\n 'var_b' =&gt; 'another value',\n ] );\n}\n</code></pre>\n\n<p>And in your custom_script.js you can get the value like these</p>\n\n<pre><code>console.log(myScript.var_a) // will return `value_a`\nconsole.log(myScript.var_b) // will return `another value`\n</code></pre>\n" }, { "answer_id": 345374, "author": "cbirdsong", "author_id": 134569, "author_profile": "https://wordpress.stackexchange.com/users/134569", "pm_score": 1, "selected": false, "text": "<p>You could output them as inline <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties\" rel=\"nofollow noreferrer\">CSS custom properties</a> instead of left/top, and then use those to set the position in either CSS or Javascript. </p>\n\n<p>PHP: </p>\n\n<pre><code>&lt;a class=\"project\" href=\"&lt;?php the_permalink(); ?&gt;\" style=\"—-x-position: &lt;?php the_field('x'); ?&gt;; —-y-position: &lt;?php the_field('y'); ?&gt;;'\"&gt;\n &lt;p&gt;&lt;?php the_field(\"title\"); ?&gt;&lt;/p&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.project {\n top: var(—-x-position);\n left: var(—-y-position);\n\n /* or CSS grid: */\n grid-row-start: var(—-x-position);\n grid-column-start: var(—-y-position);\n}\n</code></pre>\n\n<p>They’re also accessible in JS, if you need them:</p>\n\n<pre><code>var x_position = element.style.getPropertyValue(\"--x- position\");\n</code></pre>\n\n<p>This will be much more manageable for responsive design since you won’t have to override inline styles with <code>!important</code>, but inputting such specific x/y values is generally a bad idea and you’re probably better off not intermingling presentation quite so directly with your data.</p>\n" } ]
2019/08/18
[ "https://wordpress.stackexchange.com/questions/345359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173579/" ]
I installed the hestia theme from the themes listed in the dashboard. All other themes worked fine but this one causes Wordpress to crash and I am unable to login though, interestingly, I can view the hestia demo site installed on my system. So what do I need to do to be able to log in to Wordpress or remove the hestia theme or fix the error? Here is the error on all pages other than the hestia demo: > > Fatal error: Uncaught Error: Call to undefined function filter\_var() in /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/includes/admin/class-am-deactivation-survey.php:88 > > Stack trace: #0 /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/includes/admin/class-am-deactivation-survey.php(53): AM\_Deactivation\_Survey->is\_dev\_url() > > #1 /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/src/WPForms.php(298): AM\_Deactivation\_Survey->\_\_construct('WPForms', 'wpforms-lite') > > #2 /usr/local/www/wordpress/wp-includes/class-wp-hook.php(286): WPForms\WPForms->objects('') > > #3 /usr/local/www/wordpress/wp-includes/class-wp-hook.php(310): WP\_Hook->apply\_filters(NULL, Array) > > #4 /usr/local/www/wordpress/wp-includes/plugin.php(465): WP\_Hook->do\_action(Array) > > #5 /usr/local/www/wordpress/wp-settings.php(394): do\_action('plugins\_loaded') > #6 /usr/local/www/wordpress/wp-config.php(93): require\_once('/usr/local/www/...') > > #7 /usr/local/www/wordpress/wp-load.php(37): require\_once('/usr/local/www/...') > > #8 /usr/local/www/wordpress/wp-ad in /usr/local/www/wordpress/wp-content/plugins/wpforms-lite/includes/admin/class-am-deactivation-survey.php on line 88 > > > The site is experiencing technical difficulties. Please check your site admin email inbox for instructions. > > > EDIT: Elsewhere I read that I can go to wp-content/themes and remove the theme folder but that did not fix anything.
You could output them as inline [CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) instead of left/top, and then use those to set the position in either CSS or Javascript. PHP: ``` <a class="project" href="<?php the_permalink(); ?>" style="—-x-position: <?php the_field('x'); ?>; —-y-position: <?php the_field('y'); ?>;'"> <p><?php the_field("title"); ?></p> </a> ``` CSS: ``` .project { top: var(—-x-position); left: var(—-y-position); /* or CSS grid: */ grid-row-start: var(—-x-position); grid-column-start: var(—-y-position); } ``` They’re also accessible in JS, if you need them: ``` var x_position = element.style.getPropertyValue("--x- position"); ``` This will be much more manageable for responsive design since you won’t have to override inline styles with `!important`, but inputting such specific x/y values is generally a bad idea and you’re probably better off not intermingling presentation quite so directly with your data.
345,367
<p>I am trying to create my first worpress plugin! </p> <p>Actually, the idea is when i click on the button, an ajax request is sent toward php file (ajax-process.php ), it contains a very basic code to pull some data from database and then displaying it as an alert or other in my home page .</p> <p>This is my plugin floder (inside wordpress plugins folder) </p> <ul> <li><p>DB-Puller :</p> <pre><code> - DB-Puller.php - ajax-process.php </code></pre> <p>And js (js_file.js) + css (css_file.css) folders.</p></li> </ul> <p>Here what contains DB-Puller.php </p> <pre><code>&lt;?php /** * Plugin Name: DB-Puller * Plugin URI: https://my-web-site.com/ * Description: This is a my firt plugin, it(s allows to display data from database. * Version: 0.1 * Author: Firest Last name * Author URI: https://my-web-site.com/ * License: GPL3 */ function scripts_files_enqueue_scripts() { // Adding css file wp_enqueue_style('css_file',plugins_url( 'css/css_file.css', __FILE__ ) ); // Adding JS file wp_enqueue_script( 'js_file', plugins_url( 'js/js_file.js', __FILE__ ), array('jquery'), '1.0', true ); } add_action('wp_enqueue_scripts', 'scripts_files_enqueue_scripts'); /* Load Ajax Callback to "wp_ajax_*" Action Hook */ add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' ); ?&gt; </code></pre> <p>And This what contains ajax-process.php<br> N.B : the database table is very basic, it contains just id + text columns </p> <pre><code>&lt;?php function my_ajax_action_callback() { if (isset($_POST['req'])) { global $wpdb; $quer = $wpdb-&gt;get_results( "SELECT * FROM wp_custom_table_1" ); $arr = $quer[0]-&gt;text; echo $arr; die(); } wp_die(); // required. to end AJAX request. } </code></pre> <p>What contains js file </p> <pre><code>jQuery(function($){ $('body').prepend('&lt;button class="btn" type="button"&gt;PULL DATA&lt;/button&gt;'); $('button.btn').on('click', function() { $.ajax({ url:'http://127.0.0.1/wp522/wp-content/plugins/DB-Puller/ajax-process.php', method:'POST', data:{ req:'', action:'my_ajax_action', }, success:function(data) { alert(data); }, error:function() { alert(erooor); } }) }) }) </code></pre> <p>The Alert is sent empty ! Please help me to detect where is the problem!</p> <p>Thank you.</p>
[ { "answer_id": 345394, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": -1, "selected": false, "text": "<p>Try bellow Code:</p>\n\n<ul>\n<li><p>DB-Puller.php</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: DB-Puller \n * Plugin URI: https://my-web-site.com/\n * Description: This is a my firt plugin, it(s allows to display data from database. \n * Version: 0.1\n * Author: Firest Last name\n * Author URI: https://my-web-site.com/\n * License: GPL3\n */\n\nfunction scripts_files_enqueue_scripts() {\n // Adding css file \n wp_enqueue_style('css_file',plugins_url( 'css/css_file.css', __FILE__ ) );\n\n // Adding JS file \n wp_enqueue_script( 'js_file', plugins_url( 'js/js_file.js', __FILE__ ), array('jquery'), '1.0', true );\n # define ajax objext\n wp_localize_script('js_file','my_ajax_object',array('ajaxurl' =&gt; admin_url( 'admin-ajax.php' )));\n}\n\nadd_action('wp_enqueue_scripts', 'scripts_files_enqueue_scripts');\n\nrequire_once plugin_dir_path( __FILE__ ) . 'ajax-process.php';\n\n/* Load Ajax Callback to \"wp_ajax_*\" Action Hook */\nadd_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );\nadd_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );\n</code></pre></li>\n</ul>\n\n<p>js/js_file.js</p>\n\n<pre><code>jQuery(function($){\n\n $('body').prepend('&lt;button class=\"btn\" type=\"button\"&gt;PULL DATA&lt;/button&gt;');\n\n $('button.btn').on('click', function()\n {\n\n $.ajax({\n\n url:my_ajax_object.ajaxurl,\n method:'POST',\n data:{\n req:'',\n action:'my_ajax_action',\n },\n success:function(data)\n {\n alert(data);\n },\n error:function()\n {\n alert(erooor);\n }\n })\n })\n})\n</code></pre>\n\n<p>ajax-procees.php</p>\n\n<pre><code>&lt;?php\n\nfunction my_ajax_action_callback()\n{\n if (isset($_POST['req']))\n {\n global $wpdb;\n $quer = $wpdb-&gt;get_results( \"SELECT * FROM wp_custom_table_1\" ); \n $arr = $quer[0]-&gt;text;\n echo $arr;\n die();\n }\n wp_die(); // required. to end AJAX request.\n}\n</code></pre>\n\n<p>in above code, i have added a localize ajax path and include a ajax-process.php file, and in js_file.js i have added url of ajax. let me know if this works for you!</p>\n" }, { "answer_id": 345560, "author": "Cyclonecode", "author_id": 14870, "author_profile": "https://wordpress.stackexchange.com/users/14870", "pm_score": 0, "selected": false, "text": "<p>I have already answered this question stackoverflow, but adding the answer here as well:</p>\n\n<p>Looking on the code it does not seem like the Wordpress way of doing this kind of thing.</p>\n\n<p>First you need to include your <code>ajax-process.php</code> in the plugins main file e.g:</p>\n\n<pre><code>require_once plugin_dir_path(__FILE__) . '/ajax-process.php';\n</code></pre>\n\n<p>Second, you need to register your ajax callback like this:</p>\n\n<pre><code>add_action('wp_ajax_my_ajax_action', 'my_ajax_function');\nadd_action('wp_ajax_no_priv_my_ajax_action', 'my_ajax_function');\n</code></pre>\n\n<p>Then register the ajaxUrl in <code>scripts_files_enqueue_scripts()</code> so it accessible from your javascript. The <code>admin-ajax.php</code> file handles all ajax requests:</p>\n\n<pre><code>wp_localize_script(\n 'js_file',\n 'ajax',\n array(\n 'ajaxUrl' =&gt; admin_url('admin-ajax.php'),\n )\n);\n</code></pre>\n\n<p>Then in your javascript you need to use the <code>ajaxUrl</code> and specifying the <code>action</code> which will tell Wordpress which callback should be triggered:</p>\n\n<pre><code>jQuery(function($) {\n $('body').prepend('&lt;button class=\"btn\" type=\"button\"&gt;PULL DATA&lt;/button&gt;');\n\n $('button.btn').on('click', function() {\n $.post({\n url: ajax.ajaxUrl,\n data: {\n req: '',\n action: 'my_ajax_action',\n },\n success: function(data) {\n alert(data);\n },\n error: function() {\n alert('error'); \n }\n });\n});\n</code></pre>\n\n<p>Here is a good article <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">AJAX in Plugins</a>, explaining how to use ajax in a plugin.</p>\n" } ]
2019/08/18
[ "https://wordpress.stackexchange.com/questions/345367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173693/" ]
I am trying to create my first worpress plugin! Actually, the idea is when i click on the button, an ajax request is sent toward php file (ajax-process.php ), it contains a very basic code to pull some data from database and then displaying it as an alert or other in my home page . This is my plugin floder (inside wordpress plugins folder) * DB-Puller : ``` - DB-Puller.php - ajax-process.php ``` And js (js\_file.js) + css (css\_file.css) folders. Here what contains DB-Puller.php ``` <?php /** * Plugin Name: DB-Puller * Plugin URI: https://my-web-site.com/ * Description: This is a my firt plugin, it(s allows to display data from database. * Version: 0.1 * Author: Firest Last name * Author URI: https://my-web-site.com/ * License: GPL3 */ function scripts_files_enqueue_scripts() { // Adding css file wp_enqueue_style('css_file',plugins_url( 'css/css_file.css', __FILE__ ) ); // Adding JS file wp_enqueue_script( 'js_file', plugins_url( 'js/js_file.js', __FILE__ ), array('jquery'), '1.0', true ); } add_action('wp_enqueue_scripts', 'scripts_files_enqueue_scripts'); /* Load Ajax Callback to "wp_ajax_*" Action Hook */ add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' ); ?> ``` And This what contains ajax-process.php N.B : the database table is very basic, it contains just id + text columns ``` <?php function my_ajax_action_callback() { if (isset($_POST['req'])) { global $wpdb; $quer = $wpdb->get_results( "SELECT * FROM wp_custom_table_1" ); $arr = $quer[0]->text; echo $arr; die(); } wp_die(); // required. to end AJAX request. } ``` What contains js file ``` jQuery(function($){ $('body').prepend('<button class="btn" type="button">PULL DATA</button>'); $('button.btn').on('click', function() { $.ajax({ url:'http://127.0.0.1/wp522/wp-content/plugins/DB-Puller/ajax-process.php', method:'POST', data:{ req:'', action:'my_ajax_action', }, success:function(data) { alert(data); }, error:function() { alert(erooor); } }) }) }) ``` The Alert is sent empty ! Please help me to detect where is the problem! Thank you.
I have already answered this question stackoverflow, but adding the answer here as well: Looking on the code it does not seem like the Wordpress way of doing this kind of thing. First you need to include your `ajax-process.php` in the plugins main file e.g: ``` require_once plugin_dir_path(__FILE__) . '/ajax-process.php'; ``` Second, you need to register your ajax callback like this: ``` add_action('wp_ajax_my_ajax_action', 'my_ajax_function'); add_action('wp_ajax_no_priv_my_ajax_action', 'my_ajax_function'); ``` Then register the ajaxUrl in `scripts_files_enqueue_scripts()` so it accessible from your javascript. The `admin-ajax.php` file handles all ajax requests: ``` wp_localize_script( 'js_file', 'ajax', array( 'ajaxUrl' => admin_url('admin-ajax.php'), ) ); ``` Then in your javascript you need to use the `ajaxUrl` and specifying the `action` which will tell Wordpress which callback should be triggered: ``` jQuery(function($) { $('body').prepend('<button class="btn" type="button">PULL DATA</button>'); $('button.btn').on('click', function() { $.post({ url: ajax.ajaxUrl, data: { req: '', action: 'my_ajax_action', }, success: function(data) { alert(data); }, error: function() { alert('error'); } }); }); ``` Here is a good article [AJAX in Plugins](https://codex.wordpress.org/AJAX_in_Plugins), explaining how to use ajax in a plugin.
345,376
<p>I am trying to add some custom meta variables to a custom post type, but I can't see the new variables when I dump a posts meta data, and I can't access it in</p> <p>Here is the post definition from my functions.php file</p> <pre><code>function register_team_post(){ register_post_type('team', [ 'public'=&gt;true, 'labels'=&gt;array( 'name'=&gt;'Team', 'add_new_item'=&gt;'Add New Team Member', 'edit_item'=&gt;'Edit Team Member', 'all_items'=&gt;'All Team Member' ), 'menu_icon'=&gt;'dashicons-businessman', 'show_in_rest' =&gt; true, // 'supports' =&gt; array('editor','title', 'custom-fields'), 'supports' =&gt; array('editor','title'), 'rewrite' =&gt; array('slug' =&gt; 'teams'), 'template' =&gt; array( array( 'dqcblocks/member' ) ) ]); $fields = [ 'team_member_portrait', 'team_member_name', 'team_member_title', 'team_member_description' ]; $args = array('show_in_rest' =&gt; true, 'type' =&gt; 'string'); foreach($fields as $field){ register_post_meta( 'team', $field, $args); } } add_action('init', 'register_team_post'); </code></pre> <p>If I create a team post and tried dumping the meta fields, but my new fields don't appear:</p> <pre><code>$meta_values = get_post_meta( get_the_ID() ); var_dump( $meta_values ); </code></pre> <p>result:</p> <pre><code>array(2) { ["_edit_lock"]=&gt; array(1) { [0]=&gt; string(12) "1566159392:1" } ["_edit_last"]=&gt; array(1) { [0]=&gt; string(1) "1" } } </code></pre> <p>I also tried using my custom meta fields in a Gutenberg block.</p> <pre><code>attributes: { portrait: { type: "string", source: "meta", meta: "team_member_portrait", }, name: { type: "string", source: "meta", meta: "team_member_name", }, title: { type: "string", source : "meta", meta: "team_member_title", }, description: { type: "string", source: "meta", meta: "team_member_description", } } </code></pre> <p>but when I add my block and save the variables don't update and remain empty.</p> <p>Am I using register_post_meta correctly?</p>
[ { "answer_id": 345378, "author": "Den Pat", "author_id": 103569, "author_profile": "https://wordpress.stackexchange.com/users/103569", "pm_score": -1, "selected": false, "text": "<p>Try Fire it on init instead of inside register_post_type like this:</p>\n\n<pre><code>add_action('init','345376_register_metaof_team');\nfunction 345376_register_metaof_team(){\n\n$object_type = 'post';\n$args = array(\n 'type' =&gt; 'string',\n 'description' =&gt; 'A meta key associated with post views.',\n 'single' =&gt; true,\n 'show_in_rest' =&gt; true,\n);\n\nregister_meta( $object_type, 'post_views', $args );\n\n}\n</code></pre>\n" }, { "answer_id": 386954, "author": "S.Walsh", "author_id": 194155, "author_profile": "https://wordpress.stackexchange.com/users/194155", "pm_score": 1, "selected": false, "text": "<p>When registering the Custom Post Type, ensure <strong>custom-fields</strong> is present in <code>supports =&gt; array('editor','title', 'custom-fields')</code>. It's the legacy wording of <em>meta fields</em> and is commonly mistakenly omitted when declaring supports in CPTs.</p>\n<p>After you make the above change, your Team CPT should work with meta values. You still may encounter in Gutenberg initially, the meta values are 'undefined' as they don't have a default value set. A default value can be set either when registering the Post Meta eg. <code>'default' =&gt; 'test string'</code> or in the block attributes.</p>\n<p><em>NB. The documentation has been updated since this question was posted <a href=\"https://core.trac.wordpress.org/ticket/47866\" rel=\"nofollow noreferrer\">ref: trac #47866</a>\nRefer to the latest <a href=\"https://developer.wordpress.org/rest-api/changelog/\" rel=\"nofollow noreferrer\">WordPress REST API</a> to see all the changes</em></p>\n" }, { "answer_id": 395865, "author": "Sunny Johal", "author_id": 161335, "author_profile": "https://wordpress.stackexchange.com/users/161335", "pm_score": 0, "selected": false, "text": "<p>For anyone else reading this old thread:</p>\n<p>Here is how it should've been done</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nfunction register_team_post() {\n register_post_type(\n 'team',\n [\n 'public' =&gt; true,\n 'labels' =&gt; [\n 'name' =&gt; 'Team',\n 'add_new_item' =&gt; 'Add New Team Member',\n 'edit_item' =&gt; 'Edit Team Member',\n 'all_items' =&gt; 'All Team Member',\n ],\n 'menu_icon' =&gt; 'dashicons-businessman',\n 'show_in_rest' =&gt; true,\n 'supports' =&gt; [ 'editor', 'title', 'custom-fields' ],\n 'rewrite' =&gt; [ 'slug' =&gt; 'teams' ],\n 'template' =&gt; [ [ 'dqcblocks/member' ] ],\n ]\n );\n\n $fields = [\n 'team_member_portrait',\n 'team_member_name',\n 'team_member_title',\n 'team_member_description',\n ];\n\n $args = [\n 'object_subtype' =&gt; 'team', // this is the correct place to pass the post type.\n 'show_in_rest' =&gt; true,\n 'type' =&gt; 'string',\n ];\n\n foreach ( $fields as $field ) {\n register_meta( 'post', $field, $args );\n }\n}\n\nadd_action( 'init', 'register_team_post' );\n\n</code></pre>\n" } ]
2019/08/18
[ "https://wordpress.stackexchange.com/questions/345376", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173665/" ]
I am trying to add some custom meta variables to a custom post type, but I can't see the new variables when I dump a posts meta data, and I can't access it in Here is the post definition from my functions.php file ``` function register_team_post(){ register_post_type('team', [ 'public'=>true, 'labels'=>array( 'name'=>'Team', 'add_new_item'=>'Add New Team Member', 'edit_item'=>'Edit Team Member', 'all_items'=>'All Team Member' ), 'menu_icon'=>'dashicons-businessman', 'show_in_rest' => true, // 'supports' => array('editor','title', 'custom-fields'), 'supports' => array('editor','title'), 'rewrite' => array('slug' => 'teams'), 'template' => array( array( 'dqcblocks/member' ) ) ]); $fields = [ 'team_member_portrait', 'team_member_name', 'team_member_title', 'team_member_description' ]; $args = array('show_in_rest' => true, 'type' => 'string'); foreach($fields as $field){ register_post_meta( 'team', $field, $args); } } add_action('init', 'register_team_post'); ``` If I create a team post and tried dumping the meta fields, but my new fields don't appear: ``` $meta_values = get_post_meta( get_the_ID() ); var_dump( $meta_values ); ``` result: ``` array(2) { ["_edit_lock"]=> array(1) { [0]=> string(12) "1566159392:1" } ["_edit_last"]=> array(1) { [0]=> string(1) "1" } } ``` I also tried using my custom meta fields in a Gutenberg block. ``` attributes: { portrait: { type: "string", source: "meta", meta: "team_member_portrait", }, name: { type: "string", source: "meta", meta: "team_member_name", }, title: { type: "string", source : "meta", meta: "team_member_title", }, description: { type: "string", source: "meta", meta: "team_member_description", } } ``` but when I add my block and save the variables don't update and remain empty. Am I using register\_post\_meta correctly?
When registering the Custom Post Type, ensure **custom-fields** is present in `supports => array('editor','title', 'custom-fields')`. It's the legacy wording of *meta fields* and is commonly mistakenly omitted when declaring supports in CPTs. After you make the above change, your Team CPT should work with meta values. You still may encounter in Gutenberg initially, the meta values are 'undefined' as they don't have a default value set. A default value can be set either when registering the Post Meta eg. `'default' => 'test string'` or in the block attributes. *NB. The documentation has been updated since this question was posted [ref: trac #47866](https://core.trac.wordpress.org/ticket/47866) Refer to the latest [WordPress REST API](https://developer.wordpress.org/rest-api/changelog/) to see all the changes*
345,384
<p>I need some help writing a shortcode to display all product tags associated with a specific product category which can be displayed on any page. </p> <p>My problem is that I can display all product tags anywhere by using the below code, but I'm unable to filter those tags by a given product category:</p> <pre><code>function product_terms_by_cat() { $terms = get_terms ( array ( 'taxonomy' =&gt; 'product_tag', 'hide_empty' =&gt; false) ); foreach ( $terms as $term ) { echo $term-&gt;name; } } add_shortcode('product_terms_by_cat', 'product_terms_by_cat'); </code></pre> <p>I've tried using functions for standard WP post tags/categories but they're used within the loop (eg. category pages or single post pages) and don't help. </p> <p>Could modifying the code found on <a href="https://stackoverflow.com/questions/44578723/display-product-categories-based-on-tags-of-a-product-woocommerce-php">this link</a> work?The code filters categories based on tags (the opposite of what I want). Cheers</p>
[ { "answer_id": 345389, "author": "Wordpress Dev", "author_id": 173354, "author_profile": "https://wordpress.stackexchange.com/users/173354", "pm_score": 0, "selected": false, "text": "<pre><code>function product_terms_by_cat() { \n$terms = get_terms (\n array (\n 'taxonomy' =&gt; 'product_category', \n 'hide_empty' =&gt; false)\n );\nforeach ( $terms as $term ) {\n echo $term-&gt;name;\n}\n} \nadd_shortcode('product_terms_by_cat', 'product_terms_by_cat');\n</code></pre>\n" }, { "answer_id": 345403, "author": "JVAN", "author_id": 52551, "author_profile": "https://wordpress.stackexchange.com/users/52551", "pm_score": 2, "selected": true, "text": "<p>Ahh ha! Have figured out how to do this. Here's the code for future people who are looking for the same thing:</p>\n\n<pre><code>function get_category_tags($args) {\n global $wpdb;\n $tags = $wpdb-&gt;get_results(\"\n SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, terms2.slug as tag_slug, null as tag_link\n FROM\n wp_posts as p1\n LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID\n LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id\n LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id,\n\n wp_posts as p2\n LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID\n LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id\n LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id\n WHERE\n t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id IN (\".$args['categories'].\") AND \n t2.taxonomy = 'product_tag' AND p2.post_status = 'publish'\n AND p1.ID = p2.ID\n ORDER by tag_name\n \");\n\n $count = 0;\n\n foreach ($tags as $tag) {\n $tags[$count]-&gt;tag_link = get_tag_link($tag-&gt;tag_id);\n $count++;\n }\n return $tags;\n}\n\n$args = array('categories'=&gt; \"YOUR PRODUCT CATEGORY ID HERE\"); \n$tags = get_category_tags($args); \n\nforeach ($tags as $tag) { \n echo '&lt;a href=\"'.$tag-&gt;tag_link.'\"&gt;' . $tag-&gt;tag_name . '&lt;/a&gt;'; \n}\n</code></pre>\n\n<p>I used this in a WP Bakery shortcode and it worked a treat. I guess you could use this wherever you would like. Enjoy!</p>\n" } ]
2019/08/19
[ "https://wordpress.stackexchange.com/questions/345384", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52551/" ]
I need some help writing a shortcode to display all product tags associated with a specific product category which can be displayed on any page. My problem is that I can display all product tags anywhere by using the below code, but I'm unable to filter those tags by a given product category: ``` function product_terms_by_cat() { $terms = get_terms ( array ( 'taxonomy' => 'product_tag', 'hide_empty' => false) ); foreach ( $terms as $term ) { echo $term->name; } } add_shortcode('product_terms_by_cat', 'product_terms_by_cat'); ``` I've tried using functions for standard WP post tags/categories but they're used within the loop (eg. category pages or single post pages) and don't help. Could modifying the code found on [this link](https://stackoverflow.com/questions/44578723/display-product-categories-based-on-tags-of-a-product-woocommerce-php) work?The code filters categories based on tags (the opposite of what I want). Cheers
Ahh ha! Have figured out how to do this. Here's the code for future people who are looking for the same thing: ``` function get_category_tags($args) { global $wpdb; $tags = $wpdb->get_results(" SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, terms2.slug as tag_slug, null as tag_link FROM wp_posts as p1 LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id, wp_posts as p2 LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id WHERE t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id IN (".$args['categories'].") AND t2.taxonomy = 'product_tag' AND p2.post_status = 'publish' AND p1.ID = p2.ID ORDER by tag_name "); $count = 0; foreach ($tags as $tag) { $tags[$count]->tag_link = get_tag_link($tag->tag_id); $count++; } return $tags; } $args = array('categories'=> "YOUR PRODUCT CATEGORY ID HERE"); $tags = get_category_tags($args); foreach ($tags as $tag) { echo '<a href="'.$tag->tag_link.'">' . $tag->tag_name . '</a>'; } ``` I used this in a WP Bakery shortcode and it worked a treat. I guess you could use this wherever you would like. Enjoy!
345,422
<p>I would like to remove the "private" prefix for each post title. I found the filter <a href="https://wp-mix.com/remove-private-post-titles/" rel="nofollow noreferrer">here</a>. I managed to removed the word "Private" but when I concatenate with " : ". That does not work anymore. I checked <code>$title</code> value before the <code>str_replace</code> and it´s already translated with " : ".</p> <pre><code>Class FrontEnd{ protected function front_end_init() { add_filter( 'the_title', array( $this, 'remove_private_prefix' ) ); } public static function remove_private_prefix( $title ) { $title = str_replace( __( 'Private' ) . " : ", '', $title); return $title; } } </code></pre> <p>How can I fix this ?</p>
[ { "answer_id": 345425, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": 0, "selected": false, "text": "<p>I found a solution based on this <a href=\"https://css-tricks.com/snippets/wordpress/remove-privateprotected-from-post-titles/\" rel=\"nofollow noreferrer\">post</a></p>\n\n<pre><code>Class FrontEnd{\n\n protected function front_end_init() {\n add_filter( 'the_title', array( $this, 'remove_title_prefix' ) );\n }\n\n public static function remove_title_prefix( $title ) {\n $title = esc_attr($title);\n\n $findthese = array(\n '#[' . __(\"Protected\") . ' : ]#',\n '#[' . __(\"Private\") . ' : ]#'\n );\n $replacewith = array(\n '', // What to replace \"Protected:\" with\n '' // What to replace \"Private:\" with\n );\n\n $title = preg_replace($findthese, $replacewith, $title);\n return $title;\n }\n}\n</code></pre>\n" }, { "answer_id": 345501, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": 0, "selected": false, "text": "<p>As @Sally CJ said, A better way is to used the function <a href=\"https://developer.wordpress.org/reference/hooks/private_title_format/\" rel=\"nofollow noreferrer\">private_title_format</a>.\nSo...</p>\n\n<p>If you can set the <code>WP_Post</code>, you can use this code line : </p>\n\n<p><code>apply_filters( 'private_title_format', \"\", $post );</code></p>\n\n<p>If you do not know the $post for some reason like for my example, you can overwrite the filter like this:</p>\n\n<pre><code>Class FrontEnd{\n\n protected function front_end_init() {\n add_filter( 'private_title_format', array( $this, 'remove_prefix_private_post_title' ), 10, 2 );\n }\n\n public function remove_prefix_private_post_title( $format, $post ){\n return '%s';\n }\n}\n</code></pre>\n" }, { "answer_id": 352780, "author": "shea", "author_id": 19726, "author_profile": "https://wordpress.stackexchange.com/users/19726", "pm_score": 3, "selected": false, "text": "<p>The simplest answer is as follows:</p>\n\n<pre><code>add_filter( 'private_title_format', function ( $format ) {\n return '%s';\n} );\n</code></pre>\n\n<p>It uses the <code>private_title_format</code> to change the format of the title to just the post title, without any unnecessary classes or functions.</p>\n" }, { "answer_id": 400416, "author": "D L", "author_id": 217014, "author_profile": "https://wordpress.stackexchange.com/users/217014", "pm_score": 0, "selected": false, "text": "<p>Try removing the space before the colon, so &quot; : &quot; becomes &quot;: &quot;.\nOr use a superior method like shea's.</p>\n" } ]
2019/08/19
[ "https://wordpress.stackexchange.com/questions/345422", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I would like to remove the "private" prefix for each post title. I found the filter [here](https://wp-mix.com/remove-private-post-titles/). I managed to removed the word "Private" but when I concatenate with " : ". That does not work anymore. I checked `$title` value before the `str_replace` and it´s already translated with " : ". ``` Class FrontEnd{ protected function front_end_init() { add_filter( 'the_title', array( $this, 'remove_private_prefix' ) ); } public static function remove_private_prefix( $title ) { $title = str_replace( __( 'Private' ) . " : ", '', $title); return $title; } } ``` How can I fix this ?
The simplest answer is as follows: ``` add_filter( 'private_title_format', function ( $format ) { return '%s'; } ); ``` It uses the `private_title_format` to change the format of the title to just the post title, without any unnecessary classes or functions.
345,451
<h1>The Problem</h1> <p>I've been grappling with this bug over several days now to no luck. When editing either a post or a page, all icons in the Visual Editor are missing:</p> <p><a href="https://i.stack.imgur.com/nEvqS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nEvqS.jpg" alt="enter image description here"></a></p> <p>As you can see this, includes the icon for the Gutenberg Add Block, which is completely invisible and here highlighted by its alt text. Also notice that the icons in the WP Admin section/toolbar display as normal, indicating the problem is only with the icons of the Visual Editor. </p> <p><a href="https://i.stack.imgur.com/vSk8M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vSk8M.png" alt="enter image description here"></a></p> <h1>What I've Tried</h1> <p>To date, my extensive Googling, tweaking and testing has proved useless. The following is a list of all the solutions I've tried so far, from the standard to the slightly more complex:</p> <ul> <li><p>Clearing browser cache/viewing the page in private browsing mode (<a href="https://www.newtonbaba.com/white-text-and-missing-buttons-in-wordpress-visual-editor" rel="nofollow noreferrer">as suggested here</a>) </p></li> <li><p>Deactivating all plugins (<a href="https://wordpress.org/support/topic/visual-editor-missing-icons-problems-with-html-editing/#post-10183491" rel="nofollow noreferrer">as suggested here</a>)</p></li> <li><p>Checking that the values of <em>Wordpress Address</em> and <em>Site Address</em> in <code>Settings &gt; General</code> match</p></li> <li><p>Going to <code>Settings &gt; Permalinks</code> and clicking Save Changes (<a href="https://really-simple-ssl.com/knowledge-base/my-website-is-in-a-redirect-loop/" rel="nofollow noreferrer">as suggested here</a>)</p></li> <li><p>Adding <code>define( 'WP_MEMORY_LIMIT', '96M' );</code> to wp-config</p></li> <li><p>Adding <code>define( 'WP_MAX_MEMORY_LIMIT', '256M' );</code> to wp-config</p></li> <li><p>Adding <code>define(‘CONCATENATE_SCRIPTS’, false);</code> to wp-config (<a href="https://www.newtonbaba.com/white-text-and-missing-buttons-in-wordpress-visual-editor" rel="nofollow noreferrer">as suggested here</a>)</p></li> <li><p>Adding <code>$_SERVER[“HTTPS”] = “on”;</code> to wp-config (<a href="https://wordpress.org/support/topic/after-adding-ssl-wordpress-content-doesnt-work-properly/#post-9981709" rel="nofollow noreferrer">as suggested here</a>)</p></li> <li><p>Replacing the <code>wp-includes/js/TinyMCE</code> folder entirely with the same folder from a fresh Wordpress download (<a href="https://www.newtonbaba.com/white-text-and-missing-buttons-in-wordpress-visual-editor" rel="nofollow noreferrer">as suggested here</a>)</p></li> <li><p>Replacing the entirety of <code>wp-admin</code> with the same folder from a fresh Wordpress download (<a href="https://wordpress.org/support/topic/visual-editor-missing-icons-problems-with-html-editing/#post-10184173" rel="nofollow noreferrer">as suggested here</a>)</p></li> <li><p>Using <code>wp-cli</code> to do a site-wide search-and-replace of <code>http://www.myexamplesite.com</code> to <code>https://www.myexamplesite.com</code> (<a href="https://wordpress.org/support/topic/some-of-the-icons-are-missing-from-the-dashboard/#post-9566882" rel="nofollow noreferrer">as suggested here</a>) </p></li> <li><p>Disabling both HTTPS Enforce and and External Links Rewrite in using Siteground's cPanel (but <em>not</em> deleting the SSL certificate itself) </p></li> </ul> <p>Not a single one of the above solutions results in the icons being restored again, even when I check the changes using Incognito/Private Browsing to counteract caching.</p> <h1>Possible Cause</h1> <p>I have <em>some</em> suspicion that this issue could have been caused by activating free Let's Encrypt SSL on the server, due to <a href="https://wordpress.org/support/topic/visual-editor-missing-icons-problems-with-html-editing/#post-10195927" rel="nofollow noreferrer">this post</a>, and I also don't recall this issue occurring before I made that change, but I'm unsure as to a) how exactly enabling the free Let's Encrypt SSL would cause such an issue, and b) how it would be fixed.</p> <p>Has anyone else dealt with this before?</p>
[ { "answer_id": 345582, "author": "Pete Moore", "author_id": 173871, "author_profile": "https://wordpress.stackexchange.com/users/173871", "pm_score": 0, "selected": false, "text": "<p>I've just come across this issue myself on a new siteground install.</p>\n\n<p>After some troubleshooting I found disabling all the Frontend Optimization options in the SG Optimizer plugin brought the editor icons back after purging the cache.</p>\n\n<p>Then I enabled them one by one (except Combine CSS Files this has caused issues in the past and wasn't enabled before anyway)</p>\n\n<p>I purged the cache after re-enabling each option checking the icons were still showing on the editor page after a page refresh.</p>\n\n<p>It seems to have done the job.</p>\n\n<p>Pete</p>\n" }, { "answer_id": 345613, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 2, "selected": true, "text": "<p>After a few more days of frustrating testing, I managed to track the issue down to the External Links Rewrite option in Siteground's Site Tools, under SSL options. When HTTP Enforce is enabled with the optional External Links Rewrite option (being able to see these changes virtually immediately in the browser requires a <a href=\"https://refreshyourcache.com/en/cache/\" rel=\"nofollow noreferrer\">Force Refresh</a>, which was what has made testing this stuff so hard) the icons in Visual Editor go missing. When External Links Rewrite is turned off, the icons show up again. </p>\n\n<p>I've contacted Siteground's customer support for a solution, but so far they claim they've been unable to reproduce the issue, despite the fact I've so far managed to reproduce it on both of the two systems I have access to: Firefox and Chrome running on Windows 7, and Firefox running on MacOS High Sierra.</p>\n\n<h3>UPDATE:</h3>\n\n<p>Within 6 hours of filing the ticket, Siteground support finally escalated it to a more senior technical person, who then gave me the following response:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eXUct.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eXUct.png\" alt=\"enter image description here\"></a></p>\n\n<p>This response confirms what I'd suspected: that the \"External Links Rewrite\" option in Siteground's control panel (which they call Site Tools) is broken. They also claim that the team were already aware of the issue, although I'm skeptical of this given that it took a few responses for the initial support to escalate the ticket and the fact that the new React-based (and admittedly very good) Site Tools interface seems to have been <a href=\"https://www.siteground.com/blog/new-client-area-and-site-tools/\" rel=\"nofollow noreferrer\">launched just a few weeks ago</a>.</p>\n\n<p>In any case, Siteground insist a fix is on the way, and that in the meantime the solution is to disable HTTPS enforcement from the Site Tools panel entirely, and instead download its SG Optimiser plugin, enabling <em>HTTPS Enforce</em> and <em>External Links Rewrite</em> from there. I've tested this solution and can confirm that it solves the issue.</p>\n\n<p>I inspected my <code>.htaccess</code> file after enabling these options with SG Optimiser, and it seemed to me that the only thing it was adding was the following Apache directive:</p>\n\n<pre><code># HTTPS forced by SG-Optimizer\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteCond %{HTTPS} off\n RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]\n&lt;/IfModule&gt;\n# END HTTPS \n</code></pre>\n\n<p>As someone who tries his best to run a bare-minimum installation with only the most necessary plugins, writing code for everything else, I wondered if this was the only thing SG Optimiser was doing to force HTTPS, and if I could replace it by simply adding the same directives to .htaccess myself. </p>\n\n<p>However, on further inquiry from Siteground support, this doesn't seem to be the case: </p>\n\n<p><a href=\"https://i.stack.imgur.com/3S0Vu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3S0Vu.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now, the only thing left to do is to wait for Siteground to fix this bug in the new Site Tools interface, after which I'll finally be able to remove the unnecessary SG Optimiser plugin and enforce HTTPS from the control panel itself.</p>\n" } ]
2019/08/19
[ "https://wordpress.stackexchange.com/questions/345451", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167562/" ]
The Problem =========== I've been grappling with this bug over several days now to no luck. When editing either a post or a page, all icons in the Visual Editor are missing: [![enter image description here](https://i.stack.imgur.com/nEvqS.jpg)](https://i.stack.imgur.com/nEvqS.jpg) As you can see this, includes the icon for the Gutenberg Add Block, which is completely invisible and here highlighted by its alt text. Also notice that the icons in the WP Admin section/toolbar display as normal, indicating the problem is only with the icons of the Visual Editor. [![enter image description here](https://i.stack.imgur.com/vSk8M.png)](https://i.stack.imgur.com/vSk8M.png) What I've Tried =============== To date, my extensive Googling, tweaking and testing has proved useless. The following is a list of all the solutions I've tried so far, from the standard to the slightly more complex: * Clearing browser cache/viewing the page in private browsing mode ([as suggested here](https://www.newtonbaba.com/white-text-and-missing-buttons-in-wordpress-visual-editor)) * Deactivating all plugins ([as suggested here](https://wordpress.org/support/topic/visual-editor-missing-icons-problems-with-html-editing/#post-10183491)) * Checking that the values of *Wordpress Address* and *Site Address* in `Settings > General` match * Going to `Settings > Permalinks` and clicking Save Changes ([as suggested here](https://really-simple-ssl.com/knowledge-base/my-website-is-in-a-redirect-loop/)) * Adding `define( 'WP_MEMORY_LIMIT', '96M' );` to wp-config * Adding `define( 'WP_MAX_MEMORY_LIMIT', '256M' );` to wp-config * Adding `define(‘CONCATENATE_SCRIPTS’, false);` to wp-config ([as suggested here](https://www.newtonbaba.com/white-text-and-missing-buttons-in-wordpress-visual-editor)) * Adding `$_SERVER[“HTTPS”] = “on”;` to wp-config ([as suggested here](https://wordpress.org/support/topic/after-adding-ssl-wordpress-content-doesnt-work-properly/#post-9981709)) * Replacing the `wp-includes/js/TinyMCE` folder entirely with the same folder from a fresh Wordpress download ([as suggested here](https://www.newtonbaba.com/white-text-and-missing-buttons-in-wordpress-visual-editor)) * Replacing the entirety of `wp-admin` with the same folder from a fresh Wordpress download ([as suggested here](https://wordpress.org/support/topic/visual-editor-missing-icons-problems-with-html-editing/#post-10184173)) * Using `wp-cli` to do a site-wide search-and-replace of `http://www.myexamplesite.com` to `https://www.myexamplesite.com` ([as suggested here](https://wordpress.org/support/topic/some-of-the-icons-are-missing-from-the-dashboard/#post-9566882)) * Disabling both HTTPS Enforce and and External Links Rewrite in using Siteground's cPanel (but *not* deleting the SSL certificate itself) Not a single one of the above solutions results in the icons being restored again, even when I check the changes using Incognito/Private Browsing to counteract caching. Possible Cause ============== I have *some* suspicion that this issue could have been caused by activating free Let's Encrypt SSL on the server, due to [this post](https://wordpress.org/support/topic/visual-editor-missing-icons-problems-with-html-editing/#post-10195927), and I also don't recall this issue occurring before I made that change, but I'm unsure as to a) how exactly enabling the free Let's Encrypt SSL would cause such an issue, and b) how it would be fixed. Has anyone else dealt with this before?
After a few more days of frustrating testing, I managed to track the issue down to the External Links Rewrite option in Siteground's Site Tools, under SSL options. When HTTP Enforce is enabled with the optional External Links Rewrite option (being able to see these changes virtually immediately in the browser requires a [Force Refresh](https://refreshyourcache.com/en/cache/), which was what has made testing this stuff so hard) the icons in Visual Editor go missing. When External Links Rewrite is turned off, the icons show up again. I've contacted Siteground's customer support for a solution, but so far they claim they've been unable to reproduce the issue, despite the fact I've so far managed to reproduce it on both of the two systems I have access to: Firefox and Chrome running on Windows 7, and Firefox running on MacOS High Sierra. ### UPDATE: Within 6 hours of filing the ticket, Siteground support finally escalated it to a more senior technical person, who then gave me the following response: [![enter image description here](https://i.stack.imgur.com/eXUct.png)](https://i.stack.imgur.com/eXUct.png) This response confirms what I'd suspected: that the "External Links Rewrite" option in Siteground's control panel (which they call Site Tools) is broken. They also claim that the team were already aware of the issue, although I'm skeptical of this given that it took a few responses for the initial support to escalate the ticket and the fact that the new React-based (and admittedly very good) Site Tools interface seems to have been [launched just a few weeks ago](https://www.siteground.com/blog/new-client-area-and-site-tools/). In any case, Siteground insist a fix is on the way, and that in the meantime the solution is to disable HTTPS enforcement from the Site Tools panel entirely, and instead download its SG Optimiser plugin, enabling *HTTPS Enforce* and *External Links Rewrite* from there. I've tested this solution and can confirm that it solves the issue. I inspected my `.htaccess` file after enabling these options with SG Optimiser, and it seemed to me that the only thing it was adding was the following Apache directive: ``` # HTTPS forced by SG-Optimizer <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L] </IfModule> # END HTTPS ``` As someone who tries his best to run a bare-minimum installation with only the most necessary plugins, writing code for everything else, I wondered if this was the only thing SG Optimiser was doing to force HTTPS, and if I could replace it by simply adding the same directives to .htaccess myself. However, on further inquiry from Siteground support, this doesn't seem to be the case: [![enter image description here](https://i.stack.imgur.com/3S0Vu.png)](https://i.stack.imgur.com/3S0Vu.png) Now, the only thing left to do is to wait for Siteground to fix this bug in the new Site Tools interface, after which I'll finally be able to remove the unnecessary SG Optimiser plugin and enforce HTTPS from the control panel itself.
345,476
<p>I'm trying to use a class from another file within a wp_ajax hook And the call returns a 500 status code</p> <p>I added the class with incloud (),</p> <p>I tried to put the whole class inside the function and it worked fine.</p> <p>Is there a way to use a class file within the wp_ajax function?</p> <p>This is the code in the function.php file:</p> <pre><code>add_action( 'init', 'ajax_import_rows_init' ); function ajax_import_rows_init() { wp_register_script( 'ajax_import_rows', get_stylesheet_directory_uri().'/js/ajax_import_rows.js', array('jquery') ); wp_enqueue_script( 'ajax_import_rows' ); $rows_nonce = wp_create_nonce( 'ajax_rows_nonce' ); wp_localize_script( 'ajax_import_rows', 'ajax_import_opject', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ), 'nonce' =&gt; $rows_nonce )); add_action('wp_ajax_import_list_rows', 'response_list_rows'); add_action('wp_ajax_nopriv_import_list_rows', 'response_list_rows'); } function response_list_rows(){ check_ajax_referer( 'ajax_rows_nonce', 'nonce' ); include_once(get_stylesheet_directory_uri() . '/fileds.php'); $post_id = $_POST['post_id']; $list_rows = new fields_ACF($post_id); $list_rows_json = json_encode( $list_rows -&gt; fileds); echo( $list_rows_json); die(); } </code></pre> <p>This is the class in the fields.php file:</p> <pre><code>class fields_ACF{ public $fileds =array(); public function fields_ACF($post_id){ $income = $this -&gt; income($post_id); $expenses = $this -&gt; expenses($post_id); $debts = $this -&gt; debts($post_id); return( $this -&gt; fileds["income"] = $income and $this -&gt; fileds["expenses"] = $expenses and $this -&gt; fileds["debts"] = $debts ); //$this -&gt; fileds = array(); } //פונקציה להכנסות private function income($post_id){ $a =array(); $fileds = array(); if( have_rows('revenue', $post_id) ): while(have_rows('revenue', $post_id) ): the_row(); /*****הוצאת כמות שיש מכל קטגוריה***********/ array_push($a, get_sub_field('id_cat', $post_id)); $count_rows_registered = array_count_values($a); endwhile; endif; if( have_rows('types_income', 'option') ): while(have_rows('types_income', 'option') ): the_row(); $type_no = get_sub_field('type_income_no'); $title = get_sub_field('type_income_name'); if( have_rows('cat_income', 'option') ): while( have_rows('cat_income', 'option') ): the_row(); $cat_income_no = get_sub_field('cat_income_no'); $cat_income_name = get_sub_field('cat_income_name'); if( have_rows('settings_cat') ): while( have_rows('settings_cat') ): the_row(); $day_field = get_sub_field('day_in_months'); $month_field = get_sub_field('months'); endwhile; endif; $fileds[$type_no]['name']=$title; $fileds[$type_no]['content'][$cat_income_no]['name']= $cat_income_name; $fileds[$type_no]['content'][$cat_income_no]['settings']=[ 'day_field' =&gt; $day_field, 'month_field' =&gt; $month_field ]; $fileds[$type_no]['content'][$cat_income_no]['count_rows_registered']=$count_rows_registered[$cat_income_no]; $fileds[$type_no]['content'][$cat_income_no]['rows_registered']=[]; endwhile; endif; endwhile; endif; if( have_rows('revenue', $post_id) ): while(have_rows('revenue', $post_id) ): the_row(); /********הכנסת תוכן השורות במערך הכללי********/ $row =array( 'index_row' =&gt; get_row_index(), 'date_registered' =&gt; get_sub_field('Date_typed'), 'type' =&gt; get_sub_field('type'), 'ID_type' =&gt; get_sub_field('id_type'), 'category_name' =&gt; get_sub_field('category_Revenue'), 'ID_category' =&gt; get_sub_field('id_cat'), 'dete_in_payment' =&gt; get_sub_field('Date_payment'), 'Amount' =&gt; get_sub_field('total'), 'method_payment' =&gt; get_sub_field('method') ); $fileds[$row['ID_type']]['content'][$row['ID_category']]['rows_registered'][]=$row; endwhile; endif; return($fileds); } //פונקציה להוצאות private function expenses($post_id){ $a =array(); $fileds = array(); if( have_rows('expenses', $post_id) ): while(have_rows('expenses', $post_id) ): the_row(); /*****הוצאת כמות שיש מכל קטגוריה***********/ array_push($a, get_sub_field('id_cat', $post_id)); $count_rows_registered = array_count_values($a); endwhile; endif; if( have_rows('types_expenses', 'option') ): while(have_rows('types_expenses', 'option') ): the_row(); $type_no = get_sub_field('type_expenses_no'); $title = get_sub_field('type_expenses_name'); if( have_rows('cat_expenses', 'option') ): while( have_rows('cat_expenses', 'option') ): the_row(); $cat_income_no = get_sub_field('cat_expenses_no'); $cat_income_name = get_sub_field('cat_expenses_name'); if( have_rows('settings_cat') ): while( have_rows('settings_cat') ): the_row(); $day_field = get_sub_field('day_in_months'); $month_field = get_sub_field('months'); endwhile; endif; $fileds[$type_no]['name']=$title; $fileds[$type_no]['content'][$cat_income_no]['name']= $cat_income_name; $fileds[$type_no]['content'][$cat_income_no]['settings']=[ 'day_field' =&gt; $day_field, 'month_field' =&gt; $month_field ]; $fileds[$type_no]['content'][$cat_income_no]['count_rows_registered']=$count_rows_registered[$cat_income_no]; $fileds[$type_no]['content'][$cat_income_no]['rows_registered']=[]; endwhile; endif; endwhile; endif; if( have_rows('expenses', $post_id) ): while(have_rows('expenses', $post_id) ): the_row(); /********הכנסת תוכן השורות במערך הכללי********/ $row =array( 'index_row' =&gt; get_row_index(), 'date_registered' =&gt; get_sub_field('Date_typed'), 'type' =&gt; get_sub_field('type'), 'ID_type' =&gt; get_sub_field('id_type'), 'category_name' =&gt; get_sub_field('category_expenses'), 'ID_category' =&gt; get_sub_field('id_cat'), 'dete_in_payment' =&gt; get_sub_field('Date_payment'), 'Amount' =&gt; get_sub_field('total'), 'method_payment' =&gt; get_sub_field('method') ); $fileds[$row['ID_type']]['content'][$row['ID_category']]['rows_registered'][]=$row; endwhile; endif; return $fileds; } //פונקציה לחובות private function debts($post_id){ $a =array(); $fileds = array(); if( have_rows('debts', $post_id) ): while(have_rows('debts', $post_id) ): the_row(); /*****הוצאת כמות שיש מכל קטגוריה***********/ array_push($a, get_sub_field('id_cat', $post_id)); $count_rows_registered = array_count_values($a); endwhile; endif; if( have_rows('types_income', 'option') ): while(have_rows('types_income', 'option') ): the_row(); $type_no = get_sub_field('type_income_no'); $title = get_sub_field('type_income_name'); if( have_rows('cat_income', 'option') ): while( have_rows('cat_income', 'option') ): the_row(); $cat_income_no = get_sub_field('cat_income_no'); $cat_income_name = get_sub_field('cat_income_name'); if( have_rows('settings_cat') ): while( have_rows('settings_cat') ): the_row(); $day_field = get_sub_field('day_in_months'); $month_field = get_sub_field('months'); endwhile; endif; $fileds[$type_no]['name']=$title; $fileds[$type_no]['content'][$cat_income_no]['name']= $cat_income_name; $fileds[$type_no]['content'][$cat_income_no]['settings']=[ 'day_field' =&gt; $day_field, 'month_field' =&gt; $month_field ]; $fileds[$type_no]['content'][$cat_income_no]['count_rows_registered']=$count_rows_registered[$cat_income_no]; $fileds[$type_no]['content'][$cat_income_no]['rows_registered']=[]; endwhile; endif; endwhile; endif; if( have_rows('debts', $post_id) ): while(have_rows('debts', $post_id) ): the_row(); /********הכנסת תוכן השורות במערך הכללי********/ $row =array( 'index_row' =&gt; get_row_index(), 'date_registered' =&gt; get_sub_field('Date_typed'), 'type' =&gt; get_sub_field('type'), 'ID_type' =&gt; get_sub_field('id_type'), 'category_name' =&gt; get_sub_field('category_debts'), 'ID_category' =&gt; get_sub_field('id_cat'), 'dete_in_payment' =&gt; get_sub_field('total_debt'), 'Amount' =&gt; get_sub_field('total'), 'method_payment' =&gt; get_sub_field('method') ); $fileds[$row['ID_type']]['content'][$row['ID_category']]['rows_registered'][]=$row; endwhile; endif; return $fileds; } } </code></pre> <p>Again I note that when I put the class code inside the function directly - it works</p>
[ { "answer_id": 345582, "author": "Pete Moore", "author_id": 173871, "author_profile": "https://wordpress.stackexchange.com/users/173871", "pm_score": 0, "selected": false, "text": "<p>I've just come across this issue myself on a new siteground install.</p>\n\n<p>After some troubleshooting I found disabling all the Frontend Optimization options in the SG Optimizer plugin brought the editor icons back after purging the cache.</p>\n\n<p>Then I enabled them one by one (except Combine CSS Files this has caused issues in the past and wasn't enabled before anyway)</p>\n\n<p>I purged the cache after re-enabling each option checking the icons were still showing on the editor page after a page refresh.</p>\n\n<p>It seems to have done the job.</p>\n\n<p>Pete</p>\n" }, { "answer_id": 345613, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 2, "selected": true, "text": "<p>After a few more days of frustrating testing, I managed to track the issue down to the External Links Rewrite option in Siteground's Site Tools, under SSL options. When HTTP Enforce is enabled with the optional External Links Rewrite option (being able to see these changes virtually immediately in the browser requires a <a href=\"https://refreshyourcache.com/en/cache/\" rel=\"nofollow noreferrer\">Force Refresh</a>, which was what has made testing this stuff so hard) the icons in Visual Editor go missing. When External Links Rewrite is turned off, the icons show up again. </p>\n\n<p>I've contacted Siteground's customer support for a solution, but so far they claim they've been unable to reproduce the issue, despite the fact I've so far managed to reproduce it on both of the two systems I have access to: Firefox and Chrome running on Windows 7, and Firefox running on MacOS High Sierra.</p>\n\n<h3>UPDATE:</h3>\n\n<p>Within 6 hours of filing the ticket, Siteground support finally escalated it to a more senior technical person, who then gave me the following response:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eXUct.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eXUct.png\" alt=\"enter image description here\"></a></p>\n\n<p>This response confirms what I'd suspected: that the \"External Links Rewrite\" option in Siteground's control panel (which they call Site Tools) is broken. They also claim that the team were already aware of the issue, although I'm skeptical of this given that it took a few responses for the initial support to escalate the ticket and the fact that the new React-based (and admittedly very good) Site Tools interface seems to have been <a href=\"https://www.siteground.com/blog/new-client-area-and-site-tools/\" rel=\"nofollow noreferrer\">launched just a few weeks ago</a>.</p>\n\n<p>In any case, Siteground insist a fix is on the way, and that in the meantime the solution is to disable HTTPS enforcement from the Site Tools panel entirely, and instead download its SG Optimiser plugin, enabling <em>HTTPS Enforce</em> and <em>External Links Rewrite</em> from there. I've tested this solution and can confirm that it solves the issue.</p>\n\n<p>I inspected my <code>.htaccess</code> file after enabling these options with SG Optimiser, and it seemed to me that the only thing it was adding was the following Apache directive:</p>\n\n<pre><code># HTTPS forced by SG-Optimizer\n&lt;IfModule mod_rewrite.c&gt;\n RewriteEngine On\n RewriteCond %{HTTPS} off\n RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]\n&lt;/IfModule&gt;\n# END HTTPS \n</code></pre>\n\n<p>As someone who tries his best to run a bare-minimum installation with only the most necessary plugins, writing code for everything else, I wondered if this was the only thing SG Optimiser was doing to force HTTPS, and if I could replace it by simply adding the same directives to .htaccess myself. </p>\n\n<p>However, on further inquiry from Siteground support, this doesn't seem to be the case: </p>\n\n<p><a href=\"https://i.stack.imgur.com/3S0Vu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3S0Vu.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now, the only thing left to do is to wait for Siteground to fix this bug in the new Site Tools interface, after which I'll finally be able to remove the unnecessary SG Optimiser plugin and enforce HTTPS from the control panel itself.</p>\n" } ]
2019/08/20
[ "https://wordpress.stackexchange.com/questions/345476", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173797/" ]
I'm trying to use a class from another file within a wp\_ajax hook And the call returns a 500 status code I added the class with incloud (), I tried to put the whole class inside the function and it worked fine. Is there a way to use a class file within the wp\_ajax function? This is the code in the function.php file: ``` add_action( 'init', 'ajax_import_rows_init' ); function ajax_import_rows_init() { wp_register_script( 'ajax_import_rows', get_stylesheet_directory_uri().'/js/ajax_import_rows.js', array('jquery') ); wp_enqueue_script( 'ajax_import_rows' ); $rows_nonce = wp_create_nonce( 'ajax_rows_nonce' ); wp_localize_script( 'ajax_import_rows', 'ajax_import_opject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => $rows_nonce )); add_action('wp_ajax_import_list_rows', 'response_list_rows'); add_action('wp_ajax_nopriv_import_list_rows', 'response_list_rows'); } function response_list_rows(){ check_ajax_referer( 'ajax_rows_nonce', 'nonce' ); include_once(get_stylesheet_directory_uri() . '/fileds.php'); $post_id = $_POST['post_id']; $list_rows = new fields_ACF($post_id); $list_rows_json = json_encode( $list_rows -> fileds); echo( $list_rows_json); die(); } ``` This is the class in the fields.php file: ``` class fields_ACF{ public $fileds =array(); public function fields_ACF($post_id){ $income = $this -> income($post_id); $expenses = $this -> expenses($post_id); $debts = $this -> debts($post_id); return( $this -> fileds["income"] = $income and $this -> fileds["expenses"] = $expenses and $this -> fileds["debts"] = $debts ); //$this -> fileds = array(); } //פונקציה להכנסות private function income($post_id){ $a =array(); $fileds = array(); if( have_rows('revenue', $post_id) ): while(have_rows('revenue', $post_id) ): the_row(); /*****הוצאת כמות שיש מכל קטגוריה***********/ array_push($a, get_sub_field('id_cat', $post_id)); $count_rows_registered = array_count_values($a); endwhile; endif; if( have_rows('types_income', 'option') ): while(have_rows('types_income', 'option') ): the_row(); $type_no = get_sub_field('type_income_no'); $title = get_sub_field('type_income_name'); if( have_rows('cat_income', 'option') ): while( have_rows('cat_income', 'option') ): the_row(); $cat_income_no = get_sub_field('cat_income_no'); $cat_income_name = get_sub_field('cat_income_name'); if( have_rows('settings_cat') ): while( have_rows('settings_cat') ): the_row(); $day_field = get_sub_field('day_in_months'); $month_field = get_sub_field('months'); endwhile; endif; $fileds[$type_no]['name']=$title; $fileds[$type_no]['content'][$cat_income_no]['name']= $cat_income_name; $fileds[$type_no]['content'][$cat_income_no]['settings']=[ 'day_field' => $day_field, 'month_field' => $month_field ]; $fileds[$type_no]['content'][$cat_income_no]['count_rows_registered']=$count_rows_registered[$cat_income_no]; $fileds[$type_no]['content'][$cat_income_no]['rows_registered']=[]; endwhile; endif; endwhile; endif; if( have_rows('revenue', $post_id) ): while(have_rows('revenue', $post_id) ): the_row(); /********הכנסת תוכן השורות במערך הכללי********/ $row =array( 'index_row' => get_row_index(), 'date_registered' => get_sub_field('Date_typed'), 'type' => get_sub_field('type'), 'ID_type' => get_sub_field('id_type'), 'category_name' => get_sub_field('category_Revenue'), 'ID_category' => get_sub_field('id_cat'), 'dete_in_payment' => get_sub_field('Date_payment'), 'Amount' => get_sub_field('total'), 'method_payment' => get_sub_field('method') ); $fileds[$row['ID_type']]['content'][$row['ID_category']]['rows_registered'][]=$row; endwhile; endif; return($fileds); } //פונקציה להוצאות private function expenses($post_id){ $a =array(); $fileds = array(); if( have_rows('expenses', $post_id) ): while(have_rows('expenses', $post_id) ): the_row(); /*****הוצאת כמות שיש מכל קטגוריה***********/ array_push($a, get_sub_field('id_cat', $post_id)); $count_rows_registered = array_count_values($a); endwhile; endif; if( have_rows('types_expenses', 'option') ): while(have_rows('types_expenses', 'option') ): the_row(); $type_no = get_sub_field('type_expenses_no'); $title = get_sub_field('type_expenses_name'); if( have_rows('cat_expenses', 'option') ): while( have_rows('cat_expenses', 'option') ): the_row(); $cat_income_no = get_sub_field('cat_expenses_no'); $cat_income_name = get_sub_field('cat_expenses_name'); if( have_rows('settings_cat') ): while( have_rows('settings_cat') ): the_row(); $day_field = get_sub_field('day_in_months'); $month_field = get_sub_field('months'); endwhile; endif; $fileds[$type_no]['name']=$title; $fileds[$type_no]['content'][$cat_income_no]['name']= $cat_income_name; $fileds[$type_no]['content'][$cat_income_no]['settings']=[ 'day_field' => $day_field, 'month_field' => $month_field ]; $fileds[$type_no]['content'][$cat_income_no]['count_rows_registered']=$count_rows_registered[$cat_income_no]; $fileds[$type_no]['content'][$cat_income_no]['rows_registered']=[]; endwhile; endif; endwhile; endif; if( have_rows('expenses', $post_id) ): while(have_rows('expenses', $post_id) ): the_row(); /********הכנסת תוכן השורות במערך הכללי********/ $row =array( 'index_row' => get_row_index(), 'date_registered' => get_sub_field('Date_typed'), 'type' => get_sub_field('type'), 'ID_type' => get_sub_field('id_type'), 'category_name' => get_sub_field('category_expenses'), 'ID_category' => get_sub_field('id_cat'), 'dete_in_payment' => get_sub_field('Date_payment'), 'Amount' => get_sub_field('total'), 'method_payment' => get_sub_field('method') ); $fileds[$row['ID_type']]['content'][$row['ID_category']]['rows_registered'][]=$row; endwhile; endif; return $fileds; } //פונקציה לחובות private function debts($post_id){ $a =array(); $fileds = array(); if( have_rows('debts', $post_id) ): while(have_rows('debts', $post_id) ): the_row(); /*****הוצאת כמות שיש מכל קטגוריה***********/ array_push($a, get_sub_field('id_cat', $post_id)); $count_rows_registered = array_count_values($a); endwhile; endif; if( have_rows('types_income', 'option') ): while(have_rows('types_income', 'option') ): the_row(); $type_no = get_sub_field('type_income_no'); $title = get_sub_field('type_income_name'); if( have_rows('cat_income', 'option') ): while( have_rows('cat_income', 'option') ): the_row(); $cat_income_no = get_sub_field('cat_income_no'); $cat_income_name = get_sub_field('cat_income_name'); if( have_rows('settings_cat') ): while( have_rows('settings_cat') ): the_row(); $day_field = get_sub_field('day_in_months'); $month_field = get_sub_field('months'); endwhile; endif; $fileds[$type_no]['name']=$title; $fileds[$type_no]['content'][$cat_income_no]['name']= $cat_income_name; $fileds[$type_no]['content'][$cat_income_no]['settings']=[ 'day_field' => $day_field, 'month_field' => $month_field ]; $fileds[$type_no]['content'][$cat_income_no]['count_rows_registered']=$count_rows_registered[$cat_income_no]; $fileds[$type_no]['content'][$cat_income_no]['rows_registered']=[]; endwhile; endif; endwhile; endif; if( have_rows('debts', $post_id) ): while(have_rows('debts', $post_id) ): the_row(); /********הכנסת תוכן השורות במערך הכללי********/ $row =array( 'index_row' => get_row_index(), 'date_registered' => get_sub_field('Date_typed'), 'type' => get_sub_field('type'), 'ID_type' => get_sub_field('id_type'), 'category_name' => get_sub_field('category_debts'), 'ID_category' => get_sub_field('id_cat'), 'dete_in_payment' => get_sub_field('total_debt'), 'Amount' => get_sub_field('total'), 'method_payment' => get_sub_field('method') ); $fileds[$row['ID_type']]['content'][$row['ID_category']]['rows_registered'][]=$row; endwhile; endif; return $fileds; } } ``` Again I note that when I put the class code inside the function directly - it works
After a few more days of frustrating testing, I managed to track the issue down to the External Links Rewrite option in Siteground's Site Tools, under SSL options. When HTTP Enforce is enabled with the optional External Links Rewrite option (being able to see these changes virtually immediately in the browser requires a [Force Refresh](https://refreshyourcache.com/en/cache/), which was what has made testing this stuff so hard) the icons in Visual Editor go missing. When External Links Rewrite is turned off, the icons show up again. I've contacted Siteground's customer support for a solution, but so far they claim they've been unable to reproduce the issue, despite the fact I've so far managed to reproduce it on both of the two systems I have access to: Firefox and Chrome running on Windows 7, and Firefox running on MacOS High Sierra. ### UPDATE: Within 6 hours of filing the ticket, Siteground support finally escalated it to a more senior technical person, who then gave me the following response: [![enter image description here](https://i.stack.imgur.com/eXUct.png)](https://i.stack.imgur.com/eXUct.png) This response confirms what I'd suspected: that the "External Links Rewrite" option in Siteground's control panel (which they call Site Tools) is broken. They also claim that the team were already aware of the issue, although I'm skeptical of this given that it took a few responses for the initial support to escalate the ticket and the fact that the new React-based (and admittedly very good) Site Tools interface seems to have been [launched just a few weeks ago](https://www.siteground.com/blog/new-client-area-and-site-tools/). In any case, Siteground insist a fix is on the way, and that in the meantime the solution is to disable HTTPS enforcement from the Site Tools panel entirely, and instead download its SG Optimiser plugin, enabling *HTTPS Enforce* and *External Links Rewrite* from there. I've tested this solution and can confirm that it solves the issue. I inspected my `.htaccess` file after enabling these options with SG Optimiser, and it seemed to me that the only thing it was adding was the following Apache directive: ``` # HTTPS forced by SG-Optimizer <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L] </IfModule> # END HTTPS ``` As someone who tries his best to run a bare-minimum installation with only the most necessary plugins, writing code for everything else, I wondered if this was the only thing SG Optimiser was doing to force HTTPS, and if I could replace it by simply adding the same directives to .htaccess myself. However, on further inquiry from Siteground support, this doesn't seem to be the case: [![enter image description here](https://i.stack.imgur.com/3S0Vu.png)](https://i.stack.imgur.com/3S0Vu.png) Now, the only thing left to do is to wait for Siteground to fix this bug in the new Site Tools interface, after which I'll finally be able to remove the unnecessary SG Optimiser plugin and enforce HTTPS from the control panel itself.
345,485
<p>I have a custom post type with custom fields(advanced custom fields plugin). one of the custom fields named program_id. i can`t understand how to get all of the posts in that CPT where the ACF field value is x, and only them. i read ACF guide but i always get all of the post.</p> <pre><code>$student_query_args = [ 'post_type' =&gt; 'student_list', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 100, 'order' =&gt; 'DESC', 'meta_query' =&gt; [ 'key' =&gt; 'program_id', 'value' =&gt; 5317, ], ]; $student_query = new WP_Query($student_query_args); if ($student_query-&gt;have_posts()) { while ($student_query-&gt;have_posts()) { $student_query-&gt;the_post(); echo '&lt;br&gt;' . the_title() . '&lt;hr/&gt;'; } } </code></pre>
[ { "answer_id": 345520, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>Meta Queries are nested arrays. See the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters\" rel=\"nofollow noreferrer\">WP_Query section on meta queries</a>.</p>\n\n<h1>Option 1</h1>\n\n<p>Use <code>meta_key</code> and <code>meta_value</code> directly in the query arguments, not as a meta query.</p>\n\n<pre><code>$student_query_args = [\n 'post_type' =&gt; 'student_list',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 100,\n 'order' =&gt; 'DESC',\n 'meta_key' =&gt; 'program_id',\n 'meta_value' =&gt; 5317,\n];\n</code></pre>\n\n<h1>Option 2</h1>\n\n<p>The meta query approach. If you're adding multiple you would need multiple arrays. The default relation is <code>AND</code> but we'll supply it for clarity:</p>\n\n<pre><code>$student_query_args = [\n 'post_type' =&gt; 'student_list',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 100,\n 'order' =&gt; 'DESC',\n 'meta_query' =&gt; [\n 'relation' =&gt; 'AND',\n [\n 'key' =&gt; 'program_id',\n 'value' =&gt; 5317,\n ],\n ],\n];\n</code></pre>\n" }, { "answer_id": 345556, "author": "Doron Davidowitz", "author_id": 173802, "author_profile": "https://wordpress.stackexchange.com/users/173802", "pm_score": 0, "selected": false, "text": "<p>as Howdy_McGee notice. \nthe meta_query needs to be a nested array and to add 'LIKE' as comparison.\nthe correct answer is</p>\n\n<pre><code>$student_query_args = [\n 'post_type' =&gt; 'student_list',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 100,\n 'order' =&gt; 'DESC',\n 'meta_query' =&gt; [\n 'key' =&gt; 'program_id',\n 'value' =&gt; 5317,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'LIKE'\n ],\n\n];\n\n$student_query = new WP_Query($student_query_args);\n\nif ($student_query-&gt;have_posts()) {\n while ($student_query-&gt;have_posts()) {\n $student_query-&gt;the_post();\n echo '&lt;br&gt;' . the_title() . '&lt;hr/&gt;';\n }\n}\n\n</code></pre>\n" } ]
2019/08/20
[ "https://wordpress.stackexchange.com/questions/345485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173802/" ]
I have a custom post type with custom fields(advanced custom fields plugin). one of the custom fields named program\_id. i can`t understand how to get all of the posts in that CPT where the ACF field value is x, and only them. i read ACF guide but i always get all of the post. ``` $student_query_args = [ 'post_type' => 'student_list', 'post_status' => 'publish', 'posts_per_page' => 100, 'order' => 'DESC', 'meta_query' => [ 'key' => 'program_id', 'value' => 5317, ], ]; $student_query = new WP_Query($student_query_args); if ($student_query->have_posts()) { while ($student_query->have_posts()) { $student_query->the_post(); echo '<br>' . the_title() . '<hr/>'; } } ```
Meta Queries are nested arrays. See the [WP\_Query section on meta queries](https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters). Option 1 ======== Use `meta_key` and `meta_value` directly in the query arguments, not as a meta query. ``` $student_query_args = [ 'post_type' => 'student_list', 'post_status' => 'publish', 'posts_per_page' => 100, 'order' => 'DESC', 'meta_key' => 'program_id', 'meta_value' => 5317, ]; ``` Option 2 ======== The meta query approach. If you're adding multiple you would need multiple arrays. The default relation is `AND` but we'll supply it for clarity: ``` $student_query_args = [ 'post_type' => 'student_list', 'post_status' => 'publish', 'posts_per_page' => 100, 'order' => 'DESC', 'meta_query' => [ 'relation' => 'AND', [ 'key' => 'program_id', 'value' => 5317, ], ], ]; ```
345,514
<p>I'm creating a plugin to display schema script for my WooCommerce product. I use a custom field to add my gtin number in WooCommerce.</p> <p>This is what I did:<br></p> <pre><code>&lt;?php $gtin = get_post_meta(post_ID,'gtin',true); ?&gt; &lt;script type="application/ld+json"&gt;{ "gtin13:"&lt;?php echo $gtin;?&gt;"&lt;/script&gt;} </code></pre> <p>The result:</p> <pre><code>"gtin13:"1112223334" </code></pre> <p>Which work fine…</p> <p>But sometime products doesn't have <code>gtin</code> number, so I created function like this:</p> <ol> <li>go check if there is gtin number or not?</li> <li>If don't echo "identifier_exit:false"</li> <li>If found gtin number echo "gtin13:gtin number" <br></li> </ol> <pre><code> &lt;?php function check_gtin() { $gtin=get_post_meta(post_ID,'gtin',true); if ($gtin!='') { echo '$gtin13:$gtin'; } else { echo 'identifier_exits:false'; } } ?&gt; &lt;script type="application/json+ld"&gt;{ "&lt;?php check_gtin();?&gt;"&lt;/script&gt;} </code></pre> <p>The result:</p> <pre><code>"gtin13:$gtin" </code></pre> <p>What I am expecting:</p> <pre><code>"gtin13:1112223334" </code></pre> <p>So can someone point to me what I did wrong?</p>
[ { "answer_id": 345515, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 1, "selected": false, "text": "<p>There are some errors as <code>get_post_meta()</code> first argument need to be a defined product ID here (and in your code <code>post_ID</code> is not even dynamic variable and will not give anything)… </p>\n\n<p>Try the following:</p>\n\n<pre><code>&lt;?php\n function check_gtin(){\n if ( $gtin = get_post_meta(get_the_id(), 'gtin', true) ){\n echo \"gtin13:\". $gtin;\n } else {\n echo 'identifier_exits:false';\n }\n }\n ?&gt;\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>&lt;script type=\"application/json+ld\"&gt;{\"&lt;?php check_gtin(); ?&gt;\"&lt;/script&gt;\n</code></pre>\n\n<p>It should better work…</p>\n" }, { "answer_id": 345516, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>One problem is that you need to pass the $post_id to the function so it has something to work with.</p>\n\n<pre><code>global $post;\n\ncheck_gtin( $post-&gt;ID );\n\nfunction check_gtin( $post_id ) { /* ... */ }\n</code></pre>\n\n<hr>\n\n<p>Another problem is that in PHP single quotes are meant to be <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single\" rel=\"nofollow noreferrer\">literal strings</a> and will not print the variables in them. There's a couple ways to convert this into working code:</p>\n\n<h1><a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double\" rel=\"nofollow noreferrer\">Double Quotes</a></h1>\n\n<pre><code>echo \"gtin13:{$gtin}\";\n</code></pre>\n\n<h1><a href=\"https://www.php.net/manual/en/language.operators.string.php\" rel=\"nofollow noreferrer\">String Concatenation</a></h1>\n\n<pre><code>echo 'gtin13:' . $gtin;\n</code></pre>\n\n<h1><a href=\"https://www.php.net/manual/en/function.printf.php\" rel=\"nofollow noreferrer\">Formatted Printing</a></h1>\n\n<pre><code>printf( 'gtin13:%s', $gtin );\n</code></pre>\n\n<hr>\n\n<p>Additionally, depending on how you're setting the post meta it could return something \"empty\" but not necessary an empty string <code>''</code>. Personally, I prefer to use <a href=\"https://www.php.net/manual/en/function.empty.php\" rel=\"nofollow noreferrer\"><code>empty()</code></a> to check if something exists. This will check for empty arrays, empty strings, 0, false.</p>\n\n<hr>\n\n<p>To bring it altogether, it could look like:</p>\n\n<pre><code>/**\n * Display GTIN\n *\n * @param Integer $post_id\n *\n * @return void\n */\nfunction check_gtin( $post_id ) {\n\n $gtin = get_post_meta( $post_id, 'gtin', true );\n\n if( ! empty( $gtin ) ) {\n echo \"gtin13:{$gtin}\";\n } else {\n echo 'identifier_exits:false';\n }\n\n}\n</code></pre>\n" } ]
2019/08/20
[ "https://wordpress.stackexchange.com/questions/345514", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171340/" ]
I'm creating a plugin to display schema script for my WooCommerce product. I use a custom field to add my gtin number in WooCommerce. This is what I did: ``` <?php $gtin = get_post_meta(post_ID,'gtin',true); ?> <script type="application/ld+json">{ "gtin13:"<?php echo $gtin;?>"</script>} ``` The result: ``` "gtin13:"1112223334" ``` Which work fine… But sometime products doesn't have `gtin` number, so I created function like this: 1. go check if there is gtin number or not? 2. If don't echo "identifier\_exit:false" 3. If found gtin number echo "gtin13:gtin number" ``` <?php function check_gtin() { $gtin=get_post_meta(post_ID,'gtin',true); if ($gtin!='') { echo '$gtin13:$gtin'; } else { echo 'identifier_exits:false'; } } ?> <script type="application/json+ld">{ "<?php check_gtin();?>"</script>} ``` The result: ``` "gtin13:$gtin" ``` What I am expecting: ``` "gtin13:1112223334" ``` So can someone point to me what I did wrong?
There are some errors as `get_post_meta()` first argument need to be a defined product ID here (and in your code `post_ID` is not even dynamic variable and will not give anything)… Try the following: ``` <?php function check_gtin(){ if ( $gtin = get_post_meta(get_the_id(), 'gtin', true) ){ echo "gtin13:". $gtin; } else { echo 'identifier_exits:false'; } } ?> ``` Then: ``` <script type="application/json+ld">{"<?php check_gtin(); ?>"</script> ``` It should better work…
345,533
<p>At <a href="https://core.trac.wordpress.org/changeset/37920" rel="nofollow noreferrer">https://core.trac.wordpress.org/changeset/37920</a> it defines the <code>wp_resource_hints()</code> function that was added with WordPress 4.6.</p> <p>On that page it shows a section of the general-template.php file where the <code>wp_resource_hints()</code> function is defined, and there's also a function called <code>wp_resource_hints_scripts_styles()</code> which "Adds dns-prefetch for all scripts and styles enqueued from external hosts."</p> <p>I would like to replace "dns-prefetch" with "preconnect" for all external enqueued scripts and styles. In other words, I would like the <code>wp_resource_hints_scripts_styles()</code> function to use "preconnect" somehow.</p> <p>Is there a way I can modify the <code>wp_resource_hints()</code> function to achieve this?</p> <p>I'm looking at the following part of the function, where "dns-prefetch" points to <code>wp_resource_hints_scripts_styles()</code>, and I'm wondering if that can be changed to use "preconnect" instead:</p> <pre><code>$hints = array( 'dns-prefetch' =&gt; wp_resource_hints_scripts_styles(), 'preconnect' =&gt; array( 's.w.org' ), 'prefetch' =&gt; array(), 'prerender' =&gt; array(), ); </code></pre> <p>Apologies if I haven't worded this question in the clearest way!</p>
[ { "answer_id": 345515, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 1, "selected": false, "text": "<p>There are some errors as <code>get_post_meta()</code> first argument need to be a defined product ID here (and in your code <code>post_ID</code> is not even dynamic variable and will not give anything)… </p>\n\n<p>Try the following:</p>\n\n<pre><code>&lt;?php\n function check_gtin(){\n if ( $gtin = get_post_meta(get_the_id(), 'gtin', true) ){\n echo \"gtin13:\". $gtin;\n } else {\n echo 'identifier_exits:false';\n }\n }\n ?&gt;\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>&lt;script type=\"application/json+ld\"&gt;{\"&lt;?php check_gtin(); ?&gt;\"&lt;/script&gt;\n</code></pre>\n\n<p>It should better work…</p>\n" }, { "answer_id": 345516, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>One problem is that you need to pass the $post_id to the function so it has something to work with.</p>\n\n<pre><code>global $post;\n\ncheck_gtin( $post-&gt;ID );\n\nfunction check_gtin( $post_id ) { /* ... */ }\n</code></pre>\n\n<hr>\n\n<p>Another problem is that in PHP single quotes are meant to be <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single\" rel=\"nofollow noreferrer\">literal strings</a> and will not print the variables in them. There's a couple ways to convert this into working code:</p>\n\n<h1><a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double\" rel=\"nofollow noreferrer\">Double Quotes</a></h1>\n\n<pre><code>echo \"gtin13:{$gtin}\";\n</code></pre>\n\n<h1><a href=\"https://www.php.net/manual/en/language.operators.string.php\" rel=\"nofollow noreferrer\">String Concatenation</a></h1>\n\n<pre><code>echo 'gtin13:' . $gtin;\n</code></pre>\n\n<h1><a href=\"https://www.php.net/manual/en/function.printf.php\" rel=\"nofollow noreferrer\">Formatted Printing</a></h1>\n\n<pre><code>printf( 'gtin13:%s', $gtin );\n</code></pre>\n\n<hr>\n\n<p>Additionally, depending on how you're setting the post meta it could return something \"empty\" but not necessary an empty string <code>''</code>. Personally, I prefer to use <a href=\"https://www.php.net/manual/en/function.empty.php\" rel=\"nofollow noreferrer\"><code>empty()</code></a> to check if something exists. This will check for empty arrays, empty strings, 0, false.</p>\n\n<hr>\n\n<p>To bring it altogether, it could look like:</p>\n\n<pre><code>/**\n * Display GTIN\n *\n * @param Integer $post_id\n *\n * @return void\n */\nfunction check_gtin( $post_id ) {\n\n $gtin = get_post_meta( $post_id, 'gtin', true );\n\n if( ! empty( $gtin ) ) {\n echo \"gtin13:{$gtin}\";\n } else {\n echo 'identifier_exits:false';\n }\n\n}\n</code></pre>\n" } ]
2019/08/20
[ "https://wordpress.stackexchange.com/questions/345533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58939/" ]
At <https://core.trac.wordpress.org/changeset/37920> it defines the `wp_resource_hints()` function that was added with WordPress 4.6. On that page it shows a section of the general-template.php file where the `wp_resource_hints()` function is defined, and there's also a function called `wp_resource_hints_scripts_styles()` which "Adds dns-prefetch for all scripts and styles enqueued from external hosts." I would like to replace "dns-prefetch" with "preconnect" for all external enqueued scripts and styles. In other words, I would like the `wp_resource_hints_scripts_styles()` function to use "preconnect" somehow. Is there a way I can modify the `wp_resource_hints()` function to achieve this? I'm looking at the following part of the function, where "dns-prefetch" points to `wp_resource_hints_scripts_styles()`, and I'm wondering if that can be changed to use "preconnect" instead: ``` $hints = array( 'dns-prefetch' => wp_resource_hints_scripts_styles(), 'preconnect' => array( 's.w.org' ), 'prefetch' => array(), 'prerender' => array(), ); ``` Apologies if I haven't worded this question in the clearest way!
There are some errors as `get_post_meta()` first argument need to be a defined product ID here (and in your code `post_ID` is not even dynamic variable and will not give anything)… Try the following: ``` <?php function check_gtin(){ if ( $gtin = get_post_meta(get_the_id(), 'gtin', true) ){ echo "gtin13:". $gtin; } else { echo 'identifier_exits:false'; } } ?> ``` Then: ``` <script type="application/json+ld">{"<?php check_gtin(); ?>"</script> ``` It should better work…
345,541
<p>I've followed the documentation from <a href="https://codex.wordpress.org/Function_Reference/get_query_var" rel="nofollow noreferrer">WordPress</a>, but my <code>functions.php</code> file still is not getting the <code>token</code> (<code>abcd</code>) variable from the URL: <code>https://example.com/reset-password/?token=abcd</code></p> <p>My functions.php file includes the following:</p> <pre><code>function add_query_vars_filter( $vars ) { $vars[] = "token"; return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' ); ... add_filter( 'wpcf7_validate_text*', 'custom_password_reset_validation_filter', 10, 2 ); function custom_password_reset_validation_filter( $result, $tag ) { // Make POST request to change password $token = get_query_var( 'token', "fk" ); write_log("TKN: {$token}"); } return $result; } </code></pre> <p>For some reason, <code>get__query_var</code> always returns <code>fk</code> instead of <code>abcd</code>. </p>
[ { "answer_id": 345553, "author": "Pratikb.Simform", "author_id": 173473, "author_profile": "https://wordpress.stackexchange.com/users/173473", "pm_score": -1, "selected": false, "text": "<p>You can try </p>\n\n<pre><code>$token = $_REQUEST['token']\n</code></pre>\n" }, { "answer_id": 345710, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 0, "selected": false, "text": "<p>Contact Form 7 provides a recipe for <a href=\"https://contactform7.com/2015/03/28/custom-validation/\" rel=\"nofollow noreferrer\"><strong>Validation as a Filter</strong></a> which looks very much like what you are trying to do.</p>\n\n<p>Adapting their example to your code, I believe the following should work for you:</p>\n\n<pre><code>add_filter( 'wpcf7_validate_text*', 'custom_password_reset_validation_filter', 10, 2 );\nfunction custom_password_reset_validation_filter( $result, $tag ) { \n if ('token'==$tag-&gt;name){\n $token = isset($_POST['token']) ? $_POST['token'] : \"fk\";\n write_log(\"TKN: {$token}\");\n }\n\n return $result;\n}\n</code></pre>\n" } ]
2019/08/21
[ "https://wordpress.stackexchange.com/questions/345541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173717/" ]
I've followed the documentation from [WordPress](https://codex.wordpress.org/Function_Reference/get_query_var), but my `functions.php` file still is not getting the `token` (`abcd`) variable from the URL: `https://example.com/reset-password/?token=abcd` My functions.php file includes the following: ``` function add_query_vars_filter( $vars ) { $vars[] = "token"; return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' ); ... add_filter( 'wpcf7_validate_text*', 'custom_password_reset_validation_filter', 10, 2 ); function custom_password_reset_validation_filter( $result, $tag ) { // Make POST request to change password $token = get_query_var( 'token', "fk" ); write_log("TKN: {$token}"); } return $result; } ``` For some reason, `get__query_var` always returns `fk` instead of `abcd`.
Contact Form 7 provides a recipe for [**Validation as a Filter**](https://contactform7.com/2015/03/28/custom-validation/) which looks very much like what you are trying to do. Adapting their example to your code, I believe the following should work for you: ``` add_filter( 'wpcf7_validate_text*', 'custom_password_reset_validation_filter', 10, 2 ); function custom_password_reset_validation_filter( $result, $tag ) { if ('token'==$tag->name){ $token = isset($_POST['token']) ? $_POST['token'] : "fk"; write_log("TKN: {$token}"); } return $result; } ```
345,564
<p>In most Genesis child themes, the following line of code exists:</p> <pre><code>// Starts the engine. require_once get_template_directory() . '/lib/init.php'; </code></pre> <p>I understand that this includes the init.php file from the lib directory within the Genesis parent theme folder. </p> <p>My question is simply - why does <code>get_template_directory()</code> return the Genesis parent folder, as opposed to the child theme folder? And how does it identify it if there are multiple parent themes possible?</p>
[ { "answer_id": 345566, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>I'm not experienced with Genesis, specifically, but I imagine its child themes work the same as child themes for any other theme. <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">As documented</a>, a child theme is created by adding a <code>Template:</code> line to the style.css header, which is the directory name of the parent theme:</p>\n\n<pre><code>/*\n Theme Name: Genesis Child Theme\n Template: genesis\n*/\n</code></pre>\n\n<p>By defining the \"Template\" for a theme, WordPress functions like <code>get_template_directory()</code> know to use that theme's directory for the path or URL.</p>\n" }, { "answer_id": 346375, "author": "Bapi", "author_id": 167486, "author_profile": "https://wordpress.stackexchange.com/users/167486", "pm_score": -1, "selected": false, "text": "<p>There is no multiple parent theme possible. Because you specify parent theme by Template: genesis. This helps WordPress to find parent theme.</p>\n" } ]
2019/08/21
[ "https://wordpress.stackexchange.com/questions/345564", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170773/" ]
In most Genesis child themes, the following line of code exists: ``` // Starts the engine. require_once get_template_directory() . '/lib/init.php'; ``` I understand that this includes the init.php file from the lib directory within the Genesis parent theme folder. My question is simply - why does `get_template_directory()` return the Genesis parent folder, as opposed to the child theme folder? And how does it identify it if there are multiple parent themes possible?
I'm not experienced with Genesis, specifically, but I imagine its child themes work the same as child themes for any other theme. [As documented](https://developer.wordpress.org/themes/advanced-topics/child-themes/), a child theme is created by adding a `Template:` line to the style.css header, which is the directory name of the parent theme: ``` /* Theme Name: Genesis Child Theme Template: genesis */ ``` By defining the "Template" for a theme, WordPress functions like `get_template_directory()` know to use that theme's directory for the path or URL.
345,571
<p>I've two custom post type:</p> <p>1.products 2.seller</p> <p>Now I want to relate both the post types using the meta box. I want to display products in seller posts so that sellers can select the required multiple products and assign a price to each selected product. Finally, In the seller's post, those products need to be displayed with prices which he entered in the meta box.</p> <p>Please help me with this and I want to do this without the plugin. I am trying to code. If I get any idea will post here. Thanks in advance.</p>
[ { "answer_id": 346102, "author": "pax", "author_id": 967, "author_profile": "https://wordpress.stackexchange.com/users/967", "pm_score": 1, "selected": false, "text": "<p>You'd need a repeater <em>relationship</em> custom field. The easiest way would be still to user a plugin for this part – I'm very happy with <a href=\"https://www.advancedcustomfields.com/resources/relationship/\" rel=\"nofollow noreferrer\">ACF</a><sup>1</sup> – but there are quite a few options. One advantage is they provide a <a href=\"https://www.advancedcustomfields.com/resources/create-a-front-end-form/\" rel=\"nofollow noreferrer\">font end forms</a> option so you could move the editing for your customers in the front-end (without the need of visiting <code>/wp-admin</code>) – this requires a bit of coding. </p>\n\n<p>Then, if you're really keen of not using a plugin you could see how that works and replicate the functionality yourself – note that you'd also need to replicate the repeater metabox UI – which might not be that trivial. </p>\n\n<p>Alternatively, you could <a href=\"https://www.advancedcustomfields.com/resources/including-acf-within-a-plugin-or-theme\" rel=\"nofollow noreferrer\">include ACF in your code</a> – meaning that you won't use it as an installeg plugin – but you'd still need to include one required ACF script in yout plugin/theme.</p>\n\n<p><sup>1</sup> The repeater field would require the PRO version – for a prototype you can find it down at <a href=\"https://gpldl.com\" rel=\"nofollow noreferrer\">gpldl</a>.</p>\n" }, { "answer_id": 346107, "author": "Technoh", "author_id": 174199, "author_profile": "https://wordpress.stackexchange.com/users/174199", "pm_score": 1, "selected": false, "text": "<p>It's a bit more complicated than just using a plugin but it's certainly doable. Since you don't provide examples of your code (as of 2019-08-28) I cannot use it in my answer so I'll try to be as specific as possible in pseudo-code.</p>\n\n<p>The way I usually do it is to create a meta_field (get_post_meta, update_post_meta) with your custom post type (CPT) ID. In this case however, that would mean probably an array of <em>seller_ids</em> for each <em>product</em> and an array of <em>product_ids</em> for each <em>seller</em>. This is not practical at all, it breaks the idea of relationships and it opens the door to data corruption if one record updates but not the other.</p>\n\n<p>Since you have a many to many relationship (sellers can have different products and products can have different sellers) you want to create your own join table with only 2 fields: <em>product_id</em> and <em>seller_id</em> with each ID being the CPT's post ID. See this <a href=\"https://dba.stackexchange.com/questions/151904/mapping-many-to-many-relationship\">related post</a> for details on a many to many relationship.</p>\n\n<p>Then, when you need to display either the product or the seller, you can see which of the other you would need to load. Simply load all of the products or sellers where the ID from the relationship table match the ID of the product or seller you are showing.</p>\n" }, { "answer_id": 346370, "author": "Ahmad Wael", "author_id": 115635, "author_profile": "https://wordpress.stackexchange.com/users/115635", "pm_score": 0, "selected": false, "text": "<p>You will need to do the following logic:</p>\n\n<ol>\n<li><p>in sellers post type: create a meta box that selects the seller products from products post type, you can use select2.js to make it easy to select the seller products.</p></li>\n<li><p>save the selected products in the seller post as an array of product ids using <code>update_post_meta</code>.</p></li>\n<li><p>at the seller single page you can retrieve the selected seller product ids that we saved in the previous step using <code>get_post_meta()</code>.</p></li>\n<li><p>create a <code>WP_Query</code> with the given ids from the previous step to display the products of the current seller.</p></li>\n</ol>\n" }, { "answer_id": 346510, "author": "rozklad", "author_id": 47861, "author_profile": "https://wordpress.stackexchange.com/users/47861", "pm_score": 3, "selected": true, "text": "<p>I assume you would like to end up with something like this:\n<img src=\"https://i.stack.imgur.com/IFMIU.png\" alt=\"enter image description here\"></p>\n\n<h1>Code way</h1>\n\n<p>If you want to put this logic in your template/plugin, as you state in your question, there is quite a bit of coding. </p>\n\n<p>You need to:</p>\n\n<ul>\n<li>create custom post types</li>\n<li>create metabox for seller</li>\n<li>create content for metabox - that's called \"callback\" in the meta_box docs</li>\n<li>create logic that saves data from the meta box</li>\n<li>create metabox for product</li>\n<li>retrieve the data on front end</li>\n</ul>\n\n<h2>Create custom post types</h2>\n\n<p>I assume you already have this done, but let's register custom post types <code>product</code> and <code>seller</code> manually here:</p>\n\n<h3>Products ('product')</h3>\n\n<pre><code>/**\n * Post Type: Products.\n */\nfunction se345571_register_cpt_product() {\n\n $labels = array(\n \"name\" =&gt; __( \"Products\", \"mytheme_textdomain\" ),\n \"singular_name\" =&gt; __( \"Product\", \"mytheme_textdomain\" ),\n );\n\n $args = array(\n \"label\" =&gt; __( \"Products\", \"mytheme_textdomain\" ),\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"publicly_queryable\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"delete_with_user\" =&gt; false,\n \"show_in_rest\" =&gt; true,\n \"rest_base\" =&gt; \"\",\n \"rest_controller_class\" =&gt; \"WP_REST_Posts_Controller\",\n \"has_archive\" =&gt; false,\n \"show_in_menu\" =&gt; true,\n \"show_in_nav_menus\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"product\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"editor\", \"thumbnail\" ),\n );\n\n register_post_type( \"product\", $args );\n}\n\nadd_action( 'init', 'se345571_register_cpt_product' );\n</code></pre>\n\n<h3>Sellers ('seller')</h3>\n\n<pre><code>/**\n * Post Type: Sellers.\n */\nfunction se345571_register_cpt_seller() {\n\n $labels = array(\n \"name\" =&gt; __( \"Sellers\", \"mytheme_textdomain\" ),\n \"singular_name\" =&gt; __( \"Seller\", \"mytheme_textdomain\" ),\n );\n\n $args = array(\n \"label\" =&gt; __( \"Sellers\", \"mytheme_textdomain\" ),\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"publicly_queryable\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"delete_with_user\" =&gt; false,\n \"show_in_rest\" =&gt; true,\n \"rest_base\" =&gt; \"\",\n \"rest_controller_class\" =&gt; \"WP_REST_Posts_Controller\",\n \"has_archive\" =&gt; false,\n \"show_in_menu\" =&gt; true,\n \"show_in_nav_menus\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"seller\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"editor\", \"thumbnail\" ),\n );\n\n register_post_type( \"seller\", $args );\n}\n\nadd_action( 'init', 'se345571_register_cpt_seller' );\n\n</code></pre>\n\n<h2>Create metabox for product</h2>\n\n<pre><code>/**\n * Adds a box to \"advanced\" part on the Seller edit screen.\n * - See the different screens defined in $screens array.\n */\nfunction se345571_add_seller_meta_box() {\n\n $screens = array( 'seller' );\n\n foreach ( $screens as $screen ) {\n\n // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params\n add_meta_box(\n 'product_settings_box', // HTML 'id' attribute of the edit screen section\n __( 'Product settings', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user\n 'se345571_product_settings_meta_box_callback', // Function that prints out the HTML for the edit screen section.\n $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment')\n );\n\n }\n}\nadd_action( 'add_meta_boxes', 'se345571_add_seller_meta_box' );\n</code></pre>\n\n<p>Here you can see, that add an action, which is called in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">add_meta_boxes</a> - that means, when Wordpress is building up the meta boxes for writing screen, it's gonna call our custom <code>se345571_add_seller_meta_box()</code> function as well.</p>\n\n<h2>Create content for metabox</h2>\n\n<pre><code>/**\n * Prints the box content.\n * \n * @param WP_Post $post The object for the current post/page.\n */\nfunction se345571_product_settings_meta_box_callback( $post, $box ) {\n\n // Add a nonce field so we can check for it later.\n wp_nonce_field( 'se345571_product_settings_meta_box_data', 'se345571_product_settings_meta_box_nonce' );\n\n /*\n * Use get_post_meta() to retrieve an existing value\n * from the database and use the value for the form.\n */\n $value = get_post_meta( $post-&gt;ID, '_product_settings', true );\n\n if ($value) {\n $product_settings = json_decode($value, true);\n }\n\n // Get available products so we can show them in select box\n $args = [\n 'post_type' =&gt; 'product',\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'id',\n 'order' =&gt; 'ASC'\n ];\n\n $products = new WP_Query($args);\n\n // As you can see, i have 5 product fields, this can be just about any number\n $max = 5;\n\n ?&gt;\n &lt;table&gt;\n &lt;?php for ($index = 0; $index &lt; $max; $index++) : ?&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;label for=\"product-&lt;?php echo $index + 1 ?&gt;-product\"&gt;&lt;?php _e( 'Product #' . ($index + 1), 'mytheme_textdomain' )?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;?php $productindex = 0; ?&gt;\n &lt;select name=\"product_settings[&lt;?php echo $index ?&gt;][product_id]\" id=\"product-&lt;?php echo ($index + 1) ?&gt;-product\"&gt;\n &lt;?php while($products-&gt;have_posts()) : $products-&gt;the_post(); $productindex++; ?&gt;\n &lt;option value=\"&lt;?php the_ID() ?&gt;\" &lt;?php echo (isset($product_settings[$index]['product_id']) &amp;&amp; (int)$product_settings[$index]['product_id'] === get_the_ID()) ? 'selected' : '' ?&gt;&gt;&lt;?php the_title() ?&gt;&lt;/option&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;label for=\"product-&lt;?php echo $index + 1 ?&gt;-price\"&gt;&lt;?php _e( 'Price', 'mytheme_textdomain' )?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;input \n name=\"product_settings[&lt;?php echo $index ?&gt;][price]\" \n type=\"text\" \n class=\"components-text-control__input\" \n id=\"product-&lt;?php echo ($index + 1) ?&gt;-price\"\n value=\"&lt;?php echo isset($product_settings[$index]['price']) ? $product_settings[$index]['price'] : '' ?&gt;\"&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endfor; ?&gt;\n &lt;/table&gt;\n &lt;?php\n\n // Don't forget about this, otherwise you will mess up with other data on the page\n wp_reset_postdata();\n\n}\n</code></pre>\n\n<p>Okay, here it comes with quite a bit of code. As other people in this thread suggested, you might find useful to extend this logic with javascript (such as select2.js). You can write that directly to HTML output of this function.</p>\n\n<h2>Saving the data</h2>\n\n<pre><code>\n/**\n * When the post is saved, saves our custom data.\n *\n * @param int $post_id The ID of the post being saved.\n */\nfunction se345571_product_settings_meta_box_data( $post_id, $post ) {\n\n // Check if our nonce is set.\n if ( ! isset( $_POST['se345571_product_settings_meta_box_nonce'] ) ) {\n return;\n }\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $_POST['se345571_product_settings_meta_box_nonce'], 'se345571_product_settings_meta_box_data' ) ) {\n return;\n }\n\n // If this is an autosave, our form has not been submitted, so we don't want to do anything.\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n /* OK, it's safe for us to save the data now. */\n\n // Make sure that it is set.\n if ( ! isset( $_POST['product_settings'] ) ) {\n return;\n }\n\n // HERE STARTS THE ACTUAL FUNCTIONALITY\n\n // Sanitize user input.\n $product_settings = json_encode( $_POST['product_settings'] );\n\n // Update the meta field in the database.\n update_post_meta( $post_id, '_product_settings', $product_settings );\n\n}\n\nadd_action( 'save_post', 'se345571_product_settings_meta_box_data', 10, 2 );\n</code></pre>\n\n<p>Here's another hook, save_post and our custom logic to it. Basically, it's 1:1 what's found on <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow noreferrer\">Codex</a> to the add_meta_box() function just swapped the POST field names.</p>\n\n<h2>Create metabox for product</h2>\n\n<p>You ask to display price the seller entered for different products, as i don't have any frontend here, i will show in the product admin page. But the same logic can be applied to show it on frontend for example.</p>\n\n<pre><code>\n/**\n * Adds a box to \"advanced\" part on the Seller edit screen.\n * - See the different screens defined in $screens array.\n */\nfunction se345571_add_product_meta_box() {\n\n $screens = array( 'product' );\n\n foreach ( $screens as $screen ) {\n\n // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params\n add_meta_box(\n 'product_settings_box', // HTML 'id' attribute of the edit screen section\n __( 'Seller prices', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user\n 'se345571_seller_prices_meta_box_callback', // Function that prints out the HTML for the edit screen section.\n $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment')\n );\n\n }\n}\nadd_action( 'add_meta_boxes', 'se345571_add_product_meta_box' );\n\n/**\n * Prints the box content.\n * \n * @param WP_Post $post The object for the current post/page.\n */\nfunction se345571_seller_prices_meta_box_callback( $post, $box ) {\n\n $product_id = get_the_ID();\n\n $args = [\n 'post_type' =&gt; 'seller',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; [\n [\n 'key' =&gt; '_product_settings',\n 'value' =&gt; '\"product_id\":\"' .$product_id. '\"',\n 'compare' =&gt; 'LIKE',\n ]\n ]\n ];\n\n $sellers = new WP_Query($args);\n\n while($sellers-&gt;have_posts()) : $sellers-&gt;the_post();\n\n $seller_prices = json_decode(get_post_meta( get_the_ID(), '_product_settings', true ), true);\n\n $seller_prices_for_product = array_filter($seller_prices, function($element) use ($product_id) { \n if (isset($element['product_id'])) {\n return (int)$element['product_id'] === $product_id;\n }\n return false;\n });\n\n foreach($seller_prices_for_product as $price) :\n ?&gt;\n &lt;p&gt;\n &lt;?php the_title(); ?&gt; &lt;?php _e('for', 'mytheme_textdomain'); ?&gt; &lt;?php echo $price['price'] ?&gt;\n &lt;/p&gt;\n &lt;?php\n endforeach;\n\n endwhile;\n\n // Don't forget about this, otherwise you will mess up with other data on the page\n wp_reset_postdata();\n\n}\n</code></pre>\n\n<h2>Retrieving data</h2>\n\n<p>Finally when you need to grab your data on the frontend, you can go to template and use something like:</p>\n\n<pre><code>$value = get_post_meta( get_the_ID(), '_product_settings', true );\n$product_settings = json_decode($value, true);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_post_meta\" rel=\"nofollow noreferrer\">get_post_meta()</a> uses your current post ID, key of the field you want to retrieve (optional) and whatever you want only one or all meta (optional - not set returns all custom fields).</p>\n\n<p>This said, i'd actually go the plugin way (unless you are writing plugin yourself).</p>\n\n<h1>Plugin way</h1>\n\n<p>For cases like this, as other people pointed out, i'd pick <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">Advanced Custom Fields</a> plugin. Which can basically do the same, what is coded above.</p>\n\n<p>Setting up the meta box is done via user interface.</p>\n\n<h2>Retrieving data</h2>\n\n<p>For retrieving data you use functions get_field() or the_field() - whatever you want to return the value or print the value right away (same naming convention as in WP all around).</p>\n\n<pre><code>get_field('your_field_name');\n</code></pre>\n\n<h3>Sources and further reading</h3>\n\n<p><a href=\"http://themefoundation.com/wordpress-meta-boxes-guide/\" rel=\"nofollow noreferrer\">http://themefoundation.com/wordpress-meta-boxes-guide/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_meta_box</a>\n<a href=\"http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/</a></p>\n" } ]
2019/08/21
[ "https://wordpress.stackexchange.com/questions/345571", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97802/" ]
I've two custom post type: 1.products 2.seller Now I want to relate both the post types using the meta box. I want to display products in seller posts so that sellers can select the required multiple products and assign a price to each selected product. Finally, In the seller's post, those products need to be displayed with prices which he entered in the meta box. Please help me with this and I want to do this without the plugin. I am trying to code. If I get any idea will post here. Thanks in advance.
I assume you would like to end up with something like this: ![enter image description here](https://i.stack.imgur.com/IFMIU.png) Code way ======== If you want to put this logic in your template/plugin, as you state in your question, there is quite a bit of coding. You need to: * create custom post types * create metabox for seller * create content for metabox - that's called "callback" in the meta\_box docs * create logic that saves data from the meta box * create metabox for product * retrieve the data on front end Create custom post types ------------------------ I assume you already have this done, but let's register custom post types `product` and `seller` manually here: ### Products ('product') ``` /** * Post Type: Products. */ function se345571_register_cpt_product() { $labels = array( "name" => __( "Products", "mytheme_textdomain" ), "singular_name" => __( "Product", "mytheme_textdomain" ), ); $args = array( "label" => __( "Products", "mytheme_textdomain" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "delete_with_user" => false, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "product", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "product", $args ); } add_action( 'init', 'se345571_register_cpt_product' ); ``` ### Sellers ('seller') ``` /** * Post Type: Sellers. */ function se345571_register_cpt_seller() { $labels = array( "name" => __( "Sellers", "mytheme_textdomain" ), "singular_name" => __( "Seller", "mytheme_textdomain" ), ); $args = array( "label" => __( "Sellers", "mytheme_textdomain" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "delete_with_user" => false, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "seller", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "seller", $args ); } add_action( 'init', 'se345571_register_cpt_seller' ); ``` Create metabox for product -------------------------- ``` /** * Adds a box to "advanced" part on the Seller edit screen. * - See the different screens defined in $screens array. */ function se345571_add_seller_meta_box() { $screens = array( 'seller' ); foreach ( $screens as $screen ) { // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params add_meta_box( 'product_settings_box', // HTML 'id' attribute of the edit screen section __( 'Product settings', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user 'se345571_product_settings_meta_box_callback', // Function that prints out the HTML for the edit screen section. $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment') ); } } add_action( 'add_meta_boxes', 'se345571_add_seller_meta_box' ); ``` Here you can see, that add an action, which is called in [add\_meta\_boxes](https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes) - that means, when Wordpress is building up the meta boxes for writing screen, it's gonna call our custom `se345571_add_seller_meta_box()` function as well. Create content for metabox -------------------------- ``` /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function se345571_product_settings_meta_box_callback( $post, $box ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'se345571_product_settings_meta_box_data', 'se345571_product_settings_meta_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_product_settings', true ); if ($value) { $product_settings = json_decode($value, true); } // Get available products so we can show them in select box $args = [ 'post_type' => 'product', 'numberposts' => -1, 'orderby' => 'id', 'order' => 'ASC' ]; $products = new WP_Query($args); // As you can see, i have 5 product fields, this can be just about any number $max = 5; ?> <table> <?php for ($index = 0; $index < $max; $index++) : ?> <tr> <td> <label for="product-<?php echo $index + 1 ?>-product"><?php _e( 'Product #' . ($index + 1), 'mytheme_textdomain' )?></label> </td> <td> <?php $productindex = 0; ?> <select name="product_settings[<?php echo $index ?>][product_id]" id="product-<?php echo ($index + 1) ?>-product"> <?php while($products->have_posts()) : $products->the_post(); $productindex++; ?> <option value="<?php the_ID() ?>" <?php echo (isset($product_settings[$index]['product_id']) && (int)$product_settings[$index]['product_id'] === get_the_ID()) ? 'selected' : '' ?>><?php the_title() ?></option> <?php endwhile; ?> </select> </td> <td> <label for="product-<?php echo $index + 1 ?>-price"><?php _e( 'Price', 'mytheme_textdomain' )?></label> </td> <td> <input name="product_settings[<?php echo $index ?>][price]" type="text" class="components-text-control__input" id="product-<?php echo ($index + 1) ?>-price" value="<?php echo isset($product_settings[$index]['price']) ? $product_settings[$index]['price'] : '' ?>"> </td> </tr> <?php endfor; ?> </table> <?php // Don't forget about this, otherwise you will mess up with other data on the page wp_reset_postdata(); } ``` Okay, here it comes with quite a bit of code. As other people in this thread suggested, you might find useful to extend this logic with javascript (such as select2.js). You can write that directly to HTML output of this function. Saving the data --------------- ``` /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. */ function se345571_product_settings_meta_box_data( $post_id, $post ) { // Check if our nonce is set. if ( ! isset( $_POST['se345571_product_settings_meta_box_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['se345571_product_settings_meta_box_nonce'], 'se345571_product_settings_meta_box_data' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } /* OK, it's safe for us to save the data now. */ // Make sure that it is set. if ( ! isset( $_POST['product_settings'] ) ) { return; } // HERE STARTS THE ACTUAL FUNCTIONALITY // Sanitize user input. $product_settings = json_encode( $_POST['product_settings'] ); // Update the meta field in the database. update_post_meta( $post_id, '_product_settings', $product_settings ); } add_action( 'save_post', 'se345571_product_settings_meta_box_data', 10, 2 ); ``` Here's another hook, save\_post and our custom logic to it. Basically, it's 1:1 what's found on [Codex](https://codex.wordpress.org/Function_Reference/add_meta_box) to the add\_meta\_box() function just swapped the POST field names. Create metabox for product -------------------------- You ask to display price the seller entered for different products, as i don't have any frontend here, i will show in the product admin page. But the same logic can be applied to show it on frontend for example. ``` /** * Adds a box to "advanced" part on the Seller edit screen. * - See the different screens defined in $screens array. */ function se345571_add_product_meta_box() { $screens = array( 'product' ); foreach ( $screens as $screen ) { // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params add_meta_box( 'product_settings_box', // HTML 'id' attribute of the edit screen section __( 'Seller prices', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user 'se345571_seller_prices_meta_box_callback', // Function that prints out the HTML for the edit screen section. $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment') ); } } add_action( 'add_meta_boxes', 'se345571_add_product_meta_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function se345571_seller_prices_meta_box_callback( $post, $box ) { $product_id = get_the_ID(); $args = [ 'post_type' => 'seller', 'numberposts' => -1, 'meta_query' => [ [ 'key' => '_product_settings', 'value' => '"product_id":"' .$product_id. '"', 'compare' => 'LIKE', ] ] ]; $sellers = new WP_Query($args); while($sellers->have_posts()) : $sellers->the_post(); $seller_prices = json_decode(get_post_meta( get_the_ID(), '_product_settings', true ), true); $seller_prices_for_product = array_filter($seller_prices, function($element) use ($product_id) { if (isset($element['product_id'])) { return (int)$element['product_id'] === $product_id; } return false; }); foreach($seller_prices_for_product as $price) : ?> <p> <?php the_title(); ?> <?php _e('for', 'mytheme_textdomain'); ?> <?php echo $price['price'] ?> </p> <?php endforeach; endwhile; // Don't forget about this, otherwise you will mess up with other data on the page wp_reset_postdata(); } ``` Retrieving data --------------- Finally when you need to grab your data on the frontend, you can go to template and use something like: ``` $value = get_post_meta( get_the_ID(), '_product_settings', true ); $product_settings = json_decode($value, true); ``` [get\_post\_meta()](https://codex.wordpress.org/Function_Reference/get_post_meta) uses your current post ID, key of the field you want to retrieve (optional) and whatever you want only one or all meta (optional - not set returns all custom fields). This said, i'd actually go the plugin way (unless you are writing plugin yourself). Plugin way ========== For cases like this, as other people pointed out, i'd pick [Advanced Custom Fields](http://www.advancedcustomfields.com/) plugin. Which can basically do the same, what is coded above. Setting up the meta box is done via user interface. Retrieving data --------------- For retrieving data you use functions get\_field() or the\_field() - whatever you want to return the value or print the value right away (same naming convention as in WP all around). ``` get_field('your_field_name'); ``` ### Sources and further reading <http://themefoundation.com/wordpress-meta-boxes-guide/> <https://codex.wordpress.org/Function_Reference/add_meta_box> <http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/>
345,656
<pre><code>&lt;?php /* Template Name: Dummy Practice Page*/?&gt; &lt;div id="main-content" class="main-content"&gt; &lt;div class="main-content-inner"&gt; &lt;form method="post"&gt; &lt;p&gt;&lt;div&gt; &lt;input name="nametxt" id="nametxt" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required&gt;&lt;br&gt; &lt;/p&gt;&lt;/div&gt; &lt;p&gt;&lt;div&gt; &lt;input name="designationtxt" id="designationtxt" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required&gt;&lt;br&gt; &lt;/p&gt;&lt;/div&gt; &lt;p&gt;&lt;div&gt; &lt;input name="designationtxt" id="descriptiontxt" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required&gt;&lt;br&gt; &lt;/p&gt;&lt;/div&gt; &lt;input id="submitbtn" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px; " name='Submit' value='Add Member' /&gt;&lt;br&gt;&lt;br&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php global $wpdb; $table = $wpdb-&gt;prefix.'tboxteam'; $data = array('name' =&gt; isset($_POST['nametxt']), 'designation' =&gt; isset($_POST['designationtxt']), 'description' =&gt; isset($_POST['descriptiontxt'])); $format = array('%s','%s','%s'); $wpdb-&gt;insert($table,$data,$format); ?&gt; </code></pre>
[ { "answer_id": 346102, "author": "pax", "author_id": 967, "author_profile": "https://wordpress.stackexchange.com/users/967", "pm_score": 1, "selected": false, "text": "<p>You'd need a repeater <em>relationship</em> custom field. The easiest way would be still to user a plugin for this part – I'm very happy with <a href=\"https://www.advancedcustomfields.com/resources/relationship/\" rel=\"nofollow noreferrer\">ACF</a><sup>1</sup> – but there are quite a few options. One advantage is they provide a <a href=\"https://www.advancedcustomfields.com/resources/create-a-front-end-form/\" rel=\"nofollow noreferrer\">font end forms</a> option so you could move the editing for your customers in the front-end (without the need of visiting <code>/wp-admin</code>) – this requires a bit of coding. </p>\n\n<p>Then, if you're really keen of not using a plugin you could see how that works and replicate the functionality yourself – note that you'd also need to replicate the repeater metabox UI – which might not be that trivial. </p>\n\n<p>Alternatively, you could <a href=\"https://www.advancedcustomfields.com/resources/including-acf-within-a-plugin-or-theme\" rel=\"nofollow noreferrer\">include ACF in your code</a> – meaning that you won't use it as an installeg plugin – but you'd still need to include one required ACF script in yout plugin/theme.</p>\n\n<p><sup>1</sup> The repeater field would require the PRO version – for a prototype you can find it down at <a href=\"https://gpldl.com\" rel=\"nofollow noreferrer\">gpldl</a>.</p>\n" }, { "answer_id": 346107, "author": "Technoh", "author_id": 174199, "author_profile": "https://wordpress.stackexchange.com/users/174199", "pm_score": 1, "selected": false, "text": "<p>It's a bit more complicated than just using a plugin but it's certainly doable. Since you don't provide examples of your code (as of 2019-08-28) I cannot use it in my answer so I'll try to be as specific as possible in pseudo-code.</p>\n\n<p>The way I usually do it is to create a meta_field (get_post_meta, update_post_meta) with your custom post type (CPT) ID. In this case however, that would mean probably an array of <em>seller_ids</em> for each <em>product</em> and an array of <em>product_ids</em> for each <em>seller</em>. This is not practical at all, it breaks the idea of relationships and it opens the door to data corruption if one record updates but not the other.</p>\n\n<p>Since you have a many to many relationship (sellers can have different products and products can have different sellers) you want to create your own join table with only 2 fields: <em>product_id</em> and <em>seller_id</em> with each ID being the CPT's post ID. See this <a href=\"https://dba.stackexchange.com/questions/151904/mapping-many-to-many-relationship\">related post</a> for details on a many to many relationship.</p>\n\n<p>Then, when you need to display either the product or the seller, you can see which of the other you would need to load. Simply load all of the products or sellers where the ID from the relationship table match the ID of the product or seller you are showing.</p>\n" }, { "answer_id": 346370, "author": "Ahmad Wael", "author_id": 115635, "author_profile": "https://wordpress.stackexchange.com/users/115635", "pm_score": 0, "selected": false, "text": "<p>You will need to do the following logic:</p>\n\n<ol>\n<li><p>in sellers post type: create a meta box that selects the seller products from products post type, you can use select2.js to make it easy to select the seller products.</p></li>\n<li><p>save the selected products in the seller post as an array of product ids using <code>update_post_meta</code>.</p></li>\n<li><p>at the seller single page you can retrieve the selected seller product ids that we saved in the previous step using <code>get_post_meta()</code>.</p></li>\n<li><p>create a <code>WP_Query</code> with the given ids from the previous step to display the products of the current seller.</p></li>\n</ol>\n" }, { "answer_id": 346510, "author": "rozklad", "author_id": 47861, "author_profile": "https://wordpress.stackexchange.com/users/47861", "pm_score": 3, "selected": true, "text": "<p>I assume you would like to end up with something like this:\n<img src=\"https://i.stack.imgur.com/IFMIU.png\" alt=\"enter image description here\"></p>\n\n<h1>Code way</h1>\n\n<p>If you want to put this logic in your template/plugin, as you state in your question, there is quite a bit of coding. </p>\n\n<p>You need to:</p>\n\n<ul>\n<li>create custom post types</li>\n<li>create metabox for seller</li>\n<li>create content for metabox - that's called \"callback\" in the meta_box docs</li>\n<li>create logic that saves data from the meta box</li>\n<li>create metabox for product</li>\n<li>retrieve the data on front end</li>\n</ul>\n\n<h2>Create custom post types</h2>\n\n<p>I assume you already have this done, but let's register custom post types <code>product</code> and <code>seller</code> manually here:</p>\n\n<h3>Products ('product')</h3>\n\n<pre><code>/**\n * Post Type: Products.\n */\nfunction se345571_register_cpt_product() {\n\n $labels = array(\n \"name\" =&gt; __( \"Products\", \"mytheme_textdomain\" ),\n \"singular_name\" =&gt; __( \"Product\", \"mytheme_textdomain\" ),\n );\n\n $args = array(\n \"label\" =&gt; __( \"Products\", \"mytheme_textdomain\" ),\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"publicly_queryable\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"delete_with_user\" =&gt; false,\n \"show_in_rest\" =&gt; true,\n \"rest_base\" =&gt; \"\",\n \"rest_controller_class\" =&gt; \"WP_REST_Posts_Controller\",\n \"has_archive\" =&gt; false,\n \"show_in_menu\" =&gt; true,\n \"show_in_nav_menus\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"product\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"editor\", \"thumbnail\" ),\n );\n\n register_post_type( \"product\", $args );\n}\n\nadd_action( 'init', 'se345571_register_cpt_product' );\n</code></pre>\n\n<h3>Sellers ('seller')</h3>\n\n<pre><code>/**\n * Post Type: Sellers.\n */\nfunction se345571_register_cpt_seller() {\n\n $labels = array(\n \"name\" =&gt; __( \"Sellers\", \"mytheme_textdomain\" ),\n \"singular_name\" =&gt; __( \"Seller\", \"mytheme_textdomain\" ),\n );\n\n $args = array(\n \"label\" =&gt; __( \"Sellers\", \"mytheme_textdomain\" ),\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"publicly_queryable\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"delete_with_user\" =&gt; false,\n \"show_in_rest\" =&gt; true,\n \"rest_base\" =&gt; \"\",\n \"rest_controller_class\" =&gt; \"WP_REST_Posts_Controller\",\n \"has_archive\" =&gt; false,\n \"show_in_menu\" =&gt; true,\n \"show_in_nav_menus\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"seller\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"editor\", \"thumbnail\" ),\n );\n\n register_post_type( \"seller\", $args );\n}\n\nadd_action( 'init', 'se345571_register_cpt_seller' );\n\n</code></pre>\n\n<h2>Create metabox for product</h2>\n\n<pre><code>/**\n * Adds a box to \"advanced\" part on the Seller edit screen.\n * - See the different screens defined in $screens array.\n */\nfunction se345571_add_seller_meta_box() {\n\n $screens = array( 'seller' );\n\n foreach ( $screens as $screen ) {\n\n // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params\n add_meta_box(\n 'product_settings_box', // HTML 'id' attribute of the edit screen section\n __( 'Product settings', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user\n 'se345571_product_settings_meta_box_callback', // Function that prints out the HTML for the edit screen section.\n $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment')\n );\n\n }\n}\nadd_action( 'add_meta_boxes', 'se345571_add_seller_meta_box' );\n</code></pre>\n\n<p>Here you can see, that add an action, which is called in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">add_meta_boxes</a> - that means, when Wordpress is building up the meta boxes for writing screen, it's gonna call our custom <code>se345571_add_seller_meta_box()</code> function as well.</p>\n\n<h2>Create content for metabox</h2>\n\n<pre><code>/**\n * Prints the box content.\n * \n * @param WP_Post $post The object for the current post/page.\n */\nfunction se345571_product_settings_meta_box_callback( $post, $box ) {\n\n // Add a nonce field so we can check for it later.\n wp_nonce_field( 'se345571_product_settings_meta_box_data', 'se345571_product_settings_meta_box_nonce' );\n\n /*\n * Use get_post_meta() to retrieve an existing value\n * from the database and use the value for the form.\n */\n $value = get_post_meta( $post-&gt;ID, '_product_settings', true );\n\n if ($value) {\n $product_settings = json_decode($value, true);\n }\n\n // Get available products so we can show them in select box\n $args = [\n 'post_type' =&gt; 'product',\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'id',\n 'order' =&gt; 'ASC'\n ];\n\n $products = new WP_Query($args);\n\n // As you can see, i have 5 product fields, this can be just about any number\n $max = 5;\n\n ?&gt;\n &lt;table&gt;\n &lt;?php for ($index = 0; $index &lt; $max; $index++) : ?&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;label for=\"product-&lt;?php echo $index + 1 ?&gt;-product\"&gt;&lt;?php _e( 'Product #' . ($index + 1), 'mytheme_textdomain' )?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;?php $productindex = 0; ?&gt;\n &lt;select name=\"product_settings[&lt;?php echo $index ?&gt;][product_id]\" id=\"product-&lt;?php echo ($index + 1) ?&gt;-product\"&gt;\n &lt;?php while($products-&gt;have_posts()) : $products-&gt;the_post(); $productindex++; ?&gt;\n &lt;option value=\"&lt;?php the_ID() ?&gt;\" &lt;?php echo (isset($product_settings[$index]['product_id']) &amp;&amp; (int)$product_settings[$index]['product_id'] === get_the_ID()) ? 'selected' : '' ?&gt;&gt;&lt;?php the_title() ?&gt;&lt;/option&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;label for=\"product-&lt;?php echo $index + 1 ?&gt;-price\"&gt;&lt;?php _e( 'Price', 'mytheme_textdomain' )?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;input \n name=\"product_settings[&lt;?php echo $index ?&gt;][price]\" \n type=\"text\" \n class=\"components-text-control__input\" \n id=\"product-&lt;?php echo ($index + 1) ?&gt;-price\"\n value=\"&lt;?php echo isset($product_settings[$index]['price']) ? $product_settings[$index]['price'] : '' ?&gt;\"&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endfor; ?&gt;\n &lt;/table&gt;\n &lt;?php\n\n // Don't forget about this, otherwise you will mess up with other data on the page\n wp_reset_postdata();\n\n}\n</code></pre>\n\n<p>Okay, here it comes with quite a bit of code. As other people in this thread suggested, you might find useful to extend this logic with javascript (such as select2.js). You can write that directly to HTML output of this function.</p>\n\n<h2>Saving the data</h2>\n\n<pre><code>\n/**\n * When the post is saved, saves our custom data.\n *\n * @param int $post_id The ID of the post being saved.\n */\nfunction se345571_product_settings_meta_box_data( $post_id, $post ) {\n\n // Check if our nonce is set.\n if ( ! isset( $_POST['se345571_product_settings_meta_box_nonce'] ) ) {\n return;\n }\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $_POST['se345571_product_settings_meta_box_nonce'], 'se345571_product_settings_meta_box_data' ) ) {\n return;\n }\n\n // If this is an autosave, our form has not been submitted, so we don't want to do anything.\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n /* OK, it's safe for us to save the data now. */\n\n // Make sure that it is set.\n if ( ! isset( $_POST['product_settings'] ) ) {\n return;\n }\n\n // HERE STARTS THE ACTUAL FUNCTIONALITY\n\n // Sanitize user input.\n $product_settings = json_encode( $_POST['product_settings'] );\n\n // Update the meta field in the database.\n update_post_meta( $post_id, '_product_settings', $product_settings );\n\n}\n\nadd_action( 'save_post', 'se345571_product_settings_meta_box_data', 10, 2 );\n</code></pre>\n\n<p>Here's another hook, save_post and our custom logic to it. Basically, it's 1:1 what's found on <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow noreferrer\">Codex</a> to the add_meta_box() function just swapped the POST field names.</p>\n\n<h2>Create metabox for product</h2>\n\n<p>You ask to display price the seller entered for different products, as i don't have any frontend here, i will show in the product admin page. But the same logic can be applied to show it on frontend for example.</p>\n\n<pre><code>\n/**\n * Adds a box to \"advanced\" part on the Seller edit screen.\n * - See the different screens defined in $screens array.\n */\nfunction se345571_add_product_meta_box() {\n\n $screens = array( 'product' );\n\n foreach ( $screens as $screen ) {\n\n // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params\n add_meta_box(\n 'product_settings_box', // HTML 'id' attribute of the edit screen section\n __( 'Seller prices', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user\n 'se345571_seller_prices_meta_box_callback', // Function that prints out the HTML for the edit screen section.\n $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment')\n );\n\n }\n}\nadd_action( 'add_meta_boxes', 'se345571_add_product_meta_box' );\n\n/**\n * Prints the box content.\n * \n * @param WP_Post $post The object for the current post/page.\n */\nfunction se345571_seller_prices_meta_box_callback( $post, $box ) {\n\n $product_id = get_the_ID();\n\n $args = [\n 'post_type' =&gt; 'seller',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; [\n [\n 'key' =&gt; '_product_settings',\n 'value' =&gt; '\"product_id\":\"' .$product_id. '\"',\n 'compare' =&gt; 'LIKE',\n ]\n ]\n ];\n\n $sellers = new WP_Query($args);\n\n while($sellers-&gt;have_posts()) : $sellers-&gt;the_post();\n\n $seller_prices = json_decode(get_post_meta( get_the_ID(), '_product_settings', true ), true);\n\n $seller_prices_for_product = array_filter($seller_prices, function($element) use ($product_id) { \n if (isset($element['product_id'])) {\n return (int)$element['product_id'] === $product_id;\n }\n return false;\n });\n\n foreach($seller_prices_for_product as $price) :\n ?&gt;\n &lt;p&gt;\n &lt;?php the_title(); ?&gt; &lt;?php _e('for', 'mytheme_textdomain'); ?&gt; &lt;?php echo $price['price'] ?&gt;\n &lt;/p&gt;\n &lt;?php\n endforeach;\n\n endwhile;\n\n // Don't forget about this, otherwise you will mess up with other data on the page\n wp_reset_postdata();\n\n}\n</code></pre>\n\n<h2>Retrieving data</h2>\n\n<p>Finally when you need to grab your data on the frontend, you can go to template and use something like:</p>\n\n<pre><code>$value = get_post_meta( get_the_ID(), '_product_settings', true );\n$product_settings = json_decode($value, true);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_post_meta\" rel=\"nofollow noreferrer\">get_post_meta()</a> uses your current post ID, key of the field you want to retrieve (optional) and whatever you want only one or all meta (optional - not set returns all custom fields).</p>\n\n<p>This said, i'd actually go the plugin way (unless you are writing plugin yourself).</p>\n\n<h1>Plugin way</h1>\n\n<p>For cases like this, as other people pointed out, i'd pick <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">Advanced Custom Fields</a> plugin. Which can basically do the same, what is coded above.</p>\n\n<p>Setting up the meta box is done via user interface.</p>\n\n<h2>Retrieving data</h2>\n\n<p>For retrieving data you use functions get_field() or the_field() - whatever you want to return the value or print the value right away (same naming convention as in WP all around).</p>\n\n<pre><code>get_field('your_field_name');\n</code></pre>\n\n<h3>Sources and further reading</h3>\n\n<p><a href=\"http://themefoundation.com/wordpress-meta-boxes-guide/\" rel=\"nofollow noreferrer\">http://themefoundation.com/wordpress-meta-boxes-guide/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_meta_box</a>\n<a href=\"http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/</a></p>\n" } ]
2019/08/22
[ "https://wordpress.stackexchange.com/questions/345656", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173921/" ]
``` <?php /* Template Name: Dummy Practice Page*/?> <div id="main-content" class="main-content"> <div class="main-content-inner"> <form method="post"> <p><div> <input name="nametxt" id="nametxt" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required><br> </p></div> <p><div> <input name="designationtxt" id="designationtxt" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required><br> </p></div> <p><div> <input name="designationtxt" id="descriptiontxt" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required><br> </p></div> <input id="submitbtn" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px; " name='Submit' value='Add Member' /><br><br> </form> </div> </div> <?php global $wpdb; $table = $wpdb->prefix.'tboxteam'; $data = array('name' => isset($_POST['nametxt']), 'designation' => isset($_POST['designationtxt']), 'description' => isset($_POST['descriptiontxt'])); $format = array('%s','%s','%s'); $wpdb->insert($table,$data,$format); ?> ```
I assume you would like to end up with something like this: ![enter image description here](https://i.stack.imgur.com/IFMIU.png) Code way ======== If you want to put this logic in your template/plugin, as you state in your question, there is quite a bit of coding. You need to: * create custom post types * create metabox for seller * create content for metabox - that's called "callback" in the meta\_box docs * create logic that saves data from the meta box * create metabox for product * retrieve the data on front end Create custom post types ------------------------ I assume you already have this done, but let's register custom post types `product` and `seller` manually here: ### Products ('product') ``` /** * Post Type: Products. */ function se345571_register_cpt_product() { $labels = array( "name" => __( "Products", "mytheme_textdomain" ), "singular_name" => __( "Product", "mytheme_textdomain" ), ); $args = array( "label" => __( "Products", "mytheme_textdomain" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "delete_with_user" => false, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "product", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "product", $args ); } add_action( 'init', 'se345571_register_cpt_product' ); ``` ### Sellers ('seller') ``` /** * Post Type: Sellers. */ function se345571_register_cpt_seller() { $labels = array( "name" => __( "Sellers", "mytheme_textdomain" ), "singular_name" => __( "Seller", "mytheme_textdomain" ), ); $args = array( "label" => __( "Sellers", "mytheme_textdomain" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "delete_with_user" => false, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "seller", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "seller", $args ); } add_action( 'init', 'se345571_register_cpt_seller' ); ``` Create metabox for product -------------------------- ``` /** * Adds a box to "advanced" part on the Seller edit screen. * - See the different screens defined in $screens array. */ function se345571_add_seller_meta_box() { $screens = array( 'seller' ); foreach ( $screens as $screen ) { // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params add_meta_box( 'product_settings_box', // HTML 'id' attribute of the edit screen section __( 'Product settings', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user 'se345571_product_settings_meta_box_callback', // Function that prints out the HTML for the edit screen section. $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment') ); } } add_action( 'add_meta_boxes', 'se345571_add_seller_meta_box' ); ``` Here you can see, that add an action, which is called in [add\_meta\_boxes](https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes) - that means, when Wordpress is building up the meta boxes for writing screen, it's gonna call our custom `se345571_add_seller_meta_box()` function as well. Create content for metabox -------------------------- ``` /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function se345571_product_settings_meta_box_callback( $post, $box ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'se345571_product_settings_meta_box_data', 'se345571_product_settings_meta_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_product_settings', true ); if ($value) { $product_settings = json_decode($value, true); } // Get available products so we can show them in select box $args = [ 'post_type' => 'product', 'numberposts' => -1, 'orderby' => 'id', 'order' => 'ASC' ]; $products = new WP_Query($args); // As you can see, i have 5 product fields, this can be just about any number $max = 5; ?> <table> <?php for ($index = 0; $index < $max; $index++) : ?> <tr> <td> <label for="product-<?php echo $index + 1 ?>-product"><?php _e( 'Product #' . ($index + 1), 'mytheme_textdomain' )?></label> </td> <td> <?php $productindex = 0; ?> <select name="product_settings[<?php echo $index ?>][product_id]" id="product-<?php echo ($index + 1) ?>-product"> <?php while($products->have_posts()) : $products->the_post(); $productindex++; ?> <option value="<?php the_ID() ?>" <?php echo (isset($product_settings[$index]['product_id']) && (int)$product_settings[$index]['product_id'] === get_the_ID()) ? 'selected' : '' ?>><?php the_title() ?></option> <?php endwhile; ?> </select> </td> <td> <label for="product-<?php echo $index + 1 ?>-price"><?php _e( 'Price', 'mytheme_textdomain' )?></label> </td> <td> <input name="product_settings[<?php echo $index ?>][price]" type="text" class="components-text-control__input" id="product-<?php echo ($index + 1) ?>-price" value="<?php echo isset($product_settings[$index]['price']) ? $product_settings[$index]['price'] : '' ?>"> </td> </tr> <?php endfor; ?> </table> <?php // Don't forget about this, otherwise you will mess up with other data on the page wp_reset_postdata(); } ``` Okay, here it comes with quite a bit of code. As other people in this thread suggested, you might find useful to extend this logic with javascript (such as select2.js). You can write that directly to HTML output of this function. Saving the data --------------- ``` /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. */ function se345571_product_settings_meta_box_data( $post_id, $post ) { // Check if our nonce is set. if ( ! isset( $_POST['se345571_product_settings_meta_box_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['se345571_product_settings_meta_box_nonce'], 'se345571_product_settings_meta_box_data' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } /* OK, it's safe for us to save the data now. */ // Make sure that it is set. if ( ! isset( $_POST['product_settings'] ) ) { return; } // HERE STARTS THE ACTUAL FUNCTIONALITY // Sanitize user input. $product_settings = json_encode( $_POST['product_settings'] ); // Update the meta field in the database. update_post_meta( $post_id, '_product_settings', $product_settings ); } add_action( 'save_post', 'se345571_product_settings_meta_box_data', 10, 2 ); ``` Here's another hook, save\_post and our custom logic to it. Basically, it's 1:1 what's found on [Codex](https://codex.wordpress.org/Function_Reference/add_meta_box) to the add\_meta\_box() function just swapped the POST field names. Create metabox for product -------------------------- You ask to display price the seller entered for different products, as i don't have any frontend here, i will show in the product admin page. But the same logic can be applied to show it on frontend for example. ``` /** * Adds a box to "advanced" part on the Seller edit screen. * - See the different screens defined in $screens array. */ function se345571_add_product_meta_box() { $screens = array( 'product' ); foreach ( $screens as $screen ) { // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params add_meta_box( 'product_settings_box', // HTML 'id' attribute of the edit screen section __( 'Seller prices', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user 'se345571_seller_prices_meta_box_callback', // Function that prints out the HTML for the edit screen section. $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment') ); } } add_action( 'add_meta_boxes', 'se345571_add_product_meta_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function se345571_seller_prices_meta_box_callback( $post, $box ) { $product_id = get_the_ID(); $args = [ 'post_type' => 'seller', 'numberposts' => -1, 'meta_query' => [ [ 'key' => '_product_settings', 'value' => '"product_id":"' .$product_id. '"', 'compare' => 'LIKE', ] ] ]; $sellers = new WP_Query($args); while($sellers->have_posts()) : $sellers->the_post(); $seller_prices = json_decode(get_post_meta( get_the_ID(), '_product_settings', true ), true); $seller_prices_for_product = array_filter($seller_prices, function($element) use ($product_id) { if (isset($element['product_id'])) { return (int)$element['product_id'] === $product_id; } return false; }); foreach($seller_prices_for_product as $price) : ?> <p> <?php the_title(); ?> <?php _e('for', 'mytheme_textdomain'); ?> <?php echo $price['price'] ?> </p> <?php endforeach; endwhile; // Don't forget about this, otherwise you will mess up with other data on the page wp_reset_postdata(); } ``` Retrieving data --------------- Finally when you need to grab your data on the frontend, you can go to template and use something like: ``` $value = get_post_meta( get_the_ID(), '_product_settings', true ); $product_settings = json_decode($value, true); ``` [get\_post\_meta()](https://codex.wordpress.org/Function_Reference/get_post_meta) uses your current post ID, key of the field you want to retrieve (optional) and whatever you want only one or all meta (optional - not set returns all custom fields). This said, i'd actually go the plugin way (unless you are writing plugin yourself). Plugin way ========== For cases like this, as other people pointed out, i'd pick [Advanced Custom Fields](http://www.advancedcustomfields.com/) plugin. Which can basically do the same, what is coded above. Setting up the meta box is done via user interface. Retrieving data --------------- For retrieving data you use functions get\_field() or the\_field() - whatever you want to return the value or print the value right away (same naming convention as in WP all around). ``` get_field('your_field_name'); ``` ### Sources and further reading <http://themefoundation.com/wordpress-meta-boxes-guide/> <https://codex.wordpress.org/Function_Reference/add_meta_box> <http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/>
345,692
<p>I've been searching a lot but haven't found one very simple thing: how to import a post created on Instagram and turn it into a Wordpress post, that is, copy one Instagram post (text + photo) and create a simple post on the Wordpress blog?</p>
[ { "answer_id": 346102, "author": "pax", "author_id": 967, "author_profile": "https://wordpress.stackexchange.com/users/967", "pm_score": 1, "selected": false, "text": "<p>You'd need a repeater <em>relationship</em> custom field. The easiest way would be still to user a plugin for this part – I'm very happy with <a href=\"https://www.advancedcustomfields.com/resources/relationship/\" rel=\"nofollow noreferrer\">ACF</a><sup>1</sup> – but there are quite a few options. One advantage is they provide a <a href=\"https://www.advancedcustomfields.com/resources/create-a-front-end-form/\" rel=\"nofollow noreferrer\">font end forms</a> option so you could move the editing for your customers in the front-end (without the need of visiting <code>/wp-admin</code>) – this requires a bit of coding. </p>\n\n<p>Then, if you're really keen of not using a plugin you could see how that works and replicate the functionality yourself – note that you'd also need to replicate the repeater metabox UI – which might not be that trivial. </p>\n\n<p>Alternatively, you could <a href=\"https://www.advancedcustomfields.com/resources/including-acf-within-a-plugin-or-theme\" rel=\"nofollow noreferrer\">include ACF in your code</a> – meaning that you won't use it as an installeg plugin – but you'd still need to include one required ACF script in yout plugin/theme.</p>\n\n<p><sup>1</sup> The repeater field would require the PRO version – for a prototype you can find it down at <a href=\"https://gpldl.com\" rel=\"nofollow noreferrer\">gpldl</a>.</p>\n" }, { "answer_id": 346107, "author": "Technoh", "author_id": 174199, "author_profile": "https://wordpress.stackexchange.com/users/174199", "pm_score": 1, "selected": false, "text": "<p>It's a bit more complicated than just using a plugin but it's certainly doable. Since you don't provide examples of your code (as of 2019-08-28) I cannot use it in my answer so I'll try to be as specific as possible in pseudo-code.</p>\n\n<p>The way I usually do it is to create a meta_field (get_post_meta, update_post_meta) with your custom post type (CPT) ID. In this case however, that would mean probably an array of <em>seller_ids</em> for each <em>product</em> and an array of <em>product_ids</em> for each <em>seller</em>. This is not practical at all, it breaks the idea of relationships and it opens the door to data corruption if one record updates but not the other.</p>\n\n<p>Since you have a many to many relationship (sellers can have different products and products can have different sellers) you want to create your own join table with only 2 fields: <em>product_id</em> and <em>seller_id</em> with each ID being the CPT's post ID. See this <a href=\"https://dba.stackexchange.com/questions/151904/mapping-many-to-many-relationship\">related post</a> for details on a many to many relationship.</p>\n\n<p>Then, when you need to display either the product or the seller, you can see which of the other you would need to load. Simply load all of the products or sellers where the ID from the relationship table match the ID of the product or seller you are showing.</p>\n" }, { "answer_id": 346370, "author": "Ahmad Wael", "author_id": 115635, "author_profile": "https://wordpress.stackexchange.com/users/115635", "pm_score": 0, "selected": false, "text": "<p>You will need to do the following logic:</p>\n\n<ol>\n<li><p>in sellers post type: create a meta box that selects the seller products from products post type, you can use select2.js to make it easy to select the seller products.</p></li>\n<li><p>save the selected products in the seller post as an array of product ids using <code>update_post_meta</code>.</p></li>\n<li><p>at the seller single page you can retrieve the selected seller product ids that we saved in the previous step using <code>get_post_meta()</code>.</p></li>\n<li><p>create a <code>WP_Query</code> with the given ids from the previous step to display the products of the current seller.</p></li>\n</ol>\n" }, { "answer_id": 346510, "author": "rozklad", "author_id": 47861, "author_profile": "https://wordpress.stackexchange.com/users/47861", "pm_score": 3, "selected": true, "text": "<p>I assume you would like to end up with something like this:\n<img src=\"https://i.stack.imgur.com/IFMIU.png\" alt=\"enter image description here\"></p>\n\n<h1>Code way</h1>\n\n<p>If you want to put this logic in your template/plugin, as you state in your question, there is quite a bit of coding. </p>\n\n<p>You need to:</p>\n\n<ul>\n<li>create custom post types</li>\n<li>create metabox for seller</li>\n<li>create content for metabox - that's called \"callback\" in the meta_box docs</li>\n<li>create logic that saves data from the meta box</li>\n<li>create metabox for product</li>\n<li>retrieve the data on front end</li>\n</ul>\n\n<h2>Create custom post types</h2>\n\n<p>I assume you already have this done, but let's register custom post types <code>product</code> and <code>seller</code> manually here:</p>\n\n<h3>Products ('product')</h3>\n\n<pre><code>/**\n * Post Type: Products.\n */\nfunction se345571_register_cpt_product() {\n\n $labels = array(\n \"name\" =&gt; __( \"Products\", \"mytheme_textdomain\" ),\n \"singular_name\" =&gt; __( \"Product\", \"mytheme_textdomain\" ),\n );\n\n $args = array(\n \"label\" =&gt; __( \"Products\", \"mytheme_textdomain\" ),\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"publicly_queryable\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"delete_with_user\" =&gt; false,\n \"show_in_rest\" =&gt; true,\n \"rest_base\" =&gt; \"\",\n \"rest_controller_class\" =&gt; \"WP_REST_Posts_Controller\",\n \"has_archive\" =&gt; false,\n \"show_in_menu\" =&gt; true,\n \"show_in_nav_menus\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"product\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"editor\", \"thumbnail\" ),\n );\n\n register_post_type( \"product\", $args );\n}\n\nadd_action( 'init', 'se345571_register_cpt_product' );\n</code></pre>\n\n<h3>Sellers ('seller')</h3>\n\n<pre><code>/**\n * Post Type: Sellers.\n */\nfunction se345571_register_cpt_seller() {\n\n $labels = array(\n \"name\" =&gt; __( \"Sellers\", \"mytheme_textdomain\" ),\n \"singular_name\" =&gt; __( \"Seller\", \"mytheme_textdomain\" ),\n );\n\n $args = array(\n \"label\" =&gt; __( \"Sellers\", \"mytheme_textdomain\" ),\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"publicly_queryable\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"delete_with_user\" =&gt; false,\n \"show_in_rest\" =&gt; true,\n \"rest_base\" =&gt; \"\",\n \"rest_controller_class\" =&gt; \"WP_REST_Posts_Controller\",\n \"has_archive\" =&gt; false,\n \"show_in_menu\" =&gt; true,\n \"show_in_nav_menus\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"seller\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"editor\", \"thumbnail\" ),\n );\n\n register_post_type( \"seller\", $args );\n}\n\nadd_action( 'init', 'se345571_register_cpt_seller' );\n\n</code></pre>\n\n<h2>Create metabox for product</h2>\n\n<pre><code>/**\n * Adds a box to \"advanced\" part on the Seller edit screen.\n * - See the different screens defined in $screens array.\n */\nfunction se345571_add_seller_meta_box() {\n\n $screens = array( 'seller' );\n\n foreach ( $screens as $screen ) {\n\n // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params\n add_meta_box(\n 'product_settings_box', // HTML 'id' attribute of the edit screen section\n __( 'Product settings', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user\n 'se345571_product_settings_meta_box_callback', // Function that prints out the HTML for the edit screen section.\n $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment')\n );\n\n }\n}\nadd_action( 'add_meta_boxes', 'se345571_add_seller_meta_box' );\n</code></pre>\n\n<p>Here you can see, that add an action, which is called in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">add_meta_boxes</a> - that means, when Wordpress is building up the meta boxes for writing screen, it's gonna call our custom <code>se345571_add_seller_meta_box()</code> function as well.</p>\n\n<h2>Create content for metabox</h2>\n\n<pre><code>/**\n * Prints the box content.\n * \n * @param WP_Post $post The object for the current post/page.\n */\nfunction se345571_product_settings_meta_box_callback( $post, $box ) {\n\n // Add a nonce field so we can check for it later.\n wp_nonce_field( 'se345571_product_settings_meta_box_data', 'se345571_product_settings_meta_box_nonce' );\n\n /*\n * Use get_post_meta() to retrieve an existing value\n * from the database and use the value for the form.\n */\n $value = get_post_meta( $post-&gt;ID, '_product_settings', true );\n\n if ($value) {\n $product_settings = json_decode($value, true);\n }\n\n // Get available products so we can show them in select box\n $args = [\n 'post_type' =&gt; 'product',\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'id',\n 'order' =&gt; 'ASC'\n ];\n\n $products = new WP_Query($args);\n\n // As you can see, i have 5 product fields, this can be just about any number\n $max = 5;\n\n ?&gt;\n &lt;table&gt;\n &lt;?php for ($index = 0; $index &lt; $max; $index++) : ?&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;label for=\"product-&lt;?php echo $index + 1 ?&gt;-product\"&gt;&lt;?php _e( 'Product #' . ($index + 1), 'mytheme_textdomain' )?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;?php $productindex = 0; ?&gt;\n &lt;select name=\"product_settings[&lt;?php echo $index ?&gt;][product_id]\" id=\"product-&lt;?php echo ($index + 1) ?&gt;-product\"&gt;\n &lt;?php while($products-&gt;have_posts()) : $products-&gt;the_post(); $productindex++; ?&gt;\n &lt;option value=\"&lt;?php the_ID() ?&gt;\" &lt;?php echo (isset($product_settings[$index]['product_id']) &amp;&amp; (int)$product_settings[$index]['product_id'] === get_the_ID()) ? 'selected' : '' ?&gt;&gt;&lt;?php the_title() ?&gt;&lt;/option&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;label for=\"product-&lt;?php echo $index + 1 ?&gt;-price\"&gt;&lt;?php _e( 'Price', 'mytheme_textdomain' )?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;input \n name=\"product_settings[&lt;?php echo $index ?&gt;][price]\" \n type=\"text\" \n class=\"components-text-control__input\" \n id=\"product-&lt;?php echo ($index + 1) ?&gt;-price\"\n value=\"&lt;?php echo isset($product_settings[$index]['price']) ? $product_settings[$index]['price'] : '' ?&gt;\"&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endfor; ?&gt;\n &lt;/table&gt;\n &lt;?php\n\n // Don't forget about this, otherwise you will mess up with other data on the page\n wp_reset_postdata();\n\n}\n</code></pre>\n\n<p>Okay, here it comes with quite a bit of code. As other people in this thread suggested, you might find useful to extend this logic with javascript (such as select2.js). You can write that directly to HTML output of this function.</p>\n\n<h2>Saving the data</h2>\n\n<pre><code>\n/**\n * When the post is saved, saves our custom data.\n *\n * @param int $post_id The ID of the post being saved.\n */\nfunction se345571_product_settings_meta_box_data( $post_id, $post ) {\n\n // Check if our nonce is set.\n if ( ! isset( $_POST['se345571_product_settings_meta_box_nonce'] ) ) {\n return;\n }\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $_POST['se345571_product_settings_meta_box_nonce'], 'se345571_product_settings_meta_box_data' ) ) {\n return;\n }\n\n // If this is an autosave, our form has not been submitted, so we don't want to do anything.\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n /* OK, it's safe for us to save the data now. */\n\n // Make sure that it is set.\n if ( ! isset( $_POST['product_settings'] ) ) {\n return;\n }\n\n // HERE STARTS THE ACTUAL FUNCTIONALITY\n\n // Sanitize user input.\n $product_settings = json_encode( $_POST['product_settings'] );\n\n // Update the meta field in the database.\n update_post_meta( $post_id, '_product_settings', $product_settings );\n\n}\n\nadd_action( 'save_post', 'se345571_product_settings_meta_box_data', 10, 2 );\n</code></pre>\n\n<p>Here's another hook, save_post and our custom logic to it. Basically, it's 1:1 what's found on <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow noreferrer\">Codex</a> to the add_meta_box() function just swapped the POST field names.</p>\n\n<h2>Create metabox for product</h2>\n\n<p>You ask to display price the seller entered for different products, as i don't have any frontend here, i will show in the product admin page. But the same logic can be applied to show it on frontend for example.</p>\n\n<pre><code>\n/**\n * Adds a box to \"advanced\" part on the Seller edit screen.\n * - See the different screens defined in $screens array.\n */\nfunction se345571_add_product_meta_box() {\n\n $screens = array( 'product' );\n\n foreach ( $screens as $screen ) {\n\n // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params\n add_meta_box(\n 'product_settings_box', // HTML 'id' attribute of the edit screen section\n __( 'Seller prices', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user\n 'se345571_seller_prices_meta_box_callback', // Function that prints out the HTML for the edit screen section.\n $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment')\n );\n\n }\n}\nadd_action( 'add_meta_boxes', 'se345571_add_product_meta_box' );\n\n/**\n * Prints the box content.\n * \n * @param WP_Post $post The object for the current post/page.\n */\nfunction se345571_seller_prices_meta_box_callback( $post, $box ) {\n\n $product_id = get_the_ID();\n\n $args = [\n 'post_type' =&gt; 'seller',\n 'numberposts' =&gt; -1,\n 'meta_query' =&gt; [\n [\n 'key' =&gt; '_product_settings',\n 'value' =&gt; '\"product_id\":\"' .$product_id. '\"',\n 'compare' =&gt; 'LIKE',\n ]\n ]\n ];\n\n $sellers = new WP_Query($args);\n\n while($sellers-&gt;have_posts()) : $sellers-&gt;the_post();\n\n $seller_prices = json_decode(get_post_meta( get_the_ID(), '_product_settings', true ), true);\n\n $seller_prices_for_product = array_filter($seller_prices, function($element) use ($product_id) { \n if (isset($element['product_id'])) {\n return (int)$element['product_id'] === $product_id;\n }\n return false;\n });\n\n foreach($seller_prices_for_product as $price) :\n ?&gt;\n &lt;p&gt;\n &lt;?php the_title(); ?&gt; &lt;?php _e('for', 'mytheme_textdomain'); ?&gt; &lt;?php echo $price['price'] ?&gt;\n &lt;/p&gt;\n &lt;?php\n endforeach;\n\n endwhile;\n\n // Don't forget about this, otherwise you will mess up with other data on the page\n wp_reset_postdata();\n\n}\n</code></pre>\n\n<h2>Retrieving data</h2>\n\n<p>Finally when you need to grab your data on the frontend, you can go to template and use something like:</p>\n\n<pre><code>$value = get_post_meta( get_the_ID(), '_product_settings', true );\n$product_settings = json_decode($value, true);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_post_meta\" rel=\"nofollow noreferrer\">get_post_meta()</a> uses your current post ID, key of the field you want to retrieve (optional) and whatever you want only one or all meta (optional - not set returns all custom fields).</p>\n\n<p>This said, i'd actually go the plugin way (unless you are writing plugin yourself).</p>\n\n<h1>Plugin way</h1>\n\n<p>For cases like this, as other people pointed out, i'd pick <a href=\"http://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">Advanced Custom Fields</a> plugin. Which can basically do the same, what is coded above.</p>\n\n<p>Setting up the meta box is done via user interface.</p>\n\n<h2>Retrieving data</h2>\n\n<p>For retrieving data you use functions get_field() or the_field() - whatever you want to return the value or print the value right away (same naming convention as in WP all around).</p>\n\n<pre><code>get_field('your_field_name');\n</code></pre>\n\n<h3>Sources and further reading</h3>\n\n<p><a href=\"http://themefoundation.com/wordpress-meta-boxes-guide/\" rel=\"nofollow noreferrer\">http://themefoundation.com/wordpress-meta-boxes-guide/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_meta_box</a>\n<a href=\"http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/\" rel=\"nofollow noreferrer\">http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/</a></p>\n" } ]
2019/08/22
[ "https://wordpress.stackexchange.com/questions/345692", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143330/" ]
I've been searching a lot but haven't found one very simple thing: how to import a post created on Instagram and turn it into a Wordpress post, that is, copy one Instagram post (text + photo) and create a simple post on the Wordpress blog?
I assume you would like to end up with something like this: ![enter image description here](https://i.stack.imgur.com/IFMIU.png) Code way ======== If you want to put this logic in your template/plugin, as you state in your question, there is quite a bit of coding. You need to: * create custom post types * create metabox for seller * create content for metabox - that's called "callback" in the meta\_box docs * create logic that saves data from the meta box * create metabox for product * retrieve the data on front end Create custom post types ------------------------ I assume you already have this done, but let's register custom post types `product` and `seller` manually here: ### Products ('product') ``` /** * Post Type: Products. */ function se345571_register_cpt_product() { $labels = array( "name" => __( "Products", "mytheme_textdomain" ), "singular_name" => __( "Product", "mytheme_textdomain" ), ); $args = array( "label" => __( "Products", "mytheme_textdomain" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "delete_with_user" => false, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "product", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "product", $args ); } add_action( 'init', 'se345571_register_cpt_product' ); ``` ### Sellers ('seller') ``` /** * Post Type: Sellers. */ function se345571_register_cpt_seller() { $labels = array( "name" => __( "Sellers", "mytheme_textdomain" ), "singular_name" => __( "Seller", "mytheme_textdomain" ), ); $args = array( "label" => __( "Sellers", "mytheme_textdomain" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "delete_with_user" => false, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "seller", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "seller", $args ); } add_action( 'init', 'se345571_register_cpt_seller' ); ``` Create metabox for product -------------------------- ``` /** * Adds a box to "advanced" part on the Seller edit screen. * - See the different screens defined in $screens array. */ function se345571_add_seller_meta_box() { $screens = array( 'seller' ); foreach ( $screens as $screen ) { // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params add_meta_box( 'product_settings_box', // HTML 'id' attribute of the edit screen section __( 'Product settings', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user 'se345571_product_settings_meta_box_callback', // Function that prints out the HTML for the edit screen section. $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment') ); } } add_action( 'add_meta_boxes', 'se345571_add_seller_meta_box' ); ``` Here you can see, that add an action, which is called in [add\_meta\_boxes](https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes) - that means, when Wordpress is building up the meta boxes for writing screen, it's gonna call our custom `se345571_add_seller_meta_box()` function as well. Create content for metabox -------------------------- ``` /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function se345571_product_settings_meta_box_callback( $post, $box ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'se345571_product_settings_meta_box_data', 'se345571_product_settings_meta_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_product_settings', true ); if ($value) { $product_settings = json_decode($value, true); } // Get available products so we can show them in select box $args = [ 'post_type' => 'product', 'numberposts' => -1, 'orderby' => 'id', 'order' => 'ASC' ]; $products = new WP_Query($args); // As you can see, i have 5 product fields, this can be just about any number $max = 5; ?> <table> <?php for ($index = 0; $index < $max; $index++) : ?> <tr> <td> <label for="product-<?php echo $index + 1 ?>-product"><?php _e( 'Product #' . ($index + 1), 'mytheme_textdomain' )?></label> </td> <td> <?php $productindex = 0; ?> <select name="product_settings[<?php echo $index ?>][product_id]" id="product-<?php echo ($index + 1) ?>-product"> <?php while($products->have_posts()) : $products->the_post(); $productindex++; ?> <option value="<?php the_ID() ?>" <?php echo (isset($product_settings[$index]['product_id']) && (int)$product_settings[$index]['product_id'] === get_the_ID()) ? 'selected' : '' ?>><?php the_title() ?></option> <?php endwhile; ?> </select> </td> <td> <label for="product-<?php echo $index + 1 ?>-price"><?php _e( 'Price', 'mytheme_textdomain' )?></label> </td> <td> <input name="product_settings[<?php echo $index ?>][price]" type="text" class="components-text-control__input" id="product-<?php echo ($index + 1) ?>-price" value="<?php echo isset($product_settings[$index]['price']) ? $product_settings[$index]['price'] : '' ?>"> </td> </tr> <?php endfor; ?> </table> <?php // Don't forget about this, otherwise you will mess up with other data on the page wp_reset_postdata(); } ``` Okay, here it comes with quite a bit of code. As other people in this thread suggested, you might find useful to extend this logic with javascript (such as select2.js). You can write that directly to HTML output of this function. Saving the data --------------- ``` /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. */ function se345571_product_settings_meta_box_data( $post_id, $post ) { // Check if our nonce is set. if ( ! isset( $_POST['se345571_product_settings_meta_box_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['se345571_product_settings_meta_box_nonce'], 'se345571_product_settings_meta_box_data' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } /* OK, it's safe for us to save the data now. */ // Make sure that it is set. if ( ! isset( $_POST['product_settings'] ) ) { return; } // HERE STARTS THE ACTUAL FUNCTIONALITY // Sanitize user input. $product_settings = json_encode( $_POST['product_settings'] ); // Update the meta field in the database. update_post_meta( $post_id, '_product_settings', $product_settings ); } add_action( 'save_post', 'se345571_product_settings_meta_box_data', 10, 2 ); ``` Here's another hook, save\_post and our custom logic to it. Basically, it's 1:1 what's found on [Codex](https://codex.wordpress.org/Function_Reference/add_meta_box) to the add\_meta\_box() function just swapped the POST field names. Create metabox for product -------------------------- You ask to display price the seller entered for different products, as i don't have any frontend here, i will show in the product admin page. But the same logic can be applied to show it on frontend for example. ``` /** * Adds a box to "advanced" part on the Seller edit screen. * - See the different screens defined in $screens array. */ function se345571_add_product_meta_box() { $screens = array( 'product' ); foreach ( $screens as $screen ) { // https://codex.wordpress.org/Function_Reference/add_meta_box - add_meta_box(), see for further params add_meta_box( 'product_settings_box', // HTML 'id' attribute of the edit screen section __( 'Seller prices', 'mytheme_textdomain' ), // Title of the edit screen section, visible to user 'se345571_seller_prices_meta_box_callback', // Function that prints out the HTML for the edit screen section. $screen // Which writing screen ('post','page','dashboard','link','attachment','custom_post_type','comment') ); } } add_action( 'add_meta_boxes', 'se345571_add_product_meta_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function se345571_seller_prices_meta_box_callback( $post, $box ) { $product_id = get_the_ID(); $args = [ 'post_type' => 'seller', 'numberposts' => -1, 'meta_query' => [ [ 'key' => '_product_settings', 'value' => '"product_id":"' .$product_id. '"', 'compare' => 'LIKE', ] ] ]; $sellers = new WP_Query($args); while($sellers->have_posts()) : $sellers->the_post(); $seller_prices = json_decode(get_post_meta( get_the_ID(), '_product_settings', true ), true); $seller_prices_for_product = array_filter($seller_prices, function($element) use ($product_id) { if (isset($element['product_id'])) { return (int)$element['product_id'] === $product_id; } return false; }); foreach($seller_prices_for_product as $price) : ?> <p> <?php the_title(); ?> <?php _e('for', 'mytheme_textdomain'); ?> <?php echo $price['price'] ?> </p> <?php endforeach; endwhile; // Don't forget about this, otherwise you will mess up with other data on the page wp_reset_postdata(); } ``` Retrieving data --------------- Finally when you need to grab your data on the frontend, you can go to template and use something like: ``` $value = get_post_meta( get_the_ID(), '_product_settings', true ); $product_settings = json_decode($value, true); ``` [get\_post\_meta()](https://codex.wordpress.org/Function_Reference/get_post_meta) uses your current post ID, key of the field you want to retrieve (optional) and whatever you want only one or all meta (optional - not set returns all custom fields). This said, i'd actually go the plugin way (unless you are writing plugin yourself). Plugin way ========== For cases like this, as other people pointed out, i'd pick [Advanced Custom Fields](http://www.advancedcustomfields.com/) plugin. Which can basically do the same, what is coded above. Setting up the meta box is done via user interface. Retrieving data --------------- For retrieving data you use functions get\_field() or the\_field() - whatever you want to return the value or print the value right away (same naming convention as in WP all around). ``` get_field('your_field_name'); ``` ### Sources and further reading <http://themefoundation.com/wordpress-meta-boxes-guide/> <https://codex.wordpress.org/Function_Reference/add_meta_box> <http://www.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/>
345,743
<p>How can i make wordpress blog event titles clickable and direct to their respective post itself? Thank you!</p> <pre><code>&lt;li id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class( 'stm_post_info' ); ?&gt;&gt; &lt;?php if( get_the_title() ): ?&gt; &lt;h4 class="stripe_2"&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 345747, "author": "zain_ali", "author_id": 154909, "author_profile": "https://wordpress.stackexchange.com/users/154909", "pm_score": 1, "selected": true, "text": "<pre><code>&lt;li id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class( 'stm_post_info' ); ?&gt;&gt;\n&lt;?php if( get_the_title() ): ?&gt;\n &lt;h4 class=\"stripe_2\"&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\" &gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Please try this</p>\n" }, { "answer_id": 345768, "author": "nim", "author_id": 70070, "author_profile": "https://wordpress.stackexchange.com/users/70070", "pm_score": 1, "selected": false, "text": "<p>You can also try below one : </p>\n\n<pre><code>&lt;li id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class( 'stm_post_info' ); ?&gt;&gt;\n&lt;?php if( get_the_title() ): ?&gt; &lt;h4 class=\"stripe_2\"&gt;&lt;a href=\"&lt;?php echo get_permalink($post-&gt;ID);?&gt;\" &gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>that is more specific with particular post</p>\n" } ]
2019/08/23
[ "https://wordpress.stackexchange.com/questions/345743", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173989/" ]
How can i make wordpress blog event titles clickable and direct to their respective post itself? Thank you! ``` <li id="post-<?php the_ID(); ?>" <?php post_class( 'stm_post_info' ); ?>> <?php if( get_the_title() ): ?> <h4 class="stripe_2"><?php the_title(); ?></h4> <?php endif; ?> ```
``` <li id="post-<?php the_ID(); ?>" <?php post_class( 'stm_post_info' ); ?>> <?php if( get_the_title() ): ?> <h4 class="stripe_2"><a href="<?php the_permalink() ?>" ><?php the_title(); ?></a></h4> <?php endif; ?> ``` Please try this
345,753
<p>The website I am busy working on was built by another company that no longer supports Wordpress so I am looking for help. Below is the PHP for the search function. From the research Ive done it seems they have used the standard Wordpress code. The client has asked that the search only results in the related product. At the moment it is pulls everything with the key phase such as blog posts and titles. </p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="content pattern-background"&gt; &lt;div class="wrapper"&gt; &lt;h1&gt;Search results:&lt;/h1&gt; &lt;div class="product-list"&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="product-list__item" &gt; &lt;?php if(has_post_thumbnail()) { $url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID) ); } else { } ?&gt; &lt;a class="product__image" href="&lt;?php the_permalink() ?&gt;" style="background-image: url(&lt;?php echo $url; ?&gt;);"&gt; &lt;/a&gt; &lt;div class="product__details"&gt; &lt;h1&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;p&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt; &lt;div class="divider-solid"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;div &lt;?php post_class(); ?&gt; id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;h2&gt;Sorry, no items found.&lt;/h2&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>Can someone please guide me on what code to add or remove? or if there is documentation that can help. </p> <p>This is a very important client so I am nervous to just play around until I get it right. </p> <p>Thanks in advance</p>
[ { "answer_id": 345747, "author": "zain_ali", "author_id": 154909, "author_profile": "https://wordpress.stackexchange.com/users/154909", "pm_score": 1, "selected": true, "text": "<pre><code>&lt;li id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class( 'stm_post_info' ); ?&gt;&gt;\n&lt;?php if( get_the_title() ): ?&gt;\n &lt;h4 class=\"stripe_2\"&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\" &gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Please try this</p>\n" }, { "answer_id": 345768, "author": "nim", "author_id": 70070, "author_profile": "https://wordpress.stackexchange.com/users/70070", "pm_score": 1, "selected": false, "text": "<p>You can also try below one : </p>\n\n<pre><code>&lt;li id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class( 'stm_post_info' ); ?&gt;&gt;\n&lt;?php if( get_the_title() ): ?&gt; &lt;h4 class=\"stripe_2\"&gt;&lt;a href=\"&lt;?php echo get_permalink($post-&gt;ID);?&gt;\" &gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>that is more specific with particular post</p>\n" } ]
2019/08/23
[ "https://wordpress.stackexchange.com/questions/345753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173997/" ]
The website I am busy working on was built by another company that no longer supports Wordpress so I am looking for help. Below is the PHP for the search function. From the research Ive done it seems they have used the standard Wordpress code. The client has asked that the search only results in the related product. At the moment it is pulls everything with the key phase such as blog posts and titles. ``` <?php get_header(); ?> <div class="content pattern-background"> <div class="wrapper"> <h1>Search results:</h1> <div class="product-list"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="product-list__item" > <?php if(has_post_thumbnail()) { $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); } else { } ?> <a class="product__image" href="<?php the_permalink() ?>" style="background-image: url(<?php echo $url; ?>);"> </a> <div class="product__details"> <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1> <p><?php the_excerpt(); ?></p> <div class="divider-solid"></div> </div> </div> <?php endwhile; ?> <?php else : ?> <div <?php post_class(); ?> id="post-<?php the_ID(); ?>"> <h2>Sorry, no items found.</h2> </div> <?php endif; ?> </div> </div> <?php get_footer(); ?> ``` Can someone please guide me on what code to add or remove? or if there is documentation that can help. This is a very important client so I am nervous to just play around until I get it right. Thanks in advance
``` <li id="post-<?php the_ID(); ?>" <?php post_class( 'stm_post_info' ); ?>> <?php if( get_the_title() ): ?> <h4 class="stripe_2"><a href="<?php the_permalink() ?>" ><?php the_title(); ?></a></h4> <?php endif; ?> ``` Please try this
345,770
<p>I got all my website with a lot of internal cloaked links with a nofollow attribute. </p> <p>I need a function or filter to add inside <code>functions.php</code> that removes the <code>nofollow</code> attribute when the permalink contains a specific word es <code>"/link/pluto"</code>. Could you help me?</p> <p>Thanks for your support. Gp</p>
[ { "answer_id": 345979, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": true, "text": "<p>I wrote the following code to address ADDING tag attributes, but here is a version to help you locate, and remove <code>nofollow</code>:</p>\n\n<pre><code>add_filter( 'the_content', 'ex1_the_content_filter' );\nfunction ex1_the_content_filter($content) {\n // finds all links in your content with a nofollow\n preg_match_all('/\\&lt;a .*?\"nofollow\".*?a&gt;/',$content,$matches, PREG_SET_ORDER);\n\n // loop through all matches\n foreach($matches as $m){\n // potential link to be replaced...\n $toReplace = $m[0];\n\n // You can add whatever additional \"IF\" conditions you require to this one\n if (preg_match('/.*?\\/pluto.*?/',$toReplace)){\n // removes rel=\"nofollow\" from the current link\n $replacement = preg_replace('/(&lt;a.*?)(rel=\"nofollow\")(.*?a\\&gt;)/','$1$3',$toReplace);\n // replaces the current link with the $replacement string\n $content = str_ireplace($toReplace,$replacement,$content);\n }\n }\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 346031, "author": "Gmac", "author_id": 171547, "author_profile": "https://wordpress.stackexchange.com/users/171547", "pm_score": 1, "selected": false, "text": "<p>you are my hero. I solved my issue with internal links with your code. \nI had to modify it because i got many different rel inside my code rel=\"nofollow nooopener\" and rel=\"nooopener nofollow\" so i modify with this:</p>\n\n<pre><code>add_filter( 'the_content', 'ex1_the_content_filter' );\nfunction ex1_the_content_filter($content) {\n\n // finds all links in your content with a nofollow\n preg_match_all('/\\&lt;a .*?nofollow.*?a&gt;/',$content,$matches, PREG_SET_ORDER);\n\n // loop through all matches\n foreach($matches as $m){\n // potential link to be replaced...\n $toReplace = $m[0];\n\n // You can add whatever additional \"IF\" conditions you require to this one\n if (preg_match('/.*?\\/link.*?/',$toReplace)){\n // removes rel=\"nofollow\" from the current link\n $replacement = preg_replace('/(&lt;a.*?)(nofollow )(.*?a\\&gt;)/','$1$3',$toReplace);\n // replaces the current link with the $replacement string\n $content = str_ireplace($toReplace,$replacement,$content);\n }\n }\n return $content;\n}\n</code></pre>\n" } ]
2019/08/23
[ "https://wordpress.stackexchange.com/questions/345770", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171547/" ]
I got all my website with a lot of internal cloaked links with a nofollow attribute. I need a function or filter to add inside `functions.php` that removes the `nofollow` attribute when the permalink contains a specific word es `"/link/pluto"`. Could you help me? Thanks for your support. Gp
I wrote the following code to address ADDING tag attributes, but here is a version to help you locate, and remove `nofollow`: ``` add_filter( 'the_content', 'ex1_the_content_filter' ); function ex1_the_content_filter($content) { // finds all links in your content with a nofollow preg_match_all('/\<a .*?"nofollow".*?a>/',$content,$matches, PREG_SET_ORDER); // loop through all matches foreach($matches as $m){ // potential link to be replaced... $toReplace = $m[0]; // You can add whatever additional "IF" conditions you require to this one if (preg_match('/.*?\/pluto.*?/',$toReplace)){ // removes rel="nofollow" from the current link $replacement = preg_replace('/(<a.*?)(rel="nofollow")(.*?a\>)/','$1$3',$toReplace); // replaces the current link with the $replacement string $content = str_ireplace($toReplace,$replacement,$content); } } return $content; } ```
345,790
<p>I have this command that I'm using. I want it to use the template formating for the title but I can't figure out how to add it. I found this code online to strip everything and I added <code>&lt;?php wp_title(); ?&gt;</code> which shows the title but in plain text. How can I add it to match the rest of the site? smdpphiladelphia.com</p> <pre><code>&lt;?php /** * Template Name: Clean Page * This template will only display the content you entered in the page editor */ ?&gt; &lt;!DOCTYPE html&gt; &lt;html &lt;?php language_attributes(); ?&gt;&gt; &lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body&gt; &lt;?php wp_title(); ?&gt; &lt;?php while ( have_posts() ) : the_post(); the_content(); endwhile; ?&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 345793, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 0, "selected": false, "text": "<p>Basically, if I understand your question properly, you will want to look for another file named \"header.php\" (or \"page-{something}-header.php\" for a special header that only applies to a specific page type), which represents what is output by wp-head() (shown in your code).</p>\n\n<p>If you open header.php, you should find something like the following:</p>\n\n<pre><code>&lt;head&gt;\n &lt;title&gt; &lt;?php wp_title(); ?&gt;&lt;/title&gt;\n...\n</code></pre>\n\n<p>Keep in mind, this can get really complex. There are many themes with several conditional statements to modify your page title for any of several different circumstances. See the following example of how complex a fairly simple theme can make it.</p>\n\n<pre><code>&lt;?php\nif (function_exists('is_tag') &amp;&amp; is_tag()) { \n echo 'Tag Archive for &amp;quot;'.$tag.'&amp;quot; - '; \n} elseif (is_archive()) { \n wp_title(''); echo ' Archive - '; \n} elseif (is_search()) { \n echo 'Search for &amp;quot;'.wp_specialchars($s).'&amp;quot; - '; \n} elseif ( (!(is_404()) &amp;&amp; (is_single()) || (is_page()) ) &amp;&amp; !(is_front_page()) ) { \n wp_title(''); echo ' | '; \n} elseif (is_404()) { \n echo 'Not Found - '; \n}\nbloginfo('name');\n?&gt;\n&lt;/title&gt;\n</code></pre>\n\n<p>If you already like your theme, but just want to customize how the page titles are drawn, you may want to review this <a href=\"https://www.sanwebe.com/snippet/modify-wordpress-v4-4-header-title\" rel=\"nofollow noreferrer\">brief tutorial</a> for a better way to update page titles throughout your site, using <code>add_filter('document_title_parts','your_customizing_function')</code> (<a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\" rel=\"nofollow noreferrer\">documentation for document_title_parts</a>).</p>\n" }, { "answer_id": 345795, "author": "James E Andrews", "author_id": 174026, "author_profile": "https://wordpress.stackexchange.com/users/174026", "pm_score": -1, "selected": false, "text": "<p>I just figured out I could make it a lot easier by simpling adding teh custom attribute into the header code like so <code>&lt;h1 class=\"resurrect-entry-title resurrect-main-title\"&gt;</code></p>\n" } ]
2019/08/23
[ "https://wordpress.stackexchange.com/questions/345790", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174026/" ]
I have this command that I'm using. I want it to use the template formating for the title but I can't figure out how to add it. I found this code online to strip everything and I added `<?php wp_title(); ?>` which shows the title but in plain text. How can I add it to match the rest of the site? smdpphiladelphia.com ``` <?php /** * Template Name: Clean Page * This template will only display the content you entered in the page editor */ ?> <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php wp_head(); ?> </head> <body> <?php wp_title(); ?> <?php while ( have_posts() ) : the_post(); the_content(); endwhile; ?> <?php wp_footer(); ?> </body> </html> ```
Basically, if I understand your question properly, you will want to look for another file named "header.php" (or "page-{something}-header.php" for a special header that only applies to a specific page type), which represents what is output by wp-head() (shown in your code). If you open header.php, you should find something like the following: ``` <head> <title> <?php wp_title(); ?></title> ... ``` Keep in mind, this can get really complex. There are many themes with several conditional statements to modify your page title for any of several different circumstances. See the following example of how complex a fairly simple theme can make it. ``` <?php if (function_exists('is_tag') && is_tag()) { echo 'Tag Archive for &quot;'.$tag.'&quot; - '; } elseif (is_archive()) { wp_title(''); echo ' Archive - '; } elseif (is_search()) { echo 'Search for &quot;'.wp_specialchars($s).'&quot; - '; } elseif ( (!(is_404()) && (is_single()) || (is_page()) ) && !(is_front_page()) ) { wp_title(''); echo ' | '; } elseif (is_404()) { echo 'Not Found - '; } bloginfo('name'); ?> </title> ``` If you already like your theme, but just want to customize how the page titles are drawn, you may want to review this [brief tutorial](https://www.sanwebe.com/snippet/modify-wordpress-v4-4-header-title) for a better way to update page titles throughout your site, using `add_filter('document_title_parts','your_customizing_function')` ([documentation for document\_title\_parts](https://developer.wordpress.org/reference/hooks/document_title_parts/)).
345,824
<p>I'm currently using <code>&lt;?php the_post_thumbnail('250px', array('class'=&gt;"review-siteshot", 'alt' =&gt; get_the_title() )); ?&gt;</code></p> <p>I know that <code>'alt' =&gt; "review"</code> will output review as all text.</p> <p>I'm trying to use <code>get_the_title()</code> along with "review" so that I get <strong>title-text review</strong> as my alt text for the thumbnail.</p>
[ { "answer_id": 345829, "author": "Lazar Momcilovic", "author_id": 138412, "author_profile": "https://wordpress.stackexchange.com/users/138412", "pm_score": 3, "selected": true, "text": "<p>Like this:</p>\n\n<pre><code>'alt' =&gt; get_the_title(). ' review'\n</code></pre>\n\n<p>So the full code would be: </p>\n\n<pre><code>&lt;?php the_post_thumbnail('250px', array('class'=&gt;\"review-siteshot\", 'alt' =&gt; get_the_title(). ' review' )); ?&gt;\n</code></pre>\n" }, { "answer_id": 345830, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>The function <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> can be used to append a string and to return instead of echoing:</p>\n\n<pre><code>the_title( '', ' review', 0 )\n</code></pre>\n\n<p>In case stripping tags and escaping is necessary, the function <a href=\"https://developer.wordpress.org/reference/functions/the_title_attribute/\" rel=\"nofollow noreferrer\"><code>the_title_attribute()</code></a> can be used:</p>\n\n<pre><code>the_title_attribute( [ 'after' =&gt; ' review', 'echo' =&gt; 0 ] )\n</code></pre>\n" } ]
2019/08/24
[ "https://wordpress.stackexchange.com/questions/345824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145504/" ]
I'm currently using `<?php the_post_thumbnail('250px', array('class'=>"review-siteshot", 'alt' => get_the_title() )); ?>` I know that `'alt' => "review"` will output review as all text. I'm trying to use `get_the_title()` along with "review" so that I get **title-text review** as my alt text for the thumbnail.
Like this: ``` 'alt' => get_the_title(). ' review' ``` So the full code would be: ``` <?php the_post_thumbnail('250px', array('class'=>"review-siteshot", 'alt' => get_the_title(). ' review' )); ?> ```
345,908
<p>Since my theme's font <a href="https://wordpress.stackexchange.com/q/344767/64282">doesn't support my language</a>, I add this code to style.css to change the font. It does work:</p> <pre><code>@font-face { font-family: 'new-baskerville'; font-style: normal; src: url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot'); src: local('new-baskerville'), url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot') format('embedded-opentype'), url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.woff') format('woff'); } .new-baskerville{font-family: 'new-baskerville' !important;} body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span, font-size: 20 em;{ font-family: 'new-baskerville' !important; } </code></pre> <p>However, the font-size attribute doesn't work. Even if I set it as 20 em, it still the same size. Why does this happen?</p> <p><br></p> <p><sup> (That code is generated by <a href="https://dineshkarki.com.np/use-any-font" rel="nofollow noreferrer">Use Any Font</a> plugin) </sup></p>
[ { "answer_id": 345955, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 1, "selected": false, "text": "<p>I don't want to sound too critical, but you might want to review <a href=\"https://www.w3schools.com/cssref/css3_pr_font-face_rule.asp\" rel=\"nofollow noreferrer\">how to properly introduce a new font</a>, and apply font styles content. The declaration that you presented appears to have a couple of issues:</p>\n\n<ul>\n<li>Using \".new-baskerville\" would cause everything with the class \"new-baskerville\" (and <strong><em>ONLY</em></strong> those with that class) to appear with font-family of new-baskerville. </li>\n<li>Using \"!Important\" in this context can cause issues. It should really only be used to override a locally defined, or \"inline\" style.</li>\n<li><p>The following line is completely malformed:</p>\n\n<pre><code>body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span, font-size: 20 em;{\n font-family: 'new-baskerville' !important;\n}\n</code></pre></li>\n<li><p>I believe you were trying to do something more like the following code example, but that is still problematic, because it applies the same font-size to everything:</p>\n\n<pre><code>body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span{\n font-size: 20 em;\n font-family: \"new-baskerville\",helvetica, san-serif; /* providing fallbacks for browsers that may not be able to interpret new-baskerville */\n }\n</code></pre></li>\n</ul>\n\n<p>Instead, individual items should have their own relative font-sizes. Also, \"em\" sizes are relative. So, you might start by applying a default font size to the body. This will cause all the other font-size declarations (\"em\", \"rem\", etc) to adjust \"relative to\" the body's default. I would recommend changes similar to this:</p>\n\n<pre><code>@font-face {\n font-family: 'new-baskerville';\n font-style: normal;\n src: url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot');\n src: url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot') format('embedded-opentype'), \n url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.woff') format('woff');\n }\n\n/* Provide a base font size for the entire page */\nbody { \n font-family: 'new-baskerville',garamond,san-serif;\n font-size: 14px; \n}\n\nh1 { font-size: 2em; font-weight: bold; }\nh2 { font-size: 1.75em; font-weight: bold; }\nh3 { font-size: 1.5em; font-weight: bold; }\nh4 { font-size: 1.45em; font-weight: bold; font-style: italic;}\n... etc...\n</code></pre>\n\n<p><strong>EDIT:</strong> Something you might want to follow up on ... Not all web servers are setup with mime types configured for eot, woff, woff2, etc. You might need to <a href=\"https://webplatform.github.io/docs/tutorials/configuring_mimetypes_on_the_server/\" rel=\"nofollow noreferrer\">setup mime types</a> for your server. BTW ... the author doesn't mention woff2. That mime type is font/woff2.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 346131, "author": "Justin Waulters", "author_id": 137235, "author_profile": "https://wordpress.stackexchange.com/users/137235", "pm_score": -1, "selected": false, "text": "<p>You have at least one syntax error in your code.\nStart by changing this part:</p>\n\n<pre><code>body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span, font-size: 20 em;{\n font-family: 'new-baskerville' !important;\n}\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span {\n font-family: 'new-baskerville' !important;\n font-size: 20 em;\n}\n</code></pre>\n\n<p>The styles have to be inside the brackets. The <code>font-size</code> style was outside the brackets in the list of elements to target. The syntax error (probably from the <code>;</code>) caused everything inside the bracket fail.</p>\n" } ]
2019/08/26
[ "https://wordpress.stackexchange.com/questions/345908", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64282/" ]
Since my theme's font [doesn't support my language](https://wordpress.stackexchange.com/q/344767/64282), I add this code to style.css to change the font. It does work: ``` @font-face { font-family: 'new-baskerville'; font-style: normal; src: url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot'); src: local('new-baskerville'), url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot') format('embedded-opentype'), url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.woff') format('woff'); } .new-baskerville{font-family: 'new-baskerville' !important;} body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span, font-size: 20 em;{ font-family: 'new-baskerville' !important; } ``` However, the font-size attribute doesn't work. Even if I set it as 20 em, it still the same size. Why does this happen? (That code is generated by [Use Any Font](https://dineshkarki.com.np/use-any-font) plugin)
I don't want to sound too critical, but you might want to review [how to properly introduce a new font](https://www.w3schools.com/cssref/css3_pr_font-face_rule.asp), and apply font styles content. The declaration that you presented appears to have a couple of issues: * Using ".new-baskerville" would cause everything with the class "new-baskerville" (and ***ONLY*** those with that class) to appear with font-family of new-baskerville. * Using "!Important" in this context can cause issues. It should really only be used to override a locally defined, or "inline" style. * The following line is completely malformed: ``` body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span, font-size: 20 em;{ font-family: 'new-baskerville' !important; } ``` * I believe you were trying to do something more like the following code example, but that is still problematic, because it applies the same font-size to everything: ``` body, h1, h2, h3, h4, h5, h6, p, blockquote, li, a, #menu-main-menu li a, #menu-main-menu li span{ font-size: 20 em; font-family: "new-baskerville",helvetica, san-serif; /* providing fallbacks for browsers that may not be able to interpret new-baskerville */ } ``` Instead, individual items should have their own relative font-sizes. Also, "em" sizes are relative. So, you might start by applying a default font size to the body. This will cause all the other font-size declarations ("em", "rem", etc) to adjust "relative to" the body's default. I would recommend changes similar to this: ``` @font-face { font-family: 'new-baskerville'; font-style: normal; src: url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot'); src: url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.eot') format('embedded-opentype'), url('/wp-content/uploads/useanyfont/190811081519New-Baskerville.woff') format('woff'); } /* Provide a base font size for the entire page */ body { font-family: 'new-baskerville',garamond,san-serif; font-size: 14px; } h1 { font-size: 2em; font-weight: bold; } h2 { font-size: 1.75em; font-weight: bold; } h3 { font-size: 1.5em; font-weight: bold; } h4 { font-size: 1.45em; font-weight: bold; font-style: italic;} ... etc... ``` **EDIT:** Something you might want to follow up on ... Not all web servers are setup with mime types configured for eot, woff, woff2, etc. You might need to [setup mime types](https://webplatform.github.io/docs/tutorials/configuring_mimetypes_on_the_server/) for your server. BTW ... the author doesn't mention woff2. That mime type is font/woff2. Hope this helps!
345,916
<p>This is a rather specific and weird issue that is really bothering me now. </p> <p>Here's the setup. <br> - I'm using Elementor Pro and I've created a single page template. <br> - I have four shortcode widgets on the page that is hooked up to ACF text fields. <br> - The ACF text field takes a shortcode source of an iframe from airtables as the argument (eg [airtable-view if='src xxx']. I have created the shortcode function and added it as a plugin. This works properly (code below). <br></p> <p>The problem is this. </p> <p>When I paste the four shortcodes directly in the template, all four of them are rendered properly in the final page. But when I use ACF and add the exact same shortcodes into the respective fields, only the first and third iframes are rendered. The second and third are ignored (the elements are not present even when I checked using the Inspector). Similarly, if I remove the first field, only the second and fourth are rendered. If the second one is removed, only the third one is rendered (the fourth one is skipped). And finally if all three are removed and only the fourth one is present, the fouth one is rendered but everything after that is not rendered. </p> <p>I've tried everything I know to figure out what the issue but I think it's something related to the way Wordpress or elementor renders the pages from the template. I tried to isolate the problem by creating just four shortcode widgets on another template page and doing the same and this exact issue occurs. This looks like some async issue and I honestly have no idea how this works. If someone can figure it out, any help would be appreciated. The debug logs don't report anything related to this. </p> <p>Here's my shortcode callback (it's used as a plugin). </p> <pre><code>function shortcodeToIframe($atts){ $iframe = shortcode_atts(array('if' =&gt; 'Default'), $atts); $html = '&lt;div class = "airtable-view"&gt;' .'&lt;iframe class="airtable-embed"'. $iframe['if'] . '&lt;/iframe&gt;' . '&lt;/div&gt;'; return $html; } add_shortcode('airtable-view', 'shortcodeToIframe'); </code></pre> <p>The shortcode I use is this </p> <pre><code>[airtable-view if = 'src = "https://airtables..."&gt;'] </code></pre>
[ { "answer_id": 346049, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result,</p>\n\n<pre><code>&lt;div&gt;&lt;iframe class=\"airtable-embed\" &amp;#8217;src&lt;=\"\" iframe=\"\"&gt;&lt;/div&gt;\n&lt;div class = \"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\"&amp;#8217;src&lt;/iframe&gt;\n</code></pre>\n\n<p>It might be better idea to format your shortcode callback function along these lines,</p>\n\n<pre><code>function shortcodeToIframe($atts){\n\n $default = array(\n 'src' =&gt; '',\n );\n $atts = shortcode_atts( $default, $atts );\n\n if ( ! $atts['src'] ) {\n return;\n }\n\n return sprintf(\n '&lt;div class=\"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\" src=\"%s\"&gt;&lt;/iframe&gt;&lt;/div&gt;',\n esc_url( $atts['src'] )\n );\n\n}\n</code></pre>\n\n<p>And then use the shortcode like this,</p>\n\n<pre><code>[airtable-view src=\"http://www.domain.com\"]\n</code></pre>\n\n<p>This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.</p>\n" }, { "answer_id": 369364, "author": "Mr Sonnentag", "author_id": 190253, "author_profile": "https://wordpress.stackexchange.com/users/190253", "pm_score": 0, "selected": false, "text": "<p>As a work around you can make it work with the Elementor Shortcode Widget and for example this iFrame Shortcode Plugin: <a href=\"https://de.wordpress.org/plugins/iframe/\" rel=\"nofollow noreferrer\">https://de.wordpress.org/plugins/iframe/</a></p>\n<p>Then in the Elementor Template you make use of the before and after parameters of the Shortocode Widget with a Custom field, like this:</p>\n<p>before: [iframe src=&quot;\nafter: &quot; width=&quot;100%&quot; height=&quot;500&quot;]</p>\n<p>And in the Custom field, in the Backend just only put the iFrame Url.</p>\n<p>See Screenshot here: <a href=\"https://i.stack.imgur.com/JMMmc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JMMmc.png\" alt=\"enter image description here\" /></a></p>\n<p>Alternative: use a Crocoblock Repeater Field, there is iframe Output possible: <a href=\"https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/\" rel=\"nofollow noreferrer\">https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/</a></p>\n<p>A bit off topic (not really iFrame related): This is really powerfull, for example i managed to get dynamic Instagram Posts based on Usernames in User Profile Pages.</p>\n" } ]
2019/08/26
[ "https://wordpress.stackexchange.com/questions/345916", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/173882/" ]
This is a rather specific and weird issue that is really bothering me now. Here's the setup. - I'm using Elementor Pro and I've created a single page template. - I have four shortcode widgets on the page that is hooked up to ACF text fields. - The ACF text field takes a shortcode source of an iframe from airtables as the argument (eg [airtable-view if='src xxx']. I have created the shortcode function and added it as a plugin. This works properly (code below). The problem is this. When I paste the four shortcodes directly in the template, all four of them are rendered properly in the final page. But when I use ACF and add the exact same shortcodes into the respective fields, only the first and third iframes are rendered. The second and third are ignored (the elements are not present even when I checked using the Inspector). Similarly, if I remove the first field, only the second and fourth are rendered. If the second one is removed, only the third one is rendered (the fourth one is skipped). And finally if all three are removed and only the fourth one is present, the fouth one is rendered but everything after that is not rendered. I've tried everything I know to figure out what the issue but I think it's something related to the way Wordpress or elementor renders the pages from the template. I tried to isolate the problem by creating just four shortcode widgets on another template page and doing the same and this exact issue occurs. This looks like some async issue and I honestly have no idea how this works. If someone can figure it out, any help would be appreciated. The debug logs don't report anything related to this. Here's my shortcode callback (it's used as a plugin). ``` function shortcodeToIframe($atts){ $iframe = shortcode_atts(array('if' => 'Default'), $atts); $html = '<div class = "airtable-view">' .'<iframe class="airtable-embed"'. $iframe['if'] . '</iframe>' . '</div>'; return $html; } add_shortcode('airtable-view', 'shortcodeToIframe'); ``` The shortcode I use is this ``` [airtable-view if = 'src = "https://airtables...">'] ```
The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result, ``` <div><iframe class="airtable-embed" &#8217;src<="" iframe=""></div> <div class = "airtable-view"><iframe class="airtable-embed"&#8217;src</iframe> ``` It might be better idea to format your shortcode callback function along these lines, ``` function shortcodeToIframe($atts){ $default = array( 'src' => '', ); $atts = shortcode_atts( $default, $atts ); if ( ! $atts['src'] ) { return; } return sprintf( '<div class="airtable-view"><iframe class="airtable-embed" src="%s"></iframe></div>', esc_url( $atts['src'] ) ); } ``` And then use the shortcode like this, ``` [airtable-view src="http://www.domain.com"] ``` This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.
345,928
<p>I am creating a contact form on WordPress site.</p> <p>The form is perfectly working with following code:</p> <p><code> //validate email if(!filter_var($email, FILTER_VALIDATE_EMAIL)) my_contact_form_generate_response("error", $email_invalid); else //email is valid { //validate presence of name and message if(empty($name) || empty($topic) || empty($message)){ my_contact_form_generate_response("error", $missing_content); } else //ready to go! { $sent = wp_mail($to, $subject, strip_tags($message), $headers); if($sent) my_contact_form_generate_response("success", $message_sent); //message sent! else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent } } } } else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content); ?> </code></p> <p>However, this sends email with 'From' name as 'WordPress'. </p> <p>I want to customize 'WordPress' with sender name for which I am using $name variable, so that I got to know who send me email without opening it.</p> <p>Any help will be appreciated. </p>
[ { "answer_id": 346049, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result,</p>\n\n<pre><code>&lt;div&gt;&lt;iframe class=\"airtable-embed\" &amp;#8217;src&lt;=\"\" iframe=\"\"&gt;&lt;/div&gt;\n&lt;div class = \"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\"&amp;#8217;src&lt;/iframe&gt;\n</code></pre>\n\n<p>It might be better idea to format your shortcode callback function along these lines,</p>\n\n<pre><code>function shortcodeToIframe($atts){\n\n $default = array(\n 'src' =&gt; '',\n );\n $atts = shortcode_atts( $default, $atts );\n\n if ( ! $atts['src'] ) {\n return;\n }\n\n return sprintf(\n '&lt;div class=\"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\" src=\"%s\"&gt;&lt;/iframe&gt;&lt;/div&gt;',\n esc_url( $atts['src'] )\n );\n\n}\n</code></pre>\n\n<p>And then use the shortcode like this,</p>\n\n<pre><code>[airtable-view src=\"http://www.domain.com\"]\n</code></pre>\n\n<p>This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.</p>\n" }, { "answer_id": 369364, "author": "Mr Sonnentag", "author_id": 190253, "author_profile": "https://wordpress.stackexchange.com/users/190253", "pm_score": 0, "selected": false, "text": "<p>As a work around you can make it work with the Elementor Shortcode Widget and for example this iFrame Shortcode Plugin: <a href=\"https://de.wordpress.org/plugins/iframe/\" rel=\"nofollow noreferrer\">https://de.wordpress.org/plugins/iframe/</a></p>\n<p>Then in the Elementor Template you make use of the before and after parameters of the Shortocode Widget with a Custom field, like this:</p>\n<p>before: [iframe src=&quot;\nafter: &quot; width=&quot;100%&quot; height=&quot;500&quot;]</p>\n<p>And in the Custom field, in the Backend just only put the iFrame Url.</p>\n<p>See Screenshot here: <a href=\"https://i.stack.imgur.com/JMMmc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JMMmc.png\" alt=\"enter image description here\" /></a></p>\n<p>Alternative: use a Crocoblock Repeater Field, there is iframe Output possible: <a href=\"https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/\" rel=\"nofollow noreferrer\">https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/</a></p>\n<p>A bit off topic (not really iFrame related): This is really powerfull, for example i managed to get dynamic Instagram Posts based on Usernames in User Profile Pages.</p>\n" } ]
2019/08/26
[ "https://wordpress.stackexchange.com/questions/345928", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69221/" ]
I am creating a contact form on WordPress site. The form is perfectly working with following code: `//validate email if(!filter_var($email, FILTER_VALIDATE_EMAIL)) my_contact_form_generate_response("error", $email_invalid); else //email is valid { //validate presence of name and message if(empty($name) || empty($topic) || empty($message)){ my_contact_form_generate_response("error", $missing_content); } else //ready to go! { $sent = wp_mail($to, $subject, strip_tags($message), $headers); if($sent) my_contact_form_generate_response("success", $message_sent); //message sent! else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent } } } } else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content); ?>` However, this sends email with 'From' name as 'WordPress'. I want to customize 'WordPress' with sender name for which I am using $name variable, so that I got to know who send me email without opening it. Any help will be appreciated.
The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result, ``` <div><iframe class="airtable-embed" &#8217;src<="" iframe=""></div> <div class = "airtable-view"><iframe class="airtable-embed"&#8217;src</iframe> ``` It might be better idea to format your shortcode callback function along these lines, ``` function shortcodeToIframe($atts){ $default = array( 'src' => '', ); $atts = shortcode_atts( $default, $atts ); if ( ! $atts['src'] ) { return; } return sprintf( '<div class="airtable-view"><iframe class="airtable-embed" src="%s"></iframe></div>', esc_url( $atts['src'] ) ); } ``` And then use the shortcode like this, ``` [airtable-view src="http://www.domain.com"] ``` This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.
345,961
<p>I would like to add a post_meta (test_meta_1234) field to an existing CPT (organizer) of an external plugin.</p> <p>With register_meta() it doesn't work. But a taxonomy I can add to the same CPT with register_taxonomy().</p> <p>Code Sample:</p> <pre><code>register_meta('post', 'test_meta_1234', array( 'object_subtype' =&gt; 'organizer', 'show_in_rest' =&gt; true, 'single' =&gt; true, 'type' =&gt; 'string', 'description' =&gt; 'Test Meta 1234', ) ); register_taxonomy( 'genre', 'organizer', array( 'label' =&gt; __( 'Genre' ), 'rewrite' =&gt; array( 'slug' =&gt; 'genre' ), 'hierarchical' =&gt; true, ) ); $otherPostTypesFull = new stdClass(); $otherPostTypes = get_post_types(); foreach($otherPostTypes as $postType =&gt; $postTypeSlug){ $args = array( 'post_type' =&gt; $postTypeSlug, 'numberposts' =&gt; -1 ); foreach(get_posts( $args ) as $faPosts){ $otherPostTypesFull-&gt;$postTypeSlug-&gt;post_meta = get_post_custom($faPosts-&gt;ID); $otherPostTypesFull-&gt;$postTypeSlug-&gt;taxonomies = get_object_taxonomies( $postTypeSlug, 'objects' ); } } var_dump($otherPostTypesFull); </code></pre> <p>The taxonomy is added to the CPT, but not the post_meta (test_meta_1234).</p> <p>Why can't I see the post_meta field with get_post_custom()?</p> <hr> <p>update 1:</p> <p>The CPT did not support 'custom-fields', so now first check and add this:</p> <pre><code>`if(!post_type_supports( 'organizer', 'custom-fields' )){ add_post_type_support( 'organizer', 'custom-fields' ); }` </code></pre> <p>The custom-field 'test_meta_1234' is still not registered yet. Why that?</p>
[ { "answer_id": 346049, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result,</p>\n\n<pre><code>&lt;div&gt;&lt;iframe class=\"airtable-embed\" &amp;#8217;src&lt;=\"\" iframe=\"\"&gt;&lt;/div&gt;\n&lt;div class = \"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\"&amp;#8217;src&lt;/iframe&gt;\n</code></pre>\n\n<p>It might be better idea to format your shortcode callback function along these lines,</p>\n\n<pre><code>function shortcodeToIframe($atts){\n\n $default = array(\n 'src' =&gt; '',\n );\n $atts = shortcode_atts( $default, $atts );\n\n if ( ! $atts['src'] ) {\n return;\n }\n\n return sprintf(\n '&lt;div class=\"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\" src=\"%s\"&gt;&lt;/iframe&gt;&lt;/div&gt;',\n esc_url( $atts['src'] )\n );\n\n}\n</code></pre>\n\n<p>And then use the shortcode like this,</p>\n\n<pre><code>[airtable-view src=\"http://www.domain.com\"]\n</code></pre>\n\n<p>This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.</p>\n" }, { "answer_id": 369364, "author": "Mr Sonnentag", "author_id": 190253, "author_profile": "https://wordpress.stackexchange.com/users/190253", "pm_score": 0, "selected": false, "text": "<p>As a work around you can make it work with the Elementor Shortcode Widget and for example this iFrame Shortcode Plugin: <a href=\"https://de.wordpress.org/plugins/iframe/\" rel=\"nofollow noreferrer\">https://de.wordpress.org/plugins/iframe/</a></p>\n<p>Then in the Elementor Template you make use of the before and after parameters of the Shortocode Widget with a Custom field, like this:</p>\n<p>before: [iframe src=&quot;\nafter: &quot; width=&quot;100%&quot; height=&quot;500&quot;]</p>\n<p>And in the Custom field, in the Backend just only put the iFrame Url.</p>\n<p>See Screenshot here: <a href=\"https://i.stack.imgur.com/JMMmc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JMMmc.png\" alt=\"enter image description here\" /></a></p>\n<p>Alternative: use a Crocoblock Repeater Field, there is iframe Output possible: <a href=\"https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/\" rel=\"nofollow noreferrer\">https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/</a></p>\n<p>A bit off topic (not really iFrame related): This is really powerfull, for example i managed to get dynamic Instagram Posts based on Usernames in User Profile Pages.</p>\n" } ]
2019/08/26
[ "https://wordpress.stackexchange.com/questions/345961", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133541/" ]
I would like to add a post\_meta (test\_meta\_1234) field to an existing CPT (organizer) of an external plugin. With register\_meta() it doesn't work. But a taxonomy I can add to the same CPT with register\_taxonomy(). Code Sample: ``` register_meta('post', 'test_meta_1234', array( 'object_subtype' => 'organizer', 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'description' => 'Test Meta 1234', ) ); register_taxonomy( 'genre', 'organizer', array( 'label' => __( 'Genre' ), 'rewrite' => array( 'slug' => 'genre' ), 'hierarchical' => true, ) ); $otherPostTypesFull = new stdClass(); $otherPostTypes = get_post_types(); foreach($otherPostTypes as $postType => $postTypeSlug){ $args = array( 'post_type' => $postTypeSlug, 'numberposts' => -1 ); foreach(get_posts( $args ) as $faPosts){ $otherPostTypesFull->$postTypeSlug->post_meta = get_post_custom($faPosts->ID); $otherPostTypesFull->$postTypeSlug->taxonomies = get_object_taxonomies( $postTypeSlug, 'objects' ); } } var_dump($otherPostTypesFull); ``` The taxonomy is added to the CPT, but not the post\_meta (test\_meta\_1234). Why can't I see the post\_meta field with get\_post\_custom()? --- update 1: The CPT did not support 'custom-fields', so now first check and add this: ``` `if(!post_type_supports( 'organizer', 'custom-fields' )){ add_post_type_support( 'organizer', 'custom-fields' ); }` ``` The custom-field 'test\_meta\_1234' is still not registered yet. Why that?
The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result, ``` <div><iframe class="airtable-embed" &#8217;src<="" iframe=""></div> <div class = "airtable-view"><iframe class="airtable-embed"&#8217;src</iframe> ``` It might be better idea to format your shortcode callback function along these lines, ``` function shortcodeToIframe($atts){ $default = array( 'src' => '', ); $atts = shortcode_atts( $default, $atts ); if ( ! $atts['src'] ) { return; } return sprintf( '<div class="airtable-view"><iframe class="airtable-embed" src="%s"></iframe></div>', esc_url( $atts['src'] ) ); } ``` And then use the shortcode like this, ``` [airtable-view src="http://www.domain.com"] ``` This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.
345,962
<p>I'm trying to set up a function to fix common content errors on a site. I want to take an array of post fields <code>$check_fields</code> and check them for common errors as set up in an array called <code>$replacement_terms</code>.</p> <p>I have the following so far:</p> <pre><code>$check_fields = array( "post_title", "post_content" ); $replacement_terms = array( "™™,™", "®®,®", " , " ); foreach ( $check_fields as $field ) { foreach ( $replacement_terms as $term ) { $replacement = explode( ",", $field ) $fixed_content = str_replace( $replacement["0"], $replacement["1"], $field); update_post_meta( $post_id, $field, $fixed_content ); } } </code></pre> <p>Any tips how I can get it working properly/optimize it a bit?</p>
[ { "answer_id": 346049, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result,</p>\n\n<pre><code>&lt;div&gt;&lt;iframe class=\"airtable-embed\" &amp;#8217;src&lt;=\"\" iframe=\"\"&gt;&lt;/div&gt;\n&lt;div class = \"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\"&amp;#8217;src&lt;/iframe&gt;\n</code></pre>\n\n<p>It might be better idea to format your shortcode callback function along these lines,</p>\n\n<pre><code>function shortcodeToIframe($atts){\n\n $default = array(\n 'src' =&gt; '',\n );\n $atts = shortcode_atts( $default, $atts );\n\n if ( ! $atts['src'] ) {\n return;\n }\n\n return sprintf(\n '&lt;div class=\"airtable-view\"&gt;&lt;iframe class=\"airtable-embed\" src=\"%s\"&gt;&lt;/iframe&gt;&lt;/div&gt;',\n esc_url( $atts['src'] )\n );\n\n}\n</code></pre>\n\n<p>And then use the shortcode like this,</p>\n\n<pre><code>[airtable-view src=\"http://www.domain.com\"]\n</code></pre>\n\n<p>This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.</p>\n" }, { "answer_id": 369364, "author": "Mr Sonnentag", "author_id": 190253, "author_profile": "https://wordpress.stackexchange.com/users/190253", "pm_score": 0, "selected": false, "text": "<p>As a work around you can make it work with the Elementor Shortcode Widget and for example this iFrame Shortcode Plugin: <a href=\"https://de.wordpress.org/plugins/iframe/\" rel=\"nofollow noreferrer\">https://de.wordpress.org/plugins/iframe/</a></p>\n<p>Then in the Elementor Template you make use of the before and after parameters of the Shortocode Widget with a Custom field, like this:</p>\n<p>before: [iframe src=&quot;\nafter: &quot; width=&quot;100%&quot; height=&quot;500&quot;]</p>\n<p>And in the Custom field, in the Backend just only put the iFrame Url.</p>\n<p>See Screenshot here: <a href=\"https://i.stack.imgur.com/JMMmc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JMMmc.png\" alt=\"enter image description here\" /></a></p>\n<p>Alternative: use a Crocoblock Repeater Field, there is iframe Output possible: <a href=\"https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/\" rel=\"nofollow noreferrer\">https://crocoblock.com/knowledge-base/articles/jetengine-dynamic-repeater-widget-overview/</a></p>\n<p>A bit off topic (not really iFrame related): This is really powerfull, for example i managed to get dynamic Instagram Posts based on Usernames in User Profile Pages.</p>\n" } ]
2019/08/26
[ "https://wordpress.stackexchange.com/questions/345962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109355/" ]
I'm trying to set up a function to fix common content errors on a site. I want to take an array of post fields `$check_fields` and check them for common errors as set up in an array called `$replacement_terms`. I have the following so far: ``` $check_fields = array( "post_title", "post_content" ); $replacement_terms = array( "™™,™", "®®,®", " , " ); foreach ( $check_fields as $field ) { foreach ( $replacement_terms as $term ) { $replacement = explode( ",", $field ) $fixed_content = str_replace( $replacement["0"], $replacement["1"], $field); update_post_meta( $post_id, $field, $fixed_content ); } } ``` Any tips how I can get it working properly/optimize it a bit?
The iframes not showing is probably caused by the shortcode parser freaking out by how you pass the parameter to it. I tested your code example / shortcode (added 4 times to the post content) and here's what I got as a result, ``` <div><iframe class="airtable-embed" &#8217;src<="" iframe=""></div> <div class = "airtable-view"><iframe class="airtable-embed"&#8217;src</iframe> ``` It might be better idea to format your shortcode callback function along these lines, ``` function shortcodeToIframe($atts){ $default = array( 'src' => '', ); $atts = shortcode_atts( $default, $atts ); if ( ! $atts['src'] ) { return; } return sprintf( '<div class="airtable-view"><iframe class="airtable-embed" src="%s"></iframe></div>', esc_url( $atts['src'] ) ); } ``` And then use the shortcode like this, ``` [airtable-view src="http://www.domain.com"] ``` This would make the parameter explicit and there would be no extra quotes, double quotes, or equals signs to confuse the shortcode parser.
346,052
<p>I have a custom Submenu page with my post type in which I am querying all posts and adding custom textareas and dropdowns that will repeat with each entry. The id and name for each field is the same accept the end of it is hyphenated with the post ID at the end. I want to be able to save the values entered in these fields and preferably once the data is entered instead of clicking a save button.</p> <p>I figure that these texatareas and dropdowns need to be added into a group in order to save them, but I haven't done it in this fashion before. I usually have the values in the individual post. But, I need this section separate from the actual posts in the post type.</p> <p>Any suggestions would be helpful. Thanks in advance!!!</p> <p>Here is what I have so far for this submenu page.</p> <pre><code>$args = array( 'post_type' =&gt; 'properties', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'title', 'order' =&gt; 'DESC', 'post_status' =&gt; 'publish' ); $myposts = get_posts( $args ); ?&gt; &lt;div class="wrap"&gt; &lt;h1&gt;Status:&lt;/h1&gt; &lt;style&gt; .widefat .room-column { width: 3.2em; vertical-align: top; } .widefat textarea { width: 100%; } &lt;/style&gt; &lt;form action="" method="post"&gt; &lt;input type="submit" name="update_statuses" value="Update" class="button-primary" /&gt; &lt;table class="wp-list-table widefat fixed striped posts"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="manage-column column-cb room-column"&gt;Beds&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Address&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Renewal&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Future Rent&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Availability Date&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Deposit&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Last Showing&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Status&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Date&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Initials&lt;/th&gt; &lt;th class="manage-column column-columnname"&gt;Notes&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;?php $count = 0; foreach( $myposts as $post ) : setup_postdata($post); $count++; $bedrooms = wp_get_post_terms($post-&gt;ID, 'bedrooms', array("fields" =&gt; "all")); foreach( $bedrooms as $room ) { $bedSlug = $room-&gt;slug; } $bedStripped = preg_replace('/[^0-9]/', '', $bedSlug); ?&gt; &lt;tr&gt; &lt;th class="room-column"&gt; &lt;?php echo $bedStripped; ?&gt; &lt;/th&gt; &lt;td&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" target="_blank"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;select name="renewal-&lt;?php echo $post-&gt;ID; ?&gt;" id="renewal-&lt;?php echo $post-&gt;ID; ?&gt;"&gt; &lt;option value="0"&gt;Choose&lt;/option&gt; &lt;option value="No"&gt;No&lt;/option&gt; &lt;option value="Yes"&gt;Yes&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="future-rent-&lt;?php echo $post-&gt;ID; ?&gt;" id="future-rent-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="available-&lt;?php echo $post-&gt;ID; ?&gt;" id="available-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="deposit-&lt;?php echo $post-&gt;ID; ?&gt;" id="deposit-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="last-showing-&lt;?php echo $post-&gt;ID; ?&gt;" id="last-showing-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;td&gt; &lt;select name="status-&lt;?php echo $post-&gt;ID; ?&gt;" id="status-&lt;?php echo $post-&gt;ID; ?&gt;"&gt; &lt;option value="--"&gt;-&lt;/option&gt; &lt;option value="nf"&gt;Needs Fees&lt;/option&gt; &lt;option value="bgi"&gt;BGI&lt;/option&gt; &lt;option value="fa"&gt;Final Approval&lt;/option&gt; &lt;option value="a"&gt;Approved&lt;/option&gt; &lt;option value="nd"&gt;Need Deposit&lt;/option&gt; &lt;option value="dp"&gt;Deposit Paid&lt;/option&gt; &lt;option value="ats"&gt;Appt to Sign&lt;/option&gt; &lt;option value="rnl"&gt;Renew Lease&lt;/option&gt; &lt;option value="ls"&gt;Lease Signed&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="date-&lt;?php echo $post-&gt;ID; ?&gt;" id="date-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="initials-&lt;?php echo $post-&gt;ID; ?&gt;" id="initials-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;td&gt; &lt;textarea name="notes-&lt;?php echo $post-&gt;ID; ?&gt;" id="notes-&lt;?php echo $post-&gt;ID; ?&gt;"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; echo '&lt;div style="float:right;"&gt;Total: '.$count.'&lt;/div&gt;'; ?&gt; &lt;/table&gt; &lt;input type="submit" name="update_statuses" value="Update" class="button-primary" /&gt; &lt;/form&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 346057, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": -1, "selected": false, "text": "<p>WPBeginner <a href=\"https://www.wpbeginner.com/plugins/how-to-block-a-wordpress-user-without-deleting-their-account/\" rel=\"nofollow noreferrer\">has an article</a> describing use of the <a href=\"https://wordpress.org/plugins/user-blocker/\" rel=\"nofollow noreferrer\">\"User Blocker\"</a>. It sounds like just what you need.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 346064, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Although you could create another class of users, I'd just do the following:</p>\n\n<ul>\n<li><p>Change their password to something really strong and random</p></li>\n<li><p>Change their email address to an invalid value (or maybe a variation of yours) so they can't do a password reset.</p></li>\n<li><p>Maybe change their description/info to show that they are a 'past employee' or whatever generic/polite term you want to use</p></li>\n</ul>\n\n<p>That way, their articles will still be visible and attributed to them, but the person will no longer be able to add, since you have changed their password.</p>\n\n<p>And, if they have any other access to your site (FTP, hosting, remote access, network access, etc), deleting those accounts is important. Act as if the person would do damage to your site in any way, and block those actions, even if they are leaving on good terms. Disgruntled and ex-employees can have nefarious intents....and better to be safe than sorry. </p>\n\n<p>And I would do all of this sooner than later. No need to give them the opportunity to be nefarious.</p>\n" } ]
2019/08/27
[ "https://wordpress.stackexchange.com/questions/346052", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81422/" ]
I have a custom Submenu page with my post type in which I am querying all posts and adding custom textareas and dropdowns that will repeat with each entry. The id and name for each field is the same accept the end of it is hyphenated with the post ID at the end. I want to be able to save the values entered in these fields and preferably once the data is entered instead of clicking a save button. I figure that these texatareas and dropdowns need to be added into a group in order to save them, but I haven't done it in this fashion before. I usually have the values in the individual post. But, I need this section separate from the actual posts in the post type. Any suggestions would be helpful. Thanks in advance!!! Here is what I have so far for this submenu page. ``` $args = array( 'post_type' => 'properties', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'DESC', 'post_status' => 'publish' ); $myposts = get_posts( $args ); ?> <div class="wrap"> <h1>Status:</h1> <style> .widefat .room-column { width: 3.2em; vertical-align: top; } .widefat textarea { width: 100%; } </style> <form action="" method="post"> <input type="submit" name="update_statuses" value="Update" class="button-primary" /> <table class="wp-list-table widefat fixed striped posts"> <thead> <tr> <th class="manage-column column-cb room-column">Beds</th> <th class="manage-column column-columnname">Address</th> <th class="manage-column column-columnname">Renewal</th> <th class="manage-column column-columnname">Future Rent</th> <th class="manage-column column-columnname">Availability Date</th> <th class="manage-column column-columnname">Deposit</th> <th class="manage-column column-columnname">Last Showing</th> <th class="manage-column column-columnname">Status</th> <th class="manage-column column-columnname">Date</th> <th class="manage-column column-columnname">Initials</th> <th class="manage-column column-columnname">Notes</th> </tr> </thead> <?php $count = 0; foreach( $myposts as $post ) : setup_postdata($post); $count++; $bedrooms = wp_get_post_terms($post->ID, 'bedrooms', array("fields" => "all")); foreach( $bedrooms as $room ) { $bedSlug = $room->slug; } $bedStripped = preg_replace('/[^0-9]/', '', $bedSlug); ?> <tr> <th class="room-column"> <?php echo $bedStripped; ?> </th> <td> <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a> </td> <td> <select name="renewal-<?php echo $post->ID; ?>" id="renewal-<?php echo $post->ID; ?>"> <option value="0">Choose</option> <option value="No">No</option> <option value="Yes">Yes</option> </select> </td> <td> <textarea name="future-rent-<?php echo $post->ID; ?>" id="future-rent-<?php echo $post->ID; ?>"></textarea> </td> <td> <textarea name="available-<?php echo $post->ID; ?>" id="available-<?php echo $post->ID; ?>"></textarea> </td> <td> <textarea name="deposit-<?php echo $post->ID; ?>" id="deposit-<?php echo $post->ID; ?>"></textarea> </td> <td> <textarea name="last-showing-<?php echo $post->ID; ?>" id="last-showing-<?php echo $post->ID; ?>"></textarea> </td> <td> <select name="status-<?php echo $post->ID; ?>" id="status-<?php echo $post->ID; ?>"> <option value="--">-</option> <option value="nf">Needs Fees</option> <option value="bgi">BGI</option> <option value="fa">Final Approval</option> <option value="a">Approved</option> <option value="nd">Need Deposit</option> <option value="dp">Deposit Paid</option> <option value="ats">Appt to Sign</option> <option value="rnl">Renew Lease</option> <option value="ls">Lease Signed</option> </select> </td> <td> <textarea name="date-<?php echo $post->ID; ?>" id="date-<?php echo $post->ID; ?>"></textarea> </td> <td> <textarea name="initials-<?php echo $post->ID; ?>" id="initials-<?php echo $post->ID; ?>"></textarea> </td> <td> <textarea name="notes-<?php echo $post->ID; ?>" id="notes-<?php echo $post->ID; ?>"></textarea> </td> </tr> <?php endforeach; echo '<div style="float:right;">Total: '.$count.'</div>'; ?> </table> <input type="submit" name="update_statuses" value="Update" class="button-primary" /> </form> </div> ```
Although you could create another class of users, I'd just do the following: * Change their password to something really strong and random * Change their email address to an invalid value (or maybe a variation of yours) so they can't do a password reset. * Maybe change their description/info to show that they are a 'past employee' or whatever generic/polite term you want to use That way, their articles will still be visible and attributed to them, but the person will no longer be able to add, since you have changed their password. And, if they have any other access to your site (FTP, hosting, remote access, network access, etc), deleting those accounts is important. Act as if the person would do damage to your site in any way, and block those actions, even if they are leaving on good terms. Disgruntled and ex-employees can have nefarious intents....and better to be safe than sorry. And I would do all of this sooner than later. No need to give them the opportunity to be nefarious.
346,089
<p>Google did not fix my problem so..</p> <p>Anyone here know how to increase the character limit for woocommerce product attribute slug, default it has a limit of 28 characters (max 32 in database) i need max 40.(tried to increase to max 128).</p> <p>I’m testing a local site where product information comes from imported xml files, sometimes certain attribute names are just longer than 28 characters..</p> <p>Changed the corresponding column in database from vachar(32) to varchar(128),</p> <p>Tried to change the values in <code>wc-attribute-functions.php</code>, and changed 28 to 128, but that didnt help..</p> <pre><code>// Validate slug. if ( strlen( $slug ) &gt;= 40 ) { /* translators: %s: attribute slug */ return new WP_Error( ‘invalid_product_attribute_slug_too_long’, sprintf( __( ‘Slug “%s” is too long (40 characters max). Shorten it, please.’, ‘woocommerce’ ), $slug ), array( ‘status’ =&gt; 400 ) ); …. </code></pre> <p>By now i am able to input a longer <em>Attribute</em> slug , but still get an error when saving..</p> <p><a href="https://i.stack.imgur.com/TUIDR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TUIDR.png" alt="screen"></a></p> <p>This is the error i get when trying to add a term to the test attribute ( with longer name)</p> <p><a href="https://i.stack.imgur.com/MNKgK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MNKgK.png" alt="enter image description here"></a></p> <p>here you can see i am able to create an attribute with a slug of 38 characters, however when i look in the mysql database in the <code>"products_term_taxonomy"</code> table, it does not show up there,</p> <p><a href="https://i.stack.imgur.com/MUVk7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MUVk7.png" alt="enter image description here"></a></p> <p>After changing 32 character limit to 128 in file taxonomy.php,now i can add terms to attribute.</p> <p><a href="https://i.stack.imgur.com/E1mfy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E1mfy.png" alt="enter image description here"></a></p> <p>And now visible also in database, </p> <p><a href="https://i.stack.imgur.com/Id4zh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Id4zh.png" alt="enter image description here"></a> </p>
[ { "answer_id": 346113, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>As discussed in the comments, the problem is that these slugs are also used as taxonomy names and there's a 32-character limit on taxonomy names in WordPress core. From <a href=\"https://github.com/WordPress/WordPress/blob/5.2.2/wp-includes/taxonomy.php#L421\" rel=\"nofollow noreferrer\">register_taxonomy()</a>:</p>\n\n<pre><code>if ( empty( $taxonomy ) || strlen( $taxonomy ) &gt; 32 ) {\n _doing_it_wrong( __FUNCTION__,\n __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2.0' );\n return new WP_Error( 'taxonomy_length_invalid',\n __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );\n}\n</code></pre>\n\n<p>We can't see any way to override this limit without patching core.</p>\n" }, { "answer_id": 349543, "author": "yxl", "author_id": 163679, "author_profile": "https://wordpress.stackexchange.com/users/163679", "pm_score": 1, "selected": false, "text": "<p>There is a solution for this.</p>\n\n<ol>\n<li><p>Manually create the long name attribute in \"Product Attributes\"\npage, and <strong>use a short slug name here</strong>. In the product import\nsection there is no \"attribute slug\" in the Column Headers(Or maybe\nthere is one but not used by WooCommerce by default).</p>\n\n<p>Like so</p>\n\n<p><a href=\"https://i.stack.imgur.com/AUeLT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AUeLT.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>Then you can import from CSV files now. No need to change any code.</li>\n</ol>\n\n<p>Like so <a href=\"https://i.stack.imgur.com/nSBzt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nSBzt.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/e2Lx3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/e2Lx3.png\" alt=\"enter image description here\"></a></p>\n\n<p>Hope this helps you.</p></li>\n</ol>\n" }, { "answer_id": 379795, "author": "Enshtein", "author_id": 198943, "author_profile": "https://wordpress.stackexchange.com/users/198943", "pm_score": 0, "selected": false, "text": "<p>Why do you need a long attribute slug? Need a longer attribute name?</p>\n<p>You can solve it like this:</p>\n<pre><code>add_filter( 'sanitize_taxonomy_name', function( $urldecode, $taxonomy ) {\n $urldecode = mb_substr($urldecode, 0, 26, 'utf-8');\n return $urldecode;\n}, 10, 2 );\n</code></pre>\n<p>WooCommerce will be able to save attributes with long names (more than 28 characters) from the admin panel and more!</p>\n" } ]
2019/08/28
[ "https://wordpress.stackexchange.com/questions/346089", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174237/" ]
Google did not fix my problem so.. Anyone here know how to increase the character limit for woocommerce product attribute slug, default it has a limit of 28 characters (max 32 in database) i need max 40.(tried to increase to max 128). I’m testing a local site where product information comes from imported xml files, sometimes certain attribute names are just longer than 28 characters.. Changed the corresponding column in database from vachar(32) to varchar(128), Tried to change the values in `wc-attribute-functions.php`, and changed 28 to 128, but that didnt help.. ``` // Validate slug. if ( strlen( $slug ) >= 40 ) { /* translators: %s: attribute slug */ return new WP_Error( ‘invalid_product_attribute_slug_too_long’, sprintf( __( ‘Slug “%s” is too long (40 characters max). Shorten it, please.’, ‘woocommerce’ ), $slug ), array( ‘status’ => 400 ) ); …. ``` By now i am able to input a longer *Attribute* slug , but still get an error when saving.. [![screen](https://i.stack.imgur.com/TUIDR.png)](https://i.stack.imgur.com/TUIDR.png) This is the error i get when trying to add a term to the test attribute ( with longer name) [![enter image description here](https://i.stack.imgur.com/MNKgK.png)](https://i.stack.imgur.com/MNKgK.png) here you can see i am able to create an attribute with a slug of 38 characters, however when i look in the mysql database in the `"products_term_taxonomy"` table, it does not show up there, [![enter image description here](https://i.stack.imgur.com/MUVk7.png)](https://i.stack.imgur.com/MUVk7.png) After changing 32 character limit to 128 in file taxonomy.php,now i can add terms to attribute. [![enter image description here](https://i.stack.imgur.com/E1mfy.png)](https://i.stack.imgur.com/E1mfy.png) And now visible also in database, [![enter image description here](https://i.stack.imgur.com/Id4zh.png)](https://i.stack.imgur.com/Id4zh.png)
There is a solution for this. 1. Manually create the long name attribute in "Product Attributes" page, and **use a short slug name here**. In the product import section there is no "attribute slug" in the Column Headers(Or maybe there is one but not used by WooCommerce by default). Like so [![enter image description here](https://i.stack.imgur.com/AUeLT.png)](https://i.stack.imgur.com/AUeLT.png) 2. Then you can import from CSV files now. No need to change any code.Like so [![enter image description here](https://i.stack.imgur.com/nSBzt.png)](https://i.stack.imgur.com/nSBzt.png) [![enter image description here](https://i.stack.imgur.com/e2Lx3.png)](https://i.stack.imgur.com/e2Lx3.png) Hope this helps you.
346,106
<p>I have two custom plugins that use the <a href="https://github.com/pippinsplugins/wp-logging" rel="nofollow noreferrer">WP Logging</a> class. It creates a custom post type called Logs, which (at least in my case) is only visible inside the admin, for example at /wp-admin/edit.php?s&amp;post_status=all&amp;post_type=wp_log.</p> <p>To make it easier to tell which plugin is creating the logs, I've added a few hooks. Both plugins use them identically. What they do is:</p> <ol> <li>Add a sortable Type column to the manage posts screen, and add the type field (which the WP Logging library adds) to that screen.</li> <li>Add a dropdown to the top of the screen (next to the date filter) and allow the posts to be filtered by which type value they use.</li> </ol> <p>Here's the code I'm using:</p> <pre><code>// add a sortable Type column to the posts admin add_filter( 'manage_edit-wp_log_columns', array( $this, 'type_column' ), 10, 1 ); add_filter( 'manage_edit-wp_log_sortable_columns', array( $this, 'sortable_columns' ), 10, 1 ); add_action( 'manage_wp_log_posts_custom_column', array( $this, 'type_column_content' ), 10, 2 ); // filter the log posts admin by log type add_filter( 'parse_query', array( $this, 'posts_filter' ), 10, 1 ); add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) ); /** * Add a Type column to the posts admin for this post type * * @param array $columns * @return array $columns */ public function type_column( $columns ) { $columns['type'] = __( 'Type', 'form-processor-mailchimp' ); return $columns; } /** * Make the Type column in the posts admin for this post type sortable * * @param array $columns * @return array $columns */ public function sortable_columns( $columns ) { $columns['type'] = 'type'; return $columns; } /** * Add the content for the Type column in the posts admin for this post type * * @param string $column_name * @param int $post_id */ public function type_column_content( $column_name, $post_id ) { if ( 'type' != $column_name ) { return; } // get wp_log_type $terms = wp_get_post_terms( $post_id, 'wp_log_type', array( 'fields' =&gt; 'names', ) ); if ( is_array( $terms ) ) { echo esc_attr( $terms[0] ); } } /** * Filter log posts by the taxonomy from the dropdown when a value is present * * @param object $query * @return object $query */ public function posts_filter( $query ) { global $pagenow; $type = 'wp_log'; $taxonomy = 'wp_log_type'; if ( is_admin() &amp;&amp; 'edit.php' === $pagenow ) { if ( isset( $_GET['post_type'] ) &amp;&amp; esc_attr( $_GET['post_type'] ) === $type ) { if ( isset( $_GET[ $taxonomy ] ) &amp;&amp; '' !== $_GET[ $taxonomy ] ) { $query-&gt;post_type = $type; $query-&gt;tax_query = array( array( 'taxonomy' =&gt; $taxonomy, 'field' =&gt; 'slug', 'terms' =&gt; esc_attr( $_GET[ $taxonomy ] ), ), ); } } } } /** * Add a filter form for the log admin so we can filter by wp_log_type taxonomy values * * @param object $query * @return object $query */ public function restrict_log_posts() { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( isset( $_GET['post_type'] ) &amp;&amp; esc_attr( $_GET['post_type'] ) === $type ) { // get wp_log_type $terms = get_terms( [ 'taxonomy' =&gt; $taxonomy, 'hide_empty' =&gt; true, ] ); ?&gt; &lt;select name="wp_log_type"&gt; &lt;option value=""&gt;&lt;?php _e( 'All log types ', 'form-processor-mailchimp' ); ?&gt;&lt;/option&gt; &lt;?php $current_log_type = isset( $_GET[ $taxonomy ] ) ? esc_attr( $_GET[ $taxonomy ] ) : ''; foreach ( $terms as $key =&gt; $term ) { printf( '&lt;option value="%s"%s&gt;%s&lt;/option&gt;', $term-&gt;slug, $term-&gt;slug == $current_log_type ? ' selected="selected"' : '', $term-&gt;name ); } ?&gt; &lt;/select&gt; &lt;?php } } </code></pre> <p>The code is identical between the two plugins in this case. Of course the problem, if it's enabled in both plugins, is that it duplicates the display.</p> <p><a href="https://i.stack.imgur.com/9eoSy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9eoSy.png" alt="posts manage screen with two identical type dropdowns, and the type displayed twice in the column"></a></p> <p>Is there any way I can check to see if these additions have already been made before making them?</p> <p>I thought this was worth a try (on all the filters, and using <code>doing_action</code> on all the actions):</p> <pre><code>if ( ! doing_filter( 'manage_edit-wp_log_columns' ) ) { add_filter( 'manage_edit-wp_log_columns', array( $this, 'type_column' ), 10, 1 ); } </code></pre> <p>But it didn't change anything. Is there anything else I can try on this?</p>
[ { "answer_id": 346109, "author": "Jonathan Stegall", "author_id": 41356, "author_profile": "https://wordpress.stackexchange.com/users/41356", "pm_score": 0, "selected": false, "text": "<p>Now that I've been looking at it, I thought of a possible solution.</p>\n\n<pre><code>// add a filter to check for other plugins that might be filtering the log screen\n$are_logs_filtered = apply_filters( 'wp_logging_manage_logs_filtered', false );\nadd_filter( 'wp_logging_manage_logs_filtered', '__return_true' );\n\nif ( false === $are_logs_filtered ) {\n // add a sortable Type column to the posts admin\n add_filter( 'manage_edit-wp_log_columns', array( $this, 'type_column' ), 10, 1 );\n add_filter( 'manage_edit-wp_log_sortable_columns', array( $this, 'sortable_columns' ), 10, 1 );\n add_action( 'manage_wp_log_posts_custom_column', array( $this, 'type_column_content' ), 10, 2 );\n\n // filter the log posts admin by log type\n add_filter( 'parse_query', array( $this, 'posts_filter' ), 10, 1 );\n add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) );\n}\n</code></pre>\n\n<p>Adding a <code>wp_logging_manage_logs_filtered</code> to both plugins, and setting its value to true on both plugins, results in the filtering field, the sorted column, and the content in the column, all only happening once.</p>\n\n<p>I am inclined to think that's the best thing to do, but of course I could be missing something.</p>\n" }, { "answer_id": 346199, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>In your code, you add the filter like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) );\n</code></pre>\n\n<p>Which adds a function that starts like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function restrict_log_posts() {\n $type = 'wp_log';\n $taxonomy = 'wp_log_type';\n // only add filter to post type you want\n if ( isset( $_GET['post_type'] ) &amp;&amp; esc_attr( $_GET['post_type'] ) === $type ) {\n // get wp_log_type\n $terms = get_terms(\n</code></pre>\n\n<p>First, this action passes the post type so it can be simplified by adjusting the <code>add_action</code> and using the first parameter it passes:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function restrict_log_posts( $post_type ) {\n $type = 'wp_log';\n $taxonomy = 'wp_log_type';\n // only add filter to post type you want\n if ( 'wp_log' === $post_type ) {\n // get wp_log_type\n $terms = get_terms(\n</code></pre>\n\n<p>Then we could use <code>did_action</code> to only run it the first time:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function restrict_log_posts( $post_type ) {\n if ( did_action( 'restrict_manage_posts' ) ) {\n return;\n }\n....\n</code></pre>\n\n<p>But this might not have the desired effect, and it's crude. Instead, this action doesn't belong in this class at all, and should be a standalone action. Then we can define the function only if it isn't already defined:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>\nif ( !function_exists('restrict_logs_by_type') ) {\n add_action( 'restrict_manage_posts', 'restrict_logs_by_type', 10, 1 );\n /**\n * Add a filter form for the log admin so we can filter by wp_log_type taxonomy values\n *\n */\n function restrict_logs_by_type( $post_type ) {\n $type = 'wp_log';\n $taxonomy = 'wp_log_type';\n // only add filter to post type you want\n if ( $type !== $post_type ) {\n return;\n }\n // get wp_log_type\n $terms = get_terms([\n 'taxonomy' =&gt; $taxonomy,\n 'hide_empty' =&gt; true,\n ]);\n if ( is_wp_error( $terms ) || empty( $terms ) ) {\n // no terms, or the taxonomy doesn't exist, skip\n return;\n }\n\n ?&gt;\n &lt;select name=\"wp_log_type\"&gt;\n &lt;option value=\"\"&gt;&lt;?php esc_html_e( 'All log types ', 'form-processor-mailchimp' ); ?&gt;&lt;/option&gt;\n &lt;?php\n $current_log_type = isset( $_GET[ $taxonomy ] ) ? esc_attr( $_GET[ $taxonomy ] ) : '';\n foreach ( $terms as $key =&gt; $term ) {\n printf(\n '&lt;option value=\"%s\"%s&gt;%s&lt;/option&gt;',\n esc_attr( $term-&gt;slug ),\n selected( $term-&gt;slug, $current_log_type, false ),\n esc_html( $term-&gt;name )\n );\n }\n ?&gt;\n &lt;/select&gt;\n &lt;?php\n }\n}\n\n</code></pre>\n\n<p>Note that I made a number of <strong>significant</strong> improvements:</p>\n\n<ul>\n<li>I fixed a major security hole by adding escaping to your option tags</li>\n<li>I replaced the ugly ternary operator with the <code>selected</code> function provided by WP</li>\n<li>I replaced the if check with a <code>!==</code>, making it a guard. Now the entire function can be unindented by 1, and is more readable. Additionally both the Cyclomatic and NPath complexity have been reduced</li>\n<li>The function is now standalone, there was never any need for it to be part of an object or class</li>\n<li>I renamed the function to describe what it does</li>\n<li>If no terms are found, or the taxonomy doesn't exist, this version skips displaying the dropdown entirely. No sense having a dropdown if the only item is \"All\". Without this, the log screen would crash if there were no log types or entries</li>\n<li>The entire snippet is wrapped in a <code>function_exists</code> call, if the function is loaded by the first plugin, the second plugin won't bother defining and adding it</li>\n</ul>\n" } ]
2019/08/28
[ "https://wordpress.stackexchange.com/questions/346106", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41356/" ]
I have two custom plugins that use the [WP Logging](https://github.com/pippinsplugins/wp-logging) class. It creates a custom post type called Logs, which (at least in my case) is only visible inside the admin, for example at /wp-admin/edit.php?s&post\_status=all&post\_type=wp\_log. To make it easier to tell which plugin is creating the logs, I've added a few hooks. Both plugins use them identically. What they do is: 1. Add a sortable Type column to the manage posts screen, and add the type field (which the WP Logging library adds) to that screen. 2. Add a dropdown to the top of the screen (next to the date filter) and allow the posts to be filtered by which type value they use. Here's the code I'm using: ``` // add a sortable Type column to the posts admin add_filter( 'manage_edit-wp_log_columns', array( $this, 'type_column' ), 10, 1 ); add_filter( 'manage_edit-wp_log_sortable_columns', array( $this, 'sortable_columns' ), 10, 1 ); add_action( 'manage_wp_log_posts_custom_column', array( $this, 'type_column_content' ), 10, 2 ); // filter the log posts admin by log type add_filter( 'parse_query', array( $this, 'posts_filter' ), 10, 1 ); add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) ); /** * Add a Type column to the posts admin for this post type * * @param array $columns * @return array $columns */ public function type_column( $columns ) { $columns['type'] = __( 'Type', 'form-processor-mailchimp' ); return $columns; } /** * Make the Type column in the posts admin for this post type sortable * * @param array $columns * @return array $columns */ public function sortable_columns( $columns ) { $columns['type'] = 'type'; return $columns; } /** * Add the content for the Type column in the posts admin for this post type * * @param string $column_name * @param int $post_id */ public function type_column_content( $column_name, $post_id ) { if ( 'type' != $column_name ) { return; } // get wp_log_type $terms = wp_get_post_terms( $post_id, 'wp_log_type', array( 'fields' => 'names', ) ); if ( is_array( $terms ) ) { echo esc_attr( $terms[0] ); } } /** * Filter log posts by the taxonomy from the dropdown when a value is present * * @param object $query * @return object $query */ public function posts_filter( $query ) { global $pagenow; $type = 'wp_log'; $taxonomy = 'wp_log_type'; if ( is_admin() && 'edit.php' === $pagenow ) { if ( isset( $_GET['post_type'] ) && esc_attr( $_GET['post_type'] ) === $type ) { if ( isset( $_GET[ $taxonomy ] ) && '' !== $_GET[ $taxonomy ] ) { $query->post_type = $type; $query->tax_query = array( array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => esc_attr( $_GET[ $taxonomy ] ), ), ); } } } } /** * Add a filter form for the log admin so we can filter by wp_log_type taxonomy values * * @param object $query * @return object $query */ public function restrict_log_posts() { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( isset( $_GET['post_type'] ) && esc_attr( $_GET['post_type'] ) === $type ) { // get wp_log_type $terms = get_terms( [ 'taxonomy' => $taxonomy, 'hide_empty' => true, ] ); ?> <select name="wp_log_type"> <option value=""><?php _e( 'All log types ', 'form-processor-mailchimp' ); ?></option> <?php $current_log_type = isset( $_GET[ $taxonomy ] ) ? esc_attr( $_GET[ $taxonomy ] ) : ''; foreach ( $terms as $key => $term ) { printf( '<option value="%s"%s>%s</option>', $term->slug, $term->slug == $current_log_type ? ' selected="selected"' : '', $term->name ); } ?> </select> <?php } } ``` The code is identical between the two plugins in this case. Of course the problem, if it's enabled in both plugins, is that it duplicates the display. [![posts manage screen with two identical type dropdowns, and the type displayed twice in the column](https://i.stack.imgur.com/9eoSy.png)](https://i.stack.imgur.com/9eoSy.png) Is there any way I can check to see if these additions have already been made before making them? I thought this was worth a try (on all the filters, and using `doing_action` on all the actions): ``` if ( ! doing_filter( 'manage_edit-wp_log_columns' ) ) { add_filter( 'manage_edit-wp_log_columns', array( $this, 'type_column' ), 10, 1 ); } ``` But it didn't change anything. Is there anything else I can try on this?
In your code, you add the filter like this: ```php add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) ); ``` Which adds a function that starts like this: ```php public function restrict_log_posts() { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( isset( $_GET['post_type'] ) && esc_attr( $_GET['post_type'] ) === $type ) { // get wp_log_type $terms = get_terms( ``` First, this action passes the post type so it can be simplified by adjusting the `add_action` and using the first parameter it passes: ```php public function restrict_log_posts( $post_type ) { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( 'wp_log' === $post_type ) { // get wp_log_type $terms = get_terms( ``` Then we could use `did_action` to only run it the first time: ```php public function restrict_log_posts( $post_type ) { if ( did_action( 'restrict_manage_posts' ) ) { return; } .... ``` But this might not have the desired effect, and it's crude. Instead, this action doesn't belong in this class at all, and should be a standalone action. Then we can define the function only if it isn't already defined: ```php if ( !function_exists('restrict_logs_by_type') ) { add_action( 'restrict_manage_posts', 'restrict_logs_by_type', 10, 1 ); /** * Add a filter form for the log admin so we can filter by wp_log_type taxonomy values * */ function restrict_logs_by_type( $post_type ) { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( $type !== $post_type ) { return; } // get wp_log_type $terms = get_terms([ 'taxonomy' => $taxonomy, 'hide_empty' => true, ]); if ( is_wp_error( $terms ) || empty( $terms ) ) { // no terms, or the taxonomy doesn't exist, skip return; } ?> <select name="wp_log_type"> <option value=""><?php esc_html_e( 'All log types ', 'form-processor-mailchimp' ); ?></option> <?php $current_log_type = isset( $_GET[ $taxonomy ] ) ? esc_attr( $_GET[ $taxonomy ] ) : ''; foreach ( $terms as $key => $term ) { printf( '<option value="%s"%s>%s</option>', esc_attr( $term->slug ), selected( $term->slug, $current_log_type, false ), esc_html( $term->name ) ); } ?> </select> <?php } } ``` Note that I made a number of **significant** improvements: * I fixed a major security hole by adding escaping to your option tags * I replaced the ugly ternary operator with the `selected` function provided by WP * I replaced the if check with a `!==`, making it a guard. Now the entire function can be unindented by 1, and is more readable. Additionally both the Cyclomatic and NPath complexity have been reduced * The function is now standalone, there was never any need for it to be part of an object or class * I renamed the function to describe what it does * If no terms are found, or the taxonomy doesn't exist, this version skips displaying the dropdown entirely. No sense having a dropdown if the only item is "All". Without this, the log screen would crash if there were no log types or entries * The entire snippet is wrapped in a `function_exists` call, if the function is loaded by the first plugin, the second plugin won't bother defining and adding it
346,180
<p>I have two wordpress installations: a single one and a multisite with subdirectories. On both my users can logout with the url:</p> <pre><code>[URL to]/wp-login.php?action=logout&amp;redirect_to=%2Fmydir%2F&amp;_wpnonce=[some_code] </code></pre> <p>This works on the single site without confirmation, but on the site within the multisite it doesn't. Here the user needs to confirm the logout.</p> <p>How can I bypass the confirmation?</p> <p>Thank you.</p>
[ { "answer_id": 346109, "author": "Jonathan Stegall", "author_id": 41356, "author_profile": "https://wordpress.stackexchange.com/users/41356", "pm_score": 0, "selected": false, "text": "<p>Now that I've been looking at it, I thought of a possible solution.</p>\n\n<pre><code>// add a filter to check for other plugins that might be filtering the log screen\n$are_logs_filtered = apply_filters( 'wp_logging_manage_logs_filtered', false );\nadd_filter( 'wp_logging_manage_logs_filtered', '__return_true' );\n\nif ( false === $are_logs_filtered ) {\n // add a sortable Type column to the posts admin\n add_filter( 'manage_edit-wp_log_columns', array( $this, 'type_column' ), 10, 1 );\n add_filter( 'manage_edit-wp_log_sortable_columns', array( $this, 'sortable_columns' ), 10, 1 );\n add_action( 'manage_wp_log_posts_custom_column', array( $this, 'type_column_content' ), 10, 2 );\n\n // filter the log posts admin by log type\n add_filter( 'parse_query', array( $this, 'posts_filter' ), 10, 1 );\n add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) );\n}\n</code></pre>\n\n<p>Adding a <code>wp_logging_manage_logs_filtered</code> to both plugins, and setting its value to true on both plugins, results in the filtering field, the sorted column, and the content in the column, all only happening once.</p>\n\n<p>I am inclined to think that's the best thing to do, but of course I could be missing something.</p>\n" }, { "answer_id": 346199, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>In your code, you add the filter like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) );\n</code></pre>\n\n<p>Which adds a function that starts like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function restrict_log_posts() {\n $type = 'wp_log';\n $taxonomy = 'wp_log_type';\n // only add filter to post type you want\n if ( isset( $_GET['post_type'] ) &amp;&amp; esc_attr( $_GET['post_type'] ) === $type ) {\n // get wp_log_type\n $terms = get_terms(\n</code></pre>\n\n<p>First, this action passes the post type so it can be simplified by adjusting the <code>add_action</code> and using the first parameter it passes:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function restrict_log_posts( $post_type ) {\n $type = 'wp_log';\n $taxonomy = 'wp_log_type';\n // only add filter to post type you want\n if ( 'wp_log' === $post_type ) {\n // get wp_log_type\n $terms = get_terms(\n</code></pre>\n\n<p>Then we could use <code>did_action</code> to only run it the first time:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function restrict_log_posts( $post_type ) {\n if ( did_action( 'restrict_manage_posts' ) ) {\n return;\n }\n....\n</code></pre>\n\n<p>But this might not have the desired effect, and it's crude. Instead, this action doesn't belong in this class at all, and should be a standalone action. Then we can define the function only if it isn't already defined:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>\nif ( !function_exists('restrict_logs_by_type') ) {\n add_action( 'restrict_manage_posts', 'restrict_logs_by_type', 10, 1 );\n /**\n * Add a filter form for the log admin so we can filter by wp_log_type taxonomy values\n *\n */\n function restrict_logs_by_type( $post_type ) {\n $type = 'wp_log';\n $taxonomy = 'wp_log_type';\n // only add filter to post type you want\n if ( $type !== $post_type ) {\n return;\n }\n // get wp_log_type\n $terms = get_terms([\n 'taxonomy' =&gt; $taxonomy,\n 'hide_empty' =&gt; true,\n ]);\n if ( is_wp_error( $terms ) || empty( $terms ) ) {\n // no terms, or the taxonomy doesn't exist, skip\n return;\n }\n\n ?&gt;\n &lt;select name=\"wp_log_type\"&gt;\n &lt;option value=\"\"&gt;&lt;?php esc_html_e( 'All log types ', 'form-processor-mailchimp' ); ?&gt;&lt;/option&gt;\n &lt;?php\n $current_log_type = isset( $_GET[ $taxonomy ] ) ? esc_attr( $_GET[ $taxonomy ] ) : '';\n foreach ( $terms as $key =&gt; $term ) {\n printf(\n '&lt;option value=\"%s\"%s&gt;%s&lt;/option&gt;',\n esc_attr( $term-&gt;slug ),\n selected( $term-&gt;slug, $current_log_type, false ),\n esc_html( $term-&gt;name )\n );\n }\n ?&gt;\n &lt;/select&gt;\n &lt;?php\n }\n}\n\n</code></pre>\n\n<p>Note that I made a number of <strong>significant</strong> improvements:</p>\n\n<ul>\n<li>I fixed a major security hole by adding escaping to your option tags</li>\n<li>I replaced the ugly ternary operator with the <code>selected</code> function provided by WP</li>\n<li>I replaced the if check with a <code>!==</code>, making it a guard. Now the entire function can be unindented by 1, and is more readable. Additionally both the Cyclomatic and NPath complexity have been reduced</li>\n<li>The function is now standalone, there was never any need for it to be part of an object or class</li>\n<li>I renamed the function to describe what it does</li>\n<li>If no terms are found, or the taxonomy doesn't exist, this version skips displaying the dropdown entirely. No sense having a dropdown if the only item is \"All\". Without this, the log screen would crash if there were no log types or entries</li>\n<li>The entire snippet is wrapped in a <code>function_exists</code> call, if the function is loaded by the first plugin, the second plugin won't bother defining and adding it</li>\n</ul>\n" } ]
2019/08/29
[ "https://wordpress.stackexchange.com/questions/346180", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174300/" ]
I have two wordpress installations: a single one and a multisite with subdirectories. On both my users can logout with the url: ``` [URL to]/wp-login.php?action=logout&redirect_to=%2Fmydir%2F&_wpnonce=[some_code] ``` This works on the single site without confirmation, but on the site within the multisite it doesn't. Here the user needs to confirm the logout. How can I bypass the confirmation? Thank you.
In your code, you add the filter like this: ```php add_action( 'restrict_manage_posts', array( $this, 'restrict_log_posts' ) ); ``` Which adds a function that starts like this: ```php public function restrict_log_posts() { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( isset( $_GET['post_type'] ) && esc_attr( $_GET['post_type'] ) === $type ) { // get wp_log_type $terms = get_terms( ``` First, this action passes the post type so it can be simplified by adjusting the `add_action` and using the first parameter it passes: ```php public function restrict_log_posts( $post_type ) { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( 'wp_log' === $post_type ) { // get wp_log_type $terms = get_terms( ``` Then we could use `did_action` to only run it the first time: ```php public function restrict_log_posts( $post_type ) { if ( did_action( 'restrict_manage_posts' ) ) { return; } .... ``` But this might not have the desired effect, and it's crude. Instead, this action doesn't belong in this class at all, and should be a standalone action. Then we can define the function only if it isn't already defined: ```php if ( !function_exists('restrict_logs_by_type') ) { add_action( 'restrict_manage_posts', 'restrict_logs_by_type', 10, 1 ); /** * Add a filter form for the log admin so we can filter by wp_log_type taxonomy values * */ function restrict_logs_by_type( $post_type ) { $type = 'wp_log'; $taxonomy = 'wp_log_type'; // only add filter to post type you want if ( $type !== $post_type ) { return; } // get wp_log_type $terms = get_terms([ 'taxonomy' => $taxonomy, 'hide_empty' => true, ]); if ( is_wp_error( $terms ) || empty( $terms ) ) { // no terms, or the taxonomy doesn't exist, skip return; } ?> <select name="wp_log_type"> <option value=""><?php esc_html_e( 'All log types ', 'form-processor-mailchimp' ); ?></option> <?php $current_log_type = isset( $_GET[ $taxonomy ] ) ? esc_attr( $_GET[ $taxonomy ] ) : ''; foreach ( $terms as $key => $term ) { printf( '<option value="%s"%s>%s</option>', esc_attr( $term->slug ), selected( $term->slug, $current_log_type, false ), esc_html( $term->name ) ); } ?> </select> <?php } } ``` Note that I made a number of **significant** improvements: * I fixed a major security hole by adding escaping to your option tags * I replaced the ugly ternary operator with the `selected` function provided by WP * I replaced the if check with a `!==`, making it a guard. Now the entire function can be unindented by 1, and is more readable. Additionally both the Cyclomatic and NPath complexity have been reduced * The function is now standalone, there was never any need for it to be part of an object or class * I renamed the function to describe what it does * If no terms are found, or the taxonomy doesn't exist, this version skips displaying the dropdown entirely. No sense having a dropdown if the only item is "All". Without this, the log screen would crash if there were no log types or entries * The entire snippet is wrapped in a `function_exists` call, if the function is loaded by the first plugin, the second plugin won't bother defining and adding it
346,269
<p>Can someone explain how I would rewrite this bit of code to include a tel: clickable phone number and make the email address clickable to info:hi.com </p> <p>I am having a bit of trouble with this.</p> <pre><code>&lt;address class="address_phone"&gt; &lt;span class="icon icon-phone"&gt;&lt;/span&gt; &lt;div class="contact_title"&gt;&lt;?php echo esc_html__('Phone:', 'yogastudio') ?&gt;&lt;/div&gt; &lt;span class="contact_item phone"&gt;&lt;?php if (!empty($phone)) echo esc_html($phone); ?&gt;&lt;/span&gt; &lt;/address&gt;&lt;/div&gt;&lt;div class="column-1_3"&gt; &lt;address class="address_email"&gt; &lt;span class="icon icon-mail"&gt;&lt;/span&gt; &lt;div class="contact_title"&gt;&lt;?php echo esc_html__('Email:', 'yogastudio') ?&gt;&lt;/div&gt; &lt;span class="contact_item mail"&gt;&lt;?php if (!empty($email)) echo esc_html($email); ?&gt;&lt;/span&gt; &lt;/address&gt;&lt;/div&gt; </code></pre>
[ { "answer_id": 346271, "author": "Pratikb.Simform", "author_id": 173473, "author_profile": "https://wordpress.stackexchange.com/users/173473", "pm_score": 1, "selected": true, "text": "<p>Please edit your code as below:</p>\n\n<pre><code>&lt;address class=\"address_phone\"&gt;\n &lt;span class=\"icon icon-phone\"&gt;&lt;/span&gt;\n &lt;div class=\"contact_title\"&gt;&lt;?php echo esc_html__('Phone:', 'yogastudio') ?&gt;&lt;/div&gt;\n &lt;span class=\"contact_item phone\"&gt;\n &lt;?php if (!empty($phone)) { echo '&lt;a href=\"tel:'.$phone.'\"&gt;'.esc_html($phone).'&lt;/a&gt;';} ?&gt;\n &lt;/span&gt;\n &lt;/address&gt;&lt;/div&gt;&lt;div class=\"column-1_3\"&gt;\n &lt;address class=\"address_email\"&gt;\n &lt;span class=\"icon icon-mail\"&gt;&lt;/span&gt;\n &lt;div class=\"contact_title\"&gt;&lt;?php echo esc_html__('Email:', 'yogastudio') ?&gt;&lt;/div&gt;\n &lt;span class=\"contact_item mail\"&gt;&lt;?php if (!empty($email)) { echo '&lt;a href=\"mailto:'.$email.'\"&gt;'.esc_html($email).'&lt;/a&gt;';}?&gt;&lt;/span&gt;\n\n &lt;/address&gt;&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 346272, "author": "robwatson_dev", "author_id": 137115, "author_profile": "https://wordpress.stackexchange.com/users/137115", "pm_score": 1, "selected": false, "text": "<p>Remove.</p>\n\n<pre><code>&lt;?php if (!empty($phone)) { echo '&lt;a href=\"tel:'.$phone.'\"&gt;'.esc_html($phone).'&lt;/a&gt;';} ?&gt;\n</code></pre>\n\n<p>Replace with</p>\n\n<pre><code>&lt;a href=\"tel:+4401234567895\"&gt;Call us&lt;/a&gt;\n</code></pre>\n\n<p>Note you should include the International dial code as well.</p>\n\n<p>For the email, replace</p>\n\n<pre><code>&lt;?php if (!empty($email)) { echo '&lt;a href=\"mailto:'.$email.'\"&gt;'.esc_html($email).'&lt;/a&gt;';}?&gt;\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\"&gt;Email us&lt;/a&gt;\n</code></pre>\n" } ]
2019/08/30
[ "https://wordpress.stackexchange.com/questions/346269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174372/" ]
Can someone explain how I would rewrite this bit of code to include a tel: clickable phone number and make the email address clickable to info:hi.com I am having a bit of trouble with this. ``` <address class="address_phone"> <span class="icon icon-phone"></span> <div class="contact_title"><?php echo esc_html__('Phone:', 'yogastudio') ?></div> <span class="contact_item phone"><?php if (!empty($phone)) echo esc_html($phone); ?></span> </address></div><div class="column-1_3"> <address class="address_email"> <span class="icon icon-mail"></span> <div class="contact_title"><?php echo esc_html__('Email:', 'yogastudio') ?></div> <span class="contact_item mail"><?php if (!empty($email)) echo esc_html($email); ?></span> </address></div> ```
Please edit your code as below: ``` <address class="address_phone"> <span class="icon icon-phone"></span> <div class="contact_title"><?php echo esc_html__('Phone:', 'yogastudio') ?></div> <span class="contact_item phone"> <?php if (!empty($phone)) { echo '<a href="tel:'.$phone.'">'.esc_html($phone).'</a>';} ?> </span> </address></div><div class="column-1_3"> <address class="address_email"> <span class="icon icon-mail"></span> <div class="contact_title"><?php echo esc_html__('Email:', 'yogastudio') ?></div> <span class="contact_item mail"><?php if (!empty($email)) { echo '<a href="mailto:'.$email.'">'.esc_html($email).'</a>';}?></span> </address></div> ```
346,355
<p>I need to get posts with a price less than or equal to for example '1000'. The price is set in an arbitrary custom field. Trying to posts a price that is less than or equal to 1000</p> <pre><code>$posts = new WP_Query( { 'post_type' =&gt; 'post', 'meta_query' =&gt; array( 'key' =&gt; 'price', 'compare' =&gt; '&lt;=', 'value' =&gt; 1000 ), } ); </code></pre> <p>Expect to get posts with price 1000, 999, 998, etc.</p> <p>The problem is that many posts have already been created, in which the price is set in such a way that the word for example "from 1000" is added at the beginning. And some are simply given the number 1000. 'value' is compared to the number in which there is a string and the result is not correct.</p> <p>Is there any way to get the posts right? Or do I need to remove lines from custom fields price?</p>
[ { "answer_id": 404942, "author": "mahaidery", "author_id": 221415, "author_profile": "https://wordpress.stackexchange.com/users/221415", "pm_score": 1, "selected": false, "text": "<p>Restart PHP-FPM and it will resolve this issue :)</p>\n<p>PS: I know its an old thread, but anyone came here for the same issue, do this to get it resolved</p>\n" }, { "answer_id": 410798, "author": "Muhammad Athar", "author_id": 227006, "author_profile": "https://wordpress.stackexchange.com/users/227006", "pm_score": 0, "selected": false, "text": "<p>To add to mahaidery's answer.</p>\n<p>SSH into your root folder and run the following commands:</p>\n<p>/scripts/restartsrv_cpanel_php_fpm</p>\n<p>/scripts/restartsrv_apache_php_fpm</p>\n<p>Ref: <a href=\"https://forums.cpanel.net/threads/how-to-restart-php-fpm-using-ssh.596171/\" rel=\"nofollow noreferrer\">https://forums.cpanel.net/threads/how-to-restart-php-fpm-using-ssh.596171/</a></p>\n" } ]
2019/09/01
[ "https://wordpress.stackexchange.com/questions/346355", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174447/" ]
I need to get posts with a price less than or equal to for example '1000'. The price is set in an arbitrary custom field. Trying to posts a price that is less than or equal to 1000 ``` $posts = new WP_Query( { 'post_type' => 'post', 'meta_query' => array( 'key' => 'price', 'compare' => '<=', 'value' => 1000 ), } ); ``` Expect to get posts with price 1000, 999, 998, etc. The problem is that many posts have already been created, in which the price is set in such a way that the word for example "from 1000" is added at the beginning. And some are simply given the number 1000. 'value' is compared to the number in which there is a string and the result is not correct. Is there any way to get the posts right? Or do I need to remove lines from custom fields price?
Restart PHP-FPM and it will resolve this issue :) PS: I know its an old thread, but anyone came here for the same issue, do this to get it resolved
346,380
<p>hi guys i wanna show how much customers save with current deal. I entered regular and sale price for all products on my store and it show the percentage of discount on prdocut catalog.Woocommerce cart shows only the total and subtotal.</p> <p>Subtotal:10$<br> Total:10$</p> <p>so i wrote this function to show what i want. Although it works on my localhost, I can't get any results on live hosting.</p> <pre><code> function discount_module_in() { global $woocommerce; $items = $woocommerce-&gt;cart-&gt;get_cart(); foreach($items as $item =&gt; $values) { $price=get_post_meta($values['product_id'] , '_regular_price', true); $sale=get_post_meta($values['product_id'] , '_sale_price', true); $amount=$price-$sale; $discount=(1-$sale/$price)*100; if (intval($discount)==70) { $amount70+=$amount; } if (intval($discount)==50) { $amount50+=$amount; } if (intval($discount)==30) { $amount30+=$amount; } } if ($amount70&gt;0) { echo "70% OFF: -".$amount70.get_woocommerce_currency_symbol()."&lt;br&gt;"; } if ($amount50&gt;0) { echo "50% OFF: -".$amount50.get_woocommerce_currency_symbol()."&lt;br&gt;"; } if ($amount30&gt;0) { echo "30% OFF: -".$amount30.get_woocommerce_currency_symbol()."&lt;br&gt;"; } } add_action( 'woocommerce_after_cart_totals', 'discount_module_in'); </code></pre> <p>I also check if its theme issue or not but i just paste the code inside of fuction.php, to be ensure i try simple function and it worked. It's not a woocommerce hook issue either.</p> <pre><code> function discount_module_in() { echo "test" } add_action( 'woocommerce_after_cart_totals', 'discount_module_in'); </code></pre> <p>i also change my code with this. it eorken on local host but still not working on live host.</p> <pre><code>function deneme(){ global $woocommerce; $cart = WC()-&gt;cart-&gt;get_cart(); foreach( $cart as $cart_item ){ $product = wc_get_product( $cart_item['product_id'] ); $price=$product-&gt;get_regular_price(); $sale=$product-&gt;get_sale_price(); $amount=$price-$sale; $discount=(1-$sale/$price)*100; if (intval($discount)==70) { $amount70+=$amount; } if (intval($discount)==50) { $amount50+=$amount; } if (intval($discount)==30) { $amount30+=$amount; } } if ($amount70&gt;0) { echo "70% OFF: -".$amount70.get_woocommerce_currency_symbol()."&lt;br&gt;"; } if ($amount50&gt;0) { echo "50% OFF: -".$amount50.get_woocommerce_currency_symbol()."&lt;br&gt;"; } if ($amount30&gt;0) { echo "30% OFF: -".$amount30.get_woocommerce_currency_symbol()."&lt;br&gt;"; } } add_action( 'woocommerce_proceed_to_checkout', 'deneme'); </code></pre> <p>after debuggin it gives me this error </p> <blockquote> <p>Warning: A non-numeric value encountered in /home/u693223509/domains/inuovo.com/public_html/wp-content/themes/inuovo/functions.php on line 34</p> <p>Warning: A non-numeric value encountered in /home/u693223509/domains/inuovo.com/public_html/wp-content/themes/inuovo/functions.php on line 34</p> <p>Warning: A non-numeric value encountered in /home/u693223509/domains/inuovo.com/public_html/wp-content/themes/inuovo/functions.php on line 35</p> <p>Warning: A non-numeric value encountered in /home/u693223509/domains/inuovo.com/public_html/wp-content/themes/inuovo/functions.php on line 35</p> <p>Warning: Division by zero in /home/u693223509/domains/inuovo.com/public_html/wp-content/themes/inuovo/functions.php on line 35</p> </blockquote> <p>here are line 34 35</p> <pre><code> $amount=$price-$sale; $discount=(1-$sale/$price)*100; </code></pre>
[ { "answer_id": 404942, "author": "mahaidery", "author_id": 221415, "author_profile": "https://wordpress.stackexchange.com/users/221415", "pm_score": 1, "selected": false, "text": "<p>Restart PHP-FPM and it will resolve this issue :)</p>\n<p>PS: I know its an old thread, but anyone came here for the same issue, do this to get it resolved</p>\n" }, { "answer_id": 410798, "author": "Muhammad Athar", "author_id": 227006, "author_profile": "https://wordpress.stackexchange.com/users/227006", "pm_score": 0, "selected": false, "text": "<p>To add to mahaidery's answer.</p>\n<p>SSH into your root folder and run the following commands:</p>\n<p>/scripts/restartsrv_cpanel_php_fpm</p>\n<p>/scripts/restartsrv_apache_php_fpm</p>\n<p>Ref: <a href=\"https://forums.cpanel.net/threads/how-to-restart-php-fpm-using-ssh.596171/\" rel=\"nofollow noreferrer\">https://forums.cpanel.net/threads/how-to-restart-php-fpm-using-ssh.596171/</a></p>\n" } ]
2019/09/01
[ "https://wordpress.stackexchange.com/questions/346380", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127608/" ]
hi guys i wanna show how much customers save with current deal. I entered regular and sale price for all products on my store and it show the percentage of discount on prdocut catalog.Woocommerce cart shows only the total and subtotal. Subtotal:10$ Total:10$ so i wrote this function to show what i want. Although it works on my localhost, I can't get any results on live hosting. ``` function discount_module_in() { global $woocommerce; $items = $woocommerce->cart->get_cart(); foreach($items as $item => $values) { $price=get_post_meta($values['product_id'] , '_regular_price', true); $sale=get_post_meta($values['product_id'] , '_sale_price', true); $amount=$price-$sale; $discount=(1-$sale/$price)*100; if (intval($discount)==70) { $amount70+=$amount; } if (intval($discount)==50) { $amount50+=$amount; } if (intval($discount)==30) { $amount30+=$amount; } } if ($amount70>0) { echo "70% OFF: -".$amount70.get_woocommerce_currency_symbol()."<br>"; } if ($amount50>0) { echo "50% OFF: -".$amount50.get_woocommerce_currency_symbol()."<br>"; } if ($amount30>0) { echo "30% OFF: -".$amount30.get_woocommerce_currency_symbol()."<br>"; } } add_action( 'woocommerce_after_cart_totals', 'discount_module_in'); ``` I also check if its theme issue or not but i just paste the code inside of fuction.php, to be ensure i try simple function and it worked. It's not a woocommerce hook issue either. ``` function discount_module_in() { echo "test" } add_action( 'woocommerce_after_cart_totals', 'discount_module_in'); ``` i also change my code with this. it eorken on local host but still not working on live host. ``` function deneme(){ global $woocommerce; $cart = WC()->cart->get_cart(); foreach( $cart as $cart_item ){ $product = wc_get_product( $cart_item['product_id'] ); $price=$product->get_regular_price(); $sale=$product->get_sale_price(); $amount=$price-$sale; $discount=(1-$sale/$price)*100; if (intval($discount)==70) { $amount70+=$amount; } if (intval($discount)==50) { $amount50+=$amount; } if (intval($discount)==30) { $amount30+=$amount; } } if ($amount70>0) { echo "70% OFF: -".$amount70.get_woocommerce_currency_symbol()."<br>"; } if ($amount50>0) { echo "50% OFF: -".$amount50.get_woocommerce_currency_symbol()."<br>"; } if ($amount30>0) { echo "30% OFF: -".$amount30.get_woocommerce_currency_symbol()."<br>"; } } add_action( 'woocommerce_proceed_to_checkout', 'deneme'); ``` after debuggin it gives me this error > > Warning: A non-numeric value encountered in > /home/u693223509/domains/inuovo.com/public\_html/wp-content/themes/inuovo/functions.php > on line 34 > > > Warning: A non-numeric value encountered in > /home/u693223509/domains/inuovo.com/public\_html/wp-content/themes/inuovo/functions.php > on line 34 > > > Warning: A non-numeric value encountered in > /home/u693223509/domains/inuovo.com/public\_html/wp-content/themes/inuovo/functions.php > on line 35 > > > Warning: A non-numeric value encountered in > /home/u693223509/domains/inuovo.com/public\_html/wp-content/themes/inuovo/functions.php > on line 35 > > > Warning: Division by zero in > /home/u693223509/domains/inuovo.com/public\_html/wp-content/themes/inuovo/functions.php > on line 35 > > > here are line 34 35 ``` $amount=$price-$sale; $discount=(1-$sale/$price)*100; ```
Restart PHP-FPM and it will resolve this issue :) PS: I know its an old thread, but anyone came here for the same issue, do this to get it resolved
346,439
<p>I am trying to retrieve a list of all my <code>attributes_name</code> values (carat, color, size etc) from the WooCommerce table <code>wp_woocommerce_attribute_taxonomies</code> in WordPress database. </p> <p>And here is my code from the below but getting the name of the attribute and not what's inside that column: </p> <pre><code>$sql = "SELECT attribute_name FROM wp_woocommerce_attribute_taxonomies"; $result = $conn-&gt;query($sql); if ($result-&gt;num_rows &gt; 0) { // output data of each row while($row = $result-&gt;fetch_assoc()) { echo $row['attribute_name'] . "&lt;br&gt;"; } } else { echo "0 results"; } $conn-&gt;close(); </code></pre> <p>Any idea how to retrieve whats inside them?</p>
[ { "answer_id": 346442, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 3, "selected": true, "text": "<p>With WordPress to make a custom SQL query, you should always use the dedicated <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\"><code>WPDB</code></a> Class and related methods as <a href=\"https://developer.wordpress.org/reference/classes/wpdb/get_results/\" rel=\"nofollow noreferrer\"><code>get_results()</code></a>, this way:</p>\n\n<pre><code>global $wpdb;\n\n$results = $wpdb-&gt;get_results( \"\n SELECT attribute_name\n FROM {$wpdb-&gt;prefix}woocommerce_attribute_taxonomies\n\" );\n\nif ( count($results) &gt; 0) {\n $data = []; // Initializing\n\n // Loop through results objects\n foreach( $results as $result ) {\n // add each value to an array\n $data[] = $result-&gt;attribute_name . \"&lt;br&gt;\";\n }\n\n // output data of all rows\n echo implode( \"&lt;br&gt;\", $data );\n} else {\n echo \"0 results\";\n}\n</code></pre>\n\n<p><strong>Better</strong>, when you are querying one column of a table (as you are doing), you can use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/get_col/\" rel=\"nofollow noreferrer\"><code>get_col()</code></a> method this way:</p>\n\n<pre><code>global $wpdb;\n\n$results = $wpdb-&gt;get_col( \"\n SELECT attribute_name\n FROM {$wpdb-&gt;prefix}woocommerce_attribute_taxonomies\n\" );\n\nif ( count($results) &gt; 0) {\n // output data of all rows\n echo implode( \"&lt;br&gt;\", $results );\n} else {\n echo \"0 results\";\n}\n</code></pre>\n\n<hr>\n\n<p><strong>The best easy way</strong> is to use WooCommerce <a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_attribute_taxonomies.html#44-85\" rel=\"nofollow noreferrer\"><code>wc_get_attribute_taxonomies()</code></a> dedicated function:</p>\n\n<pre><code>$output = '&lt;ul style=\"list-style:none;\"&gt;';\n\n// Loop through all Woocommerce product attributes\nforeach( wc_get_attribute_taxonomies() as $attribute ) {\n $attribute_label = $attribute-&gt;attribute_label; // Product attribute name\n $attribute_slug = $attribute-&gt;attribute_name; // Product attribute slug\n\n $output .= '&lt;li class=\"'.$attribute_slug.'\"&gt;' . $attribute_label . '&lt;/li&gt;';\n}\n// Output\necho $output . '&lt;/ul&gt;';\n</code></pre>\n\n<p>Related thread: <a href=\"https://stackoverflow.com/questions/53742146/get-woocommerce-product-attributes-to-sidebar/53745324#53745324\">Get woocommerce product attributes to sidebar</a></p>\n" }, { "answer_id": 346731, "author": "ali", "author_id": 174467, "author_profile": "https://wordpress.stackexchange.com/users/174467", "pm_score": 0, "selected": false, "text": "<p>and thank you so much fo your answer. This is very nice solution but I am still not getting the values and am only getting the attribute name or titles (like table headings). I need the rows of attribute for each product. So for example I have the attributes: carat, color, size, condition on my dashboard and with your code or mine I am only returning \ncarat\ncolor\nsize\ncondition \nI want to be able to retrieve values such as </p>\n\n<p>product 1. carat [0.2], color [l], size[big], condition [excellent]\nproduct 2. carat [0.90], color [g], size[small], condition [good]<br>\nproduct 3. .... </p>\n\n<p>with this sql query I am a bit closer to retrieving all values: Please see</p>\n\n<pre><code>$sql = \"SELECT p.`ID` AS 'Product ID', p.`post_title` AS 'Product Name', t.`term_id` AS 'Attribute Value ID', REPLACE(REPLACE(tt.`taxonomy`, 'pa_', ''), '-', ' ') AS 'Attribute Name', t.`name` AS 'Attribute Value' FROM `wp_posts` AS p INNER JOIN `wp_term_relationships` AS tr ON p.`ID` = tr.`object_id` INNER JOIN `wp_term_taxonomy` AS tt ON tr.`term_taxonomy_id` = tt.`term_id` AND tt.`taxonomy` LIKE 'pa_%' INNER JOIN `wp_terms` AS t ON tr.`term_taxonomy_id` = t.`term_id` WHERE p.`post_type` = 'product' AND p.`post_status` = 'publish' \";\n\n$result = $conn-&gt;query($sql);\n\nif ($result-&gt;num_rows &gt; 0) {\n // output data of each row\n while($row = $result-&gt;fetch_assoc()) {\n echo $row['Attribute Value'] . \"&lt;br&gt;\";\n }\n} else {\n echo \"0 results\";\n}\n$conn-&gt;close();\n</code></pre>\n" } ]
2019/09/02
[ "https://wordpress.stackexchange.com/questions/346439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174503/" ]
I am trying to retrieve a list of all my `attributes_name` values (carat, color, size etc) from the WooCommerce table `wp_woocommerce_attribute_taxonomies` in WordPress database. And here is my code from the below but getting the name of the attribute and not what's inside that column: ``` $sql = "SELECT attribute_name FROM wp_woocommerce_attribute_taxonomies"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo $row['attribute_name'] . "<br>"; } } else { echo "0 results"; } $conn->close(); ``` Any idea how to retrieve whats inside them?
With WordPress to make a custom SQL query, you should always use the dedicated [`WPDB`](https://codex.wordpress.org/Class_Reference/wpdb) Class and related methods as [`get_results()`](https://developer.wordpress.org/reference/classes/wpdb/get_results/), this way: ``` global $wpdb; $results = $wpdb->get_results( " SELECT attribute_name FROM {$wpdb->prefix}woocommerce_attribute_taxonomies " ); if ( count($results) > 0) { $data = []; // Initializing // Loop through results objects foreach( $results as $result ) { // add each value to an array $data[] = $result->attribute_name . "<br>"; } // output data of all rows echo implode( "<br>", $data ); } else { echo "0 results"; } ``` **Better**, when you are querying one column of a table (as you are doing), you can use [`get_col()`](https://developer.wordpress.org/reference/classes/wpdb/get_col/) method this way: ``` global $wpdb; $results = $wpdb->get_col( " SELECT attribute_name FROM {$wpdb->prefix}woocommerce_attribute_taxonomies " ); if ( count($results) > 0) { // output data of all rows echo implode( "<br>", $results ); } else { echo "0 results"; } ``` --- **The best easy way** is to use WooCommerce [`wc_get_attribute_taxonomies()`](https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_attribute_taxonomies.html#44-85) dedicated function: ``` $output = '<ul style="list-style:none;">'; // Loop through all Woocommerce product attributes foreach( wc_get_attribute_taxonomies() as $attribute ) { $attribute_label = $attribute->attribute_label; // Product attribute name $attribute_slug = $attribute->attribute_name; // Product attribute slug $output .= '<li class="'.$attribute_slug.'">' . $attribute_label . '</li>'; } // Output echo $output . '</ul>'; ``` Related thread: [Get woocommerce product attributes to sidebar](https://stackoverflow.com/questions/53742146/get-woocommerce-product-attributes-to-sidebar/53745324#53745324)
346,452
<p>I have a custom taxonomy called <code>campaign</code> and a custom post type called <code>asset</code>. For assets, I want to have the following permalink structure: <code>mysite.com/&lt;campaign_name&gt;/&lt;asset_name&gt;</code>. I have achieved this by the following code, but now if I go to any normal page with the url structure <code>mysite.com/&lt;pagename&gt;</code> it gives a 404. And when I comment out the rewrite slug part in the function for registering the custom post type, or add this instead <code>ams/%campaign%</code>, it works but that's not the URL structure I want for my custom post type.</p> <p>Code for registering custom taxonomy:</p> <pre><code>... 'rewrite' =&gt; array( 'slug' =&gt; '', 'with_front' =&gt; true, ), ... </code></pre> <p>Code for registering custom post type:</p> <pre><code>... rewrite' =&gt; array( 'slug' =&gt; '%campaign%', 'with_front' =&gt; true, ), ... </code></pre> <p>Functions for rewrite rules:</p> <pre><code>function ams_asset_add_rewrite_rules( $rules ) { global $post; if ($post-&gt;post_type == 'asset' ) { $new = array(); $new['([^/]+)/(.+)/?$'] = 'index.php?asset=$matches[2]'; $new['(.+)/?$'] = 'index.php?campaign=$matches[1]'; return array_merge( $new, $rules ); } return $rules; } add_filter( 'rewrite_rules_array', 'ams_asset_add_rewrite_rules' ); // Handle the '%campaign%' URL placeholder function ams_asset_filter_post_type_link( $link, $post = 0 ) { if ( $post-&gt;post_type == 'asset' ) { $cats = wp_get_object_terms( $post-&gt;ID, 'campaign' ); if ( $cats ) { $link = str_replace( '%campaign%', $cats[0]-&gt;slug, $link ); } } return $link; } add_filter( 'post_type_link', 'ams_asset_filter_post_type_link', 10, 2 ); </code></pre> <p>Edit: it's not a duplicate. I explained why that possible duplicate question doesn't solve my problem.</p>
[ { "answer_id": 346780, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>My answer isn't directly applicable to your case as my experience is about doing funky stuff with CPT permalinks, but without taxonomies. But the end result was more or less the same as half of the site's content ended up showing 404 after starting to use custom permalink structures.</p>\n\n<p>It took me ages to figure out what was going on and get the problem fixed. The problem was that WordPress had started thinking that some of the content were attachments instead of pages/posts/CPTS. To get the content showing again, I hooked a custom function to <code>parse_request</code> and basically brute forced the <code>$wp-&gt;query_vars</code> to be correct.</p>\n\n<p>It might not be the most elegant or efficient solution, but it did the trick. I did try playing around with adding custom rewrite rules, but that got me nowhere as I couldn't wrap my head around the rewrite concepts.</p>\n\n<p>Here's a simplified and stripped down version of the code I used to solve the 404 problem. The basic idea is that I just used what <code>query_vars</code> I had, did custom <code>$wpdb</code> query to get the right data, and then pushed that data to <code>query_vars</code> and removed unnecessary data from it.</p>\n\n<pre><code>add_action( 'parse_request', 'modify_parse_request' );\nfunction modify_parse_request( $wp ) {\n if ( is_admin() || ! is_main_query() ) {\n return;\n }\n global $wpdb;\n\n // var_dump($wp-&gt;query_vars); // see whats really happening with your query\n\n if ( ! empty( $wp-&gt;query_vars['attachment'] ) ) {\n\n // $path = explode( '/', $wp-&gt;request ); // you might need to get the page name from request\n\n $sql = \"\n SELECT ID, post_name, post_type\n FROM $wpdb-&gt;posts\n WHERE post_name=%s\n \";\n $post = $wpdb-&gt;get_results( $wpdb-&gt;prepare( $sql, $wp-&gt;query_vars['attachment'] ) ); // modify this\n\n // \"brute force\" the query variables to be correct\n if ( $post ) { // modify this\n $wp-&gt;query_vars['p'] = $post-&gt;ID;\n $wp-&gt;query_vars['post_type'] = $post-&gt;post_type;\n $wp-&gt;query_vars['name'] = $wp-&gt;query_vars['attachment'];\n unset( $wp-&gt;query_vars['attachment'] );\n }\n\n }\n\n}\n</code></pre>\n\n<p>This is definetly not an copy-paste example, but just some food or thought. Maybe using this as a starting point, you can get your pages working again, if you use your custom taxonomy+cpt_post_name permalink structure.</p>\n" }, { "answer_id": 347027, "author": "Sohan Zaman", "author_id": 143312, "author_profile": "https://wordpress.stackexchange.com/users/143312", "pm_score": 3, "selected": true, "text": "<p>Solution would be a little tricky but you're on the right path.</p>\n\n<ol>\n<li>You need to register taxonomy and post type with dynamic rewrite:</li>\n</ol>\n\n<pre><code>function wpse346452_cpt() {\n\n register_taxonomy( 'campaign', 'asset', array( 'label' =&gt; 'Campaing' ) );\n\n register_post_type( 'asset', array(\n 'public' =&gt; true,\n 'label' =&gt; 'Asset',\n 'rewrite' =&gt; array(\n 'slug' =&gt; '%campaign_name%',\n ),\n ) );\n\n}\nadd_action( 'init', 'wpse346452_cpt' );\n</code></pre>\n\n<ol start=\"2\">\n<li>You need to replace that dynamic rewrite so that it represents the term attached to it:</li>\n</ol>\n\n<pre><code>function wpse346452_permalink( $post_link, $post ) {\n if( is_object( $post ) &amp;&amp; $post-&gt;post_type == 'asset' ) {\n $terms = wp_get_object_terms( $post-&gt;ID, 'campaign' );\n if( $terms ) {\n return str_replace( '%campaign_name%' , $terms[0]-&gt;slug , $post_link );\n }\n }\n return $post_link;\n}\nadd_filter( 'post_type_link', 'wpse346452_permalink', 10, 2 );\n</code></pre>\n\n<ol start=\"3\">\n<li>Now you get 404 because the rewrite rule is not defined yet. Each time you have a new term under campaign, you need a new rule. So let's add rewrite rules for each available terms dynamically:</li>\n</ol>\n\n<pre><code>function wpse346452_dynamic_rw_rules() {\n\n $terms = get_terms( array(\n 'taxonomy' =&gt; 'campaign',\n 'hide_empty' =&gt; false,\n ) );\n\n if( !empty( $terms ) ) {\n foreach( $terms as $term ) {\n add_rewrite_rule(\n '^' . $term-&gt;slug . '/(.*)/?$',\n 'index.php?post_type=asset&amp;name=$matches[1]',\n 'top'\n );\n }\n }\n\n}\nadd_action( 'init', 'wpse346452_dynamic_rw_rules' );\n</code></pre>\n\n<p>Now it will work as you needed. But the downside is, whenever you add new campaign, you need to go to permalink settings and save, thus flush rewrite rules. So let's automate that too:</p>\n\n<pre><code>function wpse346452_flush_rewrite( $term_id, $tt_id, $taxonomy = 'campaign' ) {\n if( $taxonomy === 'campaign' ) {\n $term = get_term_by( 'term_taxonomy_id', $tt_id );\n add_rewrite_rule(\n '^' . $term-&gt;slug . '/(.*)/?$',\n 'index.php?post_type=asset&amp;name=$matches[1]',\n 'top'\n );\n if( !function_exists( 'flush_rewrite_rules' ) ) {\n require_once WPINC . '/rewrite.php';\n }\n flush_rewrite_rules();\n }\n}\nadd_action( 'edit_term', 'wpse346452_flush_rewrite', 10, 3 );\nadd_action( 'create_campaign', 'wpse346452_flush_rewrite', 10, 3 );\n</code></pre>\n\n<p>Here we're hooking into create and edit term and if the taxonomy is campaign then we're firing <code>flush_rewrite_rules()</code> to refresh permalinks.</p>\n\n<p>This is the only perfect method of doing this as far my knowledge. But there's a limitation for doing this. As there's no limit of adding terms, it can conflict with rewrite rules from other plugins. So need to be used carefully.</p>\n" } ]
2019/09/03
[ "https://wordpress.stackexchange.com/questions/346452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94844/" ]
I have a custom taxonomy called `campaign` and a custom post type called `asset`. For assets, I want to have the following permalink structure: `mysite.com/<campaign_name>/<asset_name>`. I have achieved this by the following code, but now if I go to any normal page with the url structure `mysite.com/<pagename>` it gives a 404. And when I comment out the rewrite slug part in the function for registering the custom post type, or add this instead `ams/%campaign%`, it works but that's not the URL structure I want for my custom post type. Code for registering custom taxonomy: ``` ... 'rewrite' => array( 'slug' => '', 'with_front' => true, ), ... ``` Code for registering custom post type: ``` ... rewrite' => array( 'slug' => '%campaign%', 'with_front' => true, ), ... ``` Functions for rewrite rules: ``` function ams_asset_add_rewrite_rules( $rules ) { global $post; if ($post->post_type == 'asset' ) { $new = array(); $new['([^/]+)/(.+)/?$'] = 'index.php?asset=$matches[2]'; $new['(.+)/?$'] = 'index.php?campaign=$matches[1]'; return array_merge( $new, $rules ); } return $rules; } add_filter( 'rewrite_rules_array', 'ams_asset_add_rewrite_rules' ); // Handle the '%campaign%' URL placeholder function ams_asset_filter_post_type_link( $link, $post = 0 ) { if ( $post->post_type == 'asset' ) { $cats = wp_get_object_terms( $post->ID, 'campaign' ); if ( $cats ) { $link = str_replace( '%campaign%', $cats[0]->slug, $link ); } } return $link; } add_filter( 'post_type_link', 'ams_asset_filter_post_type_link', 10, 2 ); ``` Edit: it's not a duplicate. I explained why that possible duplicate question doesn't solve my problem.
Solution would be a little tricky but you're on the right path. 1. You need to register taxonomy and post type with dynamic rewrite: ``` function wpse346452_cpt() { register_taxonomy( 'campaign', 'asset', array( 'label' => 'Campaing' ) ); register_post_type( 'asset', array( 'public' => true, 'label' => 'Asset', 'rewrite' => array( 'slug' => '%campaign_name%', ), ) ); } add_action( 'init', 'wpse346452_cpt' ); ``` 2. You need to replace that dynamic rewrite so that it represents the term attached to it: ``` function wpse346452_permalink( $post_link, $post ) { if( is_object( $post ) && $post->post_type == 'asset' ) { $terms = wp_get_object_terms( $post->ID, 'campaign' ); if( $terms ) { return str_replace( '%campaign_name%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'wpse346452_permalink', 10, 2 ); ``` 3. Now you get 404 because the rewrite rule is not defined yet. Each time you have a new term under campaign, you need a new rule. So let's add rewrite rules for each available terms dynamically: ``` function wpse346452_dynamic_rw_rules() { $terms = get_terms( array( 'taxonomy' => 'campaign', 'hide_empty' => false, ) ); if( !empty( $terms ) ) { foreach( $terms as $term ) { add_rewrite_rule( '^' . $term->slug . '/(.*)/?$', 'index.php?post_type=asset&name=$matches[1]', 'top' ); } } } add_action( 'init', 'wpse346452_dynamic_rw_rules' ); ``` Now it will work as you needed. But the downside is, whenever you add new campaign, you need to go to permalink settings and save, thus flush rewrite rules. So let's automate that too: ``` function wpse346452_flush_rewrite( $term_id, $tt_id, $taxonomy = 'campaign' ) { if( $taxonomy === 'campaign' ) { $term = get_term_by( 'term_taxonomy_id', $tt_id ); add_rewrite_rule( '^' . $term->slug . '/(.*)/?$', 'index.php?post_type=asset&name=$matches[1]', 'top' ); if( !function_exists( 'flush_rewrite_rules' ) ) { require_once WPINC . '/rewrite.php'; } flush_rewrite_rules(); } } add_action( 'edit_term', 'wpse346452_flush_rewrite', 10, 3 ); add_action( 'create_campaign', 'wpse346452_flush_rewrite', 10, 3 ); ``` Here we're hooking into create and edit term and if the taxonomy is campaign then we're firing `flush_rewrite_rules()` to refresh permalinks. This is the only perfect method of doing this as far my knowledge. But there's a limitation for doing this. As there's no limit of adding terms, it can conflict with rewrite rules from other plugins. So need to be used carefully.
346,479
<p>I host my own WP site on a Debian/Raspbian buster server.</p> <p>I upgraded PHP 7.1 to 7.3 and the site broke.</p> <p>I can't understand why it broke because mysql_connect() is deprecated for 7.x (though wp-db.php seems to use it extensively - while WP nags you to upgrade to 7.3). So I looked to enabling the various modules in the fresh 7.3 install php.ini. <code>MySQLi</code> was commented out, so I enabled that (and a few others) but still get the same error.</p> <p><code>Call to undefined function mysql_connect()... wp-db.php on line 1643</code></p> <p>which is...</p> <pre><code> if ( WP_DEBUG ) { 1643 $this-&gt;dbh = mysql_connect( $this-&gt;dbhost, $this-&gt;dbuser, $this-&gt;dbpassword, $new_link, $client_flags ); </code></pre> <p>Php info references MySQLi several times so I'm assuming it's running. The same for <code>mysqlnd</code>.</p> <p>I know this question gets asked a lot. But I have tried just about everything out there.</p> <p>How can I get my site working again on 7.3?</p> <p>Edit: I tried disabling plugins by renaming the dir and got the same result. I suspect the issue is my 7.3 PHP config, since 7.0 worked fie.</p>
[ { "answer_id": 346483, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>I mean your php.ini is changed, check for the entry <code>extension=php_mysqll.dll</code>.</p>\n\n<p>(If you has no knowledge where is your used php.ini - see <a href=\"https://stackoverflow.com/questions/8684609/dude-wheres-my-php-ini\">https://stackoverflow.com/questions/8684609/dude-wheres-my-php-ini</a>) </p>\n\n<p>Is this entry active, has no <code>;</code> before the string. After change of the php.ini you need a restart of mysql, like <code>sudo /etc/init.d/mysql restart</code>.</p>\n\n<p>Also a note, check that mysql is installed for the newer php version, maybe via console or the <code>phpinfo()</code>.</p>\n\n<p><code>sudo apt-get install mysql-server mysql-common php7.3 php7.3-mysql</code></p>\n" }, { "answer_id": 346485, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Your problem is either:</p>\n\n<ul>\n<li>very old WordPress</li>\n<li>custom modifications to WP Core</li>\n</ul>\n\n<p>Update to a newer version of WordPress to resolve the problem</p>\n\n<p>For example, if we look at the current WP source code, it doesn't use <code>mysql_connect</code> and hasn't for years:</p>\n\n<p><a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/wp-db.php#L1638\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-includes/wp-db.php#L1638</a></p>\n\n<pre class=\"lang-php prettyprint-override\"><code> if ( WP_DEBUG ) {\n mysqli_real_connect( $this-&gt;dbh, $host, $this-&gt;dbuser, $this-&gt;dbpassword, null, $port, $socket, $client_flags );\n } else {\n // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged\n @mysqli_real_connect( $this-&gt;dbh, $host, $this-&gt;dbuser, $this-&gt;dbpassword, null, $port, $socket, $client_flags );\n }\n</code></pre>\n\n<p>It won't be enough to just change <code>mysql_connect</code> to <code>mysqli_real_connect</code> though, as there are other changes. So update to the latest WordPress</p>\n" } ]
2019/09/03
[ "https://wordpress.stackexchange.com/questions/346479", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70649/" ]
I host my own WP site on a Debian/Raspbian buster server. I upgraded PHP 7.1 to 7.3 and the site broke. I can't understand why it broke because mysql\_connect() is deprecated for 7.x (though wp-db.php seems to use it extensively - while WP nags you to upgrade to 7.3). So I looked to enabling the various modules in the fresh 7.3 install php.ini. `MySQLi` was commented out, so I enabled that (and a few others) but still get the same error. `Call to undefined function mysql_connect()... wp-db.php on line 1643` which is... ``` if ( WP_DEBUG ) { 1643 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags ); ``` Php info references MySQLi several times so I'm assuming it's running. The same for `mysqlnd`. I know this question gets asked a lot. But I have tried just about everything out there. How can I get my site working again on 7.3? Edit: I tried disabling plugins by renaming the dir and got the same result. I suspect the issue is my 7.3 PHP config, since 7.0 worked fie.
I mean your php.ini is changed, check for the entry `extension=php_mysqll.dll`. (If you has no knowledge where is your used php.ini - see <https://stackoverflow.com/questions/8684609/dude-wheres-my-php-ini>) Is this entry active, has no `;` before the string. After change of the php.ini you need a restart of mysql, like `sudo /etc/init.d/mysql restart`. Also a note, check that mysql is installed for the newer php version, maybe via console or the `phpinfo()`. `sudo apt-get install mysql-server mysql-common php7.3 php7.3-mysql`
346,567
<p>I found this code around and I'm testing it but it doesn't work.</p> <p>How can I solve it?</p> <pre><code>add_action( 'validate_password_reset', 'rsm_redirect_after_rest', 10, 2 ); function rsm_redirect_after_rest($errors, $user) { if ( ( ! $errors-&gt;get_error_code() ) &amp;&amp; isset( $_POST['pass1'] ) &amp;&amp; !empty( $_POST['pass1'] ) ) { reset_password( $user, $_POST['pass1'] ); setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true ); wp_set_current_user( $user-&gt;ID ); wp_set_auth_cookie( $user-&gt;ID ); do_action( 'wp_login', $user-&gt;user_login );//`[Codex Ref.][1] wp_redirect( home_url() ); exit; } } </code></pre> <p>This is the error I get: </p> <blockquote> <p>Warning: Cookie names must not be empty</p> </blockquote> <p>Thanks to those who will help me.</p> <p><strong>RESOLVED:</strong></p> <p>I used the following code as recommended by you and now it works perfectly:</p> <pre><code>add_action( 'validate_password_reset', 'rsm_redirect_after_rest', 10, 2 ); function rsm_redirect_after_rest($errors, $user) { global $rp_cookie, $rp_path; if ( ( ! $errors-&gt;get_error_code() ) &amp;&amp; isset( $_POST['pass1'] ) &amp;&amp; !empty( $_POST['pass1'] ) ) { reset_password( $user, $_POST['pass1'] ); setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true ); wp_set_current_user( $user-&gt;ID ); wp_set_auth_cookie( $user-&gt;ID ); do_action( 'wp_login', $user-&gt;user_login );//`[Codex Ref.][1] wp_redirect( home_url() ); exit; } } </code></pre>
[ { "answer_id": 346569, "author": "Ted Stresen-Reuter", "author_id": 112766, "author_profile": "https://wordpress.stackexchange.com/users/112766", "pm_score": 3, "selected": true, "text": "<p><code>$rp_cookie</code> and <code>$rp_path</code> are inside a function but are not initialized inside the function so they are out of scope and thus, empty. You can try calling <code>global $rp_cookie, $rp_path;</code> at the start of your function but I don't know if those variables have been set at the time your function is running and thus they might still be empty. </p>\n\n<p>Another, more \"modern\" approach is to add the variable to the function scope by modifying the function signature as such:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'validate_password_reset',\nfunction rsm_redirect_after_rest($errors, $user) use ($rp_cookie, $rp_path) {\n if ( ( ! $errors-&gt;get_error_code() ) &amp;&amp; isset( $_POST['pass1'] ) &amp;&amp; !empty( $_POST['pass1'] ) ) {\n reset_password( $user, $_POST['pass1'] );\n setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true );\n wp_set_current_user( $user-&gt;ID );\n wp_set_auth_cookie( $user-&gt;ID );\n do_action( 'wp_login', $user-&gt;user_login );//`[Codex Ref.][1]\n wp_redirect( home_url() );\n exit;\n }\n}, 10, 2 )\n</code></pre>\n\n<p>Note the <code>use ($rp_cookie, $rp_path)</code> following the anonymous function, but again, if those variable have not been set prior to running this function, they will still be empty. HTH.</p>\n" }, { "answer_id": 346587, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>There is nothing wrong with your code, except that you are using two variables which are not set in your code, and you probably don't even need them. Please remove this line entirely and try again:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true );\n</code></pre>\n" } ]
2019/09/04
[ "https://wordpress.stackexchange.com/questions/346567", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174135/" ]
I found this code around and I'm testing it but it doesn't work. How can I solve it? ``` add_action( 'validate_password_reset', 'rsm_redirect_after_rest', 10, 2 ); function rsm_redirect_after_rest($errors, $user) { if ( ( ! $errors->get_error_code() ) && isset( $_POST['pass1'] ) && !empty( $_POST['pass1'] ) ) { reset_password( $user, $_POST['pass1'] ); setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true ); wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID ); do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1] wp_redirect( home_url() ); exit; } } ``` This is the error I get: > > Warning: Cookie names must not be empty > > > Thanks to those who will help me. **RESOLVED:** I used the following code as recommended by you and now it works perfectly: ``` add_action( 'validate_password_reset', 'rsm_redirect_after_rest', 10, 2 ); function rsm_redirect_after_rest($errors, $user) { global $rp_cookie, $rp_path; if ( ( ! $errors->get_error_code() ) && isset( $_POST['pass1'] ) && !empty( $_POST['pass1'] ) ) { reset_password( $user, $_POST['pass1'] ); setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true ); wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID ); do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1] wp_redirect( home_url() ); exit; } } ```
`$rp_cookie` and `$rp_path` are inside a function but are not initialized inside the function so they are out of scope and thus, empty. You can try calling `global $rp_cookie, $rp_path;` at the start of your function but I don't know if those variables have been set at the time your function is running and thus they might still be empty. Another, more "modern" approach is to add the variable to the function scope by modifying the function signature as such: ```php add_action( 'validate_password_reset', function rsm_redirect_after_rest($errors, $user) use ($rp_cookie, $rp_path) { if ( ( ! $errors->get_error_code() ) && isset( $_POST['pass1'] ) && !empty( $_POST['pass1'] ) ) { reset_password( $user, $_POST['pass1'] ); setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true ); wp_set_current_user( $user->ID ); wp_set_auth_cookie( $user->ID ); do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1] wp_redirect( home_url() ); exit; } }, 10, 2 ) ``` Note the `use ($rp_cookie, $rp_path)` following the anonymous function, but again, if those variable have not been set prior to running this function, they will still be empty. HTH.
346,603
<p>I am registering a custom post type called "Products &amp; Services". I have created a file within <code>wp-content/themes/theme/</code> called <code>archive-products&amp;services.php</code> but it's not using this file. </p> <p>I also tried <code>archive-products &amp; services.php</code>, <code>archive-productsandservices.php</code> but still it wont load the template.</p> <pre><code>register_post_type( 'Products &amp; Services', array( 'supports' =&gt; array('title', 'editor', 'thumbnail'), 'labels' =&gt; array( 'name' =&gt; __( 'Products and Services' ), 'singular_name' =&gt; __( 'Service' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'productsandservices') ) ); </code></pre> <p>It works fine on two other custom post types called 'news' and 'products'. Is this an issue with blank spaces in the post type?</p>
[ { "answer_id": 346605, "author": "user2924019", "author_id": 105515, "author_profile": "https://wordpress.stackexchange.com/users/105515", "pm_score": -1, "selected": false, "text": "<p>After changing the post type to \"Products and Services\" it works with the file name \"archive-productsandservices.php\". I guess Wordpress doesn't support special characters in post types. </p>\n" }, { "answer_id": 346640, "author": "Matthew Brown aka Lord Matt", "author_id": 109240, "author_profile": "https://wordpress.stackexchange.com/users/109240", "pm_score": 1, "selected": false, "text": "<p>Your problem was the &amp; which WordPress cannot support as is. That is because &amp; is used as part of a URL to join query vars together. Like this:</p>\n\n<pre><code>example.com/file.php?foo=bar&amp;baz=zoo\n</code></pre>\n\n<p>Also, as pointed out in comments file names have to follow the naming standard. Which is clearly laid out in the documentation. </p>\n\n<p>The format is <code>archive-[slug].php</code></p>\n\n<p>That's why when you renamed the file it started working.</p>\n" }, { "answer_id": 346657, "author": "Lee", "author_id": 47505, "author_profile": "https://wordpress.stackexchange.com/users/47505", "pm_score": 0, "selected": false, "text": "<p>Wordpress doesn't support special characters in post types.</p>\n\n<p>However, it would be useful to point out the codex doesn't state this. All it says is <strong>(max 20 characters, cannot container capital letters, underscores or spaces)</strong></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n" } ]
2019/09/04
[ "https://wordpress.stackexchange.com/questions/346603", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105515/" ]
I am registering a custom post type called "Products & Services". I have created a file within `wp-content/themes/theme/` called `archive-products&services.php` but it's not using this file. I also tried `archive-products & services.php`, `archive-productsandservices.php` but still it wont load the template. ``` register_post_type( 'Products & Services', array( 'supports' => array('title', 'editor', 'thumbnail'), 'labels' => array( 'name' => __( 'Products and Services' ), 'singular_name' => __( 'Service' ) ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'productsandservices') ) ); ``` It works fine on two other custom post types called 'news' and 'products'. Is this an issue with blank spaces in the post type?
Your problem was the & which WordPress cannot support as is. That is because & is used as part of a URL to join query vars together. Like this: ``` example.com/file.php?foo=bar&baz=zoo ``` Also, as pointed out in comments file names have to follow the naming standard. Which is clearly laid out in the documentation. The format is `archive-[slug].php` That's why when you renamed the file it started working.
346,689
<p>I have a posttype 'timeslip' and I am calling this with the following API endpoint:</p> <pre><code>/wp-json/wp/v2/timeslip?meta_key=user_id&amp;meta_value=1 </code></pre> <p>I have exposed my custom field user_id to the API meta and can see it in the response.</p> <pre><code>add_filter('rest_timeslip_query', array($this, 'timeslip_meta_request_params')); public function register_meta_api() { // Meta Fields that should be added to the API $timeslip_meta_fields = array( 'user_id', 'total_time', 'start_time', 'end_time', ); // Meta foreach ($timeslip_meta_fields as $field) { register_rest_field('timeslip', $field, array( 'get_callback' =&gt; array($this, 'get_meta'), 'update_callback' =&gt; array($this, 'update_meta'), 'schema' =&gt; null, ) ); } } public function get_meta($object, $field_name) { return get_post_meta($object['id'], $field_name); } </code></pre> <p>However nothing is filtered.</p> <pre><code>public function timeslip_meta_request_params($args, $request) { $args['meta_key'] = $request['timeslip_user_id']; $args['meta_value'] = intval($request['timeslip_user_id']); $valid_vars = array_merge( $args, array( 'meta_key', 'meta_value' ) ); return $valid_vars; // $args['meta_key'] = 'user_id'; // $args['meta_value'] = 1; return $args; } </code></pre> <p>If I set the $args manually then it works so I guess something is not being passed in.</p> <p>Reading around it seems the documentation has changed a lot it is hard to find the right way to do this. </p> <p>Any help much appreciated!</p>
[ { "answer_id": 346704, "author": "Roel Magdaleno", "author_id": 99204, "author_profile": "https://wordpress.stackexchange.com/users/99204", "pm_score": 2, "selected": true, "text": "<p>Add a third parameter in the <code>get_post_meta()</code> function as <strong>true</strong>, that will return the single value of the current post meta, if you don't set it it will return an array of the values.</p>\n\n<p>What is happening now is that internally the query is trying to compare the meta_value with an array instead of a string or integer and that's why you don't get any results.</p>\n\n<p>Also, your requested data should be the same name as the query params indicated in the current endpoint, if you put:</p>\n\n<p><code>/wp-json/wp/v2/timeslip?meta_key=user_id&amp;meta_value=1</code></p>\n\n<p>Then you access to the request data as:</p>\n\n<pre><code>$request['meta_key'];\n$request['meta_value'];\n</code></pre>\n\n<p>You originally set the requested data as:</p>\n\n<pre><code>$request['timeslip_user_id'];\n$request['timeslip_user_id'];\n</code></pre>\n\n<p>So your query filter function should looks like this:</p>\n\n<pre><code>function timeslip_meta_request_params( $args, $request ) {\n $args['meta_key'] = $request['meta_key'];\n $args['meta_value'] = $request['meta_value'];\n\n return $args;\n}\n</code></pre>\n\n<p>I just tested the code in a local env, check that the <strong>user_id</strong> field is an string. Hope if works for you:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yh9ta.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yh9ta.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 391241, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>In my case, I had to get the parameters with the <code>get_query_params()</code> method and I used a <code>meta_query</code> to set the values, looking like this:</p>\n<pre><code>function timeslip_meta_request_params( $args, $request ) {\n\n $query_params = $request-&gt;get_query_params();\n\n if ( isset( $query_params['meta_key'] ) &amp;&amp; isset( $query_params['meta_value'] ) ) {\n $args['meta_query'] = array(\n [\n 'key' =&gt; sanitize_text_field( $query_params['meta_key'] ),\n 'value' =&gt; sanitize_text_field( $query_params['meta_value'] )\n ]\n );\n }\n\n return $args;\n}\n</code></pre>\n" } ]
2019/09/05
[ "https://wordpress.stackexchange.com/questions/346689", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28355/" ]
I have a posttype 'timeslip' and I am calling this with the following API endpoint: ``` /wp-json/wp/v2/timeslip?meta_key=user_id&meta_value=1 ``` I have exposed my custom field user\_id to the API meta and can see it in the response. ``` add_filter('rest_timeslip_query', array($this, 'timeslip_meta_request_params')); public function register_meta_api() { // Meta Fields that should be added to the API $timeslip_meta_fields = array( 'user_id', 'total_time', 'start_time', 'end_time', ); // Meta foreach ($timeslip_meta_fields as $field) { register_rest_field('timeslip', $field, array( 'get_callback' => array($this, 'get_meta'), 'update_callback' => array($this, 'update_meta'), 'schema' => null, ) ); } } public function get_meta($object, $field_name) { return get_post_meta($object['id'], $field_name); } ``` However nothing is filtered. ``` public function timeslip_meta_request_params($args, $request) { $args['meta_key'] = $request['timeslip_user_id']; $args['meta_value'] = intval($request['timeslip_user_id']); $valid_vars = array_merge( $args, array( 'meta_key', 'meta_value' ) ); return $valid_vars; // $args['meta_key'] = 'user_id'; // $args['meta_value'] = 1; return $args; } ``` If I set the $args manually then it works so I guess something is not being passed in. Reading around it seems the documentation has changed a lot it is hard to find the right way to do this. Any help much appreciated!
Add a third parameter in the `get_post_meta()` function as **true**, that will return the single value of the current post meta, if you don't set it it will return an array of the values. What is happening now is that internally the query is trying to compare the meta\_value with an array instead of a string or integer and that's why you don't get any results. Also, your requested data should be the same name as the query params indicated in the current endpoint, if you put: `/wp-json/wp/v2/timeslip?meta_key=user_id&meta_value=1` Then you access to the request data as: ``` $request['meta_key']; $request['meta_value']; ``` You originally set the requested data as: ``` $request['timeslip_user_id']; $request['timeslip_user_id']; ``` So your query filter function should looks like this: ``` function timeslip_meta_request_params( $args, $request ) { $args['meta_key'] = $request['meta_key']; $args['meta_value'] = $request['meta_value']; return $args; } ``` I just tested the code in a local env, check that the **user\_id** field is an string. Hope if works for you: [![enter image description here](https://i.stack.imgur.com/yh9ta.png)](https://i.stack.imgur.com/yh9ta.png)
346,696
<p>An administrator wants to make posts for a future date but not visible for visitors. The posts come from a custom <code>WP_Query</code> inside my plugin so the basical WP behaviour does not work in this case.</p> <p>I tried this :</p> <pre><code>$args = array( 'post_type' =&gt; "my-post-type", 'date_query' =&gt; array( 'before' =&gt; 'today', 'inclusive' =&gt; true ) ); $args['posts_per_page'] = -1; ... return new \WP_Query( $args ); </code></pre> <p>But if I wrote a post with the <code>post_date</code> is today, it does not appear. How can I include the post with <code>post_date</code> before today and today (1 second before now) ?</p>
[ { "answer_id": 346704, "author": "Roel Magdaleno", "author_id": 99204, "author_profile": "https://wordpress.stackexchange.com/users/99204", "pm_score": 2, "selected": true, "text": "<p>Add a third parameter in the <code>get_post_meta()</code> function as <strong>true</strong>, that will return the single value of the current post meta, if you don't set it it will return an array of the values.</p>\n\n<p>What is happening now is that internally the query is trying to compare the meta_value with an array instead of a string or integer and that's why you don't get any results.</p>\n\n<p>Also, your requested data should be the same name as the query params indicated in the current endpoint, if you put:</p>\n\n<p><code>/wp-json/wp/v2/timeslip?meta_key=user_id&amp;meta_value=1</code></p>\n\n<p>Then you access to the request data as:</p>\n\n<pre><code>$request['meta_key'];\n$request['meta_value'];\n</code></pre>\n\n<p>You originally set the requested data as:</p>\n\n<pre><code>$request['timeslip_user_id'];\n$request['timeslip_user_id'];\n</code></pre>\n\n<p>So your query filter function should looks like this:</p>\n\n<pre><code>function timeslip_meta_request_params( $args, $request ) {\n $args['meta_key'] = $request['meta_key'];\n $args['meta_value'] = $request['meta_value'];\n\n return $args;\n}\n</code></pre>\n\n<p>I just tested the code in a local env, check that the <strong>user_id</strong> field is an string. Hope if works for you:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yh9ta.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yh9ta.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 391241, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>In my case, I had to get the parameters with the <code>get_query_params()</code> method and I used a <code>meta_query</code> to set the values, looking like this:</p>\n<pre><code>function timeslip_meta_request_params( $args, $request ) {\n\n $query_params = $request-&gt;get_query_params();\n\n if ( isset( $query_params['meta_key'] ) &amp;&amp; isset( $query_params['meta_value'] ) ) {\n $args['meta_query'] = array(\n [\n 'key' =&gt; sanitize_text_field( $query_params['meta_key'] ),\n 'value' =&gt; sanitize_text_field( $query_params['meta_value'] )\n ]\n );\n }\n\n return $args;\n}\n</code></pre>\n" } ]
2019/09/05
[ "https://wordpress.stackexchange.com/questions/346696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
An administrator wants to make posts for a future date but not visible for visitors. The posts come from a custom `WP_Query` inside my plugin so the basical WP behaviour does not work in this case. I tried this : ``` $args = array( 'post_type' => "my-post-type", 'date_query' => array( 'before' => 'today', 'inclusive' => true ) ); $args['posts_per_page'] = -1; ... return new \WP_Query( $args ); ``` But if I wrote a post with the `post_date` is today, it does not appear. How can I include the post with `post_date` before today and today (1 second before now) ?
Add a third parameter in the `get_post_meta()` function as **true**, that will return the single value of the current post meta, if you don't set it it will return an array of the values. What is happening now is that internally the query is trying to compare the meta\_value with an array instead of a string or integer and that's why you don't get any results. Also, your requested data should be the same name as the query params indicated in the current endpoint, if you put: `/wp-json/wp/v2/timeslip?meta_key=user_id&meta_value=1` Then you access to the request data as: ``` $request['meta_key']; $request['meta_value']; ``` You originally set the requested data as: ``` $request['timeslip_user_id']; $request['timeslip_user_id']; ``` So your query filter function should looks like this: ``` function timeslip_meta_request_params( $args, $request ) { $args['meta_key'] = $request['meta_key']; $args['meta_value'] = $request['meta_value']; return $args; } ``` I just tested the code in a local env, check that the **user\_id** field is an string. Hope if works for you: [![enter image description here](https://i.stack.imgur.com/yh9ta.png)](https://i.stack.imgur.com/yh9ta.png)
346,707
<p>simple issue but i need some help because i dont why i m wrong on this...</p> <p>The apply filter (Important, this is in construct Class):</p> <pre><code> if ( apply_filters( 'tc_bridge_for_woocommerce_content_order_table_is_after', true ) == true ) { add_action( 'woocommerce_email_after_order_table', array( &amp;$this, 'tc_add_content_email_after_order_table' ), 99, 4 ); } else { add_action( 'woocommerce_email_before_order_table', array( &amp;$this, 'tc_add_content_email_after_order_table' ), 99, 4 ); } </code></pre> <p>I need to use the false from the conditionnal</p> <p>so in my functions.php from my theme </p> <pre><code>function filter_after_setup_theme() { add_filter( 'tc_bridge_for_woocommerce_content_order_table_is_after', '__return_false' ); // move info ticket in email before order details } add_action('after_setup_theme', 'filter_after_setup_theme'); </code></pre> <p>where i m wrong ?</p> <p>thanks</p>
[ { "answer_id": 346704, "author": "Roel Magdaleno", "author_id": 99204, "author_profile": "https://wordpress.stackexchange.com/users/99204", "pm_score": 2, "selected": true, "text": "<p>Add a third parameter in the <code>get_post_meta()</code> function as <strong>true</strong>, that will return the single value of the current post meta, if you don't set it it will return an array of the values.</p>\n\n<p>What is happening now is that internally the query is trying to compare the meta_value with an array instead of a string or integer and that's why you don't get any results.</p>\n\n<p>Also, your requested data should be the same name as the query params indicated in the current endpoint, if you put:</p>\n\n<p><code>/wp-json/wp/v2/timeslip?meta_key=user_id&amp;meta_value=1</code></p>\n\n<p>Then you access to the request data as:</p>\n\n<pre><code>$request['meta_key'];\n$request['meta_value'];\n</code></pre>\n\n<p>You originally set the requested data as:</p>\n\n<pre><code>$request['timeslip_user_id'];\n$request['timeslip_user_id'];\n</code></pre>\n\n<p>So your query filter function should looks like this:</p>\n\n<pre><code>function timeslip_meta_request_params( $args, $request ) {\n $args['meta_key'] = $request['meta_key'];\n $args['meta_value'] = $request['meta_value'];\n\n return $args;\n}\n</code></pre>\n\n<p>I just tested the code in a local env, check that the <strong>user_id</strong> field is an string. Hope if works for you:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yh9ta.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yh9ta.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 391241, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>In my case, I had to get the parameters with the <code>get_query_params()</code> method and I used a <code>meta_query</code> to set the values, looking like this:</p>\n<pre><code>function timeslip_meta_request_params( $args, $request ) {\n\n $query_params = $request-&gt;get_query_params();\n\n if ( isset( $query_params['meta_key'] ) &amp;&amp; isset( $query_params['meta_value'] ) ) {\n $args['meta_query'] = array(\n [\n 'key' =&gt; sanitize_text_field( $query_params['meta_key'] ),\n 'value' =&gt; sanitize_text_field( $query_params['meta_value'] )\n ]\n );\n }\n\n return $args;\n}\n</code></pre>\n" } ]
2019/09/05
[ "https://wordpress.stackexchange.com/questions/346707", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96285/" ]
simple issue but i need some help because i dont why i m wrong on this... The apply filter (Important, this is in construct Class): ``` if ( apply_filters( 'tc_bridge_for_woocommerce_content_order_table_is_after', true ) == true ) { add_action( 'woocommerce_email_after_order_table', array( &$this, 'tc_add_content_email_after_order_table' ), 99, 4 ); } else { add_action( 'woocommerce_email_before_order_table', array( &$this, 'tc_add_content_email_after_order_table' ), 99, 4 ); } ``` I need to use the false from the conditionnal so in my functions.php from my theme ``` function filter_after_setup_theme() { add_filter( 'tc_bridge_for_woocommerce_content_order_table_is_after', '__return_false' ); // move info ticket in email before order details } add_action('after_setup_theme', 'filter_after_setup_theme'); ``` where i m wrong ? thanks
Add a third parameter in the `get_post_meta()` function as **true**, that will return the single value of the current post meta, if you don't set it it will return an array of the values. What is happening now is that internally the query is trying to compare the meta\_value with an array instead of a string or integer and that's why you don't get any results. Also, your requested data should be the same name as the query params indicated in the current endpoint, if you put: `/wp-json/wp/v2/timeslip?meta_key=user_id&meta_value=1` Then you access to the request data as: ``` $request['meta_key']; $request['meta_value']; ``` You originally set the requested data as: ``` $request['timeslip_user_id']; $request['timeslip_user_id']; ``` So your query filter function should looks like this: ``` function timeslip_meta_request_params( $args, $request ) { $args['meta_key'] = $request['meta_key']; $args['meta_value'] = $request['meta_value']; return $args; } ``` I just tested the code in a local env, check that the **user\_id** field is an string. Hope if works for you: [![enter image description here](https://i.stack.imgur.com/yh9ta.png)](https://i.stack.imgur.com/yh9ta.png)
346,714
<p>I have a page template named <code>overview.php</code> which inside shows all the pages that are of the same category. As a result all the pages with the same category are printed but so is the current main page,because it is of the same category as well, and I don't want this to happen. So inside the loop I want to get the ID of every queried page and compare it to current main page ID so that nothing will happen when it is looped.</p> <p>This is how I query the pages:</p> <pre><code>$paged = (get_query_var( 'paged' )) ? get_query_var( 'paged' ) : 1; $args = array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'Published', 'category_name' =&gt; 'Football League', 'posts_per_page' =&gt; 12, 'paged' =&gt; $paged, ); $arr_posts = new WP_Query( $args ); if ( $arr_posts-&gt;have_posts() ) : while ( $arr_posts-&gt;have_posts() ) : $arr_posts-&gt;the_post(); ?&gt; </code></pre> <p>prints something about each page..</p> <pre><code>endwhile; wp_pagenavi( array( 'query' =&gt; $arr_posts, ) ); endif; ?&gt; </code></pre>
[ { "answer_id": 346716, "author": "Greg", "author_id": 123552, "author_profile": "https://wordpress.stackexchange.com/users/123552", "pm_score": -1, "selected": false, "text": "<p>You could store the \"current\" page ID in a variable outside of the loop.</p>\n" }, { "answer_id": 346724, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>The current queried page can be accessed with <code>get_queried_object()</code>, or if you just need the ID, you can use <code>get_queried_object_id()</code>.</p>\n\n<p>However, while comparing the current ID in the loop to the queried object ID will allow you to skip a specific post, it won't work well with your pagination, because the page that features the current page will only display 11 pages, rather than the 12 that it's supposed to.</p>\n\n<p>To exclude the current page you can use <code>post__not_in</code>, like this:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'Published',\n 'category_name' =&gt; 'Football League',\n 'posts_per_page' =&gt; 12,\n 'paged' =&gt; $paged,\n 'post__not_in' =&gt; get_queried_object_id(),\n);\n</code></pre>\n\n<p>However, if you have a lot of pages, the performance of this is not great.</p>\n\n<p>All that being said, if you're trying to create paginated lists of content, organised by category, then this is not the way I'd go about it. This seems like a good use case for a <a href=\"https://developer.wordpress.org/plugins/post-types/\" rel=\"nofollow noreferrer\">Custom Post Type</a> and <a href=\"https://developer.wordpress.org/plugins/taxonomies/working-with-custom-taxonomies/\" rel=\"nofollow noreferrer\">Custom Taxonomy</a>.</p>\n" } ]
2019/09/05
[ "https://wordpress.stackexchange.com/questions/346714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174691/" ]
I have a page template named `overview.php` which inside shows all the pages that are of the same category. As a result all the pages with the same category are printed but so is the current main page,because it is of the same category as well, and I don't want this to happen. So inside the loop I want to get the ID of every queried page and compare it to current main page ID so that nothing will happen when it is looped. This is how I query the pages: ``` $paged = (get_query_var( 'paged' )) ? get_query_var( 'paged' ) : 1; $args = array( 'post_type' => 'page', 'post_status' => 'Published', 'category_name' => 'Football League', 'posts_per_page' => 12, 'paged' => $paged, ); $arr_posts = new WP_Query( $args ); if ( $arr_posts->have_posts() ) : while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?> ``` prints something about each page.. ``` endwhile; wp_pagenavi( array( 'query' => $arr_posts, ) ); endif; ?> ```
The current queried page can be accessed with `get_queried_object()`, or if you just need the ID, you can use `get_queried_object_id()`. However, while comparing the current ID in the loop to the queried object ID will allow you to skip a specific post, it won't work well with your pagination, because the page that features the current page will only display 11 pages, rather than the 12 that it's supposed to. To exclude the current page you can use `post__not_in`, like this: ``` $args = array( 'post_type' => 'page', 'post_status' => 'Published', 'category_name' => 'Football League', 'posts_per_page' => 12, 'paged' => $paged, 'post__not_in' => get_queried_object_id(), ); ``` However, if you have a lot of pages, the performance of this is not great. All that being said, if you're trying to create paginated lists of content, organised by category, then this is not the way I'd go about it. This seems like a good use case for a [Custom Post Type](https://developer.wordpress.org/plugins/post-types/) and [Custom Taxonomy](https://developer.wordpress.org/plugins/taxonomies/working-with-custom-taxonomies/).
346,755
<p><strong>Context:</strong></p> <p>I'm making a WooCommerce/Dokan marketplace for people to sell second hand products. As this are second hand products each product should have an inventory of just 1. All products are simple products, no variations.</p> <p><strong>Problem</strong></p> <p>I want to set by default a stock of 1 to all products. I don't want the users dealing with setting the stock quantity by themselves.</p> <p><strong>What I've tried</strong></p> <ul> <li>I've done a lot of research and haven't found a solution, I came across this online tutorial: <br> <em>"<a href="https://www.skyverge.com/blog/set-default-stock-quantity-woocommerce-variations/" rel="nofollow noreferrer">Set a Default Stock Quantity for WooCommerce Products</a>"</em> that is what I'm looking for but, the code doesn't work anymore and produces the infamous white screen of death.</li> <li>I found some code to add to my child theme functions.php that sets the quantity value to 1 in the product page, it works but it isn't a complete solution because if someone buys a product the stock won't be reduced to zero and the product won't be hidden in the front-end.</li> </ul> <p><strong>What I would like to have</strong></p> <p>The ideal solution would be code to add to my child theme functions.php that sets stock quantity to 1 by default in all new published products. Of course I'm open to other solutions and plugins but the main goal is that this quantity is set automatically to all new products.</p> <p><strong>Notes</strong></p> <ul> <li>I'm not an experienced developer, I'm self thought, a designer transitioning, that's why I'm looking for help.</li> <li>I'm not lazy, I've done a lot of research in the past few days and tried many things but haven't found a solution.</li> </ul> <p>Any help you can provide is appreciated.</p>
[ { "answer_id": 346781, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>I believe in WooC the product stock data is saved as post meta with the key of <code>_stock</code>. If this is the case, then you can set the stock level just like any other post meta by hooking a custom function to <code>save_post</code> action.</p>\n\n<p>In you custom function you need to check that you're dealing with a new post and the right post type. This will overwrite any user submitted stock level data.</p>\n\n<pre><code>function save_product_meta( $post_id, $post, $update ) {\n // only new products\n if ( ! $update &amp;&amp; 'product' === $post-&gt;post_type ) {\n update_post_meta( $post_id, '_stock', 1 ); // stock count\n update_post_meta( $post_id, '_stock_status', 'instock' ); // stock status\n }\n}\nadd_action( 'save_post', 'save_product_meta', 10, 3 );\n</code></pre>\n\n<p>Please test and tweak the example above to suit your needs in a development environment before using it in a production site.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>You could also use the CPT specific save action,</p>\n\n<pre><code>function save_product_meta( $post_id, $post, $update ) {\n // only new products\n if ( ! $update ) {\n update_post_meta( $post_id, '_stock', 1 ); // stock count\n update_post_meta( $post_id, '_stock_status', 'instock' ); // stock status\n }\n}\nadd_action( 'save_post_product', 'save_product_meta', 10, 3 );\n</code></pre>\n" }, { "answer_id": 346789, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 1, "selected": false, "text": "<p>For \"New\" simple products on admin, the following embedded jQuery script will:</p>\n\n<ul>\n<li>trigger and enable \"Stock management\" at product level,</li>\n<li>set the \"Stock quantity\" to \"1\",</li>\n<li>set the \"Low stock threshold\" to \"0\".</li>\n</ul>\n\n<p>The code:</p>\n\n<pre><code>add_action( 'admin_footer', 'new_product_stock_default_setting' );\nfunction new_product_stock_default_setting() {\n global $pagenow, $post_type;\n\n // Targeting new product page (admin)\n if( $pagenow === 'post-new.php' &amp;&amp; $post_type === 'product' ) :\n ?&gt;\n &lt;script&gt;\n jQuery(function($){\n var a = '#inventory_product_data input#';\n\n // Set Manage Stock and trigger event to show other related fields\n $(a+'_manage_stock').prop('checked', true).change();\n $(a+'_stock').val('1'); // Set Stock quantity to \"1\"\n $(a+'_low_stock_amount').val('0'); // Set Low stock threshold to \"0\"\n });\n &lt;/script&gt;\n &lt;?php\n endif;\n}\n</code></pre>\n\n<p>Code goes in functions.php file of your active child theme (or active theme). Tested and works.</p>\n\n<p><a href=\"https://i.stack.imgur.com/fq09G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fq09G.png\" alt=\"enter image description here\"></a></p>\n" } ]
2019/09/06
[ "https://wordpress.stackexchange.com/questions/346755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14756/" ]
**Context:** I'm making a WooCommerce/Dokan marketplace for people to sell second hand products. As this are second hand products each product should have an inventory of just 1. All products are simple products, no variations. **Problem** I want to set by default a stock of 1 to all products. I don't want the users dealing with setting the stock quantity by themselves. **What I've tried** * I've done a lot of research and haven't found a solution, I came across this online tutorial: *"[Set a Default Stock Quantity for WooCommerce Products](https://www.skyverge.com/blog/set-default-stock-quantity-woocommerce-variations/)"* that is what I'm looking for but, the code doesn't work anymore and produces the infamous white screen of death. * I found some code to add to my child theme functions.php that sets the quantity value to 1 in the product page, it works but it isn't a complete solution because if someone buys a product the stock won't be reduced to zero and the product won't be hidden in the front-end. **What I would like to have** The ideal solution would be code to add to my child theme functions.php that sets stock quantity to 1 by default in all new published products. Of course I'm open to other solutions and plugins but the main goal is that this quantity is set automatically to all new products. **Notes** * I'm not an experienced developer, I'm self thought, a designer transitioning, that's why I'm looking for help. * I'm not lazy, I've done a lot of research in the past few days and tried many things but haven't found a solution. Any help you can provide is appreciated.
For "New" simple products on admin, the following embedded jQuery script will: * trigger and enable "Stock management" at product level, * set the "Stock quantity" to "1", * set the "Low stock threshold" to "0". The code: ``` add_action( 'admin_footer', 'new_product_stock_default_setting' ); function new_product_stock_default_setting() { global $pagenow, $post_type; // Targeting new product page (admin) if( $pagenow === 'post-new.php' && $post_type === 'product' ) : ?> <script> jQuery(function($){ var a = '#inventory_product_data input#'; // Set Manage Stock and trigger event to show other related fields $(a+'_manage_stock').prop('checked', true).change(); $(a+'_stock').val('1'); // Set Stock quantity to "1" $(a+'_low_stock_amount').val('0'); // Set Low stock threshold to "0" }); </script> <?php endif; } ``` Code goes in functions.php file of your active child theme (or active theme). Tested and works. [![enter image description here](https://i.stack.imgur.com/fq09G.png)](https://i.stack.imgur.com/fq09G.png)
346,830
<p>I am trying to pass args to archive.php so that I can order the posts, set the number of posts, etc..</p> <p>but the query is done like this </p> <pre><code>&lt;?php if (have_posts()): ?&gt; &lt;?php while (have_posts()): the_post();?&gt; </code></pre> <p>if it was<code>new \WP_Query($args);</code> i was able to pass the args here but this can't be done in archive.php template?</p>
[ { "answer_id": 346832, "author": "Matteo Feduzi", "author_id": 174135, "author_profile": "https://wordpress.stackexchange.com/users/174135", "pm_score": -1, "selected": false, "text": "<p>this is the code from my archive.php file:</p>\n\n<pre><code>$args = array( \n 'posts_per_page' =&gt; 3,\n 'order' =&gt; 'DESC'\n);\n\n$myposts = new WP_Query($args);\n\n&lt;?php if ( $myposts-&gt;have_posts() ) : ?&gt;\n\n &lt;?php while ( $myposts-&gt;have_posts() ) : $myposts-&gt;the_post(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;?php wp_reset_postdata(); ?&gt;\n\n&lt;?php else: ?&gt;\n\n //If there is no post for this category / tag\n\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>I hope I understood the question well and that I can help you.</p>\n\n<p>Best regards.</p>\n" }, { "answer_id": 346843, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": true, "text": "<p>The <code>pre_get_posts</code> hook can be used to modify queries before they're run. You can use <code>$query-&gt;set()</code> to set arguments on the <code>WP_Query</code> object, and <code>$query-&gt;is_main_query()</code> in the callback to limit your changes to the main query:</p>\n\n<pre><code>add_action(\n 'pre_get_posts',\n function( $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'posts_per_page', 12 );\n }\n }\n);\n</code></pre>\n\n<p>You can't target specific <em>templates</em>, but if you want the change to only affect archives, you can use <code>$query-&gt;is_archive()</code>, which will be true for date, taxonomy and post type archives, or if you only want to apply the changes to the category archives, you can use <code>$query-&gt;is_category()</code>. Many of the normal <a href=\"https://developer.wordpress.org/themes/basics/conditional-tags/\" rel=\"nofollow noreferrer\">conditional functions</a> are available as methods for checking the current query.</p>\n" } ]
2019/09/07
[ "https://wordpress.stackexchange.com/questions/346830", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am trying to pass args to archive.php so that I can order the posts, set the number of posts, etc.. but the query is done like this ``` <?php if (have_posts()): ?> <?php while (have_posts()): the_post();?> ``` if it was`new \WP_Query($args);` i was able to pass the args here but this can't be done in archive.php template?
The `pre_get_posts` hook can be used to modify queries before they're run. You can use `$query->set()` to set arguments on the `WP_Query` object, and `$query->is_main_query()` in the callback to limit your changes to the main query: ``` add_action( 'pre_get_posts', function( $query ) { if ( ! is_admin() && $query->is_main_query() ) { $query->set( 'posts_per_page', 12 ); } } ); ``` You can't target specific *templates*, but if you want the change to only affect archives, you can use `$query->is_archive()`, which will be true for date, taxonomy and post type archives, or if you only want to apply the changes to the category archives, you can use `$query->is_category()`. Many of the normal [conditional functions](https://developer.wordpress.org/themes/basics/conditional-tags/) are available as methods for checking the current query.
346,860
<p>How can I find what options or plugins are taking up all that size? It's not transients because after deleting all it's still 13GB.</p> <p><code>SELECT option_name, option_value FROM hihgv_options WHERE autoload = 'yes'</code> Returns 833 rows in 0.141 sec</p> <p><code>SELECT SUM(LENGTH(option_value)) as autoload_size FROM hihgv_options WHERE autoload='yes';</code> returns 670,540</p> <hr> <p>At one point it was 13GB and went down to MB when I move everything from the My Custom Functions plugin to the child theme's functions.php file.</p>
[ { "answer_id": 346861, "author": "Daviid", "author_id": 171564, "author_profile": "https://wordpress.stackexchange.com/users/171564", "pm_score": 2, "selected": true, "text": "<p>After executing these:</p>\n\n<pre><code>[root@shop ~]# mysqlcheck -p -c wordpress hihgv_options\nwordpress.hihgv_options OK\n[root@shop ~]# mysqlcheck -p -o wordpress hihgv_options\nwordpress.hihgv_options\nnote : Table does not support optimize, doing recreate + analyze instead\nstatus : OK\n[root@shop ~]# mysqlcheck -p -a wordpress hihgv_options\nwordpress.hihgv_options OK\n</code></pre>\n\n<p>Size is down to 1.6MB, not sure if it was optimize because I've done that before from HeidiSQL with no change at all.</p>\n\n<p>Edit:\nAlso the SQL queries from OP still return the same numbers.</p>\n\n<p>Edit 2:\nJust did it again, after executing:</p>\n\n<p><code>\n[root@shop wordpress]# mysqlcheck -p -o wordpress wp_options\nnote : Table does not support optimize, doing recreate + analyze instead\nstatus : OK\n</code></p>\n\n<p>It went from 3.9GB to 10MB.\nIf anyone knows exactly why I'd appreciate an explanation.</p>\n" }, { "answer_id": 411519, "author": "rubo77", "author_id": 37700, "author_profile": "https://wordpress.stackexchange.com/users/37700", "pm_score": 0, "selected": false, "text": "<p>For a start, you can delete all session entries with</p>\n<pre><code>DELETE\nFROM `wp_options`\nWHERE option_name LIKE '_wp_session%' \n</code></pre>\n<p>(this can take some hours, if you have millions of entries in your table)</p>\n<p>Then you should find out, why the sessions are not deleted when they are expired. There seems to be a buggy plugin, or the whole data-overhead is a relict of an old buggy WP version</p>\n" } ]
2019/09/08
[ "https://wordpress.stackexchange.com/questions/346860", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171564/" ]
How can I find what options or plugins are taking up all that size? It's not transients because after deleting all it's still 13GB. `SELECT option_name, option_value FROM hihgv_options WHERE autoload = 'yes'` Returns 833 rows in 0.141 sec `SELECT SUM(LENGTH(option_value)) as autoload_size FROM hihgv_options WHERE autoload='yes';` returns 670,540 --- At one point it was 13GB and went down to MB when I move everything from the My Custom Functions plugin to the child theme's functions.php file.
After executing these: ``` [root@shop ~]# mysqlcheck -p -c wordpress hihgv_options wordpress.hihgv_options OK [root@shop ~]# mysqlcheck -p -o wordpress hihgv_options wordpress.hihgv_options note : Table does not support optimize, doing recreate + analyze instead status : OK [root@shop ~]# mysqlcheck -p -a wordpress hihgv_options wordpress.hihgv_options OK ``` Size is down to 1.6MB, not sure if it was optimize because I've done that before from HeidiSQL with no change at all. Edit: Also the SQL queries from OP still return the same numbers. Edit 2: Just did it again, after executing: `[root@shop wordpress]# mysqlcheck -p -o wordpress wp_options note : Table does not support optimize, doing recreate + analyze instead status : OK` It went from 3.9GB to 10MB. If anyone knows exactly why I'd appreciate an explanation.
346,949
<p>I'm writing a plugin to block some pages to anonymous users on my site. I already blocked some pages but I can't get to identify the feed page <code>my-wordpress-site.com/feed</code>.</p> <p>I've tried:</p> <ul> <li><code>$GLOBALS['pagenow'] == 'feed'</code></li> <li><code>is_feed()</code></li> <li><code>is_page('feed')</code></li> <li>checking on <code>$_SERVER['REQUEST_URI']</code> and <code>$_SERVER['PATH_INFO']</code></li> </ul> <p>Any ideas on how to achieve that?</p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/09
[ "https://wordpress.stackexchange.com/questions/346949", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174889/" ]
I'm writing a plugin to block some pages to anonymous users on my site. I already blocked some pages but I can't get to identify the feed page `my-wordpress-site.com/feed`. I've tried: * `$GLOBALS['pagenow'] == 'feed'` * `is_feed()` * `is_page('feed')` * checking on `$_SERVER['REQUEST_URI']` and `$_SERVER['PATH_INFO']` Any ideas on how to achieve that?
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
346,955
<p>I'm trying to add property values for each user on a real estate website.</p> <p>I have a custom post type "properties." I'd like to take the "listing_price" from all of them and add them up to show how much that agent has for active listings.</p> <p>Really don't even know where to start. I see threads to add all custom post type meta values but not for a specific user.</p> <p>thank you</p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/09
[ "https://wordpress.stackexchange.com/questions/346955", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109430/" ]
I'm trying to add property values for each user on a real estate website. I have a custom post type "properties." I'd like to take the "listing\_price" from all of them and add them up to show how much that agent has for active listings. Really don't even know where to start. I see threads to add all custom post type meta values but not for a specific user. thank you
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
346,973
<p>Recently I got my website compromised so I cleaned it and enforce security. Among other things I've installed wordfence plugin that now scans everything in my worpdress installation, searched for the correct file permissions, etc...</p> <p>The problem is that I've found in a scan that many files (theme/functions.php and another files inside wp-includes) were modified AGAIN...so definetely I'm doing something wrong.</p> <p>Please anybody can give a complete guide to secure files in order no to be modified by attackers again?</p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/10
[ "https://wordpress.stackexchange.com/questions/346973", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174907/" ]
Recently I got my website compromised so I cleaned it and enforce security. Among other things I've installed wordfence plugin that now scans everything in my worpdress installation, searched for the correct file permissions, etc... The problem is that I've found in a scan that many files (theme/functions.php and another files inside wp-includes) were modified AGAIN...so definetely I'm doing something wrong. Please anybody can give a complete guide to secure files in order no to be modified by attackers again?
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
348,077
<p>I need to get the title from my custom post but its showing from my default post. here is my code. please help.<a href="https://i.stack.imgur.com/SYfy2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SYfy2.png" alt="enter image description here"></a></p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/11
[ "https://wordpress.stackexchange.com/questions/348077", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174994/" ]
I need to get the title from my custom post but its showing from my default post. here is my code. please help.[![enter image description here](https://i.stack.imgur.com/SYfy2.png)](https://i.stack.imgur.com/SYfy2.png)
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
348,105
<p>I would like to display order_item of order in admin list like in this screenshot:</p> <p><a href="https://i.stack.imgur.com/OQSyl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQSyl.png" alt="enter image description here"></a></p> <p>Changing <code>/woocommerce/includes/admin/list-tables/class-wc-admin-list-table-orders.php</code> file, I tried to add the following:</p> <pre><code>$product = wc_get_product( $product_id ); $ss = $product-&gt;get_name(); echo $ss echo $product-&gt;get_name(); echo get_the_title($product_id); // this one display the order date </code></pre> <p>But it didn't work.</p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/12
[ "https://wordpress.stackexchange.com/questions/348105", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175019/" ]
I would like to display order\_item of order in admin list like in this screenshot: [![enter image description here](https://i.stack.imgur.com/OQSyl.png)](https://i.stack.imgur.com/OQSyl.png) Changing `/woocommerce/includes/admin/list-tables/class-wc-admin-list-table-orders.php` file, I tried to add the following: ``` $product = wc_get_product( $product_id ); $ss = $product->get_name(); echo $ss echo $product->get_name(); echo get_the_title($product_id); // this one display the order date ``` But it didn't work.
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
348,175
<p>When creating a post <a href="https://wordpress.stackexchange.com/questions/151741/how-to-programmatically-create-posts-in-wordpress">programmatically</a> (with <code>wp_insert_post();</code>), how do you select the format? </p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/12
[ "https://wordpress.stackexchange.com/questions/348175", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
When creating a post [programmatically](https://wordpress.stackexchange.com/questions/151741/how-to-programmatically-create-posts-in-wordpress) (with `wp_insert_post();`), how do you select the format?
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
348,220
<p>Both functions return the website url.</p> <p>And, as home_url() needs sanitization (for example <code>&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;)</code>, why it is this snippet of code, instead of <code>&lt;?php echo get_ home_url( '/' ); ?&gt;</code>, that we found in Wordpress Codex and Wordpress Template Twenty Nineteen ?</p>
[ { "answer_id": 348182, "author": "freejack", "author_id": 124757, "author_profile": "https://wordpress.stackexchange.com/users/124757", "pm_score": 4, "selected": true, "text": "<p>You have not specified exactly when your code runs but you can hook into \"request\" to check the requested page:</p>\n\n<pre><code>add_filter( 'request', function( $request ){\n if( isset( $request['feed'] ) ){\n //This is a feed request\n }\n return $request;\n});\n</code></pre>\n\n<p>When the requested page is a feed <code>$request</code>, which is an array of query variables, will contain an item called \"feed\" which is set with the name of the feed like \"rss\" for example.\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/request</a></p>\n" }, { "answer_id": 348212, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": false, "text": "<p>You're not specifying where you are hooking your action, but most likely you are hooking too soon, because <a href=\"https://developer.wordpress.org/reference/functions/is_feed/\" rel=\"nofollow noreferrer\"><code>is_feed</code></a> should really do the trick. Let's take a look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">WordPress hook order</a>.</p>\n\n<p>As you can see the usual hook for plugins is <code>init</code>. However, at that point WP is not yet fully loaded. Only after the <code>wp_loaded</code> hook, WP starts processing the query. Because <code>is_feed</code> is a function of the <code>$wp_query</code> class it will not return <code>true</code> before this point.</p>\n\n<p>So, you can still hook the main function of your plugin into <code>init</code>, but you must make sure that inside that function you add an action to a later hook. The most logical hook is <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code></a>, because what you want is to serve a different (empty) page to some users. It would amount to this:</p>\n\n<pre><code> [inside your plugins main function]\n add_action ('template_redirect','wpse346949_redirect_feed');\n\n [elsewhere in your plugin]\n function wpse346949_redirect_feed () {\n if (is_feed () &amp;&amp; ( ... other conditions ... ) ) {\n wp_redirect (home_url ());\n die;\n }\n }\n</code></pre>\n\n<p>This will lead users to your homepage, but you can of course specify any other page, or even send them into the woods by not redirecting them at all and just cut off the page rendering.</p>\n" } ]
2019/09/13
[ "https://wordpress.stackexchange.com/questions/348220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175093/" ]
Both functions return the website url. And, as home\_url() needs sanitization (for example `<?php echo esc_url( home_url( '/' ) ); ?>)`, why it is this snippet of code, instead of `<?php echo get_ home_url( '/' ); ?>`, that we found in Wordpress Codex and Wordpress Template Twenty Nineteen ?
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: ``` add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); ``` When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <https://codex.wordpress.org/Plugin_API/Filter_Reference/request>
348,237
<p>I am witnessing a strange problem in WordPress which automatically removes 'http' from my sub domain link. I don't know why this is happening.</p> <p>Note that my domain is <em>https</em> while it's subdomain is <em>http</em>.</p> <p>My WordPress is installed in my main domain. When I add the below url of my sub domain to any post:</p> <pre><code>&lt;a href="http://www.demo.yogihosting.com/jquery/jquery-removedata/"&gt;DEMO&lt;/a&gt; </code></pre> <p>Then it automatically converts it to:</p> <pre><code>&lt;a href="//www.demo.yogihosting.com/jquery/jquery-removedata/"&gt;DEMO&lt;/a&gt; </code></pre> <p>See that the <strong>http</strong> is gone from the URL. </p> <p>Also see this below gif image which lists this problem:</p> <p><a href="https://i.stack.imgur.com/Tl885.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tl885.gif" alt="enter image description here"></a></p> <p>Why this is happening and how to solve this problem.</p>
[ { "answer_id": 348248, "author": "Matthew Brown aka Lord Matt", "author_id": 109240, "author_profile": "https://wordpress.stackexchange.com/users/109240", "pm_score": 1, "selected": false, "text": "<p>You might find that you do not want to solve this one. Links starting //example.com are protocol agnostic. This means it will load over whatever the site it is on loads over. Be that http, http<strong>s</strong>, or some truly esoteric.</p>\n\n<p>You should find that links like this work in both secure and insecure connections just fine. It looks odd if you have never seen it before but it works really well.</p>\n" }, { "answer_id": 348427, "author": "Gurpreet Singh", "author_id": 172262, "author_profile": "https://wordpress.stackexchange.com/users/172262", "pm_score": 0, "selected": false, "text": "<p>Are you using any SSL plugin? If not it might be becauee you enabled Full or flexible SSL in Cloudflare.</p>\n\n<p>Dude, why would you add www in front of your subdomain? zeez </p>\n" }, { "answer_id": 348475, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 0, "selected": false, "text": "<p>A proper subdomain takes the place of the 'www', which should not be there at all.....so your subdomain URL should be \"<a href=\"http://demo.yogihosting.com/jquery/jquery-removedata/\" rel=\"nofollow noreferrer\">http://demo.yogihosting.com/jquery/jquery-removedata/</a>\" instead of as you show it above......perhaps you have a typo in your original question?</p>\n" } ]
2019/09/13
[ "https://wordpress.stackexchange.com/questions/348237", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175101/" ]
I am witnessing a strange problem in WordPress which automatically removes 'http' from my sub domain link. I don't know why this is happening. Note that my domain is *https* while it's subdomain is *http*. My WordPress is installed in my main domain. When I add the below url of my sub domain to any post: ``` <a href="http://www.demo.yogihosting.com/jquery/jquery-removedata/">DEMO</a> ``` Then it automatically converts it to: ``` <a href="//www.demo.yogihosting.com/jquery/jquery-removedata/">DEMO</a> ``` See that the **http** is gone from the URL. Also see this below gif image which lists this problem: [![enter image description here](https://i.stack.imgur.com/Tl885.gif)](https://i.stack.imgur.com/Tl885.gif) Why this is happening and how to solve this problem.
You might find that you do not want to solve this one. Links starting //example.com are protocol agnostic. This means it will load over whatever the site it is on loads over. Be that http, http**s**, or some truly esoteric. You should find that links like this work in both secure and insecure connections just fine. It looks odd if you have never seen it before but it works really well.
348,257
<p>The search form on my website has a couple radio inputs for the user to select which source (all but one are external to the website) the search query should use. </p> <p>I retrieve those inputs (search term and source as ) ; </p> <pre><code>function search_redirect_form() { if (is_search() &amp;&amp; ! empty( $_GET['simple'] ) ) { if (isset($_GET['simple']) &amp;&amp; $_GET['simple'] == 'dogpile') { $query = $_GET["s"]; wp_redirect(esc_url_raw('theurl1'. $query)); exit(); } if (isset($_GET['simple']) &amp;&amp; $_GET['simple'] == 'askjeeves') { $query = sanitize_text_field($_GET["s"]); wp_redirect(esc_url('url3' . $query)); exit(); } else { $query = sanitize_text_field($_GET["s"]); wp_redirect(esc_url($home_url . "?s=" . $query)); exit(); } </code></pre> <p>When a user inputs a special character ((apostrophe, ampersand)) the remaining text of the query is often removed; For example: "earth wind &amp; fire" just ends up as "earth wind"</p> <p>From reading <a href="https://codex.wordpress.org/Data_Validation#URLs" rel="nofollow noreferrer">the codex</a>, I thought esc_raw_url would be the most appropriate to use; but that still results in queries being butchered on the other search engines, namely with the ampersand (&amp;) where the remaining part of the query is cut off. ("Earth wind &amp; fire" becomes "earth wind").</p> <p>At this point, I'm sort of wondering because wp_redirect does additional escaping (via <a href="https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L1283" rel="nofollow noreferrer">wp_sanitize_redirect</a>), that this may be a bug; but I'm still rusty with php and not sure. This is also probably confounded that the other websites may escape/sanitize inputs slightly differently. </p> <p>Questions: </p> <ol> <li>Should I be escaping on the input itself instead of the URL?) (around the "s" variable in my example);</li> </ol>
[ { "answer_id": 348261, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 0, "selected": false, "text": "<p>You could try just removing anything that had the potential to alter your url. I would suggest something like the following:</p>\n\n<pre><code>$str = sanitize_text_field($_GET[\"s\"]);\n// Remove anything that is not: alphanumeric, slash, dash or space.\n$query = preg_replace('/[^a-zA-Z0-9 \\-\\_]*/','',$str);\n</code></pre>\n" }, { "answer_id": 348263, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 2, "selected": true, "text": "<p>Right after posting, I learned a couple things, most importantly, <a href=\"https://www.gyrocode.com/articles/php-urlencode-vs-rawurlencode/\" rel=\"nofollow noreferrer\">that url encoding is done differently for paths and queries</a> and one of our search sources treats the search query as a path, so I had to use rawurlencode for the path; and urlencode for the others. This is why I was receiving inconsistent results from trying different search engines. </p>\n\n<p>There are a few sanitization functions within <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L1205\" rel=\"nofollow noreferrer\">wp_redirect</a> as well. </p>\n\n<pre><code>function search_redirect_form() {\n if (is_search() &amp;&amp; ! empty( $_GET['simple'] ) ) {\n if ( isset( $_GET['simple'] ) &amp;&amp; $_GET['simple'] === 'dogpile') {\n $query = urlencode( $_GET[\"s\"] )\n wp_redirect(esc_url('url1' . $query));\n exit(); \n }\n if ( isset( $_GET['simple'] ) &amp;&amp; $_GET['simple'] === 'altavista') {\n $query = rawurlencode( $_GET[\"s\"] );\n wp_redirect(esc_url('url2'. $query .'/field/all/mode/all/conn/and/order/nosort'));\n exit(); \n }\n if ( isset( $_GET['simple'] ) &amp;&amp; $_GET['simple'] === 'askjeeves') {\n $query = urlencode( $_GET[\"s\"] )\n wp_redirect(esc_url('url3' . $query));\n exit(); \n }\n else { \n $query = urlencode( $_GET[\"s\"] )\n wp_redirect(esc_url($home_url . \"?s=\" . $query));\n exit(); \n } \n }\n} add_action( 'pre_get_posts', 'search_redirect_form', 1 );\n</code></pre>\n" } ]
2019/09/13
[ "https://wordpress.stackexchange.com/questions/348257", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48698/" ]
The search form on my website has a couple radio inputs for the user to select which source (all but one are external to the website) the search query should use. I retrieve those inputs (search term and source as ) ; ``` function search_redirect_form() { if (is_search() && ! empty( $_GET['simple'] ) ) { if (isset($_GET['simple']) && $_GET['simple'] == 'dogpile') { $query = $_GET["s"]; wp_redirect(esc_url_raw('theurl1'. $query)); exit(); } if (isset($_GET['simple']) && $_GET['simple'] == 'askjeeves') { $query = sanitize_text_field($_GET["s"]); wp_redirect(esc_url('url3' . $query)); exit(); } else { $query = sanitize_text_field($_GET["s"]); wp_redirect(esc_url($home_url . "?s=" . $query)); exit(); } ``` When a user inputs a special character ((apostrophe, ampersand)) the remaining text of the query is often removed; For example: "earth wind & fire" just ends up as "earth wind" From reading [the codex](https://codex.wordpress.org/Data_Validation#URLs), I thought esc\_raw\_url would be the most appropriate to use; but that still results in queries being butchered on the other search engines, namely with the ampersand (&) where the remaining part of the query is cut off. ("Earth wind & fire" becomes "earth wind"). At this point, I'm sort of wondering because wp\_redirect does additional escaping (via [wp\_sanitize\_redirect](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L1283)), that this may be a bug; but I'm still rusty with php and not sure. This is also probably confounded that the other websites may escape/sanitize inputs slightly differently. Questions: 1. Should I be escaping on the input itself instead of the URL?) (around the "s" variable in my example);
Right after posting, I learned a couple things, most importantly, [that url encoding is done differently for paths and queries](https://www.gyrocode.com/articles/php-urlencode-vs-rawurlencode/) and one of our search sources treats the search query as a path, so I had to use rawurlencode for the path; and urlencode for the others. This is why I was receiving inconsistent results from trying different search engines. There are a few sanitization functions within [wp\_redirect](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L1205) as well. ``` function search_redirect_form() { if (is_search() && ! empty( $_GET['simple'] ) ) { if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'dogpile') { $query = urlencode( $_GET["s"] ) wp_redirect(esc_url('url1' . $query)); exit(); } if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'altavista') { $query = rawurlencode( $_GET["s"] ); wp_redirect(esc_url('url2'. $query .'/field/all/mode/all/conn/and/order/nosort')); exit(); } if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'askjeeves') { $query = urlencode( $_GET["s"] ) wp_redirect(esc_url('url3' . $query)); exit(); } else { $query = urlencode( $_GET["s"] ) wp_redirect(esc_url($home_url . "?s=" . $query)); exit(); } } } add_action( 'pre_get_posts', 'search_redirect_form', 1 ); ```
348,292
<p>EDIT</p> <p>May be my question is not well formed i need to use the url <a href="http://localhost/wordpress/houses/all-houses" rel="nofollow noreferrer">http://localhost/wordpress/houses/all-houses</a> to display a house plugin view somewhere in plugin directory</p> <pre><code>function getHouses(){ include plugin_dir_path(__FILE__) . 'public/publicHouse.php'; } </code></pre> <p>the result i'm getting is on the picture below</p> <p><a href="https://i.stack.imgur.com/HZt99.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HZt99.png" alt="enter image description here"></a></p> <p>I'm expecting the view with the whole template and houses view inside body template area</p> <p>any help is appreciated</p>
[ { "answer_id": 348261, "author": "Mike Baxter", "author_id": 38628, "author_profile": "https://wordpress.stackexchange.com/users/38628", "pm_score": 0, "selected": false, "text": "<p>You could try just removing anything that had the potential to alter your url. I would suggest something like the following:</p>\n\n<pre><code>$str = sanitize_text_field($_GET[\"s\"]);\n// Remove anything that is not: alphanumeric, slash, dash or space.\n$query = preg_replace('/[^a-zA-Z0-9 \\-\\_]*/','',$str);\n</code></pre>\n" }, { "answer_id": 348263, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 2, "selected": true, "text": "<p>Right after posting, I learned a couple things, most importantly, <a href=\"https://www.gyrocode.com/articles/php-urlencode-vs-rawurlencode/\" rel=\"nofollow noreferrer\">that url encoding is done differently for paths and queries</a> and one of our search sources treats the search query as a path, so I had to use rawurlencode for the path; and urlencode for the others. This is why I was receiving inconsistent results from trying different search engines. </p>\n\n<p>There are a few sanitization functions within <a href=\"https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L1205\" rel=\"nofollow noreferrer\">wp_redirect</a> as well. </p>\n\n<pre><code>function search_redirect_form() {\n if (is_search() &amp;&amp; ! empty( $_GET['simple'] ) ) {\n if ( isset( $_GET['simple'] ) &amp;&amp; $_GET['simple'] === 'dogpile') {\n $query = urlencode( $_GET[\"s\"] )\n wp_redirect(esc_url('url1' . $query));\n exit(); \n }\n if ( isset( $_GET['simple'] ) &amp;&amp; $_GET['simple'] === 'altavista') {\n $query = rawurlencode( $_GET[\"s\"] );\n wp_redirect(esc_url('url2'. $query .'/field/all/mode/all/conn/and/order/nosort'));\n exit(); \n }\n if ( isset( $_GET['simple'] ) &amp;&amp; $_GET['simple'] === 'askjeeves') {\n $query = urlencode( $_GET[\"s\"] )\n wp_redirect(esc_url('url3' . $query));\n exit(); \n }\n else { \n $query = urlencode( $_GET[\"s\"] )\n wp_redirect(esc_url($home_url . \"?s=\" . $query));\n exit(); \n } \n }\n} add_action( 'pre_get_posts', 'search_redirect_form', 1 );\n</code></pre>\n" } ]
2019/09/14
[ "https://wordpress.stackexchange.com/questions/348292", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175133/" ]
EDIT May be my question is not well formed i need to use the url <http://localhost/wordpress/houses/all-houses> to display a house plugin view somewhere in plugin directory ``` function getHouses(){ include plugin_dir_path(__FILE__) . 'public/publicHouse.php'; } ``` the result i'm getting is on the picture below [![enter image description here](https://i.stack.imgur.com/HZt99.png)](https://i.stack.imgur.com/HZt99.png) I'm expecting the view with the whole template and houses view inside body template area any help is appreciated
Right after posting, I learned a couple things, most importantly, [that url encoding is done differently for paths and queries](https://www.gyrocode.com/articles/php-urlencode-vs-rawurlencode/) and one of our search sources treats the search query as a path, so I had to use rawurlencode for the path; and urlencode for the others. This is why I was receiving inconsistent results from trying different search engines. There are a few sanitization functions within [wp\_redirect](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L1205) as well. ``` function search_redirect_form() { if (is_search() && ! empty( $_GET['simple'] ) ) { if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'dogpile') { $query = urlencode( $_GET["s"] ) wp_redirect(esc_url('url1' . $query)); exit(); } if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'altavista') { $query = rawurlencode( $_GET["s"] ); wp_redirect(esc_url('url2'. $query .'/field/all/mode/all/conn/and/order/nosort')); exit(); } if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'askjeeves') { $query = urlencode( $_GET["s"] ) wp_redirect(esc_url('url3' . $query)); exit(); } else { $query = urlencode( $_GET["s"] ) wp_redirect(esc_url($home_url . "?s=" . $query)); exit(); } } } add_action( 'pre_get_posts', 'search_redirect_form', 1 ); ```
348,298
<p>I am currently modernising an old WordPress theme (a standalone theme, not a child of any official themes). Trying to build pagination I am finding some issues creating one function that works for both archives and search. The first snippet works fine with archives (categories, loops, etc):</p> <pre><code>function pagination_bar() { global $wp_query; $total_pages = $wp_query-&gt;max_num_pages; if ($total_pages &gt; 1){ $current_page = max(1, get_query_var('paged')); echo paginate_links(array( 'base' =&gt; get_pagenum_link(1) . '%_%', 'format' =&gt; 'page/%#%', 'current' =&gt; $current_page, 'total' =&gt; $total_pages, 'prev_text' =&gt; __('« Previous page'), 'next_text' =&gt; __('Next page »'), )); } } </code></pre> <p>The problem is that if I use in search results pages the links end up being <code>domain.com/?s=QUERYpage/2</code> (whilst it should be <code>domain.com/page/2/?s=query</code>)</p> <p>So I created a custom function just for pagination in search:</p> <pre><code>function pagination_bar_search() { global $wp_query; $total_pages = $wp_query-&gt;max_num_pages; if ($total_pages &gt; 1){ $current_page = max(1, get_query_var('paged')); echo paginate_links(array( 'base' =&gt; get_home_url() . '%_%', 'format' =&gt; '/page/%#%/', 'current' =&gt; $current_page, 'total' =&gt; $total_pages, 'prev_text' =&gt; __('« Previous page'), 'next_text' =&gt; __('Next page »'), )); } } </code></pre> <p>Both work correctly, but do you have any ideas for how I can combine the 2 functions and make one that works correctly for both archives and search?</p> <p>I'm on the latest WordPress (5.2.3).</p> <p>This is the <code>search.php</code> loop function:</p> <pre><code>&lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; if ($wp_query-&gt;max_num_pages &gt; 1) echo 'Page ' . $paged.' of '.$wp_query-&gt;max_num_pages; ?&gt; ... &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; ... &lt;?php endwhile; ?&gt; &lt;?php pagination_bar_search(); ?&gt; </code></pre>
[ { "answer_id": 348315, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>From the <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Examples\" rel=\"nofollow noreferrer\">Codex</a>:</p>\n\n<blockquote>\n <p>To add pagination to your <em>search results and archives</em>, you can use\n the following example:</p>\n\n<pre><code>&lt;?php\nglobal $wp_query;\n\n$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; $wp_query-&gt;max_num_pages\n) );\n?&gt;\n</code></pre>\n</blockquote>\n\n<p>So based on that, I modified your function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function pagination_bar( $query = null ) {\n global $wp_query;\n\n $total_pages = $query ?\n $query-&gt;max_num_pages :\n $wp_query-&gt;max_num_pages;\n\n if ( $total_pages &gt; 1 ) {\n $big = 999999999; // need an unlikely integer\n $current_page = max( 1, get_query_var( 'paged' ) );\n\n echo paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; $current_page,\n 'total' =&gt; $total_pages,\n 'prev_text' =&gt; __( '« Previous page' ),\n 'next_text' =&gt; __( 'Next page »' ),\n ) );\n }\n}\n</code></pre>\n\n<p>and it worked well, both with archives and search results.</p>\n\n<p>I also added support for custom query (i.e. <code>new WP_Query</code>), so that you could for example do:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$my_query = new WP_Query( array( ... ) );\npagination_bar( $my_query );\n</code></pre>\n" }, { "answer_id": 348742, "author": "Simo Patrek", "author_id": 133002, "author_profile": "https://wordpress.stackexchange.com/users/133002", "pm_score": 0, "selected": false, "text": "<p>I'm facing the same problem even after using the above approach, the problem for me isn't coming from the WP_Query Class or the pagination.</p>\n\n<p>I just figured out that the <strong>offset</strong> parameter ignores and breaks the <strong>paged</strong> parameter and the whole pagination, and the thing is I can't let go of the <strong>offset</strong> parameter as my theme structure relies on it. Is there any solution for this matter?\nThanks</p>\n" }, { "answer_id": 399073, "author": "Robert Went", "author_id": 99385, "author_profile": "https://wordpress.stackexchange.com/users/99385", "pm_score": 0, "selected": false, "text": "<p>To keep the same format rather than using a query argument, I added a check in the function to see if we are on a search page or not and modified the base and format.</p>\n<pre><code>/**\n * Numbered pagination\n */\nfunction so_348298_pagination_links() {\n global $wp_query;\n\n $total_pages = $wp_query-&gt;max_num_pages;\n\n if ( $total_pages &gt; 1 ) {\n $current_page = max( 1, get_query_var( 'paged' ) );\n\n $base = get_pagenum_link( 1 ) . '%_%';\n $format = 'page/%#%';\n\n if (is_search()) {\n $base = get_home_url() . '%_%';\n $format = '/page/%#%/';\n }\n\n echo '&lt;div class=&quot;pagination-links col-12 text-center mb-5&quot;&gt;' .\n paginate_links( array(\n 'base' =&gt; $base,\n 'format' =&gt; $format,\n 'current' =&gt; $current_page,\n 'total' =&gt; $total_pages,\n 'type' =&gt; 'list',\n ) ) .\n '&lt;/div&gt;';\n }\n}\n</code></pre>\n" } ]
2019/09/14
[ "https://wordpress.stackexchange.com/questions/348298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23296/" ]
I am currently modernising an old WordPress theme (a standalone theme, not a child of any official themes). Trying to build pagination I am finding some issues creating one function that works for both archives and search. The first snippet works fine with archives (categories, loops, etc): ``` function pagination_bar() { global $wp_query; $total_pages = $wp_query->max_num_pages; if ($total_pages > 1){ $current_page = max(1, get_query_var('paged')); echo paginate_links(array( 'base' => get_pagenum_link(1) . '%_%', 'format' => 'page/%#%', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => __('« Previous page'), 'next_text' => __('Next page »'), )); } } ``` The problem is that if I use in search results pages the links end up being `domain.com/?s=QUERYpage/2` (whilst it should be `domain.com/page/2/?s=query`) So I created a custom function just for pagination in search: ``` function pagination_bar_search() { global $wp_query; $total_pages = $wp_query->max_num_pages; if ($total_pages > 1){ $current_page = max(1, get_query_var('paged')); echo paginate_links(array( 'base' => get_home_url() . '%_%', 'format' => '/page/%#%/', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => __('« Previous page'), 'next_text' => __('Next page »'), )); } } ``` Both work correctly, but do you have any ideas for how I can combine the 2 functions and make one that works correctly for both archives and search? I'm on the latest WordPress (5.2.3). This is the `search.php` loop function: ``` <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; if ($wp_query->max_num_pages > 1) echo 'Page ' . $paged.' of '.$wp_query->max_num_pages; ?> ... <?php if (have_posts()) : while (have_posts()) : the_post(); ?> ... <?php endwhile; ?> <?php pagination_bar_search(); ?> ```
From the [Codex](https://codex.wordpress.org/Function_Reference/paginate_links#Examples): > > To add pagination to your *search results and archives*, you can use > the following example: > > > > ``` > <?php > global $wp_query; > > $big = 999999999; // need an unlikely integer > > echo paginate_links( array( > 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), > 'format' => '?paged=%#%', > 'current' => max( 1, get_query_var('paged') ), > 'total' => $wp_query->max_num_pages > ) ); > ?> > > ``` > > So based on that, I modified your function: ```php function pagination_bar( $query = null ) { global $wp_query; $total_pages = $query ? $query->max_num_pages : $wp_query->max_num_pages; if ( $total_pages > 1 ) { $big = 999999999; // need an unlikely integer $current_page = max( 1, get_query_var( 'paged' ) ); echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => __( '« Previous page' ), 'next_text' => __( 'Next page »' ), ) ); } } ``` and it worked well, both with archives and search results. I also added support for custom query (i.e. `new WP_Query`), so that you could for example do: ```php $my_query = new WP_Query( array( ... ) ); pagination_bar( $my_query ); ```
348,300
<p>I'm really not a developer, but this is something I <strong>expect</strong> not to be too hard to achieve :-) I really don't know where to start, so that's point 1. I read all of the topics about dynamically changing the widget title, but they all need human interaction.</p> <p>Maybe I'm thinking too simple, but wouldn't it be easy to replace the default WOOCommerce Widget title (ie. "<strong>Product categories</strong>") by the parent category title? </p> <p>Let's say that I'm browsing through the category "<strong>Nike</strong>" where I'm viewing products or categories, and the sub-categories are showing in the widget (ie. <strong>Shoes</strong>, <strong>Shirts</strong>, <strong>etc</strong>.). In this case the widget title "<strong>Product categories</strong>" should show "<strong>Nike</strong>" as widget title.</p> <p>Could you help me getting it up and running?</p>
[ { "answer_id": 348315, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>From the <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Examples\" rel=\"nofollow noreferrer\">Codex</a>:</p>\n\n<blockquote>\n <p>To add pagination to your <em>search results and archives</em>, you can use\n the following example:</p>\n\n<pre><code>&lt;?php\nglobal $wp_query;\n\n$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; $wp_query-&gt;max_num_pages\n) );\n?&gt;\n</code></pre>\n</blockquote>\n\n<p>So based on that, I modified your function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function pagination_bar( $query = null ) {\n global $wp_query;\n\n $total_pages = $query ?\n $query-&gt;max_num_pages :\n $wp_query-&gt;max_num_pages;\n\n if ( $total_pages &gt; 1 ) {\n $big = 999999999; // need an unlikely integer\n $current_page = max( 1, get_query_var( 'paged' ) );\n\n echo paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'current' =&gt; $current_page,\n 'total' =&gt; $total_pages,\n 'prev_text' =&gt; __( '« Previous page' ),\n 'next_text' =&gt; __( 'Next page »' ),\n ) );\n }\n}\n</code></pre>\n\n<p>and it worked well, both with archives and search results.</p>\n\n<p>I also added support for custom query (i.e. <code>new WP_Query</code>), so that you could for example do:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$my_query = new WP_Query( array( ... ) );\npagination_bar( $my_query );\n</code></pre>\n" }, { "answer_id": 348742, "author": "Simo Patrek", "author_id": 133002, "author_profile": "https://wordpress.stackexchange.com/users/133002", "pm_score": 0, "selected": false, "text": "<p>I'm facing the same problem even after using the above approach, the problem for me isn't coming from the WP_Query Class or the pagination.</p>\n\n<p>I just figured out that the <strong>offset</strong> parameter ignores and breaks the <strong>paged</strong> parameter and the whole pagination, and the thing is I can't let go of the <strong>offset</strong> parameter as my theme structure relies on it. Is there any solution for this matter?\nThanks</p>\n" }, { "answer_id": 399073, "author": "Robert Went", "author_id": 99385, "author_profile": "https://wordpress.stackexchange.com/users/99385", "pm_score": 0, "selected": false, "text": "<p>To keep the same format rather than using a query argument, I added a check in the function to see if we are on a search page or not and modified the base and format.</p>\n<pre><code>/**\n * Numbered pagination\n */\nfunction so_348298_pagination_links() {\n global $wp_query;\n\n $total_pages = $wp_query-&gt;max_num_pages;\n\n if ( $total_pages &gt; 1 ) {\n $current_page = max( 1, get_query_var( 'paged' ) );\n\n $base = get_pagenum_link( 1 ) . '%_%';\n $format = 'page/%#%';\n\n if (is_search()) {\n $base = get_home_url() . '%_%';\n $format = '/page/%#%/';\n }\n\n echo '&lt;div class=&quot;pagination-links col-12 text-center mb-5&quot;&gt;' .\n paginate_links( array(\n 'base' =&gt; $base,\n 'format' =&gt; $format,\n 'current' =&gt; $current_page,\n 'total' =&gt; $total_pages,\n 'type' =&gt; 'list',\n ) ) .\n '&lt;/div&gt;';\n }\n}\n</code></pre>\n" } ]
2019/09/14
[ "https://wordpress.stackexchange.com/questions/348300", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85557/" ]
I'm really not a developer, but this is something I **expect** not to be too hard to achieve :-) I really don't know where to start, so that's point 1. I read all of the topics about dynamically changing the widget title, but they all need human interaction. Maybe I'm thinking too simple, but wouldn't it be easy to replace the default WOOCommerce Widget title (ie. "**Product categories**") by the parent category title? Let's say that I'm browsing through the category "**Nike**" where I'm viewing products or categories, and the sub-categories are showing in the widget (ie. **Shoes**, **Shirts**, **etc**.). In this case the widget title "**Product categories**" should show "**Nike**" as widget title. Could you help me getting it up and running?
From the [Codex](https://codex.wordpress.org/Function_Reference/paginate_links#Examples): > > To add pagination to your *search results and archives*, you can use > the following example: > > > > ``` > <?php > global $wp_query; > > $big = 999999999; // need an unlikely integer > > echo paginate_links( array( > 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), > 'format' => '?paged=%#%', > 'current' => max( 1, get_query_var('paged') ), > 'total' => $wp_query->max_num_pages > ) ); > ?> > > ``` > > So based on that, I modified your function: ```php function pagination_bar( $query = null ) { global $wp_query; $total_pages = $query ? $query->max_num_pages : $wp_query->max_num_pages; if ( $total_pages > 1 ) { $big = 999999999; // need an unlikely integer $current_page = max( 1, get_query_var( 'paged' ) ); echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => __( '« Previous page' ), 'next_text' => __( 'Next page »' ), ) ); } } ``` and it worked well, both with archives and search results. I also added support for custom query (i.e. `new WP_Query`), so that you could for example do: ```php $my_query = new WP_Query( array( ... ) ); pagination_bar( $my_query ); ```
348,310
<p>I am trying to query some custom posts so that I can iterate through them, extract the title of ecah and add the titles into an array. The reason I am doing this is so that I can then create a select field in woocommerce using the array contents to generate the options (haven't done this bit yet)</p> <p>Can anyone see where I'm going wrong with this snippet or provide any advice, I can't get it to work. The site goes down and I get nothing in a var_dump</p> <pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field'); function custom_checkout_field($checkout) { $args = array( 'post_type' =&gt; 'pickup-point', 'posts_per_page' =&gt; -1, 'post_status' =&gt; 'publish' ); // Custom query to pull in the pickup points. $query = new WP_Query( $args ); // Check that we have query results. if ( $query-&gt;have_posts() ) { $available_locations = []; while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); array_push($available_locations, the_title()); } } var_dump ($available_locations); } // Restore original post data. wp_reset_postdata(); </code></pre>
[ { "answer_id": 348311, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": false, "text": "<p>I see two problems with the code you've written. The first one is that <code>the_title()</code> echos the post title although returning the title would be more appropriate in this context. Also <code>wp_reset_postdata()</code> should be after the <code>while</code> loop inside the <code>if</code> statement.</p>\n\n<p>But as you mentioned that you only need the post titles, you can get them directly from the post objects from the query object without setting up the loop with <code>have_posts()</code> and <code>the_post()</code>. Like so,</p>\n\n<pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field');\nfunction custom_checkout_field($checkout) {\n\n $args = array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish',\n 'no_found_rows' =&gt; true, // pagination not needed\n 'update_post_meta_cache' =&gt; false, // post meta not needed\n 'update_post_term_cache' =&gt; false, // taxonomy terms not needed\n );\n $query = new WP_Query( $args );\n\n $titles = array_map( 'get_the_title', $query-&gt;posts );\n if ( $titles ) {\n // do something with $titles \n }\n\n}\n</code></pre>\n\n<p>I added couple of extra parameters to the query <code>$args</code>, which make the query a bit more efficient as only post titles are needed.</p>\n" }, { "answer_id": 348320, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 1, "selected": false, "text": "<p>The main problem is that you need to use <a href=\"http://%60get_the_title()%60\" rel=\"nofollow noreferrer\"><code>get_the_title()</code></a> instead of <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> in your code, as <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> is echoed and can't be set to a variable.</p>\n\n<p>It seems that you want to make your pickup locations (custom post type) to be displayed in a dropdown (or radio buttons) field in WooCommerce checkout page.</p>\n\n<p>You can also simply use <code>get_posts()</code> function like:</p>\n\n<pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field');\n\nfunction custom_checkout_field( $checkout ) {\n\n $pickup_points = (array) get_posts( array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n ) );\n\n if ( count( $pickup_points ) &gt; 0 ) {\n\n $available_locations = []; // Initializing\n\n // Loop though each 'pickup-point' WP_Post object\n foreach ( $pickup_points as $pickup_point ) {\n // Set current post title in the array\n $available_locations[] = $pickup_point-&gt;post_title;\n }\n\n // testing output\n var_dump ($available_locations);\n }\n}\n</code></pre>\n\n<p>Or if you keep a <code>WP_Query</code>:</p>\n\n<pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field');\n\nfunction custom_checkout_field( $checkout ) {\n\n // Custom query to pull in the pickup points.\n $query = new WP_Query( array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n ) );\n\n $available_locations = []; // Initializing\n\n // Check that we have query results.\n if ( $query-&gt;have_posts() ) :\n\n $available_locations = []; // Initializing\n\n while ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n\n $available_locations[] = get_the_title(); // Set the current title in the array\n\n endwhile;\n\n // testing output\n var_dump ($available_locations);\n\n wp_reset_postdata();\n\n endif;\n}\n</code></pre>\n\n<p>Both should work the same way.</p>\n" }, { "answer_id": 348322, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>There's a shorter way to get the titles of posts into an array if you use <code>get_posts()</code>:</p>\n\n<pre><code>$posts = get_posts(\n array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n )\n);\n\n$titles = array_map( 'get_the_title', $posts );\n</code></pre>\n\n<p>This takes advantage of the fact that you can pass a <code>WP_Post</code> object to <code>get_the_title()</code> by using <code>array_map()</code> to run <code>get_the_title()</code> on the results of <code>get_posts()</code>, which is an array of <code>WP_Post</code> objects.</p>\n" } ]
2019/09/14
[ "https://wordpress.stackexchange.com/questions/348310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161436/" ]
I am trying to query some custom posts so that I can iterate through them, extract the title of ecah and add the titles into an array. The reason I am doing this is so that I can then create a select field in woocommerce using the array contents to generate the options (haven't done this bit yet) Can anyone see where I'm going wrong with this snippet or provide any advice, I can't get it to work. The site goes down and I get nothing in a var\_dump ``` add_action('woocommerce_after_order_notes', 'custom_checkout_field'); function custom_checkout_field($checkout) { $args = array( 'post_type' => 'pickup-point', 'posts_per_page' => -1, 'post_status' => 'publish' ); // Custom query to pull in the pickup points. $query = new WP_Query( $args ); // Check that we have query results. if ( $query->have_posts() ) { $available_locations = []; while ( $query->have_posts() ) { $query->the_post(); array_push($available_locations, the_title()); } } var_dump ($available_locations); } // Restore original post data. wp_reset_postdata(); ```
I see two problems with the code you've written. The first one is that `the_title()` echos the post title although returning the title would be more appropriate in this context. Also `wp_reset_postdata()` should be after the `while` loop inside the `if` statement. But as you mentioned that you only need the post titles, you can get them directly from the post objects from the query object without setting up the loop with `have_posts()` and `the_post()`. Like so, ``` add_action('woocommerce_after_order_notes', 'custom_checkout_field'); function custom_checkout_field($checkout) { $args = array( 'post_type' => 'pickup-point', 'posts_per_page' => -1, 'post_status' => 'publish', 'no_found_rows' => true, // pagination not needed 'update_post_meta_cache' => false, // post meta not needed 'update_post_term_cache' => false, // taxonomy terms not needed ); $query = new WP_Query( $args ); $titles = array_map( 'get_the_title', $query->posts ); if ( $titles ) { // do something with $titles } } ``` I added couple of extra parameters to the query `$args`, which make the query a bit more efficient as only post titles are needed.
348,378
<p>I am looking for solution to display related product by multiple product attributes. I've tried <em>"<a href="https://stackoverflow.com/a/49961446/3730754">Display Related products for a specific product attribute value in single product pages </a>"</em> StackOverFlow answer code, but it works only for <strong>one</strong> product attribute value. </p> <p>How to make the same, but for <strong>two product attributes</strong> values?</p>
[ { "answer_id": 348311, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": false, "text": "<p>I see two problems with the code you've written. The first one is that <code>the_title()</code> echos the post title although returning the title would be more appropriate in this context. Also <code>wp_reset_postdata()</code> should be after the <code>while</code> loop inside the <code>if</code> statement.</p>\n\n<p>But as you mentioned that you only need the post titles, you can get them directly from the post objects from the query object without setting up the loop with <code>have_posts()</code> and <code>the_post()</code>. Like so,</p>\n\n<pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field');\nfunction custom_checkout_field($checkout) {\n\n $args = array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish',\n 'no_found_rows' =&gt; true, // pagination not needed\n 'update_post_meta_cache' =&gt; false, // post meta not needed\n 'update_post_term_cache' =&gt; false, // taxonomy terms not needed\n );\n $query = new WP_Query( $args );\n\n $titles = array_map( 'get_the_title', $query-&gt;posts );\n if ( $titles ) {\n // do something with $titles \n }\n\n}\n</code></pre>\n\n<p>I added couple of extra parameters to the query <code>$args</code>, which make the query a bit more efficient as only post titles are needed.</p>\n" }, { "answer_id": 348320, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 1, "selected": false, "text": "<p>The main problem is that you need to use <a href=\"http://%60get_the_title()%60\" rel=\"nofollow noreferrer\"><code>get_the_title()</code></a> instead of <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> in your code, as <a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\"><code>the_title()</code></a> is echoed and can't be set to a variable.</p>\n\n<p>It seems that you want to make your pickup locations (custom post type) to be displayed in a dropdown (or radio buttons) field in WooCommerce checkout page.</p>\n\n<p>You can also simply use <code>get_posts()</code> function like:</p>\n\n<pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field');\n\nfunction custom_checkout_field( $checkout ) {\n\n $pickup_points = (array) get_posts( array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n ) );\n\n if ( count( $pickup_points ) &gt; 0 ) {\n\n $available_locations = []; // Initializing\n\n // Loop though each 'pickup-point' WP_Post object\n foreach ( $pickup_points as $pickup_point ) {\n // Set current post title in the array\n $available_locations[] = $pickup_point-&gt;post_title;\n }\n\n // testing output\n var_dump ($available_locations);\n }\n}\n</code></pre>\n\n<p>Or if you keep a <code>WP_Query</code>:</p>\n\n<pre><code>add_action('woocommerce_after_order_notes', 'custom_checkout_field');\n\nfunction custom_checkout_field( $checkout ) {\n\n // Custom query to pull in the pickup points.\n $query = new WP_Query( array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n ) );\n\n $available_locations = []; // Initializing\n\n // Check that we have query results.\n if ( $query-&gt;have_posts() ) :\n\n $available_locations = []; // Initializing\n\n while ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n\n $available_locations[] = get_the_title(); // Set the current title in the array\n\n endwhile;\n\n // testing output\n var_dump ($available_locations);\n\n wp_reset_postdata();\n\n endif;\n}\n</code></pre>\n\n<p>Both should work the same way.</p>\n" }, { "answer_id": 348322, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>There's a shorter way to get the titles of posts into an array if you use <code>get_posts()</code>:</p>\n\n<pre><code>$posts = get_posts(\n array(\n 'post_type' =&gt; 'pickup-point',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n )\n);\n\n$titles = array_map( 'get_the_title', $posts );\n</code></pre>\n\n<p>This takes advantage of the fact that you can pass a <code>WP_Post</code> object to <code>get_the_title()</code> by using <code>array_map()</code> to run <code>get_the_title()</code> on the results of <code>get_posts()</code>, which is an array of <code>WP_Post</code> objects.</p>\n" } ]
2019/09/16
[ "https://wordpress.stackexchange.com/questions/348378", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am looking for solution to display related product by multiple product attributes. I've tried *"[Display Related products for a specific product attribute value in single product pages](https://stackoverflow.com/a/49961446/3730754)"* StackOverFlow answer code, but it works only for **one** product attribute value. How to make the same, but for **two product attributes** values?
I see two problems with the code you've written. The first one is that `the_title()` echos the post title although returning the title would be more appropriate in this context. Also `wp_reset_postdata()` should be after the `while` loop inside the `if` statement. But as you mentioned that you only need the post titles, you can get them directly from the post objects from the query object without setting up the loop with `have_posts()` and `the_post()`. Like so, ``` add_action('woocommerce_after_order_notes', 'custom_checkout_field'); function custom_checkout_field($checkout) { $args = array( 'post_type' => 'pickup-point', 'posts_per_page' => -1, 'post_status' => 'publish', 'no_found_rows' => true, // pagination not needed 'update_post_meta_cache' => false, // post meta not needed 'update_post_term_cache' => false, // taxonomy terms not needed ); $query = new WP_Query( $args ); $titles = array_map( 'get_the_title', $query->posts ); if ( $titles ) { // do something with $titles } } ``` I added couple of extra parameters to the query `$args`, which make the query a bit more efficient as only post titles are needed.