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
338,598
<p>I'm developing a theme for WordPress. I have a doubt about templates redirect. For example, I have a theme that have the <code>front-page.php</code> template and I don't use the <code>index.php</code> template. What I should do it with index.php file? Delete it or redirect like:</p> <p>index.php</p> <pre class="lang-php prettyprint-override"><code>&lt;?php wp_safe_redirect('front-page.php'); exit(); </code></pre> <p>The redirect affects the performance of the site? Should I left the template blank If I don't use it?</p> <p>I always have this doubt about templates. If I don't use <code>archive.php</code> template for example, I should delete it or redirect to the template I use? I don't know what to do with the underscore theme files (the files I don't use).</p> <p>Template Hierarchy: <a href="https://developer.wordpress.org/files/2014/10/Screenshot-2019-01-23-00.20.04.png" rel="nofollow noreferrer">https://developer.wordpress.org/files/2014/10/Screenshot-2019-01-23-00.20.04.png</a></p> <p>Underscores base theme: <a href="http://underscores.me/" rel="nofollow noreferrer">http://underscores.me/</a></p>
[ { "answer_id": 338599, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": true, "text": "<p>I don't see any reason to redirect <code>index.php</code>. Let's say you only have a Front Page, no blog or post types with archives. You would assign the Front Page in Settings -> Reading and WordPress will do the template redirect for you. At that point, nothing uses <code>index.php</code> and there's no need to redirect it.</p>\n\n<p>Maybe you install a plugin which create a post type and, by default, uses <code>index.php</code> to display its posts. You'll want something to display instead of redirecting it otherwise you may spend time trying to figure out why the archive of this plugin is redirecting. Copy / Paste the <code>page.php</code> template and throw some baseline styles into it.</p>\n\n<p>If you <em>do</em> have a post type archive or blog and want to keep the single posts but <strong>do not</strong> want an archive you can use the <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code> hook</a> to redirect the request:</p>\n\n<pre><code>/**\n * Redirect Archive Pages\n *\n * @return void\n */\nfunction prefix_redirects() {\n\n if( is_post_type_archive( 'foobar' ) ) {\n wp_safe_redirect( home_url() );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'prefix_redirects' );\n</code></pre>\n\n<p>The tools are there if you really need them but since <code>index.php</code> is the default display for post type archives it's not something I would redirect but instead add some baseline styles to. You can always do more specific template overrides later if you need to.</p>\n" }, { "answer_id": 338601, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>Don't redirect in templates to other templates. That's not how templates work. Notice in your browser that you're never redirected to single.php or front-page.php or anything like that. If you do this then if you load a page that uses index.php your browser is going to redirect to <code>http://website.com/front-page.php</code> and you'll get a 404.</p>\n\n<p>Templates are loaded with <code>include</code> (or <code>require</code>) in PHP by WordPress to render the page as part of a process involving many WordPress files. They are not a loaded directly, and they are not redirected to.</p>\n\n<p>The first thing to note for your specific example is that index.php is a <a href=\"https://developer.wordpress.org/themes/release/required-theme-files/\" rel=\"nofollow noreferrer\">required file</a> for WordPress themes. So you can't delete it, and you shouldn't redirect from it. So if your front-page.php and index.php templates are the same, then you should be deleting front-page.php, not index.php.</p>\n\n<p>You should start your theme with index.php, which should be the template for a generic list of posts. Then you start adding templates based on your design requirements, by referring to the <a href=\"https://developer.wordpress.org/files/2014/10/Screenshot-2019-01-23-00.20.04.png\" rel=\"nofollow noreferrer\">Template Hierarchy</a> and adding the ones you need. </p>\n\n<p>However, let's say I have a custom post type whose archive template (eg. <code>archive-project.php</code>) needs to be the same as the taxonomy archive template for its taxonomy (eg. <code>taxonomy-project_category.php</code>). Both post type archives and taxonomy archives fall back to <code>archive.php</code>. The problem is that if you're already using that for regular posts, you can't create a single template for both types of page.</p>\n\n<p>The simplest solution is to load one template into the other using <code>get_template_part()</code>. So <code>archive-project.php</code> could be your main template, and then <code>taxonomy-project_category.php</code> could look like this:</p>\n\n<pre><code>&lt;?php get_template_part( 'archive-project' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 340545, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 1, "selected": false, "text": "<p>index.php can be <code>&lt;?php //silent</code> here. Doesn’t matter at the theme level really. Unless you want to guarantee something before your <code>functions.php</code> file it’s obsolete in the theme directory. Just like anything else in php/html on apache servers anyway.</p>\n" } ]
2019/05/23
[ "https://wordpress.stackexchange.com/questions/338598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168637/" ]
I'm developing a theme for WordPress. I have a doubt about templates redirect. For example, I have a theme that have the `front-page.php` template and I don't use the `index.php` template. What I should do it with index.php file? Delete it or redirect like: index.php ```php <?php wp_safe_redirect('front-page.php'); exit(); ``` The redirect affects the performance of the site? Should I left the template blank If I don't use it? I always have this doubt about templates. If I don't use `archive.php` template for example, I should delete it or redirect to the template I use? I don't know what to do with the underscore theme files (the files I don't use). Template Hierarchy: <https://developer.wordpress.org/files/2014/10/Screenshot-2019-01-23-00.20.04.png> Underscores base theme: <http://underscores.me/>
I don't see any reason to redirect `index.php`. Let's say you only have a Front Page, no blog or post types with archives. You would assign the Front Page in Settings -> Reading and WordPress will do the template redirect for you. At that point, nothing uses `index.php` and there's no need to redirect it. Maybe you install a plugin which create a post type and, by default, uses `index.php` to display its posts. You'll want something to display instead of redirecting it otherwise you may spend time trying to figure out why the archive of this plugin is redirecting. Copy / Paste the `page.php` template and throw some baseline styles into it. If you *do* have a post type archive or blog and want to keep the single posts but **do not** want an archive you can use the [`template_redirect` hook](https://developer.wordpress.org/reference/hooks/template_redirect/) to redirect the request: ``` /** * Redirect Archive Pages * * @return void */ function prefix_redirects() { if( is_post_type_archive( 'foobar' ) ) { wp_safe_redirect( home_url() ); exit(); } } add_action( 'template_redirect', 'prefix_redirects' ); ``` The tools are there if you really need them but since `index.php` is the default display for post type archives it's not something I would redirect but instead add some baseline styles to. You can always do more specific template overrides later if you need to.
338,649
<p><a href="https://i.stack.imgur.com/wglzJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wglzJ.png" alt="enter image description here"></a></p> <p>Right now I'm getting the id statically in my output "1778a1778" because of array_push(), but I have to send ID dynamically and get the same output.</p>
[ { "answer_id": 338599, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": true, "text": "<p>I don't see any reason to redirect <code>index.php</code>. Let's say you only have a Front Page, no blog or post types with archives. You would assign the Front Page in Settings -> Reading and WordPress will do the template redirect for you. At that point, nothing uses <code>index.php</code> and there's no need to redirect it.</p>\n\n<p>Maybe you install a plugin which create a post type and, by default, uses <code>index.php</code> to display its posts. You'll want something to display instead of redirecting it otherwise you may spend time trying to figure out why the archive of this plugin is redirecting. Copy / Paste the <code>page.php</code> template and throw some baseline styles into it.</p>\n\n<p>If you <em>do</em> have a post type archive or blog and want to keep the single posts but <strong>do not</strong> want an archive you can use the <a href=\"https://developer.wordpress.org/reference/hooks/template_redirect/\" rel=\"nofollow noreferrer\"><code>template_redirect</code> hook</a> to redirect the request:</p>\n\n<pre><code>/**\n * Redirect Archive Pages\n *\n * @return void\n */\nfunction prefix_redirects() {\n\n if( is_post_type_archive( 'foobar' ) ) {\n wp_safe_redirect( home_url() );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'prefix_redirects' );\n</code></pre>\n\n<p>The tools are there if you really need them but since <code>index.php</code> is the default display for post type archives it's not something I would redirect but instead add some baseline styles to. You can always do more specific template overrides later if you need to.</p>\n" }, { "answer_id": 338601, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>Don't redirect in templates to other templates. That's not how templates work. Notice in your browser that you're never redirected to single.php or front-page.php or anything like that. If you do this then if you load a page that uses index.php your browser is going to redirect to <code>http://website.com/front-page.php</code> and you'll get a 404.</p>\n\n<p>Templates are loaded with <code>include</code> (or <code>require</code>) in PHP by WordPress to render the page as part of a process involving many WordPress files. They are not a loaded directly, and they are not redirected to.</p>\n\n<p>The first thing to note for your specific example is that index.php is a <a href=\"https://developer.wordpress.org/themes/release/required-theme-files/\" rel=\"nofollow noreferrer\">required file</a> for WordPress themes. So you can't delete it, and you shouldn't redirect from it. So if your front-page.php and index.php templates are the same, then you should be deleting front-page.php, not index.php.</p>\n\n<p>You should start your theme with index.php, which should be the template for a generic list of posts. Then you start adding templates based on your design requirements, by referring to the <a href=\"https://developer.wordpress.org/files/2014/10/Screenshot-2019-01-23-00.20.04.png\" rel=\"nofollow noreferrer\">Template Hierarchy</a> and adding the ones you need. </p>\n\n<p>However, let's say I have a custom post type whose archive template (eg. <code>archive-project.php</code>) needs to be the same as the taxonomy archive template for its taxonomy (eg. <code>taxonomy-project_category.php</code>). Both post type archives and taxonomy archives fall back to <code>archive.php</code>. The problem is that if you're already using that for regular posts, you can't create a single template for both types of page.</p>\n\n<p>The simplest solution is to load one template into the other using <code>get_template_part()</code>. So <code>archive-project.php</code> could be your main template, and then <code>taxonomy-project_category.php</code> could look like this:</p>\n\n<pre><code>&lt;?php get_template_part( 'archive-project' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 340545, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 1, "selected": false, "text": "<p>index.php can be <code>&lt;?php //silent</code> here. Doesn’t matter at the theme level really. Unless you want to guarantee something before your <code>functions.php</code> file it’s obsolete in the theme directory. Just like anything else in php/html on apache servers anyway.</p>\n" } ]
2019/05/24
[ "https://wordpress.stackexchange.com/questions/338649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168440/" ]
[![enter image description here](https://i.stack.imgur.com/wglzJ.png)](https://i.stack.imgur.com/wglzJ.png) Right now I'm getting the id statically in my output "1778a1778" because of array\_push(), but I have to send ID dynamically and get the same output.
I don't see any reason to redirect `index.php`. Let's say you only have a Front Page, no blog or post types with archives. You would assign the Front Page in Settings -> Reading and WordPress will do the template redirect for you. At that point, nothing uses `index.php` and there's no need to redirect it. Maybe you install a plugin which create a post type and, by default, uses `index.php` to display its posts. You'll want something to display instead of redirecting it otherwise you may spend time trying to figure out why the archive of this plugin is redirecting. Copy / Paste the `page.php` template and throw some baseline styles into it. If you *do* have a post type archive or blog and want to keep the single posts but **do not** want an archive you can use the [`template_redirect` hook](https://developer.wordpress.org/reference/hooks/template_redirect/) to redirect the request: ``` /** * Redirect Archive Pages * * @return void */ function prefix_redirects() { if( is_post_type_archive( 'foobar' ) ) { wp_safe_redirect( home_url() ); exit(); } } add_action( 'template_redirect', 'prefix_redirects' ); ``` The tools are there if you really need them but since `index.php` is the default display for post type archives it's not something I would redirect but instead add some baseline styles to. You can always do more specific template overrides later if you need to.
338,653
<p>I am trying to hide WordPress admin bar from all pages except the home page.</p> <p>I added the following CODE in the theme's <code>functions.php</code> file, but it hides the admin bar on all pages:</p> <pre><code>if ( ! is_single() ) { add_filter( 'show_admin_bar', '__return_false' ); } </code></pre> <p>I want it to appear only on the homepage and to be hidden everywhere else.</p>
[ { "answer_id": 338655, "author": "Vishwa", "author_id": 120712, "author_profile": "https://wordpress.stackexchange.com/users/120712", "pm_score": -1, "selected": false, "text": "<p>You should check if page is home page and/or front page. \n<code>is_front_page()</code> returns true when viewing the site's front page (blog posts index or a static page), <code>is_home()</code> returns true when viewing the blog posts index.\ntry as below,</p>\n\n<pre><code>if (!is_home() &amp;&amp; !is_front_page()){\n add_filter('show_admin_bar', '__return_false');\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (!is_home()){\n add_filter('show_admin_bar', '__return_false');\n}\n</code></pre>\n" }, { "answer_id": 338663, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>You should use conditional tag inside function hooked to <code>show_admin_bar</code> filter.</p>\n\n<pre><code>add_filter( 'show_admin_bar', 'show_adminbar_on_homepage_only', 20 );\nfunction show_adminbar_on_homepage_only()\n{\n return is_user_logged_in() &amp;&amp; is_front_page();\n}\n</code></pre>\n" }, { "answer_id": 338664, "author": "middlelady", "author_id": 93927, "author_profile": "https://wordpress.stackexchange.com/users/93927", "pm_score": 0, "selected": false, "text": "<p>Could be a priority issue, meaning that some plugin / theme function is overriding the admin bar behaviour. Try something like this:</p>\n\n<pre><code>if (!is_home() &amp;&amp; !is_front_page()){\n add_filter('show_admin_bar', '__return_false', 999);\n}\n</code></pre>\n\n<p>If this work, let's try to understand which plugins are and assign the right priority, like a lower 99 or whatever.</p>\n" }, { "answer_id": 339056, "author": "shea", "author_id": 19726, "author_profile": "https://wordpress.stackexchange.com/users/19726", "pm_score": 0, "selected": false, "text": "<p>Here's a better way to do it that improves on the existing answers:</p>\n\n<pre><code>add_filter( 'show_admin_bar', function ( $show ) {\n\n if ( is_front_page() ) {\n return false;\n }\n\n return $show;\n}, 50 );\n</code></pre>\n\n<p>Unlike the other code examples given, this snippet will only change the admin bar visibility if currently viewing the front page. Otherwise, it will use whatever the default is set to. This removes the need to account for different cases where the user is not logged in.</p>\n" } ]
2019/05/24
[ "https://wordpress.stackexchange.com/questions/338653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118356/" ]
I am trying to hide WordPress admin bar from all pages except the home page. I added the following CODE in the theme's `functions.php` file, but it hides the admin bar on all pages: ``` if ( ! is_single() ) { add_filter( 'show_admin_bar', '__return_false' ); } ``` I want it to appear only on the homepage and to be hidden everywhere else.
You should use conditional tag inside function hooked to `show_admin_bar` filter. ``` add_filter( 'show_admin_bar', 'show_adminbar_on_homepage_only', 20 ); function show_adminbar_on_homepage_only() { return is_user_logged_in() && is_front_page(); } ```
338,661
<p>i used <a href="https://wordpress.org/plugins/advanced-custom-fields/" rel="nofollow noreferrer">ACF</a> to store post data in custom fields. i'd like to copy the data from a <a href="https://www.advancedcustomfields.com/resources/wysiwyg-editor/" rel="nofollow noreferrer">wysiwyg field</a> to post_content into wp_posts table. How can i do this?</p> <p>Roughly:</p> <pre><code>data is on wp_postmeta table, where meta_key = 'description' and post_id is = $post-&gt;ID and needs to be copied over to 'post_content' of wp_posts table where id is = $post-&gt;ID </code></pre>
[ { "answer_id": 338673, "author": "Parthavi Patel", "author_id": 110795, "author_profile": "https://wordpress.stackexchange.com/users/110795", "pm_score": 1, "selected": false, "text": "<p>First get data from <code>wp_postmeta</code> table</p>\n\n<pre><code>$description = get_post_meta( $post-&gt;ID, 'description', true );\n</code></pre>\n\n<p>Try following code to update content </p>\n\n<pre><code>$my_post = array(\n 'ID' =&gt; $post-&gt;ID,\n 'post_content' =&gt; $description,\n);\n\n //Update the post into the database\n wp_update_post( $my_post );\n</code></pre>\n" }, { "answer_id": 338866, "author": "Michael Rogers", "author_id": 77283, "author_profile": "https://wordpress.stackexchange.com/users/77283", "pm_score": 1, "selected": true, "text": "<p>Putting together a working example of <a href=\"https://wordpress.stackexchange.com/users/110795/parthavi-patel\">@Parthavi Patel</a> answer.\nThis is a page template. When the page loads the code is executed. If there's too many posts it would be good to use a conservative value on <code>posts_per_page</code> and adjust the <code>offset</code> parameter after each batch is executed.</p>\n\n<pre><code> &lt;?php\n/*\n * Template Name: experiments\n * Template Post Type: page\n */\n\nglobal $post;\n$args = array( \n 'post_type' =&gt; 'YOUR_CPT_HERE', \n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post );\n\n $custom_field_raw = get_field('YOUR_CF_HERE');\n\n //speedup by skip processing when CF is empty \n if ($custom_field_raw != '') {\n\n $my_post = array(\n 'ID' =&gt; get_the_ID(),\n 'post_content' =&gt; $custom_field_raw\n );\n\n wp_update_post( $my_post );\n\n }\n\nendforeach; \nwp_reset_postdata();\n\n?&gt;\n</code></pre>\n\n<p>Reference/Source/Credits: <strong><a href=\"https://support.advancedcustomfields.com/forums/topic/migrate-a-custom-field-content-to-the_content/\" rel=\"nofollow noreferrer\">https://support.advancedcustomfields.com/forums/topic/migrate-a-custom-field-content-to-the_content/</a></strong></p>\n" } ]
2019/05/24
[ "https://wordpress.stackexchange.com/questions/338661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
i used [ACF](https://wordpress.org/plugins/advanced-custom-fields/) to store post data in custom fields. i'd like to copy the data from a [wysiwyg field](https://www.advancedcustomfields.com/resources/wysiwyg-editor/) to post\_content into wp\_posts table. How can i do this? Roughly: ``` data is on wp_postmeta table, where meta_key = 'description' and post_id is = $post->ID and needs to be copied over to 'post_content' of wp_posts table where id is = $post->ID ```
Putting together a working example of [@Parthavi Patel](https://wordpress.stackexchange.com/users/110795/parthavi-patel) answer. This is a page template. When the page loads the code is executed. If there's too many posts it would be good to use a conservative value on `posts_per_page` and adjust the `offset` parameter after each batch is executed. ``` <?php /* * Template Name: experiments * Template Post Type: page */ global $post; $args = array( 'post_type' => 'YOUR_CPT_HERE', 'posts_per_page' => -1, 'post_status' => 'publish' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); $custom_field_raw = get_field('YOUR_CF_HERE'); //speedup by skip processing when CF is empty if ($custom_field_raw != '') { $my_post = array( 'ID' => get_the_ID(), 'post_content' => $custom_field_raw ); wp_update_post( $my_post ); } endforeach; wp_reset_postdata(); ?> ``` Reference/Source/Credits: **<https://support.advancedcustomfields.com/forums/topic/migrate-a-custom-field-content-to-the_content/>**
338,662
<p>I'm trying to add these custom CSS and JS (written inside a custom plugin) only add to a specific page.</p> <p>this is my code</p> <pre><code>&lt;?php function randomAlphaNumeric($length) { $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z')); $key=''; for($i=0; $i &lt; $length; $i++) { $key .= $pool[mt_rand(0, count($pool) - 1)]; } return $key; } add_action('init', 'register_script'); function register_script(){ if(is_page('page_title')) { wp_register_script( 'custom_js', plugins_url('/js/custom-js.js', __FILE__).'?random='.randomAlphaNumeric(5), array('jquery')); wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__).'?random='.randomAlphaNumeric(5), false, 'all'); } } // use the registered jquery and style above add_action('wp_enqueue_scripts', 'enqueue_style'); function enqueue_style(){ if(is_page('page_title')) { wp_enqueue_script('custom_js'); wp_enqueue_style( 'new_style' ); } } </code></pre> <p>but <code>is_page()</code> doesn't seem to work at all.. I tried to change it with <strong>ID</strong> and <strong>SLUG</strong>, but no success</p> <p><strong>UPDATE</strong> replaced condition to check the page title, still doesnt work</p> <pre><code>add_action('init', 'register_script'); function register_script(){ global $post; if($post-&gt;post_title == 'page_title') { wp_register_script( 'custom_js', plugins_url('/js/custom-js.js', __FILE__).'?random='.randomAlphaNumeric(5), array('jquery')); wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__).'?random='.randomAlphaNumeric(5), false, 'all'); } } // use the registered jquery and style above add_action('wp_enqueue_scripts', 'enqueue_style'); function enqueue_style(){ global $post; if($post-&gt;post_title == 'page_title') { wp_enqueue_script('custom_js'); wp_enqueue_style( 'new_style' ); } } </code></pre>
[ { "answer_id": 338666, "author": "middlelady", "author_id": 93927, "author_profile": "https://wordpress.stackexchange.com/users/93927", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Try to change the parameter from <code>page_title</code>to <code>page-slug</code> or <code>id</code>. <a href=\"https://developer.wordpress.org/reference/functions/is_page/#parameters\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_page/#parameters</a></li>\n<li>Let's try to register scripts in the same <code>enqueue_style()</code> function right before enqueueing them.</li>\n</ol>\n\n<p><strong>Update</strong>: My scope here was to encourage doing tries around different parameters for <code>is_page()</code> AND using the same function <code>enqueue_style()</code> hooked in <code>wp_enqueue_scripts</code> which is the ONLY suggested way to register/enqueue scripts.</p>\n" }, { "answer_id": 338668, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<p>The <code>init</code> hook is too early &mdash; WordPress hasn't yet identified the queried object (post, category, etc.); hence the <code>is_page()</code> doesn't work there:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('init', 'register_script');\n</code></pre>\n\n<p>So for conditional tags/functions like <code>is_page()</code>, <code>is_single()</code>, etc. to work (i.e. return the proper result), you should use <code>wp</code> or a later hook:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('wp', 'whatever_function');\n</code></pre>\n\n<p>But for registering/enqueueing scripts and styles, you should always use the <code>wp_enqueue_scripts</code> hook; so you would use this (and not the above):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action('wp_enqueue_scripts', 'register_script');\n</code></pre>\n\n<p><em>PS: Credits to @<a href=\"https://wordpress.stackexchange.com/users/93927/huraji\">huraji</a> for his helpful comment.</em></p>\n" } ]
2019/05/24
[ "https://wordpress.stackexchange.com/questions/338662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163748/" ]
I'm trying to add these custom CSS and JS (written inside a custom plugin) only add to a specific page. this is my code ``` <?php function randomAlphaNumeric($length) { $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z')); $key=''; for($i=0; $i < $length; $i++) { $key .= $pool[mt_rand(0, count($pool) - 1)]; } return $key; } add_action('init', 'register_script'); function register_script(){ if(is_page('page_title')) { wp_register_script( 'custom_js', plugins_url('/js/custom-js.js', __FILE__).'?random='.randomAlphaNumeric(5), array('jquery')); wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__).'?random='.randomAlphaNumeric(5), false, 'all'); } } // use the registered jquery and style above add_action('wp_enqueue_scripts', 'enqueue_style'); function enqueue_style(){ if(is_page('page_title')) { wp_enqueue_script('custom_js'); wp_enqueue_style( 'new_style' ); } } ``` but `is_page()` doesn't seem to work at all.. I tried to change it with **ID** and **SLUG**, but no success **UPDATE** replaced condition to check the page title, still doesnt work ``` add_action('init', 'register_script'); function register_script(){ global $post; if($post->post_title == 'page_title') { wp_register_script( 'custom_js', plugins_url('/js/custom-js.js', __FILE__).'?random='.randomAlphaNumeric(5), array('jquery')); wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__).'?random='.randomAlphaNumeric(5), false, 'all'); } } // use the registered jquery and style above add_action('wp_enqueue_scripts', 'enqueue_style'); function enqueue_style(){ global $post; if($post->post_title == 'page_title') { wp_enqueue_script('custom_js'); wp_enqueue_style( 'new_style' ); } } ```
The `init` hook is too early — WordPress hasn't yet identified the queried object (post, category, etc.); hence the `is_page()` doesn't work there: ```php add_action('init', 'register_script'); ``` So for conditional tags/functions like `is_page()`, `is_single()`, etc. to work (i.e. return the proper result), you should use `wp` or a later hook: ```php add_action('wp', 'whatever_function'); ``` But for registering/enqueueing scripts and styles, you should always use the `wp_enqueue_scripts` hook; so you would use this (and not the above): ```php add_action('wp_enqueue_scripts', 'register_script'); ``` *PS: Credits to @[huraji](https://wordpress.stackexchange.com/users/93927/huraji) for his helpful comment.*
338,692
<p>So I have a Custom Post Type named network and Custom Taxonomy name company_category. Everything is all good until I can't render <a href="http://localhost/digitalhxstaging/company" rel="nofollow noreferrer">http://localhost/digitalhxstaging/company</a>. Both Company Category and Company are all good except for archive-network.php. I tried removing the dynamic slug and its working but now my company category and company post is not showing its correct link. Please help me. I hope this makes sense. Below is the code with post link function.</p> <pre><code>public function company_post_type() { $labels = array( 'name' =&gt; _x( 'Companies', 'companies', 'dhx-portal' ), 'singular_name' =&gt; _x( 'Company', 'company', 'dhx-portal' ), 'menu_name' =&gt; _x( 'Companies', 'companies', 'dhx-portal' ), 'name_admin_bar' =&gt; _x( 'Company', 'company', 'dhx-portal' ), 'add_new' =&gt; __( 'Add New', 'dhx-portal' ), 'add_new_item' =&gt; __( 'Add New Company', 'dhx-portal' ), 'new_item' =&gt; __( 'New Company', 'dhx-portal' ), 'edit_item' =&gt; __( 'Edit Company', 'dhx-portal' ), 'view_item' =&gt; __( 'View Company', 'dhx-portal' ), 'all_items' =&gt; __( 'All Companies', 'dhx-portal' ), 'search_items' =&gt; __( 'Search Companys', 'dhx-portal' ), 'parent_item_colon' =&gt; __( 'Parent Companys:', 'dhx-portal' ), 'not_found' =&gt; __( 'No companies found.', 'dhx-portal' ), 'not_found_in_trash' =&gt; __( 'No companies found in Trash.', 'dhx-portal' ), 'featured_image' =&gt; _x( 'Company Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'set_featured_image' =&gt; _x( 'Set cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'remove_featured_image' =&gt; _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'use_featured_image' =&gt; _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'archives' =&gt; _x( 'Company archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'dhx-portal' ), 'insert_into_item' =&gt; _x( 'Insert into company', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'dhx-portal' ), 'uploaded_to_this_item' =&gt; _x( 'Uploaded to this company', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'dhx-portal' ), 'filter_items_list' =&gt; _x( 'Filter companies list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'dhx-portal' ), 'items_list_navigation' =&gt; _x( 'Companies list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'dhx-portal' ), 'items_list' =&gt; _x( 'Companies list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ), ); $args = array( 'labels' =&gt; $labels, 'taxonomies' =&gt; array('company_category'), 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-building', 'rewrite' =&gt; array( 'slug' =&gt; 'company/%company_category%', 'with_front' =&gt; false ), 'query_var' =&gt; true, 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; true, 'supports' =&gt; array( 'title', 'author', 'custom-fields' ) ); register_post_type( 'network', $args ); flush_rewrite_rules(); } /** * Company custom taxonomy * @since 0.1.0 * @access public */ public function company_taxonomy() { $labels = array( 'name' =&gt; __('Company Categories', 'dhx-portal'), 'singular_name' =&gt; __('Category', 'dhx-portal'), 'search_items' =&gt; __('Search Categories', 'dhx-portal'), 'all_items' =&gt; __('All Categories', 'dhx-portal'), 'parent_item' =&gt; __('Parent', 'dhx-portal'), 'parent_item_colon' =&gt; __('Parent:', 'dhx-portal'), 'edit_item' =&gt; __('Edit Category', 'dhx-portal'), 'update_item' =&gt; __('Update Category', 'dhx-portal'), 'add_new_item' =&gt; __('Add New Category', 'dhx-portal'), 'new_item_name' =&gt; __('New Category', 'dhx-portal'), 'menu_name' =&gt; __('Categories', 'dhx-portal'), ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'company', 'with_front' =&gt; false ), ); register_taxonomy( 'company_category', array( 'company_category' ), $args ); flush_rewrite_rules(); } /** * Company custom permalink * @since 0.1.0 * @access public */ public function company_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post-&gt;ID, 'company_category' ); if( $terms ){ return str_replace( '%company_category%' , $terms[0]-&gt;slug , $post_link ); } } return $post_link; } </code></pre> <p>Here is the correct URL which is working</p> <p><a href="https://i.stack.imgur.com/te3hL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/te3hL.png" alt="enter Here is the correct URL which is working"></a></p> <p>Let me know what you think. I just need <a href="http://localhost/digitalhxstaging/company" rel="nofollow noreferrer">http://localhost/digitalhxstaging/company</a> to work</p>
[ { "answer_id": 338703, "author": "Faye", "author_id": 76600, "author_profile": "https://wordpress.stackexchange.com/users/76600", "pm_score": 0, "selected": false, "text": "<p>Reset your Permalinks (Dashboard > Settings > Permalinks). Just make a change, save and it should pick up your rewrite change. I've made this mistake a million times, you adjust a thing and forget this is needed.</p>\n" }, { "answer_id": 340072, "author": "Frank Mendez", "author_id": 149172, "author_profile": "https://wordpress.stackexchange.com/users/149172", "pm_score": -1, "selected": false, "text": "<p>Okay so the solution was just adding this code to the <code>$args</code></p>\n\n<pre><code>'has_archive' =&gt; 'companies',\n</code></pre>\n" } ]
2019/05/24
[ "https://wordpress.stackexchange.com/questions/338692", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149172/" ]
So I have a Custom Post Type named network and Custom Taxonomy name company\_category. Everything is all good until I can't render <http://localhost/digitalhxstaging/company>. Both Company Category and Company are all good except for archive-network.php. I tried removing the dynamic slug and its working but now my company category and company post is not showing its correct link. Please help me. I hope this makes sense. Below is the code with post link function. ``` public function company_post_type() { $labels = array( 'name' => _x( 'Companies', 'companies', 'dhx-portal' ), 'singular_name' => _x( 'Company', 'company', 'dhx-portal' ), 'menu_name' => _x( 'Companies', 'companies', 'dhx-portal' ), 'name_admin_bar' => _x( 'Company', 'company', 'dhx-portal' ), 'add_new' => __( 'Add New', 'dhx-portal' ), 'add_new_item' => __( 'Add New Company', 'dhx-portal' ), 'new_item' => __( 'New Company', 'dhx-portal' ), 'edit_item' => __( 'Edit Company', 'dhx-portal' ), 'view_item' => __( 'View Company', 'dhx-portal' ), 'all_items' => __( 'All Companies', 'dhx-portal' ), 'search_items' => __( 'Search Companys', 'dhx-portal' ), 'parent_item_colon' => __( 'Parent Companys:', 'dhx-portal' ), 'not_found' => __( 'No companies found.', 'dhx-portal' ), 'not_found_in_trash' => __( 'No companies found in Trash.', 'dhx-portal' ), 'featured_image' => _x( 'Company Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'set_featured_image' => _x( 'Set cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'remove_featured_image' => _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'use_featured_image' => _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'dhx-portal' ), 'archives' => _x( 'Company archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'dhx-portal' ), 'insert_into_item' => _x( 'Insert into company', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'dhx-portal' ), 'uploaded_to_this_item' => _x( 'Uploaded to this company', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'dhx-portal' ), 'filter_items_list' => _x( 'Filter companies list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'dhx-portal' ), 'items_list_navigation' => _x( 'Companies list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'dhx-portal' ), 'items_list' => _x( 'Companies list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ), ); $args = array( 'labels' => $labels, 'taxonomies' => array('company_category'), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-building', 'rewrite' => array( 'slug' => 'company/%company_category%', 'with_front' => false ), 'query_var' => true, 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => true, 'supports' => array( 'title', 'author', 'custom-fields' ) ); register_post_type( 'network', $args ); flush_rewrite_rules(); } /** * Company custom taxonomy * @since 0.1.0 * @access public */ public function company_taxonomy() { $labels = array( 'name' => __('Company Categories', 'dhx-portal'), 'singular_name' => __('Category', 'dhx-portal'), 'search_items' => __('Search Categories', 'dhx-portal'), 'all_items' => __('All Categories', 'dhx-portal'), 'parent_item' => __('Parent', 'dhx-portal'), 'parent_item_colon' => __('Parent:', 'dhx-portal'), 'edit_item' => __('Edit Category', 'dhx-portal'), 'update_item' => __('Update Category', 'dhx-portal'), 'add_new_item' => __('Add New Category', 'dhx-portal'), 'new_item_name' => __('New Category', 'dhx-portal'), 'menu_name' => __('Categories', 'dhx-portal'), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'company', 'with_front' => false ), ); register_taxonomy( 'company_category', array( 'company_category' ), $args ); flush_rewrite_rules(); } /** * Company custom permalink * @since 0.1.0 * @access public */ public function company_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'company_category' ); if( $terms ){ return str_replace( '%company_category%' , $terms[0]->slug , $post_link ); } } return $post_link; } ``` Here is the correct URL which is working [![enter Here is the correct URL which is working](https://i.stack.imgur.com/te3hL.png)](https://i.stack.imgur.com/te3hL.png) Let me know what you think. I just need <http://localhost/digitalhxstaging/company> to work
Reset your Permalinks (Dashboard > Settings > Permalinks). Just make a change, save and it should pick up your rewrite change. I've made this mistake a million times, you adjust a thing and forget this is needed.
338,745
<p>I want to pass the 'post title' of current post as parameter into a link</p> <p>For example in this way:</p> <pre><code>&lt;a href='http://example.com/send-cv/?job_position=seller'&gt;apply to job&lt;/a&gt; </code></pre> <p>Where the post title would be 'seller'</p> <p>How can I achieve this?</p>
[ { "answer_id": 338703, "author": "Faye", "author_id": 76600, "author_profile": "https://wordpress.stackexchange.com/users/76600", "pm_score": 0, "selected": false, "text": "<p>Reset your Permalinks (Dashboard > Settings > Permalinks). Just make a change, save and it should pick up your rewrite change. I've made this mistake a million times, you adjust a thing and forget this is needed.</p>\n" }, { "answer_id": 340072, "author": "Frank Mendez", "author_id": 149172, "author_profile": "https://wordpress.stackexchange.com/users/149172", "pm_score": -1, "selected": false, "text": "<p>Okay so the solution was just adding this code to the <code>$args</code></p>\n\n<pre><code>'has_archive' =&gt; 'companies',\n</code></pre>\n" } ]
2019/05/25
[ "https://wordpress.stackexchange.com/questions/338745", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168802/" ]
I want to pass the 'post title' of current post as parameter into a link For example in this way: ``` <a href='http://example.com/send-cv/?job_position=seller'>apply to job</a> ``` Where the post title would be 'seller' How can I achieve this?
Reset your Permalinks (Dashboard > Settings > Permalinks). Just make a change, save and it should pick up your rewrite change. I've made this mistake a million times, you adjust a thing and forget this is needed.
338,753
<p>we are receiving this error:</p> <p>Warning: preg_match(): No ending delimiter '^' found in /home/goose/public_html/wp-content/themes/goose/partials/contact.php on line 32 Please enter a valid email address</p> <p><a href="http://thegoosedarien.com" rel="nofollow noreferrer">http://thegoosedarien.com</a> - using the contact form, we receive this error message when submitting. </p> <p>No idea how to resolve this. What is missing from the code?</p> <pre><code>&lt;?php $asset_path = get_bloginfo('template_url'); ?&gt; &lt;div class="left"&gt; &lt;span class="main-title"&gt; &lt;?php _e( 'Contact Us', 'goose' ); ?&gt; &lt;/span&gt; &lt;?php if($_SERVER['REQUEST_METHOD'] === 'POST') { $flag = 1; echo '&lt;div class="notice"&gt;'; if($_POST['submission_name'] == '') { $flag = 0; echo "Please enter your name&lt;br /&gt;"; } else if(!preg_match('/[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*/', $_POST['submission_name'])) { $flag=0; echo "Please enter a valid name&lt;br /&gt;"; } if($_POST['submission_email'] == '') { $flag = 0; echo "Please enter your email address&lt;br /&gt;"; } else if(!preg_match("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a- z0-9-]+)*(.[a-z]{2,3})$", $_POST['submission_email'])) { $flag=0; echo "Please enter a valid email address&lt;br /&gt;"; } if($_POST['submission_message'] == '') { $flag = 0; echo "Please enter a message&lt;br /&gt;"; } if (empty($_POST)) { echo "Sorry, your submission is invalid - please try again!"; exit; } else { if($flag == 1) { wp_mail(get_option("admin_email"), trim($_POST[submission_name])." sent you a message from " . get_option("blogname"), stripslashes(trim($_POST[submission_message])),"From: ".trim($_POST[submission_name])." &lt;".trim($_POST[submission_email])."&gt;\r\nReply-To:".trim($_POST[submission_email])); echo "Submission successfully sent!&lt;br /&gt;"; } } echo '&lt;/div&gt;'; } ?&gt; &lt;form method="post" parsley-validate parsley-show-errors="false" id="contact-form"&gt; &lt;div class="line"&gt; &lt;label for="name"&gt;&lt;?php _e( 'Your Name', 'goose' ); ?&gt;&lt;/label&gt; &lt;input type="text" id="name" name="submission_name" required="required" /&gt; &lt;/div&gt; &lt;div class="line"&gt; &lt;label for="email"&gt;&lt;?php _e( 'Your Email', 'goose' ); ?&gt;&lt;/label&gt; &lt;input type="text" id="email" name="submission_email" required="required" parsley-type="email" /&gt; &lt;/div&gt; &lt;div class="line"&gt; &lt;label for="msg"&gt;&lt;?php _e( 'Message', 'goose' ); ?&gt;&lt;/label&gt; &lt;textarea id="msg" cols="10" rows="10" name="submission_message" required="required"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;button&gt; &lt;span&gt;&lt;?php _e( 'Submit', 'goose' ); ?&gt;&lt;/span&gt; &lt;/button&gt; &lt;/form&gt; </code></pre> <p></p>
[ { "answer_id": 338756, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<p>I usually try to avoid using <code>preg_match()</code>, because I get the pattern right very rarely. Perhaps you could try using some other functions to do the validating. For example PHP's <a href=\"https://www.php.net/manual/en/function.ctype-alnum.php\" rel=\"nofollow noreferrer\">ctype_alnum()</a> for the name field and WP's <a href=\"https://codex.wordpress.org/Function_Reference/is_email\" rel=\"nofollow noreferrer\">is_email()</a> for the email field. Like so,</p>\n\n<pre><code>if ( $_POST['submission_name'] == '' ) { \n $flag = 0; \n echo \"Please enter your name&lt;br /&gt;\";\n} else if ( ! ctype_alnum( $_POST['submission_name'] ) ) { // ctype_alnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. \n $flag = 0; \n echo \"Please enter a valid name&lt;br /&gt;\"; \n} \n\nif ( $_POST['submission_email'] == '' ) {\n $flag = 0; \n echo \"Please enter your email address&lt;br /&gt;\";\n} else if ( ! is_email( $_POST['submission_email'] ) ) {\n $flag = 0; \n echo \"Please enter a valid email address&lt;br /&gt;\";\n}\n</code></pre>\n\n<p>Also, if you want to make the <code>wp_mail()</code> function a little bit more readable, you could do something like this,</p>\n\n<pre><code>$name = sanitize_text_field( $_POST['submission_name'] );\n$email = sanitize_email( $_POST['submission_email'] );\n$subject = sprintf( \n '%s sent you a message from %s',\n $name,\n get_option(\"blogname\")\n);\n$message = sanitize_textarea_field( $_POST['submission_message'] );\n$from = sprintf(\n \"From: %s &lt;%s&gt;\\r\\n\",\n $name,\n $email,\n);\n$reply_to .= sprintf(\n \"Reply-To: %s\",\n $email,\n);\n$headers = $from . $reply_to;\nwp_mail(\n get_option(\"admin_email\"),\n $subject,\n $message,\n $headers,\n);\n</code></pre>\n" }, { "answer_id": 397877, "author": "Yuri", "author_id": 114347, "author_profile": "https://wordpress.stackexchange.com/users/114347", "pm_score": 0, "selected": false, "text": "<p>This is old, but the answer might help someone else.</p>\n<p>When using regular expressions, <a href=\"https://www.php.net/manual/en/regexp.reference.delimiters.php\" rel=\"nofollow noreferrer\">you can use different delimiters for the expression</a>:</p>\n<blockquote>\n<p>When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Leading whitespace before a valid delimiter is silently ignored.</p>\n</blockquote>\n<p>Usually, we use <code>/</code> to delimit it as in <code>/(\\w)+/g</code>. But other characters like <code>^</code> are also allowed.</p>\n<p>As we can see in your code, the first preg_match call uses <code>/</code>'s as delimiters: <code>/[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*/</code>, but the second preg_match call has no delimiter at all: <code>^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$</code>.</p>\n<p>So, PHP is looking at the first character in the expression (<code>^</code>) and thinking it is a delimiter. When it doesn't find <code>^</code> at the end of the expression, it throws the warning <code>No ending delimiter '^' found</code>.</p>\n<p>To fix it, all you need to do is add delimiters to your regex:</p>\n<pre><code>preg_match(&quot;/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/&quot;, $_POST['submission_email'])\n</code></pre>\n<p>And that should be enough.</p>\n" } ]
2019/05/25
[ "https://wordpress.stackexchange.com/questions/338753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168807/" ]
we are receiving this error: Warning: preg\_match(): No ending delimiter '^' found in /home/goose/public\_html/wp-content/themes/goose/partials/contact.php on line 32 Please enter a valid email address <http://thegoosedarien.com> - using the contact form, we receive this error message when submitting. No idea how to resolve this. What is missing from the code? ``` <?php $asset_path = get_bloginfo('template_url'); ?> <div class="left"> <span class="main-title"> <?php _e( 'Contact Us', 'goose' ); ?> </span> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { $flag = 1; echo '<div class="notice">'; if($_POST['submission_name'] == '') { $flag = 0; echo "Please enter your name<br />"; } else if(!preg_match('/[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*/', $_POST['submission_name'])) { $flag=0; echo "Please enter a valid name<br />"; } if($_POST['submission_email'] == '') { $flag = 0; echo "Please enter your email address<br />"; } else if(!preg_match("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a- z0-9-]+)*(.[a-z]{2,3})$", $_POST['submission_email'])) { $flag=0; echo "Please enter a valid email address<br />"; } if($_POST['submission_message'] == '') { $flag = 0; echo "Please enter a message<br />"; } if (empty($_POST)) { echo "Sorry, your submission is invalid - please try again!"; exit; } else { if($flag == 1) { wp_mail(get_option("admin_email"), trim($_POST[submission_name])." sent you a message from " . get_option("blogname"), stripslashes(trim($_POST[submission_message])),"From: ".trim($_POST[submission_name])." <".trim($_POST[submission_email]).">\r\nReply-To:".trim($_POST[submission_email])); echo "Submission successfully sent!<br />"; } } echo '</div>'; } ?> <form method="post" parsley-validate parsley-show-errors="false" id="contact-form"> <div class="line"> <label for="name"><?php _e( 'Your Name', 'goose' ); ?></label> <input type="text" id="name" name="submission_name" required="required" /> </div> <div class="line"> <label for="email"><?php _e( 'Your Email', 'goose' ); ?></label> <input type="text" id="email" name="submission_email" required="required" parsley-type="email" /> </div> <div class="line"> <label for="msg"><?php _e( 'Message', 'goose' ); ?></label> <textarea id="msg" cols="10" rows="10" name="submission_message" required="required"></textarea> </div> <button> <span><?php _e( 'Submit', 'goose' ); ?></span> </button> </form> ```
I usually try to avoid using `preg_match()`, because I get the pattern right very rarely. Perhaps you could try using some other functions to do the validating. For example PHP's [ctype\_alnum()](https://www.php.net/manual/en/function.ctype-alnum.php) for the name field and WP's [is\_email()](https://codex.wordpress.org/Function_Reference/is_email) for the email field. Like so, ``` if ( $_POST['submission_name'] == '' ) { $flag = 0; echo "Please enter your name<br />"; } else if ( ! ctype_alnum( $_POST['submission_name'] ) ) { // ctype_alnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. $flag = 0; echo "Please enter a valid name<br />"; } if ( $_POST['submission_email'] == '' ) { $flag = 0; echo "Please enter your email address<br />"; } else if ( ! is_email( $_POST['submission_email'] ) ) { $flag = 0; echo "Please enter a valid email address<br />"; } ``` Also, if you want to make the `wp_mail()` function a little bit more readable, you could do something like this, ``` $name = sanitize_text_field( $_POST['submission_name'] ); $email = sanitize_email( $_POST['submission_email'] ); $subject = sprintf( '%s sent you a message from %s', $name, get_option("blogname") ); $message = sanitize_textarea_field( $_POST['submission_message'] ); $from = sprintf( "From: %s <%s>\r\n", $name, $email, ); $reply_to .= sprintf( "Reply-To: %s", $email, ); $headers = $from . $reply_to; wp_mail( get_option("admin_email"), $subject, $message, $headers, ); ```
338,757
<p>I'm beginning to like Gutenberg, but I find it too narrow, particularly when working with the 'Columns' block. Why is it so narrow, and can it safely be made wider? I could try doing so with CSS, but I thought it best to ask first, to avoid potential trouble.</p>
[ { "answer_id": 338873, "author": "WSU", "author_id": 168474, "author_profile": "https://wordpress.stackexchange.com/users/168474", "pm_score": 1, "selected": false, "text": "<p>The only way that comes to mind is to disable the options sidebar on the right. Just click on the cog icon and it will disappear, giving you 30px more space or so.</p>\n\n<p>In addition, you can enter fullscreen mode by clicking on on the three vertical dots in the upper right corner all the way on the side and the choosing the respective option. This will disable the WordPress menu.</p>\n\n<p>Not sure if that is enough for your purpose but it's what's available.</p>\n" }, { "answer_id": 364239, "author": "shanehoban", "author_id": 135707, "author_profile": "https://wordpress.stackexchange.com/users/135707", "pm_score": 2, "selected": false, "text": "<p>This worked for me, add this to the end of your themes <code>functions.php</code> file:</p>\n\n<pre><code>add_action('admin_head', 'wp_blocks_fullwidth');\n\nfunction wp_blocks_fullwidth() {\n echo '&lt;style&gt;\n .wp-block {\n max-width: unset;\n }\n &lt;/style&gt;';\n}\n</code></pre>\n" }, { "answer_id": 374174, "author": "Cody Rees", "author_id": 194045, "author_profile": "https://wordpress.stackexchange.com/users/194045", "pm_score": 2, "selected": false, "text": "<p>A functionality for wider layouts with Gutenberg Blocks is already supported officially by Wordpress. Just add the 'align-wide' theme support option to your theme setup function.</p>\n<pre><code>add_action( 'after_setup_theme', function() { \n add_theme_support( 'align-wide' );\n} ); \n</code></pre>\n<p>You'll now see an option to use a wide/full width layouts when editing Gutenberg Blocks</p>\n" } ]
2019/05/25
[ "https://wordpress.stackexchange.com/questions/338757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131339/" ]
I'm beginning to like Gutenberg, but I find it too narrow, particularly when working with the 'Columns' block. Why is it so narrow, and can it safely be made wider? I could try doing so with CSS, but I thought it best to ask first, to avoid potential trouble.
This worked for me, add this to the end of your themes `functions.php` file: ``` add_action('admin_head', 'wp_blocks_fullwidth'); function wp_blocks_fullwidth() { echo '<style> .wp-block { max-width: unset; } </style>'; } ```
338,834
<p>I wanted to change the default taxonomy terms order by its 'term_order' value instead of 'name' in admin side. So I tried something like below. But it doesn't work and php memory exhaust. </p> <pre><code>function uc_order_term( $wp_query ) { $wp_query-&gt;query( array( 'taxonomy' =&gt; 'category', 'orderby' =&gt; 'term_order', 'order' =&gt; 'ASC' ) ); } add_action( 'pre_get_terms', 'uc_order_term'); </code></pre> <p>However in similar way I tried to sort posts by menu_order and it works. </p> <pre><code>function uc_order_post( $wp_query ) { $wp_query-&gt;set('orderby', 'menu_order'); $wp_query-&gt;set('order', 'ASC'); } add_action( 'pre_get_posts', 'uc_order_post', 1 ); </code></pre> <p><a href="https://i.stack.imgur.com/pE0I7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pE0I7.png" alt="enter image description here"></a></p>
[ { "answer_id": 338779, "author": "Kaloyan", "author_id": 128309, "author_profile": "https://wordpress.stackexchange.com/users/128309", "pm_score": 0, "selected": false, "text": "<p>Yes you have to create new database for new wordpress site. It's imposible to create several wordpress websites with one database if you use prefix in tables names. </p>\n" }, { "answer_id": 338871, "author": "WSU", "author_id": 168474, "author_profile": "https://wordpress.stackexchange.com/users/168474", "pm_score": 2, "selected": true, "text": "<p>Yes, usually you create a new database, user and password as well as use another copy of WordPress to create a new site. You can create a new directory in the same place where the \"wordpress\" directory is located and use that one for the new site.</p>\n\n<p>Note that it is possible to use the same database for two different sites if you use a different table prefix (usually wp_). However, this is only advisable in same cases.</p>\n" } ]
2019/05/26
[ "https://wordpress.stackexchange.com/questions/338834", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162381/" ]
I wanted to change the default taxonomy terms order by its 'term\_order' value instead of 'name' in admin side. So I tried something like below. But it doesn't work and php memory exhaust. ``` function uc_order_term( $wp_query ) { $wp_query->query( array( 'taxonomy' => 'category', 'orderby' => 'term_order', 'order' => 'ASC' ) ); } add_action( 'pre_get_terms', 'uc_order_term'); ``` However in similar way I tried to sort posts by menu\_order and it works. ``` function uc_order_post( $wp_query ) { $wp_query->set('orderby', 'menu_order'); $wp_query->set('order', 'ASC'); } add_action( 'pre_get_posts', 'uc_order_post', 1 ); ``` [![enter image description here](https://i.stack.imgur.com/pE0I7.png)](https://i.stack.imgur.com/pE0I7.png)
Yes, usually you create a new database, user and password as well as use another copy of WordPress to create a new site. You can create a new directory in the same place where the "wordpress" directory is located and use that one for the new site. Note that it is possible to use the same database for two different sites if you use a different table prefix (usually wp\_). However, this is only advisable in same cases.
338,877
<p>i have a taxonomy list in the home page made with <a href="https://wordpress.org/plugins/wp-categories-widget/" rel="nofollow noreferrer">https://wordpress.org/plugins/wp-categories-widget/</a> plugin .. i crated image field for taxonomies with ACF. i can show tax image on archive page but i cant show images of taxonomies on the list of taxonomies in home page. please help</p> <p>Here is my code:-</p> <pre><code>&lt;?php /* Plugin Name: WP Categories Widget Plugin URI: http://www.mrwebsolution.in/ Description: It's a very simple plugin to display categories list in your website sidebar and you can define category list for your own custom taxonomy. Author: MR Web Solution Author URI: http://raghunathgurjar.wordpress.com Version: 1.4 */ /* Copyright 2018-19 wp-categories-widget (email : [email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly /************************************************************** START CLASSS WpCategoriesWidget **************************************************************/ class WpCategoriesWidget extends WP_Widget { /** * Register widget with WordPress. */ function __construct() { parent::__construct( 'wp_categories_widget', // Base ID __( 'WP Categories list', 'mrwebsolution' ), // Name array( 'description' =&gt; esc_html__( 'Display categories list of all taxonomy post type', 'mrwebsolution' ), ) // Args ); if(!is_admin()) add_action('wcw_style',array($this,'wcw_style_func')); add_filter( "plugin_action_links_".plugin_basename( __FILE__ ), array(&amp;$this,'wcw_add_settings_link') ); } /** * Front-end display of widget. * * @see WP_Widget::widget() * * @param array $args Widget arguments. * @param array $instance Saved values from database. */ public function widget( $args, $instance ) { echo $args['before_widget']; if ( ! empty( $instance['wcw_title'] ) &amp;&amp; !$instance['wcw_hide_title']) { echo $args['before_title'] . apply_filters( 'widget_title', $instance['wcw_title'] ) . $args['after_title']; } // add css do_action('wcw_style','wcw_style_func'); /** return category list */ if($instance['wcw_taxonomy_type']){ $va_category_HTML ='&lt;div class="ve-cat-widget-div"&gt;'; $va_category_HTML .='&lt;ul class="ve-cat-widget-listing"&gt;'; $args_val = array( 'hide_empty=0' ); $excludeCat= $instance['wcw_selected_categories'] ? $instance['wcw_selected_categories'] : ''; $wcw_action_on_cat= $instance['wcw_action_on_cat'] ? $instance['wcw_action_on_cat'] : ''; if($excludeCat &amp;&amp; $wcw_action_on_cat!='') $args_val[$wcw_action_on_cat] = $excludeCat; $terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' =&gt; 'count', 'order' =&gt; 'DESC','hide_empty'=&gt;0 )); if ( $terms ) { foreach ( $terms as $term ) { $term_link = get_term_link( $term ); if ( is_wp_error( $term_link ) ) { continue; } $carrentActiveClass=''; if($term-&gt;taxonomy=='category' &amp;&amp; is_category()) { $thisCat = get_category(get_query_var('cat'),false); if($thisCat-&gt;term_id == $term-&gt;term_id) $carrentActiveClass='class="active-cat"'; } if(is_tax()) { $currentTermType = get_query_var( 'taxonomy' ); $termId= get_queried_object()-&gt;term_id; if(is_tax($currentTermType) &amp;&amp; $termId==$term-&gt;term_id) $carrentActiveClass='class="active-cat"'; } $va_category_HTML .='&lt;li '.$carrentActiveClass.'&gt;&lt;a href="' . esc_url( $term_link ) . '"&gt;' . $term-&gt;name . '&lt;/a&gt;'; if (empty( $instance['wcw_hide_count'] )) { $va_category_HTML .='&lt;span class="post-count"&gt;'.$term-&gt;count.'&lt;/span&gt;'; } if ( $tax_img = get_field('4', $term-&gt;term_id)) { $va_category_HTML .= sprintf('&lt;img src="%s" /&gt;', $tax_img); } $va_category_HTML .='&lt;/li&gt;'; } } $va_category_HTML .='&lt;/ul&gt;&lt;/div&gt;'; echo $va_category_HTML; } echo $args['after_widget']; } /** * Back-end widget form. * * @see WP_Widget::form() * * @param array $instance Previously saved values from database. */ public function form( $instance ) { $wcw_title = ! empty( $instance['wcw_title'] ) ? $instance['wcw_title'] : esc_html__( 'WP Categories', 'virtualemployee' ); $wcw_hide_title = ! empty( $instance['wcw_hide_title'] ) ? $instance['wcw_hide_title'] : esc_html__( '', 'virtualemployee' ); $wcw_taxonomy_type = ! empty( $instance['wcw_taxonomy_type'] ) ? $instance['wcw_taxonomy_type'] : esc_html__( 'category', 'virtualemployee' ); $wcw_selected_categories = (! empty( $instance['wcw_selected_categories'] ) &amp;&amp; ! empty( $instance['wcw_action_on_cat'] ) ) ? $instance['wcw_selected_categories'] : esc_html__( '', 'virtualemployee' ); $wcw_action_on_cat = ! empty( $instance['wcw_action_on_cat'] ) ? $instance['wcw_action_on_cat'] : esc_html__( '', 'virtualemployee' ); $wcw_hide_count = ! empty( $instance['wcw_hide_count'] ) ? $instance['wcw_hide_count'] : esc_html__( '', 'virtualemployee' ); ?&gt; &lt;p&gt; &lt;label for="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_title' ) ); ?&gt;"&gt;&lt;?php _e( esc_attr( 'Title:' ) ); ?&gt;&lt;/label&gt; &lt;input class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_title' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'wcw_title' ) ); ?&gt;" type="text" value="&lt;?php echo esc_attr( $wcw_title ); ?&gt;"&gt; &lt;/p&gt; &lt;input class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_hide_title' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'wcw_hide_title' ) ); ?&gt;" type="checkbox" value="1" &lt;?php checked( $wcw_hide_title, 1 ); ?&gt;&gt; &lt;label for="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_hide_title' ) ); ?&gt;"&gt;&lt;?php _e( esc_attr( 'Hide Title' ) ); ?&gt; &lt;/label&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_taxonomy_type' ) ); ?&gt;"&gt;&lt;?php _e( esc_attr( 'Taxonomy Type:' ) ); ?&gt;&lt;/label&gt; &lt;select class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_taxonomy_type' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'wcw_taxonomy_type' ) ); ?&gt;"&gt; &lt;?php $args = array( 'public' =&gt; true, '_builtin' =&gt; false ); $output = 'names'; // or objects $operator = 'and'; // 'and' or 'or' $taxonomies = get_taxonomies( $args, $output, $operator ); array_push($taxonomies,'category'); if ( $taxonomies ) { foreach ( $taxonomies as $taxonomy ) { echo '&lt;option value="'.$taxonomy.'" '.selected($taxonomy,$wcw_taxonomy_type).'&gt;'.$taxonomy.'&lt;/option&gt;'; } } ?&gt; &lt;/select&gt; &lt;/p&gt; &lt;p&gt; &lt;select class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_action_on_cat' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'wcw_action_on_cat' ) ); ?&gt;"&gt; &lt;option value="" &lt;?php selected($wcw_action_on_cat,'' )?&gt; &gt;Show All Category:&lt;/option&gt; &lt;option value="include" &lt;?php selected($wcw_action_on_cat,'include' )?&gt; &gt;Include Selected Category:&lt;/option&gt; &lt;option value="exclude" &lt;?php selected($wcw_action_on_cat,'exclude' )?&gt; &gt;Exclude Selected Category:&lt;/option&gt; &lt;/select&gt; &lt;select class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_selected_categories' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'wcw_selected_categories' ) ); ?&gt;[]" multiple&gt; &lt;?php if($wcw_taxonomy_type){ $args = array( 'hide_empty=0' ); $terms = get_terms( $wcw_taxonomy_type, $args ); echo '&lt;option value="" '.selected(true, in_array('',$wcw_selected_categories), false).'&gt;None&lt;/option&gt;'; if ( $terms ) { foreach ( $terms as $term ) { echo '&lt;option value="'.$term-&gt;term_id.'" '.selected(true, in_array($term-&gt;term_id,$wcw_selected_categories), false).'&gt;'.$term-&gt;name.'&lt;/option&gt;'; } } } ?&gt; &lt;/select&gt; &lt;/p&gt; &lt;p&gt; &lt;input class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_hide_count' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'wcw_hide_count' ) ); ?&gt;" type="checkbox" value="1" &lt;?php checked( $wcw_hide_count, 1 ); ?&gt;&gt; &lt;label for="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'wcw_hide_count' ) ); ?&gt;"&gt;&lt;?php _e( esc_attr( 'Hide Count' ) ); ?&gt; &lt;/label&gt; &lt;/p&gt; &lt;p&gt;&lt;a href="mailto:[email protected]"&gt;Contact to Author&lt;/a&gt;&lt;/p&gt; &lt;?php } /** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['wcw_title'] = ( ! empty( $new_instance['wcw_title'] ) ) ? strip_tags( $new_instance['wcw_title'] ) : ''; $instance['wcw_hide_title'] = ( ! empty( $new_instance['wcw_hide_title'] ) ) ? strip_tags( $new_instance['wcw_hide_title'] ) : ''; $instance['wcw_taxonomy_type'] = ( ! empty( $new_instance['wcw_taxonomy_type'] ) ) ? strip_tags( $new_instance['wcw_taxonomy_type'] ) : ''; $instance['wcw_selected_categories'] = ( ! empty( $new_instance['wcw_selected_categories'] ) ) ? $new_instance['wcw_selected_categories'] : ''; $instance['wcw_action_on_cat'] = ( ! empty( $new_instance['wcw_action_on_cat'] ) ) ? $new_instance['wcw_action_on_cat'] : ''; $instance['wcw_hide_count'] = ( ! empty( $new_instance['wcw_hide_count'] ) ) ? strip_tags( $new_instance['wcw_hide_count'] ) : ''; return $instance; } /** plugin CSS **/ function wcw_style_func_css() { $style='&lt;style type="text/css"&gt;/* start wp categories widget CSS */.widget_wp_categories_widget{background:#fff; position:relative;}.wp_categories_widget h2{color:#4a5f6d;font-size:24px;font-weight:400;margin:0 0 25px;line-height:24px;text-transform:uppercase}.ve-cat-widget-div ul.ve-cat-widget-listing li{font-size: 16px; margin: 0px; border-bottom: 1px dashed #f0f0f0; position: relative; list-style-type: none; line-height: 35px;}.ve-cat-widget-div ul.ve-cat-widget-listing li:last-child{border:none;}.ve-cat-widget-div ul.ve-cat-widget-listing li a{display:inline-block;color:#007acc;transition:all .5s ease;-webkit-transition:all .5s ease;-ms-transition:all .5s ease;-moz-transition:all .5s ease}.ve-cat-widget-div ul.ve-cat-widget-listing li a:hover,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat a,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat span.post-count{color:#ee546c}.ve-cat-widget-div ul.ve-cat-widget-listing li span.post-count{height: 30px; min-width: 35px; text-align: center; background: #fff; color: #605f5f; border-radius: 5px; box-shadow: inset 2px 1px 3px rgba(0, 122, 204,.1); top: 0px; float: right; margin-top: 2px;}/* End category widget CSS*/&lt;/style&gt;'; echo $style; } function wcw_style_func() { add_action('wp_footer',array($this,'wcw_style_func_css')); } /** updtate plugins links using hooks**/ // Add settings link to plugin list page in admin function wcw_add_settings_link( $links ) { $settings_link = '&lt;a href="widgets.php"&gt;' . __( 'Settings Widget', 'mrwebsolution' ) . '&lt;/a&gt; | &lt;a href="mailto:[email protected]"&gt;' . __( 'Contact to Author', 'mrwebsolution' ) . '&lt;/a&gt;'; array_unshift( $links, $settings_link ); return $links; } }// class WpCategoriesWidget // register WpCategoriesWidget widget function register_wp_categories_widget() { register_widget( 'WpCategoriesWidget' ); } add_action( 'widgets_init', 'register_wp_categories_widget'); /************************************************************** END CLASSS WpCategoriesWidget **************************************************************/ </code></pre>
[ { "answer_id": 338779, "author": "Kaloyan", "author_id": 128309, "author_profile": "https://wordpress.stackexchange.com/users/128309", "pm_score": 0, "selected": false, "text": "<p>Yes you have to create new database for new wordpress site. It's imposible to create several wordpress websites with one database if you use prefix in tables names. </p>\n" }, { "answer_id": 338871, "author": "WSU", "author_id": 168474, "author_profile": "https://wordpress.stackexchange.com/users/168474", "pm_score": 2, "selected": true, "text": "<p>Yes, usually you create a new database, user and password as well as use another copy of WordPress to create a new site. You can create a new directory in the same place where the \"wordpress\" directory is located and use that one for the new site.</p>\n\n<p>Note that it is possible to use the same database for two different sites if you use a different table prefix (usually wp_). However, this is only advisable in same cases.</p>\n" } ]
2019/05/27
[ "https://wordpress.stackexchange.com/questions/338877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168662/" ]
i have a taxonomy list in the home page made with <https://wordpress.org/plugins/wp-categories-widget/> plugin .. i crated image field for taxonomies with ACF. i can show tax image on archive page but i cant show images of taxonomies on the list of taxonomies in home page. please help Here is my code:- ``` <?php /* Plugin Name: WP Categories Widget Plugin URI: http://www.mrwebsolution.in/ Description: It's a very simple plugin to display categories list in your website sidebar and you can define category list for your own custom taxonomy. Author: MR Web Solution Author URI: http://raghunathgurjar.wordpress.com Version: 1.4 */ /* Copyright 2018-19 wp-categories-widget (email : [email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly /************************************************************** START CLASSS WpCategoriesWidget **************************************************************/ class WpCategoriesWidget extends WP_Widget { /** * Register widget with WordPress. */ function __construct() { parent::__construct( 'wp_categories_widget', // Base ID __( 'WP Categories list', 'mrwebsolution' ), // Name array( 'description' => esc_html__( 'Display categories list of all taxonomy post type', 'mrwebsolution' ), ) // Args ); if(!is_admin()) add_action('wcw_style',array($this,'wcw_style_func')); add_filter( "plugin_action_links_".plugin_basename( __FILE__ ), array(&$this,'wcw_add_settings_link') ); } /** * Front-end display of widget. * * @see WP_Widget::widget() * * @param array $args Widget arguments. * @param array $instance Saved values from database. */ public function widget( $args, $instance ) { echo $args['before_widget']; if ( ! empty( $instance['wcw_title'] ) && !$instance['wcw_hide_title']) { echo $args['before_title'] . apply_filters( 'widget_title', $instance['wcw_title'] ) . $args['after_title']; } // add css do_action('wcw_style','wcw_style_func'); /** return category list */ if($instance['wcw_taxonomy_type']){ $va_category_HTML ='<div class="ve-cat-widget-div">'; $va_category_HTML .='<ul class="ve-cat-widget-listing">'; $args_val = array( 'hide_empty=0' ); $excludeCat= $instance['wcw_selected_categories'] ? $instance['wcw_selected_categories'] : ''; $wcw_action_on_cat= $instance['wcw_action_on_cat'] ? $instance['wcw_action_on_cat'] : ''; if($excludeCat && $wcw_action_on_cat!='') $args_val[$wcw_action_on_cat] = $excludeCat; $terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' => 'count', 'order' => 'DESC','hide_empty'=>0 )); if ( $terms ) { foreach ( $terms as $term ) { $term_link = get_term_link( $term ); if ( is_wp_error( $term_link ) ) { continue; } $carrentActiveClass=''; if($term->taxonomy=='category' && is_category()) { $thisCat = get_category(get_query_var('cat'),false); if($thisCat->term_id == $term->term_id) $carrentActiveClass='class="active-cat"'; } if(is_tax()) { $currentTermType = get_query_var( 'taxonomy' ); $termId= get_queried_object()->term_id; if(is_tax($currentTermType) && $termId==$term->term_id) $carrentActiveClass='class="active-cat"'; } $va_category_HTML .='<li '.$carrentActiveClass.'><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>'; if (empty( $instance['wcw_hide_count'] )) { $va_category_HTML .='<span class="post-count">'.$term->count.'</span>'; } if ( $tax_img = get_field('4', $term->term_id)) { $va_category_HTML .= sprintf('<img src="%s" />', $tax_img); } $va_category_HTML .='</li>'; } } $va_category_HTML .='</ul></div>'; echo $va_category_HTML; } echo $args['after_widget']; } /** * Back-end widget form. * * @see WP_Widget::form() * * @param array $instance Previously saved values from database. */ public function form( $instance ) { $wcw_title = ! empty( $instance['wcw_title'] ) ? $instance['wcw_title'] : esc_html__( 'WP Categories', 'virtualemployee' ); $wcw_hide_title = ! empty( $instance['wcw_hide_title'] ) ? $instance['wcw_hide_title'] : esc_html__( '', 'virtualemployee' ); $wcw_taxonomy_type = ! empty( $instance['wcw_taxonomy_type'] ) ? $instance['wcw_taxonomy_type'] : esc_html__( 'category', 'virtualemployee' ); $wcw_selected_categories = (! empty( $instance['wcw_selected_categories'] ) && ! empty( $instance['wcw_action_on_cat'] ) ) ? $instance['wcw_selected_categories'] : esc_html__( '', 'virtualemployee' ); $wcw_action_on_cat = ! empty( $instance['wcw_action_on_cat'] ) ? $instance['wcw_action_on_cat'] : esc_html__( '', 'virtualemployee' ); $wcw_hide_count = ! empty( $instance['wcw_hide_count'] ) ? $instance['wcw_hide_count'] : esc_html__( '', 'virtualemployee' ); ?> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_title' ) ); ?>" type="text" value="<?php echo esc_attr( $wcw_title ); ?>"> </p> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_hide_title' ) ); ?>" type="checkbox" value="1" <?php checked( $wcw_hide_title, 1 ); ?>> <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_title' ) ); ?>"><?php _e( esc_attr( 'Hide Title' ) ); ?> </label> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_taxonomy_type' ) ); ?>"><?php _e( esc_attr( 'Taxonomy Type:' ) ); ?></label> <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_taxonomy_type' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_taxonomy_type' ) ); ?>"> <?php $args = array( 'public' => true, '_builtin' => false ); $output = 'names'; // or objects $operator = 'and'; // 'and' or 'or' $taxonomies = get_taxonomies( $args, $output, $operator ); array_push($taxonomies,'category'); if ( $taxonomies ) { foreach ( $taxonomies as $taxonomy ) { echo '<option value="'.$taxonomy.'" '.selected($taxonomy,$wcw_taxonomy_type).'>'.$taxonomy.'</option>'; } } ?> </select> </p> <p> <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_action_on_cat' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_action_on_cat' ) ); ?>"> <option value="" <?php selected($wcw_action_on_cat,'' )?> >Show All Category:</option> <option value="include" <?php selected($wcw_action_on_cat,'include' )?> >Include Selected Category:</option> <option value="exclude" <?php selected($wcw_action_on_cat,'exclude' )?> >Exclude Selected Category:</option> </select> <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_selected_categories' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_selected_categories' ) ); ?>[]" multiple> <?php if($wcw_taxonomy_type){ $args = array( 'hide_empty=0' ); $terms = get_terms( $wcw_taxonomy_type, $args ); echo '<option value="" '.selected(true, in_array('',$wcw_selected_categories), false).'>None</option>'; if ( $terms ) { foreach ( $terms as $term ) { echo '<option value="'.$term->term_id.'" '.selected(true, in_array($term->term_id,$wcw_selected_categories), false).'>'.$term->name.'</option>'; } } } ?> </select> </p> <p> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_count' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_hide_count' ) ); ?>" type="checkbox" value="1" <?php checked( $wcw_hide_count, 1 ); ?>> <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_count' ) ); ?>"><?php _e( esc_attr( 'Hide Count' ) ); ?> </label> </p> <p><a href="mailto:[email protected]">Contact to Author</a></p> <?php } /** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['wcw_title'] = ( ! empty( $new_instance['wcw_title'] ) ) ? strip_tags( $new_instance['wcw_title'] ) : ''; $instance['wcw_hide_title'] = ( ! empty( $new_instance['wcw_hide_title'] ) ) ? strip_tags( $new_instance['wcw_hide_title'] ) : ''; $instance['wcw_taxonomy_type'] = ( ! empty( $new_instance['wcw_taxonomy_type'] ) ) ? strip_tags( $new_instance['wcw_taxonomy_type'] ) : ''; $instance['wcw_selected_categories'] = ( ! empty( $new_instance['wcw_selected_categories'] ) ) ? $new_instance['wcw_selected_categories'] : ''; $instance['wcw_action_on_cat'] = ( ! empty( $new_instance['wcw_action_on_cat'] ) ) ? $new_instance['wcw_action_on_cat'] : ''; $instance['wcw_hide_count'] = ( ! empty( $new_instance['wcw_hide_count'] ) ) ? strip_tags( $new_instance['wcw_hide_count'] ) : ''; return $instance; } /** plugin CSS **/ function wcw_style_func_css() { $style='<style type="text/css">/* start wp categories widget CSS */.widget_wp_categories_widget{background:#fff; position:relative;}.wp_categories_widget h2{color:#4a5f6d;font-size:24px;font-weight:400;margin:0 0 25px;line-height:24px;text-transform:uppercase}.ve-cat-widget-div ul.ve-cat-widget-listing li{font-size: 16px; margin: 0px; border-bottom: 1px dashed #f0f0f0; position: relative; list-style-type: none; line-height: 35px;}.ve-cat-widget-div ul.ve-cat-widget-listing li:last-child{border:none;}.ve-cat-widget-div ul.ve-cat-widget-listing li a{display:inline-block;color:#007acc;transition:all .5s ease;-webkit-transition:all .5s ease;-ms-transition:all .5s ease;-moz-transition:all .5s ease}.ve-cat-widget-div ul.ve-cat-widget-listing li a:hover,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat a,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat span.post-count{color:#ee546c}.ve-cat-widget-div ul.ve-cat-widget-listing li span.post-count{height: 30px; min-width: 35px; text-align: center; background: #fff; color: #605f5f; border-radius: 5px; box-shadow: inset 2px 1px 3px rgba(0, 122, 204,.1); top: 0px; float: right; margin-top: 2px;}/* End category widget CSS*/</style>'; echo $style; } function wcw_style_func() { add_action('wp_footer',array($this,'wcw_style_func_css')); } /** updtate plugins links using hooks**/ // Add settings link to plugin list page in admin function wcw_add_settings_link( $links ) { $settings_link = '<a href="widgets.php">' . __( 'Settings Widget', 'mrwebsolution' ) . '</a> | <a href="mailto:[email protected]">' . __( 'Contact to Author', 'mrwebsolution' ) . '</a>'; array_unshift( $links, $settings_link ); return $links; } }// class WpCategoriesWidget // register WpCategoriesWidget widget function register_wp_categories_widget() { register_widget( 'WpCategoriesWidget' ); } add_action( 'widgets_init', 'register_wp_categories_widget'); /************************************************************** END CLASSS WpCategoriesWidget **************************************************************/ ```
Yes, usually you create a new database, user and password as well as use another copy of WordPress to create a new site. You can create a new directory in the same place where the "wordpress" directory is located and use that one for the new site. Note that it is possible to use the same database for two different sites if you use a different table prefix (usually wp\_). However, this is only advisable in same cases.
338,988
<p>I want to show the category name of the post when I write [category] shortcode in the post body. I'm using this code but only showing array error.</p> <p>Sorry, I'm not an expert in coding. Perhaps you can redefine my code? Please.</p> <pre><code>function cat_post() { return get_the_category(); } add_shortcode('categorypost', 'cat_post'); </code></pre>
[ { "answer_id": 339021, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>The main problem with your code is that you register <code>[categorypost]</code> shortcode, but you want to register it as <code>[category]</code>.</p>\n\n<p>Another problem is that your shortcode should return HTML code - the output of shortcode. And as you can see <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\">here</a>, the <code>get_the_category</code> function returns an array of terms.</p>\n\n<h2>So how to write it correctly?</h2>\n\n<p>The easiest way will be to use <a href=\"https://codex.wordpress.org/Function_Reference/the_category\" rel=\"nofollow noreferrer\"><code>the_category()</code></a> template tag. So here's the code:</p>\n\n<pre><code>function category_shortcode_callback( $atts ) {\n // set default params for the_category\n $a = shortcode_atts( array(\n 'separator' =&gt; '',\n 'parents' =&gt; '',\n 'post_id' =&gt; false\n ), $atts );\n\n ob_start(); // start output buffering\n the_category( $a['separator'], $a['parents'], $a['post_id'] ); // print categories\n return ob_get_clean(); // grab the output and return it\n}\nadd_shortcode( 'category', 'category_shortcode_callback' );\n</code></pre>\n" }, { "answer_id": 339024, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 1, "selected": true, "text": "<p>Put the code below in your <strong>functions.php</strong> file:</p>\n\n<pre><code>function register_theme_shortcodes() {\n add_shortcode( 'category',\n /**\n * category shortcode function.\n *\n * @param array $atts\n *\n * @return string\n */\n function ( $atts ) {\n $atts = shortcode_atts(\n array(\n 'id' =&gt; '',\n ),\n $atts\n );\n\n /**\n * @var int $id Optional Post ID to get categories from.\n */\n extract( $atts );\n\n if ( $id ) {\n $post_id = $id;\n } else {\n global $post;\n\n if ( $post instanceof WP_Post ) {\n $post_id = $post-&gt;ID;\n }\n }\n\n if ( empty( $post_id ) ) {\n $output = '';\n } else {\n $output = [];\n\n if ( $post_categories = get_the_category() ) {\n /**\n * @var WP_Term $category\n */\n foreach ( $post_categories as $category ) {\n // Builds the category name with its link.\n $output[] = \"&lt;a href='\" . get_term_link( $category-&gt;term_id ) . \"'&gt;{$category-&gt;name}&lt;/a&gt;\";\n\n // Build just the category name.\n // $output[] = $category-&gt;name;\n }\n }\n\n $output = implode( ', ', $output );\n }\n\n return $output;\n }\n );\n}\n\nadd_action( 'init', 'register_theme_shortcodes' );\n</code></pre>\n\n<p>Make sure you pay attention to the comments along the code as you can have the category names output with their links or not.</p>\n\n<p>And if you want to print the category of any other post, outside the post, the code above also supports the following format: <code>[category id=1234]</code>.</p>\n" } ]
2019/05/28
[ "https://wordpress.stackexchange.com/questions/338988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168974/" ]
I want to show the category name of the post when I write [category] shortcode in the post body. I'm using this code but only showing array error. Sorry, I'm not an expert in coding. Perhaps you can redefine my code? Please. ``` function cat_post() { return get_the_category(); } add_shortcode('categorypost', 'cat_post'); ```
Put the code below in your **functions.php** file: ``` function register_theme_shortcodes() { add_shortcode( 'category', /** * category shortcode function. * * @param array $atts * * @return string */ function ( $atts ) { $atts = shortcode_atts( array( 'id' => '', ), $atts ); /** * @var int $id Optional Post ID to get categories from. */ extract( $atts ); if ( $id ) { $post_id = $id; } else { global $post; if ( $post instanceof WP_Post ) { $post_id = $post->ID; } } if ( empty( $post_id ) ) { $output = ''; } else { $output = []; if ( $post_categories = get_the_category() ) { /** * @var WP_Term $category */ foreach ( $post_categories as $category ) { // Builds the category name with its link. $output[] = "<a href='" . get_term_link( $category->term_id ) . "'>{$category->name}</a>"; // Build just the category name. // $output[] = $category->name; } } $output = implode( ', ', $output ); } return $output; } ); } add_action( 'init', 'register_theme_shortcodes' ); ``` Make sure you pay attention to the comments along the code as you can have the category names output with their links or not. And if you want to print the category of any other post, outside the post, the code above also supports the following format: `[category id=1234]`.
339,005
<p>Today I migrated a WordPress site from another server to a new server, there is a new domain and new host, so I follow the manual way to upload my site. That was, I downloaded files and upload it on to new fresh host and, database export and import to the new host. After that, I have changed site URL, home page URL in the database, so site looked fine. </p> <p>But when I try to edit a page, that my back end editing redirects me to 404 page not found. But this issue is only for some old pages while making new page has no issues whatsoever.</p> <p>After that, I changed all the past domain record matching database records and replace them with the new domain name. Still, I cannot edit my pages.</p> <p>I tried all the listed ways like .htaccess, permalinks reset, deleting the .htacess and resetting permalinks, but none of that has worked.</p> <p>Please help me out is very frustrating</p>
[ { "answer_id": 339021, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>The main problem with your code is that you register <code>[categorypost]</code> shortcode, but you want to register it as <code>[category]</code>.</p>\n\n<p>Another problem is that your shortcode should return HTML code - the output of shortcode. And as you can see <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\">here</a>, the <code>get_the_category</code> function returns an array of terms.</p>\n\n<h2>So how to write it correctly?</h2>\n\n<p>The easiest way will be to use <a href=\"https://codex.wordpress.org/Function_Reference/the_category\" rel=\"nofollow noreferrer\"><code>the_category()</code></a> template tag. So here's the code:</p>\n\n<pre><code>function category_shortcode_callback( $atts ) {\n // set default params for the_category\n $a = shortcode_atts( array(\n 'separator' =&gt; '',\n 'parents' =&gt; '',\n 'post_id' =&gt; false\n ), $atts );\n\n ob_start(); // start output buffering\n the_category( $a['separator'], $a['parents'], $a['post_id'] ); // print categories\n return ob_get_clean(); // grab the output and return it\n}\nadd_shortcode( 'category', 'category_shortcode_callback' );\n</code></pre>\n" }, { "answer_id": 339024, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 1, "selected": true, "text": "<p>Put the code below in your <strong>functions.php</strong> file:</p>\n\n<pre><code>function register_theme_shortcodes() {\n add_shortcode( 'category',\n /**\n * category shortcode function.\n *\n * @param array $atts\n *\n * @return string\n */\n function ( $atts ) {\n $atts = shortcode_atts(\n array(\n 'id' =&gt; '',\n ),\n $atts\n );\n\n /**\n * @var int $id Optional Post ID to get categories from.\n */\n extract( $atts );\n\n if ( $id ) {\n $post_id = $id;\n } else {\n global $post;\n\n if ( $post instanceof WP_Post ) {\n $post_id = $post-&gt;ID;\n }\n }\n\n if ( empty( $post_id ) ) {\n $output = '';\n } else {\n $output = [];\n\n if ( $post_categories = get_the_category() ) {\n /**\n * @var WP_Term $category\n */\n foreach ( $post_categories as $category ) {\n // Builds the category name with its link.\n $output[] = \"&lt;a href='\" . get_term_link( $category-&gt;term_id ) . \"'&gt;{$category-&gt;name}&lt;/a&gt;\";\n\n // Build just the category name.\n // $output[] = $category-&gt;name;\n }\n }\n\n $output = implode( ', ', $output );\n }\n\n return $output;\n }\n );\n}\n\nadd_action( 'init', 'register_theme_shortcodes' );\n</code></pre>\n\n<p>Make sure you pay attention to the comments along the code as you can have the category names output with their links or not.</p>\n\n<p>And if you want to print the category of any other post, outside the post, the code above also supports the following format: <code>[category id=1234]</code>.</p>\n" } ]
2019/05/28
[ "https://wordpress.stackexchange.com/questions/339005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165090/" ]
Today I migrated a WordPress site from another server to a new server, there is a new domain and new host, so I follow the manual way to upload my site. That was, I downloaded files and upload it on to new fresh host and, database export and import to the new host. After that, I have changed site URL, home page URL in the database, so site looked fine. But when I try to edit a page, that my back end editing redirects me to 404 page not found. But this issue is only for some old pages while making new page has no issues whatsoever. After that, I changed all the past domain record matching database records and replace them with the new domain name. Still, I cannot edit my pages. I tried all the listed ways like .htaccess, permalinks reset, deleting the .htacess and resetting permalinks, but none of that has worked. Please help me out is very frustrating
Put the code below in your **functions.php** file: ``` function register_theme_shortcodes() { add_shortcode( 'category', /** * category shortcode function. * * @param array $atts * * @return string */ function ( $atts ) { $atts = shortcode_atts( array( 'id' => '', ), $atts ); /** * @var int $id Optional Post ID to get categories from. */ extract( $atts ); if ( $id ) { $post_id = $id; } else { global $post; if ( $post instanceof WP_Post ) { $post_id = $post->ID; } } if ( empty( $post_id ) ) { $output = ''; } else { $output = []; if ( $post_categories = get_the_category() ) { /** * @var WP_Term $category */ foreach ( $post_categories as $category ) { // Builds the category name with its link. $output[] = "<a href='" . get_term_link( $category->term_id ) . "'>{$category->name}</a>"; // Build just the category name. // $output[] = $category->name; } } $output = implode( ', ', $output ); } return $output; } ); } add_action( 'init', 'register_theme_shortcodes' ); ``` Make sure you pay attention to the comments along the code as you can have the category names output with their links or not. And if you want to print the category of any other post, outside the post, the code above also supports the following format: `[category id=1234]`.
339,017
<p>On a business listing in a directory I have a button which will lead to a custom plugin.</p> <p>The custom plugin needs to know the userid of the user (registered user) who clicked the button to get here, plus the business id of the page it came from.</p> <p>How do I track that info in the plugin?</p> <p>Thanks.</p>
[ { "answer_id": 339021, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>The main problem with your code is that you register <code>[categorypost]</code> shortcode, but you want to register it as <code>[category]</code>.</p>\n\n<p>Another problem is that your shortcode should return HTML code - the output of shortcode. And as you can see <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\">here</a>, the <code>get_the_category</code> function returns an array of terms.</p>\n\n<h2>So how to write it correctly?</h2>\n\n<p>The easiest way will be to use <a href=\"https://codex.wordpress.org/Function_Reference/the_category\" rel=\"nofollow noreferrer\"><code>the_category()</code></a> template tag. So here's the code:</p>\n\n<pre><code>function category_shortcode_callback( $atts ) {\n // set default params for the_category\n $a = shortcode_atts( array(\n 'separator' =&gt; '',\n 'parents' =&gt; '',\n 'post_id' =&gt; false\n ), $atts );\n\n ob_start(); // start output buffering\n the_category( $a['separator'], $a['parents'], $a['post_id'] ); // print categories\n return ob_get_clean(); // grab the output and return it\n}\nadd_shortcode( 'category', 'category_shortcode_callback' );\n</code></pre>\n" }, { "answer_id": 339024, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 1, "selected": true, "text": "<p>Put the code below in your <strong>functions.php</strong> file:</p>\n\n<pre><code>function register_theme_shortcodes() {\n add_shortcode( 'category',\n /**\n * category shortcode function.\n *\n * @param array $atts\n *\n * @return string\n */\n function ( $atts ) {\n $atts = shortcode_atts(\n array(\n 'id' =&gt; '',\n ),\n $atts\n );\n\n /**\n * @var int $id Optional Post ID to get categories from.\n */\n extract( $atts );\n\n if ( $id ) {\n $post_id = $id;\n } else {\n global $post;\n\n if ( $post instanceof WP_Post ) {\n $post_id = $post-&gt;ID;\n }\n }\n\n if ( empty( $post_id ) ) {\n $output = '';\n } else {\n $output = [];\n\n if ( $post_categories = get_the_category() ) {\n /**\n * @var WP_Term $category\n */\n foreach ( $post_categories as $category ) {\n // Builds the category name with its link.\n $output[] = \"&lt;a href='\" . get_term_link( $category-&gt;term_id ) . \"'&gt;{$category-&gt;name}&lt;/a&gt;\";\n\n // Build just the category name.\n // $output[] = $category-&gt;name;\n }\n }\n\n $output = implode( ', ', $output );\n }\n\n return $output;\n }\n );\n}\n\nadd_action( 'init', 'register_theme_shortcodes' );\n</code></pre>\n\n<p>Make sure you pay attention to the comments along the code as you can have the category names output with their links or not.</p>\n\n<p>And if you want to print the category of any other post, outside the post, the code above also supports the following format: <code>[category id=1234]</code>.</p>\n" } ]
2019/05/28
[ "https://wordpress.stackexchange.com/questions/339017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167925/" ]
On a business listing in a directory I have a button which will lead to a custom plugin. The custom plugin needs to know the userid of the user (registered user) who clicked the button to get here, plus the business id of the page it came from. How do I track that info in the plugin? Thanks.
Put the code below in your **functions.php** file: ``` function register_theme_shortcodes() { add_shortcode( 'category', /** * category shortcode function. * * @param array $atts * * @return string */ function ( $atts ) { $atts = shortcode_atts( array( 'id' => '', ), $atts ); /** * @var int $id Optional Post ID to get categories from. */ extract( $atts ); if ( $id ) { $post_id = $id; } else { global $post; if ( $post instanceof WP_Post ) { $post_id = $post->ID; } } if ( empty( $post_id ) ) { $output = ''; } else { $output = []; if ( $post_categories = get_the_category() ) { /** * @var WP_Term $category */ foreach ( $post_categories as $category ) { // Builds the category name with its link. $output[] = "<a href='" . get_term_link( $category->term_id ) . "'>{$category->name}</a>"; // Build just the category name. // $output[] = $category->name; } } $output = implode( ', ', $output ); } return $output; } ); } add_action( 'init', 'register_theme_shortcodes' ); ``` Make sure you pay attention to the comments along the code as you can have the category names output with their links or not. And if you want to print the category of any other post, outside the post, the code above also supports the following format: `[category id=1234]`.
339,043
<p>I am developing a theme and I noticed that</p> <pre><code>get_post_meta($post-&gt;ID, '_wp_page_template', true); </code></pre> <p>returns 'static-page.php' (as expected) when queried on static pages but returns nothing (expected 'single-post.php') when queried on a single blog post pages.</p> <p>I have single-post.php file set up and working, content displayed, etc. But I can't get template file name for some reason on this page. It works just fine on static pages. Any ideas why?</p>
[ { "answer_id": 339044, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I am using the template file name in the section to load\n corresponding css files. For static-page.php I am loading\n static-page.css, similarly for single-post.php I would like to load\n single-post.css. As said, it is working fine on my static pages, but\n returns zero on single blog post page.</p>\n</blockquote>\n\n<p>This isn't really the correct way to do this. For starters you shouldn't be placing anything in <code>&lt;head&gt;</code> directly. Instead you should be 'enqueueing' the styles from your functions file, <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow noreferrer\">as outlined in the Theme Developer Handbook</a>.</p>\n\n<p>When you do it this way you can use the <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow noreferrer\">Conditional Tags</a> to determine what is currently being viewed, and enqueue the appropriate styles.</p>\n\n<p>For example, if you want to load styles for single posts only, you'd use <code>is_singular( 'post' )</code>., while for custom page templates you'd use <code>is_page_template( 'static-page.php' );</code>.</p>\n" }, { "answer_id": 339906, "author": "sergekol", "author_id": 169014, "author_profile": "https://wordpress.stackexchange.com/users/169014", "pm_score": 0, "selected": false, "text": "<p>I am working today to upgrade my theme as per Jacob's earlier suggestion. I removed all the stylesheet links from header.php and put them into functions.php.</p>\n\n<p>The non-conditional stylesheets and those stylesheets which are connected using is_page_template() work without any issue.</p>\n\n<p>However, the stylesheets which are connected using is_category, is_tag, etc. do not work.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>function add_styles () {\n\n // Styles for all pages - work just fine\n\n wp_enqueue_style( 'normalize', get_template_directory_uri().'/css/normalize.css', false, '1', 'all' );\n wp_enqueue_style( 'main', get_template_directory_uri().'/css/main.css', false, '1', 'all' );\n wp_enqueue_style( 'header', get_template_directory_uri().'/css/header.css', false, '1', 'all' );\n wp_enqueue_style( 'index', get_template_directory_uri().'/css/index.css', false, '1', 'all' );\n wp_enqueue_style( 'functions', get_template_directory_uri().'/css/functions.css', false, '1', 'all' );\n wp_enqueue_style( 'footer', get_template_directory_uri().'/css/footer.css', false, '1', 'all' );\n\n // Styles for custom template pages - DO NOT work\n\n if ( is_category() ) { wp_enqueue_style( 'category', get_template_directory_uri().'/css/category.css', false, '1', 'all' ); };\n if ( is_tag() ) { wp_enqueue_style( 'tag', get_template_directory_uri().'/css/tag.css', false, '1', 'all' ); };\n if ( is_single() ) { wp_enqueue_style( 'single', get_template_directory_uri().'/css/single-post.css', false, '1', 'all' ); };\n if ( is_date() ) { wp_enqueue_style( 'date', get_template_directory_uri().'/css/date.css', false, '1', 'all' ); };\n\n // Styles for static page templates - DO work\n\n if ( is_page_template('front-page.php') ) { wp_enqueue_style( 'front-page', get_template_directory_uri().'/css/front-page.css', false, '1', 'all' ); };\n if ( is_page_template('static-page.php') ) { wp_enqueue_style( 'static-page', get_template_directory_uri().'/css/static-page.css', false, '1', 'all' ); };\n if ( is_page_template('landing-page.php') ) { wp_enqueue_style( 'landing-page', get_template_directory_uri().'/css/landing-page.css', false, '1', 'all' ); };\n if ( is_page_template('404.php') ) { wp_enqueue_style( '404', get_template_directory_uri().'/css/404.css', false, '1', 'all' ); };\n\nadd_action( 'wp_enqueue_scripts', 'add_styles' );\n</code></pre>\n\n<p>It is clear that is_category, is_tag, etc. do not work. From reading CODEX and the internet I figured out that they are called from functions.php too early. However, I can't understand how to hook them properly so that they work.</p>\n\n<p>What would be the right way to do this?</p>\n" } ]
2019/05/29
[ "https://wordpress.stackexchange.com/questions/339043", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169014/" ]
I am developing a theme and I noticed that ``` get_post_meta($post->ID, '_wp_page_template', true); ``` returns 'static-page.php' (as expected) when queried on static pages but returns nothing (expected 'single-post.php') when queried on a single blog post pages. I have single-post.php file set up and working, content displayed, etc. But I can't get template file name for some reason on this page. It works just fine on static pages. Any ideas why?
> > I am using the template file name in the section to load > corresponding css files. For static-page.php I am loading > static-page.css, similarly for single-post.php I would like to load > single-post.css. As said, it is working fine on my static pages, but > returns zero on single blog post page. > > > This isn't really the correct way to do this. For starters you shouldn't be placing anything in `<head>` directly. Instead you should be 'enqueueing' the styles from your functions file, [as outlined in the Theme Developer Handbook](https://developer.wordpress.org/themes/basics/including-css-javascript/). When you do it this way you can use the [Conditional Tags](https://developer.wordpress.org/themes/basics/including-css-javascript/) to determine what is currently being viewed, and enqueue the appropriate styles. For example, if you want to load styles for single posts only, you'd use `is_singular( 'post' )`., while for custom page templates you'd use `is_page_template( 'static-page.php' );`.
339,052
<p><strong>UPDATED:</strong></p> <p>I have a Custom Post Type <strong>Commercials</strong>. This post type has a title and a video id. I want to search from this specific post type. Right now it returns result which matches the titles only, I also want it to return result from tags too. For example, let's say I have a commercial named <em>"<strong>Lorem Ipsum Commercial</strong>"</em> and this has a tag <em><strong>my tag</strong></em>. <em>I want to it to return result if the searched value matches the title or the tag.</em> This is as far I got.</p> <p>function.php</p> <pre><code>function searchCommercial($query) { if ( $query -&gt; is_search &amp;&amp; !is_admin() ) { if( isset($_GET['post_type']) ) { $type = $_GET['post_type']; if( $type == 'commercials' ) { $query -&gt; set( 'post_type', array('commercials') ); /* $terms = explode(' ', $query-&gt;get('s')); $query-&gt;set('tax_query', array( 'relation'=&gt;'OR', array( 'taxonomy'=&gt;'post_tag', 'field'=&gt;'slug', 'terms'=&gt;$terms ) ));*/ } } } return $query; } add_filter( 'pre_get_posts', 'searchCommercial' ); </code></pre> <p>Search form:</p> <pre><code>&lt;form role="search" method="GET" class="search-form" action="&lt;?php echo home_url('/'); ?&gt;"&gt; &lt;label&gt; &lt;input type="search" class="search-field" name="s" value="&lt;?php echo get_search_query(); ?&gt;" &gt; &lt;input type="hidden" name="post_type" value="commercials"&gt; &lt;/label&gt; &lt;input type="submit" class="submit" value="Search"&gt; &lt;/form&gt; </code></pre> <p>search.php</p> <pre><code>if ( have_posts() ) : while ( have_posts() ) : the_post(); if ( isset($_GET['post_type']) ) { $type = $_GET['post_type']; if ( $type == 'commercials' ) { get_template_part( 'templates/content-commercilas' ); } } endwhile; endif; </code></pre> <p>I've been trying to solve this for two days, any help would be very much appreciated.</p> <p><strong>UPDATE</strong> post type codes</p> <pre><code>add_action('init', registering_commercial); function registering_commercial() { $labels = array( 'name' =&gt; __( 'Commercials' ), 'singular_name' =&gt; __( 'Commercial' ), 'menu_name' =&gt; __( 'Commercials' ), 'name_admin_bar' =&gt; __( 'Commercial' ), 'add_new' =&gt; __( 'Add New' ), 'add_new_item' =&gt; __( 'Add New Commercial' ), 'new_item' =&gt; __( 'New Commercial' ), 'edit_item' =&gt; __( 'Edit Commercial' ), 'view_item' =&gt; __( 'View Commercial' ), 'view_items' =&gt; __( 'View Commercials' ), 'all_items' =&gt; __( 'All Commercials' ), 'search_items' =&gt; __( 'Search Commercial' ), 'parent_item_colon' =&gt; __( 'Parent Commercial:' ), 'not_found' =&gt; __( 'No Commercial found.' ), 'not_found_in_trash' =&gt; __( 'No Commercial found in Trash.' ), 'item_published' =&gt; __( 'Commercial is published.' ), 'item_updated' =&gt; __( 'Commercial successfully updated!' ) ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; __( 'Description for Commercials.' ), 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'commercials' ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array( 'title', 'thumbnail' ), 'taxonomies' =&gt; array( 'commercial_category', 'post_tag' ) ); register_post_type( 'commercials', $args ); } </code></pre> <p>Category Codes:</p> <pre><code>add_action( 'init', 'create_commercial_category', 0 ); function create_commercial_category() { $labels = array( 'name' =&gt; __( 'Commercial Categories' ), 'singular_name' =&gt; __( 'Category' ), 'search_items' =&gt; __( 'Search Category' ), 'all_items' =&gt; __( 'All Categories' ), 'parent_item' =&gt; __( 'Parent Category' ), 'parent_item_colon' =&gt; __( 'Parent Category:' ), 'edit_item' =&gt; __( 'Edit Category' ), 'update_item' =&gt; __( 'Update Category' ), 'add_new_item' =&gt; __( 'Add New Category' ), 'new_item_name' =&gt; __( 'New Category Name' ), 'menu_name' =&gt; __( 'Commercial Category' ), ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'commercial-category' ) ); register_taxonomy( 'commercial_category', array( 'commercials' ), $args ); } </code></pre>
[ { "answer_id": 339064, "author": "Milan Hirpara", "author_id": 168898, "author_profile": "https://wordpress.stackexchange.com/users/168898", "pm_score": 0, "selected": false, "text": "<p>I think you need to remove </p>\n\n<pre><code>$_GET['post_type']\n</code></pre>\n\n<p>Please use below code i think you might help :</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // Only target front end,\n &amp;&amp; $q-&gt;is_main_query() // Only target the main query\n &amp;&amp; $q-&gt;is_search() // Only target the search page\n ) {\n $q-&gt;set( 'post_type', ['commercials'] );\n\n $terms = explode(' ', $q-&gt;get('s'));\n\n $q-&gt;set('tax_query', array(\n 'relation'=&gt;'OR',\n array(\n 'taxonomy'=&gt;'post_tag',\n 'field'=&gt;'slug',\n 'terms'=&gt;$terms\n )\n ));\n }\n});\n</code></pre>\n" }, { "answer_id": 339106, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 1, "selected": false, "text": "<p>The way you are customizing the query you are telling it to search for posts that ALSO match a custom <code>tax_query</code> criteria. This would never work, logically speaking.</p>\n\n<p>You said, \"I want it to return a result if this <strong>tag</strong> is searched or if it matches the <strong>title</strong>\" for which I understand ONE or ANOTHER.</p>\n\n<p>I'll show you a completely different approach, using basically the following logic:</p>\n\n<ol>\n<li>You said \"This post type has a title and a video id\" so I assume you are not going to use the field/column <code>post_excerpt</code> for the CPT <code>commercials</code>. You can add it to <code>supports</code>, but it is not required for this to work.</li>\n<li>We can make use of the action <code>save_post</code> to force WordPress adding your post tags to the field <code>post_excerpt</code> of a Commercial. When you take a look at the code this will sound less confusing.</li>\n<li>We know that WordPress by default searches the columns <code>post_title</code>, <code>post_excerpt</code> and <code>post_content</code> for a term when the query var <code>s</code> is present. So doing number 2 above would solve your issue, because WordPress would take care of the rest.</li>\n</ol>\n\n<p>Getting our hands dirty... we will still need to use the <code>pre_get_posts</code> action (yes, not a filter):</p>\n\n<pre><code>/**\n * @param WP_Query $query\n */\nfunction searchCommercial( $query ) {\n if ( is_search() &amp;&amp; ! is_admin() ) {\n if ( isset( $_GET['post_type'] ) ) {\n $type = $_GET['post_type'];\n if ( $type == 'commercials' ) {\n $query-&gt;set( 'post_type', array( 'commercials' ) );\n }\n }\n }\n}\n\nadd_action( 'pre_get_posts', 'searchCommercial' );\n</code></pre>\n\n<p>And for saving the post tags within the <code>post_excerpt</code> of a <strong>Commercial</strong>:</p>\n\n<pre><code>/**\n * Fires once a post has been created or updated.\n *\n * @param int $post_id\n * @param WP_Post $post\n * @param bool $update Whether this is an existing post being updated or not.\n */\nfunction add_post_tags_to_commercials( $post_id, $post, $update ) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n if ( wp_is_post_revision( $post_id ) ) {\n return;\n }\n\n if ( $post-&gt;post_type != 'commercials' ) {\n return;\n }\n\n $post_tags = wp_get_object_terms( $post_id, 'post_tag' );\n\n if ( $post_tags ) {\n $tags_with_comma = [];\n\n /**\n * @var WP_Term $tag\n */\n foreach ( $post_tags as $tag ) {\n $tags_with_comma[] = $tag-&gt;name;\n $tags_with_comma[] = $tag-&gt;slug;\n }\n\n $tags_with_comma = implode( ',', $tags_with_comma );\n\n // Unhook this function so it doesn't loop infinitely.\n remove_action( 'save_post', 'add_post_tags_to_commercials', 20 );\n\n wp_update_post(\n array(\n 'ID' =&gt; $post_id,\n 'post_excerpt' =&gt; $tags_with_comma, // The tags will be saved within the `post_excerpt` column.\n )\n );\n\n // Re-hook this function.\n add_action( 'save_post', 'add_post_tags_to_commercials', 20, 3 );\n }\n}\n\nadd_action( 'save_post', 'add_post_tags_to_commercials', 20, 3 );\n</code></pre>\n\n<p>The 2 snippets above can be placed within your <strong>functions.php</strong> file.</p>\n\n<p><strong>Notice:</strong></p>\n\n<ul>\n<li>If you are using Guttenberg for your CPT <code>commercials</code>, you may have issues attaching post tags to it. Until now, WP version 5.2.1, is still having trouble attaching tags to a post using the AJAX process.</li>\n<li>You have to save all of your <strong>Commercials</strong> again. I hope it's just a few.</li>\n<li>Consider adding the string <code>excerpt</code> to your <code>commercials</code> <code>supports</code> as it would make it easier for you to see what's been added to the <code>post_excerpt</code> column:</li>\n</ul>\n\n<pre><code>'supports' =&gt; array( 'title', 'thumbnail', `excerpt` ),\n</code></pre>\n" } ]
2019/05/29
[ "https://wordpress.stackexchange.com/questions/339052", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109544/" ]
**UPDATED:** I have a Custom Post Type **Commercials**. This post type has a title and a video id. I want to search from this specific post type. Right now it returns result which matches the titles only, I also want it to return result from tags too. For example, let's say I have a commercial named *"**Lorem Ipsum Commercial**"* and this has a tag ***my tag***. *I want to it to return result if the searched value matches the title or the tag.* This is as far I got. function.php ``` function searchCommercial($query) { if ( $query -> is_search && !is_admin() ) { if( isset($_GET['post_type']) ) { $type = $_GET['post_type']; if( $type == 'commercials' ) { $query -> set( 'post_type', array('commercials') ); /* $terms = explode(' ', $query->get('s')); $query->set('tax_query', array( 'relation'=>'OR', array( 'taxonomy'=>'post_tag', 'field'=>'slug', 'terms'=>$terms ) ));*/ } } } return $query; } add_filter( 'pre_get_posts', 'searchCommercial' ); ``` Search form: ``` <form role="search" method="GET" class="search-form" action="<?php echo home_url('/'); ?>"> <label> <input type="search" class="search-field" name="s" value="<?php echo get_search_query(); ?>" > <input type="hidden" name="post_type" value="commercials"> </label> <input type="submit" class="submit" value="Search"> </form> ``` search.php ``` if ( have_posts() ) : while ( have_posts() ) : the_post(); if ( isset($_GET['post_type']) ) { $type = $_GET['post_type']; if ( $type == 'commercials' ) { get_template_part( 'templates/content-commercilas' ); } } endwhile; endif; ``` I've been trying to solve this for two days, any help would be very much appreciated. **UPDATE** post type codes ``` add_action('init', registering_commercial); function registering_commercial() { $labels = array( 'name' => __( 'Commercials' ), 'singular_name' => __( 'Commercial' ), 'menu_name' => __( 'Commercials' ), 'name_admin_bar' => __( 'Commercial' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Commercial' ), 'new_item' => __( 'New Commercial' ), 'edit_item' => __( 'Edit Commercial' ), 'view_item' => __( 'View Commercial' ), 'view_items' => __( 'View Commercials' ), 'all_items' => __( 'All Commercials' ), 'search_items' => __( 'Search Commercial' ), 'parent_item_colon' => __( 'Parent Commercial:' ), 'not_found' => __( 'No Commercial found.' ), 'not_found_in_trash' => __( 'No Commercial found in Trash.' ), 'item_published' => __( 'Commercial is published.' ), 'item_updated' => __( 'Commercial successfully updated!' ) ); $args = array( 'labels' => $labels, 'description' => __( 'Description for Commercials.' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'commercials' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'thumbnail' ), 'taxonomies' => array( 'commercial_category', 'post_tag' ) ); register_post_type( 'commercials', $args ); } ``` Category Codes: ``` add_action( 'init', 'create_commercial_category', 0 ); function create_commercial_category() { $labels = array( 'name' => __( 'Commercial Categories' ), 'singular_name' => __( 'Category' ), 'search_items' => __( 'Search Category' ), 'all_items' => __( 'All Categories' ), 'parent_item' => __( 'Parent Category' ), 'parent_item_colon' => __( 'Parent Category:' ), 'edit_item' => __( 'Edit Category' ), 'update_item' => __( 'Update Category' ), 'add_new_item' => __( 'Add New Category' ), 'new_item_name' => __( 'New Category Name' ), 'menu_name' => __( 'Commercial Category' ), ); $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'commercial-category' ) ); register_taxonomy( 'commercial_category', array( 'commercials' ), $args ); } ```
The way you are customizing the query you are telling it to search for posts that ALSO match a custom `tax_query` criteria. This would never work, logically speaking. You said, "I want it to return a result if this **tag** is searched or if it matches the **title**" for which I understand ONE or ANOTHER. I'll show you a completely different approach, using basically the following logic: 1. You said "This post type has a title and a video id" so I assume you are not going to use the field/column `post_excerpt` for the CPT `commercials`. You can add it to `supports`, but it is not required for this to work. 2. We can make use of the action `save_post` to force WordPress adding your post tags to the field `post_excerpt` of a Commercial. When you take a look at the code this will sound less confusing. 3. We know that WordPress by default searches the columns `post_title`, `post_excerpt` and `post_content` for a term when the query var `s` is present. So doing number 2 above would solve your issue, because WordPress would take care of the rest. Getting our hands dirty... we will still need to use the `pre_get_posts` action (yes, not a filter): ``` /** * @param WP_Query $query */ function searchCommercial( $query ) { if ( is_search() && ! is_admin() ) { if ( isset( $_GET['post_type'] ) ) { $type = $_GET['post_type']; if ( $type == 'commercials' ) { $query->set( 'post_type', array( 'commercials' ) ); } } } } add_action( 'pre_get_posts', 'searchCommercial' ); ``` And for saving the post tags within the `post_excerpt` of a **Commercial**: ``` /** * Fires once a post has been created or updated. * * @param int $post_id * @param WP_Post $post * @param bool $update Whether this is an existing post being updated or not. */ function add_post_tags_to_commercials( $post_id, $post, $update ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } if ( wp_is_post_revision( $post_id ) ) { return; } if ( $post->post_type != 'commercials' ) { return; } $post_tags = wp_get_object_terms( $post_id, 'post_tag' ); if ( $post_tags ) { $tags_with_comma = []; /** * @var WP_Term $tag */ foreach ( $post_tags as $tag ) { $tags_with_comma[] = $tag->name; $tags_with_comma[] = $tag->slug; } $tags_with_comma = implode( ',', $tags_with_comma ); // Unhook this function so it doesn't loop infinitely. remove_action( 'save_post', 'add_post_tags_to_commercials', 20 ); wp_update_post( array( 'ID' => $post_id, 'post_excerpt' => $tags_with_comma, // The tags will be saved within the `post_excerpt` column. ) ); // Re-hook this function. add_action( 'save_post', 'add_post_tags_to_commercials', 20, 3 ); } } add_action( 'save_post', 'add_post_tags_to_commercials', 20, 3 ); ``` The 2 snippets above can be placed within your **functions.php** file. **Notice:** * If you are using Guttenberg for your CPT `commercials`, you may have issues attaching post tags to it. Until now, WP version 5.2.1, is still having trouble attaching tags to a post using the AJAX process. * You have to save all of your **Commercials** again. I hope it's just a few. * Consider adding the string `excerpt` to your `commercials` `supports` as it would make it easier for you to see what's been added to the `post_excerpt` column: ``` 'supports' => array( 'title', 'thumbnail', `excerpt` ), ```
339,054
<p>I know here is an information about the issue, but I didn't find full working solution.</p> <p>I need to use product category slugs in my product permalinks so the links are to be like <code>example.com/laptops/some-laptop</code></p> <p>I selected the <em>Custom base</em> option in my <em>Permalink Settings</em>, typed <code>/%product-cat%/</code> in the field and saved. Next I added the following code to my theme's <code>functions.php</code></p> <pre><code>add_filter('post_type_link', 'category_slug_in_product_permalink', 10, 2); function category_slug_in_product_permalink($permalink, $post) { if($post-&gt;post_type == 'product') { $categories = wp_get_object_terms($post-&gt;ID, 'product_cat'); $permalink = str_replace('%product-cat%', $categories[0]-&gt;slug, $permalink); } return $permalink; } </code></pre> <p>The code works fine and I see the product permalinks are now exactly as needed.</p> <p>But when I click by any of the links, I receive the 400 Bad Request error. As I read by the link <a href="https://wordpress.stackexchange.com/a/334902">wordpress.stackexchange.com/a/334902</a> the <code>post_type_link</code> filter only changes urls, but <em>"it doesn’t change any rewrite rules and the structure of permalinks is still the same"</em>.</p> <p>So how can I resolve this second half of the issue?</p> <p>I found mentions of <code>$GLOBALS['wp_rewrite']</code>, <code>'slug' =&gt; '%...%', 'with_front' =&gt; false</code> and so on, but I didn't find full working solution or I just don't know how to use existing ones</p>
[ { "answer_id": 339115, "author": "stckvrw", "author_id": 144565, "author_profile": "https://wordpress.stackexchange.com/users/144565", "pm_score": 3, "selected": true, "text": "<p>Ok, so the second code is:</p>\n\n<pre><code>function custom_rewrite_basic() {\n\n $prodCatArgs = ['taxonomy' =&gt; 'product_cat'];\n $wooCats = get_categories($prodCatArgs);\n $catSlugs = [];\n foreach($wooCats as $wooCat) {\n $catSlugs[] = $wooCat-&gt;slug;\n }\n add_rewrite_rule(\n '^('.implode('|', $catSlugs).')/([^/]*)/?',\n 'index.php?post_type=product&amp;category=$matches[1]&amp;product=$matches[2]',\n 'top'\n );\n flush_rewrite_rules();\n}\nadd_action('init', 'custom_rewrite_basic');\n</code></pre>\n" }, { "answer_id": 341955, "author": "Maciej Bis", "author_id": 38240, "author_profile": "https://wordpress.stackexchange.com/users/38240", "pm_score": 0, "selected": false, "text": "<p>Alternatively you can use my plugin and adjust the product permalinks directly from Wordpress admin dashboard. </p>\n\n<ol>\n<li>Firstly, you need to install Permalink Manager Lite from Wordpress Plugin Directory.</li>\n<li>Then you need to go to \"<strong>Tools -> Permalink Manager -> Permastructures</strong>\" admin page and scroll down to \"Products\".</li>\n<li>Now, you should replace the default permalink format with: <em>%product_cat%/%product%</em></li>\n<li>The new permastructure settings will be applied to the new products only, but if you need to you can regenerate the old product permalinks in \"Tools -> Permalink Manager -> Tools -> Regenerate/Reset\" section.</li>\n</ol>\n\n<p>You can find the full instructions here:\n<a href=\"https://permalinkmanager.pro/docs/tutorials/taxonomy-slugs-in-custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">https://permalinkmanager.pro/docs/tutorials/taxonomy-slugs-in-custom-post-type-permalinks/</a></p>\n" } ]
2019/05/29
[ "https://wordpress.stackexchange.com/questions/339054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144565/" ]
I know here is an information about the issue, but I didn't find full working solution. I need to use product category slugs in my product permalinks so the links are to be like `example.com/laptops/some-laptop` I selected the *Custom base* option in my *Permalink Settings*, typed `/%product-cat%/` in the field and saved. Next I added the following code to my theme's `functions.php` ``` add_filter('post_type_link', 'category_slug_in_product_permalink', 10, 2); function category_slug_in_product_permalink($permalink, $post) { if($post->post_type == 'product') { $categories = wp_get_object_terms($post->ID, 'product_cat'); $permalink = str_replace('%product-cat%', $categories[0]->slug, $permalink); } return $permalink; } ``` The code works fine and I see the product permalinks are now exactly as needed. But when I click by any of the links, I receive the 400 Bad Request error. As I read by the link [wordpress.stackexchange.com/a/334902](https://wordpress.stackexchange.com/a/334902) the `post_type_link` filter only changes urls, but *"it doesn’t change any rewrite rules and the structure of permalinks is still the same"*. So how can I resolve this second half of the issue? I found mentions of `$GLOBALS['wp_rewrite']`, `'slug' => '%...%', 'with_front' => false` and so on, but I didn't find full working solution or I just don't know how to use existing ones
Ok, so the second code is: ``` function custom_rewrite_basic() { $prodCatArgs = ['taxonomy' => 'product_cat']; $wooCats = get_categories($prodCatArgs); $catSlugs = []; foreach($wooCats as $wooCat) { $catSlugs[] = $wooCat->slug; } add_rewrite_rule( '^('.implode('|', $catSlugs).')/([^/]*)/?', 'index.php?post_type=product&category=$matches[1]&product=$matches[2]', 'top' ); flush_rewrite_rules(); } add_action('init', 'custom_rewrite_basic'); ```
339,059
<p>I'm using a plugin where I have manipulated a function within a class of the plugin. However I would like to put this function in my theme instead since if someone updates the plugin, my edits to the function will be replaced. But if I lift out my edited function and put in the theme I get the error that "Fatal error: Cannot declare class Groups_Post_Access, because the name is already in use in ..."</p> <p>The function within class Groups_Post_Access originally looks like this:</p> <pre><code>public static function wp_get_nav_menu_items( $items = null, $menu = null, $args = null ) { $result = array(); if ( apply_filters( 'groups_post_access_wp_get_nav_menu_items_apply', true, $items, $menu, $args ) ) { $user_id = get_current_user_id(); foreach ( $items as $item ) { // @todo might want to check $item-&gt;object and $item-&gt;type first, // for example these are 'page' and 'post_type' for a page if ( self::user_can_read_post( $item-&gt;object_id, $user_id ) ) { $result[] = $item; } } } else { $result = $items; } return $result; } </code></pre> <p>And my version is like this:</p> <pre><code>public static function wp_get_nav_menu_items( $items = null, $menu = null, $args = null ) { $result = array(); if ( apply_filters( 'groups_post_access_wp_get_nav_menu_items_apply', true, $items, $menu, $args ) ) { $user_id = get_current_user_id(); foreach ( $items as $item ) { // @todo might want to check $item-&gt;object and $item-&gt;type first, // for example these are 'page' and 'post_type' for a page if ( self::user_can_read_post( $item-&gt;object_id, $user_id ) ) { $group_ids = self::get_read_group_ids( $item-&gt;object_id ); if ( count( $group_ids ) &gt; 0 ) { $item-&gt;title .= '&lt;i class="unlocked"&gt;&lt;/i&gt;'; } $result[] = $item; } else { $item-&gt;title .= '&lt;i class="locked"&gt;&lt;/i&gt;'; $result[] = $item; } } } else { $result = $items; } return $result; } </code></pre> <p>So is there a way to override the function, or disable the class somehow from my theme? So it keeps separate from all the plugins file and then don't get replaced by an update for an example.</p>
[ { "answer_id": 339115, "author": "stckvrw", "author_id": 144565, "author_profile": "https://wordpress.stackexchange.com/users/144565", "pm_score": 3, "selected": true, "text": "<p>Ok, so the second code is:</p>\n\n<pre><code>function custom_rewrite_basic() {\n\n $prodCatArgs = ['taxonomy' =&gt; 'product_cat'];\n $wooCats = get_categories($prodCatArgs);\n $catSlugs = [];\n foreach($wooCats as $wooCat) {\n $catSlugs[] = $wooCat-&gt;slug;\n }\n add_rewrite_rule(\n '^('.implode('|', $catSlugs).')/([^/]*)/?',\n 'index.php?post_type=product&amp;category=$matches[1]&amp;product=$matches[2]',\n 'top'\n );\n flush_rewrite_rules();\n}\nadd_action('init', 'custom_rewrite_basic');\n</code></pre>\n" }, { "answer_id": 341955, "author": "Maciej Bis", "author_id": 38240, "author_profile": "https://wordpress.stackexchange.com/users/38240", "pm_score": 0, "selected": false, "text": "<p>Alternatively you can use my plugin and adjust the product permalinks directly from Wordpress admin dashboard. </p>\n\n<ol>\n<li>Firstly, you need to install Permalink Manager Lite from Wordpress Plugin Directory.</li>\n<li>Then you need to go to \"<strong>Tools -> Permalink Manager -> Permastructures</strong>\" admin page and scroll down to \"Products\".</li>\n<li>Now, you should replace the default permalink format with: <em>%product_cat%/%product%</em></li>\n<li>The new permastructure settings will be applied to the new products only, but if you need to you can regenerate the old product permalinks in \"Tools -> Permalink Manager -> Tools -> Regenerate/Reset\" section.</li>\n</ol>\n\n<p>You can find the full instructions here:\n<a href=\"https://permalinkmanager.pro/docs/tutorials/taxonomy-slugs-in-custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">https://permalinkmanager.pro/docs/tutorials/taxonomy-slugs-in-custom-post-type-permalinks/</a></p>\n" } ]
2019/05/29
[ "https://wordpress.stackexchange.com/questions/339059", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11348/" ]
I'm using a plugin where I have manipulated a function within a class of the plugin. However I would like to put this function in my theme instead since if someone updates the plugin, my edits to the function will be replaced. But if I lift out my edited function and put in the theme I get the error that "Fatal error: Cannot declare class Groups\_Post\_Access, because the name is already in use in ..." The function within class Groups\_Post\_Access originally looks like this: ``` public static function wp_get_nav_menu_items( $items = null, $menu = null, $args = null ) { $result = array(); if ( apply_filters( 'groups_post_access_wp_get_nav_menu_items_apply', true, $items, $menu, $args ) ) { $user_id = get_current_user_id(); foreach ( $items as $item ) { // @todo might want to check $item->object and $item->type first, // for example these are 'page' and 'post_type' for a page if ( self::user_can_read_post( $item->object_id, $user_id ) ) { $result[] = $item; } } } else { $result = $items; } return $result; } ``` And my version is like this: ``` public static function wp_get_nav_menu_items( $items = null, $menu = null, $args = null ) { $result = array(); if ( apply_filters( 'groups_post_access_wp_get_nav_menu_items_apply', true, $items, $menu, $args ) ) { $user_id = get_current_user_id(); foreach ( $items as $item ) { // @todo might want to check $item->object and $item->type first, // for example these are 'page' and 'post_type' for a page if ( self::user_can_read_post( $item->object_id, $user_id ) ) { $group_ids = self::get_read_group_ids( $item->object_id ); if ( count( $group_ids ) > 0 ) { $item->title .= '<i class="unlocked"></i>'; } $result[] = $item; } else { $item->title .= '<i class="locked"></i>'; $result[] = $item; } } } else { $result = $items; } return $result; } ``` So is there a way to override the function, or disable the class somehow from my theme? So it keeps separate from all the plugins file and then don't get replaced by an update for an example.
Ok, so the second code is: ``` function custom_rewrite_basic() { $prodCatArgs = ['taxonomy' => 'product_cat']; $wooCats = get_categories($prodCatArgs); $catSlugs = []; foreach($wooCats as $wooCat) { $catSlugs[] = $wooCat->slug; } add_rewrite_rule( '^('.implode('|', $catSlugs).')/([^/]*)/?', 'index.php?post_type=product&category=$matches[1]&product=$matches[2]', 'top' ); flush_rewrite_rules(); } add_action('init', 'custom_rewrite_basic'); ```
339,067
<p>Trying to add certain allowed MIME types to the upload filter - currently my custom function looks like this:</p> <pre><code>// allow SVG and video mime types for upload function cc_mime_types( $mimes ){ $mimes['svg'] = 'image/svg+xml'; $mimes['webm'] = 'video/webm'; $mimes['mp4'] = ['video/mp4','video/mpeg']; $mimes['ogg'] = 'video/ogg'; $mimes['ogv'] = 'video/ogg'; return $mimes; } add_filter( 'upload_mimes', 'cc_mime_types' ); </code></pre> <p>Uploading videos with ogg/ogv format seems to work well, but MP4 is failing. It seems like an array of different MIME types is not the solution. How should I add this?</p>
[ { "answer_id": 339090, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 2, "selected": false, "text": "<p>This filter only accepts strings for mime types. It also <a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/functions.php#L2707\" rel=\"nofollow noreferrer\">already has support for webm, mp4, mpeg, ogv, and ogg</a>. </p>\n\n<p>I think you can remove everything except the line for SVGs. </p>\n\n<p>A word of warning, WordPress doesn't support SVG upload by default because it's a security concern. Be careful about enabling this. At the least, use something like the <a href=\"https://wordpress.org/plugins/safe-svg/\" rel=\"nofollow noreferrer\">Safe SVG plugin</a> to help mitigate the risk. </p>\n" }, { "answer_id": 339092, "author": "Blackbam", "author_id": 12035, "author_profile": "https://wordpress.stackexchange.com/users/12035", "pm_score": 2, "selected": true, "text": "<p>@MikeNGarret's answer pointed me to the interesting function <code>wp_get_mime_types()</code>. Within this function you can look up how to correctly add MIME types to the <code>upload_mimes</code> filter (<a href=\"https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/functions.php#L2707\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/functions.php#L2707</a>). </p>\n\n<p>The correct answer therefore is:</p>\n\n<pre><code>// allow SVG and video mime types for upload\nfunction cc_mime_types( $mimes ){\n $mimes['svg'] = 'image/svg+xml';\n $mimes['webm'] = 'video/webm';\n $mimes['mp4|m4v'] = 'video/mp4';\n $mimes['mpeg|mpg|mpe'] = 'video/mpeg';\n $mimes['ogv'] = 'video/ogg';\n return $mimes;\n}\nadd_filter( 'upload_mimes', 'cc_mime_types' );\n</code></pre>\n\n<p>For registering an unknown MIME type you should therefore use the <code>mime_types</code> filter, for the upload (independently) you have to add it to the list of allowed upload mimes.</p>\n" } ]
2019/05/29
[ "https://wordpress.stackexchange.com/questions/339067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
Trying to add certain allowed MIME types to the upload filter - currently my custom function looks like this: ``` // allow SVG and video mime types for upload function cc_mime_types( $mimes ){ $mimes['svg'] = 'image/svg+xml'; $mimes['webm'] = 'video/webm'; $mimes['mp4'] = ['video/mp4','video/mpeg']; $mimes['ogg'] = 'video/ogg'; $mimes['ogv'] = 'video/ogg'; return $mimes; } add_filter( 'upload_mimes', 'cc_mime_types' ); ``` Uploading videos with ogg/ogv format seems to work well, but MP4 is failing. It seems like an array of different MIME types is not the solution. How should I add this?
@MikeNGarret's answer pointed me to the interesting function `wp_get_mime_types()`. Within this function you can look up how to correctly add MIME types to the `upload_mimes` filter (<https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/functions.php#L2707>). The correct answer therefore is: ``` // allow SVG and video mime types for upload function cc_mime_types( $mimes ){ $mimes['svg'] = 'image/svg+xml'; $mimes['webm'] = 'video/webm'; $mimes['mp4|m4v'] = 'video/mp4'; $mimes['mpeg|mpg|mpe'] = 'video/mpeg'; $mimes['ogv'] = 'video/ogg'; return $mimes; } add_filter( 'upload_mimes', 'cc_mime_types' ); ``` For registering an unknown MIME type you should therefore use the `mime_types` filter, for the upload (independently) you have to add it to the list of allowed upload mimes.
339,082
<p>I'm adding a button to Gutenbergs RichTextToolbar with a plugin I created, but I cannot figure out how to add mulitple classes to the tag/span I create.</p> <pre><code>( function( wp ) { var MyCustomButton = function( props ) { return wp.element.createElement( wp.editor.RichTextToolbarButton, { icon: 'editor-code', title: 'Sample output', onClick: function() { props.onChange( wp.richText.toggleFormat( props.value, { type: 'my-custom-format/sample-output' } ) ); }, isActive: props.isActive, } ); } wp.richText.registerFormatType( 'my-custom-format/sample-output', { title: 'Sample output', tagName: 'span', className: 'classname another-classname', //this line needs the help - works as just 'classname' no spaces but can only wrap with one class then edit: MyCustomButton, } ); } )( window.wp ); </code></pre> <p>Console error says: </p> <blockquote> <p>A class name must begin with a letter, followed by any number of hyphens, letters, or numbers.</p> </blockquote> <p>So the space is creating the error, but how do I add 2 classes to this function? I've also tried the following which doesn't work.</p> <pre><code>className: {'has-primary-color has-text-color'}, </code></pre>
[ { "answer_id": 359704, "author": "Evgeniy Z.", "author_id": 173367, "author_profile": "https://wordpress.stackexchange.com/users/173367", "pm_score": 1, "selected": false, "text": "<p>As we can see from the registerFormatType function <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/rich-text/src/register-format-type.js\" rel=\"nofollow noreferrer\">source code</a>, only letters, numbers, \"_\" and \"-\" are allowed in the class name.</p>\n\n<pre><code>if ( ! /^[_a-zA-Z]+[a-zA-Z0-9-]*$/.test( settings.className ) ) {\n window.console.error(\n 'A class name must begin with a letter, followed by any number of \n hyphens, letters, or numbers.'\n );\n return;\n}\n</code></pre>\n\n<p>So you cannot separate two class names with a space.</p>\n" }, { "answer_id": 402778, "author": "Simon", "author_id": 91765, "author_profile": "https://wordpress.stackexchange.com/users/91765", "pm_score": 0, "selected": false, "text": "<p>You can add extra classes in the options section of toggleFormat. The className specified in the registerFormatType is used to distinguish between different formats so needs to be one class.</p>\n<p>In your example:</p>\n<pre><code>( function( wp ) {\n var MyCustomButton = function( props ) {\n return wp.element.createElement(\n wp.editor.RichTextToolbarButton, {\n icon: 'editor-code',\n title: 'Sample output',\n onClick: function() {\n props.onChange( wp.richText.toggleFormat(\n props.value,\n {\n type: 'my-custom-format/sample-output',\n attributes: {\n class: 'another-classname'\n }\n }\n ) );\n },\n isActive: props.isActive,\n }\n );\n }\n wp.richText.registerFormatType(\n 'my-custom-format/sample-output', {\n title: 'Sample output',\n tagName: 'span',\n className: 'classname', \n edit: MyCustomButton,\n }\n );\n} )( window.wp );\n</code></pre>\n" } ]
2019/05/29
[ "https://wordpress.stackexchange.com/questions/339082", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155008/" ]
I'm adding a button to Gutenbergs RichTextToolbar with a plugin I created, but I cannot figure out how to add mulitple classes to the tag/span I create. ``` ( function( wp ) { var MyCustomButton = function( props ) { return wp.element.createElement( wp.editor.RichTextToolbarButton, { icon: 'editor-code', title: 'Sample output', onClick: function() { props.onChange( wp.richText.toggleFormat( props.value, { type: 'my-custom-format/sample-output' } ) ); }, isActive: props.isActive, } ); } wp.richText.registerFormatType( 'my-custom-format/sample-output', { title: 'Sample output', tagName: 'span', className: 'classname another-classname', //this line needs the help - works as just 'classname' no spaces but can only wrap with one class then edit: MyCustomButton, } ); } )( window.wp ); ``` Console error says: > > A class name must begin with a letter, followed by any number of > hyphens, letters, or numbers. > > > So the space is creating the error, but how do I add 2 classes to this function? I've also tried the following which doesn't work. ``` className: {'has-primary-color has-text-color'}, ```
As we can see from the registerFormatType function [source code](https://github.com/WordPress/gutenberg/blob/master/packages/rich-text/src/register-format-type.js), only letters, numbers, "\_" and "-" are allowed in the class name. ``` if ( ! /^[_a-zA-Z]+[a-zA-Z0-9-]*$/.test( settings.className ) ) { window.console.error( 'A class name must begin with a letter, followed by any number of hyphens, letters, or numbers.' ); return; } ``` So you cannot separate two class names with a space.
339,134
<p>How to detect the value of selected page template in the edit page? I have used jQuery to select the page attribute select box but it is not working when we hide the editor sidebar; Because it removes the markup of that settings. I think it keeps data somewhere as we are able to bring back the sidebar without any change.</p> <p>My code: <code>$('.editor-page-attributes__template select').val()</code></p> <p>Is there any way to get the value when the sidebar is closed? Like any JavaScript variable in the page that updates when we change page template.</p> <p>Note: I mean getting the value and use it in JavaScript without refreshing or updating the editor.</p>
[ { "answer_id": 343332, "author": "SkyShab", "author_id": 63263, "author_profile": "https://wordpress.stackexchange.com/users/63263", "pm_score": 2, "selected": false, "text": "<p>To get this value, use the wp.data module. </p>\n\n<pre><code>const template = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'template' );\n</code></pre>\n\n<p>Since this can be changed in the document settings, you would likely need to \"subscribe\" and run a callback whenever this changes. </p>\n\n<p>For example:</p>\n\n<pre><code>const { select, subscribe } = wp.data;\n\nclass PageTemplateSwitcher {\n\n constructor() {\n this.template = null;\n }\n\n init() {\n\n subscribe( () =&gt; {\n\n const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' );\n\n if ( newTemplate &amp;&amp; newTemplate !== this.template ) {\n this.template = newTemplate;\n this.changeTemplate();\n }\n\n });\n }\n\n changeTemplate() {\n // do your stuff here\n console.log(`template changed to ${this.template}`);\n }\n}\n\nnew PageTemplateSwitcher().init();\n</code></pre>\n" }, { "answer_id": 373473, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 3, "selected": true, "text": "<p>I slightly modified SkyShab's code, because it fired template change event on page load and it didn't fire when template was changed to default (since getEditedPostAttribute( 'template' ) is then '', which equals to null when testing for template change)</p>\n<pre><code>const { select, subscribe } = wp.data;\n\nclass PageTemplateSwitcher {\n\n constructor() {\n this.template = null;\n }\n\n init() {\n\n subscribe( () =&gt; {\n\n const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' );\n if (newTemplate !== undefined &amp;&amp; this.template === null) {\n this.template = newTemplate;\n }\n\n if ( newTemplate !== undefined &amp;&amp; newTemplate !== this.template ) {\n this.template = newTemplate;\n this.changeTemplate();\n }\n\n });\n }\n\n changeTemplate() {\n // do your stuff here\n console.log('template changed to ${this.template}');\n }\n}\n\nnew PageTemplateSwitcher().init();\n</code></pre>\n" } ]
2019/05/30
[ "https://wordpress.stackexchange.com/questions/339134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48376/" ]
How to detect the value of selected page template in the edit page? I have used jQuery to select the page attribute select box but it is not working when we hide the editor sidebar; Because it removes the markup of that settings. I think it keeps data somewhere as we are able to bring back the sidebar without any change. My code: `$('.editor-page-attributes__template select').val()` Is there any way to get the value when the sidebar is closed? Like any JavaScript variable in the page that updates when we change page template. Note: I mean getting the value and use it in JavaScript without refreshing or updating the editor.
I slightly modified SkyShab's code, because it fired template change event on page load and it didn't fire when template was changed to default (since getEditedPostAttribute( 'template' ) is then '', which equals to null when testing for template change) ``` const { select, subscribe } = wp.data; class PageTemplateSwitcher { constructor() { this.template = null; } init() { subscribe( () => { const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' ); if (newTemplate !== undefined && this.template === null) { this.template = newTemplate; } if ( newTemplate !== undefined && newTemplate !== this.template ) { this.template = newTemplate; this.changeTemplate(); } }); } changeTemplate() { // do your stuff here console.log('template changed to ${this.template}'); } } new PageTemplateSwitcher().init(); ```
339,138
<p>The introduction of the <strong>Block Editor</strong> killed all plugins which offered publishing conditions, such as minimum word counts, featured image requirements etc.</p> <p>But the Block Editor <em>did</em> introduce the <strong>pre-publish checks</strong>:</p> <p><a href="https://i.stack.imgur.com/zwGUd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zwGUd.png" alt="Pre-publish checks"></a></p> <p>Beautiful. How can we disable the <code>Publish</code> button until a set amount of conditions have been fulfilled?</p> <p>Examples of four (very) different conditions:</p> <ol> <li>Minimum word count (example: <code>500</code> words)</li> <li>Min/max tags (example: <code>3-5</code> tags)</li> <li>Min category (that isn't <code>uncategorized</code>)</li> <li>Featured image is assigned</li> </ol> <h2>What we have so far</h2> <p>As expected, the documentation is non-existent. But leads are scattered across the web. </p> <p>In <code>core/editor</code>, we can use <a href="https://developer.wordpress.org/block-editor/data/data-core-editor/#lockPostSaving" rel="noreferrer">.lockPostSaving()</a> to disabled the <code>Publish</code> button, and unlock it via <code>.unlockPostSaving()</code>.</p> <p>We can add a panel to the pre-publish screen via <code>PluginPrePublishPanel</code>. Example (by <a href="https://wordpress.stackexchange.com/a/334671/24875">MadMaardigan</a>):</p> <pre><code>var PluginPrePublishPanel = wp.editPost.PluginPrePublishPanel; var registerPlugin = wp.plugins.registerPlugin; function Component() { // lock post saving wp.data.dispatch('core/editor').lockPostSaving() // unlock post saving // wp.data.dispatch('core/editor').unlockPostSaving() return wp.element.createElement( PluginPrePublishPanel, { className: 'my-plugin-publish-panel', title: 'Panel title', initialOpen: true, }, 'Panel content' ); } registerPlugin( 'my-plugin', { render: Component, }); </code></pre> <p>It works:</p> <p><a href="https://i.stack.imgur.com/SuFJ5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SuFJ5.png" alt="Custom pre-publish panel"></a></p> <p>And we have great discussions on GitHub: <a href="https://github.com/WordPress/gutenberg/issues/7020" rel="noreferrer">#7020</a>, <a href="https://github.com/WordPress/gutenberg/issues/7426" rel="noreferrer">#7426</a>, <a href="https://github.com/WordPress/gutenberg/issues/13413" rel="noreferrer">#13413</a>, <a href="https://github.com/WordPress/gutenberg/issues/15568" rel="noreferrer">#15568</a>, <a href="https://github.com/WordPress/gutenberg/issues/10649" rel="noreferrer">#10649</a>...</p>
[ { "answer_id": 339662, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 5, "selected": true, "text": "<p><strong>EDIT Sept 2021:</strong></p>\n<p>An updated version of the answer that uses hooks.</p>\n<p>This version tracks changes in the editor much better. It also uses <code>import</code> statement instead of importing directly from the <code>wp</code> global. This approach when used with the <code>@wordpress/scripts</code> package will correctly add dependencies for this file when being enqueued. Accessing the <code>wp</code> global will still work but you will have to be sure you're managing your script dependencies manually.</p>\n<p>Thanks to everyone in the comments!</p>\n<pre><code>import { useState, useEffect } from '@wordpress/element';\nimport { registerPlugin } from '@wordpress/plugins';\nimport { PluginPrePublishPanel } from '@wordpress/edit-post';\nimport { useSelect, useDispatch } from '@wordpress/data';\nimport { count } from '@wordpress/wordcount';\nimport { serialize } from '@wordpress/blocks';\n\nconst PrePublishCheckList = () =&gt; {\n // Manage the messaging in state.\n const [wordCountMessage, setWordCountMessage] = useState('');\n const [catsMessage, setCatsMessage] = useState('');\n const [tagsMessage, setTagsMessage] = useState('');\n const [featuredImageMessage, setFeaturedImageMessage] = useState('');\n\n // The useSelect hook is better for retrieving data from the store.\n const { blocks, cats, tags, featuredImageID } = useSelect((select) =&gt; {\n return {\n blocks: select('core/block-editor').getBlocks(),\n cats: select('core/editor').getEditedPostAttribute('categories'),\n tags: select('core/editor').getEditedPostAttribute('tags'),\n featuredImageID:\n select('core/editor').getEditedPostAttribute('featured_media'),\n };\n });\n\n // The useDispatch hook is better for dispatching actions.\n const { lockPostSaving, unlockPostSaving } = useDispatch('core/editor');\n\n // Put all the logic in the useEffect hook.\n useEffect(() =&gt; {\n let lockPost = false;\n // Get the WordCount\n const wordCount = count(serialize(blocks), 'words');\n if (wordCount &lt; 500) {\n lockPost = true;\n setWordCountMessage(`${wordCount} - Minimum of 500 required.`);\n } else {\n setWordCountMessage(`${wordCount}`);\n }\n\n // Get the category count\n if (!cats.length || (cats.length === 1 &amp;&amp; cats[0] === 1)) {\n lockPost = true;\n setCatsMessage('Missing');\n // Check that the cat is not Uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs.\n if (cats.length === 1 &amp;&amp; cats[0] === 1) {\n setCatsMessage('Cannot use Uncategorized');\n }\n } else {\n setCatsMessage('Set');\n }\n\n // Get the tags\n if (tags.length &lt; 3 || tags.length &gt; 5) {\n lockPost = true;\n setTagsMessage('Required 3 - 5 tags');\n } else {\n setTagsMessage('Set');\n }\n // Get the featured image\n if (featuredImageID === 0) {\n lockPost = true;\n setFeaturedImageMessage('Not Set');\n } else {\n setFeaturedImageMessage(' Set');\n }\n\n if (lockPost === true) {\n lockPostSaving();\n } else {\n unlockPostSaving();\n }\n }, [blocks, cats, tags, featuredImageID]);\n\n return (\n &lt;PluginPrePublishPanel title={'Publish Checklist'}&gt;\n &lt;p&gt;\n &lt;b&gt;Word Count:&lt;/b&gt; {wordCountMessage}\n &lt;/p&gt;\n &lt;p&gt;\n &lt;b&gt;Categories:&lt;/b&gt; {catsMessage}\n &lt;/p&gt;\n &lt;p&gt;\n &lt;b&gt;Tags:&lt;/b&gt; {tagsMessage}\n &lt;/p&gt;\n &lt;p&gt;\n &lt;b&gt;Featured Image:&lt;/b&gt; {featuredImageMessage}\n &lt;/p&gt;\n &lt;/PluginPrePublishPanel&gt;\n );\n};\n\nregisterPlugin('pre-publish-checklist', { render: PrePublishCheckList });\n</code></pre>\n<p><strong>Old Version</strong>:</p>\n<pre><code>const { registerPlugin } = wp.plugins;\nconst { PluginPrePublishPanel } = wp.editPost;\nconst { select, dispatch } = wp.data;\nconst { count } = wp.wordcount;\nconst { serialize } = wp.blocks;\nconst { PanelBody } = wp.components;\n\nconst PrePublishCheckList = () =&gt; {\n let lockPost = false;\n\n // Get the WordCount\n const blocks = select( 'core/block-editor' ).getBlocks();\n const wordCount = count( serialize( blocks ), 'words' );\n let wordCountMessage = `${wordCount}`;\n if ( wordCount &lt; 500 ) {\n lockPost = true;\n wordCountMessage += ` - Minimum of 500 required.`;\n }\n\n // Get the cats\n const cats = select( 'core/editor' ).getEditedPostAttribute( 'categories' );\n let catsMessage = 'Set';\n if ( ! cats.length ) {\n lockPost = true;\n catsMessage = 'Missing';\n } else {\n // Check that the cat is not uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs.\n if ( cats.length === 1 &amp;&amp; cats[0] === 1 ) {\n lockPost = true;\n catsMessage = 'Cannot use Uncategorized';\n }\n }\n\n // Get the tags\n const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' );\n let tagsMessage = 'Set';\n if ( tags.length &lt; 3 || tags.length &gt; 5 ) {\n lockPost = true;\n tagsMessage = 'Required 3 - 5 tags';\n }\n\n // Get the featured image\n const featuredImageID = select( 'core/editor' ).getEditedPostAttribute( 'featured_media' );\n let featuredImage = 'Set';\n\n if ( featuredImageID === 0 ) {\n lockPost = true;\n featuredImage = 'Not Set';\n }\n\n // Do we need to lock the post?\n if ( lockPost === true ) {\n dispatch( 'core/editor' ).lockPostSaving();\n } else {\n dispatch( 'core/editor' ).unlockPostSaving();\n }\n return (\n &lt;PluginPrePublishPanel title={ 'Publish Checklist' }&gt;\n &lt;p&gt;&lt;b&gt;Word Count:&lt;/b&gt; { wordCountMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Categories:&lt;/b&gt; { catsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Tags:&lt;/b&gt; { tagsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Featured Image:&lt;/b&gt; { featuredImage }&lt;/p&gt;\n &lt;/PluginPrePublishPanel&gt;\n )\n};\n\nregisterPlugin( 'pre-publish-checklist', { render: PrePublishCheckList } );\n</code></pre>\n<p>Display:</p>\n<p><a href=\"https://i.stack.imgur.com/tQFVh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tQFVh.png\" alt=\"enter image description here\" /></a></p>\n<p>The solution above addresses the requirements listed in the question. One thing that can be expanded on is the category checking, I am making some assumptions about the category ID.</p>\n<p>I have kept all of the checks in the same component for the sake of brevity and readability here. I would recommend moving each portion into a separate component and potentially making them Higher Order Components ( i.e withWordCount ).</p>\n<p>I have inline comments that explain what is being done but am happy to explain further if there are any questions.</p>\n<p>EDIT: Here's how I'm enqueuing the script</p>\n<pre><code>function enqueue_block_editor_assets() {\n wp_enqueue_script(\n 'my-custom-script', // Handle.\n plugin_dir_url( __FILE__ ) . '/build/index.js',\n array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-edit-post', 'word-count' ) // Dependencies, defined above.\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'enqueue_block_editor_assets' );\n</code></pre>\n<p>Adding some more details about the build process. I am using <a href=\"https://www.npmjs.com/package/@wordpress/scripts\" rel=\"nofollow noreferrer\">@wordpress/scripts</a> and running the following scripts:</p>\n<pre><code>&quot;scripts&quot;: {\n &quot;build&quot;: &quot;wp-scripts build&quot;,\n &quot;start&quot;: &quot;wp-scripts start&quot;\n },\n</code></pre>\n<p>Edit 2:</p>\n<p>You can get the attachment data via:</p>\n<pre><code>wp.data.select('core').getMedia( ID )\n</code></pre>\n" }, { "answer_id": 359780, "author": "BenB", "author_id": 62909, "author_profile": "https://wordpress.stackexchange.com/users/62909", "pm_score": 3, "selected": false, "text": "<p><strong>Update 29.02.2020</strong></p>\n<p>You have to replace <code>select( 'core/editor' ).getBlocks()</code> with <code>select( 'core/block-editor' ).getBlocks()</code> in order for this to work</p>\n<p>This worked for me:</p>\n<p><code>path\\to\\theme\\pre-publish-checklist\\src\\index.js</code></p>\n<pre class=\"lang-js prettyprint-override\"><code>const { registerPlugin } = wp.plugins;\nconst { PluginPrePublishPanel } = wp.editPost;\nconst { select, dispatch } = wp.data;\nconst { count } = wp.wordcount;\nconst { serialize } = wp.blocks;\nconst { PanelBody } = wp.components;\n\nconst PrePublishCheckList = () =&gt; {\n let lockPost = false;\n\n // Get the WordCount\n const blocks = select( 'core/block-editor' ).getBlocks();\n const wordCount = count( serialize( blocks ), 'words' );\n let wordCountMessage = `${wordCount}`;\n if ( wordCount &lt; 500 ) {\n lockPost = true;\n wordCountMessage += ` - Minimum of 500 required.`;\n }\n\n // Get the cats\n const cats = select( 'core/editor' ).getEditedPostAttribute( 'categories' );\n let catsMessage = 'Set';\n if ( ! cats.length ) {\n lockPost = true;\n catsMessage = 'Missing';\n } else {\n // Check that the cat is not uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs.\n if ( cats.length === 1 &amp;&amp; cats[0] === 1 ) {\n lockPost = true;\n catsMessage = 'Cannot use Uncategorized';\n }\n }\n\n // Get the tags\n const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' );\n let tagsMessage = 'Set';\n if ( tags.length &lt; 3 || tags.length &gt; 5 ) {\n lockPost = true;\n tagsMessage = 'Required 3 - 5 tags';\n }\n\n // Get the featured image\n const featuredImageID = select( 'core/editor' ).getEditedPostAttribute( 'featured_media' );\n let featuredImage = 'Set';\n\n if ( featuredImageID === 0 ) {\n lockPost = true;\n featuredImage = 'Not Set';\n }\n\n // Do we need to lock the post?\n if ( lockPost === true ) {\n dispatch( 'core/editor' ).lockPostSaving();\n } else {\n dispatch( 'core/editor' ).unlockPostSaving();\n }\n return (\n &lt;PluginPrePublishPanel title={ 'Publish Checklist' }&gt;\n &lt;p&gt;&lt;b&gt;Word Count:&lt;/b&gt; { wordCountMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Categories:&lt;/b&gt; { catsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Tags:&lt;/b&gt; { tagsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Featured Image:&lt;/b&gt; { featuredImage }&lt;/p&gt;\n &lt;/PluginPrePublishPanel&gt;\n )\n};\n\nregisterPlugin( 'pre-publish-checklist', { render: PrePublishCheckList } );\n</code></pre>\n<p>Full steps to create the panel with @wordpress/scripts</p>\n<ol>\n<li>Create a folder <code>pre-publish-checklist</code> in your theme</li>\n<li>Create inside the folder package.json file with</li>\n</ol>\n<pre class=\"lang-json prettyprint-override\"><code>{\n &quot;scripts&quot;: {\n &quot;build&quot;: &quot;wp-scripts build&quot;,\n &quot;check-engines&quot;: &quot;wp-scripts check-engines&quot;,\n &quot;check-licenses&quot;: &quot;wp-scripts check-licenses&quot;,\n &quot;format:js&quot;: &quot;wp-scripts format-js&quot;,\n &quot;lint:css&quot;: &quot;wp-scripts lint-style&quot;,\n &quot;lint:js&quot;: &quot;wp-scripts lint-js&quot;,\n &quot;lint:md:docs&quot;: &quot;wp-scripts lint-md-docs&quot;,\n &quot;lint:md:js&quot;: &quot;wp-scripts lint-md-js&quot;,\n &quot;lint:pkg-json&quot;: &quot;wp-scripts lint-pkg-json&quot;,\n &quot;packages-update&quot;: &quot;wp-scripts packages-update&quot;,\n &quot;start&quot;: &quot;wp-scripts start&quot;,\n &quot;test:e2e&quot;: &quot;wp-scripts test-e2e&quot;,\n &quot;test:unit&quot;: &quot;wp-scripts test-unit-js&quot;\n },\n &quot;dependencies&quot;: {\n &quot;@wordpress/scripts&quot;: &quot;^7.1.2&quot;\n }\n}\n</code></pre>\n<ol start=\"3\">\n<li>Create a file in the folder with the path 'src/index.js' and place the code in the file</li>\n<li><code>yarn</code></li>\n<li><code>yarn build</code></li>\n<li>Add this code to functions.php to enqueue the file</li>\n</ol>\n<pre><code>function enqueue_block_editor_assets() {\n wp_enqueue_script(\n 'pre-publish-checklist', // Handle.\n get_template_directory_uri(). '/pre-publish-checklist/build/index.js',\n array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-edit-post', 'word-count' ) // Dependencies, defined above.\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'enqueue_block_editor_assets' );\n</code></pre>\n" } ]
2019/05/30
[ "https://wordpress.stackexchange.com/questions/339138", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24875/" ]
The introduction of the **Block Editor** killed all plugins which offered publishing conditions, such as minimum word counts, featured image requirements etc. But the Block Editor *did* introduce the **pre-publish checks**: [![Pre-publish checks](https://i.stack.imgur.com/zwGUd.png)](https://i.stack.imgur.com/zwGUd.png) Beautiful. How can we disable the `Publish` button until a set amount of conditions have been fulfilled? Examples of four (very) different conditions: 1. Minimum word count (example: `500` words) 2. Min/max tags (example: `3-5` tags) 3. Min category (that isn't `uncategorized`) 4. Featured image is assigned What we have so far ------------------- As expected, the documentation is non-existent. But leads are scattered across the web. In `core/editor`, we can use [.lockPostSaving()](https://developer.wordpress.org/block-editor/data/data-core-editor/#lockPostSaving) to disabled the `Publish` button, and unlock it via `.unlockPostSaving()`. We can add a panel to the pre-publish screen via `PluginPrePublishPanel`. Example (by [MadMaardigan](https://wordpress.stackexchange.com/a/334671/24875)): ``` var PluginPrePublishPanel = wp.editPost.PluginPrePublishPanel; var registerPlugin = wp.plugins.registerPlugin; function Component() { // lock post saving wp.data.dispatch('core/editor').lockPostSaving() // unlock post saving // wp.data.dispatch('core/editor').unlockPostSaving() return wp.element.createElement( PluginPrePublishPanel, { className: 'my-plugin-publish-panel', title: 'Panel title', initialOpen: true, }, 'Panel content' ); } registerPlugin( 'my-plugin', { render: Component, }); ``` It works: [![Custom pre-publish panel](https://i.stack.imgur.com/SuFJ5.png)](https://i.stack.imgur.com/SuFJ5.png) And we have great discussions on GitHub: [#7020](https://github.com/WordPress/gutenberg/issues/7020), [#7426](https://github.com/WordPress/gutenberg/issues/7426), [#13413](https://github.com/WordPress/gutenberg/issues/13413), [#15568](https://github.com/WordPress/gutenberg/issues/15568), [#10649](https://github.com/WordPress/gutenberg/issues/10649)...
**EDIT Sept 2021:** An updated version of the answer that uses hooks. This version tracks changes in the editor much better. It also uses `import` statement instead of importing directly from the `wp` global. This approach when used with the `@wordpress/scripts` package will correctly add dependencies for this file when being enqueued. Accessing the `wp` global will still work but you will have to be sure you're managing your script dependencies manually. Thanks to everyone in the comments! ``` import { useState, useEffect } from '@wordpress/element'; import { registerPlugin } from '@wordpress/plugins'; import { PluginPrePublishPanel } from '@wordpress/edit-post'; import { useSelect, useDispatch } from '@wordpress/data'; import { count } from '@wordpress/wordcount'; import { serialize } from '@wordpress/blocks'; const PrePublishCheckList = () => { // Manage the messaging in state. const [wordCountMessage, setWordCountMessage] = useState(''); const [catsMessage, setCatsMessage] = useState(''); const [tagsMessage, setTagsMessage] = useState(''); const [featuredImageMessage, setFeaturedImageMessage] = useState(''); // The useSelect hook is better for retrieving data from the store. const { blocks, cats, tags, featuredImageID } = useSelect((select) => { return { blocks: select('core/block-editor').getBlocks(), cats: select('core/editor').getEditedPostAttribute('categories'), tags: select('core/editor').getEditedPostAttribute('tags'), featuredImageID: select('core/editor').getEditedPostAttribute('featured_media'), }; }); // The useDispatch hook is better for dispatching actions. const { lockPostSaving, unlockPostSaving } = useDispatch('core/editor'); // Put all the logic in the useEffect hook. useEffect(() => { let lockPost = false; // Get the WordCount const wordCount = count(serialize(blocks), 'words'); if (wordCount < 500) { lockPost = true; setWordCountMessage(`${wordCount} - Minimum of 500 required.`); } else { setWordCountMessage(`${wordCount}`); } // Get the category count if (!cats.length || (cats.length === 1 && cats[0] === 1)) { lockPost = true; setCatsMessage('Missing'); // Check that the cat is not Uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs. if (cats.length === 1 && cats[0] === 1) { setCatsMessage('Cannot use Uncategorized'); } } else { setCatsMessage('Set'); } // Get the tags if (tags.length < 3 || tags.length > 5) { lockPost = true; setTagsMessage('Required 3 - 5 tags'); } else { setTagsMessage('Set'); } // Get the featured image if (featuredImageID === 0) { lockPost = true; setFeaturedImageMessage('Not Set'); } else { setFeaturedImageMessage(' Set'); } if (lockPost === true) { lockPostSaving(); } else { unlockPostSaving(); } }, [blocks, cats, tags, featuredImageID]); return ( <PluginPrePublishPanel title={'Publish Checklist'}> <p> <b>Word Count:</b> {wordCountMessage} </p> <p> <b>Categories:</b> {catsMessage} </p> <p> <b>Tags:</b> {tagsMessage} </p> <p> <b>Featured Image:</b> {featuredImageMessage} </p> </PluginPrePublishPanel> ); }; registerPlugin('pre-publish-checklist', { render: PrePublishCheckList }); ``` **Old Version**: ``` const { registerPlugin } = wp.plugins; const { PluginPrePublishPanel } = wp.editPost; const { select, dispatch } = wp.data; const { count } = wp.wordcount; const { serialize } = wp.blocks; const { PanelBody } = wp.components; const PrePublishCheckList = () => { let lockPost = false; // Get the WordCount const blocks = select( 'core/block-editor' ).getBlocks(); const wordCount = count( serialize( blocks ), 'words' ); let wordCountMessage = `${wordCount}`; if ( wordCount < 500 ) { lockPost = true; wordCountMessage += ` - Minimum of 500 required.`; } // Get the cats const cats = select( 'core/editor' ).getEditedPostAttribute( 'categories' ); let catsMessage = 'Set'; if ( ! cats.length ) { lockPost = true; catsMessage = 'Missing'; } else { // Check that the cat is not uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs. if ( cats.length === 1 && cats[0] === 1 ) { lockPost = true; catsMessage = 'Cannot use Uncategorized'; } } // Get the tags const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' ); let tagsMessage = 'Set'; if ( tags.length < 3 || tags.length > 5 ) { lockPost = true; tagsMessage = 'Required 3 - 5 tags'; } // Get the featured image const featuredImageID = select( 'core/editor' ).getEditedPostAttribute( 'featured_media' ); let featuredImage = 'Set'; if ( featuredImageID === 0 ) { lockPost = true; featuredImage = 'Not Set'; } // Do we need to lock the post? if ( lockPost === true ) { dispatch( 'core/editor' ).lockPostSaving(); } else { dispatch( 'core/editor' ).unlockPostSaving(); } return ( <PluginPrePublishPanel title={ 'Publish Checklist' }> <p><b>Word Count:</b> { wordCountMessage }</p> <p><b>Categories:</b> { catsMessage }</p> <p><b>Tags:</b> { tagsMessage }</p> <p><b>Featured Image:</b> { featuredImage }</p> </PluginPrePublishPanel> ) }; registerPlugin( 'pre-publish-checklist', { render: PrePublishCheckList } ); ``` Display: [![enter image description here](https://i.stack.imgur.com/tQFVh.png)](https://i.stack.imgur.com/tQFVh.png) The solution above addresses the requirements listed in the question. One thing that can be expanded on is the category checking, I am making some assumptions about the category ID. I have kept all of the checks in the same component for the sake of brevity and readability here. I would recommend moving each portion into a separate component and potentially making them Higher Order Components ( i.e withWordCount ). I have inline comments that explain what is being done but am happy to explain further if there are any questions. EDIT: Here's how I'm enqueuing the script ``` function enqueue_block_editor_assets() { wp_enqueue_script( 'my-custom-script', // Handle. plugin_dir_url( __FILE__ ) . '/build/index.js', array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-edit-post', 'word-count' ) // Dependencies, defined above. ); } add_action( 'enqueue_block_editor_assets', 'enqueue_block_editor_assets' ); ``` Adding some more details about the build process. I am using [@wordpress/scripts](https://www.npmjs.com/package/@wordpress/scripts) and running the following scripts: ``` "scripts": { "build": "wp-scripts build", "start": "wp-scripts start" }, ``` Edit 2: You can get the attachment data via: ``` wp.data.select('core').getMedia( ID ) ```
339,156
<p>I need to show one item from menu only for users that are logged in and have certain custom capability set.</p> <p>Is it doable from theme functions.php or does it need a custom plugin?</p> <p>Note: I already use a plugin to show/hide menu items based on user roles, but couldn't find anything for Custom Capabilities (user meta value).</p> <p>Thanks for your time and help!</p>
[ { "answer_id": 339662, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 5, "selected": true, "text": "<p><strong>EDIT Sept 2021:</strong></p>\n<p>An updated version of the answer that uses hooks.</p>\n<p>This version tracks changes in the editor much better. It also uses <code>import</code> statement instead of importing directly from the <code>wp</code> global. This approach when used with the <code>@wordpress/scripts</code> package will correctly add dependencies for this file when being enqueued. Accessing the <code>wp</code> global will still work but you will have to be sure you're managing your script dependencies manually.</p>\n<p>Thanks to everyone in the comments!</p>\n<pre><code>import { useState, useEffect } from '@wordpress/element';\nimport { registerPlugin } from '@wordpress/plugins';\nimport { PluginPrePublishPanel } from '@wordpress/edit-post';\nimport { useSelect, useDispatch } from '@wordpress/data';\nimport { count } from '@wordpress/wordcount';\nimport { serialize } from '@wordpress/blocks';\n\nconst PrePublishCheckList = () =&gt; {\n // Manage the messaging in state.\n const [wordCountMessage, setWordCountMessage] = useState('');\n const [catsMessage, setCatsMessage] = useState('');\n const [tagsMessage, setTagsMessage] = useState('');\n const [featuredImageMessage, setFeaturedImageMessage] = useState('');\n\n // The useSelect hook is better for retrieving data from the store.\n const { blocks, cats, tags, featuredImageID } = useSelect((select) =&gt; {\n return {\n blocks: select('core/block-editor').getBlocks(),\n cats: select('core/editor').getEditedPostAttribute('categories'),\n tags: select('core/editor').getEditedPostAttribute('tags'),\n featuredImageID:\n select('core/editor').getEditedPostAttribute('featured_media'),\n };\n });\n\n // The useDispatch hook is better for dispatching actions.\n const { lockPostSaving, unlockPostSaving } = useDispatch('core/editor');\n\n // Put all the logic in the useEffect hook.\n useEffect(() =&gt; {\n let lockPost = false;\n // Get the WordCount\n const wordCount = count(serialize(blocks), 'words');\n if (wordCount &lt; 500) {\n lockPost = true;\n setWordCountMessage(`${wordCount} - Minimum of 500 required.`);\n } else {\n setWordCountMessage(`${wordCount}`);\n }\n\n // Get the category count\n if (!cats.length || (cats.length === 1 &amp;&amp; cats[0] === 1)) {\n lockPost = true;\n setCatsMessage('Missing');\n // Check that the cat is not Uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs.\n if (cats.length === 1 &amp;&amp; cats[0] === 1) {\n setCatsMessage('Cannot use Uncategorized');\n }\n } else {\n setCatsMessage('Set');\n }\n\n // Get the tags\n if (tags.length &lt; 3 || tags.length &gt; 5) {\n lockPost = true;\n setTagsMessage('Required 3 - 5 tags');\n } else {\n setTagsMessage('Set');\n }\n // Get the featured image\n if (featuredImageID === 0) {\n lockPost = true;\n setFeaturedImageMessage('Not Set');\n } else {\n setFeaturedImageMessage(' Set');\n }\n\n if (lockPost === true) {\n lockPostSaving();\n } else {\n unlockPostSaving();\n }\n }, [blocks, cats, tags, featuredImageID]);\n\n return (\n &lt;PluginPrePublishPanel title={'Publish Checklist'}&gt;\n &lt;p&gt;\n &lt;b&gt;Word Count:&lt;/b&gt; {wordCountMessage}\n &lt;/p&gt;\n &lt;p&gt;\n &lt;b&gt;Categories:&lt;/b&gt; {catsMessage}\n &lt;/p&gt;\n &lt;p&gt;\n &lt;b&gt;Tags:&lt;/b&gt; {tagsMessage}\n &lt;/p&gt;\n &lt;p&gt;\n &lt;b&gt;Featured Image:&lt;/b&gt; {featuredImageMessage}\n &lt;/p&gt;\n &lt;/PluginPrePublishPanel&gt;\n );\n};\n\nregisterPlugin('pre-publish-checklist', { render: PrePublishCheckList });\n</code></pre>\n<p><strong>Old Version</strong>:</p>\n<pre><code>const { registerPlugin } = wp.plugins;\nconst { PluginPrePublishPanel } = wp.editPost;\nconst { select, dispatch } = wp.data;\nconst { count } = wp.wordcount;\nconst { serialize } = wp.blocks;\nconst { PanelBody } = wp.components;\n\nconst PrePublishCheckList = () =&gt; {\n let lockPost = false;\n\n // Get the WordCount\n const blocks = select( 'core/block-editor' ).getBlocks();\n const wordCount = count( serialize( blocks ), 'words' );\n let wordCountMessage = `${wordCount}`;\n if ( wordCount &lt; 500 ) {\n lockPost = true;\n wordCountMessage += ` - Minimum of 500 required.`;\n }\n\n // Get the cats\n const cats = select( 'core/editor' ).getEditedPostAttribute( 'categories' );\n let catsMessage = 'Set';\n if ( ! cats.length ) {\n lockPost = true;\n catsMessage = 'Missing';\n } else {\n // Check that the cat is not uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs.\n if ( cats.length === 1 &amp;&amp; cats[0] === 1 ) {\n lockPost = true;\n catsMessage = 'Cannot use Uncategorized';\n }\n }\n\n // Get the tags\n const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' );\n let tagsMessage = 'Set';\n if ( tags.length &lt; 3 || tags.length &gt; 5 ) {\n lockPost = true;\n tagsMessage = 'Required 3 - 5 tags';\n }\n\n // Get the featured image\n const featuredImageID = select( 'core/editor' ).getEditedPostAttribute( 'featured_media' );\n let featuredImage = 'Set';\n\n if ( featuredImageID === 0 ) {\n lockPost = true;\n featuredImage = 'Not Set';\n }\n\n // Do we need to lock the post?\n if ( lockPost === true ) {\n dispatch( 'core/editor' ).lockPostSaving();\n } else {\n dispatch( 'core/editor' ).unlockPostSaving();\n }\n return (\n &lt;PluginPrePublishPanel title={ 'Publish Checklist' }&gt;\n &lt;p&gt;&lt;b&gt;Word Count:&lt;/b&gt; { wordCountMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Categories:&lt;/b&gt; { catsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Tags:&lt;/b&gt; { tagsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Featured Image:&lt;/b&gt; { featuredImage }&lt;/p&gt;\n &lt;/PluginPrePublishPanel&gt;\n )\n};\n\nregisterPlugin( 'pre-publish-checklist', { render: PrePublishCheckList } );\n</code></pre>\n<p>Display:</p>\n<p><a href=\"https://i.stack.imgur.com/tQFVh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tQFVh.png\" alt=\"enter image description here\" /></a></p>\n<p>The solution above addresses the requirements listed in the question. One thing that can be expanded on is the category checking, I am making some assumptions about the category ID.</p>\n<p>I have kept all of the checks in the same component for the sake of brevity and readability here. I would recommend moving each portion into a separate component and potentially making them Higher Order Components ( i.e withWordCount ).</p>\n<p>I have inline comments that explain what is being done but am happy to explain further if there are any questions.</p>\n<p>EDIT: Here's how I'm enqueuing the script</p>\n<pre><code>function enqueue_block_editor_assets() {\n wp_enqueue_script(\n 'my-custom-script', // Handle.\n plugin_dir_url( __FILE__ ) . '/build/index.js',\n array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-edit-post', 'word-count' ) // Dependencies, defined above.\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'enqueue_block_editor_assets' );\n</code></pre>\n<p>Adding some more details about the build process. I am using <a href=\"https://www.npmjs.com/package/@wordpress/scripts\" rel=\"nofollow noreferrer\">@wordpress/scripts</a> and running the following scripts:</p>\n<pre><code>&quot;scripts&quot;: {\n &quot;build&quot;: &quot;wp-scripts build&quot;,\n &quot;start&quot;: &quot;wp-scripts start&quot;\n },\n</code></pre>\n<p>Edit 2:</p>\n<p>You can get the attachment data via:</p>\n<pre><code>wp.data.select('core').getMedia( ID )\n</code></pre>\n" }, { "answer_id": 359780, "author": "BenB", "author_id": 62909, "author_profile": "https://wordpress.stackexchange.com/users/62909", "pm_score": 3, "selected": false, "text": "<p><strong>Update 29.02.2020</strong></p>\n<p>You have to replace <code>select( 'core/editor' ).getBlocks()</code> with <code>select( 'core/block-editor' ).getBlocks()</code> in order for this to work</p>\n<p>This worked for me:</p>\n<p><code>path\\to\\theme\\pre-publish-checklist\\src\\index.js</code></p>\n<pre class=\"lang-js prettyprint-override\"><code>const { registerPlugin } = wp.plugins;\nconst { PluginPrePublishPanel } = wp.editPost;\nconst { select, dispatch } = wp.data;\nconst { count } = wp.wordcount;\nconst { serialize } = wp.blocks;\nconst { PanelBody } = wp.components;\n\nconst PrePublishCheckList = () =&gt; {\n let lockPost = false;\n\n // Get the WordCount\n const blocks = select( 'core/block-editor' ).getBlocks();\n const wordCount = count( serialize( blocks ), 'words' );\n let wordCountMessage = `${wordCount}`;\n if ( wordCount &lt; 500 ) {\n lockPost = true;\n wordCountMessage += ` - Minimum of 500 required.`;\n }\n\n // Get the cats\n const cats = select( 'core/editor' ).getEditedPostAttribute( 'categories' );\n let catsMessage = 'Set';\n if ( ! cats.length ) {\n lockPost = true;\n catsMessage = 'Missing';\n } else {\n // Check that the cat is not uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs.\n if ( cats.length === 1 &amp;&amp; cats[0] === 1 ) {\n lockPost = true;\n catsMessage = 'Cannot use Uncategorized';\n }\n }\n\n // Get the tags\n const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' );\n let tagsMessage = 'Set';\n if ( tags.length &lt; 3 || tags.length &gt; 5 ) {\n lockPost = true;\n tagsMessage = 'Required 3 - 5 tags';\n }\n\n // Get the featured image\n const featuredImageID = select( 'core/editor' ).getEditedPostAttribute( 'featured_media' );\n let featuredImage = 'Set';\n\n if ( featuredImageID === 0 ) {\n lockPost = true;\n featuredImage = 'Not Set';\n }\n\n // Do we need to lock the post?\n if ( lockPost === true ) {\n dispatch( 'core/editor' ).lockPostSaving();\n } else {\n dispatch( 'core/editor' ).unlockPostSaving();\n }\n return (\n &lt;PluginPrePublishPanel title={ 'Publish Checklist' }&gt;\n &lt;p&gt;&lt;b&gt;Word Count:&lt;/b&gt; { wordCountMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Categories:&lt;/b&gt; { catsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Tags:&lt;/b&gt; { tagsMessage }&lt;/p&gt;\n &lt;p&gt;&lt;b&gt;Featured Image:&lt;/b&gt; { featuredImage }&lt;/p&gt;\n &lt;/PluginPrePublishPanel&gt;\n )\n};\n\nregisterPlugin( 'pre-publish-checklist', { render: PrePublishCheckList } );\n</code></pre>\n<p>Full steps to create the panel with @wordpress/scripts</p>\n<ol>\n<li>Create a folder <code>pre-publish-checklist</code> in your theme</li>\n<li>Create inside the folder package.json file with</li>\n</ol>\n<pre class=\"lang-json prettyprint-override\"><code>{\n &quot;scripts&quot;: {\n &quot;build&quot;: &quot;wp-scripts build&quot;,\n &quot;check-engines&quot;: &quot;wp-scripts check-engines&quot;,\n &quot;check-licenses&quot;: &quot;wp-scripts check-licenses&quot;,\n &quot;format:js&quot;: &quot;wp-scripts format-js&quot;,\n &quot;lint:css&quot;: &quot;wp-scripts lint-style&quot;,\n &quot;lint:js&quot;: &quot;wp-scripts lint-js&quot;,\n &quot;lint:md:docs&quot;: &quot;wp-scripts lint-md-docs&quot;,\n &quot;lint:md:js&quot;: &quot;wp-scripts lint-md-js&quot;,\n &quot;lint:pkg-json&quot;: &quot;wp-scripts lint-pkg-json&quot;,\n &quot;packages-update&quot;: &quot;wp-scripts packages-update&quot;,\n &quot;start&quot;: &quot;wp-scripts start&quot;,\n &quot;test:e2e&quot;: &quot;wp-scripts test-e2e&quot;,\n &quot;test:unit&quot;: &quot;wp-scripts test-unit-js&quot;\n },\n &quot;dependencies&quot;: {\n &quot;@wordpress/scripts&quot;: &quot;^7.1.2&quot;\n }\n}\n</code></pre>\n<ol start=\"3\">\n<li>Create a file in the folder with the path 'src/index.js' and place the code in the file</li>\n<li><code>yarn</code></li>\n<li><code>yarn build</code></li>\n<li>Add this code to functions.php to enqueue the file</li>\n</ol>\n<pre><code>function enqueue_block_editor_assets() {\n wp_enqueue_script(\n 'pre-publish-checklist', // Handle.\n get_template_directory_uri(). '/pre-publish-checklist/build/index.js',\n array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-edit-post', 'word-count' ) // Dependencies, defined above.\n );\n}\nadd_action( 'enqueue_block_editor_assets', 'enqueue_block_editor_assets' );\n</code></pre>\n" } ]
2019/05/30
[ "https://wordpress.stackexchange.com/questions/339156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65215/" ]
I need to show one item from menu only for users that are logged in and have certain custom capability set. Is it doable from theme functions.php or does it need a custom plugin? Note: I already use a plugin to show/hide menu items based on user roles, but couldn't find anything for Custom Capabilities (user meta value). Thanks for your time and help!
**EDIT Sept 2021:** An updated version of the answer that uses hooks. This version tracks changes in the editor much better. It also uses `import` statement instead of importing directly from the `wp` global. This approach when used with the `@wordpress/scripts` package will correctly add dependencies for this file when being enqueued. Accessing the `wp` global will still work but you will have to be sure you're managing your script dependencies manually. Thanks to everyone in the comments! ``` import { useState, useEffect } from '@wordpress/element'; import { registerPlugin } from '@wordpress/plugins'; import { PluginPrePublishPanel } from '@wordpress/edit-post'; import { useSelect, useDispatch } from '@wordpress/data'; import { count } from '@wordpress/wordcount'; import { serialize } from '@wordpress/blocks'; const PrePublishCheckList = () => { // Manage the messaging in state. const [wordCountMessage, setWordCountMessage] = useState(''); const [catsMessage, setCatsMessage] = useState(''); const [tagsMessage, setTagsMessage] = useState(''); const [featuredImageMessage, setFeaturedImageMessage] = useState(''); // The useSelect hook is better for retrieving data from the store. const { blocks, cats, tags, featuredImageID } = useSelect((select) => { return { blocks: select('core/block-editor').getBlocks(), cats: select('core/editor').getEditedPostAttribute('categories'), tags: select('core/editor').getEditedPostAttribute('tags'), featuredImageID: select('core/editor').getEditedPostAttribute('featured_media'), }; }); // The useDispatch hook is better for dispatching actions. const { lockPostSaving, unlockPostSaving } = useDispatch('core/editor'); // Put all the logic in the useEffect hook. useEffect(() => { let lockPost = false; // Get the WordCount const wordCount = count(serialize(blocks), 'words'); if (wordCount < 500) { lockPost = true; setWordCountMessage(`${wordCount} - Minimum of 500 required.`); } else { setWordCountMessage(`${wordCount}`); } // Get the category count if (!cats.length || (cats.length === 1 && cats[0] === 1)) { lockPost = true; setCatsMessage('Missing'); // Check that the cat is not Uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs. if (cats.length === 1 && cats[0] === 1) { setCatsMessage('Cannot use Uncategorized'); } } else { setCatsMessage('Set'); } // Get the tags if (tags.length < 3 || tags.length > 5) { lockPost = true; setTagsMessage('Required 3 - 5 tags'); } else { setTagsMessage('Set'); } // Get the featured image if (featuredImageID === 0) { lockPost = true; setFeaturedImageMessage('Not Set'); } else { setFeaturedImageMessage(' Set'); } if (lockPost === true) { lockPostSaving(); } else { unlockPostSaving(); } }, [blocks, cats, tags, featuredImageID]); return ( <PluginPrePublishPanel title={'Publish Checklist'}> <p> <b>Word Count:</b> {wordCountMessage} </p> <p> <b>Categories:</b> {catsMessage} </p> <p> <b>Tags:</b> {tagsMessage} </p> <p> <b>Featured Image:</b> {featuredImageMessage} </p> </PluginPrePublishPanel> ); }; registerPlugin('pre-publish-checklist', { render: PrePublishCheckList }); ``` **Old Version**: ``` const { registerPlugin } = wp.plugins; const { PluginPrePublishPanel } = wp.editPost; const { select, dispatch } = wp.data; const { count } = wp.wordcount; const { serialize } = wp.blocks; const { PanelBody } = wp.components; const PrePublishCheckList = () => { let lockPost = false; // Get the WordCount const blocks = select( 'core/block-editor' ).getBlocks(); const wordCount = count( serialize( blocks ), 'words' ); let wordCountMessage = `${wordCount}`; if ( wordCount < 500 ) { lockPost = true; wordCountMessage += ` - Minimum of 500 required.`; } // Get the cats const cats = select( 'core/editor' ).getEditedPostAttribute( 'categories' ); let catsMessage = 'Set'; if ( ! cats.length ) { lockPost = true; catsMessage = 'Missing'; } else { // Check that the cat is not uncategorized - this assumes that the ID of Uncategorized is 1, which it would be for most installs. if ( cats.length === 1 && cats[0] === 1 ) { lockPost = true; catsMessage = 'Cannot use Uncategorized'; } } // Get the tags const tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' ); let tagsMessage = 'Set'; if ( tags.length < 3 || tags.length > 5 ) { lockPost = true; tagsMessage = 'Required 3 - 5 tags'; } // Get the featured image const featuredImageID = select( 'core/editor' ).getEditedPostAttribute( 'featured_media' ); let featuredImage = 'Set'; if ( featuredImageID === 0 ) { lockPost = true; featuredImage = 'Not Set'; } // Do we need to lock the post? if ( lockPost === true ) { dispatch( 'core/editor' ).lockPostSaving(); } else { dispatch( 'core/editor' ).unlockPostSaving(); } return ( <PluginPrePublishPanel title={ 'Publish Checklist' }> <p><b>Word Count:</b> { wordCountMessage }</p> <p><b>Categories:</b> { catsMessage }</p> <p><b>Tags:</b> { tagsMessage }</p> <p><b>Featured Image:</b> { featuredImage }</p> </PluginPrePublishPanel> ) }; registerPlugin( 'pre-publish-checklist', { render: PrePublishCheckList } ); ``` Display: [![enter image description here](https://i.stack.imgur.com/tQFVh.png)](https://i.stack.imgur.com/tQFVh.png) The solution above addresses the requirements listed in the question. One thing that can be expanded on is the category checking, I am making some assumptions about the category ID. I have kept all of the checks in the same component for the sake of brevity and readability here. I would recommend moving each portion into a separate component and potentially making them Higher Order Components ( i.e withWordCount ). I have inline comments that explain what is being done but am happy to explain further if there are any questions. EDIT: Here's how I'm enqueuing the script ``` function enqueue_block_editor_assets() { wp_enqueue_script( 'my-custom-script', // Handle. plugin_dir_url( __FILE__ ) . '/build/index.js', array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-edit-post', 'word-count' ) // Dependencies, defined above. ); } add_action( 'enqueue_block_editor_assets', 'enqueue_block_editor_assets' ); ``` Adding some more details about the build process. I am using [@wordpress/scripts](https://www.npmjs.com/package/@wordpress/scripts) and running the following scripts: ``` "scripts": { "build": "wp-scripts build", "start": "wp-scripts start" }, ``` Edit 2: You can get the attachment data via: ``` wp.data.select('core').getMedia( ID ) ```
339,163
<p>I am working on a script to bring in an xml file from another server via Post request, This would then return another xml of data which I can then store into a wordpress database depending on certain values.</p> <p>I have made various attempts at this</p> <p>This first attempt some what works outside of wordpress</p> <pre><code> $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_PORT =&gt; "2222", CURLOPT_URL =&gt; "http://11.111.11.111:2222/folder/query", CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; "", CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 30, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; "POST", CURLOPT_POSTFIELDS =&gt; "&lt;root&gt;\r\n &lt;something1&gt;username&lt;/something1&gt;\r\n &lt;something2&gt;123456789&lt;/something2&gt;\r\n &lt;something3&gt;Hello&lt;/something3&gt;\r\n&lt;/root&gt;\r\n", CURLOPT_HTTPHEADER =&gt; array( "Accept: application/xml", "Cache-Control: no-cache", "Connection: keep-alive", "Content-Type: application/xml", "Host: 80.177.77.210:2222", "Postman-Token: ", "User-Agent: PostmanRuntime/7.13.0", "accept-encoding: gzip, deflate", "cache-control: no-cache", "content-length: 107" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { print_r($response); } </code></pre> <p>I tried to change this into wordpress </p> <pre><code>$url = 'http://11.111.11.111:2222/folder/query'; $args = array( 'headers' =&gt; array( '', 'cache-control' =&gt; 'no-cache', 'Connection' =&gt; 'keep-alive', 'Host' =&gt; '80.177.77.210:2222', 'Content-Type' =&gt; 'application/xml', 'Accept' =&gt; 'application/xml' ), 'body' =&gt; '&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;root&gt; &lt;something1&gt;username&lt;/something1&gt; &lt;something2&gt;123456789&lt;/something2&gt; &lt;something3&gt;Hello&lt;/something3&gt; &lt;/root&gt;', ); $response = wp_remote_post( $url, $args ); $body = wp_remote_retrieve_body( $response ); var_dump($body); </code></pre> <p>And Again</p> <pre><code>$url = 'http://11.111.11.111:2222/folder/query'; $request-&gt;setHeaders(array( 'cache-control' =&gt; 'no-cache', 'Connection' =&gt; 'keep-alive', 'content-length' =&gt; '107', 'accept-encoding' =&gt; 'gzip, deflate', 'Host' =&gt; '80.177.77.210:2222', 'Postman-Token' =&gt; '', 'Cache-Control' =&gt; 'no-cache', 'User-Agent' =&gt; 'PostmanRuntime/7.13.0', 'Content-Type' =&gt; 'application/xml', 'Accept' =&gt; 'application/xml' )); $body = '&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;root&gt; &lt;something1&gt;username&lt;/something1&gt; &lt;something2&gt;123456789&lt;/something2&gt; &lt;something3&gt;Hello&lt;/something3&gt; &lt;/root&gt;'; $result = wp_remote_post($url, array( 'method' =&gt; 'POST', 'headers' =&gt; $request, 'httpversion' =&gt; '1.0', 'body' =&gt; $body) ); $reci = wp_remote_retrieve_body( $result ); var_dump($reci); </code></pre> <p>Nothing happens and the Error_log comes back empty</p> <p>What am I doing wrong here? Can anyone assist please</p> <p>Also is there a specific place I should be running the script? Page template? Functions.php? A Plugin? </p> <p>Eventually I will need to grab the current logged in users username and a custom user meta field and put this data into here </p> <pre><code> &lt;root&gt; &lt;something1&gt;username&lt;/something1&gt; &lt;something2&gt;123456789&lt;/something2&gt; &lt;something3&gt;Hello&lt;/something3&gt; &lt;/root&gt; </code></pre> <p>and then I will need to format the XML into php when its returned so I can then I can do things with the data.</p>
[ { "answer_id": 339175, "author": "user1348927", "author_id": 169118, "author_profile": "https://wordpress.stackexchange.com/users/169118", "pm_score": 2, "selected": true, "text": "<p>I managed to solve this by adding the following into my functions.php</p>\n\n<pre><code>add_shortcode('my_shortode', 'my_function');\nfunction my_function () {\n\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n CURLOPT_PORT =&gt; \"2222\",\n CURLOPT_URL =&gt; \"http://11.111.11.111:2222/folder/query\",\n CURLOPT_RETURNTRANSFER =&gt; true,\n CURLOPT_ENCODING =&gt; \"\",\n CURLOPT_MAXREDIRS =&gt; 10,\n CURLOPT_TIMEOUT =&gt; 30,\n CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST =&gt; \"POST\",\n CURLOPT_POSTFIELDS =&gt; \"&lt;root&gt;\\r\\n &lt;something1&gt;username&lt;/something1&gt;\\r\\n &lt;something2&gt;123456789&lt;/something2&gt;\\r\\n &lt;something3&gt;Hello&lt;/something3&gt;\\r\\n&lt;/root&gt;\\r\\n\",\n CURLOPT_HTTPHEADER =&gt; array(\n \"Accept: application/xml\",\n \"Cache-Control: no-cache\",\n \"Connection: keep-alive\",\n \"Content-Type: application/xml\",\n \"Host: 80.177.77.210:2222\",\n \"Postman-Token: \",\n \"User-Agent: \",\n \"accept-encoding: gzip, deflate\",\n \"cache-control: no-cache\",\n \"content-length: 107\"\n ),\n));\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n\nif ($err) {\n echo \"cURL Error #:\" . $err;\n} else {\n echo $response;\n}\n}\n</code></pre>\n\n<p>Then in my page template </p>\n\n<pre><code>&lt;?php echo do_shortcode( '[my_shortode]' ); ?&gt; \n</code></pre>\n" }, { "answer_id": 339182, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>The proper way in WP is to use WP's <code>wp_remote_post()</code> function to do the HTTP request. A simple example:</p>\n\n<pre><code>$fields_string = http_build_query($post_array);\n// send the post via wp_remote_post\n$response = wp_remote_post($url . $fields_string);\n</code></pre>\n\n<p>Set the <code>$fields_string</code> to an array of parameters that are needed. Then use the <code>wp_remote_post()</code> function to do the actual request. See <a href=\"https://codex.wordpress.org/Function_Reference/wp_remote_post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_remote_post</a> .</p>\n" } ]
2019/05/30
[ "https://wordpress.stackexchange.com/questions/339163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169118/" ]
I am working on a script to bring in an xml file from another server via Post request, This would then return another xml of data which I can then store into a wordpress database depending on certain values. I have made various attempts at this This first attempt some what works outside of wordpress ``` $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_PORT => "2222", CURLOPT_URL => "http://11.111.11.111:2222/folder/query", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "<root>\r\n <something1>username</something1>\r\n <something2>123456789</something2>\r\n <something3>Hello</something3>\r\n</root>\r\n", CURLOPT_HTTPHEADER => array( "Accept: application/xml", "Cache-Control: no-cache", "Connection: keep-alive", "Content-Type: application/xml", "Host: 80.177.77.210:2222", "Postman-Token: ", "User-Agent: PostmanRuntime/7.13.0", "accept-encoding: gzip, deflate", "cache-control: no-cache", "content-length: 107" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { print_r($response); } ``` I tried to change this into wordpress ``` $url = 'http://11.111.11.111:2222/folder/query'; $args = array( 'headers' => array( '', 'cache-control' => 'no-cache', 'Connection' => 'keep-alive', 'Host' => '80.177.77.210:2222', 'Content-Type' => 'application/xml', 'Accept' => 'application/xml' ), 'body' => '<?xml version="1.0" encoding="UTF-8"?> <root> <something1>username</something1> <something2>123456789</something2> <something3>Hello</something3> </root>', ); $response = wp_remote_post( $url, $args ); $body = wp_remote_retrieve_body( $response ); var_dump($body); ``` And Again ``` $url = 'http://11.111.11.111:2222/folder/query'; $request->setHeaders(array( 'cache-control' => 'no-cache', 'Connection' => 'keep-alive', 'content-length' => '107', 'accept-encoding' => 'gzip, deflate', 'Host' => '80.177.77.210:2222', 'Postman-Token' => '', 'Cache-Control' => 'no-cache', 'User-Agent' => 'PostmanRuntime/7.13.0', 'Content-Type' => 'application/xml', 'Accept' => 'application/xml' )); $body = '<?xml version="1.0" encoding="UTF-8"?> <root> <something1>username</something1> <something2>123456789</something2> <something3>Hello</something3> </root>'; $result = wp_remote_post($url, array( 'method' => 'POST', 'headers' => $request, 'httpversion' => '1.0', 'body' => $body) ); $reci = wp_remote_retrieve_body( $result ); var_dump($reci); ``` Nothing happens and the Error\_log comes back empty What am I doing wrong here? Can anyone assist please Also is there a specific place I should be running the script? Page template? Functions.php? A Plugin? Eventually I will need to grab the current logged in users username and a custom user meta field and put this data into here ``` <root> <something1>username</something1> <something2>123456789</something2> <something3>Hello</something3> </root> ``` and then I will need to format the XML into php when its returned so I can then I can do things with the data.
I managed to solve this by adding the following into my functions.php ``` add_shortcode('my_shortode', 'my_function'); function my_function () { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_PORT => "2222", CURLOPT_URL => "http://11.111.11.111:2222/folder/query", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "<root>\r\n <something1>username</something1>\r\n <something2>123456789</something2>\r\n <something3>Hello</something3>\r\n</root>\r\n", CURLOPT_HTTPHEADER => array( "Accept: application/xml", "Cache-Control: no-cache", "Connection: keep-alive", "Content-Type: application/xml", "Host: 80.177.77.210:2222", "Postman-Token: ", "User-Agent: ", "accept-encoding: gzip, deflate", "cache-control: no-cache", "content-length: 107" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } } ``` Then in my page template ``` <?php echo do_shortcode( '[my_shortode]' ); ?> ```
339,209
<p>I'm tyrying to let the admin search through the users by a single meta value called 'indice de busqueda' insithe the wordpress /wp-admin/users.php page</p> <p>How can I hook into the search box in such a way so that I can change the query to look something like this?</p> <pre><code> $query = get_users([ 'meta_key' =&gt; 'indice de busqueda', 'meta_value' =&gt; $search_value, 'meta_compare'=&gt;'REGEX' ]) </code></pre> <p>I tried many possible aproaches but I cant seem to find one where I can avoid messing with SQL.</p>
[ { "answer_id": 339213, "author": "Radley Sustaire", "author_id": 19105, "author_profile": "https://wordpress.stackexchange.com/users/19105", "pm_score": 2, "selected": true, "text": "<p>Take a look at the <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_users/\" rel=\"nofollow noreferrer\">pre_get_users</a> hook. It is very similar to pre_get_posts if you are familiar with that, except it is for wp_user_query instead of wp_query.</p>\n\n<p>You will need to ensure that you only check the users screen in the dashboard, because that hook would affect any user listing otherwise.</p>\n\n<p>Here is an example of what the code might look like. <strong>Not fully tested</strong> but based on some working code from my own plugin.</p>\n\n<pre><code>function so339209_filter_users_indice_de_busqueda( $query ) {\n if ( !function_exists('get_current_screen') ) return;\n\n // Only apply on the Users screen in the dashboard\n $screen = get_current_screen();\n if ( !screen || screen-&gt;in !== 'users' ) return;\n\n $query-&gt;set('meta_key', 'indice de busqueda');\n $query-&gt;set('meta_value', $search_value);\n $query-&gt;set('meta_compare', 'REGEX');\n}\nadd_action( 'pre_get_users', 'so339209_filter_users_indice_de_busqueda', 20 );\n</code></pre>\n" }, { "answer_id": 339270, "author": "Joaquin Brandan", "author_id": 169151, "author_profile": "https://wordpress.stackexchange.com/users/169151", "pm_score": 0, "selected": false, "text": "<p>I found the problem.</p>\n\n<p>The query from <code>pre_get_users</code> was returning empty because wordpress was appending and prepending asterisks <code>*</code> to my search string. if i searched for 11 then <code>$query-&gt;query_vars['search']</code> would be equal to <code>'*11*'</code> instead of <code>11</code> and that was screwing up all of my searches, regex or otherwise.</p>\n\n<p>The solution was to remove the asterisks from the search value</p>\n\n<pre><code>function so339209_filter_users_indice_de_busqueda($query)\n{\n global $pagenow;\n\n if (is_admin() &amp;&amp; 'users.php' == $pagenow) {\n\n\n //Remove trailing and starting empty spaces\n $the_search = trim($query-&gt;query_vars['search']);\n\n //Remove trailing and starting asterisks that wordpress adds to your search\n // string\n $the_search = trim($query-&gt;query_vars['search'], '*');\n\n //Build your query from the search string, Im using a LIKE comparison \n //for simplicity but you could use a REGEX too\n $query-&gt;set('meta_key', 'indice de busqueda');\n $query-&gt;set('meta_value', $the_search);\n $query-&gt;set('meta_compare', 'LIKE');\n\n //Nuke the search string so that the query does not try to match your search\n //with the users username or email.\n $query-&gt;set('search', '');\n }\n}\nadd_action('pre_get_users', 'so339209_filter_users_indice_de_busqueda', 20);\n</code></pre>\n" } ]
2019/05/30
[ "https://wordpress.stackexchange.com/questions/339209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169151/" ]
I'm tyrying to let the admin search through the users by a single meta value called 'indice de busqueda' insithe the wordpress /wp-admin/users.php page How can I hook into the search box in such a way so that I can change the query to look something like this? ``` $query = get_users([ 'meta_key' => 'indice de busqueda', 'meta_value' => $search_value, 'meta_compare'=>'REGEX' ]) ``` I tried many possible aproaches but I cant seem to find one where I can avoid messing with SQL.
Take a look at the [pre\_get\_users](https://developer.wordpress.org/reference/hooks/pre_get_users/) hook. It is very similar to pre\_get\_posts if you are familiar with that, except it is for wp\_user\_query instead of wp\_query. You will need to ensure that you only check the users screen in the dashboard, because that hook would affect any user listing otherwise. Here is an example of what the code might look like. **Not fully tested** but based on some working code from my own plugin. ``` function so339209_filter_users_indice_de_busqueda( $query ) { if ( !function_exists('get_current_screen') ) return; // Only apply on the Users screen in the dashboard $screen = get_current_screen(); if ( !screen || screen->in !== 'users' ) return; $query->set('meta_key', 'indice de busqueda'); $query->set('meta_value', $search_value); $query->set('meta_compare', 'REGEX'); } add_action( 'pre_get_users', 'so339209_filter_users_indice_de_busqueda', 20 ); ```
339,234
<p>How we can verify "Cancel the header auth" the "endpoint" functions of WordPress with an API key that we produce. (Note: not a different endpoint, original endpoints)</p> <p>I have my own "Crypto" class/function. In the request, I need to send an encrypted key, "decrypt" the "encrypted key" from "wp-function" and so on, and allow the request.</p> <p>I need to be able to do all of this on wordpress own endpoint libraries.</p> <p><strong>A simple example of my query structure:</strong></p> <pre><code>$.ajax({ type: "POST", url: "http://localhost/workspace/wordpress/wp-json/wp/v2/posts?request=&lt;?php echo $encrypted; ?&gt;", dataType: "json" }); </code></pre> <p><strong>PHP</strong></p> <pre><code>&lt;?php echo $encrypted; ?&gt; &lt;?php // "z0/8Q6cuMWBlZGzfTwOVi9HwCpKThN9Ju/o/MywK74vimB467vjGfKqoDVQdyKIdmXCxxE=" ?&gt; </code></pre> <p><strong>functions.php or e.g. php page: After Decrypt</strong></p> <pre><code>&lt;?php echo $decrypted; ?&gt; &lt;?php // "Secret Password" ?&gt; &lt;?php // I will verify my key, and to let </code></pre> <p><a href="https://i.stack.imgur.com/Mv25U.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mv25U.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/wdx6z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wdx6z.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 339236, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>Sounds like you can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_authentication_errors/\" rel=\"nofollow noreferrer\"><code>rest_authentication_errors</code></a> filter:</p>\n\n<blockquote>\n <p>This is used to pass a <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> from an authentication method back to\n the API.</p>\n \n <p>[...] If the authentication method hooked in is not actually being\n attempted, <code>null</code> should be returned [...]. Similarly, callbacks\n should ensure the value is <code>null</code> before checking for errors.</p>\n \n <p>A <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> instance can be returned if an error occurs [...]. A\n callback can return <code>true</code> to indicate that the authentication method\n was used, and it succeeded.</p>\n</blockquote>\n\n<p>For a code example, you can look how WP implemented their custom check for the <code>X-WP-Nonce</code> header in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/rest-api.php#L807\" rel=\"nofollow noreferrer\"><em>wp-includes/rest-api.php</em> starting at line 807</a>.</p>\n\n<p>(The function <code>rest_cookie_check_errors</code> is <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L278\" rel=\"nofollow noreferrer\">added to the <code>rest_authentication_errors</code> filter with priority 100</a>.)</p>\n" }, { "answer_id": 339321, "author": "BOZ", "author_id": 162608, "author_profile": "https://wordpress.stackexchange.com/users/162608", "pm_score": 3, "selected": true, "text": "<pre><code>function checkApiAuth( $result ){\n\n $yourEncryptAPIKey = $_GET['request'];\n\n if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ):\n $result = true;\n\n else:\n $result = false;\n\n endif;\n\n return $result; \n}\nadd_filter('rest_authentication_errors', 'checkApiAuth');\n</code></pre>\n" } ]
2019/05/31
[ "https://wordpress.stackexchange.com/questions/339234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169188/" ]
How we can verify "Cancel the header auth" the "endpoint" functions of WordPress with an API key that we produce. (Note: not a different endpoint, original endpoints) I have my own "Crypto" class/function. In the request, I need to send an encrypted key, "decrypt" the "encrypted key" from "wp-function" and so on, and allow the request. I need to be able to do all of this on wordpress own endpoint libraries. **A simple example of my query structure:** ``` $.ajax({ type: "POST", url: "http://localhost/workspace/wordpress/wp-json/wp/v2/posts?request=<?php echo $encrypted; ?>", dataType: "json" }); ``` **PHP** ``` <?php echo $encrypted; ?> <?php // "z0/8Q6cuMWBlZGzfTwOVi9HwCpKThN9Ju/o/MywK74vimB467vjGfKqoDVQdyKIdmXCxxE=" ?> ``` **functions.php or e.g. php page: After Decrypt** ``` <?php echo $decrypted; ?> <?php // "Secret Password" ?> <?php // I will verify my key, and to let ``` [![enter image description here](https://i.stack.imgur.com/Mv25U.jpg)](https://i.stack.imgur.com/Mv25U.jpg) [![enter image description here](https://i.stack.imgur.com/wdx6z.jpg)](https://i.stack.imgur.com/wdx6z.jpg)
``` function checkApiAuth( $result ){ $yourEncryptAPIKey = $_GET['request']; if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ): $result = true; else: $result = false; endif; return $result; } add_filter('rest_authentication_errors', 'checkApiAuth'); ```
339,253
<p>I have wordpress site and need advise regarding redirect htaccess based on useragent:</p> <p>Sample:</p> <p>my old url: myolddomain/old-post/ redirect to: mynewdomain/new-post/</p> <p>based on useragent</p> <p>thanks</p>
[ { "answer_id": 339236, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>Sounds like you can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_authentication_errors/\" rel=\"nofollow noreferrer\"><code>rest_authentication_errors</code></a> filter:</p>\n\n<blockquote>\n <p>This is used to pass a <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> from an authentication method back to\n the API.</p>\n \n <p>[...] If the authentication method hooked in is not actually being\n attempted, <code>null</code> should be returned [...]. Similarly, callbacks\n should ensure the value is <code>null</code> before checking for errors.</p>\n \n <p>A <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> instance can be returned if an error occurs [...]. A\n callback can return <code>true</code> to indicate that the authentication method\n was used, and it succeeded.</p>\n</blockquote>\n\n<p>For a code example, you can look how WP implemented their custom check for the <code>X-WP-Nonce</code> header in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/rest-api.php#L807\" rel=\"nofollow noreferrer\"><em>wp-includes/rest-api.php</em> starting at line 807</a>.</p>\n\n<p>(The function <code>rest_cookie_check_errors</code> is <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L278\" rel=\"nofollow noreferrer\">added to the <code>rest_authentication_errors</code> filter with priority 100</a>.)</p>\n" }, { "answer_id": 339321, "author": "BOZ", "author_id": 162608, "author_profile": "https://wordpress.stackexchange.com/users/162608", "pm_score": 3, "selected": true, "text": "<pre><code>function checkApiAuth( $result ){\n\n $yourEncryptAPIKey = $_GET['request'];\n\n if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ):\n $result = true;\n\n else:\n $result = false;\n\n endif;\n\n return $result; \n}\nadd_filter('rest_authentication_errors', 'checkApiAuth');\n</code></pre>\n" } ]
2019/05/31
[ "https://wordpress.stackexchange.com/questions/339253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169210/" ]
I have wordpress site and need advise regarding redirect htaccess based on useragent: Sample: my old url: myolddomain/old-post/ redirect to: mynewdomain/new-post/ based on useragent thanks
``` function checkApiAuth( $result ){ $yourEncryptAPIKey = $_GET['request']; if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ): $result = true; else: $result = false; endif; return $result; } add_filter('rest_authentication_errors', 'checkApiAuth'); ```
339,255
<p>I have a website where I need to 301 redirect all old pages that are incoming from old URLs like <code>/?page_id=261</code>, <code>/?page_id=204</code>, <code>/?page_id=2677</code> and so on to the main home page.</p> <p>What would be a proper way of doing it? Will something like this in <code>.htaccess</code> work? I do not want to redirect all 404's - just these type of old links.</p> <pre><code>RedirectMatch 301 ^/?page_id=4&amp;n=$1 https://www.example.com/ </code></pre>
[ { "answer_id": 339236, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>Sounds like you can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_authentication_errors/\" rel=\"nofollow noreferrer\"><code>rest_authentication_errors</code></a> filter:</p>\n\n<blockquote>\n <p>This is used to pass a <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> from an authentication method back to\n the API.</p>\n \n <p>[...] If the authentication method hooked in is not actually being\n attempted, <code>null</code> should be returned [...]. Similarly, callbacks\n should ensure the value is <code>null</code> before checking for errors.</p>\n \n <p>A <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> instance can be returned if an error occurs [...]. A\n callback can return <code>true</code> to indicate that the authentication method\n was used, and it succeeded.</p>\n</blockquote>\n\n<p>For a code example, you can look how WP implemented their custom check for the <code>X-WP-Nonce</code> header in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/rest-api.php#L807\" rel=\"nofollow noreferrer\"><em>wp-includes/rest-api.php</em> starting at line 807</a>.</p>\n\n<p>(The function <code>rest_cookie_check_errors</code> is <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L278\" rel=\"nofollow noreferrer\">added to the <code>rest_authentication_errors</code> filter with priority 100</a>.)</p>\n" }, { "answer_id": 339321, "author": "BOZ", "author_id": 162608, "author_profile": "https://wordpress.stackexchange.com/users/162608", "pm_score": 3, "selected": true, "text": "<pre><code>function checkApiAuth( $result ){\n\n $yourEncryptAPIKey = $_GET['request'];\n\n if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ):\n $result = true;\n\n else:\n $result = false;\n\n endif;\n\n return $result; \n}\nadd_filter('rest_authentication_errors', 'checkApiAuth');\n</code></pre>\n" } ]
2019/05/31
[ "https://wordpress.stackexchange.com/questions/339255", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138568/" ]
I have a website where I need to 301 redirect all old pages that are incoming from old URLs like `/?page_id=261`, `/?page_id=204`, `/?page_id=2677` and so on to the main home page. What would be a proper way of doing it? Will something like this in `.htaccess` work? I do not want to redirect all 404's - just these type of old links. ``` RedirectMatch 301 ^/?page_id=4&n=$1 https://www.example.com/ ```
``` function checkApiAuth( $result ){ $yourEncryptAPIKey = $_GET['request']; if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ): $result = true; else: $result = false; endif; return $result; } add_filter('rest_authentication_errors', 'checkApiAuth'); ```
339,267
<p>I've been making a find-a-dealer type plugin in WordPress and I finally got it all done, everything works on my local <strong>and</strong> dev server.</p> <p>I push it up to production and upon activation, I get these errors/warnings:</p> <blockquote> <p>Notice: wp_register_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my_site/public_html/wp-includes/functions.php on line 4773</p> <p>Notice: wp_register_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my_site/public_html/wp-includes/functions.php on line 4773</p> <p>Notice: wp_enqueue_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my_site/public_html/wp-includes/functions.php on line 4773</p> <p>Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my_site/public_html/wp-includes/functions.php on line 4773</p> <p>Notice: Undefined offset: 0 in /home/sites/my_site/public_html/wp-includes/plugin.php on line 914</p> <p>Notice: Undefined offset: 0 in /home/sites/my_site/public_html/wp-includes/plugin.php on line 933</p> <p>Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in /home/sites/my_site/public_html/wp-includes/class-wp-hook.php on line 286</p> </blockquote> <p>Looking at these errors, I immediately went to my plugin's code for handling registering css/js:</p> <blockquote> <p>main-plugin-file.php (skimmed down)</p> </blockquote> <pre><code>function fad_css_js() { # add css wp_register_style('front_css', plugins_url('skin/css/front.css', __FILE__)); # register css wp_enqueue_style('front_css'); } # actions add_action('init', 'fad_css_js'); </code></pre> <blockquote> <p>admin-plugin-file.php (skimmed down)</p> </blockquote> <pre><code>function adn_css_js() { # css wp_register_style('adn-css', plugins_url('skin/css/admin.css', __FILE__)); wp_enqueue_style('adn-css'); # js wp_register_script('adn-js', plugins_url('skin/js/admin.js', __FILE__), array(), false, true); wp_enqueue_script('adn-js'); } add_action('admin_enqueue_scripts', adn_css_js()); </code></pre> <p>Like I said, this worked on my localhost and development server. Going to production seems to bring up all these errors, it (the code) doesn't look to be in the wrong, I register before any enqueue, so I'm really not sure.</p> <p>Going to the debugging page on WP site wasn't helpful.. </p> <p>How do I debug/resolve this?</p> <p><strong>Edit</strong></p> <p>Can confirm that a different plugin with the css/js code like this:</p> <pre><code>function my_other_js_css() { # add css wp_register_style('my_other__css', plugins_url('css/main.css', __FILE__)); wp_register_style('my_other_media_css', plugins_url('css/media.css', __FILE__)); # add js wp_register_script('my_other_js', plugins_url('js/main.js', __FILE__), array(), false, true); # register css wp_enqueue_style('my_other_css'); wp_enqueue_style('my_other_media_css'); # register js wp_enqueue_script('my_other_js'); } add_action('plugins_loaded', array('the_plugin', 'get_instance')); add_action('init', 'my_other_js_css'); </code></pre>
[ { "answer_id": 339236, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>Sounds like you can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_authentication_errors/\" rel=\"nofollow noreferrer\"><code>rest_authentication_errors</code></a> filter:</p>\n\n<blockquote>\n <p>This is used to pass a <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> from an authentication method back to\n the API.</p>\n \n <p>[...] If the authentication method hooked in is not actually being\n attempted, <code>null</code> should be returned [...]. Similarly, callbacks\n should ensure the value is <code>null</code> before checking for errors.</p>\n \n <p>A <a href=\"https://developer.wordpress.org/reference/classes/wp_error/\" rel=\"nofollow noreferrer\"><code>WP_Error</code></a> instance can be returned if an error occurs [...]. A\n callback can return <code>true</code> to indicate that the authentication method\n was used, and it succeeded.</p>\n</blockquote>\n\n<p>For a code example, you can look how WP implemented their custom check for the <code>X-WP-Nonce</code> header in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/rest-api.php#L807\" rel=\"nofollow noreferrer\"><em>wp-includes/rest-api.php</em> starting at line 807</a>.</p>\n\n<p>(The function <code>rest_cookie_check_errors</code> is <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L278\" rel=\"nofollow noreferrer\">added to the <code>rest_authentication_errors</code> filter with priority 100</a>.)</p>\n" }, { "answer_id": 339321, "author": "BOZ", "author_id": 162608, "author_profile": "https://wordpress.stackexchange.com/users/162608", "pm_score": 3, "selected": true, "text": "<pre><code>function checkApiAuth( $result ){\n\n $yourEncryptAPIKey = $_GET['request'];\n\n if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ):\n $result = true;\n\n else:\n $result = false;\n\n endif;\n\n return $result; \n}\nadd_filter('rest_authentication_errors', 'checkApiAuth');\n</code></pre>\n" } ]
2019/05/31
[ "https://wordpress.stackexchange.com/questions/339267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155748/" ]
I've been making a find-a-dealer type plugin in WordPress and I finally got it all done, everything works on my local **and** dev server. I push it up to production and upon activation, I get these errors/warnings: > > Notice: wp\_register\_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp\_enqueue\_scripts, admin\_enqueue\_scripts, or login\_enqueue\_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my\_site/public\_html/wp-includes/functions.php on line 4773 > > > Notice: wp\_register\_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp\_enqueue\_scripts, admin\_enqueue\_scripts, or login\_enqueue\_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my\_site/public\_html/wp-includes/functions.php on line 4773 > > > Notice: wp\_enqueue\_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp\_enqueue\_scripts, admin\_enqueue\_scripts, or login\_enqueue\_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my\_site/public\_html/wp-includes/functions.php on line 4773 > > > Notice: wp\_enqueue\_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp\_enqueue\_scripts, admin\_enqueue\_scripts, or login\_enqueue\_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/sites/my\_site/public\_html/wp-includes/functions.php on line 4773 > > > Notice: Undefined offset: 0 in /home/sites/my\_site/public\_html/wp-includes/plugin.php on line 914 > > > Notice: Undefined offset: 0 in /home/sites/my\_site/public\_html/wp-includes/plugin.php on line 933 > > > Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, no array or string given in /home/sites/my\_site/public\_html/wp-includes/class-wp-hook.php on line 286 > > > Looking at these errors, I immediately went to my plugin's code for handling registering css/js: > > main-plugin-file.php (skimmed down) > > > ``` function fad_css_js() { # add css wp_register_style('front_css', plugins_url('skin/css/front.css', __FILE__)); # register css wp_enqueue_style('front_css'); } # actions add_action('init', 'fad_css_js'); ``` > > admin-plugin-file.php (skimmed down) > > > ``` function adn_css_js() { # css wp_register_style('adn-css', plugins_url('skin/css/admin.css', __FILE__)); wp_enqueue_style('adn-css'); # js wp_register_script('adn-js', plugins_url('skin/js/admin.js', __FILE__), array(), false, true); wp_enqueue_script('adn-js'); } add_action('admin_enqueue_scripts', adn_css_js()); ``` Like I said, this worked on my localhost and development server. Going to production seems to bring up all these errors, it (the code) doesn't look to be in the wrong, I register before any enqueue, so I'm really not sure. Going to the debugging page on WP site wasn't helpful.. How do I debug/resolve this? **Edit** Can confirm that a different plugin with the css/js code like this: ``` function my_other_js_css() { # add css wp_register_style('my_other__css', plugins_url('css/main.css', __FILE__)); wp_register_style('my_other_media_css', plugins_url('css/media.css', __FILE__)); # add js wp_register_script('my_other_js', plugins_url('js/main.js', __FILE__), array(), false, true); # register css wp_enqueue_style('my_other_css'); wp_enqueue_style('my_other_media_css'); # register js wp_enqueue_script('my_other_js'); } add_action('plugins_loaded', array('the_plugin', 'get_instance')); add_action('init', 'my_other_js_css'); ```
``` function checkApiAuth( $result ){ $yourEncryptAPIKey = $_GET['request']; if( yourDecryptFn( $yourEncryptAPIKey ) === $realKey ): $result = true; else: $result = false; endif; return $result; } add_filter('rest_authentication_errors', 'checkApiAuth'); ```
339,279
<p>I've got a bizarre problem with a website I'm working on.</p> <p>Recently, when anyone uploads images to the site, some time later (maybe an hour, sometimes several hours) one or more images disappear from the server. They still show up in the Media Library, and all the other sizes created by Wordpress are still on the server. But whatever size is being used on the page (usually the full size image, but not always) randomly gets deleted.</p> <p>If I replace the missing file via FTP, they tend to disappear again fairly quickly (sometimes minutes, sometimes hours later).</p> <p>I've tried removing any plugins recently installed. No luck.</p> <p>I've even migrated the site to a completely different server. Oddly, it seemed to work at first. For several days, I had the site on the new server and no images disappeared. But then, once I updated the DNS settings to point the domain over, then they started to disappear.</p> <p>Neither hosting company had any clue what could be causing it.</p> <p>Have you ever seen a problem like this? Any idea what function I can look for that could be deleting images at random?</p> <p><strong>Update:</strong> I eventually found the problem was related to a plugin called CyberSEO Lite. Ever since I removed it, no more images have disappeared.</p>
[ { "answer_id": 339300, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 1, "selected": false, "text": "<p>If it occurs periodically, the first place I would check is scheduled tasks. I would also check your error log to see if anything shows up there. I would also check permissions. </p>\n\n<p>Of course, if you can't figured it out, try disabling all plugins and changing the theme. </p>\n" }, { "answer_id": 339305, "author": "coolpasta", "author_id": 143406, "author_profile": "https://wordpress.stackexchange.com/users/143406", "pm_score": 3, "selected": true, "text": "<p>Obviously, I imagine you already checked cron jobs.</p>\n\n<p>No one can tell you, but whenever you have an issue and you're wondering \"what the hell is interacting with my system?\" and that part that's problematic (in your case, the deletion of the image) has actions inside of it, we can see what called that specific deletion. So let's see how this applies in your case.</p>\n\n<p>An image is a post. When it gets deleted, unless something bad happens, you can safely say that <code>wp_delete_post</code> will be used and inside of this function, we have the earliest action we can hook into <code>before_delete_post</code>:</p>\n\n<pre><code>add_action( 'before_delete_post', function( $postid ) {\n $past_backtrace = get_option( 'backtrace_for_deletion', [] );\n $current_backtrace = debug_backtrace();\n\n $past_backtrace[] = json_encode( $current_backtrace );\n update_option( 'backtrace_for_deletion', $past_backtrace );\n});\n</code></pre>\n\n<p>We basically want to see what called this deletion, so let's make it a bit prettier:</p>\n\n<pre><code> $backtraces = get_option( 'backtrace_for_deletion' );\n foreach( $backtraces as $backtrace ) {\n ?&gt;\n &lt;pre&gt;\n &lt;?php\n print_r( json_decode( $backtrace ) );\n echo '-----------------------------------------------------------------------------------';\n ?&gt;\n &lt;/pre&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>This isn't exactly the best view, but it gives you the information.</p>\n\n<p>A few points:</p>\n\n<ol>\n<li>Third item is always where the deletion is called from, it'll give you the exact file name and line of what called the deletion.</li>\n<li>If this doesn't work, then I advise you turn server file logging on, as well as database logging and look at the queries.</li>\n</ol>\n" }, { "answer_id": 355258, "author": "thingEvery", "author_id": 143237, "author_profile": "https://wordpress.stackexchange.com/users/143237", "pm_score": 2, "selected": false, "text": "<p>After dealing with this problem for almost a year, I finally solved it. It turned out to be a plugin after all. It was difficult to diagnose, since it happened so sporadically - sometimes not for months. But eventually, I found a certain post which was doing it with some regularity so I copied the site to a dev environment and went through the plugins one at a time until I found the culprit. It's called CyberSEO Lite. Once I removed it, the problem stopped and hasn't come back since.</p>\n" } ]
2019/05/31
[ "https://wordpress.stackexchange.com/questions/339279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143237/" ]
I've got a bizarre problem with a website I'm working on. Recently, when anyone uploads images to the site, some time later (maybe an hour, sometimes several hours) one or more images disappear from the server. They still show up in the Media Library, and all the other sizes created by Wordpress are still on the server. But whatever size is being used on the page (usually the full size image, but not always) randomly gets deleted. If I replace the missing file via FTP, they tend to disappear again fairly quickly (sometimes minutes, sometimes hours later). I've tried removing any plugins recently installed. No luck. I've even migrated the site to a completely different server. Oddly, it seemed to work at first. For several days, I had the site on the new server and no images disappeared. But then, once I updated the DNS settings to point the domain over, then they started to disappear. Neither hosting company had any clue what could be causing it. Have you ever seen a problem like this? Any idea what function I can look for that could be deleting images at random? **Update:** I eventually found the problem was related to a plugin called CyberSEO Lite. Ever since I removed it, no more images have disappeared.
Obviously, I imagine you already checked cron jobs. No one can tell you, but whenever you have an issue and you're wondering "what the hell is interacting with my system?" and that part that's problematic (in your case, the deletion of the image) has actions inside of it, we can see what called that specific deletion. So let's see how this applies in your case. An image is a post. When it gets deleted, unless something bad happens, you can safely say that `wp_delete_post` will be used and inside of this function, we have the earliest action we can hook into `before_delete_post`: ``` add_action( 'before_delete_post', function( $postid ) { $past_backtrace = get_option( 'backtrace_for_deletion', [] ); $current_backtrace = debug_backtrace(); $past_backtrace[] = json_encode( $current_backtrace ); update_option( 'backtrace_for_deletion', $past_backtrace ); }); ``` We basically want to see what called this deletion, so let's make it a bit prettier: ``` $backtraces = get_option( 'backtrace_for_deletion' ); foreach( $backtraces as $backtrace ) { ?> <pre> <?php print_r( json_decode( $backtrace ) ); echo '-----------------------------------------------------------------------------------'; ?> </pre> <?php } ``` This isn't exactly the best view, but it gives you the information. A few points: 1. Third item is always where the deletion is called from, it'll give you the exact file name and line of what called the deletion. 2. If this doesn't work, then I advise you turn server file logging on, as well as database logging and look at the queries.
339,297
<p>I am using WordPress FormCraft plugin on my site. I created a form and got the form short embedded code</p> <pre><code>[fc id='4'][/fc] </code></pre> <p>I want to show this form when the user opens the page.</p> <p>Can anyone tell how can approach this?</p> <p>I also try in Page Editor I got an option to add form it generated below code for me.</p> <pre><code>[fc id='4' type='popup' button_color='#4488ee' font_color='white'][/fc] </code></pre>
[ { "answer_id": 339302, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 2, "selected": true, "text": "<p>From the <a href=\"https://formcraft-wp.com/help/how-to-use-a-custom-popup-form-trigger/\" rel=\"nofollow noreferrer\">documentation</a>, you have to use the shortcode:</p>\n\n<pre><code>[fc id='12' type='popup'][/fc]\n</code></pre>\n\n<p>Next, something has to trigger the form, you can create a button for that and then click it from jQury, edit the link which would trigger this form, and put the href or hyperlink to:</p>\n\n<pre><code>&lt;a class=\"triggerForm\" href=\"http://yoursite.com/form-view/12\"&gt;Link Trigger&lt;/a&gt;\n</code></pre>\n\n<p>jQuery trigger.</p>\n\n<pre><code>$(document).ready(function () {\n $('a.triggerForm').click();\n});\n</code></pre>\n" }, { "answer_id": 340023, "author": "Developer", "author_id": 117095, "author_profile": "https://wordpress.stackexchange.com/users/117095", "pm_score": 0, "selected": false, "text": "<p>Found a simple solution without changing any code. I have used another plugin <a href=\"https://wordpress.org/plugins/popup-maker/\" rel=\"nofollow noreferrer\">Popup maker</a> that will create a pop-up, there I can configure on page load / with time delay.</p>\n" } ]
2019/05/31
[ "https://wordpress.stackexchange.com/questions/339297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117095/" ]
I am using WordPress FormCraft plugin on my site. I created a form and got the form short embedded code ``` [fc id='4'][/fc] ``` I want to show this form when the user opens the page. Can anyone tell how can approach this? I also try in Page Editor I got an option to add form it generated below code for me. ``` [fc id='4' type='popup' button_color='#4488ee' font_color='white'][/fc] ```
From the [documentation](https://formcraft-wp.com/help/how-to-use-a-custom-popup-form-trigger/), you have to use the shortcode: ``` [fc id='12' type='popup'][/fc] ``` Next, something has to trigger the form, you can create a button for that and then click it from jQury, edit the link which would trigger this form, and put the href or hyperlink to: ``` <a class="triggerForm" href="http://yoursite.com/form-view/12">Link Trigger</a> ``` jQuery trigger. ``` $(document).ready(function () { $('a.triggerForm').click(); }); ```
339,330
<p>I'm using the plugin <a href="https://wordpress.org/plugins/modern-events-calendar-lite/" rel="nofollow noreferrer">Modern Events Calendar Lite</a>.</p> <p>This is a recent plugin, so actually no doc exist.</p> <p>So i'm looking a way to display my upcoming events on homepage. But i can not make it to work, because start is stored in a second table.</p> <p>So i have a wpquery that list custom posts "mec-events", this is ok. But i'm not able to JOIN info to second table to get start_date &amp; to order posts on its value.</p> <p>I add you a capture of the second table wp-mec-dates &amp; events are store in wp-mec-events</p> <p><a href="https://i.stack.imgur.com/HUMhj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HUMhj.png" alt="enter image description here"></a></p> <p>Based on this tuto : <a href="https://www.ibenic.com/extending-wp-query-custom-queries-tables/" rel="nofollow noreferrer">Filtering the JOIN tables in WP_Query</a> exemple code : </p> <pre><code>add_filter( 'posts_join', 'add_other_table', 10, 2 ); /** * Joining another table and relating the column post_id with the Post's ID * * @param string $join String containing joins. * @param WP_Query $wp_query Object. * @return string */ function add_other_table( $join, $wp_query ) { global $wpdb; $join .= " JOIN {$wpdb-&gt;prefix}my_table as mytable on mytable.post_id = {$wpdb-&gt;posts}.ID "; return $join; } </code></pre> <p>i figure to do like this : </p> <pre><code>&lt;?php $args = array( 'post_type'=&gt; 'mec-events', 'orderby' =&gt; 'dstart', 'order' =&gt; 'ASC', ); add_filter( 'posts_join', 'add_other_table', 10, 2 ); function add_other_table( $join, $upcoming_events_query ) { global $wpdb; $join .= " JOIN {$wpdb-&gt;prefix}mec_dates as wp_mec_dates on wp_mec_dates.post_id = {$wpdb-&gt;posts}.ID "; return $join; } $upcoming_events_query = new WP_Query( $args ); if($upcoming_events_query-&gt;have_posts() ) { while ( $upcoming_events_query-&gt;have_posts() ) { $upcoming_events_query-&gt;the_post(); $image_url = get_the_post_thumbnail_url('','liste-etablissements'); $event_cities = get_field('contact_city',$post-&gt;ID); $start_date = get_field('dstart'); var_dump($start_date); ?&gt; &lt;div class="presta-img-home-events"&gt; &lt;?php if($image_url[0]) { ?&gt; &lt;img src="&lt;?php echo esc_url( $image_url ); ?&gt;" alt="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php } else { ?&gt; &lt;img src="&lt;?php echo get_template_directory_uri() . '/images/placeholder-blog.jpg'; ?&gt;" alt="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php } ?&gt; &lt;div class="presta-img-home-events-overlay"&gt;&lt;?php //echo $start_date; ?&gt; - &lt;?php if($event_cities) { $cities = 0; $max_cities = 1; foreach($event_cities as $event_city) { $cities++; if($cities &gt; $max_cities) { break; } echo ''. get_the_title( $event_city-&gt;ID ) .''; } } ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="featured-content-wrapper"&gt; &lt;h3 class="featured-title"&gt; &lt;a title="&lt;?php the_title_attribute(); ?&gt;" href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;!--&lt;a href="&lt;?php the_permalink(); ?&gt;" class="single_add_to_wishlist" &gt;&lt;?php esc_html_e('Découvrir','BeProvence'); ?&gt;&lt;i class="fa fa-heart"&gt;&lt;/i&gt;&lt;/a&gt;--&gt; &lt;/div&gt;&lt;!-- featured content wrapper --&gt; &lt;?php } } ?&gt; </code></pre> <p>But my var_dump() return "null". So i probably do something wrong. Any help will be apreciate !</p>
[ { "answer_id": 339438, "author": "Gregory", "author_id": 139936, "author_profile": "https://wordpress.stackexchange.com/users/139936", "pm_score": 2, "selected": true, "text": "<p>i have found a solution, making a custom SQL query </p>\n\n<p>here is the code ( using WPML ) </p>\n\n<pre><code> $startday = date(\"Y-m-d\");\n if ( defined( 'ICL_LANGUAGE_CODE' ) ) {\n $lang = ICL_LANGUAGE_CODE;\n } \n //echo $startday;\n global $wpdb,$post;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM wp_posts, `wp_mec_dates` AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND dstart&gt;'$startday' and wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart\" );\n foreach ($results as $post) {\n setup_postdata($post);\n $event_permalink = get_the_permalink();\n $event_date = $post-&gt;dstart; \n $new_event_date = date(\"d/m\", strtotime($event_date));\n $event_title = get_the_title();\n echo $new_event_date . ' - &lt;a href=\"'.$event_permalink.'\" title=\"'.$event_title.'\"&gt;' . substr($event_title,0,38) .'&lt;/a&gt;&lt;br /&gt;';\n }\n wp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 402407, "author": "Darko Mitrovic", "author_id": 187538, "author_profile": "https://wordpress.stackexchange.com/users/187538", "pm_score": 0, "selected": false, "text": "<pre><code>$args = array( \n 'posts_per_page' =&gt; 5, \n 'post_type' =&gt; 'mec-events', \n 'orderby' =&gt; 'mec_start_date', \n 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'mec_start_date',\n 'value' =&gt; date('Ymd'),\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'DATE'\n ),\n ),\n); \n</code></pre>\n" } ]
2019/06/01
[ "https://wordpress.stackexchange.com/questions/339330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/139936/" ]
I'm using the plugin [Modern Events Calendar Lite](https://wordpress.org/plugins/modern-events-calendar-lite/). This is a recent plugin, so actually no doc exist. So i'm looking a way to display my upcoming events on homepage. But i can not make it to work, because start is stored in a second table. So i have a wpquery that list custom posts "mec-events", this is ok. But i'm not able to JOIN info to second table to get start\_date & to order posts on its value. I add you a capture of the second table wp-mec-dates & events are store in wp-mec-events [![enter image description here](https://i.stack.imgur.com/HUMhj.png)](https://i.stack.imgur.com/HUMhj.png) Based on this tuto : [Filtering the JOIN tables in WP\_Query](https://www.ibenic.com/extending-wp-query-custom-queries-tables/) exemple code : ``` add_filter( 'posts_join', 'add_other_table', 10, 2 ); /** * Joining another table and relating the column post_id with the Post's ID * * @param string $join String containing joins. * @param WP_Query $wp_query Object. * @return string */ function add_other_table( $join, $wp_query ) { global $wpdb; $join .= " JOIN {$wpdb->prefix}my_table as mytable on mytable.post_id = {$wpdb->posts}.ID "; return $join; } ``` i figure to do like this : ``` <?php $args = array( 'post_type'=> 'mec-events', 'orderby' => 'dstart', 'order' => 'ASC', ); add_filter( 'posts_join', 'add_other_table', 10, 2 ); function add_other_table( $join, $upcoming_events_query ) { global $wpdb; $join .= " JOIN {$wpdb->prefix}mec_dates as wp_mec_dates on wp_mec_dates.post_id = {$wpdb->posts}.ID "; return $join; } $upcoming_events_query = new WP_Query( $args ); if($upcoming_events_query->have_posts() ) { while ( $upcoming_events_query->have_posts() ) { $upcoming_events_query->the_post(); $image_url = get_the_post_thumbnail_url('','liste-etablissements'); $event_cities = get_field('contact_city',$post->ID); $start_date = get_field('dstart'); var_dump($start_date); ?> <div class="presta-img-home-events"> <?php if($image_url[0]) { ?> <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php the_title_attribute(); ?>"> <?php } else { ?> <img src="<?php echo get_template_directory_uri() . '/images/placeholder-blog.jpg'; ?>" alt="<?php the_title_attribute(); ?>"> <?php } ?> <div class="presta-img-home-events-overlay"><?php //echo $start_date; ?> - <?php if($event_cities) { $cities = 0; $max_cities = 1; foreach($event_cities as $event_city) { $cities++; if($cities > $max_cities) { break; } echo ''. get_the_title( $event_city->ID ) .''; } } ?></div> </div> <div class="featured-content-wrapper"> <h3 class="featured-title"> <a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <!--<a href="<?php the_permalink(); ?>" class="single_add_to_wishlist" ><?php esc_html_e('Découvrir','BeProvence'); ?><i class="fa fa-heart"></i></a>--> </div><!-- featured content wrapper --> <?php } } ?> ``` But my var\_dump() return "null". So i probably do something wrong. Any help will be apreciate !
i have found a solution, making a custom SQL query here is the code ( using WPML ) ``` $startday = date("Y-m-d"); if ( defined( 'ICL_LANGUAGE_CODE' ) ) { $lang = ICL_LANGUAGE_CODE; } //echo $startday; global $wpdb,$post; $results = $wpdb->get_results( "SELECT * FROM wp_posts, `wp_mec_dates` AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND dstart>'$startday' and wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart" ); foreach ($results as $post) { setup_postdata($post); $event_permalink = get_the_permalink(); $event_date = $post->dstart; $new_event_date = date("d/m", strtotime($event_date)); $event_title = get_the_title(); echo $new_event_date . ' - <a href="'.$event_permalink.'" title="'.$event_title.'">' . substr($event_title,0,38) .'</a><br />'; } wp_reset_postdata(); ```
339,342
<p>been hacking at this for some time and haven't been able to make much progress. The goal is to add a custom body class to a specific page. -I know there are a few answered posts on this topic, and while the solution provided works if I add the custom body class globally, it fails when I add the if statement. Any ideas of what might prevent this from registering the custom body class?</p> <p>These Fail:</p> <pre><code>add_filter('body_class', 'custom_body_class'); function custom_body_class($classes) { if (is_page('shop')) $classes[] = 'services'; return $classes; } </code></pre> <p>Or</p> <pre><code>add_filter('body_class', 'custom_body_class'); function custom_body_class($classes) { if (is_page('4')) $classes[] = 'services'; return $classes; } </code></pre> <p>but this works, unfortunately globally:</p> <pre><code>add_filter('body_class', 'custom_body_class'); function custom_body_class($classes) { // if (is_page('shop')) $classes[] = 'services'; return $classes; } </code></pre> <p>I am on Genesis Framework, WPEngine, have WooCommerce and all are up to date. -Weird.</p>
[ { "answer_id": 339438, "author": "Gregory", "author_id": 139936, "author_profile": "https://wordpress.stackexchange.com/users/139936", "pm_score": 2, "selected": true, "text": "<p>i have found a solution, making a custom SQL query </p>\n\n<p>here is the code ( using WPML ) </p>\n\n<pre><code> $startday = date(\"Y-m-d\");\n if ( defined( 'ICL_LANGUAGE_CODE' ) ) {\n $lang = ICL_LANGUAGE_CODE;\n } \n //echo $startday;\n global $wpdb,$post;\n $results = $wpdb-&gt;get_results( \"SELECT * FROM wp_posts, `wp_mec_dates` AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND dstart&gt;'$startday' and wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart\" );\n foreach ($results as $post) {\n setup_postdata($post);\n $event_permalink = get_the_permalink();\n $event_date = $post-&gt;dstart; \n $new_event_date = date(\"d/m\", strtotime($event_date));\n $event_title = get_the_title();\n echo $new_event_date . ' - &lt;a href=\"'.$event_permalink.'\" title=\"'.$event_title.'\"&gt;' . substr($event_title,0,38) .'&lt;/a&gt;&lt;br /&gt;';\n }\n wp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 402407, "author": "Darko Mitrovic", "author_id": 187538, "author_profile": "https://wordpress.stackexchange.com/users/187538", "pm_score": 0, "selected": false, "text": "<pre><code>$args = array( \n 'posts_per_page' =&gt; 5, \n 'post_type' =&gt; 'mec-events', \n 'orderby' =&gt; 'mec_start_date', \n 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'mec_start_date',\n 'value' =&gt; date('Ymd'),\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'DATE'\n ),\n ),\n); \n</code></pre>\n" } ]
2019/06/01
[ "https://wordpress.stackexchange.com/questions/339342", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168423/" ]
been hacking at this for some time and haven't been able to make much progress. The goal is to add a custom body class to a specific page. -I know there are a few answered posts on this topic, and while the solution provided works if I add the custom body class globally, it fails when I add the if statement. Any ideas of what might prevent this from registering the custom body class? These Fail: ``` add_filter('body_class', 'custom_body_class'); function custom_body_class($classes) { if (is_page('shop')) $classes[] = 'services'; return $classes; } ``` Or ``` add_filter('body_class', 'custom_body_class'); function custom_body_class($classes) { if (is_page('4')) $classes[] = 'services'; return $classes; } ``` but this works, unfortunately globally: ``` add_filter('body_class', 'custom_body_class'); function custom_body_class($classes) { // if (is_page('shop')) $classes[] = 'services'; return $classes; } ``` I am on Genesis Framework, WPEngine, have WooCommerce and all are up to date. -Weird.
i have found a solution, making a custom SQL query here is the code ( using WPML ) ``` $startday = date("Y-m-d"); if ( defined( 'ICL_LANGUAGE_CODE' ) ) { $lang = ICL_LANGUAGE_CODE; } //echo $startday; global $wpdb,$post; $results = $wpdb->get_results( "SELECT * FROM wp_posts, `wp_mec_dates` AS mecd, wp_icl_translations WHERE wp_posts.ID = mecd.post_id and post_status='publish' AND wp_icl_translations.language_code='$lang' AND dstart>'$startday' and wp_posts.ID = wp_icl_translations.element_id ORDER BY dstart" ); foreach ($results as $post) { setup_postdata($post); $event_permalink = get_the_permalink(); $event_date = $post->dstart; $new_event_date = date("d/m", strtotime($event_date)); $event_title = get_the_title(); echo $new_event_date . ' - <a href="'.$event_permalink.'" title="'.$event_title.'">' . substr($event_title,0,38) .'</a><br />'; } wp_reset_postdata(); ```
339,356
<p>I am working on a plugin that handles logic for when a user tries to checkout on the frontend and the order fails (e.g., person is using a credit card but it does not have enough balance to meet the cart totals, etc). I can see the order is in fact set as "FAILED" in WooCommerce, because I get the automated email from WC alerting admin of a failed order. I'm spending a lot of time testing out various actions and filters, and hoping someone could point me in the right direction.</p>
[ { "answer_id": 339357, "author": "gdarko", "author_id": 73926, "author_profile": "https://wordpress.stackexchange.com/users/73926", "pm_score": 2, "selected": true, "text": "<p>You can catch specific status change by using this action hook 'woocommerce_order_status_{status}'. It is defined in the <a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-order.php\" rel=\"nofollow noreferrer\">WC_Order class</a>.</p>\n\n<p>This is how you define it:</p>\n\n<pre><code>/**\n * Executed when the status is changed to failed.\n * @param int $order_id\n * @param \\WC_Order $order\n */\nfunction wpdg_9291_woocommerce_order_status_failed( $order_id, $order ) {\n // Do something here\n}\nadd_action('woocommerce_order_status_failed', 'wpdg_9291_woocommerce_order_status_failed', 15, 2);\n</code></pre>\n" }, { "answer_id": 339360, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 0, "selected": false, "text": "<p>When customer returns from a gateway without paying, it falls on order received <em>(thankyou)</em> page with 2 possible status: <code>failed</code> or <code>pending</code>, and there is 2 possible action hooks:</p>\n\n<ul>\n<li><code>woocommerce_thankyou_{$order_payment_method}</code> <em>(composite hook with <code>$order_id</code> available argument)</em></li>\n<li><code>woocommerce_thankyou</code> <em>(with <code>$order_id</code> available argument)</em></li>\n</ul>\n\n<p>You can target that case with the following example:</p>\n\n<pre><code>add_action( 'woocommerce_thankyou', 'thankyou_action_callback', 10, 1 );\nfunction thankyou_action_callback( $order_id ) {\n // Get an instance of the WC_Order Object\n $order = wc_get_order( $order_id );\n\n if( in_array( $order-&gt;get_status(), ['failed','pending'] ) ) {\n // Your code comes here\n }\n}\n</code></pre>\n" } ]
2019/06/01
[ "https://wordpress.stackexchange.com/questions/339356", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1354/" ]
I am working on a plugin that handles logic for when a user tries to checkout on the frontend and the order fails (e.g., person is using a credit card but it does not have enough balance to meet the cart totals, etc). I can see the order is in fact set as "FAILED" in WooCommerce, because I get the automated email from WC alerting admin of a failed order. I'm spending a lot of time testing out various actions and filters, and hoping someone could point me in the right direction.
You can catch specific status change by using this action hook 'woocommerce\_order\_status\_{status}'. It is defined in the [WC\_Order class](https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-order.php). This is how you define it: ``` /** * Executed when the status is changed to failed. * @param int $order_id * @param \WC_Order $order */ function wpdg_9291_woocommerce_order_status_failed( $order_id, $order ) { // Do something here } add_action('woocommerce_order_status_failed', 'wpdg_9291_woocommerce_order_status_failed', 15, 2); ```
339,364
<p>I have a problem with my WordPress site, it is working well until today.</p> <p>The problem is when I type my domain name it is redirecting to wp-admin/setup-config.php file. I have no idea why this is happening. The site works fine before.</p> <p>On domain/wp-admin/setup-config.php page shows a message</p> <blockquote> <p>"This page isn’t working www.domain.com is currently unable to handle this request. HTTP ERROR 500"</p> </blockquote>
[ { "answer_id": 358857, "author": "user182877", "author_id": 182877, "author_profile": "https://wordpress.stackexchange.com/users/182877", "pm_score": 0, "selected": false, "text": "<p>I have crossed the same issue.</p>\n\n<p>First, you need to clear your browser cache and deactivate all the plugins related to cache and page preload to your website. Then open your config.php and insert these commands before the line <code>/* That's all, stop editing! Happy publishing. */</code></p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n\n<p>Worked for me.</p>\n" }, { "answer_id": 392883, "author": "Masoud Tavakkoli", "author_id": 204146, "author_profile": "https://wordpress.stackexchange.com/users/204146", "pm_score": 1, "selected": false, "text": "<p>In my case there was a permission problem. I solved with this commands.</p>\n<pre><code>chown www-data:www-data -R * # Let Apache be owner\nfind . -type d -exec chmod 755 {} \\; # Change directory permissions rwxr-xr-x\nfind . -type f -exec chmod 644 {} \\; # Change file permissions rw-r--r--\n</code></pre>\n" } ]
2019/06/02
[ "https://wordpress.stackexchange.com/questions/339364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165090/" ]
I have a problem with my WordPress site, it is working well until today. The problem is when I type my domain name it is redirecting to wp-admin/setup-config.php file. I have no idea why this is happening. The site works fine before. On domain/wp-admin/setup-config.php page shows a message > > "This page isn’t working www.domain.com is currently unable to handle > this request. HTTP ERROR 500" > > >
In my case there was a permission problem. I solved with this commands. ``` chown www-data:www-data -R * # Let Apache be owner find . -type d -exec chmod 755 {} \; # Change directory permissions rwxr-xr-x find . -type f -exec chmod 644 {} \; # Change file permissions rw-r--r-- ```
339,375
<p>I create a file name <code>custom.php</code> which is like below:</p> <pre><code>class customClass{ function dothisfunction( $mobiles , $message ){ //use parameters } } </code></pre> <p>In my <code>function.php</code> file I add the following code:</p> <pre><code>$number = '09112223344'; $mymsg = 'nadia is testing'; $myClass = new customClass(); add_action( 'publish_post', array( $myClass ,'dothisfunction', $number, $mymsg ) ); </code></pre> <p>but it returns error, the error is :</p> <blockquote> <p><strong>PHP Warning</strong>: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in C:\xampp\htdocs\wp-includes\class-wp-hook.php on line 288</p> </blockquote> <p>How can I solve it? Can anyone help me?</p>
[ { "answer_id": 339377, "author": "gdarko", "author_id": 73926, "author_profile": "https://wordpress.stackexchange.com/users/73926", "pm_score": 3, "selected": true, "text": "<p>The <code>publish_post</code> post takes two arguments first is <code>$ID</code> of the post that is being published and the second is the <code>$post</code> instance (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow noreferrer\">See codex</a>). I modified your code a bit below.</p>\n\n<p>Your class is almost identical just renamed the parameters of the function to not cause confusion.</p>\n\n<pre><code>class customClass{ \n function dothisfunction( $ID, $post ){\n echo \"something\";\n }\n }\n</code></pre>\n\n<p>No need for the <code>$number</code> and <code>$mymsg</code> in the array() because you only need to specify instance and the method to be used of the instance.</p>\n\n<pre><code>$myClass = new customClass();\nadd_action( 'publish_post', array( $myClass ,'dothisfunction' ), 10, 2 );\n</code></pre>\n\n<p>Also, you should specify how much parameters you are passing to <code>dothisfunction</code> in <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action</a> as 4th parameter.</p>\n" }, { "answer_id": 339380, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": false, "text": "<p>To hook your method <code>dothisfunction</code> to action <code>publish_post</code>, you should use <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action()</code></a> this way:</p>\n\n<pre><code>$myClass = new customClass();\nadd_action( 'publish_post', array( $myClass, 'dothisfunction' ), 10, 2 );\n</code></pre>\n\n<p>The number of arguments accepted by the function is specified in the 4th parameter of <code>add_action()</code>. </p>\n\n<p>However, this number can not be greater than the number of arguments passed in <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\"><code>do_action()</code></a>, because it is the <strong><code>do_action()</code></strong> that <strong>decides how many and what arguments</strong> will be passed to the functions hooked to specific action hook. </p>\n\n<p>More about actions you can read <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2019/06/02
[ "https://wordpress.stackexchange.com/questions/339375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169303/" ]
I create a file name `custom.php` which is like below: ``` class customClass{ function dothisfunction( $mobiles , $message ){ //use parameters } } ``` In my `function.php` file I add the following code: ``` $number = '09112223344'; $mymsg = 'nadia is testing'; $myClass = new customClass(); add_action( 'publish_post', array( $myClass ,'dothisfunction', $number, $mymsg ) ); ``` but it returns error, the error is : > > **PHP Warning**: call\_user\_func\_array() expects parameter 1 to be a valid callback, array must have exactly two members in C:\xampp\htdocs\wp-includes\class-wp-hook.php on line 288 > > > How can I solve it? Can anyone help me?
The `publish_post` post takes two arguments first is `$ID` of the post that is being published and the second is the `$post` instance ([See codex](https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post)). I modified your code a bit below. Your class is almost identical just renamed the parameters of the function to not cause confusion. ``` class customClass{ function dothisfunction( $ID, $post ){ echo "something"; } } ``` No need for the `$number` and `$mymsg` in the array() because you only need to specify instance and the method to be used of the instance. ``` $myClass = new customClass(); add_action( 'publish_post', array( $myClass ,'dothisfunction' ), 10, 2 ); ``` Also, you should specify how much parameters you are passing to `dothisfunction` in [add\_action](https://developer.wordpress.org/reference/functions/add_action/) as 4th parameter.
339,395
<p>I'm working on a plugin that fetches remote RSS feeds using <code>wp_remote_get</code>. The problem is that Tumblr requires a cookie for GDPR compliance. This includes RSS feeds. Which means all Tumblr feeds are currently broken.</p> <p>I found <a href="https://github.com/Arvedui/tt-rss-tumblr-gdpr" rel="nofollow noreferrer">an example of using CURL to acquire the cookies</a> so the feed will load. However, I have little more than a passing acquaintance with <code>wp_remote_get</code> and related functions.</p> <p>How do I implement the cookie getting hack from the example via WordPress' remote get methodology?</p> <p><strong>Edit</strong>: To clarify, I need to <em>get</em> and then use a cookie. That's two requests; one for the cookie and a second using the cookie.</p>
[ { "answer_id": 339481, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": false, "text": "<p>The arguments array for <code>wp_remote_get</code> accepts a <code>cookies</code> parameter:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$cookies = [];\n$cookie = new WP_Http_Cookie( 'cookie_name' );\n$cookie-&gt;name = 'cookie_name';\n$cookie-&gt;value = 'your cookie value';\n$cookie-&gt;expires = 7 * DAY_IN_SECONDS; // expires in 7 days\n$cookie-&gt;path = '/';\n$cookie-&gt;domain = '.reddit.com';\n$cookies[] = $cookie;\n\n$url = 'https://tumblr.com/some/url/';\n\n$args = [\n 'cookies' =&gt; $cookies,\n];\n\n$response = wp_remote_get( $url, $args );\n</code></pre>\n" }, { "answer_id": 375078, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 1, "selected": false, "text": "<p>Going off of @phatskat answer, you can also pass the values in the constructor as well, and example from WooCommerce is as follows:</p>\n<pre><code>$cookies = [];\n$cookies[] = new WP_Http_Cookie( array(\n 'name' =&gt; $name,\n 'value' =&gt; $value,\n));\n\n\n$args = [\n 'cookies' =&gt; $cookies,\n];\n\n$response = wp_remote_get( $url, $args );\n</code></pre>\n<p>Looking at core code though, there is a method to build the cookies when a request is made (@since 2.8.0):\n<a href=\"https://github.com/WordPress/WordPress/blob/f547eb617441853b6e316c6f127a2182c12925e3/wp-includes/class-http.php#L775-L797\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/f547eb617441853b6e316c6f127a2182c12925e3/wp-includes/class-http.php#L775-L797</a></p>\n<p>When CURL or STREAM request is made:\n<a href=\"https://github.com/WordPress/WordPress/blob/57a3f803ae67814b2639ab8816d59c5fa5add441/wp-includes/class-wp-http-curl.php#L93\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/57a3f803ae67814b2639ab8816d59c5fa5add441/wp-includes/class-wp-http-curl.php#L93</a></p>\n" } ]
2019/06/02
[ "https://wordpress.stackexchange.com/questions/339395", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
I'm working on a plugin that fetches remote RSS feeds using `wp_remote_get`. The problem is that Tumblr requires a cookie for GDPR compliance. This includes RSS feeds. Which means all Tumblr feeds are currently broken. I found [an example of using CURL to acquire the cookies](https://github.com/Arvedui/tt-rss-tumblr-gdpr) so the feed will load. However, I have little more than a passing acquaintance with `wp_remote_get` and related functions. How do I implement the cookie getting hack from the example via WordPress' remote get methodology? **Edit**: To clarify, I need to *get* and then use a cookie. That's two requests; one for the cookie and a second using the cookie.
The arguments array for `wp_remote_get` accepts a `cookies` parameter: ```php $cookies = []; $cookie = new WP_Http_Cookie( 'cookie_name' ); $cookie->name = 'cookie_name'; $cookie->value = 'your cookie value'; $cookie->expires = 7 * DAY_IN_SECONDS; // expires in 7 days $cookie->path = '/'; $cookie->domain = '.reddit.com'; $cookies[] = $cookie; $url = 'https://tumblr.com/some/url/'; $args = [ 'cookies' => $cookies, ]; $response = wp_remote_get( $url, $args ); ```
339,413
<p>Good day! </p> <p>How do you properly migrate your localhost wordpress file to a live server? What I do is usually copy all my wordpress file then transferred to my website thru FTP and the database is usually imported to the target sql.</p> <p>The problem is when I do this, the website layout gets all messed up. I wanted to migrate my website without the layout being affected. </p> <p>Thanks.</p>
[ { "answer_id": 339417, "author": "magefms", "author_id": 157832, "author_profile": "https://wordpress.stackexchange.com/users/157832", "pm_score": 0, "selected": false, "text": "<p>Make sure to also change the <strong>site URL</strong> in your database under the <strong>wp_options</strong> table. And it should work. </p>\n" }, { "answer_id": 339432, "author": "WSU", "author_id": 168474, "author_profile": "https://wordpress.stackexchange.com/users/168474", "pm_score": 0, "selected": false, "text": "<p>I always recommend <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/duplicator/</a> to move your entire site. It makes the process really easy and also takes care of any database replacements needed during migration.</p>\n" }, { "answer_id": 339473, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 3, "selected": true, "text": "<p>You can use the <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">WP CLI</a> too to rename your site's hostname safely and effectively. There's a chance that your layout is being messed up because naively replacing the domain name with a simple string replace, e.g. <code>perl -pi -e 's/oldhost/newhost/g' backup.sql</code>, will not take into account things like serialized data.</p>\n\n<p>Try this on your local machine after install WP-CLI:</p>\n\n<h3>Using the <code>db-checkpoint</code> package:</h3>\n\n<pre class=\"lang-sh prettyprint-override\"><code>wp package install binarygary/db-checkpoint\nwp dbsnap pre-search-replace\nwp search-replace --precise oldhost newhost\nwp dbsnap post-search-replace\nwp dbsnapback pre-search-replace\n</code></pre>\n\n<p>Now, take the file in <code>wp-content/uploads/checkpoint-storage</code> that starts with <code>post-search-replace</code> and import that to your remote host.</p>\n\n<h3>Without <code>db-checkpoint</code>:</h3>\n\n<pre class=\"lang-sh prettyprint-override\"><code># Backup your database here, this will be restored to your local once the\n# operation is done\nwp search-replace --precise oldhost newhost\n# Take another backup now - this backup will go to your remote server\n# Now, restore your original backup to have your local in a working state...\n# OR do this:\nwp search-replace --precise newhost oldhost\n</code></pre>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162882/" ]
Good day! How do you properly migrate your localhost wordpress file to a live server? What I do is usually copy all my wordpress file then transferred to my website thru FTP and the database is usually imported to the target sql. The problem is when I do this, the website layout gets all messed up. I wanted to migrate my website without the layout being affected. Thanks.
You can use the [WP CLI](https://wp-cli.org/) too to rename your site's hostname safely and effectively. There's a chance that your layout is being messed up because naively replacing the domain name with a simple string replace, e.g. `perl -pi -e 's/oldhost/newhost/g' backup.sql`, will not take into account things like serialized data. Try this on your local machine after install WP-CLI: ### Using the `db-checkpoint` package: ```sh wp package install binarygary/db-checkpoint wp dbsnap pre-search-replace wp search-replace --precise oldhost newhost wp dbsnap post-search-replace wp dbsnapback pre-search-replace ``` Now, take the file in `wp-content/uploads/checkpoint-storage` that starts with `post-search-replace` and import that to your remote host. ### Without `db-checkpoint`: ```sh # Backup your database here, this will be restored to your local once the # operation is done wp search-replace --precise oldhost newhost # Take another backup now - this backup will go to your remote server # Now, restore your original backup to have your local in a working state... # OR do this: wp search-replace --precise newhost oldhost ```
339,436
<p>When the <strong>Block Editor</strong> was added to WordPress, custom and core meta boxes became legacy, meaning, using the <a href="https://developer.wordpress.org/reference/functions/remove_meta_box/" rel="noreferrer">remove_meta_box()</a> function won't work when removing meta boxes/panels displayed on the post editing screen.</p> <p>So, how do we remove the <code>Excerpt</code> panel when we can't use <code>remove_meta_box()</code> anymore?</p>
[ { "answer_id": 339437, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 6, "selected": true, "text": "<p>The <code>remove_meta_box()</code> function will not work with the Block Editor, because these are now <em>Panels</em> and work differently. There is currently no documentation on how to disable Panels, but, <em>let's dance</em>.</p>\n<p>We want to avoid <em>hiding</em> panels via CSS, and rely on the JS API.</p>\n<p>We need to use the JS function <code>removeEditorPanel()</code> which will completely remove the panel with all its controls:</p>\n<pre><code>// remove excerpt panel\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'post-excerpt' );\n</code></pre>\n<p>Here is an (incomplete) list of panel IDs:</p>\n<ul>\n<li><code>taxonomy-panel-category</code> - <strong>Category</strong> panel.</li>\n<li><code>taxonomy-panel-CUSTOM-TAXONOMY-NAME</code> - <strong>Custom taxonomy</strong> panel. If your taxonomy is <code>topic</code>, then <code>taxonomy-panel-topic</code> works.</li>\n<li><code>taxonomy-panel-post_tag</code> - <strong>Tags</strong> panel</li>\n<li><code>featured-image</code> - <strong>Featured image</strong> panel.</li>\n<li><code>post-link</code> - <strong>Permalink</strong> panel.</li>\n<li><code>page-attributes</code> - <strong>Page attributes</strong> panel.</li>\n<li><code>post-excerpt</code> - Post <strong>excerpt</strong> panel.</li>\n<li><code>discussion-panel</code> - <strong>Discussions</strong> panel.</li>\n<li><code>template</code> - <strong>Template</strong> panel added with WP 5.9.</li>\n</ul>\n<h2>The full code</h2>\n<p>PHP (in your <code>functions.php</code> or custom plugin):</p>\n<pre><code>function cc_gutenberg_register_files() {\n // script file\n wp_register_script(\n 'cc-block-script',\n get_stylesheet_directory_uri() .'/js/block-script.js', // adjust the path to the JS file\n array( 'wp-blocks', 'wp-edit-post' )\n );\n // register block editor script\n register_block_type( 'cc/ma-block-files', array(\n 'editor_script' =&gt; 'cc-block-script'\n ) );\n\n}\nadd_action( 'init', 'cc_gutenberg_register_files' );\n</code></pre>\n<p>The JS file (<code>block-script.js</code>):</p>\n<pre><code>wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'taxonomy-panel-category' ) ; // category\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'taxonomy-panel-TAXONOMY-NAME' ) ; // custom taxonomy\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'taxonomy-panel-post_tag' ); // tags\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'featured-image' ); // featured image\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'post-link' ); // permalink\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'page-attributes' ); // page attributes\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'post-excerpt' ); // Excerpt\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'discussion-panel' ); // Discussion\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'template' ); // Template\n</code></pre>\n<h2>How about other panels?</h2>\n<p>If you know the ID of other panel than the ones listed above, please leave a comment.</p>\n<p>On some panels, there is the alternative to to <em>hide</em> the panel via CSS. For example, to hide the <code>Revisions</code> panel, we can use:</p>\n<pre><code>.components-panel__body.edit-post-last-revision__panel {\n display:none !important;\n}\n</code></pre>\n<p>Inspect the element of the panel to located the class name (<code>edit-post-last-revision__panel</code>). Note that some panels do not have unique class names.</p>\n<p>So, register you block style:</p>\n<pre><code>wp_register_style(\n 'cc-block-style',\n get_stylesheet_directory_uri() .'/inc/block-style.css', // adjust file path\n array( 'wp-edit-blocks' )\n);\n\nregister_block_type( 'cc/ma-block-files', array(\n 'editor_style' =&gt; 'cc-block-style',\n) );\n</code></pre>\n<p>And include your CSS code into the <code>block-style.css</code> file.</p>\n" }, { "answer_id": 342181, "author": "Krzysztof Chodera", "author_id": 170719, "author_profile": "https://wordpress.stackexchange.com/users/170719", "pm_score": 2, "selected": false, "text": "<p>To hide meta_box from <em>Block Editor</em> and display them <strong>only</strong> in classic editor add arg <code>__back_compat_meta_box</code> set to true when adding meta box</p>\n\n<pre><code>add_meta_box( 'my-meta-box', 'My Meta Box', 'my_meta_box_callback',\n null, 'normal', 'high',\n array(\n '__back_compat_meta_box' =&gt; true,\n )\n); \n</code></pre>\n" }, { "answer_id": 349926, "author": "Philipp", "author_id": 31140, "author_profile": "https://wordpress.stackexchange.com/users/31140", "pm_score": 3, "selected": false, "text": "<p>Addition to Christine Coopers answer <a href=\"https://wordpress.stackexchange.com/a/339437/31140\">https://wordpress.stackexchange.com/a/339437/31140</a></p>\n\n<h2>How to remove non-core meta boxes</h2>\n\n<p>If you want to remove panels that were added by themes or plugins, proceed like this:</p>\n\n<ol>\n<li>Find the <strong>PANEL-ID</strong> by inspecting the HTML code:<br>\nRun <code>jQuery('.postbox')</code> in your browsers JS console.<br>\njQuery will find all custom meta boxes for you!<br>\nYou need to identify the correct box and copy the element ID.\n<a href=\"https://i.stack.imgur.com/MkxPx.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MkxPx.png\" alt=\"Find the Panel-ID\"></a></li>\n<li>The internal panel ID of the meta box is <strong><code>meta-box-&lt;PANEL-ID&gt;</code></strong></li>\n</ol>\n\n<h3>Example</h3>\n\n<pre><code>// Remove the DIVI meta-box:\nvar boxId = 'et_settings_meta_box_gutenberg';\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'meta-box-' + boxId );\n\n// Remove an ACF meta-box:\nvar boxId = 'acf-group_5d9b020a3db4e';\nwp.data.dispatch( 'core/edit-post').removeEditorPanel( 'meta-box-' + boxId );\n</code></pre>\n\n<hr>\n\n<h2>How to remove core panels</h2>\n\n<p>See Christine Coopers answer <a href=\"https://wordpress.stackexchange.com/a/339437/31140\">https://wordpress.stackexchange.com/a/339437/31140</a></p>\n" }, { "answer_id": 383584, "author": "Makoto", "author_id": 202098, "author_profile": "https://wordpress.stackexchange.com/users/202098", "pm_score": 0, "selected": false, "text": "<p>This one worked for me.</p>\n<pre><code>function remove_post_support() {\n remove_post_type_support('post','excerpt'); \n}\nadd_action('init','remove_post_support');\n</code></pre>\n" }, { "answer_id": 407549, "author": "svyazy", "author_id": 223937, "author_profile": "https://wordpress.stackexchange.com/users/223937", "pm_score": 2, "selected": false, "text": "<p>And this is how to get a list of core panel IDs:</p>\n<pre><code>wp.data.select( 'core/edit-post' ).getPreferences().panels;\n</code></pre>\n" }, { "answer_id": 408281, "author": "user18365616", "author_id": 224646, "author_profile": "https://wordpress.stackexchange.com/users/224646", "pm_score": 0, "selected": false, "text": "<p>I found a faster solution, you can just add this functions in php.\nThis for example disables tags:</p>\n<pre><code>add_action('admin_head', 'webroom_add_css_js_to_admin');\nfunction webroom_add_css_js_to_admin() {\n echo '&lt;script&gt;\n wp.domReady( () =&gt; {\n const { removeEditorPanel } = wp.data.dispatch(&quot;core/edit-post&quot;);\n // Remove featured image panel from sidebar.\n removeEditorPanel( &quot;taxonomy-panel-post_tag&quot; );\n } );\n &lt;/script&gt;';\n}\n</code></pre>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339436", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24875/" ]
When the **Block Editor** was added to WordPress, custom and core meta boxes became legacy, meaning, using the [remove\_meta\_box()](https://developer.wordpress.org/reference/functions/remove_meta_box/) function won't work when removing meta boxes/panels displayed on the post editing screen. So, how do we remove the `Excerpt` panel when we can't use `remove_meta_box()` anymore?
The `remove_meta_box()` function will not work with the Block Editor, because these are now *Panels* and work differently. There is currently no documentation on how to disable Panels, but, *let's dance*. We want to avoid *hiding* panels via CSS, and rely on the JS API. We need to use the JS function `removeEditorPanel()` which will completely remove the panel with all its controls: ``` // remove excerpt panel wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'post-excerpt' ); ``` Here is an (incomplete) list of panel IDs: * `taxonomy-panel-category` - **Category** panel. * `taxonomy-panel-CUSTOM-TAXONOMY-NAME` - **Custom taxonomy** panel. If your taxonomy is `topic`, then `taxonomy-panel-topic` works. * `taxonomy-panel-post_tag` - **Tags** panel * `featured-image` - **Featured image** panel. * `post-link` - **Permalink** panel. * `page-attributes` - **Page attributes** panel. * `post-excerpt` - Post **excerpt** panel. * `discussion-panel` - **Discussions** panel. * `template` - **Template** panel added with WP 5.9. The full code ------------- PHP (in your `functions.php` or custom plugin): ``` function cc_gutenberg_register_files() { // script file wp_register_script( 'cc-block-script', get_stylesheet_directory_uri() .'/js/block-script.js', // adjust the path to the JS file array( 'wp-blocks', 'wp-edit-post' ) ); // register block editor script register_block_type( 'cc/ma-block-files', array( 'editor_script' => 'cc-block-script' ) ); } add_action( 'init', 'cc_gutenberg_register_files' ); ``` The JS file (`block-script.js`): ``` wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'taxonomy-panel-category' ) ; // category wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'taxonomy-panel-TAXONOMY-NAME' ) ; // custom taxonomy wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'taxonomy-panel-post_tag' ); // tags wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'featured-image' ); // featured image wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'post-link' ); // permalink wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'page-attributes' ); // page attributes wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'post-excerpt' ); // Excerpt wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'discussion-panel' ); // Discussion wp.data.dispatch( 'core/edit-post').removeEditorPanel( 'template' ); // Template ``` How about other panels? ----------------------- If you know the ID of other panel than the ones listed above, please leave a comment. On some panels, there is the alternative to to *hide* the panel via CSS. For example, to hide the `Revisions` panel, we can use: ``` .components-panel__body.edit-post-last-revision__panel { display:none !important; } ``` Inspect the element of the panel to located the class name (`edit-post-last-revision__panel`). Note that some panels do not have unique class names. So, register you block style: ``` wp_register_style( 'cc-block-style', get_stylesheet_directory_uri() .'/inc/block-style.css', // adjust file path array( 'wp-edit-blocks' ) ); register_block_type( 'cc/ma-block-files', array( 'editor_style' => 'cc-block-style', ) ); ``` And include your CSS code into the `block-style.css` file.
339,449
<p>Actually im stuck on this!</p> <ul> <li>XML-File ~ 140.000 Rows</li> <li>Filesize ~ 9.0 MB</li> <li><code>LOAD XML INFILE 'file_name'</code> isnt't allowed ( shared hosting! )</li> </ul> <p>The supplier provides a single XML file with quantity and sku. The XML is formatted like:</p> <pre class="lang-xml prettyprint-override"><code>&lt;item&gt; &lt;LITM&gt;0000001&lt;/LITM&gt; &lt;STQU&gt;1&lt;STQU&gt; &lt;/item&gt; &lt;item&gt; &lt;LITM&gt;0000002&lt;/LITM&gt; &lt;STQU&gt;4&lt;STQU&gt; &lt;/item&gt; </code></pre> <p>The following function works, but as you can think about - its slow!</p> <pre class="lang-php prettyprint-override"><code>function load_xml2mysql($filename,$type) { global $wpdb; $file = XML_DIR.$filename; $xml = new XMLReader(); $xml-&gt;open($file); $charset = $wpdb-&gt;get_charset_collate(); $table = $wpdb-&gt;prefix.'supplier_stock'; ignore_user_abort(); while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; } while($xml-&gt;name == 'item') { $element = new SimpleXMLElement($xml-&gt;readOuterXML()); $query = $wpdb-&gt;prepare("INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d", strval($element-&gt;LITM),strval($element-&gt;STQU),strval($element-&gt;STQU)); $wpdb-&gt;query( $query ); $wpdb-&gt;flush(); $xml-&gt;next('item'); unset($element); } } </code></pre> <p>I've read alot about batch/bulk insert and the benchmarks are very clear on this. Querying 140.000 rows with my function is done in average 40 seconds. The Stock table is the smallest one from a set of three XML files, imagine inserting the main product data with a total filesize ~ 145.0 MB maybe put me in some trouble?</p> <p>Any Ideas on this how to improve or batch insert?</p>
[ { "answer_id": 339459, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>First of all: don't flush after every insert. I did not test this, but it should be faster if you import all the data, then do the flush.</p>\n\n<p>Second: What exactly do you want to accomplish? A onetime Import, or a regular update to your database?\nIf you need option a), then take the waiting. Maybe increase the PHP Maximum Runtime if you need to.</p>\n\n<p>If you want to regularly update your database, then you maybe should go for another approach. Like, first reading your XML File and converting it into an array/put it into a temporary database table, check if the article must be added or updated, then in a third step complete it by adding the new articles and updating the articles to be updated.</p>\n\n<p>Happy Coding! </p>\n" }, { "answer_id": 339469, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": false, "text": "<p>You can try to mitigate memory issues by using a <a href=\"https://www.php.net/manual/en/language.generators.overview.php\" rel=\"nofollow noreferrer\">Generator</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function load_xml2mysql($filename,$type) {\n global $wpdb;\n\n $charset = $wpdb-&gt;get_charset_collate();\n $table = $wpdb-&gt;prefix.'supplier_stock';\n\n ignore_user_abort();\n\n $query_template = &quot;INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d&quot;;\n $wpdb-&gt;query( 'SET autocommit = 0' );\n foreach ( get_xml_element( $filename ) as $element ) {\n $query = $wpdb-&gt;prepare(\n $query_template,\n strval($element-&gt;LITM),\n strval($element-&gt;STQU),\n strval($element-&gt;STQU)\n );\n\n $wpdb-&gt;query( $query );\n }\n $wpdb-&gt;query( 'COMMIT' );\n}\n\nfunction get_xml_element( $filename ) {\n $file = XML_DIR.$filename;\n $xml = new XMLReader();\n $xml-&gt;open($file);\n\n // I'm not clear on what exactly this is doing, do you need it?\n // edit: this moves us to the first &lt;item&gt; node \n while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; }\n\n while ( $xml-&gt;name === 'item' ) {\n yield new SimpleXMLElement( $xml-&gt;readOuterXML() );\n $xml-&gt;next('item');\n }\n}\n</code></pre>\n<p>Generators tend to be more efficient than just doing a loop, and in a case like this it may be what you need.</p>\n<p>We're also doing <code>SET autocommit=0</code> before you run your queries, this should provide some performance boost as you're telling MySQL not to commit the changes until we call <code>COMMIT</code> after the loop.</p>\n" }, { "answer_id": 339644, "author": "click here", "author_id": 169354, "author_profile": "https://wordpress.stackexchange.com/users/169354", "pm_score": 2, "selected": false, "text": "<p>After facing problems with exhausted memory and time consuming queries i've tried a different way bulk importing. The idea isn't new but but to show a possible way i want to share my solution. Keep in mind, i'm not a professional in PHP/MySQL, so maybe there is a more effective or better way to accomplish this task in different manner or with better performance</p>\n\n<h1>Main function to BULK INSERT with $wpdb</h1>\n\n<p>Since @kuchenundkakao pushed me some new ideas using a temporary table to import the whole XML file and processing the data from in a second query. In Conclusion, the bulk_insert function didn't check for any existing data or updating them, the table gets <code>truncated</code> every 24hrs after processing is done.</p>\n\n<p>It's used in PHP Class, so be aware if you try to just copy and paste - check the syntax!</p>\n\n<pre>\n// Table, including your prefix!\n$table = $wpdb->prefix.'table_name';\n\n$rows = array(\n array('price' => '12.00','vat' => '7.7'),\n array('price' => '230.00', 'vat' => '7.7')\n );\n</pre>\n\n<p>content of my <code>bulk_insert</code> function. </p>\n\n<pre><code> function bulk_insert($table, $rows) {\n global $wpdb;\n\n /* Extract column list from first row of data! */ \n $columns = array_keys($rows[0]);\n asort($columns);\n $columnList = '`' . implode('`, `', $columns) . '`';\n\n /* Start building SQL, initialise data and placeholder arrays */\n $sql = \"INSERT INTO `$table` ($columnList) VALUES\\n\";\n $placeholders = array();\n $data = array();\n\n /* Build placeholders for each row, and add values to data array */\n foreach ($rows as $row) {\n ksort($row);\n $rowPlaceholders = array();\n foreach ($row as $key =&gt; $value) {\n $data[] = $value;\n\n /* differentiate values and set placeholders */\n if (is_numeric($value)) {\n $rowPlaceholders[] = is_float($value) ? '%f' : '%d';\n } else {\n $rowPlaceholders[] = '%s';\n }\n }\n $placeholders[] = '(' . implode(', ', $rowPlaceholders) . ')';\n }\n\n /* Stitching all rows together */\n $sql .= implode(\",\\n\", $placeholders);\n // Run the query. Returning number of affected rows for this chunk\n return $wpdb-&gt;query($wpdb-&gt;prepare($sql, $data));\n }\n</code></pre>\n\n<h1>Chunking XML Data</h1>\n\n<p>It's really different how much data you can push to <code>bulk_insert()</code> and depends alot on your hosting/server - so i've made it flexible and easy to adjust by limitting the amount of data before it's send to <code>bulk_insert()</code>. </p>\n\n<p><strong>What is this function doing?</strong>\nIt's using XMLReader and SimpleXMLElement to parse the XML Document Line-by-Line instead parsing the whole document ( which mostly ends in exhausted memory ). After a given amount set by <code>$limit</code> of XML Elements in <code>$array[]</code> is reached, the function sends this chunk of your XML file as an array to <code>bulk_insert()</code> -> stamps the whole array into your database. </p>\n\n<p>I'm passing a filename to <code>load_price_xml2mysql</code> for flexibility purposes like <code>myfile.xml</code></p>\n\n<pre><code>function load_price_xml2mysql($filename) {\n global $wpdb;\n\n /* get xml file */\n\n $file = WP_UPLOAD_DIR.$filename;\n $xml = new XMLReader();\n $xml-&gt;open($file);\n\n /* set your limit here, define the limit in your plugin or just add $limit = 1000 */\n $limit = MYSQL_PRICE_INSERTLIMIT;\n\n $array = array();\n $table = $wpdb-&gt;prefix.'temp_api_price';\n\n /* counting entries, so we have to set zero before while */\n $i = 0;\n while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; }\n while ( $xml-&gt;name === 'item' ) {\n ++$i;\n\n $element = new SimpleXMLElement( $xml-&gt;readOuterXML() );\n $array[] = array(\n 'sku' =&gt; intval($element-&gt;SKU),\n 'buying' =&gt; floatval($element-&gt;price-&gt;BUYING),\n 'buying_ex_vat' =&gt; floatval($element-&gt;price-&gt;BUYING_EX),\n 'vat' =&gt; floatval($element-&gt;price-&gt;VAT),\n 'selling' =&gt; floatval($element-&gt;price-&gt;SELLING)\n );\n\n /* start chunking the while routine by $limit\n passing the array to bulk_insert() if the limits gets reached. */\n\n if (count($array) == $limit) {\n $this-&gt;bulk_insert($table, $array);\n unset($array);\n }\n unset($element);\n $xml-&gt;next('item');\n }\n /* don't miss the last chunk, if it didn't reach the given limit, send it now! */\n $this-&gt;bulk_insert($table, $array);\n /* return the total amount of entries */\n return $i;\n }\n\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>You have to find your working <code>$limit</code>, just as reference:</p>\n\n<pre>product_item.xml\n - 140MB\n - 9.1 Million rows in document\n - 142.000 items \n$limit = 5000;\n$runtime = 43.93240232324 [average]\n</pre>\n\n<p>Runtime = including parsing &amp; inserting into MySQL Database. </p>\n\n<p>6500 rows each was the max working limit, so i've decided getting a little more room and went down to <code>$limit = 5000</code> and still hit the same average runtime. Pretty sure, most of the time is needed parsing the XML document, mabye i'll do some benchmarking and tracking microtime form each function separate.</p>\n\n<p>Thanks so @phatskat and @kuchenandkakao for pushing me into the right direction.</p>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339449", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169354/" ]
Actually im stuck on this! * XML-File ~ 140.000 Rows * Filesize ~ 9.0 MB * `LOAD XML INFILE 'file_name'` isnt't allowed ( shared hosting! ) The supplier provides a single XML file with quantity and sku. The XML is formatted like: ```xml <item> <LITM>0000001</LITM> <STQU>1<STQU> </item> <item> <LITM>0000002</LITM> <STQU>4<STQU> </item> ``` The following function works, but as you can think about - its slow! ```php function load_xml2mysql($filename,$type) { global $wpdb; $file = XML_DIR.$filename; $xml = new XMLReader(); $xml->open($file); $charset = $wpdb->get_charset_collate(); $table = $wpdb->prefix.'supplier_stock'; ignore_user_abort(); while($xml->read() && $xml->name != 'item'){ ; } while($xml->name == 'item') { $element = new SimpleXMLElement($xml->readOuterXML()); $query = $wpdb->prepare("INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d", strval($element->LITM),strval($element->STQU),strval($element->STQU)); $wpdb->query( $query ); $wpdb->flush(); $xml->next('item'); unset($element); } } ``` I've read alot about batch/bulk insert and the benchmarks are very clear on this. Querying 140.000 rows with my function is done in average 40 seconds. The Stock table is the smallest one from a set of three XML files, imagine inserting the main product data with a total filesize ~ 145.0 MB maybe put me in some trouble? Any Ideas on this how to improve or batch insert?
You can try to mitigate memory issues by using a [Generator](https://www.php.net/manual/en/language.generators.overview.php): ```php function load_xml2mysql($filename,$type) { global $wpdb; $charset = $wpdb->get_charset_collate(); $table = $wpdb->prefix.'supplier_stock'; ignore_user_abort(); $query_template = "INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d"; $wpdb->query( 'SET autocommit = 0' ); foreach ( get_xml_element( $filename ) as $element ) { $query = $wpdb->prepare( $query_template, strval($element->LITM), strval($element->STQU), strval($element->STQU) ); $wpdb->query( $query ); } $wpdb->query( 'COMMIT' ); } function get_xml_element( $filename ) { $file = XML_DIR.$filename; $xml = new XMLReader(); $xml->open($file); // I'm not clear on what exactly this is doing, do you need it? // edit: this moves us to the first <item> node while($xml->read() && $xml->name != 'item'){ ; } while ( $xml->name === 'item' ) { yield new SimpleXMLElement( $xml->readOuterXML() ); $xml->next('item'); } } ``` Generators tend to be more efficient than just doing a loop, and in a case like this it may be what you need. We're also doing `SET autocommit=0` before you run your queries, this should provide some performance boost as you're telling MySQL not to commit the changes until we call `COMMIT` after the loop.
339,452
<p>I have a HTML form embedded within a PHP file with an onclick button which summons a javascript function.</p> <pre><code>&lt;form name="addStamp"&gt; Validation Code:&lt;br&gt; &lt;input type="number" name="inputcode"&gt;&lt;br&gt; &lt;input type="text" name="message" id="message"&gt;&lt;br&gt; &lt;input type="button" name="submitbutton" value="Submit" onClick="stampme()"&gt; &lt;/form&gt; </code></pre> <p>The function looks at the entry in "inputcode" field and:</p> <ul> <li>if valid returns the word "<strong>valid</strong>" into the "message" field</li> <li>if void returns the word "<strong>failed</strong>" into the "message" field</li> </ul> <p>Script snippet that populates the form:</p> <pre><code>document.addStamp.message.value = msg; document.addStamp.inputcode.value = ""; } else if (document.addStamp.inputcode.value != test) { document.addStamp.message.value = msg2; } </code></pre> <p>What I can't figure out is now how to bring the result back into php so I can use it to perform a <code>update_user_meta</code> task.</p> <p>All of the above happens without refreshing the page and I need to get the result of the javascript function back into php without refreshing the page also.</p> <p>Any help please?</p>
[ { "answer_id": 339459, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>First of all: don't flush after every insert. I did not test this, but it should be faster if you import all the data, then do the flush.</p>\n\n<p>Second: What exactly do you want to accomplish? A onetime Import, or a regular update to your database?\nIf you need option a), then take the waiting. Maybe increase the PHP Maximum Runtime if you need to.</p>\n\n<p>If you want to regularly update your database, then you maybe should go for another approach. Like, first reading your XML File and converting it into an array/put it into a temporary database table, check if the article must be added or updated, then in a third step complete it by adding the new articles and updating the articles to be updated.</p>\n\n<p>Happy Coding! </p>\n" }, { "answer_id": 339469, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": false, "text": "<p>You can try to mitigate memory issues by using a <a href=\"https://www.php.net/manual/en/language.generators.overview.php\" rel=\"nofollow noreferrer\">Generator</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function load_xml2mysql($filename,$type) {\n global $wpdb;\n\n $charset = $wpdb-&gt;get_charset_collate();\n $table = $wpdb-&gt;prefix.'supplier_stock';\n\n ignore_user_abort();\n\n $query_template = &quot;INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d&quot;;\n $wpdb-&gt;query( 'SET autocommit = 0' );\n foreach ( get_xml_element( $filename ) as $element ) {\n $query = $wpdb-&gt;prepare(\n $query_template,\n strval($element-&gt;LITM),\n strval($element-&gt;STQU),\n strval($element-&gt;STQU)\n );\n\n $wpdb-&gt;query( $query );\n }\n $wpdb-&gt;query( 'COMMIT' );\n}\n\nfunction get_xml_element( $filename ) {\n $file = XML_DIR.$filename;\n $xml = new XMLReader();\n $xml-&gt;open($file);\n\n // I'm not clear on what exactly this is doing, do you need it?\n // edit: this moves us to the first &lt;item&gt; node \n while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; }\n\n while ( $xml-&gt;name === 'item' ) {\n yield new SimpleXMLElement( $xml-&gt;readOuterXML() );\n $xml-&gt;next('item');\n }\n}\n</code></pre>\n<p>Generators tend to be more efficient than just doing a loop, and in a case like this it may be what you need.</p>\n<p>We're also doing <code>SET autocommit=0</code> before you run your queries, this should provide some performance boost as you're telling MySQL not to commit the changes until we call <code>COMMIT</code> after the loop.</p>\n" }, { "answer_id": 339644, "author": "click here", "author_id": 169354, "author_profile": "https://wordpress.stackexchange.com/users/169354", "pm_score": 2, "selected": false, "text": "<p>After facing problems with exhausted memory and time consuming queries i've tried a different way bulk importing. The idea isn't new but but to show a possible way i want to share my solution. Keep in mind, i'm not a professional in PHP/MySQL, so maybe there is a more effective or better way to accomplish this task in different manner or with better performance</p>\n\n<h1>Main function to BULK INSERT with $wpdb</h1>\n\n<p>Since @kuchenundkakao pushed me some new ideas using a temporary table to import the whole XML file and processing the data from in a second query. In Conclusion, the bulk_insert function didn't check for any existing data or updating them, the table gets <code>truncated</code> every 24hrs after processing is done.</p>\n\n<p>It's used in PHP Class, so be aware if you try to just copy and paste - check the syntax!</p>\n\n<pre>\n// Table, including your prefix!\n$table = $wpdb->prefix.'table_name';\n\n$rows = array(\n array('price' => '12.00','vat' => '7.7'),\n array('price' => '230.00', 'vat' => '7.7')\n );\n</pre>\n\n<p>content of my <code>bulk_insert</code> function. </p>\n\n<pre><code> function bulk_insert($table, $rows) {\n global $wpdb;\n\n /* Extract column list from first row of data! */ \n $columns = array_keys($rows[0]);\n asort($columns);\n $columnList = '`' . implode('`, `', $columns) . '`';\n\n /* Start building SQL, initialise data and placeholder arrays */\n $sql = \"INSERT INTO `$table` ($columnList) VALUES\\n\";\n $placeholders = array();\n $data = array();\n\n /* Build placeholders for each row, and add values to data array */\n foreach ($rows as $row) {\n ksort($row);\n $rowPlaceholders = array();\n foreach ($row as $key =&gt; $value) {\n $data[] = $value;\n\n /* differentiate values and set placeholders */\n if (is_numeric($value)) {\n $rowPlaceholders[] = is_float($value) ? '%f' : '%d';\n } else {\n $rowPlaceholders[] = '%s';\n }\n }\n $placeholders[] = '(' . implode(', ', $rowPlaceholders) . ')';\n }\n\n /* Stitching all rows together */\n $sql .= implode(\",\\n\", $placeholders);\n // Run the query. Returning number of affected rows for this chunk\n return $wpdb-&gt;query($wpdb-&gt;prepare($sql, $data));\n }\n</code></pre>\n\n<h1>Chunking XML Data</h1>\n\n<p>It's really different how much data you can push to <code>bulk_insert()</code> and depends alot on your hosting/server - so i've made it flexible and easy to adjust by limitting the amount of data before it's send to <code>bulk_insert()</code>. </p>\n\n<p><strong>What is this function doing?</strong>\nIt's using XMLReader and SimpleXMLElement to parse the XML Document Line-by-Line instead parsing the whole document ( which mostly ends in exhausted memory ). After a given amount set by <code>$limit</code> of XML Elements in <code>$array[]</code> is reached, the function sends this chunk of your XML file as an array to <code>bulk_insert()</code> -> stamps the whole array into your database. </p>\n\n<p>I'm passing a filename to <code>load_price_xml2mysql</code> for flexibility purposes like <code>myfile.xml</code></p>\n\n<pre><code>function load_price_xml2mysql($filename) {\n global $wpdb;\n\n /* get xml file */\n\n $file = WP_UPLOAD_DIR.$filename;\n $xml = new XMLReader();\n $xml-&gt;open($file);\n\n /* set your limit here, define the limit in your plugin or just add $limit = 1000 */\n $limit = MYSQL_PRICE_INSERTLIMIT;\n\n $array = array();\n $table = $wpdb-&gt;prefix.'temp_api_price';\n\n /* counting entries, so we have to set zero before while */\n $i = 0;\n while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; }\n while ( $xml-&gt;name === 'item' ) {\n ++$i;\n\n $element = new SimpleXMLElement( $xml-&gt;readOuterXML() );\n $array[] = array(\n 'sku' =&gt; intval($element-&gt;SKU),\n 'buying' =&gt; floatval($element-&gt;price-&gt;BUYING),\n 'buying_ex_vat' =&gt; floatval($element-&gt;price-&gt;BUYING_EX),\n 'vat' =&gt; floatval($element-&gt;price-&gt;VAT),\n 'selling' =&gt; floatval($element-&gt;price-&gt;SELLING)\n );\n\n /* start chunking the while routine by $limit\n passing the array to bulk_insert() if the limits gets reached. */\n\n if (count($array) == $limit) {\n $this-&gt;bulk_insert($table, $array);\n unset($array);\n }\n unset($element);\n $xml-&gt;next('item');\n }\n /* don't miss the last chunk, if it didn't reach the given limit, send it now! */\n $this-&gt;bulk_insert($table, $array);\n /* return the total amount of entries */\n return $i;\n }\n\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>You have to find your working <code>$limit</code>, just as reference:</p>\n\n<pre>product_item.xml\n - 140MB\n - 9.1 Million rows in document\n - 142.000 items \n$limit = 5000;\n$runtime = 43.93240232324 [average]\n</pre>\n\n<p>Runtime = including parsing &amp; inserting into MySQL Database. </p>\n\n<p>6500 rows each was the max working limit, so i've decided getting a little more room and went down to <code>$limit = 5000</code> and still hit the same average runtime. Pretty sure, most of the time is needed parsing the XML document, mabye i'll do some benchmarking and tracking microtime form each function separate.</p>\n\n<p>Thanks so @phatskat and @kuchenandkakao for pushing me into the right direction.</p>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167925/" ]
I have a HTML form embedded within a PHP file with an onclick button which summons a javascript function. ``` <form name="addStamp"> Validation Code:<br> <input type="number" name="inputcode"><br> <input type="text" name="message" id="message"><br> <input type="button" name="submitbutton" value="Submit" onClick="stampme()"> </form> ``` The function looks at the entry in "inputcode" field and: * if valid returns the word "**valid**" into the "message" field * if void returns the word "**failed**" into the "message" field Script snippet that populates the form: ``` document.addStamp.message.value = msg; document.addStamp.inputcode.value = ""; } else if (document.addStamp.inputcode.value != test) { document.addStamp.message.value = msg2; } ``` What I can't figure out is now how to bring the result back into php so I can use it to perform a `update_user_meta` task. All of the above happens without refreshing the page and I need to get the result of the javascript function back into php without refreshing the page also. Any help please?
You can try to mitigate memory issues by using a [Generator](https://www.php.net/manual/en/language.generators.overview.php): ```php function load_xml2mysql($filename,$type) { global $wpdb; $charset = $wpdb->get_charset_collate(); $table = $wpdb->prefix.'supplier_stock'; ignore_user_abort(); $query_template = "INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d"; $wpdb->query( 'SET autocommit = 0' ); foreach ( get_xml_element( $filename ) as $element ) { $query = $wpdb->prepare( $query_template, strval($element->LITM), strval($element->STQU), strval($element->STQU) ); $wpdb->query( $query ); } $wpdb->query( 'COMMIT' ); } function get_xml_element( $filename ) { $file = XML_DIR.$filename; $xml = new XMLReader(); $xml->open($file); // I'm not clear on what exactly this is doing, do you need it? // edit: this moves us to the first <item> node while($xml->read() && $xml->name != 'item'){ ; } while ( $xml->name === 'item' ) { yield new SimpleXMLElement( $xml->readOuterXML() ); $xml->next('item'); } } ``` Generators tend to be more efficient than just doing a loop, and in a case like this it may be what you need. We're also doing `SET autocommit=0` before you run your queries, this should provide some performance boost as you're telling MySQL not to commit the changes until we call `COMMIT` after the loop.
339,485
<p>Does anyone know if there is a function to remove/bypass file types uploads filter (specifically for admins). I know there are plugins available but they often break or don't contain ALL the mime types I need to allow and to be completely honest I'm just tired of dealing with this constantly. I also know about the constant ALLOW_UNFILTERED_UPLOADS which I'm using currently, but eventually I need only for the admin to be able to upload without restriction. I'm not sure how to do this in config file. Tried searching for a resolution but only found for allowing specific file types.</p>
[ { "answer_id": 339459, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>First of all: don't flush after every insert. I did not test this, but it should be faster if you import all the data, then do the flush.</p>\n\n<p>Second: What exactly do you want to accomplish? A onetime Import, or a regular update to your database?\nIf you need option a), then take the waiting. Maybe increase the PHP Maximum Runtime if you need to.</p>\n\n<p>If you want to regularly update your database, then you maybe should go for another approach. Like, first reading your XML File and converting it into an array/put it into a temporary database table, check if the article must be added or updated, then in a third step complete it by adding the new articles and updating the articles to be updated.</p>\n\n<p>Happy Coding! </p>\n" }, { "answer_id": 339469, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": false, "text": "<p>You can try to mitigate memory issues by using a <a href=\"https://www.php.net/manual/en/language.generators.overview.php\" rel=\"nofollow noreferrer\">Generator</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function load_xml2mysql($filename,$type) {\n global $wpdb;\n\n $charset = $wpdb-&gt;get_charset_collate();\n $table = $wpdb-&gt;prefix.'supplier_stock';\n\n ignore_user_abort();\n\n $query_template = &quot;INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d&quot;;\n $wpdb-&gt;query( 'SET autocommit = 0' );\n foreach ( get_xml_element( $filename ) as $element ) {\n $query = $wpdb-&gt;prepare(\n $query_template,\n strval($element-&gt;LITM),\n strval($element-&gt;STQU),\n strval($element-&gt;STQU)\n );\n\n $wpdb-&gt;query( $query );\n }\n $wpdb-&gt;query( 'COMMIT' );\n}\n\nfunction get_xml_element( $filename ) {\n $file = XML_DIR.$filename;\n $xml = new XMLReader();\n $xml-&gt;open($file);\n\n // I'm not clear on what exactly this is doing, do you need it?\n // edit: this moves us to the first &lt;item&gt; node \n while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; }\n\n while ( $xml-&gt;name === 'item' ) {\n yield new SimpleXMLElement( $xml-&gt;readOuterXML() );\n $xml-&gt;next('item');\n }\n}\n</code></pre>\n<p>Generators tend to be more efficient than just doing a loop, and in a case like this it may be what you need.</p>\n<p>We're also doing <code>SET autocommit=0</code> before you run your queries, this should provide some performance boost as you're telling MySQL not to commit the changes until we call <code>COMMIT</code> after the loop.</p>\n" }, { "answer_id": 339644, "author": "click here", "author_id": 169354, "author_profile": "https://wordpress.stackexchange.com/users/169354", "pm_score": 2, "selected": false, "text": "<p>After facing problems with exhausted memory and time consuming queries i've tried a different way bulk importing. The idea isn't new but but to show a possible way i want to share my solution. Keep in mind, i'm not a professional in PHP/MySQL, so maybe there is a more effective or better way to accomplish this task in different manner or with better performance</p>\n\n<h1>Main function to BULK INSERT with $wpdb</h1>\n\n<p>Since @kuchenundkakao pushed me some new ideas using a temporary table to import the whole XML file and processing the data from in a second query. In Conclusion, the bulk_insert function didn't check for any existing data or updating them, the table gets <code>truncated</code> every 24hrs after processing is done.</p>\n\n<p>It's used in PHP Class, so be aware if you try to just copy and paste - check the syntax!</p>\n\n<pre>\n// Table, including your prefix!\n$table = $wpdb->prefix.'table_name';\n\n$rows = array(\n array('price' => '12.00','vat' => '7.7'),\n array('price' => '230.00', 'vat' => '7.7')\n );\n</pre>\n\n<p>content of my <code>bulk_insert</code> function. </p>\n\n<pre><code> function bulk_insert($table, $rows) {\n global $wpdb;\n\n /* Extract column list from first row of data! */ \n $columns = array_keys($rows[0]);\n asort($columns);\n $columnList = '`' . implode('`, `', $columns) . '`';\n\n /* Start building SQL, initialise data and placeholder arrays */\n $sql = \"INSERT INTO `$table` ($columnList) VALUES\\n\";\n $placeholders = array();\n $data = array();\n\n /* Build placeholders for each row, and add values to data array */\n foreach ($rows as $row) {\n ksort($row);\n $rowPlaceholders = array();\n foreach ($row as $key =&gt; $value) {\n $data[] = $value;\n\n /* differentiate values and set placeholders */\n if (is_numeric($value)) {\n $rowPlaceholders[] = is_float($value) ? '%f' : '%d';\n } else {\n $rowPlaceholders[] = '%s';\n }\n }\n $placeholders[] = '(' . implode(', ', $rowPlaceholders) . ')';\n }\n\n /* Stitching all rows together */\n $sql .= implode(\",\\n\", $placeholders);\n // Run the query. Returning number of affected rows for this chunk\n return $wpdb-&gt;query($wpdb-&gt;prepare($sql, $data));\n }\n</code></pre>\n\n<h1>Chunking XML Data</h1>\n\n<p>It's really different how much data you can push to <code>bulk_insert()</code> and depends alot on your hosting/server - so i've made it flexible and easy to adjust by limitting the amount of data before it's send to <code>bulk_insert()</code>. </p>\n\n<p><strong>What is this function doing?</strong>\nIt's using XMLReader and SimpleXMLElement to parse the XML Document Line-by-Line instead parsing the whole document ( which mostly ends in exhausted memory ). After a given amount set by <code>$limit</code> of XML Elements in <code>$array[]</code> is reached, the function sends this chunk of your XML file as an array to <code>bulk_insert()</code> -> stamps the whole array into your database. </p>\n\n<p>I'm passing a filename to <code>load_price_xml2mysql</code> for flexibility purposes like <code>myfile.xml</code></p>\n\n<pre><code>function load_price_xml2mysql($filename) {\n global $wpdb;\n\n /* get xml file */\n\n $file = WP_UPLOAD_DIR.$filename;\n $xml = new XMLReader();\n $xml-&gt;open($file);\n\n /* set your limit here, define the limit in your plugin or just add $limit = 1000 */\n $limit = MYSQL_PRICE_INSERTLIMIT;\n\n $array = array();\n $table = $wpdb-&gt;prefix.'temp_api_price';\n\n /* counting entries, so we have to set zero before while */\n $i = 0;\n while($xml-&gt;read() &amp;&amp; $xml-&gt;name != 'item'){ ; }\n while ( $xml-&gt;name === 'item' ) {\n ++$i;\n\n $element = new SimpleXMLElement( $xml-&gt;readOuterXML() );\n $array[] = array(\n 'sku' =&gt; intval($element-&gt;SKU),\n 'buying' =&gt; floatval($element-&gt;price-&gt;BUYING),\n 'buying_ex_vat' =&gt; floatval($element-&gt;price-&gt;BUYING_EX),\n 'vat' =&gt; floatval($element-&gt;price-&gt;VAT),\n 'selling' =&gt; floatval($element-&gt;price-&gt;SELLING)\n );\n\n /* start chunking the while routine by $limit\n passing the array to bulk_insert() if the limits gets reached. */\n\n if (count($array) == $limit) {\n $this-&gt;bulk_insert($table, $array);\n unset($array);\n }\n unset($element);\n $xml-&gt;next('item');\n }\n /* don't miss the last chunk, if it didn't reach the given limit, send it now! */\n $this-&gt;bulk_insert($table, $array);\n /* return the total amount of entries */\n return $i;\n }\n\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>You have to find your working <code>$limit</code>, just as reference:</p>\n\n<pre>product_item.xml\n - 140MB\n - 9.1 Million rows in document\n - 142.000 items \n$limit = 5000;\n$runtime = 43.93240232324 [average]\n</pre>\n\n<p>Runtime = including parsing &amp; inserting into MySQL Database. </p>\n\n<p>6500 rows each was the max working limit, so i've decided getting a little more room and went down to <code>$limit = 5000</code> and still hit the same average runtime. Pretty sure, most of the time is needed parsing the XML document, mabye i'll do some benchmarking and tracking microtime form each function separate.</p>\n\n<p>Thanks so @phatskat and @kuchenandkakao for pushing me into the right direction.</p>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164435/" ]
Does anyone know if there is a function to remove/bypass file types uploads filter (specifically for admins). I know there are plugins available but they often break or don't contain ALL the mime types I need to allow and to be completely honest I'm just tired of dealing with this constantly. I also know about the constant ALLOW\_UNFILTERED\_UPLOADS which I'm using currently, but eventually I need only for the admin to be able to upload without restriction. I'm not sure how to do this in config file. Tried searching for a resolution but only found for allowing specific file types.
You can try to mitigate memory issues by using a [Generator](https://www.php.net/manual/en/language.generators.overview.php): ```php function load_xml2mysql($filename,$type) { global $wpdb; $charset = $wpdb->get_charset_collate(); $table = $wpdb->prefix.'supplier_stock'; ignore_user_abort(); $query_template = "INSERT INTO {$table} (sku,stock) VALUES (%d,%d) ON DUPLICATE KEY UPDATE stock = %d"; $wpdb->query( 'SET autocommit = 0' ); foreach ( get_xml_element( $filename ) as $element ) { $query = $wpdb->prepare( $query_template, strval($element->LITM), strval($element->STQU), strval($element->STQU) ); $wpdb->query( $query ); } $wpdb->query( 'COMMIT' ); } function get_xml_element( $filename ) { $file = XML_DIR.$filename; $xml = new XMLReader(); $xml->open($file); // I'm not clear on what exactly this is doing, do you need it? // edit: this moves us to the first <item> node while($xml->read() && $xml->name != 'item'){ ; } while ( $xml->name === 'item' ) { yield new SimpleXMLElement( $xml->readOuterXML() ); $xml->next('item'); } } ``` Generators tend to be more efficient than just doing a loop, and in a case like this it may be what you need. We're also doing `SET autocommit=0` before you run your queries, this should provide some performance boost as you're telling MySQL not to commit the changes until we call `COMMIT` after the loop.
339,495
<p>Is there any plugin or script where i can use to define maximum number of users with a specific role on subsite in a multisite network?</p> <p>I'm offering cloud helpdesk wordpress and pricing is based on number of agents, so I want to make sure that site admin is not able to add more agents than the predefined.</p> <p>Thanks a lot in advance</p>
[ { "answer_id": 339500, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 0, "selected": false, "text": "<p><strong>Update:</strong> There was a problem with my previous code based on some erroneous digging into WordPress roles and capabilities. The below code should work a little better now.</p>\n\n<p>You could maybe try hooking the <code>map_meta_cap</code> filter, something like this might work:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'map_meta_cap', 'has_max_agents', 10, 2 );\n\nfunction has_max_agents( $caps, $cap ) {\n static $max_agents = 30; // Example max number of agents.\n if ( 'create_users' !== $cap ) {\n return $caps;\n }\n\n $users = get_users( [\n 'role__in' =&gt; [ 'agent' ], // Your custom role in place of 'agent'\n ] );\n\n if ( true || $max_agents &lt;= count( $users ) ) {\n foreach ( $caps as $index =&gt; $maybe_remove_cap ) {\n if ( 'create_users' !== $maybe_remove_cap ) {\n continue;\n }\n\n unset( $caps[ $index ] );\n }\n }\n\n $caps[] = 'do_not_allow';\n\n return $caps;\n}\n</code></pre>\n" }, { "answer_id": 339550, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>Maybe using <a href=\"https://developer.wordpress.org/reference/hooks/insert_user_meta/\" rel=\"nofollow noreferrer\">insert_user_meta</a> (inside <code>wp_insert_user()</code>, which is also called by <code>wp_update_user()</code>) could also be a viable method to block extra agents from being registered. <a href=\"https://developer.wordpress.org/reference/hooks/set_user_role/\" rel=\"nofollow noreferrer\">set_user_role</a> action might also be needed to prevent existing users from getting an agent role.</p>\n\n<pre><code>// Maybe prevent setting new users to agent role\nfunction new_user_check_roles( $meta, $user, $update ) {\n\n $max_agents = 30;\n $agents = get_users( array( 'role' =&gt; 'agent' ) );\n $agents = count( $agents );\n\n if ( $max_agents != $agents ) {\n return $meta;\n }\n\n if ( in_array( 'agent', $user-&gt;roles ) ) {\n $user-&gt;set_role( 'subscriber' );\n }\n\n if ( isset( $meta['role'] ) &amp;&amp; 'agent' == $meta['role'] ) {\n $meta['role'] = 'subscriber';\n } \n\n return $meta;\n}\nadd_filter( 'insert_user_meta', 'new_user_check_roles', 10, 3 );\n\n// Maybe prevent setting existing user to agent role\nfunction set_roles_check_role( $user_id, $role, $old_roles ) {\n\n $max_agents = 30;\n $agents = get_users( array( 'role' =&gt; 'agent' ) );\n $agents = count( $agents );\n\n if ( $max_agents != $agents ) {\n return;\n }\n\n if ( 'agent' !== $role ) {\n return;\n }\n\n $user = new WP_User( user_id );\n $user-&gt;set_role( 'subscriber' );\n}\nadd_action( 'set_user_role', 'set_roles_check_role', 10, 3 );\n</code></pre>\n" }, { "answer_id": 339729, "author": "Akram", "author_id": 157457, "author_profile": "https://wordpress.stackexchange.com/users/157457", "pm_score": 3, "selected": true, "text": "<p>Ok here is how I did it:</p>\n\n<pre><code>add_action( 'editable_roles' , 'hide_editable_roles' );\nfunction hide_editable_roles( $roles ){\n$blog_id = get_current_blog_id(); // Get current subsite id\nswitch($blog_id) { // Define different max agents numbers depending on subsite id\n case 6: \n $max_agents = 10; //for subsite id#6 we can have maximum 10 agents\n break; \n case 7: //for subsite id#7 we can have maximum 3 agents\n $max_agents = 3;\n break; \n default:\n $max_agents = 3000; //default is 3000 agents\n break;\n}\n $agents = get_users( array( 'role' =&gt; 'agent' ) ); // here you define the role\n $agents = count( $agents );\n if ($max_agents &lt;= $agents){\n unset( $roles['agent'] ); // here you define the role\n }\n return $roles;\n}\n</code></pre>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339495", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157457/" ]
Is there any plugin or script where i can use to define maximum number of users with a specific role on subsite in a multisite network? I'm offering cloud helpdesk wordpress and pricing is based on number of agents, so I want to make sure that site admin is not able to add more agents than the predefined. Thanks a lot in advance
Ok here is how I did it: ``` add_action( 'editable_roles' , 'hide_editable_roles' ); function hide_editable_roles( $roles ){ $blog_id = get_current_blog_id(); // Get current subsite id switch($blog_id) { // Define different max agents numbers depending on subsite id case 6: $max_agents = 10; //for subsite id#6 we can have maximum 10 agents break; case 7: //for subsite id#7 we can have maximum 3 agents $max_agents = 3; break; default: $max_agents = 3000; //default is 3000 agents break; } $agents = get_users( array( 'role' => 'agent' ) ); // here you define the role $agents = count( $agents ); if ($max_agents <= $agents){ unset( $roles['agent'] ); // here you define the role } return $roles; } ```
339,506
<p>I'm currently building a site on my local computer. I will transfer the finished product onto my client's new host/domain. Before he chooses this, what's the best way for him to view my current progress?</p>
[ { "answer_id": 339500, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 0, "selected": false, "text": "<p><strong>Update:</strong> There was a problem with my previous code based on some erroneous digging into WordPress roles and capabilities. The below code should work a little better now.</p>\n\n<p>You could maybe try hooking the <code>map_meta_cap</code> filter, something like this might work:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'map_meta_cap', 'has_max_agents', 10, 2 );\n\nfunction has_max_agents( $caps, $cap ) {\n static $max_agents = 30; // Example max number of agents.\n if ( 'create_users' !== $cap ) {\n return $caps;\n }\n\n $users = get_users( [\n 'role__in' =&gt; [ 'agent' ], // Your custom role in place of 'agent'\n ] );\n\n if ( true || $max_agents &lt;= count( $users ) ) {\n foreach ( $caps as $index =&gt; $maybe_remove_cap ) {\n if ( 'create_users' !== $maybe_remove_cap ) {\n continue;\n }\n\n unset( $caps[ $index ] );\n }\n }\n\n $caps[] = 'do_not_allow';\n\n return $caps;\n}\n</code></pre>\n" }, { "answer_id": 339550, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>Maybe using <a href=\"https://developer.wordpress.org/reference/hooks/insert_user_meta/\" rel=\"nofollow noreferrer\">insert_user_meta</a> (inside <code>wp_insert_user()</code>, which is also called by <code>wp_update_user()</code>) could also be a viable method to block extra agents from being registered. <a href=\"https://developer.wordpress.org/reference/hooks/set_user_role/\" rel=\"nofollow noreferrer\">set_user_role</a> action might also be needed to prevent existing users from getting an agent role.</p>\n\n<pre><code>// Maybe prevent setting new users to agent role\nfunction new_user_check_roles( $meta, $user, $update ) {\n\n $max_agents = 30;\n $agents = get_users( array( 'role' =&gt; 'agent' ) );\n $agents = count( $agents );\n\n if ( $max_agents != $agents ) {\n return $meta;\n }\n\n if ( in_array( 'agent', $user-&gt;roles ) ) {\n $user-&gt;set_role( 'subscriber' );\n }\n\n if ( isset( $meta['role'] ) &amp;&amp; 'agent' == $meta['role'] ) {\n $meta['role'] = 'subscriber';\n } \n\n return $meta;\n}\nadd_filter( 'insert_user_meta', 'new_user_check_roles', 10, 3 );\n\n// Maybe prevent setting existing user to agent role\nfunction set_roles_check_role( $user_id, $role, $old_roles ) {\n\n $max_agents = 30;\n $agents = get_users( array( 'role' =&gt; 'agent' ) );\n $agents = count( $agents );\n\n if ( $max_agents != $agents ) {\n return;\n }\n\n if ( 'agent' !== $role ) {\n return;\n }\n\n $user = new WP_User( user_id );\n $user-&gt;set_role( 'subscriber' );\n}\nadd_action( 'set_user_role', 'set_roles_check_role', 10, 3 );\n</code></pre>\n" }, { "answer_id": 339729, "author": "Akram", "author_id": 157457, "author_profile": "https://wordpress.stackexchange.com/users/157457", "pm_score": 3, "selected": true, "text": "<p>Ok here is how I did it:</p>\n\n<pre><code>add_action( 'editable_roles' , 'hide_editable_roles' );\nfunction hide_editable_roles( $roles ){\n$blog_id = get_current_blog_id(); // Get current subsite id\nswitch($blog_id) { // Define different max agents numbers depending on subsite id\n case 6: \n $max_agents = 10; //for subsite id#6 we can have maximum 10 agents\n break; \n case 7: //for subsite id#7 we can have maximum 3 agents\n $max_agents = 3;\n break; \n default:\n $max_agents = 3000; //default is 3000 agents\n break;\n}\n $agents = get_users( array( 'role' =&gt; 'agent' ) ); // here you define the role\n $agents = count( $agents );\n if ($max_agents &lt;= $agents){\n unset( $roles['agent'] ); // here you define the role\n }\n return $roles;\n}\n</code></pre>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339506", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169383/" ]
I'm currently building a site on my local computer. I will transfer the finished product onto my client's new host/domain. Before he chooses this, what's the best way for him to view my current progress?
Ok here is how I did it: ``` add_action( 'editable_roles' , 'hide_editable_roles' ); function hide_editable_roles( $roles ){ $blog_id = get_current_blog_id(); // Get current subsite id switch($blog_id) { // Define different max agents numbers depending on subsite id case 6: $max_agents = 10; //for subsite id#6 we can have maximum 10 agents break; case 7: //for subsite id#7 we can have maximum 3 agents $max_agents = 3; break; default: $max_agents = 3000; //default is 3000 agents break; } $agents = get_users( array( 'role' => 'agent' ) ); // here you define the role $agents = count( $agents ); if ($max_agents <= $agents){ unset( $roles['agent'] ); // here you define the role } return $roles; } ```
339,507
<p>Edited for clarity and to display steps we take to reproduce the issue.</p> <h2>Question</h2> <p>What would cause absolute URLs on our staging site to prepend the staging site's subdomain to them when saved in the editor? </p> <h2>Summary</h2> <p>We write pages manually in HTML and CSS on a staging site hosted on SiteGround, save our changes, then test them. However, when we save our work in the editor, they all prepend the staging subdomain we are writing on to each of the absolute URLs we've written.</p> <h2>Steps to Reproduce</h2> <ol> <li>Create a staging copy of the live site.</li> <li>Disable all plugins.</li> <li>Install and activate the twenty nineteen default theme from WordPress.</li> <li>Create a new page, title it whatever you want.</li> <li>On that page, create four links: a. <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a> b. <a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a> c. <a href="https://example.com" rel="nofollow noreferrer">https://example.com</a> d. <a href="https://www.example.com" rel="nofollow noreferrer">https://www.example.com</a></li> <li>Save the page.</li> <li>View the page - all links point to <a href="https://stagingX.example.com" rel="nofollow noreferrer">https://stagingX.example.com</a></li> <li>Edit the page - all links will have had "stagingX." prepended to them, showing that they have been rewritten.</li> </ol> <h2>Detailed Breakdown</h2> <p>We write a link destination as an absolute URL into a page, like this example:</p> <p>"Click here for our <code>&lt;a href="https://example.com/daily-specials"&gt;Daily Specials&lt;/a&gt;</code>!"</p> <p>We then save our work in the editor. </p> <p>If we immediately check the link on the staging site, it is already pointing instead to <code>&lt;a href="https://staging.example.com/daily-specials"&gt;&lt;/a&gt;</code> and displays as such if we relaunch the editor.</p> <p>While this does not affect any relative URLs (i.e. <code>&lt;a href="/daily-specials"&gt;&lt;/a&gt;</code>), it does affect every prefix variant of absolute URLs. </p> <p>The site has thousands of absolute URLs affected by this.</p> <h2>What We've Tried</h2> <p>We must be missing something, so please feel free to offer any guidance or perspective, regardless of whether it seems redundant or not.</p> <p>We've attempted checking the server, theme, and child theme .htaccess and functions.php files in cPanel for any code that would cause this (perhaps we missed or misunderstood it?). </p> <p>We've also verified that the site URL etc. under Settings > General in the WordPress dashboard are pointing at the live site without the staging prefix. </p> <p>We have disabled all plugins and switched to the Twenty Nineteen theme and experience the same issues.</p> <p>The Home URL and Site URL in settings and in the database are set to the main site, but in the help section of the "Better Search Replace" plugin it shows both URLs as having the staging subdomain preceding them. </p>
[ { "answer_id": 339500, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 0, "selected": false, "text": "<p><strong>Update:</strong> There was a problem with my previous code based on some erroneous digging into WordPress roles and capabilities. The below code should work a little better now.</p>\n\n<p>You could maybe try hooking the <code>map_meta_cap</code> filter, something like this might work:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'map_meta_cap', 'has_max_agents', 10, 2 );\n\nfunction has_max_agents( $caps, $cap ) {\n static $max_agents = 30; // Example max number of agents.\n if ( 'create_users' !== $cap ) {\n return $caps;\n }\n\n $users = get_users( [\n 'role__in' =&gt; [ 'agent' ], // Your custom role in place of 'agent'\n ] );\n\n if ( true || $max_agents &lt;= count( $users ) ) {\n foreach ( $caps as $index =&gt; $maybe_remove_cap ) {\n if ( 'create_users' !== $maybe_remove_cap ) {\n continue;\n }\n\n unset( $caps[ $index ] );\n }\n }\n\n $caps[] = 'do_not_allow';\n\n return $caps;\n}\n</code></pre>\n" }, { "answer_id": 339550, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>Maybe using <a href=\"https://developer.wordpress.org/reference/hooks/insert_user_meta/\" rel=\"nofollow noreferrer\">insert_user_meta</a> (inside <code>wp_insert_user()</code>, which is also called by <code>wp_update_user()</code>) could also be a viable method to block extra agents from being registered. <a href=\"https://developer.wordpress.org/reference/hooks/set_user_role/\" rel=\"nofollow noreferrer\">set_user_role</a> action might also be needed to prevent existing users from getting an agent role.</p>\n\n<pre><code>// Maybe prevent setting new users to agent role\nfunction new_user_check_roles( $meta, $user, $update ) {\n\n $max_agents = 30;\n $agents = get_users( array( 'role' =&gt; 'agent' ) );\n $agents = count( $agents );\n\n if ( $max_agents != $agents ) {\n return $meta;\n }\n\n if ( in_array( 'agent', $user-&gt;roles ) ) {\n $user-&gt;set_role( 'subscriber' );\n }\n\n if ( isset( $meta['role'] ) &amp;&amp; 'agent' == $meta['role'] ) {\n $meta['role'] = 'subscriber';\n } \n\n return $meta;\n}\nadd_filter( 'insert_user_meta', 'new_user_check_roles', 10, 3 );\n\n// Maybe prevent setting existing user to agent role\nfunction set_roles_check_role( $user_id, $role, $old_roles ) {\n\n $max_agents = 30;\n $agents = get_users( array( 'role' =&gt; 'agent' ) );\n $agents = count( $agents );\n\n if ( $max_agents != $agents ) {\n return;\n }\n\n if ( 'agent' !== $role ) {\n return;\n }\n\n $user = new WP_User( user_id );\n $user-&gt;set_role( 'subscriber' );\n}\nadd_action( 'set_user_role', 'set_roles_check_role', 10, 3 );\n</code></pre>\n" }, { "answer_id": 339729, "author": "Akram", "author_id": 157457, "author_profile": "https://wordpress.stackexchange.com/users/157457", "pm_score": 3, "selected": true, "text": "<p>Ok here is how I did it:</p>\n\n<pre><code>add_action( 'editable_roles' , 'hide_editable_roles' );\nfunction hide_editable_roles( $roles ){\n$blog_id = get_current_blog_id(); // Get current subsite id\nswitch($blog_id) { // Define different max agents numbers depending on subsite id\n case 6: \n $max_agents = 10; //for subsite id#6 we can have maximum 10 agents\n break; \n case 7: //for subsite id#7 we can have maximum 3 agents\n $max_agents = 3;\n break; \n default:\n $max_agents = 3000; //default is 3000 agents\n break;\n}\n $agents = get_users( array( 'role' =&gt; 'agent' ) ); // here you define the role\n $agents = count( $agents );\n if ($max_agents &lt;= $agents){\n unset( $roles['agent'] ); // here you define the role\n }\n return $roles;\n}\n</code></pre>\n" } ]
2019/06/03
[ "https://wordpress.stackexchange.com/questions/339507", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169384/" ]
Edited for clarity and to display steps we take to reproduce the issue. Question -------- What would cause absolute URLs on our staging site to prepend the staging site's subdomain to them when saved in the editor? Summary ------- We write pages manually in HTML and CSS on a staging site hosted on SiteGround, save our changes, then test them. However, when we save our work in the editor, they all prepend the staging subdomain we are writing on to each of the absolute URLs we've written. Steps to Reproduce ------------------ 1. Create a staging copy of the live site. 2. Disable all plugins. 3. Install and activate the twenty nineteen default theme from WordPress. 4. Create a new page, title it whatever you want. 5. On that page, create four links: a. <http://example.com> b. <http://www.example.com> c. <https://example.com> d. <https://www.example.com> 6. Save the page. 7. View the page - all links point to <https://stagingX.example.com> 8. Edit the page - all links will have had "stagingX." prepended to them, showing that they have been rewritten. Detailed Breakdown ------------------ We write a link destination as an absolute URL into a page, like this example: "Click here for our `<a href="https://example.com/daily-specials">Daily Specials</a>`!" We then save our work in the editor. If we immediately check the link on the staging site, it is already pointing instead to `<a href="https://staging.example.com/daily-specials"></a>` and displays as such if we relaunch the editor. While this does not affect any relative URLs (i.e. `<a href="/daily-specials"></a>`), it does affect every prefix variant of absolute URLs. The site has thousands of absolute URLs affected by this. What We've Tried ---------------- We must be missing something, so please feel free to offer any guidance or perspective, regardless of whether it seems redundant or not. We've attempted checking the server, theme, and child theme .htaccess and functions.php files in cPanel for any code that would cause this (perhaps we missed or misunderstood it?). We've also verified that the site URL etc. under Settings > General in the WordPress dashboard are pointing at the live site without the staging prefix. We have disabled all plugins and switched to the Twenty Nineteen theme and experience the same issues. The Home URL and Site URL in settings and in the database are set to the main site, but in the help section of the "Better Search Replace" plugin it shows both URLs as having the staging subdomain preceding them.
Ok here is how I did it: ``` add_action( 'editable_roles' , 'hide_editable_roles' ); function hide_editable_roles( $roles ){ $blog_id = get_current_blog_id(); // Get current subsite id switch($blog_id) { // Define different max agents numbers depending on subsite id case 6: $max_agents = 10; //for subsite id#6 we can have maximum 10 agents break; case 7: //for subsite id#7 we can have maximum 3 agents $max_agents = 3; break; default: $max_agents = 3000; //default is 3000 agents break; } $agents = get_users( array( 'role' => 'agent' ) ); // here you define the role $agents = count( $agents ); if ($max_agents <= $agents){ unset( $roles['agent'] ); // here you define the role } return $roles; } ```
339,517
<p>Does WordPress have a built-in function that allows duplicating posts?</p> <p>I am looking for something like <code>$new_post_id = duplicate_post(post_id);</code></p>
[ { "answer_id": 339520, "author": "Mahmod Issa", "author_id": 169394, "author_profile": "https://wordpress.stackexchange.com/users/169394", "pm_score": -1, "selected": false, "text": "<p>No, there isnt built in function but there are a plenty of plugins that easily can do what you need as those below:</p>\n\n<p><a href=\"https://wordpress.org/plugins/duplicate-post/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/duplicate-post/</a> </p>\n\n<p><a href=\"https://www.wpbeginner.com/plugins/how-to-duplicate-a-wordpress-page-or-post-with-a-single-click/\" rel=\"nofollow noreferrer\">https://www.wpbeginner.com/plugins/how-to-duplicate-a-wordpress-page-or-post-with-a-single-click/</a></p>\n\n<p><a href=\"https://www.hostinger.com/tutorials/how-to-duplicate-wordpress-page-post\" rel=\"nofollow noreferrer\">https://www.hostinger.com/tutorials/how-to-duplicate-wordpress-page-post</a></p>\n" }, { "answer_id": 339554, "author": "Caleb Mieszko", "author_id": 169384, "author_profile": "https://wordpress.stackexchange.com/users/169384", "pm_score": 0, "selected": false, "text": "<p>Mahmod is right, and that last link Mahmod posted (<a href=\"https://www.hostinger.com/tutorials/how-to-duplicate-wordpress-page-post\" rel=\"nofollow noreferrer\">https://www.hostinger.com/tutorials/how-to-duplicate-wordpress-page-post</a>) is the one I used as the basis of writing my own post/page duplication functions in my functions.php files. </p>\n\n<p>Back up your site, use the last suggestions from that link (#4) and you can create your own post duplication and page duplication on any site. It'll help you better understand how to write something like this for yourself, which I recommend if you're a little hesitant about it.</p>\n\n<p>As long as you back up first and don't deviate outside of what you know, you should be fine. :)</p>\n\n<p>If coding isn't your thing or you don't have time to maintain it, I found the Duplicate Post plugin Mahmod linked to be incredibly helpful on other sites I maintain: <a href=\"https://wordpress.org/plugins/duplicate-post/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/duplicate-post/</a></p>\n\n<p>Either way, good luck, and who knows why this isn't a core feature yet... but hopefully it will be some day!</p>\n" }, { "answer_id": 339563, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can add your one...</p>\n\n<pre><code>/*\n * Function creates post duplicate as a draft and redirects then to the edit post screen\n */\nfunction rd_duplicate_post_as_draft(){\n global $wpdb;\n if (! ( isset( $_GET['post']) || isset( $_POST['post']) || ( isset($_REQUEST['action']) &amp;&amp; 'rd_duplicate_post_as_draft' == $_REQUEST['action'] ) ) ) {\n wp_die('No post to duplicate has been supplied!');\n }\n\n /*\n * Nonce verification\n */\n if ( !isset( $_GET['duplicate_nonce'] ) || !wp_verify_nonce( $_GET['duplicate_nonce'], basename( __FILE__ ) ) )\n return;\n\n /*\n * get the original post id\n */\n $post_id = (isset($_GET['post']) ? absint( $_GET['post'] ) : absint( $_POST['post'] ) );\n /*\n * and all the original post data then\n */\n $post = get_post( $post_id );\n\n /*\n * if you don't want current user to be the new post author,\n * then change next couple of lines to this: $new_post_author = $post-&gt;post_author;\n */\n $current_user = wp_get_current_user();\n $new_post_author = $current_user-&gt;ID;\n\n /*\n * if post data exists, create the post duplicate\n */\n if (isset( $post ) &amp;&amp; $post != null) {\n\n /*\n * new post data array\n */\n $args = array(\n 'comment_status' =&gt; $post-&gt;comment_status,\n 'ping_status' =&gt; $post-&gt;ping_status,\n 'post_author' =&gt; $new_post_author,\n 'post_content' =&gt; $post-&gt;post_content,\n 'post_excerpt' =&gt; $post-&gt;post_excerpt,\n 'post_name' =&gt; $post-&gt;post_name,\n 'post_parent' =&gt; $post-&gt;post_parent,\n 'post_password' =&gt; $post-&gt;post_password,\n 'post_status' =&gt; 'draft',\n 'post_title' =&gt; $post-&gt;post_title,\n 'post_type' =&gt; $post-&gt;post_type,\n 'to_ping' =&gt; $post-&gt;to_ping,\n 'menu_order' =&gt; $post-&gt;menu_order\n );\n\n /*\n * insert the post by wp_insert_post() function\n */\n $new_post_id = wp_insert_post( $args );\n\n /*\n * get all current post terms ad set them to the new post draft\n */\n $taxonomies = get_object_taxonomies($post-&gt;post_type); // returns array of taxonomy names for post type, ex array(\"category\", \"post_tag\");\n foreach ($taxonomies as $taxonomy) {\n $post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' =&gt; 'slugs'));\n wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);\n }\n\n /*\n * duplicate all post meta just in two SQL queries\n */\n $post_meta_infos = $wpdb-&gt;get_results(\"SELECT meta_key, meta_value FROM $wpdb-&gt;postmeta WHERE post_id=$post_id\");\n if (count($post_meta_infos)!=0) {\n $sql_query = \"INSERT INTO $wpdb-&gt;postmeta (post_id, meta_key, meta_value) \";\n foreach ($post_meta_infos as $meta_info) {\n $meta_key = $meta_info-&gt;meta_key;\n if( $meta_key == '_wp_old_slug' ) continue;\n $meta_value = addslashes($meta_info-&gt;meta_value);\n $sql_query_sel[]= \"SELECT $new_post_id, '$meta_key', '$meta_value'\";\n }\n $sql_query.= implode(\" UNION ALL \", $sql_query_sel);\n $wpdb-&gt;query($sql_query);\n }\n\n\n /*\n * finally, redirect to the edit post screen for the new draft\n */\n wp_redirect( admin_url( 'post.php?action=edit&amp;post=' . $new_post_id ) );\n exit;\n } else {\n wp_die('Post creation failed, could not find original post: ' . $post_id);\n }\n}\nadd_action( 'admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft' );\n\n/*\n * Add the duplicate link to action list for post_row_actions\n */\nfunction rd_duplicate_post_link( $actions, $post ) {\n if (current_user_can('edit_posts')) {\n $actions['duplicate'] = '&lt;a href=\"' . wp_nonce_url('admin.php?action=rd_duplicate_post_as_draft&amp;post=' . $post-&gt;ID, basename(__FILE__), 'duplicate_nonce' ) . '\" title=\"Дублировать\" rel=\"permalink\"&gt;Дублировать&lt;/a&gt;';\n }\n return $actions;\n}\n\nadd_filter( 'post_row_actions', 'rd_duplicate_post_link', 10, 2 );\nadd_filter( 'page_row_actions', 'rd_duplicate_post_link', 10, 2 );\nadd_filter( 'product_row_actions', 'rd_duplicate_post_link', 10, 2 );\n</code></pre>\n" } ]
2019/06/04
[ "https://wordpress.stackexchange.com/questions/339517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123092/" ]
Does WordPress have a built-in function that allows duplicating posts? I am looking for something like `$new_post_id = duplicate_post(post_id);`
You can add your one... ``` /* * Function creates post duplicate as a draft and redirects then to the edit post screen */ function rd_duplicate_post_as_draft(){ global $wpdb; if (! ( isset( $_GET['post']) || isset( $_POST['post']) || ( isset($_REQUEST['action']) && 'rd_duplicate_post_as_draft' == $_REQUEST['action'] ) ) ) { wp_die('No post to duplicate has been supplied!'); } /* * Nonce verification */ if ( !isset( $_GET['duplicate_nonce'] ) || !wp_verify_nonce( $_GET['duplicate_nonce'], basename( __FILE__ ) ) ) return; /* * get the original post id */ $post_id = (isset($_GET['post']) ? absint( $_GET['post'] ) : absint( $_POST['post'] ) ); /* * and all the original post data then */ $post = get_post( $post_id ); /* * if you don't want current user to be the new post author, * then change next couple of lines to this: $new_post_author = $post->post_author; */ $current_user = wp_get_current_user(); $new_post_author = $current_user->ID; /* * if post data exists, create the post duplicate */ if (isset( $post ) && $post != null) { /* * new post data array */ $args = array( 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_author' => $new_post_author, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_name' => $post->post_name, 'post_parent' => $post->post_parent, 'post_password' => $post->post_password, 'post_status' => 'draft', 'post_title' => $post->post_title, 'post_type' => $post->post_type, 'to_ping' => $post->to_ping, 'menu_order' => $post->menu_order ); /* * insert the post by wp_insert_post() function */ $new_post_id = wp_insert_post( $args ); /* * get all current post terms ad set them to the new post draft */ $taxonomies = get_object_taxonomies($post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag"); foreach ($taxonomies as $taxonomy) { $post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs')); wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false); } /* * duplicate all post meta just in two SQL queries */ $post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id"); if (count($post_meta_infos)!=0) { $sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) "; foreach ($post_meta_infos as $meta_info) { $meta_key = $meta_info->meta_key; if( $meta_key == '_wp_old_slug' ) continue; $meta_value = addslashes($meta_info->meta_value); $sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'"; } $sql_query.= implode(" UNION ALL ", $sql_query_sel); $wpdb->query($sql_query); } /* * finally, redirect to the edit post screen for the new draft */ wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) ); exit; } else { wp_die('Post creation failed, could not find original post: ' . $post_id); } } add_action( 'admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft' ); /* * Add the duplicate link to action list for post_row_actions */ function rd_duplicate_post_link( $actions, $post ) { if (current_user_can('edit_posts')) { $actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=rd_duplicate_post_as_draft&post=' . $post->ID, basename(__FILE__), 'duplicate_nonce' ) . '" title="Дублировать" rel="permalink">Дублировать</a>'; } return $actions; } add_filter( 'post_row_actions', 'rd_duplicate_post_link', 10, 2 ); add_filter( 'page_row_actions', 'rd_duplicate_post_link', 10, 2 ); add_filter( 'product_row_actions', 'rd_duplicate_post_link', 10, 2 ); ```
339,533
<p>my site have multiple authors. I need to show all type of author posts in author page that if visitors can see all posts of author when visitied his profile page.</p> <p>this code</p> <pre><code> &lt;?php get_header(); ?&gt; &lt;!-- Show custom post type posts from the author --&gt; &lt;?php global $wp_query; query_posts( array( 'post_type' =&gt; 'sikayet' , 'author' =&gt; get_queried_object_id(), 'showposts' =&gt; 10 ) ); ?&gt; &lt;?php if ( have_posts() ): ?&gt; &lt;h3&gt;SIKAYETKLER &lt;?php echo $curauth-&gt;first_name; ?&gt;:&lt;/h3&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;p&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link: &lt;?php the_title(); ?&gt;"&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;p&gt;&lt;?php _e('User has no custom posts'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 339539, "author": "maryyyyyyy", "author_id": 159827, "author_profile": "https://wordpress.stackexchange.com/users/159827", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this is what you mean but this Wordpress function can display list of authors:</p>\n\n<pre><code>wp_list_authors( $args );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_list_authors\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_list_authors</a></p>\n\n<p>You can use this one to display the posts of an author:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters</a></p>\n\n<p>The author is the parameter.</p>\n" }, { "answer_id": 339549, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": true, "text": "<p>If you use WordPress <a href=\"https://codex.wordpress.org/Author_Templates\" rel=\"nofollow noreferrer\">author template</a> to show user posts ( <code>example.com/author/{user_name}</code> ) the best solution will be to change the main query via the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">pre_get_posts</a> filter hook.</p>\n\n<pre><code>function se339534_author_any_post_types $query ) {\n\n // apply changes only for author archive page\n if ( ! is_author() || ! $query-&gt;is_main_query() )\n return;\n\n $query-&gt;set('post_type', 'any');\n}\nadd_action( 'pre_get_posts', 'se339534_author_any_post_types' );\n</code></pre>\n" } ]
2019/06/04
[ "https://wordpress.stackexchange.com/questions/339533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168662/" ]
my site have multiple authors. I need to show all type of author posts in author page that if visitors can see all posts of author when visitied his profile page. this code ``` <?php get_header(); ?> <!-- Show custom post type posts from the author --> <?php global $wp_query; query_posts( array( 'post_type' => 'sikayet' , 'author' => get_queried_object_id(), 'showposts' => 10 ) ); ?> <?php if ( have_posts() ): ?> <h3>SIKAYETKLER <?php echo $curauth->first_name; ?>:</h3> <?php while ( have_posts() ) : the_post(); ?> <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"> <?php the_title(); ?></a></p> <?php endwhile; ?> <?php else: ?> <p><?php _e('User has no custom posts'); ?></p> <?php endif; ?> <?php get_footer(); ?> ```
If you use WordPress [author template](https://codex.wordpress.org/Author_Templates) to show user posts ( `example.com/author/{user_name}` ) the best solution will be to change the main query via the [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) filter hook. ``` function se339534_author_any_post_types $query ) { // apply changes only for author archive page if ( ! is_author() || ! $query->is_main_query() ) return; $query->set('post_type', 'any'); } add_action( 'pre_get_posts', 'se339534_author_any_post_types' ); ```
339,565
<p>I'm trying to make a post display some PHP code example. Using WordPress 5.2.1 with PHP 7.3</p> <p>The website works fine otherwise. However, when I'm editing a post, select "Formating - Code" and enter some PHP code within the block, it won't save the updated post version.</p> <p>"updating failed".</p> <p>Has anyone else had this problem? Tried disabling WordFence - didn't help.</p> <p>So it's either the (shared) hosting provider, or something with the WordPress.</p> <p>EDIT: The "problematic" code example:</p> <pre><code>// BEGIN Google Analytics function ns_google_analytics() { ?&gt; &lt;script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"&gt;&lt;/script&gt; &lt;script&gt; window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXXXXXX-X'); &lt;/script&gt; &lt;?php } add_action( 'wp_head', 'ns_google_analytics', 10 ); // END Google Analytics </code></pre> <p>To avoid misunderstanding: My attempt is/was to display the code in a post, like it is displayed here. When implementing it on a website, this goes into child theme's functions.php. But the post I'm trying to write is a tutorial one and should display the code sample so it can be easily copied by any visitor. The code (as shown) is not supposed to run on that post.</p>
[ { "answer_id": 339539, "author": "maryyyyyyy", "author_id": 159827, "author_profile": "https://wordpress.stackexchange.com/users/159827", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this is what you mean but this Wordpress function can display list of authors:</p>\n\n<pre><code>wp_list_authors( $args );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_list_authors\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_list_authors</a></p>\n\n<p>You can use this one to display the posts of an author:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters</a></p>\n\n<p>The author is the parameter.</p>\n" }, { "answer_id": 339549, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": true, "text": "<p>If you use WordPress <a href=\"https://codex.wordpress.org/Author_Templates\" rel=\"nofollow noreferrer\">author template</a> to show user posts ( <code>example.com/author/{user_name}</code> ) the best solution will be to change the main query via the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">pre_get_posts</a> filter hook.</p>\n\n<pre><code>function se339534_author_any_post_types $query ) {\n\n // apply changes only for author archive page\n if ( ! is_author() || ! $query-&gt;is_main_query() )\n return;\n\n $query-&gt;set('post_type', 'any');\n}\nadd_action( 'pre_get_posts', 'se339534_author_any_post_types' );\n</code></pre>\n" } ]
2019/06/04
[ "https://wordpress.stackexchange.com/questions/339565", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153697/" ]
I'm trying to make a post display some PHP code example. Using WordPress 5.2.1 with PHP 7.3 The website works fine otherwise. However, when I'm editing a post, select "Formating - Code" and enter some PHP code within the block, it won't save the updated post version. "updating failed". Has anyone else had this problem? Tried disabling WordFence - didn't help. So it's either the (shared) hosting provider, or something with the WordPress. EDIT: The "problematic" code example: ``` // BEGIN Google Analytics function ns_google_analytics() { ?> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXXXXXX-X'); </script> <?php } add_action( 'wp_head', 'ns_google_analytics', 10 ); // END Google Analytics ``` To avoid misunderstanding: My attempt is/was to display the code in a post, like it is displayed here. When implementing it on a website, this goes into child theme's functions.php. But the post I'm trying to write is a tutorial one and should display the code sample so it can be easily copied by any visitor. The code (as shown) is not supposed to run on that post.
If you use WordPress [author template](https://codex.wordpress.org/Author_Templates) to show user posts ( `example.com/author/{user_name}` ) the best solution will be to change the main query via the [pre\_get\_posts](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) filter hook. ``` function se339534_author_any_post_types $query ) { // apply changes only for author archive page if ( ! is_author() || ! $query->is_main_query() ) return; $query->set('post_type', 'any'); } add_action( 'pre_get_posts', 'se339534_author_any_post_types' ); ```
339,603
<p>I would like to get the list of all URLs from a wordpress installation. Nevertheless, I Don't want the full post titles in the permalink but I would like the shortlinks instead. I would like to get the following in the same fashion:</p> <pre><code>https://example.com/?p=123 https://example.com/?p=124 https://example.com/?p=125 https://example.com/?p=126 </code></pre>
[ { "answer_id": 339605, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 2, "selected": true, "text": "<p>You can get this from the <code>guid</code> column in the <code>posts</code> table of your database. </p>\n\n<p><a href=\"https://i.stack.imgur.com/vFdJZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vFdJZ.png\" alt=\"List of guids from database, eg http://wordpress.test/?p=1\"></a></p>\n" }, { "answer_id": 339609, "author": "Jakob Smith", "author_id": 169434, "author_profile": "https://wordpress.stackexchange.com/users/169434", "pm_score": 0, "selected": false, "text": "<p>Couple ways to go here, my friend. </p>\n\n<p><strong>Plugin:</strong>\nAll-in-SEO (<a href=\"https://wordpress.org/plugins/all-in-one-seo-pack/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/all-in-one-seo-pack/</a>). Generates a sitemap.xml that should be mighty useful for your needs.</p>\n\n<p><strong>Code:</strong>\nIf you need an array of permalinks to work with later, I'd recommend you use The Loop (<a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a>) to loop through all your posts, pages, etc. and feed the_permalink (<a href=\"https://codex.wordpress.org/Function_Reference/the_permalink\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/the_permalink</a>) in an array.</p>\n\n<p>Something like this:</p>\n\n<pre><code>&lt;?php\n // Not copy and paste safe, please read\n // This sets up what we want to fetch from the database\n // All the posts, pages, and any other custom post types\n // Setting 'posts_per_page' to -1 give you all the matches in the db\n $args = array('post_type' =&gt; array( 'post', 'page', 'any-other-custom-post-type'), 'posts_per_page' =&gt; -1 );\n\n // Go get what we want\n $WP_objects_I_will_loop_through = new WP_Query($args);\n\n //If there are any objects in the db that match our search...\n if ($WP_objects_I_will_loop_through-&gt;have_posts()):\n //loop through them and...\n while ($WP_objects_I_will_loop_through-&gt;have_posts()):\n //...Start with the first one, and then the next and....\n $WP_objects_I_will_loop_through-&gt;the_post();\n //...get the right post object each time through the loop\n global $post;\n // Create an array to fill with URL's and...\n $my_array_filled_with_urls = [];\n // Pop them in one at a time\n $my_array_filled_with_urls[] = get_permalink($post-&gt;ID);\n\n endwhile;\n endif;\n // Keeps you safe if you use this somewhere near another loop\n wp_reset_query();\n</code></pre>\n" } ]
2019/06/04
[ "https://wordpress.stackexchange.com/questions/339603", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71531/" ]
I would like to get the list of all URLs from a wordpress installation. Nevertheless, I Don't want the full post titles in the permalink but I would like the shortlinks instead. I would like to get the following in the same fashion: ``` https://example.com/?p=123 https://example.com/?p=124 https://example.com/?p=125 https://example.com/?p=126 ```
You can get this from the `guid` column in the `posts` table of your database. [![List of guids from database, eg http://wordpress.test/?p=1](https://i.stack.imgur.com/vFdJZ.png)](https://i.stack.imgur.com/vFdJZ.png)
339,606
<p>Here is how the loop looks? I need to exclude a few posts with the custom term, how can I manage it</p> <pre><code>&lt;?php global $post, $PIXAD_Autos; $Settings = new PIXAD_Settings(); $settings = $Settings-&gt;getSettings( 'WP_OPTIONS', '_pixad_autos_settings', true ); $validate = $Settings-&gt;getSettings( 'WP_OPTIONS', '_pixad_autos_validation', true ); // Get validation settings $showInSidebar = pixad::getsideviewfields($validate); $validate = pixad::validation( $validate ); // Fix undefined index notice $auto_translate = unserialize( get_option( '_pixad_auto_translate' ) ); ?&gt; &lt;div class="row"&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php $comment_args = array( 'status' =&gt; 'approve', 'post_id' =&gt; $post-&gt;ID, ); $comments = get_comments($comment_args); $post_rating = []; foreach($comments as $comment){ $post_rating[] = floatval( get_comment_meta( $comment-&gt;comment_ID, 'rating', true ) ); } ?&gt; &lt;div class="col-md-4"&gt; &lt;div class="slider-grid__inner slider-grid__inner_mod-b"&gt; &lt;div class="card__img"&gt; &lt;?php if( has_post_thumbnail() ): ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_post_thumbnail('autozone_latest_item', array('class' =&gt; 'img-responsive')); ?&gt; &lt;/a&gt; &lt;?php else: ?&gt; &lt;img class="no-image" src="&lt;?php echo PIXAD_AUTO_URI .'assets/img/no_image.jpg'; ?&gt;" alt="no-image"&gt; &lt;?php endif; ?&gt; &lt;?php if( get_post_meta(get_the_ID(), 'pixad_auto_featured_text', true) ): ?&gt; &lt;span class="card__wrap-label"&gt;&lt;span class="card__label"&gt;&lt;?php echo get_post_meta( get_the_ID(), 'pixad_auto_featured_text', true ); ?&gt;&lt;/span&gt;&lt;/span&gt; &lt;?php endif; ?&gt; &lt;?php if( $validate['auto-price_show'] &amp;&amp; $PIXAD_Autos-&gt;get_meta('_auto_price') ): ?&gt; &lt;span class="slider-grid__price_wrap"&gt;&lt;span class="slider-grid__price"&gt;&lt;span&gt;&lt;?php echo wp_kses_post($PIXAD_Autos-&gt;get_price()); ?&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt; &lt;?php endif; ?&gt; &lt;?php do_action( 'autozone_autos_single_auto_img', $post ); ?&gt; &lt;/div&gt; &lt;div class="tmpl-gray-footer"&gt; &lt;span class="tmpl-slider-grid__name"&gt;&lt;?php echo wp_kses_post(get_the_title())?&gt;&lt;/span&gt; &lt;?php if(!empty($post_rating)):?&gt; &lt;div class="star-rating"&gt;&lt;span style="width:&lt;?php echo esc_html( array_sum($post_rating)/count($post_rating) * 20 );?&gt;%"&gt;&lt;/span&gt;&lt;/div&gt; &lt;?php endif;?&gt; &lt;ul class="tmpl-slider-grid__info list-unstyled"&gt; &lt;?php foreach ($showInSidebar as $id =&gt; $sideAttribute):?&gt; &lt;?php $id='_'.$id; $id = str_replace('-', '_', $id); ?&gt; &lt;?php if( $PIXAD_Autos-&gt;get_meta($id) ): ?&gt; &lt;li&gt;&lt;i class="&lt;?php echo esc_html($sideAttribute['icon'])?&gt;"&gt;&lt;/i&gt; &lt;?php $val_attr = $PIXAD_Autos-&gt;get_meta($id); if(!empty($auto_translate[$val_attr]) ){ echo esc_html($auto_translate[$val_attr]); }else{ echo esc_html($PIXAD_Autos-&gt;get_meta($id)); } ?&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php endforeach;?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 339605, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 2, "selected": true, "text": "<p>You can get this from the <code>guid</code> column in the <code>posts</code> table of your database. </p>\n\n<p><a href=\"https://i.stack.imgur.com/vFdJZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vFdJZ.png\" alt=\"List of guids from database, eg http://wordpress.test/?p=1\"></a></p>\n" }, { "answer_id": 339609, "author": "Jakob Smith", "author_id": 169434, "author_profile": "https://wordpress.stackexchange.com/users/169434", "pm_score": 0, "selected": false, "text": "<p>Couple ways to go here, my friend. </p>\n\n<p><strong>Plugin:</strong>\nAll-in-SEO (<a href=\"https://wordpress.org/plugins/all-in-one-seo-pack/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/all-in-one-seo-pack/</a>). Generates a sitemap.xml that should be mighty useful for your needs.</p>\n\n<p><strong>Code:</strong>\nIf you need an array of permalinks to work with later, I'd recommend you use The Loop (<a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a>) to loop through all your posts, pages, etc. and feed the_permalink (<a href=\"https://codex.wordpress.org/Function_Reference/the_permalink\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/the_permalink</a>) in an array.</p>\n\n<p>Something like this:</p>\n\n<pre><code>&lt;?php\n // Not copy and paste safe, please read\n // This sets up what we want to fetch from the database\n // All the posts, pages, and any other custom post types\n // Setting 'posts_per_page' to -1 give you all the matches in the db\n $args = array('post_type' =&gt; array( 'post', 'page', 'any-other-custom-post-type'), 'posts_per_page' =&gt; -1 );\n\n // Go get what we want\n $WP_objects_I_will_loop_through = new WP_Query($args);\n\n //If there are any objects in the db that match our search...\n if ($WP_objects_I_will_loop_through-&gt;have_posts()):\n //loop through them and...\n while ($WP_objects_I_will_loop_through-&gt;have_posts()):\n //...Start with the first one, and then the next and....\n $WP_objects_I_will_loop_through-&gt;the_post();\n //...get the right post object each time through the loop\n global $post;\n // Create an array to fill with URL's and...\n $my_array_filled_with_urls = [];\n // Pop them in one at a time\n $my_array_filled_with_urls[] = get_permalink($post-&gt;ID);\n\n endwhile;\n endif;\n // Keeps you safe if you use this somewhere near another loop\n wp_reset_query();\n</code></pre>\n" } ]
2019/06/04
[ "https://wordpress.stackexchange.com/questions/339606", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169433/" ]
Here is how the loop looks? I need to exclude a few posts with the custom term, how can I manage it ``` <?php global $post, $PIXAD_Autos; $Settings = new PIXAD_Settings(); $settings = $Settings->getSettings( 'WP_OPTIONS', '_pixad_autos_settings', true ); $validate = $Settings->getSettings( 'WP_OPTIONS', '_pixad_autos_validation', true ); // Get validation settings $showInSidebar = pixad::getsideviewfields($validate); $validate = pixad::validation( $validate ); // Fix undefined index notice $auto_translate = unserialize( get_option( '_pixad_auto_translate' ) ); ?> <div class="row"> <?php while ( have_posts() ) : the_post(); ?> <?php $comment_args = array( 'status' => 'approve', 'post_id' => $post->ID, ); $comments = get_comments($comment_args); $post_rating = []; foreach($comments as $comment){ $post_rating[] = floatval( get_comment_meta( $comment->comment_ID, 'rating', true ) ); } ?> <div class="col-md-4"> <div class="slider-grid__inner slider-grid__inner_mod-b"> <div class="card__img"> <?php if( has_post_thumbnail() ): ?> <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail('autozone_latest_item', array('class' => 'img-responsive')); ?> </a> <?php else: ?> <img class="no-image" src="<?php echo PIXAD_AUTO_URI .'assets/img/no_image.jpg'; ?>" alt="no-image"> <?php endif; ?> <?php if( get_post_meta(get_the_ID(), 'pixad_auto_featured_text', true) ): ?> <span class="card__wrap-label"><span class="card__label"><?php echo get_post_meta( get_the_ID(), 'pixad_auto_featured_text', true ); ?></span></span> <?php endif; ?> <?php if( $validate['auto-price_show'] && $PIXAD_Autos->get_meta('_auto_price') ): ?> <span class="slider-grid__price_wrap"><span class="slider-grid__price"><span><?php echo wp_kses_post($PIXAD_Autos->get_price()); ?></span></span></span> <?php endif; ?> <?php do_action( 'autozone_autos_single_auto_img', $post ); ?> </div> <div class="tmpl-gray-footer"> <span class="tmpl-slider-grid__name"><?php echo wp_kses_post(get_the_title())?></span> <?php if(!empty($post_rating)):?> <div class="star-rating"><span style="width:<?php echo esc_html( array_sum($post_rating)/count($post_rating) * 20 );?>%"></span></div> <?php endif;?> <ul class="tmpl-slider-grid__info list-unstyled"> <?php foreach ($showInSidebar as $id => $sideAttribute):?> <?php $id='_'.$id; $id = str_replace('-', '_', $id); ?> <?php if( $PIXAD_Autos->get_meta($id) ): ?> <li><i class="<?php echo esc_html($sideAttribute['icon'])?>"></i> <?php $val_attr = $PIXAD_Autos->get_meta($id); if(!empty($auto_translate[$val_attr]) ){ echo esc_html($auto_translate[$val_attr]); }else{ echo esc_html($PIXAD_Autos->get_meta($id)); } ?> </li> <?php endif; ?> <?php endforeach;?> </ul> </div> </div> </div> <?php endwhile; ?> </div> ```
You can get this from the `guid` column in the `posts` table of your database. [![List of guids from database, eg http://wordpress.test/?p=1](https://i.stack.imgur.com/vFdJZ.png)](https://i.stack.imgur.com/vFdJZ.png)
339,612
<p>I’ve been searching for solution to my problem but posts already made are not fulfilling the answer to me, or I'm just not qualified enough to work this out. Here is what I need:</p> <p>I’ve got a simple landing page with a form. What I need is a way to create unique url’s for people I choose so only they can access this site and fill out the form. URL has to be active only for 7 days and once used, deactivated immediately. The unique URL’s should work a long, which means at the same time I can generate multiple URL’s.</p> <p>The other way to approach this problem is to generate many passwords that I can send to people I choose. Same story – every password is unique and works only once. Page is password restricted and when user puts the password in it’s no longer active.</p> <p>The best possible addition to this would be - deactivating / expiring the URL / visitor access the moment they send the form &lt;- but that's not necessary.</p> <p>I’m really not type of guy who just wants solution given to him on a silver platter, but right now… I have my back against the wall and literally no time. Any help is appreciated. Thank you.</p>
[ { "answer_id": 339613, "author": "brothman01", "author_id": 104630, "author_profile": "https://wordpress.stackexchange.com/users/104630", "pm_score": 0, "selected": false, "text": "<p>Is the page something they pay to gain access to? Why is the accessing it one time so important? Can they access it as many times as they want, but only for a day?\n(I know this is a comment but I do not have enough reputation to comment so can a moderator please move this over to a comment? thanks.)</p>\n" }, { "answer_id": 339615, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 2, "selected": false, "text": "<p>You could add a setting using <code>add_option( 'access_keys', [ 'key_1', 'key_2 ] )</code> to check against when loading the page.</p>\n\n<pre><code>add_action( 'init', 'wpse339612_check_access_codes' );\nfunction wpse339612_check_access_codes(){\n\n if( isset( $_GET['key'] ) ){\n\n $available_keys = get_option( 'access_keys' );\n\n $key_index = array_search( filter_var( $_GET['key'], $available_keys );\n\n if( $key_index !== false ){\n\n /*User has access! Delete the key from the available keys*/\n unset( $available_keys[$key_index] );\n update_option( 'access_keys', $available_keys );\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>Then whenever a user hits a URL of <a href=\"https://yoursite.com?key=key_1\" rel=\"nofollow noreferrer\">https://yoursite.com?key=key_1</a> they will get to the access condition and the key will be deleted from the database.</p>\n" } ]
2019/06/04
[ "https://wordpress.stackexchange.com/questions/339612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169436/" ]
I’ve been searching for solution to my problem but posts already made are not fulfilling the answer to me, or I'm just not qualified enough to work this out. Here is what I need: I’ve got a simple landing page with a form. What I need is a way to create unique url’s for people I choose so only they can access this site and fill out the form. URL has to be active only for 7 days and once used, deactivated immediately. The unique URL’s should work a long, which means at the same time I can generate multiple URL’s. The other way to approach this problem is to generate many passwords that I can send to people I choose. Same story – every password is unique and works only once. Page is password restricted and when user puts the password in it’s no longer active. The best possible addition to this would be - deactivating / expiring the URL / visitor access the moment they send the form <- but that's not necessary. I’m really not type of guy who just wants solution given to him on a silver platter, but right now… I have my back against the wall and literally no time. Any help is appreciated. Thank you.
You could add a setting using `add_option( 'access_keys', [ 'key_1', 'key_2 ] )` to check against when loading the page. ``` add_action( 'init', 'wpse339612_check_access_codes' ); function wpse339612_check_access_codes(){ if( isset( $_GET['key'] ) ){ $available_keys = get_option( 'access_keys' ); $key_index = array_search( filter_var( $_GET['key'], $available_keys ); if( $key_index !== false ){ /*User has access! Delete the key from the available keys*/ unset( $available_keys[$key_index] ); update_option( 'access_keys', $available_keys ); } } } ``` Then whenever a user hits a URL of <https://yoursite.com?key=key_1> they will get to the access condition and the key will be deleted from the database.
339,619
<p>I'm having a great deal of trouble phrasing this.</p> <p>If I were to use the filter </p> <pre><code>views_edit-page </code></pre> <p>How can I see what exactly is being passed through the filter so that I may edit them? Normally I would var_dump something similar to this, to get a breakdown of it's contents, but due to it being a filter, this does not seem to work.</p> <p>For example</p> <pre><code>add_filter('views_edit-page','addFilter'); function addFilter($views) { var_dump($views); die(); } </code></pre> <p>Is what I'd like to do, so that I may see exactly what $views consists of, in order to edit them. However, this does not work, what is a method I can use in order to see the content of $views?</p>
[ { "answer_id": 339613, "author": "brothman01", "author_id": 104630, "author_profile": "https://wordpress.stackexchange.com/users/104630", "pm_score": 0, "selected": false, "text": "<p>Is the page something they pay to gain access to? Why is the accessing it one time so important? Can they access it as many times as they want, but only for a day?\n(I know this is a comment but I do not have enough reputation to comment so can a moderator please move this over to a comment? thanks.)</p>\n" }, { "answer_id": 339615, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 2, "selected": false, "text": "<p>You could add a setting using <code>add_option( 'access_keys', [ 'key_1', 'key_2 ] )</code> to check against when loading the page.</p>\n\n<pre><code>add_action( 'init', 'wpse339612_check_access_codes' );\nfunction wpse339612_check_access_codes(){\n\n if( isset( $_GET['key'] ) ){\n\n $available_keys = get_option( 'access_keys' );\n\n $key_index = array_search( filter_var( $_GET['key'], $available_keys );\n\n if( $key_index !== false ){\n\n /*User has access! Delete the key from the available keys*/\n unset( $available_keys[$key_index] );\n update_option( 'access_keys', $available_keys );\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>Then whenever a user hits a URL of <a href=\"https://yoursite.com?key=key_1\" rel=\"nofollow noreferrer\">https://yoursite.com?key=key_1</a> they will get to the access condition and the key will be deleted from the database.</p>\n" } ]
2019/06/05
[ "https://wordpress.stackexchange.com/questions/339619", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146727/" ]
I'm having a great deal of trouble phrasing this. If I were to use the filter ``` views_edit-page ``` How can I see what exactly is being passed through the filter so that I may edit them? Normally I would var\_dump something similar to this, to get a breakdown of it's contents, but due to it being a filter, this does not seem to work. For example ``` add_filter('views_edit-page','addFilter'); function addFilter($views) { var_dump($views); die(); } ``` Is what I'd like to do, so that I may see exactly what $views consists of, in order to edit them. However, this does not work, what is a method I can use in order to see the content of $views?
You could add a setting using `add_option( 'access_keys', [ 'key_1', 'key_2 ] )` to check against when loading the page. ``` add_action( 'init', 'wpse339612_check_access_codes' ); function wpse339612_check_access_codes(){ if( isset( $_GET['key'] ) ){ $available_keys = get_option( 'access_keys' ); $key_index = array_search( filter_var( $_GET['key'], $available_keys ); if( $key_index !== false ){ /*User has access! Delete the key from the available keys*/ unset( $available_keys[$key_index] ); update_option( 'access_keys', $available_keys ); } } } ``` Then whenever a user hits a URL of <https://yoursite.com?key=key_1> they will get to the access condition and the key will be deleted from the database.
339,652
<p>I recently had to upload my wordpress website from live host (cpanel) to my localhost. (Took database from cpanel and updated it and changed the url settings in my database) Now when im entering the url <a href="http://localhost:8080/xxx/" rel="nofollow noreferrer">http://localhost:8080/xxx/</a> the page url redirects to <a href="http://localhost/xxx/" rel="nofollow noreferrer">http://localhost/xxx/</a> and is showing an error. I can visit <a href="http://localhost:8080/xxx/wp-admin" rel="nofollow noreferrer">http://localhost:8080/xxx/wp-admin</a> and all my pages but the home url/redirect is broken.</p> <p>Anyone know why this happening?</p>
[ { "answer_id": 339613, "author": "brothman01", "author_id": 104630, "author_profile": "https://wordpress.stackexchange.com/users/104630", "pm_score": 0, "selected": false, "text": "<p>Is the page something they pay to gain access to? Why is the accessing it one time so important? Can they access it as many times as they want, but only for a day?\n(I know this is a comment but I do not have enough reputation to comment so can a moderator please move this over to a comment? thanks.)</p>\n" }, { "answer_id": 339615, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 2, "selected": false, "text": "<p>You could add a setting using <code>add_option( 'access_keys', [ 'key_1', 'key_2 ] )</code> to check against when loading the page.</p>\n\n<pre><code>add_action( 'init', 'wpse339612_check_access_codes' );\nfunction wpse339612_check_access_codes(){\n\n if( isset( $_GET['key'] ) ){\n\n $available_keys = get_option( 'access_keys' );\n\n $key_index = array_search( filter_var( $_GET['key'], $available_keys );\n\n if( $key_index !== false ){\n\n /*User has access! Delete the key from the available keys*/\n unset( $available_keys[$key_index] );\n update_option( 'access_keys', $available_keys );\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>Then whenever a user hits a URL of <a href=\"https://yoursite.com?key=key_1\" rel=\"nofollow noreferrer\">https://yoursite.com?key=key_1</a> they will get to the access condition and the key will be deleted from the database.</p>\n" } ]
2019/06/05
[ "https://wordpress.stackexchange.com/questions/339652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167492/" ]
I recently had to upload my wordpress website from live host (cpanel) to my localhost. (Took database from cpanel and updated it and changed the url settings in my database) Now when im entering the url <http://localhost:8080/xxx/> the page url redirects to <http://localhost/xxx/> and is showing an error. I can visit <http://localhost:8080/xxx/wp-admin> and all my pages but the home url/redirect is broken. Anyone know why this happening?
You could add a setting using `add_option( 'access_keys', [ 'key_1', 'key_2 ] )` to check against when loading the page. ``` add_action( 'init', 'wpse339612_check_access_codes' ); function wpse339612_check_access_codes(){ if( isset( $_GET['key'] ) ){ $available_keys = get_option( 'access_keys' ); $key_index = array_search( filter_var( $_GET['key'], $available_keys ); if( $key_index !== false ){ /*User has access! Delete the key from the available keys*/ unset( $available_keys[$key_index] ); update_option( 'access_keys', $available_keys ); } } } ``` Then whenever a user hits a URL of <https://yoursite.com?key=key_1> they will get to the access condition and the key will be deleted from the database.
339,699
<p>Thank you for reading my question.</p> <p>I can't seem to figure out a way to make this page full width (or almost full width). When i am on tablet and mobile phone it does fill the screen almost entirely. Does anyone have a suggestion about where to start with customising these settings?</p> <p>Thank you.</p> <pre><code>&lt;?php /** * Template Name: Full Width * */ get_header(); ?&gt; &lt;div class="row"&gt; &lt;div id="primary" class="content-area"&gt; &lt;div class="large-12 columns"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php get_template_part( 'template-parts/content', 'page' ); ?&gt; &lt;?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?&gt; &lt;?php endwhile; // end of the loop. ?&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- .large-12 --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;/div&gt;&lt;!-- .row --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>i use the template shown above on the homepage of my site.</p> <p><a href="https://www.tuberadar.nl" rel="nofollow noreferrer">https://www.tuberadar.nl</a></p>
[ { "answer_id": 339613, "author": "brothman01", "author_id": 104630, "author_profile": "https://wordpress.stackexchange.com/users/104630", "pm_score": 0, "selected": false, "text": "<p>Is the page something they pay to gain access to? Why is the accessing it one time so important? Can they access it as many times as they want, but only for a day?\n(I know this is a comment but I do not have enough reputation to comment so can a moderator please move this over to a comment? thanks.)</p>\n" }, { "answer_id": 339615, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 2, "selected": false, "text": "<p>You could add a setting using <code>add_option( 'access_keys', [ 'key_1', 'key_2 ] )</code> to check against when loading the page.</p>\n\n<pre><code>add_action( 'init', 'wpse339612_check_access_codes' );\nfunction wpse339612_check_access_codes(){\n\n if( isset( $_GET['key'] ) ){\n\n $available_keys = get_option( 'access_keys' );\n\n $key_index = array_search( filter_var( $_GET['key'], $available_keys );\n\n if( $key_index !== false ){\n\n /*User has access! Delete the key from the available keys*/\n unset( $available_keys[$key_index] );\n update_option( 'access_keys', $available_keys );\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>Then whenever a user hits a URL of <a href=\"https://yoursite.com?key=key_1\" rel=\"nofollow noreferrer\">https://yoursite.com?key=key_1</a> they will get to the access condition and the key will be deleted from the database.</p>\n" } ]
2019/06/06
[ "https://wordpress.stackexchange.com/questions/339699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162007/" ]
Thank you for reading my question. I can't seem to figure out a way to make this page full width (or almost full width). When i am on tablet and mobile phone it does fill the screen almost entirely. Does anyone have a suggestion about where to start with customising these settings? Thank you. ``` <?php /** * Template Name: Full Width * */ get_header(); ?> <div class="row"> <div id="primary" class="content-area"> <div class="large-12 columns"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'template-parts/content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- .large-12 --> </div><!-- #primary --> </div><!-- .row --> <?php get_footer(); ?> ``` i use the template shown above on the homepage of my site. <https://www.tuberadar.nl>
You could add a setting using `add_option( 'access_keys', [ 'key_1', 'key_2 ] )` to check against when loading the page. ``` add_action( 'init', 'wpse339612_check_access_codes' ); function wpse339612_check_access_codes(){ if( isset( $_GET['key'] ) ){ $available_keys = get_option( 'access_keys' ); $key_index = array_search( filter_var( $_GET['key'], $available_keys ); if( $key_index !== false ){ /*User has access! Delete the key from the available keys*/ unset( $available_keys[$key_index] ); update_option( 'access_keys', $available_keys ); } } } ``` Then whenever a user hits a URL of <https://yoursite.com?key=key_1> they will get to the access condition and the key will be deleted from the database.
339,712
<p>This might be a beginner question, for disclaimer I'm just getting used to the WordPress templating system:</p> <p><strong>I have a purchased theme installed on my working WordPress site</strong>, looking great sofar, was relatively easy to setup.</p> <p><strong>I installed a plugin for members functionality (Ultimate Member)</strong>, then I wanted to <strong>list a group of members</strong> I created in the design with the following shortcode:</p> <p><code>[ultimatemember form_id="xxxx"]</code></p> <p>It displays a list of my members, fine, but in some kind of default design <em>(header/footer, other contents are ok, like the template, I can put stuff before or after the generated list, but the member's thumb and info are not exactly as it needs to be as per client's requests)</em></p> <p>On the other hand, my template's "Meet the Team" page which I intend to use is only a combination of "Mikado Team" elements in the page editor, where I can input team member informations right away, in text format.</p> <p><strong>How do I implement Ultimate Member's listing to a template like that?</strong> In my imagination that would be like setting the specific datas assigned to design parts, like I have on the "Meet the Team" template page:</p> <pre><code>[mkdf_team team_name="Jane Doe" ... etc data settings] </code></pre> <p><strong>How do I set the datas to be as the member list of Ultimate Member?</strong></p> <p>The only thing I could think of is modifying the "members-grid.php" file as it controls how Ultimate Member displays those lists, but I'm sure there's an easier solution for this. :)</p>
[ { "answer_id": 339613, "author": "brothman01", "author_id": 104630, "author_profile": "https://wordpress.stackexchange.com/users/104630", "pm_score": 0, "selected": false, "text": "<p>Is the page something they pay to gain access to? Why is the accessing it one time so important? Can they access it as many times as they want, but only for a day?\n(I know this is a comment but I do not have enough reputation to comment so can a moderator please move this over to a comment? thanks.)</p>\n" }, { "answer_id": 339615, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 2, "selected": false, "text": "<p>You could add a setting using <code>add_option( 'access_keys', [ 'key_1', 'key_2 ] )</code> to check against when loading the page.</p>\n\n<pre><code>add_action( 'init', 'wpse339612_check_access_codes' );\nfunction wpse339612_check_access_codes(){\n\n if( isset( $_GET['key'] ) ){\n\n $available_keys = get_option( 'access_keys' );\n\n $key_index = array_search( filter_var( $_GET['key'], $available_keys );\n\n if( $key_index !== false ){\n\n /*User has access! Delete the key from the available keys*/\n unset( $available_keys[$key_index] );\n update_option( 'access_keys', $available_keys );\n\n }\n\n }\n\n}\n</code></pre>\n\n<p>Then whenever a user hits a URL of <a href=\"https://yoursite.com?key=key_1\" rel=\"nofollow noreferrer\">https://yoursite.com?key=key_1</a> they will get to the access condition and the key will be deleted from the database.</p>\n" } ]
2019/06/06
[ "https://wordpress.stackexchange.com/questions/339712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169496/" ]
This might be a beginner question, for disclaimer I'm just getting used to the WordPress templating system: **I have a purchased theme installed on my working WordPress site**, looking great sofar, was relatively easy to setup. **I installed a plugin for members functionality (Ultimate Member)**, then I wanted to **list a group of members** I created in the design with the following shortcode: `[ultimatemember form_id="xxxx"]` It displays a list of my members, fine, but in some kind of default design *(header/footer, other contents are ok, like the template, I can put stuff before or after the generated list, but the member's thumb and info are not exactly as it needs to be as per client's requests)* On the other hand, my template's "Meet the Team" page which I intend to use is only a combination of "Mikado Team" elements in the page editor, where I can input team member informations right away, in text format. **How do I implement Ultimate Member's listing to a template like that?** In my imagination that would be like setting the specific datas assigned to design parts, like I have on the "Meet the Team" template page: ``` [mkdf_team team_name="Jane Doe" ... etc data settings] ``` **How do I set the datas to be as the member list of Ultimate Member?** The only thing I could think of is modifying the "members-grid.php" file as it controls how Ultimate Member displays those lists, but I'm sure there's an easier solution for this. :)
You could add a setting using `add_option( 'access_keys', [ 'key_1', 'key_2 ] )` to check against when loading the page. ``` add_action( 'init', 'wpse339612_check_access_codes' ); function wpse339612_check_access_codes(){ if( isset( $_GET['key'] ) ){ $available_keys = get_option( 'access_keys' ); $key_index = array_search( filter_var( $_GET['key'], $available_keys ); if( $key_index !== false ){ /*User has access! Delete the key from the available keys*/ unset( $available_keys[$key_index] ); update_option( 'access_keys', $available_keys ); } } } ``` Then whenever a user hits a URL of <https://yoursite.com?key=key_1> they will get to the access condition and the key will be deleted from the database.
339,718
<p>Can anyone explain why I cannot see the role from the code below:</p> <pre><code>$userID = get_current_user_id(); $user = get_userdata(userID); &lt;?php echo $user-&gt;roles; ?&gt; </code></pre> <p>but I can see all the other user data such as </p> <pre><code>&lt;?php echo $user-&gt;ID; ?&gt; &lt;?php echo $user-&gt;user_login; ?&gt; </code></pre> <p>I'm following <a href="https://codex.wordpress.org/Function_Reference/get_userdata" rel="nofollow noreferrer">this</a> documentation.</p>
[ { "answer_id": 339721, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>You can't see any roles printed, because the <code>-&gt;roles</code> field is an <code>Array</code>, so you can't print it using <code>echo</code>. User <code>print_r</code> instead.</p>\n\n<p>You also have an error in this line:</p>\n\n<pre><code>$user = get_userdata(userID);\n</code></pre>\n\n<p>There is no such thing like <code>userID</code> - it should be <code>$userID</code>.</p>\n" }, { "answer_id": 339724, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 0, "selected": false, "text": "<p>Please change</p>\n\n<pre><code>$user = get_userdata(userID);\n</code></pre>\n\n<p>To</p>\n\n<pre><code>$user = get_userdata(YOUR_USER_ID_VARIABLE);\n</code></pre>\n\n<p>And check using <code>print_r($user-&gt;roles);</code></p>\n" } ]
2019/06/06
[ "https://wordpress.stackexchange.com/questions/339718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169499/" ]
Can anyone explain why I cannot see the role from the code below: ``` $userID = get_current_user_id(); $user = get_userdata(userID); <?php echo $user->roles; ?> ``` but I can see all the other user data such as ``` <?php echo $user->ID; ?> <?php echo $user->user_login; ?> ``` I'm following [this](https://codex.wordpress.org/Function_Reference/get_userdata) documentation.
You can't see any roles printed, because the `->roles` field is an `Array`, so you can't print it using `echo`. User `print_r` instead. You also have an error in this line: ``` $user = get_userdata(userID); ``` There is no such thing like `userID` - it should be `$userID`.
339,850
<p>As my understanding, The <code>wp_ajax_{action}</code> hook only fires for logged in users. For logged-out users, <code>wp_ajax_nopriv_{action}</code>action is triggered on an ajax request.</p> <p>So, how can I write for both logged and non-logged users? Do I have to write two functions?</p> <p>Eg Situation: There is a form which can be filled by both logged and non-logged users.</p>
[ { "answer_id": 339851, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 2, "selected": false, "text": "<p>No. You have to write only one function. For example,</p>\n\n<pre><code>function ajaxTest(){\n//your code\n}\nadd_action('wp_ajax_ajaxTest', 'ajaxTest');\nadd_action('wp_ajax_nopriv_ajaxTest', 'ajaxTest');\n</code></pre>\n" }, { "answer_id": 339855, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>You can add the function to both hooks:</p>\n\n<pre><code>add_action('wp_ajax_ajaxTest', 'ajaxTest');\nadd_action('wp_ajax_nopriv_ajaxTest', 'ajaxTest');\n</code></pre>\n\n<p>But, there's a better way to do it, use a REST API endpoint:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'yourstuff/v1', '/test/', array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'yourstuff_test_endpoint'\n ) );\n} );\n\nfunction yourstuff_test_endpoint( $request ) {\n $stuff = $request['stuff'];\n return \"Received \".esc_html( $stuff );\n}\n</code></pre>\n\n<p>Now if we flush our permalinks we'll find a new endpoint at <code>example.com/wp-json/yourstuff/v1/test</code>, and when we do a POST request to it, we get back a JSON string. E.g.</p>\n\n<pre><code>jQuery.ajax( {\n url: '/wp-json/yourstuff/v1/test',\n method: 'POST',\n data:{\n 'stuff' : 'Hello World!'\n }\n} ).done( function ( response ) {\n console.log( response );\n} );\n</code></pre>\n\n<p>With that JavaScript I would expect to see the following in the console:</p>\n\n<pre><code>\"Received Hello World!\"\n</code></pre>\n\n<p>You can pass more parameters to <code>register_rest_route</code> telling it about what arguments your request expects/needs/are optional, authentication, validation, sanitisation, and it will take care of it all for you.</p>\n\n<p>With WP Admin AJAX, you have to do all of it yourself, and hope that you built it right, as well as program in all the possible errors. The REST API does that all for you</p>\n" } ]
2019/06/07
[ "https://wordpress.stackexchange.com/questions/339850", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123092/" ]
As my understanding, The `wp_ajax_{action}` hook only fires for logged in users. For logged-out users, `wp_ajax_nopriv_{action}`action is triggered on an ajax request. So, how can I write for both logged and non-logged users? Do I have to write two functions? Eg Situation: There is a form which can be filled by both logged and non-logged users.
You can add the function to both hooks: ``` add_action('wp_ajax_ajaxTest', 'ajaxTest'); add_action('wp_ajax_nopriv_ajaxTest', 'ajaxTest'); ``` But, there's a better way to do it, use a REST API endpoint: ``` add_action( 'rest_api_init', function () { register_rest_route( 'yourstuff/v1', '/test/', array( 'methods' => 'POST', 'callback' => 'yourstuff_test_endpoint' ) ); } ); function yourstuff_test_endpoint( $request ) { $stuff = $request['stuff']; return "Received ".esc_html( $stuff ); } ``` Now if we flush our permalinks we'll find a new endpoint at `example.com/wp-json/yourstuff/v1/test`, and when we do a POST request to it, we get back a JSON string. E.g. ``` jQuery.ajax( { url: '/wp-json/yourstuff/v1/test', method: 'POST', data:{ 'stuff' : 'Hello World!' } } ).done( function ( response ) { console.log( response ); } ); ``` With that JavaScript I would expect to see the following in the console: ``` "Received Hello World!" ``` You can pass more parameters to `register_rest_route` telling it about what arguments your request expects/needs/are optional, authentication, validation, sanitisation, and it will take care of it all for you. With WP Admin AJAX, you have to do all of it yourself, and hope that you built it right, as well as program in all the possible errors. The REST API does that all for you
339,904
<p>As my title explains I am trying to migrate a customers Wordpress site to new environment and domain. Why? because Godaddy instance exploded and everything went down. I only have the complete website dumps taken from CPANEL. This includes all the website folders and a SQL dump. Of course everything in the DB and files points to the old environment.</p> <p>How do I achieve this in 2019? Do I still have to painstakingly piece together everything manually?</p> <p>Recap:</p> <ul> <li>Migrate Wordpress site with a Zip file backup made from cpanel (includes files and DB).</li> <li>New domain name</li> <li>New environment</li> </ul>
[ { "answer_id": 339911, "author": "Debbie Kurth", "author_id": 119560, "author_profile": "https://wordpress.stackexchange.com/users/119560", "pm_score": 2, "selected": true, "text": "<p>Migration with domain change can be tricky and not for the faint of heart. It is much easier to keep the domain the same and port it over to a new environment and then changes the domain. Then, at the very most, it is just a matter of passwords for the database resident in the root via file: wp_config.php file.</p>\n\n<p>Classicly there are two solutions, based on what environment you are going \"to\". </p>\n\n<p>If you have access to the WHM, then you have the lovely tool <em>WHM >> Home >> Transfers >> Transfer Tool</em>. This will do all the work for you.</p>\n\n<p>If not, then you are in for a bit of a harder road, given you want to change the domain name at the same time. The method I have used in the past, is a 2 part solution.</p>\n\n<ol>\n<li><p>Break up the full backup into full source files and the .gz file for the mysql database.</p></li>\n<li><p>Import the database using the PhpMySQL CPanel tool. Make sure the database is empty and import the database directly via the import option.</p>\n\n<ol start=\"3\">\n<li>Using the Cpanel assign the database name and the password.</li>\n<li>Copy all the files to the HTML folder one for one. Typically this is called \"public_html\"</li>\n<li>While they are copying you are going to need to manually change the database domain name. There is a good website that explains all the areas you will need to change.</li>\n</ol></li>\n</ol>\n\n<p><a href=\"https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-\" rel=\"nofollow noreferrer\">https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-</a></p>\n\n<ol start=\"6\">\n<li><p>Then you will need to modify the wp_config.php, resident in the HTML folder as follows: </p>\n\n<pre><code> /** The name of the database for WordPress */\n define('DB_NAME', 'site_wrdp1');\n\n /** MySQL database username */\n define('DB_USER', 'site_wrdp1');\n\n /** MySQL database password */\n define('DB_PASSWORD', 'password');\n</code></pre></li>\n</ol>\n\n<p>and place a rewrite code (since you are changing domain names)</p>\n\n<pre><code> #Options +FollowSymLinks\n RewriteEngine on\n RewriteRule ^(.*)$ http://www.newsite.COM/$1 [R=301,L]\n</code></pre>\n\n<p>Place that code at the top of the wp_config.php file.\nThen you fire it up and see what happens. Usually it is the database user name and password that is the problem. Another good site, that covers a lot of this, in much more detail is: \n<a href=\"https://wedevs.com/92444/change-wordpress-site-address/\" rel=\"nofollow noreferrer\">https://wedevs.com/92444/change-wordpress-site-address/</a></p>\n\n<p>Hope this helps...good luck</p>\n" }, { "answer_id": 341853, "author": "Emerson Maningo", "author_id": 20972, "author_profile": "https://wordpress.stackexchange.com/users/20972", "pm_score": 0, "selected": false, "text": "<p>Assuming you can still access your WordPress admin, install new plugins and your original/source website is working (front-end / backend). You can install this plugin: <a href=\"https://wordpress.org/plugins/prime-mover/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/prime-mover/</a></p>\n\n<p>You can export the entire website package (complete export mode: db + media + plugins + themes) as a single zip and download it to your computer.</p>\n\n<p>Then in your new server / new domain, install a blank WordPress (fresh install) and activate Prime Mover plugin. Go to Tools - Migration Tools. Restore the package zip you downloaded earlier and it should be uploaded/restored to your new domain. Now your site is fully migrated.</p>\n\n<p>The plugin handles all things automatically including changes in db/ copying files ,etc. You don't need to mess with PHP code or server settings.</p>\n" } ]
2019/06/08
[ "https://wordpress.stackexchange.com/questions/339904", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169630/" ]
As my title explains I am trying to migrate a customers Wordpress site to new environment and domain. Why? because Godaddy instance exploded and everything went down. I only have the complete website dumps taken from CPANEL. This includes all the website folders and a SQL dump. Of course everything in the DB and files points to the old environment. How do I achieve this in 2019? Do I still have to painstakingly piece together everything manually? Recap: * Migrate Wordpress site with a Zip file backup made from cpanel (includes files and DB). * New domain name * New environment
Migration with domain change can be tricky and not for the faint of heart. It is much easier to keep the domain the same and port it over to a new environment and then changes the domain. Then, at the very most, it is just a matter of passwords for the database resident in the root via file: wp\_config.php file. Classicly there are two solutions, based on what environment you are going "to". If you have access to the WHM, then you have the lovely tool *WHM >> Home >> Transfers >> Transfer Tool*. This will do all the work for you. If not, then you are in for a bit of a harder road, given you want to change the domain name at the same time. The method I have used in the past, is a 2 part solution. 1. Break up the full backup into full source files and the .gz file for the mysql database. 2. Import the database using the PhpMySQL CPanel tool. Make sure the database is empty and import the database directly via the import option. 3. Using the Cpanel assign the database name and the password. 4. Copy all the files to the HTML folder one for one. Typically this is called "public\_html" 5. While they are copying you are going to need to manually change the database domain name. There is a good website that explains all the areas you will need to change. <https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-> 6. Then you will need to modify the wp\_config.php, resident in the HTML folder as follows: ``` /** The name of the database for WordPress */ define('DB_NAME', 'site_wrdp1'); /** MySQL database username */ define('DB_USER', 'site_wrdp1'); /** MySQL database password */ define('DB_PASSWORD', 'password'); ``` and place a rewrite code (since you are changing domain names) ``` #Options +FollowSymLinks RewriteEngine on RewriteRule ^(.*)$ http://www.newsite.COM/$1 [R=301,L] ``` Place that code at the top of the wp\_config.php file. Then you fire it up and see what happens. Usually it is the database user name and password that is the problem. Another good site, that covers a lot of this, in much more detail is: <https://wedevs.com/92444/change-wordpress-site-address/> Hope this helps...good luck
339,909
<p>I am creating a dynamic page, in a WordPress environment. The page is created by a default standard WordPress page and then using shortcode. Combined with URL parameters in order to retrieve the necessary data. </p> <p>The problem is, this page, including the URL parameters, is "shareable" to facebook and other social media. Thus the description that comes up is too generic. I assume this is because the default page, on which the shortcode resides, is also generic. That is what I want to change based on the data I am retrieving for display.</p> <p>I have tried the code below and a few other variations, with no luck. In fact the filter is not even executed. Tried embedding the filter into an add_action call..the action call is done, but the filter remains executed. </p> <pre><code> add_filter('wp_title','ChangeTitle', 10, 2); function ChangeTitle($title, $id) { if ( $title== 'Details' ) { $BusinessName = $_GET['Name']; return $BusinessName; } return $title; } </code></pre> <p>Does anyone have a clever way to do this? part two of the question, would be how to assign a logo to the share.... but one thing at a time.</p>
[ { "answer_id": 339911, "author": "Debbie Kurth", "author_id": 119560, "author_profile": "https://wordpress.stackexchange.com/users/119560", "pm_score": 2, "selected": true, "text": "<p>Migration with domain change can be tricky and not for the faint of heart. It is much easier to keep the domain the same and port it over to a new environment and then changes the domain. Then, at the very most, it is just a matter of passwords for the database resident in the root via file: wp_config.php file.</p>\n\n<p>Classicly there are two solutions, based on what environment you are going \"to\". </p>\n\n<p>If you have access to the WHM, then you have the lovely tool <em>WHM >> Home >> Transfers >> Transfer Tool</em>. This will do all the work for you.</p>\n\n<p>If not, then you are in for a bit of a harder road, given you want to change the domain name at the same time. The method I have used in the past, is a 2 part solution.</p>\n\n<ol>\n<li><p>Break up the full backup into full source files and the .gz file for the mysql database.</p></li>\n<li><p>Import the database using the PhpMySQL CPanel tool. Make sure the database is empty and import the database directly via the import option.</p>\n\n<ol start=\"3\">\n<li>Using the Cpanel assign the database name and the password.</li>\n<li>Copy all the files to the HTML folder one for one. Typically this is called \"public_html\"</li>\n<li>While they are copying you are going to need to manually change the database domain name. There is a good website that explains all the areas you will need to change.</li>\n</ol></li>\n</ol>\n\n<p><a href=\"https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-\" rel=\"nofollow noreferrer\">https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-</a></p>\n\n<ol start=\"6\">\n<li><p>Then you will need to modify the wp_config.php, resident in the HTML folder as follows: </p>\n\n<pre><code> /** The name of the database for WordPress */\n define('DB_NAME', 'site_wrdp1');\n\n /** MySQL database username */\n define('DB_USER', 'site_wrdp1');\n\n /** MySQL database password */\n define('DB_PASSWORD', 'password');\n</code></pre></li>\n</ol>\n\n<p>and place a rewrite code (since you are changing domain names)</p>\n\n<pre><code> #Options +FollowSymLinks\n RewriteEngine on\n RewriteRule ^(.*)$ http://www.newsite.COM/$1 [R=301,L]\n</code></pre>\n\n<p>Place that code at the top of the wp_config.php file.\nThen you fire it up and see what happens. Usually it is the database user name and password that is the problem. Another good site, that covers a lot of this, in much more detail is: \n<a href=\"https://wedevs.com/92444/change-wordpress-site-address/\" rel=\"nofollow noreferrer\">https://wedevs.com/92444/change-wordpress-site-address/</a></p>\n\n<p>Hope this helps...good luck</p>\n" }, { "answer_id": 341853, "author": "Emerson Maningo", "author_id": 20972, "author_profile": "https://wordpress.stackexchange.com/users/20972", "pm_score": 0, "selected": false, "text": "<p>Assuming you can still access your WordPress admin, install new plugins and your original/source website is working (front-end / backend). You can install this plugin: <a href=\"https://wordpress.org/plugins/prime-mover/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/prime-mover/</a></p>\n\n<p>You can export the entire website package (complete export mode: db + media + plugins + themes) as a single zip and download it to your computer.</p>\n\n<p>Then in your new server / new domain, install a blank WordPress (fresh install) and activate Prime Mover plugin. Go to Tools - Migration Tools. Restore the package zip you downloaded earlier and it should be uploaded/restored to your new domain. Now your site is fully migrated.</p>\n\n<p>The plugin handles all things automatically including changes in db/ copying files ,etc. You don't need to mess with PHP code or server settings.</p>\n" } ]
2019/06/08
[ "https://wordpress.stackexchange.com/questions/339909", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119560/" ]
I am creating a dynamic page, in a WordPress environment. The page is created by a default standard WordPress page and then using shortcode. Combined with URL parameters in order to retrieve the necessary data. The problem is, this page, including the URL parameters, is "shareable" to facebook and other social media. Thus the description that comes up is too generic. I assume this is because the default page, on which the shortcode resides, is also generic. That is what I want to change based on the data I am retrieving for display. I have tried the code below and a few other variations, with no luck. In fact the filter is not even executed. Tried embedding the filter into an add\_action call..the action call is done, but the filter remains executed. ``` add_filter('wp_title','ChangeTitle', 10, 2); function ChangeTitle($title, $id) { if ( $title== 'Details' ) { $BusinessName = $_GET['Name']; return $BusinessName; } return $title; } ``` Does anyone have a clever way to do this? part two of the question, would be how to assign a logo to the share.... but one thing at a time.
Migration with domain change can be tricky and not for the faint of heart. It is much easier to keep the domain the same and port it over to a new environment and then changes the domain. Then, at the very most, it is just a matter of passwords for the database resident in the root via file: wp\_config.php file. Classicly there are two solutions, based on what environment you are going "to". If you have access to the WHM, then you have the lovely tool *WHM >> Home >> Transfers >> Transfer Tool*. This will do all the work for you. If not, then you are in for a bit of a harder road, given you want to change the domain name at the same time. The method I have used in the past, is a 2 part solution. 1. Break up the full backup into full source files and the .gz file for the mysql database. 2. Import the database using the PhpMySQL CPanel tool. Make sure the database is empty and import the database directly via the import option. 3. Using the Cpanel assign the database name and the password. 4. Copy all the files to the HTML folder one for one. Typically this is called "public\_html" 5. While they are copying you are going to need to manually change the database domain name. There is a good website that explains all the areas you will need to change. <https://help.dreamhost.com/hc/en-us/articles/214580498-How-do-I-change-the-WordPress-Site-URL-> 6. Then you will need to modify the wp\_config.php, resident in the HTML folder as follows: ``` /** The name of the database for WordPress */ define('DB_NAME', 'site_wrdp1'); /** MySQL database username */ define('DB_USER', 'site_wrdp1'); /** MySQL database password */ define('DB_PASSWORD', 'password'); ``` and place a rewrite code (since you are changing domain names) ``` #Options +FollowSymLinks RewriteEngine on RewriteRule ^(.*)$ http://www.newsite.COM/$1 [R=301,L] ``` Place that code at the top of the wp\_config.php file. Then you fire it up and see what happens. Usually it is the database user name and password that is the problem. Another good site, that covers a lot of this, in much more detail is: <https://wedevs.com/92444/change-wordpress-site-address/> Hope this helps...good luck
339,923
<p><a href="https://www.hongkiat.com/blog/wordpress-admin-color-scheme/" rel="noreferrer">I followed this guide</a>, but idk if it doesnt work for WP 5.0+ or if im doing something wrong. </p> <p>I added this to my functions.php and the css file is a copy of the Light Scheme.</p> <pre><code> function additional_admin_color_schemes() { $theme_dir = get_template_directory_uri(); wp_admin_css_color( 'pro', __( 'Pro' ), $theme_dir . '/wp-content/themes/astra-child/pro/colors.min.css', array( '#E5E5E5', '#E5E5E5', '#3498DB', '#3498DB' ) ); } add_action('admin_init', 'additional_admin_color_schemes'); </code></pre>
[ { "answer_id": 339925, "author": "Paul G.", "author_id": 41288, "author_profile": "https://wordpress.stackexchange.com/users/41288", "pm_score": 2, "selected": false, "text": "<p>This code works with WordPress 5.2 and is correct.</p>\n\n<p>You now need to go to your Profile and select it by going to\n<code>Users</code> > <code>Your Profile</code> > <code>Admin Color Scheme</code>\nselect the scheme and save.</p>\n\n<p><a href=\"https://i.stack.imgur.com/0xlHm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0xlHm.png\" alt=\"enter image description here\"></a></p>\n\n<p>Edit: Adding updated code for your colors CSS file since you're using a child theme:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function additional_admin_color_schemes() {\n wp_admin_css_color( 'pro', __( 'Pro' ),\n get_stylesheet_directory_uri().'/wp-content/themes/astra-child/pro/colors.css',\n [ '#E5E5E5', '#E5E5E5', '#3498DB', '#3498DB' ]\n );\n}\nadd_action( 'admin_init', 'additional_admin_color_schemes' );\n</code></pre>\n\n<p>Note here I removed the <code>.min</code> from the CSS file. I recommend you copy the non-minified CSS file over, so you can easily edit and customize the styles.</p>\n" }, { "answer_id": 413423, "author": "Jafar Abazeed", "author_id": 161580, "author_profile": "https://wordpress.stackexchange.com/users/161580", "pm_score": 0, "selected": false, "text": "<p>Check this website, it allows you to pick the colors and generate the style sheet and code needed to add the new color scheme: <a href=\"https://wpadmincolors.com/\" rel=\"nofollow noreferrer\"><strong>WordPress Admin Colors</strong></a>.</p>\n" } ]
2019/06/08
[ "https://wordpress.stackexchange.com/questions/339923", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169632/" ]
[I followed this guide](https://www.hongkiat.com/blog/wordpress-admin-color-scheme/), but idk if it doesnt work for WP 5.0+ or if im doing something wrong. I added this to my functions.php and the css file is a copy of the Light Scheme. ``` function additional_admin_color_schemes() { $theme_dir = get_template_directory_uri(); wp_admin_css_color( 'pro', __( 'Pro' ), $theme_dir . '/wp-content/themes/astra-child/pro/colors.min.css', array( '#E5E5E5', '#E5E5E5', '#3498DB', '#3498DB' ) ); } add_action('admin_init', 'additional_admin_color_schemes'); ```
This code works with WordPress 5.2 and is correct. You now need to go to your Profile and select it by going to `Users` > `Your Profile` > `Admin Color Scheme` select the scheme and save. [![enter image description here](https://i.stack.imgur.com/0xlHm.png)](https://i.stack.imgur.com/0xlHm.png) Edit: Adding updated code for your colors CSS file since you're using a child theme: ```php function additional_admin_color_schemes() { wp_admin_css_color( 'pro', __( 'Pro' ), get_stylesheet_directory_uri().'/wp-content/themes/astra-child/pro/colors.css', [ '#E5E5E5', '#E5E5E5', '#3498DB', '#3498DB' ] ); } add_action( 'admin_init', 'additional_admin_color_schemes' ); ``` Note here I removed the `.min` from the CSS file. I recommend you copy the non-minified CSS file over, so you can easily edit and customize the styles.
339,946
<p>I have a custom tracking system in place which works with an include of a .js file in the footer of each page. Unfortunately some high traffic sites are including images from my site which are already removed. therefor the 404 error page of my theme is frequenty hit and those users are registered aswell as website visitors even though I dont want them to count.</p> <p>Long story short: I want to provent that tracking.js file to load on the 404 error page. What would be the best way to do that?</p>
[ { "answer_id": 339949, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You could use the <code>is_page()</code> function on your footer to check if it is a 404 page, then don't add the js code if it is the 404 page. <strong>Added</strong> the commenter is right - a 404 is a response, not a page, so you can't test for it. (I blame temporary insanity...) So .... the answer is now....</p>\n\n<p><strong>updated</strong> Create a 404 page template that doesn't include the js code. That template will be used is a page request causes a '404' response.</p>\n\n<p>Related to your question: I also worry about incomplete tracking because of ad blockers. So developed a server-side tracker that sends GA tracking data. Ad-blockers never see it, so I get full tracking data. (With GDPR notifications, of course.) Perhaps an alternative for you. </p>\n" }, { "answer_id": 340009, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 1, "selected": false, "text": "<p>There is <a href=\"https://codex.wordpress.org/Function_Reference/is_404\" rel=\"nofollow noreferrer\"><code>is_404()</code></a>. I normally use it to do just the opposite, to add CSS and JS animations which are specific to the 404 error page. In your case that would be:</p>\n\n<pre><code>function wpse_339946() {\n\n if ( ! is_404() ) {\n wp_enqueue_script( 'tracking-js', get_template_directory_uri() . '/js/tracking.js' );\n }\n}\n\nadd_action( 'wp_enqueue_scripts', 'wpse_339946' );\n</code></pre>\n" } ]
2019/06/08
[ "https://wordpress.stackexchange.com/questions/339946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116018/" ]
I have a custom tracking system in place which works with an include of a .js file in the footer of each page. Unfortunately some high traffic sites are including images from my site which are already removed. therefor the 404 error page of my theme is frequenty hit and those users are registered aswell as website visitors even though I dont want them to count. Long story short: I want to provent that tracking.js file to load on the 404 error page. What would be the best way to do that?
There is [`is_404()`](https://codex.wordpress.org/Function_Reference/is_404). I normally use it to do just the opposite, to add CSS and JS animations which are specific to the 404 error page. In your case that would be: ``` function wpse_339946() { if ( ! is_404() ) { wp_enqueue_script( 'tracking-js', get_template_directory_uri() . '/js/tracking.js' ); } } add_action( 'wp_enqueue_scripts', 'wpse_339946' ); ```
339,950
<p>On the WP homepage I have a Form like this:</p> <pre><code>&lt;form action="'.esc_url( admin_url('admin-post.php')).'" method="post"&gt; //etc. //etc. </code></pre> <p>and in the file <strong>functions.php</strong> I have this snipped of code.</p> <pre><code> function redirect_form() { if (isset($_POST["var1"]) &amp;&amp; !empty($_POST["var1"]) &amp;&amp; isset($_POST["var2"]) &amp;&amp; isset($_POST["var3"]) &amp;&amp; !empty($_POST["var3"])) { if ($_POST["var1"] == 'product1'){ wp_redirect(home_url('/product/product1/')); exit; // etc. // etc. </code></pre> <p>Everything is working as <strong>expected</strong>.</p> <p>But the question is how can I get those variables on the WooCommerce single product page? I want echo those variables on the page of the product.</p> <p><strong>UPDATED:</strong></p> <p>I am trying the same thing with global variables. What I am missing?</p> <pre><code>function redirect_form() { if (isset($_POST["var1"]) &amp;&amp; !empty($_POST["var1"]) &amp;&amp; isset($_POST["var2"]) &amp;&amp; isset($_POST["var3"]) &amp;&amp; !empty($_POST["var3"])) { global $abc; $abc = $_POST["var2"]; if ($_POST["var1"] == 'product1'){ wp_redirect(home_url('/products/product1/')); exit; // etc. // etc. </code></pre> <p>then</p> <pre><code>add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 ); function dev_designs_show_sku(){ global $product, $abc; echo $abc; } </code></pre> <p>It is not working. What I am missing?</p> <p><strong>UPDATED 2</strong></p> <p>then I want adjust price of the product based on those variables. Something like this.</p> <pre><code>function return_custom_price($price, $product) { global $post, $blog_id, $abc; $price = get_post_meta($post-&gt;ID, '_regular_price'); $post_id = $post-&gt;ID; $price = ($price[0] + $abc); return $price; } add_filter('woocommerce_get_price', 'return_custom_price', 10, 2); </code></pre>
[ { "answer_id": 339951, "author": "JBarnden", "author_id": 169666, "author_profile": "https://wordpress.stackexchange.com/users/169666", "pm_score": -1, "selected": false, "text": "<p>If you're looking to customize what's displayed on product pages, there are a couple of ways you can do this:</p>\n\n<p><strong>1) Overriding the product page templates:</strong>\nThe components that make up a product page can be found in <code>wp-content/plugins/woocommerce/templates</code>, if you want to add variables to one or more parts of a product page, you can override that part of the page within your currently set theme.</p>\n\n<p>For example if you wanted to add variables to the short description, you could copy the short description template:</p>\n\n<pre><code>wp-content/plugins/woocommerce/templates/single-product/short-description.php\n</code></pre>\n\n<p>to your currently set theme:</p>\n\n<pre><code>yourtheme/woocommerce/single-product/short-description.php`\n</code></pre>\n\n<p>and add variables/change the structure on your copy. You can do the same with the tabs in the product pages (e.g. additional information &amp; description), check out the files in <code>plugins/woocommerce/templates/single-product/tabs/</code>.</p>\n\n<p>This is useful if you want to make major changes to a section, a downside is that you may need to re-copy the file for compatability if WooCommerce developers make changes to that template.</p>\n\n<p><strong>2) Add variables via filters:</strong>\nSome of the elements have filters, you could manipulate the data that would be used in each section using these.</p>\n\n<p>Using the short description as an example again, you could add a hook to manipulate the data like so:</p>\n\n<pre><code>// define the woocommerce_short_description callback \nfunction filter_woocommerce_short_description( $post_post_excerpt ) { \n // make filter magic happen here... \n return $post_post_excerpt; \n}; \n\n// add the filter \nadd_filter( 'woocommerce_short_description', 'filter_woocommerce_short_description', 10, 1 ); \n</code></pre>\n\n<p><em>Taken from <a href=\"http://hookr.io/filters/woocommerce_short_description/#\" rel=\"nofollow noreferrer\">hookr.io</a></em></p>\n\n<p>You could do this in your <code>functions.php</code> file or inside a custom plugin. The benefit of this is that it's a bit more robust against WooCommerce developer changes to the template, but you're more limited in terms of the changes you can make.</p>\n\n<h1>Update based on clarification</h1>\n\n<p>I think I misunderstood your question, if you're asking about variable scope, this is more of a PHP question than a WordPress question. You could <a href=\"https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.global\" rel=\"nofollow noreferrer\">declare your variable as a global</a>, which you can then access anywhere.</p>\n\n<pre><code>function redirect_form() {#\n /* This is now globally scoped, you can access it anywhere */\n global $my_var;\n $my_var = $_POST[\"var1\"];\n}\n</code></pre>\n\n<p>You'll then need to re-define you're global wherever you want to use it, so wherever your manipulating your product page code you can access it like this:</p>\n\n<pre><code>global $my_var;\necho $my_var;\n</code></pre>\n\n<p>Just be careful what you name your variable as you don't want to overwrite something important. I'd always try to avoid using globals if possible, depending on what you're trying to do, there may be a better/safer way of sharing this variable, but I wouldn't be able to suggest a better approach without fully knowing what it is you're trying to achieve.</p>\n" }, { "answer_id": 340213, "author": "ChristopherJones", "author_id": 168744, "author_profile": "https://wordpress.stackexchange.com/users/168744", "pm_score": 1, "selected": true, "text": "<p>I think you can maybe use $_SESSIONS or a $_GET var.</p>\n\n<p><strong>Option 1:</strong> (I think this will work best for you situation)</p>\n\n<pre><code>function redirect_form() {\n if (isset($_POST[\"var1\"]) &amp;&amp; !empty($_POST[\"var1\"]) &amp;&amp; isset($_POST[\"var2\"]) &amp;&amp; isset($_POST[\"var3\"]) &amp;&amp; !empty($_POST[\"var3\"])) {\n\n $_SESSION['var2'] = htmlentities(stripslashes(trim($_POST[\"var2\"])), ENT_QUOTES);\n\n if ($_POST[\"var1\"] == 'product1'){\n wp_redirect(home_url('/products/product1/')); exit;\n\n///// And In your price adjustment call\n\nfunction return_custom_price($price, $product) {\n global $post, $blog_id;\n $price = get_post_meta($post-&gt;ID, '_regular_price');\n $post_id = $post-&gt;ID;\n $price = ($price[0] + $_SESSION['var2']);\n return $price;\n}\nadd_filter('woocommerce_get_price', 'return_custom_price', 10, 2);\n\n</code></pre>\n\n<p><strong>Note:</strong> And at the top of your functions.php file, you'll need to start $_SESSIONS in order to use them.</p>\n\n<pre><code>function register_my_session(){\n if( !session_id()){\n session_start();\n }\n}\n\nadd_action('init', 'register_my_session');\n</code></pre>\n\n<p><strong>Option 2:</strong> (If you run into $_SESSION issues)</p>\n\n<pre><code>function redirect_form() {\n if (isset($_POST[\"var1\"]) &amp;&amp; !empty($_POST[\"var1\"]) &amp;&amp; isset($_POST[\"var2\"]) &amp;&amp; isset($_POST[\"var3\"]) &amp;&amp; !empty($_POST[\"var3\"])) {\n\n $url_parm = htmlentities(stripslashes(trim($_POST[\"var2\"])), ENT_QUOTES);\n\n if ($_POST[\"var1\"] == 'product1'){\n wp_redirect(home_url('/products/product1/?var2='.$url_parm)); exit;\n\n///// And In your price adjustment call\n\nfunction return_custom_price($price, $product) {\n global $post, $blog_id;\n $price = get_post_meta($post-&gt;ID, '_regular_price');\n $post_id = $post-&gt;ID;\n $price = ($price[0] + $_GET['var2']);\n return $price;\n}\nadd_filter('woocommerce_get_price', 'return_custom_price', 10, 2);\n\n</code></pre>\n\n<p>If you take Option 2, I would maybe think about protecting doing some checks and balances in your <code>return_custom_price()</code> call to make sure you have clean data;</p>\n\n<p>Hope that helps and let me know if you running into any issues!!</p>\n" } ]
2019/06/08
[ "https://wordpress.stackexchange.com/questions/339950", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169665/" ]
On the WP homepage I have a Form like this: ``` <form action="'.esc_url( admin_url('admin-post.php')).'" method="post"> //etc. //etc. ``` and in the file **functions.php** I have this snipped of code. ``` function redirect_form() { if (isset($_POST["var1"]) && !empty($_POST["var1"]) && isset($_POST["var2"]) && isset($_POST["var3"]) && !empty($_POST["var3"])) { if ($_POST["var1"] == 'product1'){ wp_redirect(home_url('/product/product1/')); exit; // etc. // etc. ``` Everything is working as **expected**. But the question is how can I get those variables on the WooCommerce single product page? I want echo those variables on the page of the product. **UPDATED:** I am trying the same thing with global variables. What I am missing? ``` function redirect_form() { if (isset($_POST["var1"]) && !empty($_POST["var1"]) && isset($_POST["var2"]) && isset($_POST["var3"]) && !empty($_POST["var3"])) { global $abc; $abc = $_POST["var2"]; if ($_POST["var1"] == 'product1'){ wp_redirect(home_url('/products/product1/')); exit; // etc. // etc. ``` then ``` add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 ); function dev_designs_show_sku(){ global $product, $abc; echo $abc; } ``` It is not working. What I am missing? **UPDATED 2** then I want adjust price of the product based on those variables. Something like this. ``` function return_custom_price($price, $product) { global $post, $blog_id, $abc; $price = get_post_meta($post->ID, '_regular_price'); $post_id = $post->ID; $price = ($price[0] + $abc); return $price; } add_filter('woocommerce_get_price', 'return_custom_price', 10, 2); ```
I think you can maybe use $\_SESSIONS or a $\_GET var. **Option 1:** (I think this will work best for you situation) ``` function redirect_form() { if (isset($_POST["var1"]) && !empty($_POST["var1"]) && isset($_POST["var2"]) && isset($_POST["var3"]) && !empty($_POST["var3"])) { $_SESSION['var2'] = htmlentities(stripslashes(trim($_POST["var2"])), ENT_QUOTES); if ($_POST["var1"] == 'product1'){ wp_redirect(home_url('/products/product1/')); exit; ///// And In your price adjustment call function return_custom_price($price, $product) { global $post, $blog_id; $price = get_post_meta($post->ID, '_regular_price'); $post_id = $post->ID; $price = ($price[0] + $_SESSION['var2']); return $price; } add_filter('woocommerce_get_price', 'return_custom_price', 10, 2); ``` **Note:** And at the top of your functions.php file, you'll need to start $\_SESSIONS in order to use them. ``` function register_my_session(){ if( !session_id()){ session_start(); } } add_action('init', 'register_my_session'); ``` **Option 2:** (If you run into $\_SESSION issues) ``` function redirect_form() { if (isset($_POST["var1"]) && !empty($_POST["var1"]) && isset($_POST["var2"]) && isset($_POST["var3"]) && !empty($_POST["var3"])) { $url_parm = htmlentities(stripslashes(trim($_POST["var2"])), ENT_QUOTES); if ($_POST["var1"] == 'product1'){ wp_redirect(home_url('/products/product1/?var2='.$url_parm)); exit; ///// And In your price adjustment call function return_custom_price($price, $product) { global $post, $blog_id; $price = get_post_meta($post->ID, '_regular_price'); $post_id = $post->ID; $price = ($price[0] + $_GET['var2']); return $price; } add_filter('woocommerce_get_price', 'return_custom_price', 10, 2); ``` If you take Option 2, I would maybe think about protecting doing some checks and balances in your `return_custom_price()` call to make sure you have clean data; Hope that helps and let me know if you running into any issues!!
339,984
<p>I have a list of articles on my website.</p> <p>Some of the articles are post types with the "Article" category and others are PDF files uploaded to the media library, also with the "Article" category. I added categories to the media library using these functions in <em>functions.php</em>:</p> <pre><code>// add categories for attachments function add_categories_for_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'add_categories_for_attachments' ); // add tags for attachments function add_tags_for_attachments() { register_taxonomy_for_object_type( 'post_tag', 'attachment' ); } add_action( 'init' , 'add_tags_for_attachments' ); </code></pre> <p>thanks to this <a href="https://premium.wpmudev.org/blog/wordpress-media-categories-tags/" rel="nofollow noreferrer">article</a>.</p> <p>I need to display a single category page which lists both types of posts (media and regular posts). </p> <p>Is there a simple way to achieve it?</p>
[ { "answer_id": 339992, "author": "bjornredemption", "author_id": 64380, "author_profile": "https://wordpress.stackexchange.com/users/64380", "pm_score": 1, "selected": false, "text": "<p>Something like this should work :</p>\n\n<pre><code>$args = array ( 'post_type' =&gt; array( 'post', 'attachment'), 'category' =&gt; ARTICLE_CATID );\n$query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 339995, "author": "CaptainNemo", "author_id": 168795, "author_profile": "https://wordpress.stackexchange.com/users/168795", "pm_score": 0, "selected": false, "text": "<p>Thanks to @bjornredemption, I used the following code snippet:</p>\n\n<pre><code>$args = array('category' =&gt; $wp_query-&gt;get_queried_object_id(), 'posts_per_page' =&gt; -1, 'orderby'=&gt; 'title', 'order' =&gt; 'ASC', 'post_type' =&gt; array( 'post', 'attachment'),'post_status' =&gt; array( 'publish', 'inherit'));\n$glossaryposts = get_posts( $args );\n</code></pre>\n\n<p>Furthermore the function have_posts() must be changed because the default one does not check for attachments. </p>\n" } ]
2019/06/09
[ "https://wordpress.stackexchange.com/questions/339984", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168795/" ]
I have a list of articles on my website. Some of the articles are post types with the "Article" category and others are PDF files uploaded to the media library, also with the "Article" category. I added categories to the media library using these functions in *functions.php*: ``` // add categories for attachments function add_categories_for_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'add_categories_for_attachments' ); // add tags for attachments function add_tags_for_attachments() { register_taxonomy_for_object_type( 'post_tag', 'attachment' ); } add_action( 'init' , 'add_tags_for_attachments' ); ``` thanks to this [article](https://premium.wpmudev.org/blog/wordpress-media-categories-tags/). I need to display a single category page which lists both types of posts (media and regular posts). Is there a simple way to achieve it?
Something like this should work : ``` $args = array ( 'post_type' => array( 'post', 'attachment'), 'category' => ARTICLE_CATID ); $query = new WP_Query( $args ); ```
339,986
<p>I have a query that get relationship fields for multiple ID.</p> <p>I get the ID of selected item, and merge it in an array with other ID's</p> <p>ex : </p> <p>my page relationship ID = 5 my other pages ID in array = 6,3,8 so i make an array = 6,3,8,5</p> <p>how can I display my value, to display first the value of "5", and then the other values ? </p> <p>shoud I do a query for </p> <p>5</p> <p>and then a query for 6,3,8 ? </p> <p>or is there a way to order by 5 and then by others ?</p> <p>My query :</p> <pre><code> $args = array( 'post_type' =&gt; 'maison-hotes', 'post__not_in' =&gt; $post_id, 'meta_query' =&gt; array( 'relation' =&gt; 'OR', ) ); foreach($cities_id as $single_city_id) { $args['meta_query'][] = array( 'key' =&gt; 'contact_city', 'value' =&gt; '"'.$single_city_id.'"', 'compare' =&gt; 'LIKE' ); } $query = new WP_Query($args); if ($query-&gt;have_posts() ) : echo '&lt;h3 class="widget-title"&gt;&lt;span&gt;&lt;i class="fas fa-hotel"&gt;&lt;/i&gt; D\'autres chambres d\'hôtes à '. $city_name .'&lt;/span&gt;&lt;/h3&gt;'; while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); my_stuf(); endwhile; endif; </code></pre> <p>In SQL i know i can do something like </p> <pre><code>ORDER BY CASE contact_city WHEN '5' THEN 1 ELSE 2 </code></pre> <p>But i don't know how to reproduce this to wordpress</p>
[ { "answer_id": 339992, "author": "bjornredemption", "author_id": 64380, "author_profile": "https://wordpress.stackexchange.com/users/64380", "pm_score": 1, "selected": false, "text": "<p>Something like this should work :</p>\n\n<pre><code>$args = array ( 'post_type' =&gt; array( 'post', 'attachment'), 'category' =&gt; ARTICLE_CATID );\n$query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 339995, "author": "CaptainNemo", "author_id": 168795, "author_profile": "https://wordpress.stackexchange.com/users/168795", "pm_score": 0, "selected": false, "text": "<p>Thanks to @bjornredemption, I used the following code snippet:</p>\n\n<pre><code>$args = array('category' =&gt; $wp_query-&gt;get_queried_object_id(), 'posts_per_page' =&gt; -1, 'orderby'=&gt; 'title', 'order' =&gt; 'ASC', 'post_type' =&gt; array( 'post', 'attachment'),'post_status' =&gt; array( 'publish', 'inherit'));\n$glossaryposts = get_posts( $args );\n</code></pre>\n\n<p>Furthermore the function have_posts() must be changed because the default one does not check for attachments. </p>\n" } ]
2019/06/09
[ "https://wordpress.stackexchange.com/questions/339986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/139936/" ]
I have a query that get relationship fields for multiple ID. I get the ID of selected item, and merge it in an array with other ID's ex : my page relationship ID = 5 my other pages ID in array = 6,3,8 so i make an array = 6,3,8,5 how can I display my value, to display first the value of "5", and then the other values ? shoud I do a query for 5 and then a query for 6,3,8 ? or is there a way to order by 5 and then by others ? My query : ``` $args = array( 'post_type' => 'maison-hotes', 'post__not_in' => $post_id, 'meta_query' => array( 'relation' => 'OR', ) ); foreach($cities_id as $single_city_id) { $args['meta_query'][] = array( 'key' => 'contact_city', 'value' => '"'.$single_city_id.'"', 'compare' => 'LIKE' ); } $query = new WP_Query($args); if ($query->have_posts() ) : echo '<h3 class="widget-title"><span><i class="fas fa-hotel"></i> D\'autres chambres d\'hôtes à '. $city_name .'</span></h3>'; while ( $query->have_posts() ) : $query->the_post(); my_stuf(); endwhile; endif; ``` In SQL i know i can do something like ``` ORDER BY CASE contact_city WHEN '5' THEN 1 ELSE 2 ``` But i don't know how to reproduce this to wordpress
Something like this should work : ``` $args = array ( 'post_type' => array( 'post', 'attachment'), 'category' => ARTICLE_CATID ); $query = new WP_Query( $args ); ```
339,990
<p>On my frontend I am using Boostrap 4, however Gutenberg block table has class <code>&lt;table class="wp-block-table"&gt;</code> so instead of creating new table style it would make more sense to append the Boostrap table class to <code>wp-block-table</code> class. Would like to know if this possible. Thanks.</p>
[ { "answer_id": 339998, "author": "Benjamin Franklin", "author_id": 162254, "author_profile": "https://wordpress.stackexchange.com/users/162254", "pm_score": 1, "selected": true, "text": "<p>Since my theme did not recognize wp block table class I have added table Sass class from Gutenberg to my theme. </p>\n\n<pre><code>.wp-block-table {\n width: 100%;\n min-width: 240px;\n border-collapse: collapse;\n margin-bottom: 24px;\n\n td, th {\n padding: .3em;\n border: 1px solid rgba(0, 0, 0, 0.1);\n word-break: break-all;\n }\n th {\n text-align: center;\n }\n}\n</code></pre>\n" }, { "answer_id": 349103, "author": "RaajTram", "author_id": 82482, "author_profile": "https://wordpress.stackexchange.com/users/82482", "pm_score": -1, "selected": false, "text": "<p>You can add <code>.table</code> as the class under the \"block settings\" for the table block. You can also add additional classes such as <code>.table-bordered</code> and <code>.table-styled</code>. All table class references can be found in the <a href=\"https://getbootstrap.com/docs/4.3/content/tables/\" rel=\"nofollow noreferrer\">Bootstrap Docs</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eHJZ4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eHJZ4.png\" alt=\"gutenberg-class\"></a></p>\n" }, { "answer_id": 376820, "author": "Xdg", "author_id": 28061, "author_profile": "https://wordpress.stackexchange.com/users/28061", "pm_score": 0, "selected": false, "text": "<p>Good solution is to add this to functions.php of your theme (taken <a href=\"https://napitwptech.com/tutorial/wordpress-development/integrate-bootstrap-responsive-table-wordpress/\" rel=\"nofollow noreferrer\">from there</a>):</p>\n<pre><code>function theme_prefix_bootstrap_responsive_table( $content ) {\n $content = str_replace(\n [ '&lt;table&gt;', '&lt;/table&gt;' ],\n [ '&lt;table class=&quot;table table-bordered table-hover table-striped table-responsive&quot;&gt;', '&lt;/table&gt;' ],\n $content\n );\n\n return $content;\n}\n\nadd_filter( 'the_content', 'theme_prefix_bootstrap_responsive_table' );\n</code></pre>\n" }, { "answer_id": 384350, "author": "Richard Stimson", "author_id": 202747, "author_profile": "https://wordpress.stackexchange.com/users/202747", "pm_score": 0, "selected": false, "text": "<p>Tables were not showing with the Wordpress Magazinely theme.</p>\n<p>Adding this code (from Benjamin Franklyn above) worked for me. Add it to Apperance -&gt; Customize -&gt; Additional CSS</p>\n<pre class=\"lang-css prettyprint-override\"><code>.wp-block-table {\n width: 100%;\n min-width: 240px;\n border-collapse: collapse;\n margin-bottom: 24px;\n\n td, th {\n padding: .3em;\n border: 1px solid rgba(0, 0, 0, 0.1);\n word-break: break-all;\n }\n th {\n text-align: center;\n }\n}\n</code></pre>\n" } ]
2019/06/09
[ "https://wordpress.stackexchange.com/questions/339990", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162254/" ]
On my frontend I am using Boostrap 4, however Gutenberg block table has class `<table class="wp-block-table">` so instead of creating new table style it would make more sense to append the Boostrap table class to `wp-block-table` class. Would like to know if this possible. Thanks.
Since my theme did not recognize wp block table class I have added table Sass class from Gutenberg to my theme. ``` .wp-block-table { width: 100%; min-width: 240px; border-collapse: collapse; margin-bottom: 24px; td, th { padding: .3em; border: 1px solid rgba(0, 0, 0, 0.1); word-break: break-all; } th { text-align: center; } } ```
340,034
<pre><code>wp_mail($emails, 'New Contact Enquiry | ' . $subject, $message, $headers, $attachments) </code></pre> <p>but getting this error.</p> <p>WP_Error Object ( [errors] => Array ( [2] => Array ( [0] => SMTP Error: data not accepted. ) ) [error_data] => Array ( [2] => Array ( [to] => Array ( [0] => [email protected] ) [subject] => New Contact Enquiry | Government Project Enquiry [message] =></p> <p>Sender Email :[email protected]</p> <p>Sender Contact: :21312312312</p> <p>Message :tersrtrt</p> <p>[headers] => Array ( [Reply-To] => [email protected] [MIME-Version] => 1.0 ) [attachments] => Array ( [0] => ) ) ) )</p>
[ { "answer_id": 340003, "author": "Rimarx", "author_id": 169228, "author_profile": "https://wordpress.stackexchange.com/users/169228", "pm_score": 1, "selected": false, "text": "<p>First you need to find where does the code slow down, try:</p>\n\n<ul>\n<li>Deactivating all plugins and then check speed. If this works,\nre-activate them individually( one-by-one ) to find the problematic\nplugin(s).</li>\n<li>Switching theme then check speed.</li>\n<li>Transfer the theme and plugins to a new WordPress that installed from\nscratch, then check.</li>\n</ul>\n\n<p>Then write the results.</p>\n" }, { "answer_id": 340010, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>In addition to what @Rimarx has already suggested, another possible cause (among many) is with the Updates API making external calls which eventually timeout, you can try setting this in your <code>wp-config.php</code>:</p>\n\n<pre><code>define('WP_HTTP_BLOCK_EXTERNAL', true);\ndefine('WP_ACCESSIBLE_HOSTS', '*.wordpress.org');\n</code></pre>\n\n<p>If this works, it is possibly a plugin or theme checking for updates on a slow update server, or where the connection to it is timing out. Again, just one thing to check / eliminate. (If it does make a difference, you would have to narrow down which plugin / theme is causing the issue and go from there.)</p>\n" } ]
2019/06/10
[ "https://wordpress.stackexchange.com/questions/340034", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168208/" ]
``` wp_mail($emails, 'New Contact Enquiry | ' . $subject, $message, $headers, $attachments) ``` but getting this error. WP\_Error Object ( [errors] => Array ( [2] => Array ( [0] => SMTP Error: data not accepted. ) ) [error\_data] => Array ( [2] => Array ( [to] => Array ( [0] => [email protected] ) [subject] => New Contact Enquiry | Government Project Enquiry [message] => Sender Email :[email protected] Sender Contact: :21312312312 Message :tersrtrt [headers] => Array ( [Reply-To] => [email protected] [MIME-Version] => 1.0 ) [attachments] => Array ( [0] => ) ) ) )
First you need to find where does the code slow down, try: * Deactivating all plugins and then check speed. If this works, re-activate them individually( one-by-one ) to find the problematic plugin(s). * Switching theme then check speed. * Transfer the theme and plugins to a new WordPress that installed from scratch, then check. Then write the results.
340,060
<p>I'm trying to query wordpress with multiple values but it looks like it can't take no more than 4 keywords</p> <p>I'm currently using a loop and I already tried to switch to a <strong>IN</strong> operator but I need the query to work with wildcards and while <strong>REGEXP</strong> does the job, IN does not</p> <pre><code>foreach ($keywords as $value) { $args['meta_query'] = array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'customfields', 'value' =&gt; $value, 'compare' =&gt; 'REGEXP' ) ); } </code></pre> <p>In this case <code>$keywords</code> is an array of words that I need to query to a custom field. It works with a few keywords, but it breaks with 5 or more. </p>
[ { "answer_id": 340003, "author": "Rimarx", "author_id": 169228, "author_profile": "https://wordpress.stackexchange.com/users/169228", "pm_score": 1, "selected": false, "text": "<p>First you need to find where does the code slow down, try:</p>\n\n<ul>\n<li>Deactivating all plugins and then check speed. If this works,\nre-activate them individually( one-by-one ) to find the problematic\nplugin(s).</li>\n<li>Switching theme then check speed.</li>\n<li>Transfer the theme and plugins to a new WordPress that installed from\nscratch, then check.</li>\n</ul>\n\n<p>Then write the results.</p>\n" }, { "answer_id": 340010, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>In addition to what @Rimarx has already suggested, another possible cause (among many) is with the Updates API making external calls which eventually timeout, you can try setting this in your <code>wp-config.php</code>:</p>\n\n<pre><code>define('WP_HTTP_BLOCK_EXTERNAL', true);\ndefine('WP_ACCESSIBLE_HOSTS', '*.wordpress.org');\n</code></pre>\n\n<p>If this works, it is possibly a plugin or theme checking for updates on a slow update server, or where the connection to it is timing out. Again, just one thing to check / eliminate. (If it does make a difference, you would have to narrow down which plugin / theme is causing the issue and go from there.)</p>\n" } ]
2019/06/10
[ "https://wordpress.stackexchange.com/questions/340060", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169734/" ]
I'm trying to query wordpress with multiple values but it looks like it can't take no more than 4 keywords I'm currently using a loop and I already tried to switch to a **IN** operator but I need the query to work with wildcards and while **REGEXP** does the job, IN does not ``` foreach ($keywords as $value) { $args['meta_query'] = array( 'relation' => 'OR', array( 'key' => 'customfields', 'value' => $value, 'compare' => 'REGEXP' ) ); } ``` In this case `$keywords` is an array of words that I need to query to a custom field. It works with a few keywords, but it breaks with 5 or more.
First you need to find where does the code slow down, try: * Deactivating all plugins and then check speed. If this works, re-activate them individually( one-by-one ) to find the problematic plugin(s). * Switching theme then check speed. * Transfer the theme and plugins to a new WordPress that installed from scratch, then check. Then write the results.
340,062
<p>After introduction of <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> I'm confused with existing <code>WP_DEBUG</code> feature. Now what's the difference here? </p> <p>I mean what constant I should use to see the error if I use <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> then what's the meaning of <code>WP_DEBUG</code> now?</p> <p>Even though I went through some of tickets on WordPress but I can't figure out the use of <code>WP_DEBUG</code> now.</p> <p>Did WordPress ends the use of <code>WP_DEBUG</code> ?<br> After introduction of new constant <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> I'm not able to see errors anymore with <code>define("WP_DEBUG",true)</code>.<br> I know about <code>display_errors</code> setting in php.ini so not expecting this solution :)</p>
[ { "answer_id": 340067, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>Those constants do different things.</p>\n\n<ul>\n<li>The <code>WP_DISABLE_FATAL_ERROR_HANDLER</code> constant is for disabling the <a href=\"https://make.wordpress.org/core/2019/04/16/fatal-error-recovery-mode-in-5-2/\" rel=\"noreferrer\">new fatal error recovery feature</a> introduced in WordPress 5.2. This new feature ensures that fatal errors from plugins don't lock you out of your site, and that front-end users get some kind of \"technical difficulties\" message, rather than a white screen.</li>\n<li>The <code>WP_DEBUG</code> constant is to enable a debug mode that displays all PHP error messages and warnings on the front-end, as well as WordPress specific messages such as deprecation notices.</li>\n</ul>\n\n<p>So you can see that they are not really related. The fatal error recovery functionality is intended to be used in production, so that white screens and PHP error messages are not displayed to users. While debug mode is intended to be used in a development environment to debug issues when developing a theme or plugin.</p>\n\n<p>In a production environment (so a live site), neither constant should be enabled. Fatal error recovery should be enabled, and debug mode should be disabled.</p>\n\n<p>In a development environment, you probably don't need fatal error recovery, and you'll likely want debug mode to be enabled.</p>\n\n<p>If for some reason you need to debug issues on a live site, then debug mode might need to be enabled, but in that case you should have <code>WP_DEBUG_DISPLAY</code> set to <code>false</code>, and <code>WP_DEBUG_LOG</code> set to <code>true</code>, so that you can debug error messages from a log file, rather than exposing them to users.</p>\n\n<p>So in a <strong>development environment</strong> you probably want:</p>\n\n<pre><code>define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );\ndefine( 'WP_DEBUG', true );\n</code></pre>\n\n<p>And in a <strong>production environment</strong> you probably want (these would be the same as not manually defining them):</p>\n\n<pre><code>define( 'WP_DISABLE_FATAL_ERROR_HANDLER', false );\ndefine( 'WP_DEBUG', false );\n</code></pre>\n\n<p>And if you need to <strong>debug a live site</strong> you could use:</p>\n\n<pre><code>define( 'WP_DISABLE_FATAL_ERROR_HANDLER', false );\ndefine( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_DISPLAY', false );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n" }, { "answer_id": 371355, "author": "dylzee", "author_id": 190737, "author_profile": "https://wordpress.stackexchange.com/users/190737", "pm_score": 1, "selected": false, "text": "<p>Very detailed answer by Jacob Peattie and I would +1 that for sure. I'd also like to add that you can use the following ini_set commands and also specify your debug log location.</p>\n<pre><code>@ini_set('log_errors','On'); // This is essentialy what ('WP_DEBUG', true) does.\n@ini_set('display_errors','Off'); // Avoid the ugly display of errors on live sites.\n@ini_set('error_log','/home/domain.com/logs/php_error.log'); // Set your log path.\n</code></pre>\n" } ]
2019/06/10
[ "https://wordpress.stackexchange.com/questions/340062", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169739/" ]
After introduction of `WP_DISABLE_FATAL_ERROR_HANDLER` I'm confused with existing `WP_DEBUG` feature. Now what's the difference here? I mean what constant I should use to see the error if I use `WP_DISABLE_FATAL_ERROR_HANDLER` then what's the meaning of `WP_DEBUG` now? Even though I went through some of tickets on WordPress but I can't figure out the use of `WP_DEBUG` now. Did WordPress ends the use of `WP_DEBUG` ? After introduction of new constant `WP_DISABLE_FATAL_ERROR_HANDLER` I'm not able to see errors anymore with `define("WP_DEBUG",true)`. I know about `display_errors` setting in php.ini so not expecting this solution :)
Those constants do different things. * The `WP_DISABLE_FATAL_ERROR_HANDLER` constant is for disabling the [new fatal error recovery feature](https://make.wordpress.org/core/2019/04/16/fatal-error-recovery-mode-in-5-2/) introduced in WordPress 5.2. This new feature ensures that fatal errors from plugins don't lock you out of your site, and that front-end users get some kind of "technical difficulties" message, rather than a white screen. * The `WP_DEBUG` constant is to enable a debug mode that displays all PHP error messages and warnings on the front-end, as well as WordPress specific messages such as deprecation notices. So you can see that they are not really related. The fatal error recovery functionality is intended to be used in production, so that white screens and PHP error messages are not displayed to users. While debug mode is intended to be used in a development environment to debug issues when developing a theme or plugin. In a production environment (so a live site), neither constant should be enabled. Fatal error recovery should be enabled, and debug mode should be disabled. In a development environment, you probably don't need fatal error recovery, and you'll likely want debug mode to be enabled. If for some reason you need to debug issues on a live site, then debug mode might need to be enabled, but in that case you should have `WP_DEBUG_DISPLAY` set to `false`, and `WP_DEBUG_LOG` set to `true`, so that you can debug error messages from a log file, rather than exposing them to users. So in a **development environment** you probably want: ``` define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true ); define( 'WP_DEBUG', true ); ``` And in a **production environment** you probably want (these would be the same as not manually defining them): ``` define( 'WP_DISABLE_FATAL_ERROR_HANDLER', false ); define( 'WP_DEBUG', false ); ``` And if you need to **debug a live site** you could use: ``` define( 'WP_DISABLE_FATAL_ERROR_HANDLER', false ); define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', false ); define( 'WP_DEBUG_LOG', true ); ```
340,117
<p>I am developing a theme and I need to get the actual page ID, when I do:</p> <pre><code>global $post; $thePostID = $post-&gt;ID; </code></pre> <p>I get the wrong ID. I tried get_the_ID() and I get the same ID that in the code above, but both are wrong. I also tried to do wp_reset_query() before getting the ID but I still get the same wrong ID. I am running the code above in a template and it is NOT inside of a loop. I also want to clarify that I am trying to get a page ID, not a post ID, although the function seems to be the same. What I am doing wrong and how could I fix it?</p> <p>**Context</p> <p>I have been testing the different suggestions and here I will try to clarify some. The template page that doesn't show the right page ID displays the posts of a custom field that I created using ACF. The ID that I am getting when executing the_ID() or its variants is the first ID of the first post of the custom field. I retrieved the ID on the header of the template before executing any query and the result is the same, also when I reset the query the ID doesn't change.</p> <p>Any suggestions?</p> <p>thanks</p>
[ { "answer_id": 340127, "author": "Manyang", "author_id": 94471, "author_profile": "https://wordpress.stackexchange.com/users/94471", "pm_score": -1, "selected": false, "text": "<p>You get the ID after another post appear or after another loop.</p>\n\n<p>if you want to get the original main query (current page ID)</p>\n\n<p>use this function <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\">wp_reset_query</a>, before you get the ID</p>\n" }, { "answer_id": 340174, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 1, "selected": false, "text": "<p>As I mentioned in the comments, context matters when getting a post ID. </p>\n\n<p>Try using <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\"><code>get_queried_object()</code></a> to determine what WordPress thinks you're trying to get based on the url. This will return the full object for you to better understand what's being queried. </p>\n\n<p>From the <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\"><code>get_queried_object()</code></a> Codex:</p>\n\n<blockquote>\n <ul>\n <li>if you're on a single post, it will return the post object</li>\n <li>if you're on a page, it will return the page object</li>\n <li>if you're on an archive page, it will return the post type object</li>\n <li>if you're on a category archive, it will return the category object</li>\n <li>if you're on an author archive, it will return the author object</li>\n <li>etc.</li>\n </ul>\n</blockquote>\n\n<p>This will give you a bit more information to determine if you have the page ID available to you or if you'll have to do a query for the page to get the ID.</p>\n\n<p>If this is the object you're looking for, you can use <code>get_queried_object_id()</code> to retrieve the ID. </p>\n" }, { "answer_id": 340218, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 0, "selected": false, "text": "<p>--- UPDATED ---</p>\n\n<p>Ok now that I understand more about what you're doing (querying for a CPT and displaying it on a Page using a template file), here is how I handle a similar function:</p>\n\n<p>On one of my sites I have a Page that describes hiking in a particular area, below which I query for all custom posts of the CPT \"hike\" that have a custom field that holds a (future) date for the hike (it's a guided hike that has a scheduled date and a form for folks to signup for the hike).</p>\n\n<p>The Template file for the Hiking Page starts out as previously mentioned with </p>\n\n<p><code>if (have_posts()) : while (have_posts()) : the_post();</code></p>\n\n<p>followed by some HTML, within which is </p>\n\n<p><code>the_content();</code></p>\n\n<p>in order to display the generic verbiage on the page about hiking in that area.</p>\n\n<p>Below that I use <code>get_posts();</code> to fetch all of the CPT posts for upcoming hikes, so older (past) hikes are not displayed</p>\n\n<pre><code> global $post;\n $args = array (\n 'post_type' =&gt; 'hike',\n 'meta_key' =&gt; 'hike_date_start',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; -1);\n\n $myposts = get_posts($args); \n foreach ( $myposts as $post ) : setup_postdata( $post );\n\n $exp_date = strtotime(get_post_meta($post-&gt;ID,'hike_date_start',true));\n $today = time();\n if ($today &lt;= $exp_date) {\n\n $hikedate = get_post_meta($post-&gt;ID,'hike_date_start',true);\n $hikedate2 = get_post_meta($post-&gt;ID,'hike_date_end',true);\n $hikedateend = strtotime(get_post_meta($post-&gt;ID,'hike_date_end',true));\n $hikerating = get_post_meta($post-&gt;ID,'hike_rating',true);\n $hikeleader = get_post_meta($post-&gt;ID,'hike_leader',true);\n $hikecontactph = get_post_meta($post-&gt;ID,'hike_contact_phone',true);\n $hikecontactem = get_post_meta($post-&gt;ID,'hike_contact_email',true);\n $hikedirections = get_post_meta($post-&gt;ID,'hike_directions',true);\n</code></pre>\n\n<p>Below that is some more HTML to display the data in the format I want, like so:</p>\n\n<pre><code> &lt;div class=\"hikeentry\"&gt;\n &lt;div class=\"time\"&gt;\n &lt;div class=\"month\"&gt;&lt;?php echo date('M', $exp_date); ?&gt;&lt;/div&gt;\n &lt;div class=\"wkday\"&gt;&lt;?php echo date('l', $exp_date); ?&gt;&lt;/div&gt;\n &lt;div class=\"day\"&gt;&lt;?php echo date('d', $exp_date); ?&gt;&lt;/div&gt;\n &lt;div class=\"year\"&gt;&lt;?php echo date('Y', $exp_date); ?&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"hikedata\"&gt;\n &lt;h4&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;\n &lt;div class=\"hikemeta\"&gt;\n &lt;div class=\"left\"&gt;\n &lt;span&gt;Rating:&lt;/span&gt; &lt;?php echo $hikerating; ?&gt;&lt;br /&gt;\n &lt;span&gt;Leader:&lt;/span&gt; &lt;?php echo $hikeleader; ?&gt;&lt;br /&gt;\n &lt;span&gt;Contact:&lt;/span&gt; &lt;a href=\"mailto:&lt;?php echo antispambot($hikecontactem); ?&gt;\"&gt;&lt;?php echo antispambot($hikecontactem); ?&gt;&lt;/a&gt; &amp;nbsp;&amp;nbsp; &lt;?php echo $hikecontactph; ?&gt; \n &lt;/div&gt;\n &lt;div class=\"left bordered rounded bkgd\"&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\"&gt;Click here to read full&lt;br /&gt;description and Sign Up&lt;/a&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php the_excerpt(); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;&lt;!-- end .hikeentry --&gt;\n</code></pre>\n\n<p>ALSO when you're done with the foreach loop, it's important to reset the postdata, like so</p>\n\n<pre><code> } endforeach; wp_reset_postdata();\n</code></pre>\n\n<p>Because I use <code>get_posts($args);</code> and not <code>wp_query();</code> then you don't need to reset the query, just the postdata.</p>\n\n<p>I'm not specifically using <code>the_ID();</code> but you can, wherever you need it WITHIN the foreach loop just call <code>the_ID();</code> as it's part of each individual CPTs data retrieved with <code>setup_postdata();</code> </p>\n\n<p>I hope this helps, ask more questions in the comments and I'm happy to explain more about how/why I use this......I prefer to use the WP built-in methods for retrieving and using data instead of ACFs but I love ACF for making it easy for my users to enter custom data. :-)</p>\n\n<p>--- prior answer, updated above --\nIt's difficult to know exactly how to advise you without knowing more about your specific use, but if I understand your question correctly, you're creating a Template file for a specific Page, yes?</p>\n\n<p>In that case in your Pages>Add New where you've added your page and specified your new template to use, you still need at the top of your Template file:</p>\n\n<p><code>if (have_posts()) : while (have_posts()) : the_post();</code></p>\n\n<p>then where you need the ID you use <code>the_ID();</code></p>\n\n<p>I use this to assign the page's ID (which for all intents and purposes in current versions of WP is the same as a 'post' - pretty much everything is a 'post' nowadays) to a specific element on the page.</p>\n\n<p>If you can post more details about what you're trying to accomplish it will help us to give you better suggestions.</p>\n" }, { "answer_id": 340349, "author": "Hector", "author_id": 48376, "author_profile": "https://wordpress.stackexchange.com/users/48376", "pm_score": 2, "selected": true, "text": "<p>As mentioned in the comments, you are trying to get the ID in the taxonomy archive (<code>template-taxonomy.php</code>) which is not a post object and has no record in the database. It just tries to show some posts and you may get the first post ID when you use <code>get_te_ID()</code> function in that archive page.</p>\n\n<p>Using some themes or plugins, you are able to create a page and use that as an archive page. In that case, the <code>get_the_ID()</code> function is able to return the actual page ID (Out of the loop) because it is a real post object and it has a place in the database.</p>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340117", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117809/" ]
I am developing a theme and I need to get the actual page ID, when I do: ``` global $post; $thePostID = $post->ID; ``` I get the wrong ID. I tried get\_the\_ID() and I get the same ID that in the code above, but both are wrong. I also tried to do wp\_reset\_query() before getting the ID but I still get the same wrong ID. I am running the code above in a template and it is NOT inside of a loop. I also want to clarify that I am trying to get a page ID, not a post ID, although the function seems to be the same. What I am doing wrong and how could I fix it? \*\*Context I have been testing the different suggestions and here I will try to clarify some. The template page that doesn't show the right page ID displays the posts of a custom field that I created using ACF. The ID that I am getting when executing the\_ID() or its variants is the first ID of the first post of the custom field. I retrieved the ID on the header of the template before executing any query and the result is the same, also when I reset the query the ID doesn't change. Any suggestions? thanks
As mentioned in the comments, you are trying to get the ID in the taxonomy archive (`template-taxonomy.php`) which is not a post object and has no record in the database. It just tries to show some posts and you may get the first post ID when you use `get_te_ID()` function in that archive page. Using some themes or plugins, you are able to create a page and use that as an archive page. In that case, the `get_the_ID()` function is able to return the actual page ID (Out of the loop) because it is a real post object and it has a place in the database.
340,139
<p>I've noticed that each call to <a href="https://developer.wordpress.org/reference/functions/update_post_meta/" rel="nofollow noreferrer">update_post_meta</a> results in a small increase in my memory usage.</p> <p>Normally, the increase is small enough to not matter. But I'm writing a CSV import function that calls it 10,000+ times, which eventually results in an out-of-memory error.</p> <p>Here's a minimal code example:</p> <pre><code>function update_business($myData) { error_log("Used memory 1: " . memory_get_usage(false)); error_log("Allocated memory 1: " . memory_get_usage(true)); update_post_meta('13663', 'business_id', $myData); error_log("Used memory 2: " . memory_get_usage(false)); error_log("Allocated memory 2: " . memory_get_usage(true)); } </code></pre> <p>This results in:</p> <pre><code>... Used memory 1: 17995848 Used memory 2: 17996992 Used memory 1: 17996992 Used memory 2: 18027720 Used memory 1: 18027720 Used memory 2: 18058448 Used memory 1: 18058448 Used memory 2: 18089176 Used memory 1: 18089176 Used memory 2: 18119904 ... </code></pre> <p>Without the <code>update_post_meta</code> statement, the memory usage stays the same throughout the entire loop (as expected).</p> <p>But with the <code>update_post_meta</code> statement, the memory usage grows bigger and bigger and never gets freed.</p> <p>I've tried a bunch of different techniques for clearing the memory, including:</p> <ul> <li>wpdb::flush</li> <li>unset</li> <li>gc_collect_cycles</li> <li>wp_cache_flush</li> <li>wp_suspend_cache_addition(true)</li> </ul> <p>But nothing seems to work.</p> <p>I've looked at tons of search results and although quite a few people have had this problem, there aren't many answers besides "raise your memory limit" or "do it a different way", neither of which seems like the best solution.</p> <p>Surely there's some way to free up the memory? I assume that either WordPress, PHP, MySQL or something else is caching something that I don't want it to, or that there's a memory leak somewhere, but I can't figure it out.</p>
[ { "answer_id": 340142, "author": "Pikamander2", "author_id": 119995, "author_profile": "https://wordpress.stackexchange.com/users/119995", "pm_score": 3, "selected": true, "text": "<p>It turns out that it was due to Query Monitor, a plugin that records info about each query. Every time update_post_meta ran, Query Monitor would store some data about the query, which eventually added up to be more than the server could handle.</p>\n\n<p>Running my example code on a default theme like Twenty Nineteen with no other plugins enabled results in the expected behavior:</p>\n\n<pre><code>...\n\nUsed memory 1: 5480528\nUsed memory 2: 5480528\n\nUsed memory 1: 5480528\nUsed memory 2: 5480528\n\n...\n</code></pre>\n\n<p>So if you're running into a similar issue, try disabling all of your plugins and switching to a default theme to help narrow down the issue.</p>\n\n<p><code>update_post_meta</code> doesn't appear to be the problem, at least not by itself.</p>\n" }, { "answer_id": 340154, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>While it is good that you found the specific problem in your setup, the general answer is that you are doing it wrong.</p>\n\n<p>Every time that you are doing anything which requires many DB operations you are risking running out of memory, out of bandwidth to the DB server, or out of time. It may get very tricky as something that might work on one server will fail on another.</p>\n\n<p>The right way to do any operation which requires handling of Ks of records is to split it into handling only (for example) 100 of them at a time and use an AJAX based process to control the progress of the operation until all the data was processed.</p>\n\n<p>For sure over time PHP and MySQL became faster and hardware became stronger which is why you might get away with using a naive \"brute force\" approach in your code, but you are walking on the edge especially if your code is not just a \"one-off\" and will need to be used again.</p>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340139", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119995/" ]
I've noticed that each call to [update\_post\_meta](https://developer.wordpress.org/reference/functions/update_post_meta/) results in a small increase in my memory usage. Normally, the increase is small enough to not matter. But I'm writing a CSV import function that calls it 10,000+ times, which eventually results in an out-of-memory error. Here's a minimal code example: ``` function update_business($myData) { error_log("Used memory 1: " . memory_get_usage(false)); error_log("Allocated memory 1: " . memory_get_usage(true)); update_post_meta('13663', 'business_id', $myData); error_log("Used memory 2: " . memory_get_usage(false)); error_log("Allocated memory 2: " . memory_get_usage(true)); } ``` This results in: ``` ... Used memory 1: 17995848 Used memory 2: 17996992 Used memory 1: 17996992 Used memory 2: 18027720 Used memory 1: 18027720 Used memory 2: 18058448 Used memory 1: 18058448 Used memory 2: 18089176 Used memory 1: 18089176 Used memory 2: 18119904 ... ``` Without the `update_post_meta` statement, the memory usage stays the same throughout the entire loop (as expected). But with the `update_post_meta` statement, the memory usage grows bigger and bigger and never gets freed. I've tried a bunch of different techniques for clearing the memory, including: * wpdb::flush * unset * gc\_collect\_cycles * wp\_cache\_flush * wp\_suspend\_cache\_addition(true) But nothing seems to work. I've looked at tons of search results and although quite a few people have had this problem, there aren't many answers besides "raise your memory limit" or "do it a different way", neither of which seems like the best solution. Surely there's some way to free up the memory? I assume that either WordPress, PHP, MySQL or something else is caching something that I don't want it to, or that there's a memory leak somewhere, but I can't figure it out.
It turns out that it was due to Query Monitor, a plugin that records info about each query. Every time update\_post\_meta ran, Query Monitor would store some data about the query, which eventually added up to be more than the server could handle. Running my example code on a default theme like Twenty Nineteen with no other plugins enabled results in the expected behavior: ``` ... Used memory 1: 5480528 Used memory 2: 5480528 Used memory 1: 5480528 Used memory 2: 5480528 ... ``` So if you're running into a similar issue, try disabling all of your plugins and switching to a default theme to help narrow down the issue. `update_post_meta` doesn't appear to be the problem, at least not by itself.
340,140
<p>Would it be fine if i had 1 main product category in woocommerce with lots of child categories? I'm talking about thousands products in this 1 main category with many subcategories.</p> <p>Is this alright, or not recommended? What about speed of the page, will it affect it in any way by doing this?</p>
[ { "answer_id": 340142, "author": "Pikamander2", "author_id": 119995, "author_profile": "https://wordpress.stackexchange.com/users/119995", "pm_score": 3, "selected": true, "text": "<p>It turns out that it was due to Query Monitor, a plugin that records info about each query. Every time update_post_meta ran, Query Monitor would store some data about the query, which eventually added up to be more than the server could handle.</p>\n\n<p>Running my example code on a default theme like Twenty Nineteen with no other plugins enabled results in the expected behavior:</p>\n\n<pre><code>...\n\nUsed memory 1: 5480528\nUsed memory 2: 5480528\n\nUsed memory 1: 5480528\nUsed memory 2: 5480528\n\n...\n</code></pre>\n\n<p>So if you're running into a similar issue, try disabling all of your plugins and switching to a default theme to help narrow down the issue.</p>\n\n<p><code>update_post_meta</code> doesn't appear to be the problem, at least not by itself.</p>\n" }, { "answer_id": 340154, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>While it is good that you found the specific problem in your setup, the general answer is that you are doing it wrong.</p>\n\n<p>Every time that you are doing anything which requires many DB operations you are risking running out of memory, out of bandwidth to the DB server, or out of time. It may get very tricky as something that might work on one server will fail on another.</p>\n\n<p>The right way to do any operation which requires handling of Ks of records is to split it into handling only (for example) 100 of them at a time and use an AJAX based process to control the progress of the operation until all the data was processed.</p>\n\n<p>For sure over time PHP and MySQL became faster and hardware became stronger which is why you might get away with using a naive \"brute force\" approach in your code, but you are walking on the edge especially if your code is not just a \"one-off\" and will need to be used again.</p>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169775/" ]
Would it be fine if i had 1 main product category in woocommerce with lots of child categories? I'm talking about thousands products in this 1 main category with many subcategories. Is this alright, or not recommended? What about speed of the page, will it affect it in any way by doing this?
It turns out that it was due to Query Monitor, a plugin that records info about each query. Every time update\_post\_meta ran, Query Monitor would store some data about the query, which eventually added up to be more than the server could handle. Running my example code on a default theme like Twenty Nineteen with no other plugins enabled results in the expected behavior: ``` ... Used memory 1: 5480528 Used memory 2: 5480528 Used memory 1: 5480528 Used memory 2: 5480528 ... ``` So if you're running into a similar issue, try disabling all of your plugins and switching to a default theme to help narrow down the issue. `update_post_meta` doesn't appear to be the problem, at least not by itself.
340,143
<p>I need to get a list of the years with posts of given category. Like this: 2008, 2009, 2010, 2012, 2013 (if there were no posts in 2011, it's not included).</p> <p>I try this query, and it works — I get my list of the years:</p> <pre><code>$wpdb-&gt;get_results("SELECT YEAR(post_date) FROM {$wpdb-&gt;posts} WHERE post_status = 'publish' GROUP BY YEAR(post_date) DESC"); </code></pre> <p>Then I introduce category ID, and nothing works:</p> <pre><code>$wpdb-&gt;get_results("SELECT YEAR(post_date) FROM {$wpdb-&gt;posts} WHERE post_status = 'publish' AND cat = '4' GROUP BY YEAR(post_date) DESC"); </code></pre> <p>And even simple query with category doesn't work:</p> <pre><code>$wpdb-&gt;get_results("SELECT YEAR(post_date) FROM {$wpdb-&gt;posts} WHERE cat = '2' GROUP BY YEAR(post_date) DESC"); </code></pre> <p>Category with this ID definitely exists — this is the part of url from the list of categories: <code>term.php?taxonomy=category&amp;tag_ID=2&amp;post_type=post</code></p> <p>There are more than a hundred posts it it.</p>
[ { "answer_id": 340147, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>This is because the category-relations are not stored within the wp_posts table, but in another table named wp_term_relationships. </p>\n\n<p>You have to do some joins to get what you want.\nThis should give you an array of Years with the published posts in this year. </p>\n\n<pre><code>$years = $wpdb-&gt;get_results(\"SELECT DISTINCT YEAR($wpdb-&gt;posts.post_date) as year, COUNT($wpdb-&gt;posts.ID) as count FROM $wpdb-&gt;posts\n LEFT JOIN $wpdb-&gt;term_relationships ON ($wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id)\n LEFT JOIN $wpdb-&gt;term_taxonomy ON ($wpdb-&gt;term_relationships.term_taxonomy_id = $wpdb-&gt;term_taxonomy.term_taxonomy_id)\nWHERE $wpdb-&gt;term_taxonomy.taxonomy = 'category' AND $wpdb-&gt;term_taxonomy.term_id = 4 AND $wpdb-&gt;posts.post_status = 'publish' AND\n$wpdb-&gt;posts.post_type = 'post' \nGROUP BY YEAR($wpdb-&gt;posts.post_date) \nORDER BY $wpdb-&gt;posts.post_date ASC\");\n</code></pre>\n\n<p>Happy Coding!</p>\n" }, { "answer_id": 340148, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Relationship between post and category is not stored in the <code>posts</code> table. You must extend your query for additional tables.</p>\n\n<p>By category <code>id</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nWHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post'\nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n\n<p>Or by category <code>slug</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nJOIN {$wpdb-&gt;terms} t ON t.term_id = tt.term_id \nWHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' \nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n" }, { "answer_id": 340149, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>There category is not stored in the wp_posts but in the wp_terms-table. Please have a look <a href=\"https://codex.wordpress.org/Database_Description#Database_Diagram\" rel=\"nofollow noreferrer\">here</a>. There query should probably be more like this one:</p>\n\n<pre><code>SELECT YEAR(post_date) FROM wp_posts WHERE post_status = \"publish\" AND ID IN (\n SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (\n SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = \"category\" AND term_id = 4\n )\n) GROUP BY YEAR(post_date) DESC;\n</code></pre>\n\n<p>You could use also <a href=\"https://codex.wordpress.org/it:Riferimento_classi/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> if you need a list the of posts of a category of a specific year:</p>\n\n<pre><code>$params = [ \n 'cat' =&gt; 4, \n 'date_query' =&gt; [\n [ 'year' =&gt; 2016 ],\n ],\n 'posts_per_page' =&gt; -1,\n];\n$query = new WP_Query( $params );\n</code></pre>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340143", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167012/" ]
I need to get a list of the years with posts of given category. Like this: 2008, 2009, 2010, 2012, 2013 (if there were no posts in 2011, it's not included). I try this query, and it works — I get my list of the years: ``` $wpdb->get_results("SELECT YEAR(post_date) FROM {$wpdb->posts} WHERE post_status = 'publish' GROUP BY YEAR(post_date) DESC"); ``` Then I introduce category ID, and nothing works: ``` $wpdb->get_results("SELECT YEAR(post_date) FROM {$wpdb->posts} WHERE post_status = 'publish' AND cat = '4' GROUP BY YEAR(post_date) DESC"); ``` And even simple query with category doesn't work: ``` $wpdb->get_results("SELECT YEAR(post_date) FROM {$wpdb->posts} WHERE cat = '2' GROUP BY YEAR(post_date) DESC"); ``` Category with this ID definitely exists — this is the part of url from the list of categories: `term.php?taxonomy=category&tag_ID=2&post_type=post` There are more than a hundred posts it it.
Relationship between post and category is not stored in the `posts` table. You must extend your query for additional tables. By category `id`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post' GROUP BY YEAR(p.post_date) DESC ``` Or by category `slug`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id JOIN {$wpdb->terms} t ON t.term_id = tt.term_id WHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' GROUP BY YEAR(p.post_date) DESC ```
340,161
<p><a href="https://i.stack.imgur.com/jhijR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jhijR.jpg" alt="Mike"></a> Hi! It is possible without plugin to add ability edit custom thumbnail image size and apply changes to it?</p>
[ { "answer_id": 340147, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>This is because the category-relations are not stored within the wp_posts table, but in another table named wp_term_relationships. </p>\n\n<p>You have to do some joins to get what you want.\nThis should give you an array of Years with the published posts in this year. </p>\n\n<pre><code>$years = $wpdb-&gt;get_results(\"SELECT DISTINCT YEAR($wpdb-&gt;posts.post_date) as year, COUNT($wpdb-&gt;posts.ID) as count FROM $wpdb-&gt;posts\n LEFT JOIN $wpdb-&gt;term_relationships ON ($wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id)\n LEFT JOIN $wpdb-&gt;term_taxonomy ON ($wpdb-&gt;term_relationships.term_taxonomy_id = $wpdb-&gt;term_taxonomy.term_taxonomy_id)\nWHERE $wpdb-&gt;term_taxonomy.taxonomy = 'category' AND $wpdb-&gt;term_taxonomy.term_id = 4 AND $wpdb-&gt;posts.post_status = 'publish' AND\n$wpdb-&gt;posts.post_type = 'post' \nGROUP BY YEAR($wpdb-&gt;posts.post_date) \nORDER BY $wpdb-&gt;posts.post_date ASC\");\n</code></pre>\n\n<p>Happy Coding!</p>\n" }, { "answer_id": 340148, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Relationship between post and category is not stored in the <code>posts</code> table. You must extend your query for additional tables.</p>\n\n<p>By category <code>id</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nWHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post'\nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n\n<p>Or by category <code>slug</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nJOIN {$wpdb-&gt;terms} t ON t.term_id = tt.term_id \nWHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' \nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n" }, { "answer_id": 340149, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>There category is not stored in the wp_posts but in the wp_terms-table. Please have a look <a href=\"https://codex.wordpress.org/Database_Description#Database_Diagram\" rel=\"nofollow noreferrer\">here</a>. There query should probably be more like this one:</p>\n\n<pre><code>SELECT YEAR(post_date) FROM wp_posts WHERE post_status = \"publish\" AND ID IN (\n SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (\n SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = \"category\" AND term_id = 4\n )\n) GROUP BY YEAR(post_date) DESC;\n</code></pre>\n\n<p>You could use also <a href=\"https://codex.wordpress.org/it:Riferimento_classi/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> if you need a list the of posts of a category of a specific year:</p>\n\n<pre><code>$params = [ \n 'cat' =&gt; 4, \n 'date_query' =&gt; [\n [ 'year' =&gt; 2016 ],\n ],\n 'posts_per_page' =&gt; -1,\n];\n$query = new WP_Query( $params );\n</code></pre>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340161", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169787/" ]
[![Mike](https://i.stack.imgur.com/jhijR.jpg)](https://i.stack.imgur.com/jhijR.jpg) Hi! It is possible without plugin to add ability edit custom thumbnail image size and apply changes to it?
Relationship between post and category is not stored in the `posts` table. You must extend your query for additional tables. By category `id`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post' GROUP BY YEAR(p.post_date) DESC ``` Or by category `slug`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id JOIN {$wpdb->terms} t ON t.term_id = tt.term_id WHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' GROUP BY YEAR(p.post_date) DESC ```
340,169
<p>I want to moving my site followourtrack.fr from http to https but i have the message ERR_TOO_MANY_REDIRECTS</p> <p><strong>wp-config.php :</strong></p> <pre><code>define('WP_HOME','https://www.followourtrack.fr/'); define('WP_SITEURL','https://www.followourtrack.fr/'); </code></pre> <p><strong>.htaccess file :</strong></p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] &lt;/IfModule&gt; </code></pre> <p>I need to help</p> <p>Thank you :)</p>
[ { "answer_id": 340147, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>This is because the category-relations are not stored within the wp_posts table, but in another table named wp_term_relationships. </p>\n\n<p>You have to do some joins to get what you want.\nThis should give you an array of Years with the published posts in this year. </p>\n\n<pre><code>$years = $wpdb-&gt;get_results(\"SELECT DISTINCT YEAR($wpdb-&gt;posts.post_date) as year, COUNT($wpdb-&gt;posts.ID) as count FROM $wpdb-&gt;posts\n LEFT JOIN $wpdb-&gt;term_relationships ON ($wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id)\n LEFT JOIN $wpdb-&gt;term_taxonomy ON ($wpdb-&gt;term_relationships.term_taxonomy_id = $wpdb-&gt;term_taxonomy.term_taxonomy_id)\nWHERE $wpdb-&gt;term_taxonomy.taxonomy = 'category' AND $wpdb-&gt;term_taxonomy.term_id = 4 AND $wpdb-&gt;posts.post_status = 'publish' AND\n$wpdb-&gt;posts.post_type = 'post' \nGROUP BY YEAR($wpdb-&gt;posts.post_date) \nORDER BY $wpdb-&gt;posts.post_date ASC\");\n</code></pre>\n\n<p>Happy Coding!</p>\n" }, { "answer_id": 340148, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Relationship between post and category is not stored in the <code>posts</code> table. You must extend your query for additional tables.</p>\n\n<p>By category <code>id</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nWHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post'\nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n\n<p>Or by category <code>slug</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nJOIN {$wpdb-&gt;terms} t ON t.term_id = tt.term_id \nWHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' \nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n" }, { "answer_id": 340149, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>There category is not stored in the wp_posts but in the wp_terms-table. Please have a look <a href=\"https://codex.wordpress.org/Database_Description#Database_Diagram\" rel=\"nofollow noreferrer\">here</a>. There query should probably be more like this one:</p>\n\n<pre><code>SELECT YEAR(post_date) FROM wp_posts WHERE post_status = \"publish\" AND ID IN (\n SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (\n SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = \"category\" AND term_id = 4\n )\n) GROUP BY YEAR(post_date) DESC;\n</code></pre>\n\n<p>You could use also <a href=\"https://codex.wordpress.org/it:Riferimento_classi/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> if you need a list the of posts of a category of a specific year:</p>\n\n<pre><code>$params = [ \n 'cat' =&gt; 4, \n 'date_query' =&gt; [\n [ 'year' =&gt; 2016 ],\n ],\n 'posts_per_page' =&gt; -1,\n];\n$query = new WP_Query( $params );\n</code></pre>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169788/" ]
I want to moving my site followourtrack.fr from http to https but i have the message ERR\_TOO\_MANY\_REDIRECTS **wp-config.php :** ``` define('WP_HOME','https://www.followourtrack.fr/'); define('WP_SITEURL','https://www.followourtrack.fr/'); ``` **.htaccess file :** ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> ``` I need to help Thank you :)
Relationship between post and category is not stored in the `posts` table. You must extend your query for additional tables. By category `id`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post' GROUP BY YEAR(p.post_date) DESC ``` Or by category `slug`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id JOIN {$wpdb->terms} t ON t.term_id = tt.term_id WHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' GROUP BY YEAR(p.post_date) DESC ```
340,211
<p>I simply have a quick question. I've found information related to this, but I'm not completely sure if this is possible. I know that I can create a second database connection using the wpdb object as follows:</p> <pre><code>$new_db = new wpdb(usr, pw, name, host); </code></pre> <p>However, is this compatible with an Oracle database that wouldn't have any of the Wordpress tables?</p>
[ { "answer_id": 340147, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>This is because the category-relations are not stored within the wp_posts table, but in another table named wp_term_relationships. </p>\n\n<p>You have to do some joins to get what you want.\nThis should give you an array of Years with the published posts in this year. </p>\n\n<pre><code>$years = $wpdb-&gt;get_results(\"SELECT DISTINCT YEAR($wpdb-&gt;posts.post_date) as year, COUNT($wpdb-&gt;posts.ID) as count FROM $wpdb-&gt;posts\n LEFT JOIN $wpdb-&gt;term_relationships ON ($wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id)\n LEFT JOIN $wpdb-&gt;term_taxonomy ON ($wpdb-&gt;term_relationships.term_taxonomy_id = $wpdb-&gt;term_taxonomy.term_taxonomy_id)\nWHERE $wpdb-&gt;term_taxonomy.taxonomy = 'category' AND $wpdb-&gt;term_taxonomy.term_id = 4 AND $wpdb-&gt;posts.post_status = 'publish' AND\n$wpdb-&gt;posts.post_type = 'post' \nGROUP BY YEAR($wpdb-&gt;posts.post_date) \nORDER BY $wpdb-&gt;posts.post_date ASC\");\n</code></pre>\n\n<p>Happy Coding!</p>\n" }, { "answer_id": 340148, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Relationship between post and category is not stored in the <code>posts</code> table. You must extend your query for additional tables.</p>\n\n<p>By category <code>id</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nWHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post'\nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n\n<p>Or by category <code>slug</code>:</p>\n\n<pre><code>SELECT YEAR(p.post_date) FROM {$wpdb-&gt;posts} p \nJOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id \nJOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id \nJOIN {$wpdb-&gt;terms} t ON t.term_id = tt.term_id \nWHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' \nGROUP BY YEAR(p.post_date) DESC\n</code></pre>\n" }, { "answer_id": 340149, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>There category is not stored in the wp_posts but in the wp_terms-table. Please have a look <a href=\"https://codex.wordpress.org/Database_Description#Database_Diagram\" rel=\"nofollow noreferrer\">here</a>. There query should probably be more like this one:</p>\n\n<pre><code>SELECT YEAR(post_date) FROM wp_posts WHERE post_status = \"publish\" AND ID IN (\n SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (\n SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = \"category\" AND term_id = 4\n )\n) GROUP BY YEAR(post_date) DESC;\n</code></pre>\n\n<p>You could use also <a href=\"https://codex.wordpress.org/it:Riferimento_classi/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> if you need a list the of posts of a category of a specific year:</p>\n\n<pre><code>$params = [ \n 'cat' =&gt; 4, \n 'date_query' =&gt; [\n [ 'year' =&gt; 2016 ],\n ],\n 'posts_per_page' =&gt; -1,\n];\n$query = new WP_Query( $params );\n</code></pre>\n" } ]
2019/06/11
[ "https://wordpress.stackexchange.com/questions/340211", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153230/" ]
I simply have a quick question. I've found information related to this, but I'm not completely sure if this is possible. I know that I can create a second database connection using the wpdb object as follows: ``` $new_db = new wpdb(usr, pw, name, host); ``` However, is this compatible with an Oracle database that wouldn't have any of the Wordpress tables?
Relationship between post and category is not stored in the `posts` table. You must extend your query for additional tables. By category `id`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_id = 4 AND p.post_status = 'publish' AND p.post_type = 'post' GROUP BY YEAR(p.post_date) DESC ``` Or by category `slug`: ``` SELECT YEAR(p.post_date) FROM {$wpdb->posts} p JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id JOIN {$wpdb->terms} t ON t.term_id = tt.term_id WHERE t.slug = 'your_category_slug' AND p.post_type = 'post' AND p.post_status = 'publish' GROUP BY YEAR(p.post_date) DESC ```
340,265
<p>I'm trying to repair a function that was working properly before going to php 7.2. The error comes from the count () function but I do not know how to rewrite it. Can you help me ?</p> <p>Here is the error message: Warning: count(): Parameter must be an array or an object that implements Countable in...</p> <p>This function is a part of the code for displays a page above a category.</p> <ul><li>is_category: If the current page is a category</li> <li>id : category identifier</li> <li>title : Category title</li></ul> <pre><code>private function get_category($id_cat = false){ $Category = new stdClass(); $Category-&gt;is_category = false; $Category-&gt;id = 0; $Category-&gt;title = ''; if (( is_category())||(is_tax('portfolio_categories'))) { $Category-&gt;is_category = true; } if ($id_cat === false) { $cat = single_cat_title("",false); } else{ if ( (int) $id_cat &gt; 0) { $cat = get_cat_name($id_cat); } else{ return $Category; } } $page_id = false; $titre_page = sanitize_title($cat); global $wpdb; $req = $wpdb-&gt;prepare("SELECT ID FROM {$wpdb-&gt;prefix}posts WHERE post_name=%s AND post_content != '' AND post_type = 'page' AND post_status = 'publish'", $titre_page); $page = $wpdb-&gt;get_row($req); $Category-&gt;id = (count($page) &gt; 0) ? $page-&gt;ID : 0; $Category-&gt;title = $titre_page; return $Category; } </code></pre> <p><em>I am not a php developer, so thank you for your indulgence</em></p>
[ { "answer_id": 340227, "author": "Marc", "author_id": 71657, "author_profile": "https://wordpress.stackexchange.com/users/71657", "pm_score": 1, "selected": true, "text": "<p>As long as <code>has_category</code> is used within the loop then it should work when used within <code>index.php</code>, <code>archive.php</code>, etc. You will likely run into issues if it is used outside of the loop on those templates.</p>\n" }, { "answer_id": 340259, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p><code>has_category()</code> only tells you if a <em>specific post</em> has a given category (or any category, if none is provided). You can tell it which post to check by passing the post ID as the second argument. When used inside the loop however, you can omit the post ID and it will check the current post. </p>\n\n<p>The problem is that if it's used outside the loop, then the 'current post' will likely be either the first or last post in the loop. Or, if there's secondary loops on the page, it could be something else entirely.</p>\n\n<p>If you're on an archive page that lists multiple posts that have different categories, and you want to check if any of them have a specific category, then you're going to need to loop through them and check:</p>\n\n<pre><code>$has_category = false;\n\nwhile ( have_posts() ) : the_post();\n if ( has_category( 'category' ) ) {\n $has_category = true;\n }\nendif;\n\nif ( $has_category ) {\n // At least one post has the category.\n}\n</code></pre>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340265", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169846/" ]
I'm trying to repair a function that was working properly before going to php 7.2. The error comes from the count () function but I do not know how to rewrite it. Can you help me ? Here is the error message: Warning: count(): Parameter must be an array or an object that implements Countable in... This function is a part of the code for displays a page above a category. * is\_category: If the current page is a category * id : category identifier * title : Category title ``` private function get_category($id_cat = false){ $Category = new stdClass(); $Category->is_category = false; $Category->id = 0; $Category->title = ''; if (( is_category())||(is_tax('portfolio_categories'))) { $Category->is_category = true; } if ($id_cat === false) { $cat = single_cat_title("",false); } else{ if ( (int) $id_cat > 0) { $cat = get_cat_name($id_cat); } else{ return $Category; } } $page_id = false; $titre_page = sanitize_title($cat); global $wpdb; $req = $wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts WHERE post_name=%s AND post_content != '' AND post_type = 'page' AND post_status = 'publish'", $titre_page); $page = $wpdb->get_row($req); $Category->id = (count($page) > 0) ? $page->ID : 0; $Category->title = $titre_page; return $Category; } ``` *I am not a php developer, so thank you for your indulgence*
As long as `has_category` is used within the loop then it should work when used within `index.php`, `archive.php`, etc. You will likely run into issues if it is used outside of the loop on those templates.
340,272
<p>I am working on a plugin for which I need to create an array of all users (name and ID) that have one or more publish blog posts. </p> <p>Looking at the documentation for <code>get_users()</code> it does not seem to have an arg value for this particular requirement.</p> <p>How do I obtain this data?</p>
[ { "answer_id": 340274, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 0, "selected": false, "text": "<p>You can set \"orderby\" and \"who\" in get_users:\n<a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_users</a></p>\n\n<pre><code> $usersList = get_users( 'orderby=post_count&amp;who=authors' );\n foreach ( $usersList as $user ) {\n echo '&lt;li&gt;' . esc_html( $user-&gt;display_name ) . '&lt;/li&gt;';\n }\n</code></pre>\n" }, { "answer_id": 340277, "author": "chandima", "author_id": 137996, "author_profile": "https://wordpress.stackexchange.com/users/137996", "pm_score": -1, "selected": false, "text": "<p>You can always use custom sql queries to perform things like that.</p>\n\n<pre><code>function custom_query(){\n global $wpdb;\n $tbl_users = $wpdb-&gt;prefix . \"users\";\n $tbl_posts = $wpdb-&gt;prefix . \"posts\";\n\n $sql = \"SELECT ID, user_nicename FROM $tbl_users where ID in (SELECT post_author from tbl_posts WHERE post_status='publish' group by post_author);\";\n $results = $wpdb-&gt;get_results($sql);\n\n if($results){\n foreach($results as $row){\n response[] = array($row-&gt;ID, $row-&gt;user_nicename);\n }\n return response;\n }else{\n return null;\n }\n}\n</code></pre>\n\n<p>I have tested the sql command. But didn't test the complete PHP implementation. But I think you got the idea.</p>\n\n<p><strong>EDIT:</strong> I have add this method just to show that you could always go for custom queries if you stuck on something.</p>\n" }, { "answer_id": 340278, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>There is an argument for this, and it is documented. If you look at <a href=\"https://developer.wordpress.org/reference/functions/get_users/\" rel=\"nofollow noreferrer\">the documentation for <code>get_users()</code></a> is says this:</p>\n\n<blockquote>\n <p>See <a href=\"https://developer.wordpress.org/reference/classes/WP_User_Query/prepare_query/\" rel=\"nofollow noreferrer\">WP_User_Query::prepare_query()</a>. for more information on accepted arguments.</p>\n</blockquote>\n\n<p>If you follow that link you'll see the list of arguments, and one of those is:</p>\n\n<blockquote>\n <p><strong>'has_published_posts'</strong></p>\n \n <p><em>(bool|array)</em> Pass an array of post types to filter results to users who have published posts in those post types. <code>true</code> is an alias for all public post types.</p>\n</blockquote>\n\n<p>So you can get published authors like this:</p>\n\n<pre><code>$authors = get_users( [ 'has_published_posts' =&gt; true ] );\n</code></pre>\n\n<p>Or, if you just want users who have published posts:</p>\n\n<pre><code>$authors = get_users(\n [\n 'has_published_posts' =&gt; [ 'post' ],\n ]\n);\n</code></pre>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340272", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
I am working on a plugin for which I need to create an array of all users (name and ID) that have one or more publish blog posts. Looking at the documentation for `get_users()` it does not seem to have an arg value for this particular requirement. How do I obtain this data?
There is an argument for this, and it is documented. If you look at [the documentation for `get_users()`](https://developer.wordpress.org/reference/functions/get_users/) is says this: > > See [WP\_User\_Query::prepare\_query()](https://developer.wordpress.org/reference/classes/WP_User_Query/prepare_query/). for more information on accepted arguments. > > > If you follow that link you'll see the list of arguments, and one of those is: > > **'has\_published\_posts'** > > > *(bool|array)* Pass an array of post types to filter results to users who have published posts in those post types. `true` is an alias for all public post types. > > > So you can get published authors like this: ``` $authors = get_users( [ 'has_published_posts' => true ] ); ``` Or, if you just want users who have published posts: ``` $authors = get_users( [ 'has_published_posts' => [ 'post' ], ] ); ```
340,295
<p>How to move 1 WP site from a mult-site environment to a different multi-site area?</p> <p>Doing on same server if that assists at all.</p> <p>We know how to move a site from a multi-site area into a single site area, and vice versa. Loads of coverage and instructions on this. But not to move a site from 1 multi-site WP area to another on different domain/server.</p>
[ { "answer_id": 340300, "author": "Blackbam", "author_id": 12035, "author_profile": "https://wordpress.stackexchange.com/users/12035", "pm_score": 2, "selected": false, "text": "<p>If you know how WordPress is structured internally it should not be too hard. Here are the steps:</p>\n\n<ol>\n<li>For your site to migrate create a new site in the WordPress multisite environment (the information in the following tables must fit the new environment)</li>\n</ol>\n\n<blockquote>\n<pre><code>wp_blogs (especially this)\nwp_blogs_versions (probably irrelevant)\nwp_registration_log (probably irrelevant)\nwp_signups (probably irrelevant)\nwp_site (especially this)\nwp_sitemeta (especially this)\n</code></pre>\n</blockquote>\n\n<ol start=\"3\">\n<li>Extract the media folder from the old multisite subsite and copy it to the new multisite subsite</li>\n<li>The following tables are site specific - move them from the old subsite to the new subsite (delete the tables from the new multisite and replace them, adjust the prefix)</li>\n</ol>\n\n<blockquote>\n<pre><code>wp_2_commentmeta\nwp_2_comments\nwp_2_links\nwp_2_options\nwp_2_postmeta\nwp_2_posts\nwp_2_terms\nwp_2_termmeta\nwp_2_term_relationships\nwp_2_term_taxonomy\n</code></pre>\n</blockquote>\n\n<ol start=\"4\">\n<li><p>The <code>wp_users</code> and <code>wp_usermeta</code> information will be different in your new multisite environment - you will have to extract the information from the old database or synchronize them somehow</p></li>\n<li><p>The Plugins/Themes in your new environment will be different, you have to make sure that this is either available or you remove those functionality from the subsite first.</p></li>\n</ol>\n\n<p>Note that there might still be certain problems to fix as of different environments.</p>\n\n<p>An easier way is to just copy over the theme and export the users and their contents and import them in your new site. If this is sufficient depends on what you want to achieve.</p>\n" }, { "answer_id": 341852, "author": "Emerson Maningo", "author_id": 20972, "author_profile": "https://wordpress.stackexchange.com/users/20972", "pm_score": -1, "selected": false, "text": "<p>If I understood the question correctly, you want to move a multisite sub-site from one site to another multisite subsite in different domain or server?</p>\n\n<p>There is a plugin that can do this easily: <a href=\"https://wordpress.org/plugins/prime-mover/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/prime-mover/</a></p>\n\n<p>Documentation: \n<a href=\"https://codexonics.com/prime_mover/prime-mover/how-to-migrate-your-wordpress-multisite-sub-site-to-another-multisite-sub-site/\" rel=\"nofollow noreferrer\">https://codexonics.com/prime_mover/prime-mover/how-to-migrate-your-wordpress-multisite-sub-site-to-another-multisite-sub-site/</a></p>\n\n<p><a href=\"https://codexonics.com/prime_mover/prime-mover/important-notes-on-prime-mover-single-site-and-multisite-packages/\" rel=\"nofollow noreferrer\">https://codexonics.com/prime_mover/prime-mover/important-notes-on-prime-mover-single-site-and-multisite-packages/</a></p>\n\n<p>The plugin can also do: single-site to single-site, single-site to multisite, multisite to single-site and multisite subsite to another multisite subsite migrations (just like your case). Just activate on the network admin go to the sub-site listed in Network Sites and click Export to generate site package. On the target end.</p>\n\n<p>One thing that is important is that in WordPress multisite, subsite is identified by blog ID. So it means that if in the origin multisite, the subsite has a blog ID of 7. It needs to be migrated also on the target server with a blog ID of 7. </p>\n\n<p>Otherwise if its different blog ID, it could mean different site. So cannot mix it up.</p>\n\n<p>Ideally in multisite to multisite migration, domain name / website URL can change. But not its blog ID, which is supposed to be used as a means of identification.</p>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80415/" ]
How to move 1 WP site from a mult-site environment to a different multi-site area? Doing on same server if that assists at all. We know how to move a site from a multi-site area into a single site area, and vice versa. Loads of coverage and instructions on this. But not to move a site from 1 multi-site WP area to another on different domain/server.
If you know how WordPress is structured internally it should not be too hard. Here are the steps: 1. For your site to migrate create a new site in the WordPress multisite environment (the information in the following tables must fit the new environment) > > > ``` > wp_blogs (especially this) > wp_blogs_versions (probably irrelevant) > wp_registration_log (probably irrelevant) > wp_signups (probably irrelevant) > wp_site (especially this) > wp_sitemeta (especially this) > > ``` > > 3. Extract the media folder from the old multisite subsite and copy it to the new multisite subsite 4. The following tables are site specific - move them from the old subsite to the new subsite (delete the tables from the new multisite and replace them, adjust the prefix) > > > ``` > wp_2_commentmeta > wp_2_comments > wp_2_links > wp_2_options > wp_2_postmeta > wp_2_posts > wp_2_terms > wp_2_termmeta > wp_2_term_relationships > wp_2_term_taxonomy > > ``` > > 4. The `wp_users` and `wp_usermeta` information will be different in your new multisite environment - you will have to extract the information from the old database or synchronize them somehow 5. The Plugins/Themes in your new environment will be different, you have to make sure that this is either available or you remove those functionality from the subsite first. Note that there might still be certain problems to fix as of different environments. An easier way is to just copy over the theme and export the users and their contents and import them in your new site. If this is sufficient depends on what you want to achieve.
340,328
<p>How do I create a page(in wordpress theme folder) so that it can be accessed on my site as <code>examplepage.com/somepost.php</code>?</p> <p>I can see it as <code>examplepage.com/wp-content/themes/mytheme/somepost.php</code> but is there any way to cut off the path? Placing the file in the root folder is not an option. </p> <p>Thanks in advance.</p>
[ { "answer_id": 340332, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": true, "text": "<p>You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule somepost.php ^/somepost/\n</code></pre>\n\n<p>It's much more common, and recommended, to create a PHP file <em>and</em> a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder:</p>\n\n<pre><code>&lt;?php\n/* Template Name: Show Some Post\n*/\n// all your PHP here\n?&gt;\n</code></pre>\n\n<p>then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as <a href=\"http://examplepage.com/somepost/\" rel=\"nofollow noreferrer\">http://examplepage.com/somepost/</a>.</p>\n" }, { "answer_id": 340347, "author": "Ryan DiMascio", "author_id": 89412, "author_profile": "https://wordpress.stackexchange.com/users/89412", "pm_score": 0, "selected": false, "text": "<p>As <a href=\"https://wordpress.stackexchange.com/a/340332/89412\">WebElaine</a> said, it's common practice to create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Page Template</a> in your theme and then create a page in your WordPress dashboard and select the template you just created.</p>\n\n<p>You can also create a PHP file in your theme and name it <em>page-some-post.php</em> and then create a page in your dashboard named <em>Some Post</em>.</p>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340328", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162638/" ]
How do I create a page(in wordpress theme folder) so that it can be accessed on my site as `examplepage.com/somepost.php`? I can see it as `examplepage.com/wp-content/themes/mytheme/somepost.php` but is there any way to cut off the path? Placing the file in the root folder is not an option. Thanks in advance.
You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block: ``` RewriteEngine On RewriteRule somepost.php ^/somepost/ ``` It's much more common, and recommended, to create a PHP file *and* a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder: ``` <?php /* Template Name: Show Some Post */ // all your PHP here ?> ``` then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as <http://examplepage.com/somepost/>.
340,343
<p>I'm displaying list of term from each taxonomy assigned to custom post:</p> <pre><code>&lt;?php $taxonomies = get_object_taxonomies( $post ); foreach ( $taxonomies as $taxonomy ) { the_terms( $post-&gt;ID, $taxonomy, '&lt;span class="e-article__category__item"&gt;&lt;strong&gt;' . SINGULAR_NAME . ': &lt;/strong&gt; ', ", ", '&lt;/span&gt;' ); } ?&gt; </code></pre> <p>but here, in SINGULAR_NAME I would like to display the singular_name of custom taxonomy.</p> <p>I was trying this:</p> <pre><code>&lt;?php $taxonomies = get_object_taxonomies( $post ); foreach ( $taxonomies as $taxonomy ) { $term_name = $taxonomy-&gt;labels-&gt;singular_name; the_terms( $post-&gt;ID, $taxonomy, '&lt;span class="e-article__category__item"&gt;&lt;strong&gt;' . $term_name . ': &lt;/strong&gt; ', ", ", '&lt;/span&gt;' ); } ?&gt; </code></pre> <p>What I want to do is show all terms, separately for each taxonomy, but before each list I want to display taxonomy name (singular_name).</p> <p>How to do that correctly?</p> <p>Thanks :)</p>
[ { "answer_id": 340332, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": true, "text": "<p>You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule somepost.php ^/somepost/\n</code></pre>\n\n<p>It's much more common, and recommended, to create a PHP file <em>and</em> a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder:</p>\n\n<pre><code>&lt;?php\n/* Template Name: Show Some Post\n*/\n// all your PHP here\n?&gt;\n</code></pre>\n\n<p>then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as <a href=\"http://examplepage.com/somepost/\" rel=\"nofollow noreferrer\">http://examplepage.com/somepost/</a>.</p>\n" }, { "answer_id": 340347, "author": "Ryan DiMascio", "author_id": 89412, "author_profile": "https://wordpress.stackexchange.com/users/89412", "pm_score": 0, "selected": false, "text": "<p>As <a href=\"https://wordpress.stackexchange.com/a/340332/89412\">WebElaine</a> said, it's common practice to create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Page Template</a> in your theme and then create a page in your WordPress dashboard and select the template you just created.</p>\n\n<p>You can also create a PHP file in your theme and name it <em>page-some-post.php</em> and then create a page in your dashboard named <em>Some Post</em>.</p>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340343", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163478/" ]
I'm displaying list of term from each taxonomy assigned to custom post: ``` <?php $taxonomies = get_object_taxonomies( $post ); foreach ( $taxonomies as $taxonomy ) { the_terms( $post->ID, $taxonomy, '<span class="e-article__category__item"><strong>' . SINGULAR_NAME . ': </strong> ', ", ", '</span>' ); } ?> ``` but here, in SINGULAR\_NAME I would like to display the singular\_name of custom taxonomy. I was trying this: ``` <?php $taxonomies = get_object_taxonomies( $post ); foreach ( $taxonomies as $taxonomy ) { $term_name = $taxonomy->labels->singular_name; the_terms( $post->ID, $taxonomy, '<span class="e-article__category__item"><strong>' . $term_name . ': </strong> ', ", ", '</span>' ); } ?> ``` What I want to do is show all terms, separately for each taxonomy, but before each list I want to display taxonomy name (singular\_name). How to do that correctly? Thanks :)
You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block: ``` RewriteEngine On RewriteRule somepost.php ^/somepost/ ``` It's much more common, and recommended, to create a PHP file *and* a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder: ``` <?php /* Template Name: Show Some Post */ // all your PHP here ?> ``` then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as <http://examplepage.com/somepost/>.
340,351
<p>I used an ACF repeater field for data sheets/instruction manual download links of products in woocommerce. There's 50 products and each has 1 to 4 download links on their product page. I've been searching for a way to list all the links form all 50 products on one page the way you would query all posts on a page in a list. I don't even know where to start looking and I didn't see anything specific on the ACF forums.</p>
[ { "answer_id": 340332, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": true, "text": "<p>You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule somepost.php ^/somepost/\n</code></pre>\n\n<p>It's much more common, and recommended, to create a PHP file <em>and</em> a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder:</p>\n\n<pre><code>&lt;?php\n/* Template Name: Show Some Post\n*/\n// all your PHP here\n?&gt;\n</code></pre>\n\n<p>then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as <a href=\"http://examplepage.com/somepost/\" rel=\"nofollow noreferrer\">http://examplepage.com/somepost/</a>.</p>\n" }, { "answer_id": 340347, "author": "Ryan DiMascio", "author_id": 89412, "author_profile": "https://wordpress.stackexchange.com/users/89412", "pm_score": 0, "selected": false, "text": "<p>As <a href=\"https://wordpress.stackexchange.com/a/340332/89412\">WebElaine</a> said, it's common practice to create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Page Template</a> in your theme and then create a page in your WordPress dashboard and select the template you just created.</p>\n\n<p>You can also create a PHP file in your theme and name it <em>page-some-post.php</em> and then create a page in your dashboard named <em>Some Post</em>.</p>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340351", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103767/" ]
I used an ACF repeater field for data sheets/instruction manual download links of products in woocommerce. There's 50 products and each has 1 to 4 download links on their product page. I've been searching for a way to list all the links form all 50 products on one page the way you would query all posts on a page in a list. I don't even know where to start looking and I didn't see anything specific on the ACF forums.
You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block: ``` RewriteEngine On RewriteRule somepost.php ^/somepost/ ``` It's much more common, and recommended, to create a PHP file *and* a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder: ``` <?php /* Template Name: Show Some Post */ // all your PHP here ?> ``` then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as <http://examplepage.com/somepost/>.
340,358
<p>Given this code:</p> <pre><code>class test_class { function greeting() { echo 'Howdy! Test is successful!'; } function greeting_head() { //Close PHP tags ?&gt; &lt;?php greeting() ?&gt; &lt;?php //Open PHP tags } } add_action( 'wp_head', array( 'test_class', 'greeting_head' ) ); </code></pre> <p><code>greeting()</code> is undefined. How to access if from outside <code>test_class</code>?</p> <p>UPDATE: I wound up using Sally J.'s solution</p> <p>PREVIOUS UPDATE: I tried Adnane's solution and it didn't work, but it put me on the trail of the correct answer.</p> <pre><code>class test_class { public static function greeting() { return 'Howdy! Test is successful!'; } function greeting_head() { echo self::greeting(); } } add_action( 'wp_head', array( 'test_class', 'greeting_head' ) ); </code></pre> <p>Apparrently I was calling a static function in a non-static way. <a href="https://stackoverflow.com/questions/30860601/fatal-error-using-this-when-not-in-object-context-in-e-xampp-htdocs">See this question</a>.</p>
[ { "answer_id": 340363, "author": "Adnane Zarrouk", "author_id": 64067, "author_profile": "https://wordpress.stackexchange.com/users/64067", "pm_score": -1, "selected": false, "text": "<p>1 - Inside your <strong>class</strong> you are trying to call the function <strong>greeting()</strong> thats not a Method of current <strong>class</strong> so php will try to find this function outside the <strong>class</strong> and will show Fatal error message if function not exists.</p>\n\n<p>to Call this function inside your class you need to call it as method :</p>\n\n<pre><code>$this-&gt;greeting();\n</code></pre>\n\n<p>2 - Is not a good Idea to use php tags inside <strong>class</strong></p>\n\n<p><strong>This is the right Way :</strong></p>\n\n<pre><code>class test_class {\n\n function greeting() {\n return 'Howdy! Test is successful!';\n }\n\n function greeting_head() {\n echo $this-&gt;greeting();\n }\n}\n\nadd_action( 'wp_head', array( 'test_class', 'greeting_head' ) );\n</code></pre>\n" }, { "answer_id": 340366, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You're using the <em>static</em> class method call when supplying a <a href=\"https://www.php.net/manual/en/language.types.callable.php\" rel=\"nofollow noreferrer\">callable/callback</a> to <code>add_action()</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wp_head', array( 'test_class', 'greeting_head' ) );\n</code></pre>\n\n<p>So you should make the <code>greeting_head()</code> a static method in your <code>test_class</code> class. But you'd also need to make the <code>greeting()</code> a static method:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class test_class {\n\n public static function greeting() {\n echo 'Howdy! Test is successful!';\n }\n\n public static function greeting_head() {\n self::greeting();\n }\n}\n</code></pre>\n\n<p>And unless you use a singleton pattern, you'd need to use the <code>self</code> keyword to access methods and properties from a static method; for example, in the above code, you could see that I'm using <code>self::greeting()</code> and not <code>$this-&gt;greeting()</code>.</p>\n\n<p>But I wouldn't suggest using static class methods unless <em>absolutely</em> necessary, and you can just leave your class as it is now &mdash; <em>except, use <code>$this-&gt;greeting()</code> in the <code>greeting_head()</code> method</em> &mdash; and use the object method call when supplying the <code>add_action()</code> callback:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class test_class {\n\n function greeting() {\n echo 'Howdy! Test is successful!';\n }\n\n function greeting_head() {\n $this-&gt;greeting();\n }\n}\n\n$test_class = new test_class;\n\nadd_action( 'wp_head', array( $test_class, 'greeting_head' ) );\n</code></pre>\n\n<p>This answer <em>doesn't</em> cover everything about classes in PHP, but I hope it helps you; and if you need further guide, you can search on Stack Overflow or even here on WordPress Stack Exchange.. =)</p>\n\n<h2>UPDATE</h2>\n\n<p>For completeness,</p>\n\n<ol>\n<li><p>You're getting this error because you're trying to access a <em>global</em> function named <code>greeting</code> which obviously doesn't exist since PHP threw that error:</p>\n\n<blockquote>\n <p><code>greeting()</code> is undefined.</p>\n</blockquote></li>\n<li><p>\"<em>How to access if from outside <code>test_class</code>?</em>\" &mdash; Use the <code>$this</code> keyword: <code>$this-&gt;greeting()</code>, just as @Adnane and I mentioned in our original answer. Or use <code>self::greeting()</code> as I stated in my original answer.</p>\n\n<p><strong>(Update)</strong> \"<em>if from outside <code>test_class</code></em>\" &mdash; Actually, the proper question should be, \"how to access the <code>greeting()</code> method from another method <em>in the same class</em>\" because you are actually calling <code>test_class::greeting()</code> from <code>test_class::greeting_head()</code>. :)</p></li>\n<li><p>And your code as in the current question would result in the following PHP <em>notice</em>: (see the <code>add_action()</code> note above)</p>\n\n<blockquote>\n <p>Non-static method test_class::greeting_head() should not be called\n statically</p>\n</blockquote>\n\n<p>In addition, you'd get the following PHP fatal error if you simply use <code>$this</code> in your original <code>greeting_head()</code>:</p>\n\n<blockquote>\n <p>Uncaught Error: Using $this when not in object context</p>\n</blockquote></li>\n</ol>\n\n<p>And for this question:</p>\n\n<blockquote>\n <p>Can you point me to some documentation on the pros and cons of using\n static class methods?</p>\n</blockquote>\n\n<ul>\n<li><p><a href=\"https://wpshout.com/courses/object-oriented-php-for-wordpress-developers/php-static-methods-in-depth/\" rel=\"nofollow noreferrer\">https://wpshout.com/courses/object-oriented-php-for-wordpress-developers/php-static-methods-in-depth/</a></p></li>\n<li><p><a href=\"https://www.php.net/manual/en/language.oop5.basic.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.oop5.basic.php</a></p></li>\n<li><p><a href=\"https://www.php.net/manual/en/language.oop5.static.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.oop5.static.php</a></p></li>\n</ul>\n" } ]
2019/06/12
[ "https://wordpress.stackexchange.com/questions/340358", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119814/" ]
Given this code: ``` class test_class { function greeting() { echo 'Howdy! Test is successful!'; } function greeting_head() { //Close PHP tags ?> <?php greeting() ?> <?php //Open PHP tags } } add_action( 'wp_head', array( 'test_class', 'greeting_head' ) ); ``` `greeting()` is undefined. How to access if from outside `test_class`? UPDATE: I wound up using Sally J.'s solution PREVIOUS UPDATE: I tried Adnane's solution and it didn't work, but it put me on the trail of the correct answer. ``` class test_class { public static function greeting() { return 'Howdy! Test is successful!'; } function greeting_head() { echo self::greeting(); } } add_action( 'wp_head', array( 'test_class', 'greeting_head' ) ); ``` Apparrently I was calling a static function in a non-static way. [See this question](https://stackoverflow.com/questions/30860601/fatal-error-using-this-when-not-in-object-context-in-e-xampp-htdocs).
You're using the *static* class method call when supplying a [callable/callback](https://www.php.net/manual/en/language.types.callable.php) to `add_action()`: ```php add_action( 'wp_head', array( 'test_class', 'greeting_head' ) ); ``` So you should make the `greeting_head()` a static method in your `test_class` class. But you'd also need to make the `greeting()` a static method: ```php class test_class { public static function greeting() { echo 'Howdy! Test is successful!'; } public static function greeting_head() { self::greeting(); } } ``` And unless you use a singleton pattern, you'd need to use the `self` keyword to access methods and properties from a static method; for example, in the above code, you could see that I'm using `self::greeting()` and not `$this->greeting()`. But I wouldn't suggest using static class methods unless *absolutely* necessary, and you can just leave your class as it is now — *except, use `$this->greeting()` in the `greeting_head()` method* — and use the object method call when supplying the `add_action()` callback: ```php class test_class { function greeting() { echo 'Howdy! Test is successful!'; } function greeting_head() { $this->greeting(); } } $test_class = new test_class; add_action( 'wp_head', array( $test_class, 'greeting_head' ) ); ``` This answer *doesn't* cover everything about classes in PHP, but I hope it helps you; and if you need further guide, you can search on Stack Overflow or even here on WordPress Stack Exchange.. =) UPDATE ------ For completeness, 1. You're getting this error because you're trying to access a *global* function named `greeting` which obviously doesn't exist since PHP threw that error: > > `greeting()` is undefined. > > > 2. "*How to access if from outside `test_class`?*" — Use the `$this` keyword: `$this->greeting()`, just as @Adnane and I mentioned in our original answer. Or use `self::greeting()` as I stated in my original answer. **(Update)** "*if from outside `test_class`*" — Actually, the proper question should be, "how to access the `greeting()` method from another method *in the same class*" because you are actually calling `test_class::greeting()` from `test_class::greeting_head()`. :) 3. And your code as in the current question would result in the following PHP *notice*: (see the `add_action()` note above) > > Non-static method test\_class::greeting\_head() should not be called > statically > > > In addition, you'd get the following PHP fatal error if you simply use `$this` in your original `greeting_head()`: > > Uncaught Error: Using $this when not in object context > > > And for this question: > > Can you point me to some documentation on the pros and cons of using > static class methods? > > > * <https://wpshout.com/courses/object-oriented-php-for-wordpress-developers/php-static-methods-in-depth/> * <https://www.php.net/manual/en/language.oop5.basic.php> * <https://www.php.net/manual/en/language.oop5.static.php>
340,362
<p>I'm getting several create_function is depreciated errors from a plugin as the result of a recent WP upgrade to 5.2. The plugin is no longer supported which means I need to refactor the code myself. Would anyone be able to get me pointed in the right direction?</p> <pre><code> function _options_page(){ if($this-&gt;args['page_type'] == 'submenu'){ if(!isset($this-&gt;args['page_parent']) || empty($this-&gt;args['page_parent'])){ $this-&gt;args['page_parent'] = 'themes.php'; } $this-&gt;page = add_theme_page( $this-&gt;args['page_parent'], $this-&gt;args['page_title'], $this-&gt;args['menu_title'], $this-&gt;args['page_cap'], $this-&gt;args['page_slug'], array(&amp;$this, '_options_page_html') ); }else{ $this-&gt;page = add_theme_page( $this-&gt;args['page_title'], $this-&gt;args['menu_title'], $this-&gt;args['page_cap'], $this-&gt;args['page_slug'], array(&amp;$this, '_options_page_html'), $this-&gt;args['menu_icon'], $this-&gt;args['page_position'] ); if(true === $this-&gt;args['allow_sub_menu']){ //this is needed to remove the top level menu item from showing in the submenu add_theme_page($this-&gt;args['page_slug'],$this-&gt;args['page_title'],'',$this-&gt;args['page_cap'],$this-&gt;args['page_slug'],create_function( '$a', "return null;" )); foreach($this-&gt;sections as $k =&gt; $section){ add_theme_page( $this-&gt;args['page_slug'], $section['title'], $section['title'], $this-&gt;args['page_cap'], $this-&gt;args['page_slug'].'&amp;tab='.$k, create_function( '$a', "return null;" ) ); } if(true === $this-&gt;args['show_import_export']){ add_theme_page( $this-&gt;args['page_slug'], __('Import / Export', 'nhp-opts'), __('Import / Export', 'nhp-opts'), $this-&gt;args['page_cap'], $this-&gt;args['page_slug'].'&amp;tab=import_export_default', create_function( '$a', "return null;" ) ); }//if foreach($this-&gt;extra_tabs as $k =&gt; $tab){ add_theme_page( $this-&gt;args['page_slug'], $tab['title'], $tab['title'], $this-&gt;args['page_cap'], $this-&gt;args['page_slug'].'&amp;tab='.$k, create_function( '$a', "return null;" ) ); } if(true === $this-&gt;args['dev_mode']){ add_theme_page( $this-&gt;args['page_slug'], __('Dev Mode Info', 'nhp-opts'), __('Dev Mode Info', 'nhp-opts'), $this-&gt;args['page_cap'], $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', create_function( '$a', "return null;" ) ); }//if }//if }//else add_action('admin_print_styles-'.$this-&gt;page, array(&amp;$this, '_enqueue')); add_action('load-'.$this-&gt;page, array(&amp;$this, '_load_page')); }//function </code></pre>
[ { "answer_id": 340364, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": false, "text": "<p>There is an inbuilt function for returning <code>null</code>: <code>__return_null</code>. </p>\n\n<p>So you can replace <code>create_function('$a', 'return null;');</code> with just <code>'__return_null'</code> (note the quotes) as it seems <code>$a</code> is not used anyway.</p>\n\n<p>Or you can use an anonymous function as the argument directly: <code>function($a) {return null;}</code> (no quotes). Either way since the argument is expecting a function calback.</p>\n" }, { "answer_id": 340365, "author": "Adnane Zarrouk", "author_id": 64067, "author_profile": "https://wordpress.stackexchange.com/users/64067", "pm_score": 2, "selected": false, "text": "<p>You should be able to change create_function( '$a', \"return null;\" ) to <a href=\"https://php.net/manual/en/functions.anonymous.php\" rel=\"nofollow noreferrer\">Anonymous Function</a> (aka Closure) :</p>\n\n<p><strong>From :</strong></p>\n\n<pre><code> add_theme_page(\n $this-&gt;args['page_slug'],\n __('Dev Mode Info', 'nhp-opts'), \n __('Dev Mode Info', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', \n create_function( '$a', \"return null;\" )\n );\n</code></pre>\n\n<p><strong>To :</strong> </p>\n\n<pre><code> add_theme_page(\n $this-&gt;args['page_slug'],\n __('Dev Mode Info', 'nhp-opts'), \n __('Dev Mode Info', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', \n function($a){ return null; }\n );\n</code></pre>\n\n<p>full code changes :</p>\n\n<pre><code>function _options_page(){\n if($this-&gt;args['page_type'] == 'submenu'){\n if(!isset($this-&gt;args['page_parent']) || empty($this-&gt;args['page_parent'])){\n $this-&gt;args['page_parent'] = 'themes.php';\n }\n $this-&gt;page = add_theme_page(\n $this-&gt;args['page_parent'],\n $this-&gt;args['page_title'], \n $this-&gt;args['menu_title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'], \n array(&amp;$this, '_options_page_html')\n );\n }else{\n $this-&gt;page = add_theme_page(\n $this-&gt;args['page_title'], \n $this-&gt;args['menu_title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'], \n array(&amp;$this, '_options_page_html'),\n $this-&gt;args['menu_icon'],\n $this-&gt;args['page_position']\n );\n\n if(true === $this-&gt;args['allow_sub_menu']){\n\n //this is needed to remove the top level menu item from showing in the submenu\n add_theme_page(\n $this-&gt;args['page_slug'],\n $this-&gt;args['page_title'],\n '',\n $this-&gt;args['page_cap'],\n $this-&gt;args['page_slug'],\n function($a){ return null; }\n );\n\n\n foreach($this-&gt;sections as $k =&gt; $section){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n $section['title'], \n $section['title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab='.$k, \n function($a){ return null; }\n );\n\n }\n\n if(true === $this-&gt;args['show_import_export']){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n __('Import / Export', 'nhp-opts'), \n __('Import / Export', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=import_export_default', \n function($a){ return null; }\n );\n\n }//if\n\n foreach($this-&gt;extra_tabs as $k =&gt; $tab){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n $tab['title'], \n $tab['title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab='.$k, \n function($a){ return null; }\n );\n\n }\n if(true === $this-&gt;args['dev_mode']){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n __('Dev Mode Info', 'nhp-opts'), \n __('Dev Mode Info', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', \n function($a){ return null; }\n );\n\n }//if\n }//if \n\n\n }//else\n add_action('admin_print_styles-'.$this-&gt;page, array(&amp;$this, '_enqueue'));\n add_action('load-'.$this-&gt;page, array(&amp;$this, '_load_page'));\n}//function\n</code></pre>\n" } ]
2019/06/13
[ "https://wordpress.stackexchange.com/questions/340362", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116635/" ]
I'm getting several create\_function is depreciated errors from a plugin as the result of a recent WP upgrade to 5.2. The plugin is no longer supported which means I need to refactor the code myself. Would anyone be able to get me pointed in the right direction? ``` function _options_page(){ if($this->args['page_type'] == 'submenu'){ if(!isset($this->args['page_parent']) || empty($this->args['page_parent'])){ $this->args['page_parent'] = 'themes.php'; } $this->page = add_theme_page( $this->args['page_parent'], $this->args['page_title'], $this->args['menu_title'], $this->args['page_cap'], $this->args['page_slug'], array(&$this, '_options_page_html') ); }else{ $this->page = add_theme_page( $this->args['page_title'], $this->args['menu_title'], $this->args['page_cap'], $this->args['page_slug'], array(&$this, '_options_page_html'), $this->args['menu_icon'], $this->args['page_position'] ); if(true === $this->args['allow_sub_menu']){ //this is needed to remove the top level menu item from showing in the submenu add_theme_page($this->args['page_slug'],$this->args['page_title'],'',$this->args['page_cap'],$this->args['page_slug'],create_function( '$a', "return null;" )); foreach($this->sections as $k => $section){ add_theme_page( $this->args['page_slug'], $section['title'], $section['title'], $this->args['page_cap'], $this->args['page_slug'].'&tab='.$k, create_function( '$a', "return null;" ) ); } if(true === $this->args['show_import_export']){ add_theme_page( $this->args['page_slug'], __('Import / Export', 'nhp-opts'), __('Import / Export', 'nhp-opts'), $this->args['page_cap'], $this->args['page_slug'].'&tab=import_export_default', create_function( '$a', "return null;" ) ); }//if foreach($this->extra_tabs as $k => $tab){ add_theme_page( $this->args['page_slug'], $tab['title'], $tab['title'], $this->args['page_cap'], $this->args['page_slug'].'&tab='.$k, create_function( '$a', "return null;" ) ); } if(true === $this->args['dev_mode']){ add_theme_page( $this->args['page_slug'], __('Dev Mode Info', 'nhp-opts'), __('Dev Mode Info', 'nhp-opts'), $this->args['page_cap'], $this->args['page_slug'].'&tab=dev_mode_default', create_function( '$a', "return null;" ) ); }//if }//if }//else add_action('admin_print_styles-'.$this->page, array(&$this, '_enqueue')); add_action('load-'.$this->page, array(&$this, '_load_page')); }//function ```
There is an inbuilt function for returning `null`: `__return_null`. So you can replace `create_function('$a', 'return null;');` with just `'__return_null'` (note the quotes) as it seems `$a` is not used anyway. Or you can use an anonymous function as the argument directly: `function($a) {return null;}` (no quotes). Either way since the argument is expecting a function calback.
340,372
<p>I need to retrieve the name of all the categories that a given user has published posts for. If I can also get a URL for the archive of that cat for that user only, this would make me very happy.</p> <p>How do I get a list of all categories that a given user has written blog posts for (and possibly the URL for that user's cat specific archive)?</p> <h3>What I've got so far:</h3> <p>From what I have learned, I have guessed:</p> <pre><code> $args=array(); $args['taxonomy']='categories'; $args['hide_empty']=TRUE; $args['???']=$user_id; $list = get_terms( $args ); </code></pre> <p>or <a href="https://wordpress.stackexchange.com/questions/340146/get-all-the-blogs-categories-and-the-related-urls">maybe</a></p> <pre><code> $cats = get_categories( 'hide_empty=0' . '???' ); </code></pre> <p>One, both, or neither of these might be what I need. Can anyone help me get this across the finish line?</p>
[ { "answer_id": 340364, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": false, "text": "<p>There is an inbuilt function for returning <code>null</code>: <code>__return_null</code>. </p>\n\n<p>So you can replace <code>create_function('$a', 'return null;');</code> with just <code>'__return_null'</code> (note the quotes) as it seems <code>$a</code> is not used anyway.</p>\n\n<p>Or you can use an anonymous function as the argument directly: <code>function($a) {return null;}</code> (no quotes). Either way since the argument is expecting a function calback.</p>\n" }, { "answer_id": 340365, "author": "Adnane Zarrouk", "author_id": 64067, "author_profile": "https://wordpress.stackexchange.com/users/64067", "pm_score": 2, "selected": false, "text": "<p>You should be able to change create_function( '$a', \"return null;\" ) to <a href=\"https://php.net/manual/en/functions.anonymous.php\" rel=\"nofollow noreferrer\">Anonymous Function</a> (aka Closure) :</p>\n\n<p><strong>From :</strong></p>\n\n<pre><code> add_theme_page(\n $this-&gt;args['page_slug'],\n __('Dev Mode Info', 'nhp-opts'), \n __('Dev Mode Info', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', \n create_function( '$a', \"return null;\" )\n );\n</code></pre>\n\n<p><strong>To :</strong> </p>\n\n<pre><code> add_theme_page(\n $this-&gt;args['page_slug'],\n __('Dev Mode Info', 'nhp-opts'), \n __('Dev Mode Info', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', \n function($a){ return null; }\n );\n</code></pre>\n\n<p>full code changes :</p>\n\n<pre><code>function _options_page(){\n if($this-&gt;args['page_type'] == 'submenu'){\n if(!isset($this-&gt;args['page_parent']) || empty($this-&gt;args['page_parent'])){\n $this-&gt;args['page_parent'] = 'themes.php';\n }\n $this-&gt;page = add_theme_page(\n $this-&gt;args['page_parent'],\n $this-&gt;args['page_title'], \n $this-&gt;args['menu_title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'], \n array(&amp;$this, '_options_page_html')\n );\n }else{\n $this-&gt;page = add_theme_page(\n $this-&gt;args['page_title'], \n $this-&gt;args['menu_title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'], \n array(&amp;$this, '_options_page_html'),\n $this-&gt;args['menu_icon'],\n $this-&gt;args['page_position']\n );\n\n if(true === $this-&gt;args['allow_sub_menu']){\n\n //this is needed to remove the top level menu item from showing in the submenu\n add_theme_page(\n $this-&gt;args['page_slug'],\n $this-&gt;args['page_title'],\n '',\n $this-&gt;args['page_cap'],\n $this-&gt;args['page_slug'],\n function($a){ return null; }\n );\n\n\n foreach($this-&gt;sections as $k =&gt; $section){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n $section['title'], \n $section['title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab='.$k, \n function($a){ return null; }\n );\n\n }\n\n if(true === $this-&gt;args['show_import_export']){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n __('Import / Export', 'nhp-opts'), \n __('Import / Export', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=import_export_default', \n function($a){ return null; }\n );\n\n }//if\n\n foreach($this-&gt;extra_tabs as $k =&gt; $tab){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n $tab['title'], \n $tab['title'], \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab='.$k, \n function($a){ return null; }\n );\n\n }\n if(true === $this-&gt;args['dev_mode']){\n\n add_theme_page(\n $this-&gt;args['page_slug'],\n __('Dev Mode Info', 'nhp-opts'), \n __('Dev Mode Info', 'nhp-opts'), \n $this-&gt;args['page_cap'], \n $this-&gt;args['page_slug'].'&amp;tab=dev_mode_default', \n function($a){ return null; }\n );\n\n }//if\n }//if \n\n\n }//else\n add_action('admin_print_styles-'.$this-&gt;page, array(&amp;$this, '_enqueue'));\n add_action('load-'.$this-&gt;page, array(&amp;$this, '_load_page'));\n}//function\n</code></pre>\n" } ]
2019/06/13
[ "https://wordpress.stackexchange.com/questions/340372", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
I need to retrieve the name of all the categories that a given user has published posts for. If I can also get a URL for the archive of that cat for that user only, this would make me very happy. How do I get a list of all categories that a given user has written blog posts for (and possibly the URL for that user's cat specific archive)? ### What I've got so far: From what I have learned, I have guessed: ``` $args=array(); $args['taxonomy']='categories'; $args['hide_empty']=TRUE; $args['???']=$user_id; $list = get_terms( $args ); ``` or [maybe](https://wordpress.stackexchange.com/questions/340146/get-all-the-blogs-categories-and-the-related-urls) ``` $cats = get_categories( 'hide_empty=0' . '???' ); ``` One, both, or neither of these might be what I need. Can anyone help me get this across the finish line?
There is an inbuilt function for returning `null`: `__return_null`. So you can replace `create_function('$a', 'return null;');` with just `'__return_null'` (note the quotes) as it seems `$a` is not used anyway. Or you can use an anonymous function as the argument directly: `function($a) {return null;}` (no quotes). Either way since the argument is expecting a function calback.
340,379
<p>I wanted to show you this issue. This is happening first time with me in my 10 years career, I have cloned many sites to another domain in past but this is for the first time when I do not see the "site URL and home options" under Wp_Options (phpmyadmin)</p> <p>This is the domain name which I cloned </p> <p><strong><a href="https://13cabsonline.com.au" rel="nofollow noreferrer">https://13cabsonline.com.au</a></strong></p> <p>and this is the destination domain </p> <p><strong><a href="https://silverservice.sydney/" rel="nofollow noreferrer">https://silverservice.sydney/</a></strong></p> <p>I have downloaded and restored files via Backup Widget. Uploaded the file manager + databases and connected the databases with a user too.</p> <p>But the issue is that I am not able to find the options under Wp_Options in phpmyadmin.</p> <p><strong>For example:</strong> A normal look of <code>wp_options</code> is like this <a href="http://prnt.sc/o1724k" rel="nofollow noreferrer">http://prnt.sc/o1724k</a> but I see this <a href="https://prnt.sc/o172as" rel="nofollow noreferrer">https://prnt.sc/o172as</a></p> <p>Can you please have a look at it as there is no video or blog about it on the internet. This is strange to me.</p>
[ { "answer_id": 340382, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Check wp-config.php. It's possible to define these values there, in which case they won't be available as settings, which means they won't be saved in the database.</p>\n\n<blockquote>\n <p>It is possible to set the site URL manually in the wp-config.php file.</p>\n \n <p>Add these two lines to your wp-config.php, where “example.com” is the correct location of your site.</p>\n\n<pre><code>define( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n</code></pre>\n \n <p>This is not necessarily the best fix, it’s just hard-coding the values into the site itself. You won’t be able to edit them on the General settings page anymore when using this method.</p>\n</blockquote>\n\n<p>&mdash; <a href=\"https://wordpress.org/support/article/changing-the-site-url/#edit-wp-config-php\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/#edit-wp-config-php</a></p>\n\n<p>If this was done on the original site, the corresponding values won't exist in <code>wp_options</code>. The solution would be to either change the values in wp-config.php, or remove these lines from wp-config.php and then insert the desired values into <code>wp_options</code> manually.</p>\n" }, { "answer_id": 340392, "author": "Daljit Singh Khalsa", "author_id": 169913, "author_profile": "https://wordpress.stackexchange.com/users/169913", "pm_score": 0, "selected": false, "text": "<p>I got it solved. I deleted the cpanel and recreated cpanel again in my hosting. Then i just restore everything. It worked.</p>\n\n<p>I am going to add a screenshot here which will help others to find the hidden siteurl and home field --> <a href=\"https://i.stack.imgur.com/n0fFa.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n0fFa.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/7ZorD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7ZorD.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/hDWLq.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hDWLq.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>You can search siteurl as well to edit the hidden field.</p>\n\n<p>My official website is this --> <a href=\"https://www.khalsa-website-designers.net/\" rel=\"nofollow noreferrer\">https://www.khalsa-website-designers.net/</a></p>\n\n<p>You can contact me, if you are having the same issue, and want me to help you. I will dafinatly help you for free.</p>\n" }, { "answer_id": 359629, "author": "Дуся Негромова", "author_id": 183481, "author_profile": "https://wordpress.stackexchange.com/users/183481", "pm_score": 0, "selected": false, "text": "<p>I see that this is really a problem. I think you can try using Google’s add url from LinkBox <a href=\"http://linkbox.pro/ru/google-addurl\" rel=\"nofollow noreferrer\">http://linkbox.pro/ru/google-addurl</a> . The problem can be solved this way.</p>\n" }, { "answer_id": 376258, "author": "Acm", "author_id": 195899, "author_profile": "https://wordpress.stackexchange.com/users/195899", "pm_score": 1, "selected": false, "text": "<p>Please check ID no. 13496, 13497 in page 22 of the table list</p>\n<p><a href=\"https://i.stack.imgur.com/JL5D6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JL5D6.png\" alt=\"Screenshot of table\" /></a></p>\n" }, { "answer_id": 388250, "author": "Hussain Abdullah", "author_id": 205806, "author_profile": "https://wordpress.stackexchange.com/users/205806", "pm_score": 0, "selected": false, "text": "<p>I have used the search option and searched for &quot;siteurl&quot; and &quot;home&quot; and thus I have got them under OPTIONS. You can see below how I did it.</p>\n<p><a href=\"https://i.stack.imgur.com/fjHzl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fjHzl.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/AFNFg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AFNFg.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/btntN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/btntN.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/vgoFZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vgoFZ.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 409434, "author": "Md Mohiuddin Sourov", "author_id": 225740, "author_profile": "https://wordpress.stackexchange.com/users/225740", "pm_score": -1, "selected": false, "text": "<p>The easiest way is just to open the SQL file in a code editor. Search for <code>siteurl</code> and then replace the URLs with your preferred way and save the file. after then import the SQL to your database.</p>\n<p>Have fun debugging!</p>\n" } ]
2019/06/13
[ "https://wordpress.stackexchange.com/questions/340379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169913/" ]
I wanted to show you this issue. This is happening first time with me in my 10 years career, I have cloned many sites to another domain in past but this is for the first time when I do not see the "site URL and home options" under Wp\_Options (phpmyadmin) This is the domain name which I cloned **<https://13cabsonline.com.au>** and this is the destination domain **<https://silverservice.sydney/>** I have downloaded and restored files via Backup Widget. Uploaded the file manager + databases and connected the databases with a user too. But the issue is that I am not able to find the options under Wp\_Options in phpmyadmin. **For example:** A normal look of `wp_options` is like this <http://prnt.sc/o1724k> but I see this <https://prnt.sc/o172as> Can you please have a look at it as there is no video or blog about it on the internet. This is strange to me.
Check wp-config.php. It's possible to define these values there, in which case they won't be available as settings, which means they won't be saved in the database. > > It is possible to set the site URL manually in the wp-config.php file. > > > Add these two lines to your wp-config.php, where “example.com” is the correct location of your site. > > > > ``` > define( 'WP_HOME', 'http://example.com' ); > define( 'WP_SITEURL', 'http://example.com' ); > > ``` > > This is not necessarily the best fix, it’s just hard-coding the values into the site itself. You won’t be able to edit them on the General settings page anymore when using this method. > > > — <https://wordpress.org/support/article/changing-the-site-url/#edit-wp-config-php> If this was done on the original site, the corresponding values won't exist in `wp_options`. The solution would be to either change the values in wp-config.php, or remove these lines from wp-config.php and then insert the desired values into `wp_options` manually.
340,432
<p>I'm stuck trying to do the remote SSH with WP-CLI.</p> <p>I have installed WP-CLI on my <strong>Webfaction server</strong> and tested it's working</p> <pre><code># This is in server $ wp --info OS: Linux web561.webfaction.com 3.10.0-862.14.4.el7.x86_64 #1 SMP Wed Sep 26 15:12:11 UTC 2018 x86_64 Shell: /bin/bash PHP binary: /usr/local/bin/php56 PHP version: 5.6.40 php.ini used: /usr/local/lib/php56/php.ini </code></pre> <p>But whenever I tried to do remote access (I'm on Windows10 using GitBash), I get this error:</p> <pre><code># This is in my local comp $ wp @staging --info [email protected]'s password: bash: wp: command not found </code></pre> <p>I'm sure there's nothing wrong with the @staging alias.</p> <p>Path is definitely correct too because when I change it to non-existent directory, it gives <code>No such file or directory</code> error.</p> <p>Have anyone experienced this problem before?</p> <p>Thanks</p>
[ { "answer_id": 340459, "author": "hrsetyono", "author_id": 33361, "author_profile": "https://wordpress.stackexchange.com/users/33361", "pm_score": 2, "selected": false, "text": "<p>Found a solution here <a href=\"https://github.com/hrsetyono/wordpress/wiki/WP-CLI-on-Webfaction\" rel=\"nofollow noreferrer\">https://github.com/hrsetyono/wordpress/wiki/WP-CLI-on-Webfaction</a>\n.</p>\n\n<p>This seems to be Webfaction specific issue</p>\n\n<p>You simply need to open FTP and append this line in <code>/home/yourname/.bashrc</code></p>\n\n<pre><code>export PATH=$PATH:$HOME/bin\n</code></pre>\n" }, { "answer_id": 369714, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 0, "selected": false, "text": "<p>I know this might be trivial, - but it was my solution. I simply hadn't installed WP-CLI on my machine. So I followed the install instructions here: <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a> - and then it worked for me.</p>\n" } ]
2019/06/13
[ "https://wordpress.stackexchange.com/questions/340432", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33361/" ]
I'm stuck trying to do the remote SSH with WP-CLI. I have installed WP-CLI on my **Webfaction server** and tested it's working ``` # This is in server $ wp --info OS: Linux web561.webfaction.com 3.10.0-862.14.4.el7.x86_64 #1 SMP Wed Sep 26 15:12:11 UTC 2018 x86_64 Shell: /bin/bash PHP binary: /usr/local/bin/php56 PHP version: 5.6.40 php.ini used: /usr/local/lib/php56/php.ini ``` But whenever I tried to do remote access (I'm on Windows10 using GitBash), I get this error: ``` # This is in my local comp $ wp @staging --info [email protected]'s password: bash: wp: command not found ``` I'm sure there's nothing wrong with the @staging alias. Path is definitely correct too because when I change it to non-existent directory, it gives `No such file or directory` error. Have anyone experienced this problem before? Thanks
Found a solution here <https://github.com/hrsetyono/wordpress/wiki/WP-CLI-on-Webfaction> . This seems to be Webfaction specific issue You simply need to open FTP and append this line in `/home/yourname/.bashrc` ``` export PATH=$PATH:$HOME/bin ```
340,523
<p>I have enabled SVG uploads using this code:</p> <pre><code>add_filter('upload_mimes', function($mimes) { $mimes['svg'] = 'image/svg+xml'; return $mimes; }); </code></pre> <p>However, uploads of SVG files that start with the <code>&lt;svg&gt;</code> tag fail with the usual "Sorry, this file type is not permitted for security reasons." error that WordPress displays when SVG uploads are not supported.</p> <p>If I add <code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;</code> to the file, just before the opening <code>&lt;svg&gt;</code> tag, the upload succeeds.</p> <p>Why is the XML tag required? Is this requirement normal in WordPress, or is there something wrong with my setup?</p>
[ { "answer_id": 340535, "author": "twelvell", "author_id": 138568, "author_profile": "https://wordpress.stackexchange.com/users/138568", "pm_score": 3, "selected": true, "text": "<p>It seems that in the recent releases of WordPress, changes were made to the mime type handling to make sure that files have the extension they say they do: <a href=\"https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/</a></p>\n\n<p>This poses an issue for SVG files without the tag in them.</p>\n\n<p>SVG is actually an XML, and WordPress is now requiring to have a line such as </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n</code></pre>\n\n<p> in an SVG file.</p>\n" }, { "answer_id": 340550, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>To validate uploads WordPress compares the MIME type of the file to the allowed MIME types for that extension. So when the file is uploaded, WordPress checks for the file extension, <code>.svg</code>, and the file's MIME type. It then these against the allowed MIME type for the <code>.svg</code> extension. If the detected MIME type does not match, then the upload is refused. The purpose of this is to prevent dangerous files being uploaded with a misleading file extension.</p>\n\n<p>The actual detection of the MIME type for the file is ultimately handled by PHP, though. So if your SVG file is not being detected as <code>image/svg+xml</code>, then this is because PHP doesn't recognise it as an SVG file. As you've discovered, it appears that PHP does not recognise files without the <code>&lt;?xml ?&gt;</code> tag as an SVG. It's likely that it thinks the file is an HTML file, <code>text/html</code>. This would be because HTML documents can contain <code>&lt;svg&gt;</code> elements, meaning only way to reliably distinguish between an HTML file with SVG and an actual SVG file is the presence of this tag.</p>\n\n<p>So this is why the tag needs to be included. It's what makes it an <code>image/svg+xml</code> file.</p>\n" } ]
2019/06/14
[ "https://wordpress.stackexchange.com/questions/340523", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131339/" ]
I have enabled SVG uploads using this code: ``` add_filter('upload_mimes', function($mimes) { $mimes['svg'] = 'image/svg+xml'; return $mimes; }); ``` However, uploads of SVG files that start with the `<svg>` tag fail with the usual "Sorry, this file type is not permitted for security reasons." error that WordPress displays when SVG uploads are not supported. If I add `<?xml version="1.0" encoding="UTF-8" standalone="no"?>` to the file, just before the opening `<svg>` tag, the upload succeeds. Why is the XML tag required? Is this requirement normal in WordPress, or is there something wrong with my setup?
It seems that in the recent releases of WordPress, changes were made to the mime type handling to make sure that files have the extension they say they do: <https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/> This poses an issue for SVG files without the tag in them. SVG is actually an XML, and WordPress is now requiring to have a line such as  ``` <?xml version="1.0" encoding="utf-8"?> ```  in an SVG file.
340,531
<p>I want to add a button (that will open an INFO popup screen with info about a certain option in a woocommerce variable product), all that can be easily created with a plugin that converts the whole thing to a shortcode, the problem is to insert it into the products page, this will run on hundreds of products so i cannot simply add it on the HTML directly.</p> <p>I will attach below the CSS code that works to add an IMAGE to where i want, but im guessing we cant use the "Content" CSS to add shortcodes or so i tried..</p> <p>Please advice me how can i insert a shortcode in that EXACT location (that is only one of the lines that will use the INFO button, each variable title will get a different one)</p> <pre><code>.label [for=pa_size-of-product]:before { content: url(shortcode would go here, but only images or text work with this option) !important; } </code></pre> <p>Thanks! </p>
[ { "answer_id": 340535, "author": "twelvell", "author_id": 138568, "author_profile": "https://wordpress.stackexchange.com/users/138568", "pm_score": 3, "selected": true, "text": "<p>It seems that in the recent releases of WordPress, changes were made to the mime type handling to make sure that files have the extension they say they do: <a href=\"https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/</a></p>\n\n<p>This poses an issue for SVG files without the tag in them.</p>\n\n<p>SVG is actually an XML, and WordPress is now requiring to have a line such as </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n</code></pre>\n\n<p> in an SVG file.</p>\n" }, { "answer_id": 340550, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>To validate uploads WordPress compares the MIME type of the file to the allowed MIME types for that extension. So when the file is uploaded, WordPress checks for the file extension, <code>.svg</code>, and the file's MIME type. It then these against the allowed MIME type for the <code>.svg</code> extension. If the detected MIME type does not match, then the upload is refused. The purpose of this is to prevent dangerous files being uploaded with a misleading file extension.</p>\n\n<p>The actual detection of the MIME type for the file is ultimately handled by PHP, though. So if your SVG file is not being detected as <code>image/svg+xml</code>, then this is because PHP doesn't recognise it as an SVG file. As you've discovered, it appears that PHP does not recognise files without the <code>&lt;?xml ?&gt;</code> tag as an SVG. It's likely that it thinks the file is an HTML file, <code>text/html</code>. This would be because HTML documents can contain <code>&lt;svg&gt;</code> elements, meaning only way to reliably distinguish between an HTML file with SVG and an actual SVG file is the presence of this tag.</p>\n\n<p>So this is why the tag needs to be included. It's what makes it an <code>image/svg+xml</code> file.</p>\n" } ]
2019/06/14
[ "https://wordpress.stackexchange.com/questions/340531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170002/" ]
I want to add a button (that will open an INFO popup screen with info about a certain option in a woocommerce variable product), all that can be easily created with a plugin that converts the whole thing to a shortcode, the problem is to insert it into the products page, this will run on hundreds of products so i cannot simply add it on the HTML directly. I will attach below the CSS code that works to add an IMAGE to where i want, but im guessing we cant use the "Content" CSS to add shortcodes or so i tried.. Please advice me how can i insert a shortcode in that EXACT location (that is only one of the lines that will use the INFO button, each variable title will get a different one) ``` .label [for=pa_size-of-product]:before { content: url(shortcode would go here, but only images or text work with this option) !important; } ``` Thanks!
It seems that in the recent releases of WordPress, changes were made to the mime type handling to make sure that files have the extension they say they do: <https://make.wordpress.org/core/2018/12/13/backwards-compatibility-breaks-in-5-0-1/> This poses an issue for SVG files without the tag in them. SVG is actually an XML, and WordPress is now requiring to have a line such as  ``` <?xml version="1.0" encoding="utf-8"?> ```  in an SVG file.
340,539
<p>I am working on an options panel for a plugin. And have an array being posted and updated to the options table. I am using the array_map() function to iterate over the array with sanitize_text_fields() </p> <p>Is this an optimal way to do this? </p> <pre><code> if( ! empty( $_POST['my_array'] ) ) { foreach( $_POST['my_array'] as $value ) { $value = array_map( 'sanitize_text_field', $value ); update_option( 'my_option_value', $value ); } } </code></pre>
[ { "answer_id": 340544, "author": "Lucas Vendramini", "author_id": 168637, "author_profile": "https://wordpress.stackexchange.com/users/168637", "pm_score": 2, "selected": false, "text": "<p>I think you are in the right path. What you can do to improve is:</p>\n\n<p>Separate the logic in functions to increase readability or do a good commenting what you are doing. E.g.:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>... \n\nfunction mytheme_sanitize_fields($fields){\n\n foreach($fields as $field){\n mytheme_sanitize_field($field);\n }\n\n}\n\n\nfunction mytheme_sanitize_field($field){\n if( is_array($field){\n $value = array_map( 'sanitize_text_field', $field );\n\n }\n else{\n\n $value = sanitize_text_field($field);\n }\n\n update_option('yourkey', $value);\n\n...\n\n}\n\n\n...\n\n\nmytheme_sanitize_fields($_POST); \n\n...\n\n\n\n\n\n\n}\n\n</code></pre>\n" }, { "answer_id": 340549, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": true, "text": "<p>It's probably not a great idea. Firstly, if you've got other field types then you should probably use more appropriate functions. For example, <code>textarea</code> fields should be sanitised with <code>sanitize_textarea_field()</code>, and color pickers should be sanitized with <code>sanitize_hex_color()</code>.</p>\n\n<p>You should also consider that <code>$_POST</code> likely also contains fields that you <em>don't</em> want to save, such as the hidden inputs that power the Settings API: <code>option_page</code>, <code>action</code> <code>_wpnonce</code>, and <code>_wp_http_referer</code>.</p>\n\n<p>Lastly, it means that your function essentially accepts all input and will add it to the database. While sanitising and escaping the inputs means they can't do too much damage, you're still not coding defensively. Ideally you'd whitelist the inputs you expect to be submitted, and only submit those.</p>\n\n<p>However, you shouldn't need to handle the <code>$_POST</code> at all when properly using the Settings or Customisation APIs, which suggests you're not building this options panel correctly. When properly using the either of these APIs, the sanitisation function can be specified when registering the setting, and no manipulation of the submission should be necessary.</p>\n" } ]
2019/06/15
[ "https://wordpress.stackexchange.com/questions/340539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138567/" ]
I am working on an options panel for a plugin. And have an array being posted and updated to the options table. I am using the array\_map() function to iterate over the array with sanitize\_text\_fields() Is this an optimal way to do this? ``` if( ! empty( $_POST['my_array'] ) ) { foreach( $_POST['my_array'] as $value ) { $value = array_map( 'sanitize_text_field', $value ); update_option( 'my_option_value', $value ); } } ```
It's probably not a great idea. Firstly, if you've got other field types then you should probably use more appropriate functions. For example, `textarea` fields should be sanitised with `sanitize_textarea_field()`, and color pickers should be sanitized with `sanitize_hex_color()`. You should also consider that `$_POST` likely also contains fields that you *don't* want to save, such as the hidden inputs that power the Settings API: `option_page`, `action` `_wpnonce`, and `_wp_http_referer`. Lastly, it means that your function essentially accepts all input and will add it to the database. While sanitising and escaping the inputs means they can't do too much damage, you're still not coding defensively. Ideally you'd whitelist the inputs you expect to be submitted, and only submit those. However, you shouldn't need to handle the `$_POST` at all when properly using the Settings or Customisation APIs, which suggests you're not building this options panel correctly. When properly using the either of these APIs, the sanitisation function can be specified when registering the setting, and no manipulation of the submission should be necessary.
340,648
<p>I'm developing Wordpress locally with XAMPP, and currently trying to install the WP-CLI tools <a href="https://wp-cli.org/#installing" rel="nofollow noreferrer">as described here</a> using Cygwin. </p> <p>I renamed <code>wp-cli.phar</code> to <code>wp</code>, made it executable and moved it to the <code>XAMPP/php</code> folder. </p> <p>However, running <code>wp</code> gives me the error:</p> <blockquote> <p>Could not open input file: /cygdrive/b/Users/User/Desktop/XAMPP/php/wp</p> </blockquote> <p>On the other hand, doing <code>./wp</code> from the directory that the file is located in runs the program without issue.</p> <p>This is despite the fact that both <code>/cygdrive/b/Users/User/Desktop/XAMPP/php</code> and <code>/cygdrive/b/Users/User/Desktop/XAMPP/php/wp</code> are in my PATH, via Cygwin's <code>~/.bash_profile</code> file. </p> <p>This is confirmed by doing <code>which php</code>:</p> <pre><code>/cygdrive/b/Users/User/Desktop/XAMPP/php/php </code></pre> <p>...and <code>which wp</code>: </p> <pre><code>/cygdrive/b/Users/User/Desktop/XAMPP/php/wp </code></pre> <p><strong>What could be causing this problem?</strong> </p>
[ { "answer_id": 340662, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 2, "selected": false, "text": "<p>There are at least two interesting questions on SO:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/2266661/2199525\">Cygwin and PHPUnit: Could not open input file: /cygdrive/c/xampp/php/phpunit</a></li>\n<li><a href=\"https://stackoverflow.com/q/12276946/2199525\">Composer &amp; Cygwin</a></li>\n</ul>\n\n<p>The easiest seems to be putting an alias into your Cygwin's <code>~/.bashrc</code> or <code>~/.bash_profile</code>:</p>\n\n<pre><code>alias wp=\"/cygdrive/b/Users/User/XAMPP/php/php /cygdrive/b/Users/User/XAMPP/php/wp\"\n</code></pre>\n" }, { "answer_id": 340747, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 3, "selected": true, "text": "<p>I finally managed to scrape together enough information from disparate sources to figure out how to fix this, because - as I'm increasingly finding with anything related to Wordpress development - the documentation is so woefully inadequate.</p>\n<p>The fact that it took so much research and hacking together on my part just to get an official command-line utility working on a platform that it claims to support is ridiculous, and my estimation of the Wordpress project and the Automattic team has dropped massively over the last few weeks for such reasons.</p>\n<p>What follows in this answer adapts information from <a href=\"https://stackoverflow.com/questions/12276946/composer-cygwin/14904607#14904607\">aefxx's answer here</a> and <a href=\"https://wordpress.stackexchange.com/a/340662/167562\">leymannx's answer</a> to this question.</p>\n<p>As far I can tell, the issue here is that <code>php.exe</code> - the PHP binary included with XAMPP, WAMP and similar local servers - is a Windows binary that only understands paths in Windows format. The solution, as coded by <em>aefxx</em> in his answer, is to use a wrapper script that checks for Unix-style paths passed to the PHP binary and converts them into Windows paths that it can understand.</p>\n<p>Note that because this solution is implemented as a wrapper to the PHP binary itself, it should work to solve this issue for any PHP program running under Cygwin, not just WP-CLI.</p>\n<h2>How to get WP-CLI working with Cygwin</h2>\n<p><strong>Remember to replace any paths below with your own.</strong></p>\n<p>Once you've downloaded the <code>wp-cli.phar</code> file and made it executable <a href=\"https://wp-cli.org/#install\" rel=\"nofollow noreferrer\">as detailed in the documentation</a>, move it to where you want to install it - <code>/usr/local/bin</code> tends to be the convention for user-installed binaries on Linux, or inside of XAMPP's PHP server root if you're using XAMPP - and rename it to something easier to type, like <code>wp</code>:</p>\n<pre><code>mv wp-cli.phar /cygdrive/c/XAMPP/php/wp\n</code></pre>\n<p>Then, navigate to the new install directory and create a wrapper file called <code>php</code>:</p>\n<pre><code>cd /cygdrive/c/XAMPP/php/wp &amp;&amp;\ntouch php &amp;&amp;\nchmod +x ./php\n</code></pre>\n<p>Open the file in a text editor and paste the following into it, replacing the path to the PHP executable with your own:</p>\n<pre><code>#!/bin/bash\n\nphp=&quot;/cygdrive/c/XAMPP/php/php.exe&quot;\n\nfor ((n=1; n &lt;= $#; n++)); do\n if [ -e &quot;${!n}&quot; ]; then\n # Converts Unix style paths to Windows equivalents\n path=&quot;$(cygpath --mixed ${!n} | xargs)&quot;\n\n case 1 in\n $(( n == 1 )) )\n set -- &quot;$path&quot; &quot;${@:$(($n+1))}&quot;;;\n $(( n &lt; $# )) )\n set -- &quot;${@:1:$((n-1))}&quot; &quot;$path&quot; ${@:$((n+1)):$#};;\n *)\n set -- &quot;${@:1:$(($#-1))}&quot; &quot;$path&quot;;;\n esac\n fi\ndone\n\n&quot;$php&quot; &quot;$@&quot;\n</code></pre>\n<p>Finally, run <code>wp</code> to confirm that WP-CLI - and any other PHP tools requiring a Cygwin wrapper - is now working on Cygwin.</p>\n" } ]
2019/06/16
[ "https://wordpress.stackexchange.com/questions/340648", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167562/" ]
I'm developing Wordpress locally with XAMPP, and currently trying to install the WP-CLI tools [as described here](https://wp-cli.org/#installing) using Cygwin. I renamed `wp-cli.phar` to `wp`, made it executable and moved it to the `XAMPP/php` folder. However, running `wp` gives me the error: > > Could not open input file: /cygdrive/b/Users/User/Desktop/XAMPP/php/wp > > > On the other hand, doing `./wp` from the directory that the file is located in runs the program without issue. This is despite the fact that both `/cygdrive/b/Users/User/Desktop/XAMPP/php` and `/cygdrive/b/Users/User/Desktop/XAMPP/php/wp` are in my PATH, via Cygwin's `~/.bash_profile` file. This is confirmed by doing `which php`: ``` /cygdrive/b/Users/User/Desktop/XAMPP/php/php ``` ...and `which wp`: ``` /cygdrive/b/Users/User/Desktop/XAMPP/php/wp ``` **What could be causing this problem?**
I finally managed to scrape together enough information from disparate sources to figure out how to fix this, because - as I'm increasingly finding with anything related to Wordpress development - the documentation is so woefully inadequate. The fact that it took so much research and hacking together on my part just to get an official command-line utility working on a platform that it claims to support is ridiculous, and my estimation of the Wordpress project and the Automattic team has dropped massively over the last few weeks for such reasons. What follows in this answer adapts information from [aefxx's answer here](https://stackoverflow.com/questions/12276946/composer-cygwin/14904607#14904607) and [leymannx's answer](https://wordpress.stackexchange.com/a/340662/167562) to this question. As far I can tell, the issue here is that `php.exe` - the PHP binary included with XAMPP, WAMP and similar local servers - is a Windows binary that only understands paths in Windows format. The solution, as coded by *aefxx* in his answer, is to use a wrapper script that checks for Unix-style paths passed to the PHP binary and converts them into Windows paths that it can understand. Note that because this solution is implemented as a wrapper to the PHP binary itself, it should work to solve this issue for any PHP program running under Cygwin, not just WP-CLI. How to get WP-CLI working with Cygwin ------------------------------------- **Remember to replace any paths below with your own.** Once you've downloaded the `wp-cli.phar` file and made it executable [as detailed in the documentation](https://wp-cli.org/#install), move it to where you want to install it - `/usr/local/bin` tends to be the convention for user-installed binaries on Linux, or inside of XAMPP's PHP server root if you're using XAMPP - and rename it to something easier to type, like `wp`: ``` mv wp-cli.phar /cygdrive/c/XAMPP/php/wp ``` Then, navigate to the new install directory and create a wrapper file called `php`: ``` cd /cygdrive/c/XAMPP/php/wp && touch php && chmod +x ./php ``` Open the file in a text editor and paste the following into it, replacing the path to the PHP executable with your own: ``` #!/bin/bash php="/cygdrive/c/XAMPP/php/php.exe" for ((n=1; n <= $#; n++)); do if [ -e "${!n}" ]; then # Converts Unix style paths to Windows equivalents path="$(cygpath --mixed ${!n} | xargs)" case 1 in $(( n == 1 )) ) set -- "$path" "${@:$(($n+1))}";; $(( n < $# )) ) set -- "${@:1:$((n-1))}" "$path" ${@:$((n+1)):$#};; *) set -- "${@:1:$(($#-1))}" "$path";; esac fi done "$php" "$@" ``` Finally, run `wp` to confirm that WP-CLI - and any other PHP tools requiring a Cygwin wrapper - is now working on Cygwin.
340,698
<p>Hi there could somedoby explain please why <a href="https://www" rel="nofollow noreferrer">https://www</a>. SUBdomain does not redirect to <a href="https://non-www.sudomain" rel="nofollow noreferrer">https://non-www.sudomain</a></p> <p>I am running nginx and seems like set up all the redirects but the one above seem to be redirected wrongly by Wordpress, I have all A records set up 2 for http version of main domain with and without www and two for https records. My config redirects are below. WordPress Address (URL) and Site Address (URL) are set to <a href="https://maindomain" rel="nofollow noreferrer">https://maindomain</a> not sure if this is the issue and how to resolve it</p> <pre><code> #Main domain confing server { server_name domain.club; access_log /var/www/bclub/logs/access.log; error_log /var/www/bclub/logs/error.log; root /var/www/bclub/; index index.php index.html index.htm index.nginx-debian.html; listen [::]:443 ssl http2; # managed by Certbot listen 443 ssl http2; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.club/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.club/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot ssl_trusted_certificate /etc/letsencrypt/live/domain.club/chain.pem; # managed by Certbot ssl_stapling on; # managed by Certbot ssl_stapling_verify on; # managed by Certbot } server { listen 80; server_name domain.club www.domain.club; return 301 https://domain.club$request_uri; } #SUB-domain confing server { server_name cdn.domain.club www.cdn.domain.club; access_log /var/www/cdn.bclub/logs/access.log; error_log /var/www/cdn.bclub/logs/error.log; root /var/www/cdn.bclub; index index.php index.html index.htm index.nginx-debian.html; etag off; listen 443 ssl http2; # managed by Certbot listen [::]:443 ssl http2; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.club/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.club/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot ssl_trusted_certificate /etc/letsencrypt/live/domain.club/chain.pem; # managed by Certbot ssl_stapling on; # managed by Certbot ssl_stapling_verify on; # managed by Certbot } server { listen 80; server_name cdn.domain.club www.cdn.domain.club; return 301 https://cdn.domain.club$request_uri; } </code></pre> <p>Many thanks</p>
[ { "answer_id": 340662, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 2, "selected": false, "text": "<p>There are at least two interesting questions on SO:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/2266661/2199525\">Cygwin and PHPUnit: Could not open input file: /cygdrive/c/xampp/php/phpunit</a></li>\n<li><a href=\"https://stackoverflow.com/q/12276946/2199525\">Composer &amp; Cygwin</a></li>\n</ul>\n\n<p>The easiest seems to be putting an alias into your Cygwin's <code>~/.bashrc</code> or <code>~/.bash_profile</code>:</p>\n\n<pre><code>alias wp=\"/cygdrive/b/Users/User/XAMPP/php/php /cygdrive/b/Users/User/XAMPP/php/wp\"\n</code></pre>\n" }, { "answer_id": 340747, "author": "Hashim Aziz", "author_id": 167562, "author_profile": "https://wordpress.stackexchange.com/users/167562", "pm_score": 3, "selected": true, "text": "<p>I finally managed to scrape together enough information from disparate sources to figure out how to fix this, because - as I'm increasingly finding with anything related to Wordpress development - the documentation is so woefully inadequate.</p>\n<p>The fact that it took so much research and hacking together on my part just to get an official command-line utility working on a platform that it claims to support is ridiculous, and my estimation of the Wordpress project and the Automattic team has dropped massively over the last few weeks for such reasons.</p>\n<p>What follows in this answer adapts information from <a href=\"https://stackoverflow.com/questions/12276946/composer-cygwin/14904607#14904607\">aefxx's answer here</a> and <a href=\"https://wordpress.stackexchange.com/a/340662/167562\">leymannx's answer</a> to this question.</p>\n<p>As far I can tell, the issue here is that <code>php.exe</code> - the PHP binary included with XAMPP, WAMP and similar local servers - is a Windows binary that only understands paths in Windows format. The solution, as coded by <em>aefxx</em> in his answer, is to use a wrapper script that checks for Unix-style paths passed to the PHP binary and converts them into Windows paths that it can understand.</p>\n<p>Note that because this solution is implemented as a wrapper to the PHP binary itself, it should work to solve this issue for any PHP program running under Cygwin, not just WP-CLI.</p>\n<h2>How to get WP-CLI working with Cygwin</h2>\n<p><strong>Remember to replace any paths below with your own.</strong></p>\n<p>Once you've downloaded the <code>wp-cli.phar</code> file and made it executable <a href=\"https://wp-cli.org/#install\" rel=\"nofollow noreferrer\">as detailed in the documentation</a>, move it to where you want to install it - <code>/usr/local/bin</code> tends to be the convention for user-installed binaries on Linux, or inside of XAMPP's PHP server root if you're using XAMPP - and rename it to something easier to type, like <code>wp</code>:</p>\n<pre><code>mv wp-cli.phar /cygdrive/c/XAMPP/php/wp\n</code></pre>\n<p>Then, navigate to the new install directory and create a wrapper file called <code>php</code>:</p>\n<pre><code>cd /cygdrive/c/XAMPP/php/wp &amp;&amp;\ntouch php &amp;&amp;\nchmod +x ./php\n</code></pre>\n<p>Open the file in a text editor and paste the following into it, replacing the path to the PHP executable with your own:</p>\n<pre><code>#!/bin/bash\n\nphp=&quot;/cygdrive/c/XAMPP/php/php.exe&quot;\n\nfor ((n=1; n &lt;= $#; n++)); do\n if [ -e &quot;${!n}&quot; ]; then\n # Converts Unix style paths to Windows equivalents\n path=&quot;$(cygpath --mixed ${!n} | xargs)&quot;\n\n case 1 in\n $(( n == 1 )) )\n set -- &quot;$path&quot; &quot;${@:$(($n+1))}&quot;;;\n $(( n &lt; $# )) )\n set -- &quot;${@:1:$((n-1))}&quot; &quot;$path&quot; ${@:$((n+1)):$#};;\n *)\n set -- &quot;${@:1:$(($#-1))}&quot; &quot;$path&quot;;;\n esac\n fi\ndone\n\n&quot;$php&quot; &quot;$@&quot;\n</code></pre>\n<p>Finally, run <code>wp</code> to confirm that WP-CLI - and any other PHP tools requiring a Cygwin wrapper - is now working on Cygwin.</p>\n" } ]
2019/06/17
[ "https://wordpress.stackexchange.com/questions/340698", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130477/" ]
Hi there could somedoby explain please why <https://www>. SUBdomain does not redirect to <https://non-www.sudomain> I am running nginx and seems like set up all the redirects but the one above seem to be redirected wrongly by Wordpress, I have all A records set up 2 for http version of main domain with and without www and two for https records. My config redirects are below. WordPress Address (URL) and Site Address (URL) are set to <https://maindomain> not sure if this is the issue and how to resolve it ``` #Main domain confing server { server_name domain.club; access_log /var/www/bclub/logs/access.log; error_log /var/www/bclub/logs/error.log; root /var/www/bclub/; index index.php index.html index.htm index.nginx-debian.html; listen [::]:443 ssl http2; # managed by Certbot listen 443 ssl http2; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.club/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.club/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot ssl_trusted_certificate /etc/letsencrypt/live/domain.club/chain.pem; # managed by Certbot ssl_stapling on; # managed by Certbot ssl_stapling_verify on; # managed by Certbot } server { listen 80; server_name domain.club www.domain.club; return 301 https://domain.club$request_uri; } #SUB-domain confing server { server_name cdn.domain.club www.cdn.domain.club; access_log /var/www/cdn.bclub/logs/access.log; error_log /var/www/cdn.bclub/logs/error.log; root /var/www/cdn.bclub; index index.php index.html index.htm index.nginx-debian.html; etag off; listen 443 ssl http2; # managed by Certbot listen [::]:443 ssl http2; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.club/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.club/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot ssl_trusted_certificate /etc/letsencrypt/live/domain.club/chain.pem; # managed by Certbot ssl_stapling on; # managed by Certbot ssl_stapling_verify on; # managed by Certbot } server { listen 80; server_name cdn.domain.club www.cdn.domain.club; return 301 https://cdn.domain.club$request_uri; } ``` Many thanks
I finally managed to scrape together enough information from disparate sources to figure out how to fix this, because - as I'm increasingly finding with anything related to Wordpress development - the documentation is so woefully inadequate. The fact that it took so much research and hacking together on my part just to get an official command-line utility working on a platform that it claims to support is ridiculous, and my estimation of the Wordpress project and the Automattic team has dropped massively over the last few weeks for such reasons. What follows in this answer adapts information from [aefxx's answer here](https://stackoverflow.com/questions/12276946/composer-cygwin/14904607#14904607) and [leymannx's answer](https://wordpress.stackexchange.com/a/340662/167562) to this question. As far I can tell, the issue here is that `php.exe` - the PHP binary included with XAMPP, WAMP and similar local servers - is a Windows binary that only understands paths in Windows format. The solution, as coded by *aefxx* in his answer, is to use a wrapper script that checks for Unix-style paths passed to the PHP binary and converts them into Windows paths that it can understand. Note that because this solution is implemented as a wrapper to the PHP binary itself, it should work to solve this issue for any PHP program running under Cygwin, not just WP-CLI. How to get WP-CLI working with Cygwin ------------------------------------- **Remember to replace any paths below with your own.** Once you've downloaded the `wp-cli.phar` file and made it executable [as detailed in the documentation](https://wp-cli.org/#install), move it to where you want to install it - `/usr/local/bin` tends to be the convention for user-installed binaries on Linux, or inside of XAMPP's PHP server root if you're using XAMPP - and rename it to something easier to type, like `wp`: ``` mv wp-cli.phar /cygdrive/c/XAMPP/php/wp ``` Then, navigate to the new install directory and create a wrapper file called `php`: ``` cd /cygdrive/c/XAMPP/php/wp && touch php && chmod +x ./php ``` Open the file in a text editor and paste the following into it, replacing the path to the PHP executable with your own: ``` #!/bin/bash php="/cygdrive/c/XAMPP/php/php.exe" for ((n=1; n <= $#; n++)); do if [ -e "${!n}" ]; then # Converts Unix style paths to Windows equivalents path="$(cygpath --mixed ${!n} | xargs)" case 1 in $(( n == 1 )) ) set -- "$path" "${@:$(($n+1))}";; $(( n < $# )) ) set -- "${@:1:$((n-1))}" "$path" ${@:$((n+1)):$#};; *) set -- "${@:1:$(($#-1))}" "$path";; esac fi done "$php" "$@" ``` Finally, run `wp` to confirm that WP-CLI - and any other PHP tools requiring a Cygwin wrapper - is now working on Cygwin.
340,718
<p>I try to get gutenberg media gallery block output, and want to use default figcaption text feature for images titles (for js lightbox). How can i get this property figcaption text value?</p> <pre><code>add_filter( 'render_block', function( $block_content, $block ) { if ( 'core/gallery' !== $block['blockName'] || ! isset( $block['attrs']['ids'] ) ) { return $block_content; } $li = ''; foreach( (array) $block['attrs']['ids'] as $id ) { $li .= sprintf( '&lt;li&gt;&lt;a href="%s" data-lightbox="photo" data-title="%s"&gt;&lt;img src="%s" class="w-100"&gt;&lt;/a&gt;&lt;/li&gt;', wp_get_attachment_image_src( $id, '' )[0], 'FIGCAPTION TEXT', wp_get_attachment_image_src( $id, 'thumbnail' )[0] ); } return sprintf( '&lt;ul id="gallery-grid"&gt;%s&lt;/ul&gt;', $li ); }, 10, 2 ); </code></pre>
[ { "answer_id": 340740, "author": "Vortac", "author_id": 167651, "author_profile": "https://wordpress.stackexchange.com/users/167651", "pm_score": 0, "selected": false, "text": "<p>Try <code>wp_get_attachment_caption( $id )</code> for caption and <code>get_post_meta( $id, '_wp_attachment_image_alt', true )</code> for alt-text</p>\n" }, { "answer_id": 340807, "author": "Vortac", "author_id": 167651, "author_profile": "https://wordpress.stackexchange.com/users/167651", "pm_score": 1, "selected": false, "text": "<p>You’re right...the figcaptions are encoded as html in <code>$block['innerHTML']</code>. You could do sth. like <code>$tmpArray = explode('&lt;/li&gt;',$block['innerHTML']);</code> before your <code>foreach</code> loop to split the HTML string into an array that matches your gallery items and inside the loop <code>strip_tags($tmpArray[i]);</code> to strip away all html tags and only get the text string inside <code>&lt;figcaption&gt;&lt;/figcaption&gt;</code>. You’ll only need to add a counter <code>i</code> to your loop to have an index for the <code>$tmpArray</code>.</p>\n" } ]
2019/06/17
[ "https://wordpress.stackexchange.com/questions/340718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/169787/" ]
I try to get gutenberg media gallery block output, and want to use default figcaption text feature for images titles (for js lightbox). How can i get this property figcaption text value? ``` add_filter( 'render_block', function( $block_content, $block ) { if ( 'core/gallery' !== $block['blockName'] || ! isset( $block['attrs']['ids'] ) ) { return $block_content; } $li = ''; foreach( (array) $block['attrs']['ids'] as $id ) { $li .= sprintf( '<li><a href="%s" data-lightbox="photo" data-title="%s"><img src="%s" class="w-100"></a></li>', wp_get_attachment_image_src( $id, '' )[0], 'FIGCAPTION TEXT', wp_get_attachment_image_src( $id, 'thumbnail' )[0] ); } return sprintf( '<ul id="gallery-grid">%s</ul>', $li ); }, 10, 2 ); ```
You’re right...the figcaptions are encoded as html in `$block['innerHTML']`. You could do sth. like `$tmpArray = explode('</li>',$block['innerHTML']);` before your `foreach` loop to split the HTML string into an array that matches your gallery items and inside the loop `strip_tags($tmpArray[i]);` to strip away all html tags and only get the text string inside `<figcaption></figcaption>`. You’ll only need to add a counter `i` to your loop to have an index for the `$tmpArray`.
340,731
<p>The link <a href="https://vreqenz-stream.de/shop/" rel="nofollow noreferrer">https://vreqenz-stream.de/shop/</a> throws warning when opened on some devices and not on others. <br> I thought it may be a cahce issue but I have cleared cache from WP-rocket and also browser. Just for the info I am using Plesk web admin tool.<br> Below is my WP_Config settings</p> <pre><code>ini_set('log_errors','On'); ini_set('display_errors','Off'); ini_set('error_reporting', E_ALL ); define('WP_DEBUG', false); define('WP_DEBUG_LOG', true); define('WP_DEBUG_DISPLAY', false); </code></pre> <p><a href="https://i.stack.imgur.com/lO9rz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lO9rz.jpg" alt="Site snipshot with warning on top"></a></p>
[ { "answer_id": 340734, "author": "Ilona", "author_id": 136877, "author_profile": "https://wordpress.stackexchange.com/users/136877", "pm_score": 0, "selected": false, "text": "<p>Try checking your php.ini file. display_errors may be turned on there and it might be overriding your wp_config file.</p>\n" }, { "answer_id": 340737, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>There are two constants causing the error: <code>WP_MEMORY_LIMIT</code> and <code>WP_MAX_MEMORY_LIMIT</code> , according to the error message I see. </p>\n\n<p>Constants are just that -- '<strong>constant</strong>'. They can only be defined once. Once defined, you can't change them. (Cause if you changed them, they wouldn't be 'constant'.)</p>\n\n<p>Check your <code>wp-config.php</code> file first for duplicate definitions of those. Then check your theme's files (functions.php first, other files next), and plugin files for 'extra' <code>DEFINES</code> of those constants. </p>\n\n<p><strong>Added</strong></p>\n\n<p>For instance:</p>\n\n<pre><code>DEFINE ($myconstant,\"the value\");\necho $myconstant; // this is ok\n$myconstant = 'new value'; // this will cause an 'already defined' error\n</code></pre>\n\n<p>One DEFINE for a constant. Use it any way you want, but don't change it. </p>\n" }, { "answer_id": 340741, "author": "Svetoslav Marinov", "author_id": 26487, "author_profile": "https://wordpress.stackexchange.com/users/26487", "pm_score": 0, "selected": false, "text": "<p>Some plugins authors turn on error displaying due to inexperience.\nTry searching for this exact string in wp-content folder.</p>\n\n<pre><code>'error_reporting('\n</code></pre>\n" }, { "answer_id": 340764, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>The <code>WP_DEBUG</code> setting only takes effect when <code>/wp-includes/default-constants.php</code> is loaded.</p>\n\n<p>You are seeing these errors because they are occurring <em>before</em> that, ie. in <code>wp-config.php</code>... (which loads <code>wp-settings.php</code> which then consequently loads <code>/wp-includes/default-constants.php</code>)</p>\n\n<p>If you want to use define constants multiple times without warnings you would need to check if they are already defined first:</p>\n\n<pre><code>if ( !defined( 'WP_MEMORY_LIMIT' ) ) {define( 'WP_MEMORY_LIMIT', '128M' ); }\n</code></pre>\n\n<p>Of course only the first definition will be in effect, but this way you won't get the warnings and you can use this to allow for multiple fallback conditions.</p>\n\n<p>But your solution is probably just to simply to check for and remove the multiple definitions, as it's doesn't sound like you are trying to do something more complex like this.</p>\n" }, { "answer_id": 340795, "author": "veetrag", "author_id": 170150, "author_profile": "https://wordpress.stackexchange.com/users/170150", "pm_score": 1, "selected": false, "text": "<p>Thanks all of you for your response the issue got resolved. The problem was with cached copy of this link <a href=\"https://vreqenz-stream.de/shop/\" rel=\"nofollow noreferrer\">https://vreqenz-stream.de/shop/</a> . I had WP Rocket for caching and apparently it is not doing very good job of purging the cache. \nI got sure that it is cache issue when I defined the WP_CACHE as false which was true earlier and the warnings disappeared. </p>\n" } ]
2019/06/17
[ "https://wordpress.stackexchange.com/questions/340731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170150/" ]
The link <https://vreqenz-stream.de/shop/> throws warning when opened on some devices and not on others. I thought it may be a cahce issue but I have cleared cache from WP-rocket and also browser. Just for the info I am using Plesk web admin tool. Below is my WP\_Config settings ``` ini_set('log_errors','On'); ini_set('display_errors','Off'); ini_set('error_reporting', E_ALL ); define('WP_DEBUG', false); define('WP_DEBUG_LOG', true); define('WP_DEBUG_DISPLAY', false); ``` [![Site snipshot with warning on top](https://i.stack.imgur.com/lO9rz.jpg)](https://i.stack.imgur.com/lO9rz.jpg)
Thanks all of you for your response the issue got resolved. The problem was with cached copy of this link <https://vreqenz-stream.de/shop/> . I had WP Rocket for caching and apparently it is not doing very good job of purging the cache. I got sure that it is cache issue when I defined the WP\_CACHE as false which was true earlier and the warnings disappeared.
340,759
<p>I have created a table in which i have delete link something like <a href="http://localhost/wptheme/wp-admin/admin.php?page=batch-op-settings&amp;action=batch-delete&amp;post_id=5" rel="nofollow noreferrer">http://localhost/wptheme/wp-admin/admin.php?page=batch-op-settings&amp;action=batch-delete&amp;post_id=5</a> and i have added a code to delete the post </p> <pre><code>if ($action == 'batch-delete') { require_once (plugin_dir_path( __FILE__ ).'views/single_batch_delete.php'); } </code></pre> <p>code in the required file is </p> <pre><code>if (isset($_GET['action']) == 'batch-delete') { global $wpdb; $delete_batch = $wpdb-&gt;delete( 'batch_number', array( 'id'=&gt;$_GET['post_id'] ) ); wp_redirect( $_SERVER['PHP_SELF'].'?page="batch-op-settings"', 302, 'Deleted' ); } </code></pre> <p>the data row is deleted but it is not redirecting to the all batches code all data i have used wp_redirect function i have also used header() function but it shows this error </p> <blockquote> <p>Warning: Cannot modify header information - headers already sent</p> </blockquote> <p>I want to know is there any better way to handle this issue or any solution with the current code .</p>
[ { "answer_id": 340834, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 2, "selected": true, "text": "<p>Parcel is intended to be used to build apps from the ground up. That's why they recommend starting with a index.js or index.html file. </p>\n\n<p>You might be able to use Parcel's packaging for a theme or plugin, but you would lose the built-in server and live reloading (\"hot module replacement\") among other things. There may be more that wouldn't work. </p>\n\n<p>I don't think Parcel is a good fit for WordPress development. <a href=\"https://github.com/parcel-bundler/parcel/issues/262\" rel=\"nofollow noreferrer\">Read more</a>.</p>\n" }, { "answer_id": 366843, "author": "rassoh", "author_id": 18713, "author_profile": "https://wordpress.stackexchange.com/users/18713", "pm_score": 3, "selected": false, "text": "<p>Since 2018, I have been developing all my WordPress themes with parcel. It does accept javascript files as an entry points (or even <a href=\"https://parceljs.org/getting_started.html#multiple-entry-files\" rel=\"noreferrer\">multiple of entry files</a>). In your console:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$ parcel ./path/to/your-theme-script.js\n</code></pre>\n\n<p>...or for development:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$ parcel watch ./path/to/your-theme-script.js\n</code></pre>\n\n<p>...import your styles in your main file like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>import './scss/app.scss';\n</code></pre>\n\n<p>...for watching other theme files like <code>.php</code> or <code>.json</code>, you can use <a href=\"https://www.npmjs.com/package/parcel-plugin-watch-reload\" rel=\"noreferrer\">parcel-plugin-watch-reload</a>.</p>\n" } ]
2019/06/18
[ "https://wordpress.stackexchange.com/questions/340759", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151182/" ]
I have created a table in which i have delete link something like <http://localhost/wptheme/wp-admin/admin.php?page=batch-op-settings&action=batch-delete&post_id=5> and i have added a code to delete the post ``` if ($action == 'batch-delete') { require_once (plugin_dir_path( __FILE__ ).'views/single_batch_delete.php'); } ``` code in the required file is ``` if (isset($_GET['action']) == 'batch-delete') { global $wpdb; $delete_batch = $wpdb->delete( 'batch_number', array( 'id'=>$_GET['post_id'] ) ); wp_redirect( $_SERVER['PHP_SELF'].'?page="batch-op-settings"', 302, 'Deleted' ); } ``` the data row is deleted but it is not redirecting to the all batches code all data i have used wp\_redirect function i have also used header() function but it shows this error > > Warning: Cannot modify header information - headers already sent > > > I want to know is there any better way to handle this issue or any solution with the current code .
Parcel is intended to be used to build apps from the ground up. That's why they recommend starting with a index.js or index.html file. You might be able to use Parcel's packaging for a theme or plugin, but you would lose the built-in server and live reloading ("hot module replacement") among other things. There may be more that wouldn't work. I don't think Parcel is a good fit for WordPress development. [Read more](https://github.com/parcel-bundler/parcel/issues/262).
340,767
<p>Is it possible to some how make my plugin dequeue / deregister any styles and any scripts from what ever theme activated. so it doesn't matter what theme will be installed the styles and scripts of that theme will be dequeue / deregister?</p> <p>Just to be super clear:</p> <ol> <li>I don't know what theme will be used.</li> <li>I need to dequeue / deregister only the styles and scripts from the theme and not from other plugins.</li> </ol>
[ { "answer_id": 340768, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 1, "selected": false, "text": "<p>May be this will helps you. try </p>\n\n<pre><code>#For dequeue JavaScripts\nfunction remove_unnecessary_scripts() {\n # pass Name of the enqueued js.\n # dequeue js\n wp_dequeue_script( 'toaster-js' );\n # deregister js\n wp_deregister_script( 'toaster-js' );\n}\nadd_action( 'wp_print_scripts', 'remove_unnecessary_scripts' );\n\n#For dequeue Styles \nfunction remove_unnecessary_styles() {\n # pass Name of the enqueued stylesheet.\n # dequeue style\n wp_dequeue_style( 'custom-style' );\n # deregister style\n wp_deregister_style( 'custom-style' );\n}\nadd_action( 'wp_print_styles', 'remove_unnecessary_styles' );\n</code></pre>\n\n<p>For Remove only themes styles and scripts you can try below :</p>\n\n<pre><code>function remove_all_scripts_from_theme() {\n global $wp_scripts;\n # remove all js\n // $wp_scripts-&gt;queue = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n\n if (strpos($wp_scripts-&gt;registered[$handle]-&gt;src, '/themes/') !== false) {\n # dequeue js\n wp_dequeue_script( $handle );\n # deregister js\n wp_deregister_script( $handle);\n }\n }\n\n}\nadd_action('wp_print_scripts', 'remove_all_scripts_from_theme', 100);\n\nfunction remove_all_styles_from_theme() {\n global $wp_styles;\n # remove all css\n // $wp_styles-&gt;queue = array();\n\n foreach( $wp_styles-&gt;queue as $handle ) {\n\n if (strpos($wp_styles-&gt;registered[$handle]-&gt;src, '/themes/') !== false) {\n # dequeue js\n wp_dequeue_style( $handle );\n # deregister js\n wp_deregister_style( $handle);\n }\n }\n\n}\nadd_action('wp_print_styles', 'remove_all_styles_from_theme', 100);\n</code></pre>\n\n<p>let me know if it works or not. i have tested this code. it is works like charms :-)</p>\n\n<p>Thank you!</p>\n" }, { "answer_id": 340769, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": -1, "selected": false, "text": "<p>You can use wp_print_scripts to remove scripts and styles enqueued from plugins or parent theme. Please see the demo code:</p>\n\n<pre><code>/**\n * Dequeue the Parent Theme and Plugins scripts and styles\n */\nfunction custom_dequeue_script() {\n wp_dequeue_script( 'script-handle' );\n wp_dequeue_style('script-handle');\n wp_deregister_style('script-handle');\n}\n\nadd_action( 'wp_print_scripts', 'custom_dequeue_script', 100 );\n</code></pre>\n\n<p>Please try this new code to remove scripts and styles from activated theme:</p>\n\n<pre><code>function remove_theme_all_scripts() {\nglobal $wp_scripts;\n\n$stylesheet_uri = get_stylesheet_directory_uri();\n$new_scripts_list = array(); \n\nforeach( $wp_scripts-&gt;queue as $handle ) {\n $obj = $wp_scripts-&gt;registered[$handle];\n $obj_handle = $obj-&gt;handle;\n $obj_uri = $obj-&gt;src;\n\n if ( strpos( $obj_uri, $stylesheet_uri ) === 0 ) {\n //Do Nothing\n } else {\n $new_scripts_list[] = $obj_handle;\n }\n}\n\n$wp_scripts-&gt;queue = $new_scripts_list;\n}\nadd_action('wp_print_scripts', 'remove_theme_all_scripts', 100);\n\nfunction remove_theme_all_styles() {\nglobal $wp_styles;\n$stylesheet_uri = get_stylesheet_directory_uri();\n$new_styles_list = array(); \n\nforeach( $wp_styles-&gt;queue as $handle ) {\n $obj = $wp_styles-&gt;registered[$handle];\n $obj_handle = $obj-&gt;handle;\n $obj_uri = $obj-&gt;src;\n\n if ( strpos( $obj_uri, $stylesheet_uri ) === 0 ) {\n //Do Nothing\n } else {\n $new_styles_list[] = $obj_handle;\n }\n}\n\n$wp_styles-&gt;queue = $new_styles_list;\n}\nadd_action('wp_print_styles', 'remove_theme_all_styles', 100);\n</code></pre>\n" }, { "answer_id": 340770, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>The tricky thing is knowing whether or not a particular script or style was enqueued by the theme. </p>\n\n<p>Themes and plugins both use the same hooks and functions, so they're not explicitly labelled in any way as belonging to a specific theme or plugin. This means that the only way to know whether a script or style is from the theme is to check the URL to see whether the the script/style's URL is pointing to somewhere in the theme directory.</p>\n\n<p>One way you can do this is to loop over <code>$wp_scripts-&gt;registered</code> and <code>$wp_styles-&gt;registered</code>, and check the URL of each script and style against <code>get_theme_root_uri()</code> which tells you the URL to the themes folder. If the script/style appears to be inside that folder, you can dequeue it:</p>\n\n<pre><code>function wpse_340767_dequeue_theme_assets() {\n $wp_scripts = wp_scripts();\n $wp_styles = wp_styles();\n $themes_uri = get_theme_root_uri();\n\n foreach ( $wp_scripts-&gt;registered as $wp_script ) {\n if ( strpos( $wp_script-&gt;src, $themes_uri ) !== false ) {\n wp_deregister_script( $wp_script-&gt;handle );\n }\n }\n\n foreach ( $wp_styles-&gt;registered as $wp_style ) {\n if ( strpos( $wp_style-&gt;src, $themes_uri ) !== false ) {\n wp_deregister_style( $wp_style-&gt;handle );\n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_340767_dequeue_theme_assets', 999 );\n</code></pre>\n\n<p>This will only work if the stylesheet or script is inside the theme. If the theme is enqueueing scripts or styles from a CDN, then I'm not sure if it's possible to target those.</p>\n" }, { "answer_id": 384489, "author": "hayatbiralem", "author_id": 57693, "author_profile": "https://wordpress.stackexchange.com/users/57693", "pm_score": 0, "selected": false, "text": "<p>If there is no theme, the theme's function.php will never run so this should work as expected:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function myprefix_disable_theme_load() {\n return &quot;&quot;;\n}\nadd_filter(&quot;template_directory&quot;, &quot;myprefix_disable_theme_load&quot;, 1, 0);\nadd_filter(&quot;stylesheet_directory&quot;, &quot;myprefix_disable_theme_load&quot;, 1, 0);\n</code></pre>\n<p>But be aware of this remove all functionality from the theme which we want in this case.</p>\n" } ]
2019/06/18
[ "https://wordpress.stackexchange.com/questions/340767", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159259/" ]
Is it possible to some how make my plugin dequeue / deregister any styles and any scripts from what ever theme activated. so it doesn't matter what theme will be installed the styles and scripts of that theme will be dequeue / deregister? Just to be super clear: 1. I don't know what theme will be used. 2. I need to dequeue / deregister only the styles and scripts from the theme and not from other plugins.
The tricky thing is knowing whether or not a particular script or style was enqueued by the theme. Themes and plugins both use the same hooks and functions, so they're not explicitly labelled in any way as belonging to a specific theme or plugin. This means that the only way to know whether a script or style is from the theme is to check the URL to see whether the the script/style's URL is pointing to somewhere in the theme directory. One way you can do this is to loop over `$wp_scripts->registered` and `$wp_styles->registered`, and check the URL of each script and style against `get_theme_root_uri()` which tells you the URL to the themes folder. If the script/style appears to be inside that folder, you can dequeue it: ``` function wpse_340767_dequeue_theme_assets() { $wp_scripts = wp_scripts(); $wp_styles = wp_styles(); $themes_uri = get_theme_root_uri(); foreach ( $wp_scripts->registered as $wp_script ) { if ( strpos( $wp_script->src, $themes_uri ) !== false ) { wp_deregister_script( $wp_script->handle ); } } foreach ( $wp_styles->registered as $wp_style ) { if ( strpos( $wp_style->src, $themes_uri ) !== false ) { wp_deregister_style( $wp_style->handle ); } } } add_action( 'wp_enqueue_scripts', 'wpse_340767_dequeue_theme_assets', 999 ); ``` This will only work if the stylesheet or script is inside the theme. If the theme is enqueueing scripts or styles from a CDN, then I'm not sure if it's possible to target those.
340,814
<p>I need a list of every shortcode inside the content. Is there any way to list them?</p> <p>This is what I need:</p> <pre><code>$str = '[term value="Value" id="600"][term value="Term" id="609"]'; </code></pre> <p>So every shortcode should be inside the <code>$str</code>.</p> <p>I found a code snippet to check if there is a shortcode. But how can I display them all?</p> <pre><code>$content = 'This is some text, (perhaps pulled via $post-&gt;post_content). It has a [gallery] shortcode.'; if( has_shortcode( $content, 'gallery' ) ) { // The content has a [gallery] short code, so this check returned true. } </code></pre>
[ { "answer_id": 340817, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>If you only need the Shortcodes without the attributes, you can use this function:</p>\n\n<pre><code>function get_used_shortcodes( $content) {\n global $shortcode_tags;\n if ( false === strpos( $content, '[' ) ) {\n return array();\n }\n if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {\n return array();\n }\n // Find all registered tag names in $content.\n preg_match_all( '@\\[([^&lt;&gt;&amp;/\\[\\]\\x00-\\x20=]++)@', $content, $matches );\n $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );\n return $tagnames;\n}\n</code></pre>\n\n<p>You will get an array of all shortcodes, that are used within the content you give it.</p>\n" }, { "answer_id": 340819, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Here's one way:</p>\n\n<p>You can look at <a href=\"https://developer.wordpress.org/reference/functions/has_shortcode/\" rel=\"nofollow noreferrer\">has_shortcode()</a> and find the parsing there:</p>\n\n<pre><code>preg_match_all( \n '/' . get_shortcode_regex() . '/', \n $content, \n $matches, \n PREG_SET_ORDER\n);\n</code></pre>\n\n<p>using the <a href=\"https://developer.wordpress.org/reference/functions/get_shortcode_regex/\" rel=\"nofollow noreferrer\">get_shortcode_regex()</a> function for the regex pattern.</p>\n\n<p>For non empty matches, you can then loop through them and collect the full shortcode matches with:</p>\n\n<pre><code>$shortcodes = [];\nforeach( $matches as $shortcode ) {\n $shortcodes[] = $shortcode[0];\n}\n</code></pre>\n\n<p>Finally you format the output to your needs, e.g.:</p>\n\n<pre><code>echo join( '', $shortcodes );\n</code></pre>\n\n<p>PS: It can be handy to wrap this into your custom function.</p>\n" }, { "answer_id": 402483, "author": "Ian", "author_id": 101226, "author_profile": "https://wordpress.stackexchange.com/users/101226", "pm_score": 1, "selected": false, "text": "<p>Love @birgire's accepted answer, but a limitation of it is that any nested shortcodes are missed. You can overcome this by creating a simple walker:</p>\n<pre><code>function all_shortcodes($content) {\n $return = array();\n\n preg_match_all(\n '/' . get_shortcode_regex() . '/',\n $content,\n $shortcodes,\n PREG_SET_ORDER\n );\n\n if (!empty($shortcodes)) {\n foreach ($shortcodes as $shortcode) {\n $return[] = $shortcode;\n $return = array_merge($return, all_shortcodes($shortcode[5]));\n }\n }\n return $return;\n}\n\n$shortcodes_including_nested = all_shortcodes($post_content);\n</code></pre>\n" } ]
2019/06/18
[ "https://wordpress.stackexchange.com/questions/340814", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96806/" ]
I need a list of every shortcode inside the content. Is there any way to list them? This is what I need: ``` $str = '[term value="Value" id="600"][term value="Term" id="609"]'; ``` So every shortcode should be inside the `$str`. I found a code snippet to check if there is a shortcode. But how can I display them all? ``` $content = 'This is some text, (perhaps pulled via $post->post_content). It has a [gallery] shortcode.'; if( has_shortcode( $content, 'gallery' ) ) { // The content has a [gallery] short code, so this check returned true. } ```
Here's one way: You can look at [has\_shortcode()](https://developer.wordpress.org/reference/functions/has_shortcode/) and find the parsing there: ``` preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER ); ``` using the [get\_shortcode\_regex()](https://developer.wordpress.org/reference/functions/get_shortcode_regex/) function for the regex pattern. For non empty matches, you can then loop through them and collect the full shortcode matches with: ``` $shortcodes = []; foreach( $matches as $shortcode ) { $shortcodes[] = $shortcode[0]; } ``` Finally you format the output to your needs, e.g.: ``` echo join( '', $shortcodes ); ``` PS: It can be handy to wrap this into your custom function.
340,829
<p>I need to add a link to the drop-down user menu in the admin bar. Is there a hook or function for this?</p> <p><a href="https://i.stack.imgur.com/JZA97.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JZA97.png" alt="WP admin bar user drop-down menu"></a></p>
[ { "answer_id": 340830, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 3, "selected": true, "text": "<p>You want to use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Admin_Bar/add_node\" rel=\"nofollow noreferrer\">$wp_admin_bar->add_node( $args )</a>. </p>\n\n<p>Below is a tested working example.</p>\n\n<pre><code>function wpse_add_toolbar_edit($wp_admin_bar) { \n $wp_admin_bar-&gt;add_node( array(\n 'id' =&gt; 'mylink',\n 'title' =&gt; 'My New Link',\n 'href' =&gt; 'mailto:[email protected]',\n 'parent' =&gt; 'user-actions'\n ) );\n}\n\nadd_action('admin_bar_menu', 'wpse_add_toolbar_edit', 999);\n</code></pre>\n\n<p>Note: The <code>parent</code> param adds the link to an existing ID. If you need to find the correct ID to add your new link to you can <code>var_dump($wp_admin_bar);</code> and look through the output for the correct ID.</p>\n" }, { "answer_id": 357596, "author": "Jaskaran Singh", "author_id": 181929, "author_profile": "https://wordpress.stackexchange.com/users/181929", "pm_score": 0, "selected": false, "text": "<p>Follow the steps to add link between logout and edit my profile.<br><br>\n1. remove the default logout node</p>\n\n<pre><code>$wp_admin_bar-&gt;remove_node( 'logout' );\n</code></pre>\n\n<p><br>2.add the link that you want to put between logout and edit my profile.<br></p>\n\n<pre><code>$wp_admin_bar-&gt;add_node([\n 'id' =&gt; 'link-id',\n 'title' =&gt; 'Link Title',\n 'href' =&gt; get_site_url(null, 'site-path'),\n 'parent' =&gt; 'user-actions'\n]);\n</code></pre>\n\n<p><br>3. Add the logout node back to the list using:</p>\n\n<pre><code>$wp_admin_bar-&gt;add_node([\n 'id' =&gt; 'logout',\n 'title' =&gt; 'Log Out',\n 'href' =&gt; wp_logout_url(),\n 'parent' =&gt; 'user-actions'\n]);\n</code></pre>\n\n<p>Just manipulated the above function in order to insert the link between logout and profile.</p>\n\n<p>Final Code:</p>\n\n<pre><code> add_action( 'admin_bar_menu', 'adjust_admin_menu_bar_items' , 999);\n function adjust_admin_menu_bar_items ($wp_admin_bar) {\n $user = wp_get_current_user();\n\n $wp_admin_bar-&gt;add_node([\n 'id' =&gt; 'link-id',\n 'title' =&gt; 'Link Title',\n 'href' =&gt; get_site_url(null, 'site-path'),\n 'parent' =&gt; 'user-actions'\n ]);\n\n $wp_admin_bar-&gt;add_node([\n 'id' =&gt; 'logout',\n 'title' =&gt; 'Log Out',\n 'href' =&gt; wp_logout_url(),\n 'parent' =&gt; 'user-actions'\n ]);\n }\n</code></pre>\n\n<p>Hope this will help. :)</p>\n" } ]
2019/06/18
[ "https://wordpress.stackexchange.com/questions/340829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60726/" ]
I need to add a link to the drop-down user menu in the admin bar. Is there a hook or function for this? [![WP admin bar user drop-down menu](https://i.stack.imgur.com/JZA97.png)](https://i.stack.imgur.com/JZA97.png)
You want to use [$wp\_admin\_bar->add\_node( $args )](https://codex.wordpress.org/Class_Reference/WP_Admin_Bar/add_node). Below is a tested working example. ``` function wpse_add_toolbar_edit($wp_admin_bar) { $wp_admin_bar->add_node( array( 'id' => 'mylink', 'title' => 'My New Link', 'href' => 'mailto:[email protected]', 'parent' => 'user-actions' ) ); } add_action('admin_bar_menu', 'wpse_add_toolbar_edit', 999); ``` Note: The `parent` param adds the link to an existing ID. If you need to find the correct ID to add your new link to you can `var_dump($wp_admin_bar);` and look through the output for the correct ID.
340,871
<p>I'm creating a custom form for a wordpress page, and I'm using admin-post.php as my action. However, whenever I try to submit the form, I get a 404.</p> <p>Below is the code which outputs the form:</p> <pre><code>function output_email_verification() { $error = ''; if(isset($_COOKIE['rguroo_form_error'])) { $error = $_COOKIE['rguroo_form_error']; unset($_COOKIE['rguroo_form_error']); } return '&lt;form action='.esc_url( admin_url("admin-post.php") ).'method="post"&gt; &lt;p class="error"&gt;'.$error.'&lt;/p&gt; &lt;input type="radio" label="Purchase 12 months access" value="purchase" name="rguroo_desired_action" checked&gt;Purchase 12 months access&lt;/input&gt; &lt;input type="radio" label="Renew account" name="rguroo_desired_action" value="renewal"&gt;Renew account&lt;/input&gt; &lt;input type="radio" label="Create trial account" name="rguroo_desired_action" value="trial"&gt;Create trial account&lt;/input&gt; &lt;p class="form-subtext"&gt;* indicates required field&lt;/p&gt; &lt;p&gt;Email address*&lt;/p&gt; &lt;input type="text" name="rguroo_email" required&gt; &lt;p&gt;Re-type email address*&lt;/p&gt; &lt;input type="text" name="rguroo_email_confirmation" required&gt; &lt;input type="hidden" name="action" value="rguroo_email_verification_form"&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt;'; } </code></pre> <p>This is the action that I've hooked onto admin-post.php</p> <pre><code>add_action( 'admin_post_nopriv_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); add_action( 'admin_post_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); // Email verification callback function verify_and_sanitize_email_form() { if(empty($_POST) || !isset($_POST['rguroo_email']) || !isset($_POST['rguroo_email_confirmation']) || !isset($_POST['rguroo_desired_action'])) { send_form_error('There is one or more empty fields'); return; } $sanitized_email = sanitize_email( esc_html($_POST['rguroo_email'] )); $sanitized_email_confirmation = sanitize_email( esc_html($_POST['rguroo_email_confirmation'] )); $desired_action = esc_html($_POST['rguroo_desired_action']); if(!is_email( $sanitized_email ) || !is_email( $sanitized_email_confirmation )) { send_form_error('Email is not valid'); return; } if($sanitized_email !== $sanitized_email_confirmation) { send_form_error('Emails do not match'); return; } if($desired_action !== 'purchase' || $desired_action !== 'renewal' || $desired_action !== 'trial') { send_form_error('Fatal error with radio buttons'); return; } if(!isset($_COOKIE['rguroo_form_type'])) { send_form_error('Server error'); return; } // student email verification logic $form_type = $_COOKIE['rguroo_form_type']; if($form_type === 'student') { $trail = substr($sanitized_email, -4); if($trail !== '.edu') { send_form_error('Not a valid student email'); return; } // Other university specific logic here } setcookie('rguroo_form_action',$desired_action, 14 * DAY_IN_SECONDS); setcookie('rguroo_form_email', $sanitized_email, 14 * DAY_IN_SECONDS); } // Helper. Used to output an error function send_form_error($msg) { setcookie('rguroo_form_error', $msg, 14 * DAY_IN_SECONDS); } </code></pre> <p>Sorry about the mess of error validation.</p> <p>Any ideas?</p>
[ { "answer_id": 340873, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>First of all...</p>\n\n<p>Your <code>action</code> is called <code>rguroo_email_verification_form</code>, so you should use it when registering your hooks. But you use this instead:</p>\n\n<pre><code>add_action( 'admin_post_nopriv_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\nadd_action( 'admin_post_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\n</code></pre>\n\n<p>It should be:</p>\n\n<pre><code>add_action( 'admin_post_nopriv_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\nadd_action( 'admin_post_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\n</code></pre>\n\n<p>Also... These actions don't take any params, but you declare they should take one param (but later on, your function doesn't take any...)</p>\n" }, { "answer_id": 340949, "author": "Eli", "author_id": 153230, "author_profile": "https://wordpress.stackexchange.com/users/153230", "pm_score": 0, "selected": false, "text": "<p>As pointed out by Krzysiek, there was an inconsistency between the action field in the form and the admin-post hook.</p>\n\n<p>That being said, the real source the issue and the cause of the 404 was a formatting error.</p>\n\n<pre><code>&lt;form action='.esc_url( admin_url(\"admin-post.php\") ).'method=\"post\"&gt;\n</code></pre>\n\n<p>Was outputting</p>\n\n<pre><code>&lt;form action=\"https://rguroo.com/wp-admin/admin-post.phpmethod=post\"&gt;\n</code></pre>\n\n<p>The correct tag was as follows:</p>\n\n<pre><code>&lt;form action=\"'.esc_url( admin_url(\"admin-post.php\") ).'\" method=\"post\"&gt;\n</code></pre>\n\n<p>I'm an idiot...</p>\n" } ]
2019/06/19
[ "https://wordpress.stackexchange.com/questions/340871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153230/" ]
I'm creating a custom form for a wordpress page, and I'm using admin-post.php as my action. However, whenever I try to submit the form, I get a 404. Below is the code which outputs the form: ``` function output_email_verification() { $error = ''; if(isset($_COOKIE['rguroo_form_error'])) { $error = $_COOKIE['rguroo_form_error']; unset($_COOKIE['rguroo_form_error']); } return '<form action='.esc_url( admin_url("admin-post.php") ).'method="post"> <p class="error">'.$error.'</p> <input type="radio" label="Purchase 12 months access" value="purchase" name="rguroo_desired_action" checked>Purchase 12 months access</input> <input type="radio" label="Renew account" name="rguroo_desired_action" value="renewal">Renew account</input> <input type="radio" label="Create trial account" name="rguroo_desired_action" value="trial">Create trial account</input> <p class="form-subtext">* indicates required field</p> <p>Email address*</p> <input type="text" name="rguroo_email" required> <p>Re-type email address*</p> <input type="text" name="rguroo_email_confirmation" required> <input type="hidden" name="action" value="rguroo_email_verification_form"> <input type="submit" value="Submit"> </form>'; } ``` This is the action that I've hooked onto admin-post.php ``` add_action( 'admin_post_nopriv_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); add_action( 'admin_post_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); // Email verification callback function verify_and_sanitize_email_form() { if(empty($_POST) || !isset($_POST['rguroo_email']) || !isset($_POST['rguroo_email_confirmation']) || !isset($_POST['rguroo_desired_action'])) { send_form_error('There is one or more empty fields'); return; } $sanitized_email = sanitize_email( esc_html($_POST['rguroo_email'] )); $sanitized_email_confirmation = sanitize_email( esc_html($_POST['rguroo_email_confirmation'] )); $desired_action = esc_html($_POST['rguroo_desired_action']); if(!is_email( $sanitized_email ) || !is_email( $sanitized_email_confirmation )) { send_form_error('Email is not valid'); return; } if($sanitized_email !== $sanitized_email_confirmation) { send_form_error('Emails do not match'); return; } if($desired_action !== 'purchase' || $desired_action !== 'renewal' || $desired_action !== 'trial') { send_form_error('Fatal error with radio buttons'); return; } if(!isset($_COOKIE['rguroo_form_type'])) { send_form_error('Server error'); return; } // student email verification logic $form_type = $_COOKIE['rguroo_form_type']; if($form_type === 'student') { $trail = substr($sanitized_email, -4); if($trail !== '.edu') { send_form_error('Not a valid student email'); return; } // Other university specific logic here } setcookie('rguroo_form_action',$desired_action, 14 * DAY_IN_SECONDS); setcookie('rguroo_form_email', $sanitized_email, 14 * DAY_IN_SECONDS); } // Helper. Used to output an error function send_form_error($msg) { setcookie('rguroo_form_error', $msg, 14 * DAY_IN_SECONDS); } ``` Sorry about the mess of error validation. Any ideas?
First of all... Your `action` is called `rguroo_email_verification_form`, so you should use it when registering your hooks. But you use this instead: ``` add_action( 'admin_post_nopriv_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); add_action( 'admin_post_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); ``` It should be: ``` add_action( 'admin_post_nopriv_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); add_action( 'admin_post_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); ``` Also... These actions don't take any params, but you declare they should take one param (but later on, your function doesn't take any...)
340,906
<p>I made a custom post type filters for others post types. The slug is a concatenation like <code>"filters-" . $custom-post-type</code>.</p> <p>And the custom post type appears correctly in the menu :</p> <p><a href="https://i.stack.imgur.com/xxsiZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xxsiZ.jpg" alt="enter image description here"></a></p> <p>My problem is when I try to save one, it is saved with <code>post_type = post</code>. What I missed up ?</p> <p>This is my PHP Code :</p> <pre><code>class SearchFilters { public $post_type_slug; public $post_type_label_name; public $post_type_singular_name; public $current_plugin_domain; public function __construct( $post_type_slug, $post_type_label_name, $post_type_singular_name ) { $this-&gt;current_plugin_domain = get_current_plugin_domain(); $this-&gt;post_type_slug = $post_type_slug; $this-&gt;post_type_label_name = $post_type_label_name; $this-&gt;post_type_singular_name = $post_type_singular_name; $this-&gt;init(); } private function init(){ $filters_slug = "filters-" . $this-&gt;post_type_slug; $filters_args = [ 'labels' =&gt; array( 'name' =&gt; sprintf( __( "Filters - Search Form for %s", $this-&gt;current_plugin_domain ), $this-&gt;post_type_label_name ), 'singular_name' =&gt; __( "Filter", $this-&gt;current_plugin_domain ), 'menu_name' =&gt; __( "Filters", $this-&gt;current_plugin_domain ), 'add_new_item' =&gt; sprintf( __( "Filters - Add New Search Form for %s", $this-&gt;current_plugin_domain ), $this-&gt;post_type_singular_name ) ), 'description' =&gt; __( "Filters to display search form on front end", $this-&gt;current_plugin_domain ), 'supports' =&gt; array( 'title' ), 'public' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; "edit.php?post_type=" . $this-&gt;post_type_slug, 'auto_save' =&gt; false ]; $result_filter = register_post_type( $filters_slug, $filters_args ); if ( is_wp_error( $result_filter ) ) { wp_error_log( $result_filter-&gt;get_error_message(), "Filter Post type creation " . "[" . __CLASS__ . "]" ); } } } </code></pre>
[ { "answer_id": 340873, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>First of all...</p>\n\n<p>Your <code>action</code> is called <code>rguroo_email_verification_form</code>, so you should use it when registering your hooks. But you use this instead:</p>\n\n<pre><code>add_action( 'admin_post_nopriv_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\nadd_action( 'admin_post_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\n</code></pre>\n\n<p>It should be:</p>\n\n<pre><code>add_action( 'admin_post_nopriv_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\nadd_action( 'admin_post_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 );\n</code></pre>\n\n<p>Also... These actions don't take any params, but you declare they should take one param (but later on, your function doesn't take any...)</p>\n" }, { "answer_id": 340949, "author": "Eli", "author_id": 153230, "author_profile": "https://wordpress.stackexchange.com/users/153230", "pm_score": 0, "selected": false, "text": "<p>As pointed out by Krzysiek, there was an inconsistency between the action field in the form and the admin-post hook.</p>\n\n<p>That being said, the real source the issue and the cause of the 404 was a formatting error.</p>\n\n<pre><code>&lt;form action='.esc_url( admin_url(\"admin-post.php\") ).'method=\"post\"&gt;\n</code></pre>\n\n<p>Was outputting</p>\n\n<pre><code>&lt;form action=\"https://rguroo.com/wp-admin/admin-post.phpmethod=post\"&gt;\n</code></pre>\n\n<p>The correct tag was as follows:</p>\n\n<pre><code>&lt;form action=\"'.esc_url( admin_url(\"admin-post.php\") ).'\" method=\"post\"&gt;\n</code></pre>\n\n<p>I'm an idiot...</p>\n" } ]
2019/06/19
[ "https://wordpress.stackexchange.com/questions/340906", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I made a custom post type filters for others post types. The slug is a concatenation like `"filters-" . $custom-post-type`. And the custom post type appears correctly in the menu : [![enter image description here](https://i.stack.imgur.com/xxsiZ.jpg)](https://i.stack.imgur.com/xxsiZ.jpg) My problem is when I try to save one, it is saved with `post_type = post`. What I missed up ? This is my PHP Code : ``` class SearchFilters { public $post_type_slug; public $post_type_label_name; public $post_type_singular_name; public $current_plugin_domain; public function __construct( $post_type_slug, $post_type_label_name, $post_type_singular_name ) { $this->current_plugin_domain = get_current_plugin_domain(); $this->post_type_slug = $post_type_slug; $this->post_type_label_name = $post_type_label_name; $this->post_type_singular_name = $post_type_singular_name; $this->init(); } private function init(){ $filters_slug = "filters-" . $this->post_type_slug; $filters_args = [ 'labels' => array( 'name' => sprintf( __( "Filters - Search Form for %s", $this->current_plugin_domain ), $this->post_type_label_name ), 'singular_name' => __( "Filter", $this->current_plugin_domain ), 'menu_name' => __( "Filters", $this->current_plugin_domain ), 'add_new_item' => sprintf( __( "Filters - Add New Search Form for %s", $this->current_plugin_domain ), $this->post_type_singular_name ) ), 'description' => __( "Filters to display search form on front end", $this->current_plugin_domain ), 'supports' => array( 'title' ), 'public' => false, 'show_ui' => true, 'show_in_menu' => "edit.php?post_type=" . $this->post_type_slug, 'auto_save' => false ]; $result_filter = register_post_type( $filters_slug, $filters_args ); if ( is_wp_error( $result_filter ) ) { wp_error_log( $result_filter->get_error_message(), "Filter Post type creation " . "[" . __CLASS__ . "]" ); } } } ```
First of all... Your `action` is called `rguroo_email_verification_form`, so you should use it when registering your hooks. But you use this instead: ``` add_action( 'admin_post_nopriv_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); add_action( 'admin_post_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); ``` It should be: ``` add_action( 'admin_post_nopriv_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); add_action( 'admin_post_rguroo_email_verification_form', 'verify_and_sanitize_email_form', $priority = 10, $accepted_args = 1 ); ``` Also... These actions don't take any params, but you declare they should take one param (but later on, your function doesn't take any...)
340,911
<p>both main and second domain (addon domain ) are in same host i want to find a way to change upload directory to another directory that located in another domain root.</p> <p><strong>default location (first location) :</strong> My main domain upload directory is : /domains/domain1.com/public_html/wp-content/uploads</p> <p><strong>destination location (second location) :</strong> the destination directory. is : /domains/domain2.com/public_html/wp-content/uploads</p> <p>I want to define second domain upload directory as main domain upload dir</p> <p>I mean I want domain1.com upload directory uses from the second domain upload directory.</p> <p>for example can i use another wordpress root location address from same host in this code in wp-config.php ? </p> <pre><code> wp config function: define('UPLOADS', 'destination directory'); </code></pre> <p>if its matter i use shared hosting and my control panel is directadmin</p> <p>is this possible ?</p>
[ { "answer_id": 340913, "author": "Lucas Vendramini", "author_id": 168637, "author_profile": "https://wordpress.stackexchange.com/users/168637", "pm_score": 1, "selected": false, "text": "<p>Well, what you want to achieve saving uploads in another domain? You want to share the uploads folder with another domain? </p>\n\n<p>Did you know you can use more than one domain (site) in a single WordPress Installation? It's called Multisite:\n<a href=\"https://premium.wpmudev.org/blog/ultimate-guide-multisite/\" rel=\"nofollow noreferrer\">https://premium.wpmudev.org/blog/ultimate-guide-multisite/</a></p>\n\n<p>To change the upload dir. Just use the filter <strong>upload_dir</strong>. It's documented here:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir</a></p>\n\n<p>Be happy!</p>\n" }, { "answer_id": 408075, "author": "Jesse Nickles", "author_id": 152624, "author_profile": "https://wordpress.stackexchange.com/users/152624", "pm_score": 0, "selected": false, "text": "<p>Yes, it's possible with Linux symlinks! <a href=\"https://github.com/littlebizzy/slickstack/blob/master/bash/ss-perms-wordpress-core.txt\" rel=\"nofollow noreferrer\">We do this now</a> on SlickStack staging sites.</p>\n<p>There is no way to do it using WordPress configuration settings alone -- WordPress is rather finicky with the <code>/uploads/</code> folder in particular, because the defined path must be relative to <code>/wp-content/</code> so hacking settings will not work, unless you want to share the <a href=\"https://wordpress.stackexchange.com/questions/54063/can-local-wordpress-installs-share-wp-content-folder-and-database\">entire directory tree</a> which is usually not what questions like yours are looking for.</p>\n<p>But you can easily &quot;trick&quot; WordPress into sharing a single folder with symlinks.</p>\n<p>In your case, point symlink like this:</p>\n<pre><code>sudo ln -s -f /domains/domain1.com/public_html/wp-content/uploads /domains/domain2.com/public_html/wp-content/uploads\n</code></pre>\n<p>Remember, for symlinks the first directory is &quot;canonical&quot; or the physical source, and the second directory is the actual symlink (virtual directory).</p>\n<p>You might also want to setup a cron job to ensure the symlink doesn't get overwritten.</p>\n" } ]
2019/06/19
[ "https://wordpress.stackexchange.com/questions/340911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170293/" ]
both main and second domain (addon domain ) are in same host i want to find a way to change upload directory to another directory that located in another domain root. **default location (first location) :** My main domain upload directory is : /domains/domain1.com/public\_html/wp-content/uploads **destination location (second location) :** the destination directory. is : /domains/domain2.com/public\_html/wp-content/uploads I want to define second domain upload directory as main domain upload dir I mean I want domain1.com upload directory uses from the second domain upload directory. for example can i use another wordpress root location address from same host in this code in wp-config.php ? ``` wp config function: define('UPLOADS', 'destination directory'); ``` if its matter i use shared hosting and my control panel is directadmin is this possible ?
Well, what you want to achieve saving uploads in another domain? You want to share the uploads folder with another domain? Did you know you can use more than one domain (site) in a single WordPress Installation? It's called Multisite: <https://premium.wpmudev.org/blog/ultimate-guide-multisite/> To change the upload dir. Just use the filter **upload\_dir**. It's documented here: <https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir> Be happy!