qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
317,969
<p>I am trying to change the text color of my current menu item as on hover its green but the background is green so I want the color to be white on hover but it does not seem to want to work, to view hover over the selected page on 'our products'</p> <p><a href="http://beta2018.bedcentregrimsby.co.uk/product-category/bunk-beds" rel="nofollow noreferrer">website link</a></p> <pre><code>li.current-menu-item a:hover{ color:white !important; } </code></pre>
[ { "answer_id": 317901, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 0, "selected": false, "text": "<p>in general it's not a good idea to insert inline styles. </p>\n\n<p>try with a CSS class and add your custom CSS to your theme.</p>\n" }, { "answer_id": 317958, "author": "Aculine", "author_id": 150879, "author_profile": "https://wordpress.stackexchange.com/users/150879", "pm_score": 1, "selected": false, "text": "<p>SOLVED:<br>\nas @milo suggests, I found solution disabling mod_security under cPanel. So I ask to my hoster (register.it) if there was some problem. They confirm me that servers are under updating security stuff and to disable and then re-able mod_security in CPanel. After that, post.php works properly.</p>\n\n<p>Thank you all.</p>\n" }, { "answer_id": 318025, "author": "Francesco Colombo", "author_id": 153289, "author_profile": "https://wordpress.stackexchange.com/users/153289", "pm_score": 2, "selected": true, "text": "<p>I've had the same issue recently. </p>\n\n<p>Inline styles, as well as <code>&lt;img&gt;</code> tags, would cause the <code>410 Gone</code> status and error message (<code>The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource.</code> upon previewing or publishing the post.</p>\n\n<p>The problem was due to the hosting provider doing some maintenance on <code>mod_security</code> in cPanel.</p>\n\n<p>I found out when I asked them for the Apache logs so that I could look into it more.</p>\n\n<p>Contact your hosting provider to get this fixed.</p>\n" } ]
2018/10/30
[ "https://wordpress.stackexchange.com/questions/317969", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150429/" ]
I am trying to change the text color of my current menu item as on hover its green but the background is green so I want the color to be white on hover but it does not seem to want to work, to view hover over the selected page on 'our products' [website link](http://beta2018.bedcentregrimsby.co.uk/product-category/bunk-beds) ``` li.current-menu-item a:hover{ color:white !important; } ```
I've had the same issue recently. Inline styles, as well as `<img>` tags, would cause the `410 Gone` status and error message (`The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource.` upon previewing or publishing the post. The problem was due to the hosting provider doing some maintenance on `mod_security` in cPanel. I found out when I asked them for the Apache logs so that I could look into it more. Contact your hosting provider to get this fixed.
318,029
<p>Is there a way to display a video using only the default video player of the browser, without the <code>mejs</code> / <code>wp-video</code> interface? The additional markup gives me a lot of trouble. I just want to use the <code>&lt;video&gt;</code> element, and handle my custom needs with CSS/JS.</p> <p>I won't say I'm an expert. I have considerable amount of experience with custom templates and hooks, but I can't figure this one out.</p>
[ { "answer_id": 318039, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": -1, "selected": false, "text": "<p>I would try to use the <strong>embed_oembed_html filter</strong></p>\n\n<p>Here is an ultra basic example</p>\n\n<pre><code>add_filter('embed_oembed_html','oembed_video_add_wrapper',10,4);\n\nfunction oembed_video_add_wrapper( $cache, $url, $attr, $post_ID) {\n return sprintf('&lt;video src=\"%s\"&gt;',$url);\n}\n</code></pre>\n" }, { "answer_id": 318181, "author": "Nekomajin42", "author_id": 153292, "author_profile": "https://wordpress.stackexchange.com/users/153292", "pm_score": 1, "selected": true, "text": "<p>I've found the right way digging through the WP documentation: <a href=\"https://developer.wordpress.org/reference/hooks/wp_video_shortcode/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_video_shortcode/</a></p>\n\n<p>This code seems to do the trick:</p>\n\n<pre><code>function buildVideoPlayer($output, $attr)\n{\n // $output contains the default HTML string, created by the WP core\n // $attr is an associative array, which contains the parameters \n // (src, poster, preload, etc.) specified in the shortcode\n\n // The following piece of HTML string will replace the default WP video player\n return \"&lt;video src='\".$attr[\"mp4\"].\"'&gt;&lt;/video&gt;\";\n}\nadd_filter(\"wp_video_shortcode\", \"buildVideoPlayer\", 10, 2);\n</code></pre>\n\n<p>Make sure to pass how many parameters do you want to catch in <code>add_filter()</code>. The default value is 1, but <code>wp_video_shortcode</code> has 4, and in this code, I needed the 2nd one.</p>\n" } ]
2018/10/30
[ "https://wordpress.stackexchange.com/questions/318029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153292/" ]
Is there a way to display a video using only the default video player of the browser, without the `mejs` / `wp-video` interface? The additional markup gives me a lot of trouble. I just want to use the `<video>` element, and handle my custom needs with CSS/JS. I won't say I'm an expert. I have considerable amount of experience with custom templates and hooks, but I can't figure this one out.
I've found the right way digging through the WP documentation: <https://developer.wordpress.org/reference/hooks/wp_video_shortcode/> This code seems to do the trick: ``` function buildVideoPlayer($output, $attr) { // $output contains the default HTML string, created by the WP core // $attr is an associative array, which contains the parameters // (src, poster, preload, etc.) specified in the shortcode // The following piece of HTML string will replace the default WP video player return "<video src='".$attr["mp4"]."'></video>"; } add_filter("wp_video_shortcode", "buildVideoPlayer", 10, 2); ``` Make sure to pass how many parameters do you want to catch in `add_filter()`. The default value is 1, but `wp_video_shortcode` has 4, and in this code, I needed the 2nd one.
318,073
<p>I'm trying to set <code>posts_per_page</code> depending on what category is being shown. </p> <p>The following code works.</p> <pre><code>function category_posts_per_page( $query ) { if ( $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_category() &amp;&amp; $query-&gt;is_category('books') ) { $query-&gt;set('posts_per_page', 2); } } add_action( 'pre_get_posts', 'category_posts_per_page' ); </code></pre> <p><strong>The problem:</strong></p> <p>I'm getting a php notice every 30 seconds in my debug log. No notices from visiting any posts, pages, categories or anything manually.</p> <p>From debug.log:</p> <pre><code>[31-Oct-2018 10:18:46 UTC] PHP Notice: Trying to get property 'term_id' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3502 [31-Oct-2018 10:18:46 UTC] PHP Notice: Trying to get property 'name' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3504 [31-Oct-2018 10:18:46 UTC] PHP Notice: Trying to get property 'slug' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3506 </code></pre> <p>I've disabled all plugins, switched themes to a default one (and added the above code to functions.php).</p> <p>How would I fix this? The code works and it's just a php notice, but it's a bit annoying... especially now in development and all notices are visible in debug.</p>
[ { "answer_id": 318084, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": 0, "selected": false, "text": "<p>Maybe you should try this behavior happens only on frontend, with adding !is_admin like this. It is maybe due to the admin ajax heartbeat?</p>\n\n<pre><code>function category_posts_per_page( $query )\n{\n\n if (!is_admin() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_category() &amp;&amp; $query-&gt;is_category('books') ) {\n $query-&gt;set('posts_per_page', 2);\n\n }\n\n}\nadd_action( 'pre_get_posts', 'category_posts_per_page' );\n</code></pre>\n" }, { "answer_id": 318096, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p><code>is_category('category-name')</code> won't work until after the query is run. If we check source code where those notices are generated, we can see that it's using <code>get_queried_object</code>, which gets populated with the results of the main query, and at the <code>pre_get_posts</code> stage will still be empty.</p>\n\n<p>As an alternate, check the contents of <code>$query-&gt;query_vars</code>, which will be an array of query vars parsed from the requested URL.</p>\n" } ]
2018/10/31
[ "https://wordpress.stackexchange.com/questions/318073", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15809/" ]
I'm trying to set `posts_per_page` depending on what category is being shown. The following code works. ``` function category_posts_per_page( $query ) { if ( $query->is_main_query() && $query->is_category() && $query->is_category('books') ) { $query->set('posts_per_page', 2); } } add_action( 'pre_get_posts', 'category_posts_per_page' ); ``` **The problem:** I'm getting a php notice every 30 seconds in my debug log. No notices from visiting any posts, pages, categories or anything manually. From debug.log: ``` [31-Oct-2018 10:18:46 UTC] PHP Notice: Trying to get property 'term_id' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3502 [31-Oct-2018 10:18:46 UTC] PHP Notice: Trying to get property 'name' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3504 [31-Oct-2018 10:18:46 UTC] PHP Notice: Trying to get property 'slug' of non-object in /var/www/html/wp-includes/class-wp-query.php on line 3506 ``` I've disabled all plugins, switched themes to a default one (and added the above code to functions.php). How would I fix this? The code works and it's just a php notice, but it's a bit annoying... especially now in development and all notices are visible in debug.
`is_category('category-name')` won't work until after the query is run. If we check source code where those notices are generated, we can see that it's using `get_queried_object`, which gets populated with the results of the main query, and at the `pre_get_posts` stage will still be empty. As an alternate, check the contents of `$query->query_vars`, which will be an array of query vars parsed from the requested URL.
318,117
<p>I'm sorry if this is a already asked Question but i'm trying to get my custom post types displayed in grid like this: </p> <pre><code>&lt;div class="row&gt; &lt;div class="col-md-4&gt; /* Start the Loop */ while (have_posts()) : the_post(); get_template_part('template-parts/post/content', get_post_format()); endwhile; // End of the loop. &lt;/div&gt; &lt;/div </code></pre> <p>that mean i would like to Display every post in a div with the class col-md-4</p>
[ { "answer_id": 318084, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": 0, "selected": false, "text": "<p>Maybe you should try this behavior happens only on frontend, with adding !is_admin like this. It is maybe due to the admin ajax heartbeat?</p>\n\n<pre><code>function category_posts_per_page( $query )\n{\n\n if (!is_admin() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_category() &amp;&amp; $query-&gt;is_category('books') ) {\n $query-&gt;set('posts_per_page', 2);\n\n }\n\n}\nadd_action( 'pre_get_posts', 'category_posts_per_page' );\n</code></pre>\n" }, { "answer_id": 318096, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p><code>is_category('category-name')</code> won't work until after the query is run. If we check source code where those notices are generated, we can see that it's using <code>get_queried_object</code>, which gets populated with the results of the main query, and at the <code>pre_get_posts</code> stage will still be empty.</p>\n\n<p>As an alternate, check the contents of <code>$query-&gt;query_vars</code>, which will be an array of query vars parsed from the requested URL.</p>\n" } ]
2018/10/31
[ "https://wordpress.stackexchange.com/questions/318117", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153348/" ]
I'm sorry if this is a already asked Question but i'm trying to get my custom post types displayed in grid like this: ``` <div class="row> <div class="col-md-4> /* Start the Loop */ while (have_posts()) : the_post(); get_template_part('template-parts/post/content', get_post_format()); endwhile; // End of the loop. </div> </div ``` that mean i would like to Display every post in a div with the class col-md-4
`is_category('category-name')` won't work until after the query is run. If we check source code where those notices are generated, we can see that it's using `get_queried_object`, which gets populated with the results of the main query, and at the `pre_get_posts` stage will still be empty. As an alternate, check the contents of `$query->query_vars`, which will be an array of query vars parsed from the requested URL.
318,165
<p>I am looking for help to put single page favicon that would overwrite global one. Say for example I have wordpress website that is example.com and it has favicon set for every page. What I want is for example.com/page3 to have diffrent favicon. I have seen quite a few options around but I cannot figure out how to make it work (my coding skills are limited). This solution:</p> <pre><code>&lt;?php echo '&lt;link rel="shortcut icon" href="http://www.yoursite.com/favicon.ico?t=' . time() . '" /&gt;'; ?&gt; </code></pre> <p>Is marked as working one, but I cannot figure out how to set it up. Thank you for help</p>
[ { "answer_id": 318260, "author": "thehbhatt", "author_id": 92703, "author_profile": "https://wordpress.stackexchange.com/users/92703", "pm_score": -1, "selected": false, "text": "<p>Here is the link: <a href=\"https://elementor.com/blog/header-footer-builder/\" rel=\"nofollow noreferrer\">https://elementor.com/blog/header-footer-builder/</a></p>\n\n<p>there is a video link on this page which explains how can you create/use multiple header with Elementor plugin.</p>\n\n<p>Normally if you have FTP access go to theme folder and duplicate <strong>header.php</strong> and name it something relevant <strong>ie. header-blog.php</strong></p>\n\n<p>Then you can call that file in your page/templates via <code>&lt;?php get_header('blog); ?&gt;</code></p>\n\n<p>In your new header file use the rel link you've got for custom favicon. That's it :)</p>\n" }, { "answer_id": 318279, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>If you have a modern theme, where you can upload a favicon with the theme customizer (rather than a hardcoded url in the <code>header.php</code>), you can simply use a filter. Take a look at the function <a href=\"https://developer.wordpress.org/reference/functions/get_site_icon_url/\" rel=\"nofollow noreferrer\"><code>get_site_icon</code></a>. As you can see it returns the url of the image that you have uploaded using the customizer. However, before it does so, it runs it through a filter, allowing you to change it under any condition you would like. For instance, to change it when you are on a page with ID=3:</p>\n\n<pre><code>add_filter( 'get_site_icon_url','wpse318165_filter_favicon', 10, 3 );\nfunction wpse318165_filter_favicon ($url, $size, $blog_id) {\n global $post;\n if ( is_page( 3 ) ) $url = 'path-to-other-favicon';\n return $url;\n }\n</code></pre>\n" } ]
2018/11/01
[ "https://wordpress.stackexchange.com/questions/318165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153372/" ]
I am looking for help to put single page favicon that would overwrite global one. Say for example I have wordpress website that is example.com and it has favicon set for every page. What I want is for example.com/page3 to have diffrent favicon. I have seen quite a few options around but I cannot figure out how to make it work (my coding skills are limited). This solution: ``` <?php echo '<link rel="shortcut icon" href="http://www.yoursite.com/favicon.ico?t=' . time() . '" />'; ?> ``` Is marked as working one, but I cannot figure out how to set it up. Thank you for help
If you have a modern theme, where you can upload a favicon with the theme customizer (rather than a hardcoded url in the `header.php`), you can simply use a filter. Take a look at the function [`get_site_icon`](https://developer.wordpress.org/reference/functions/get_site_icon_url/). As you can see it returns the url of the image that you have uploaded using the customizer. However, before it does so, it runs it through a filter, allowing you to change it under any condition you would like. For instance, to change it when you are on a page with ID=3: ``` add_filter( 'get_site_icon_url','wpse318165_filter_favicon', 10, 3 ); function wpse318165_filter_favicon ($url, $size, $blog_id) { global $post; if ( is_page( 3 ) ) $url = 'path-to-other-favicon'; return $url; } ```
318,167
<p>So i installed the wp admin package, but i can't seem to get her working, an error pops up telling me xdg-open doenst exist.. For install i used:</p> <pre><code>wp package install [email protected]:wp-cli/admin-command.git Installing package wp-cli/admin-command (dev-master) Updating ~.wp-cli\packages\composer.json to require the package... Registering [email protected]:wp-cli/admin-command.git as a VCS repository... Using Composer to install the package... --- Loading composer repositories with package information Updating dependencies Resolving dependencies through SAT Looking at all rules. Dependency resolution completed in 0.385 seconds Analyzed 6619 packages to resolve dependencies Analyzed 474197 rules to resolve dependencies Package operations: 1 install, 0 updates, 0 removals Installs: wp-cli/admin-command:dev-master 384f6d3 - Installing wp-cli/admin-command (dev-master 384f6d3) Writing lock file Generating autoload files --- Success: Package installed. </code></pre> <p>Now checking if she's there</p> <pre><code>wp admin --info 'xdg-open' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>So what's going wrong, how can i get the wp admin command to run? btw, im running WP-CLI 2.0.1 on win10 from powershell. Any help would be greatly appreciated.</p>
[ { "answer_id": 319299, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>This happened due to Windows not yet being supported.</p>\n\n<p>With <a href=\"https://github.com/wp-cli/admin-command/pull/18\" rel=\"nofollow noreferrer\">PR#18</a> this was resolved, update the package to the latest version and it will work on Windows machines.</p>\n" }, { "answer_id": 319302, "author": "DGRFDSGN", "author_id": 108736, "author_profile": "https://wordpress.stackexchange.com/users/108736", "pm_score": 1, "selected": false, "text": "<p>So <code>xdg-open</code> is not supported on Windows, therefor the code has been updated to check for a Windows OS and use <code>start</code>\nCheck out <a href=\"https://github.com/wp-cli/admin-command/pull/18\" rel=\"nofollow noreferrer\">this repo</a> if you cant wait for the merge with master.</p>\n\n<p>Will leave this Question here untill everything is merged, so people experiencing a similar problem have some reference. Thanks @king-kero @schlessera for the quick support@github!</p>\n" } ]
2018/11/01
[ "https://wordpress.stackexchange.com/questions/318167", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108736/" ]
So i installed the wp admin package, but i can't seem to get her working, an error pops up telling me xdg-open doenst exist.. For install i used: ``` wp package install [email protected]:wp-cli/admin-command.git Installing package wp-cli/admin-command (dev-master) Updating ~.wp-cli\packages\composer.json to require the package... Registering [email protected]:wp-cli/admin-command.git as a VCS repository... Using Composer to install the package... --- Loading composer repositories with package information Updating dependencies Resolving dependencies through SAT Looking at all rules. Dependency resolution completed in 0.385 seconds Analyzed 6619 packages to resolve dependencies Analyzed 474197 rules to resolve dependencies Package operations: 1 install, 0 updates, 0 removals Installs: wp-cli/admin-command:dev-master 384f6d3 - Installing wp-cli/admin-command (dev-master 384f6d3) Writing lock file Generating autoload files --- Success: Package installed. ``` Now checking if she's there ``` wp admin --info 'xdg-open' is not recognized as an internal or external command, operable program or batch file. ``` So what's going wrong, how can i get the wp admin command to run? btw, im running WP-CLI 2.0.1 on win10 from powershell. Any help would be greatly appreciated.
This happened due to Windows not yet being supported. With [PR#18](https://github.com/wp-cli/admin-command/pull/18) this was resolved, update the package to the latest version and it will work on Windows machines.
318,213
<p>I tried reading the WordPress codex about integrating WordPress into an existing website.</p> <p>I tried using the header information</p> <pre><code>&lt;?php /* Short and sweet */ define('WP_USE_THEMES', false); require('./wp-blog-header.php'); ?&gt; </code></pre> <p>And then the test code</p> <pre><code>&lt;?php // Get the last 3 posts. global $post; $args = array( 'posts_per_page' =&gt; 3 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>Another code I added to make the page only for logged in users:</p> <pre><code>if ( ! is_user_logged_in() ) { // Display WordPress login form: wp_login_form($args); </code></pre> <p>This code does make the login show, but when I log in, it cannot remember that it is logged in, and the functions (blog posts) will not show. The funny thing is, the login form (as called by the wp_login_form) shows, but I cannot log in. This is quite anoying, as the information in the codex doesn't work <a href="https://codex.wordpress.org/Integrating_WordPress_with_Your_Website" rel="nofollow noreferrer">Integrating Wordpress with Your Website</a></p> <p>It does not work. Can someone help me? I tried posting at the WordPress forum, but no help there </p> <p>New edit 07th november: This is how the PHP file looks like now. It's called lite_index.php and includes the wp-load, and because of that I believe the login form under here shows, bt still it cannot login.</p> <pre><code>&lt;?php //define('WP_USE_THEMES', false); //require('lite/wp-blog-header.php'); define('COOKIEPATH', '/'); require('lite/wp-load.php'); require('loggin_check.php'); //require(dirname(__FILE__) . 'lite/wp-load.php'); //header('Content-Type: text/html; charset=ISO-8859-1'); $posts = get_posts('numberposts=10&amp;order=ASC&amp;orderby=post_title'); foreach ($posts as $post) : setup_postdata( $post ); ?&gt; &lt;?php the_date(); echo "&lt;br /&gt;"; ?&gt; &lt;?php the_title(); ?&gt; &lt;?php the_excerpt(); ?&gt; &lt;?php endforeach; ?&gt; &lt;h1&gt;Lite v4&lt;/h1&gt; &lt;?php if ( ! is_user_logged_in() ) { // Display WordPress login form: wp_login_form($args); } else { wp_loginout(index.php); // Display "Log Out" link. echo " | "; wp_register('', ''); // Display "Site Admin" link. echo "&lt;br /&gt;\n"; } ?&gt; </code></pre>
[ { "answer_id": 318248, "author": "Bob", "author_id": 116319, "author_profile": "https://wordpress.stackexchange.com/users/116319", "pm_score": 1, "selected": false, "text": "<p>Have you tried using the following?<br></p>\n\n<pre><code>require(dirname(__FILE__) . '/wp-load.php');\n</code></pre>\n\n<p>Note that this requires WordPress to be installed in the root directory of the website.</p>\n" }, { "answer_id": 318654, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 2, "selected": true, "text": "<p>I started writing a pretty long comment, but I figured I would write it as a solution instead. </p>\n\n<p>If you mix all your files in one big jumble, then it probably wont work. But if you put WordPress in a subdirectory, then it would work (that's how I used to do it). </p>\n\n<p>REMEMBER!!! If you already have a working WordPress-installation and want to move the posts, then you can't simply move the files. You'd have to follow the right procedure, which is <a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\">explained here</a>.</p>\n\n<p>Example of correct file-structure, mixing a static website with WordPress:</p>\n\n<pre><code>|-your-index.php\n|-your-page-1.php\n|-your-page-2.php\n|-your-css\n| |-your-styles.css\n|\n|-your-js \n| |-your-js-file.js\n|\n|-wp &lt;-- Put your entire WP-installation in a folder\n |-wp-content\n | |-themes\n | |-uploads\n | |-...\n | |-...\n | \n |-wp-includes\n | |-...\n | |-...\n |\n |-wp-admin\n | |-...\n | |-...\n |\n |-wp-config.php\n |-wp-blog-header.php\n |-...\n |-...\n</code></pre>\n\n<p>This way you can call </p>\n\n<pre><code>&lt;?php require( $_SERVER['document_root'] . '/wp/wp-blog-header.php'); ?&gt;\n</code></pre>\n\n<p>Then you can keep your own static files and your WordPress-installation seperate and make it work. This is how I used to do it, and that worked. </p>\n\n<hr>\n\n<p><strong>Flipside</strong></p>\n\n<p>I can see (by Googling a bit), that it looks like that @Bob's suggestion has become more popular. <a href=\"https://www.creare.co.uk/blog/wp/how-to-display-recent-posts-outside-wordpress\" rel=\"nofollow noreferrer\">Here's an example, using wp-load</a>. I must admit, that I don't know what the difference is between the two. </p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/47928/external-wordpress-pages-using-wp-blog-header\">This solution</a> suggest a third way of doing it. </p>\n\n<p>But all things considered... Regardless of which way you load WordPress, then I think that it's your file structure that is your current challenge (if I'm not mistaken). WordPress needs it's own isolated environment (folder), so it can make it's URL and call the files as intended. </p>\n\n<hr>\n\n<p><strong>Final word</strong></p>\n\n<p>But as I suggested in my comment. I used to do this, - and I wish I never did. I wish I had baked my static website into a WordPress-theme. </p>\n" }, { "answer_id": 367469, "author": "user3066853", "author_id": 98545, "author_profile": "https://wordpress.stackexchange.com/users/98545", "pm_score": 0, "selected": false, "text": "<p>You can learn step by step by click below link:</p>\n\n<p><a href=\"https://youtu.be/LFBe3KkyUA4\" rel=\"nofollow noreferrer\">https://youtu.be/LFBe3KkyUA4</a></p>\n\n<p>You can comment in comment section for any query, We will answer in next 2 hours.</p>\n" } ]
2018/11/01
[ "https://wordpress.stackexchange.com/questions/318213", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152515/" ]
I tried reading the WordPress codex about integrating WordPress into an existing website. I tried using the header information ``` <?php /* Short and sweet */ define('WP_USE_THEMES', false); require('./wp-blog-header.php'); ?> ``` And then the test code ``` <?php // Get the last 3 posts. global $post; $args = array( 'posts_per_page' => 3 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><br /> <?php endforeach; ?> ``` Another code I added to make the page only for logged in users: ``` if ( ! is_user_logged_in() ) { // Display WordPress login form: wp_login_form($args); ``` This code does make the login show, but when I log in, it cannot remember that it is logged in, and the functions (blog posts) will not show. The funny thing is, the login form (as called by the wp\_login\_form) shows, but I cannot log in. This is quite anoying, as the information in the codex doesn't work [Integrating Wordpress with Your Website](https://codex.wordpress.org/Integrating_WordPress_with_Your_Website) It does not work. Can someone help me? I tried posting at the WordPress forum, but no help there New edit 07th november: This is how the PHP file looks like now. It's called lite\_index.php and includes the wp-load, and because of that I believe the login form under here shows, bt still it cannot login. ``` <?php //define('WP_USE_THEMES', false); //require('lite/wp-blog-header.php'); define('COOKIEPATH', '/'); require('lite/wp-load.php'); require('loggin_check.php'); //require(dirname(__FILE__) . 'lite/wp-load.php'); //header('Content-Type: text/html; charset=ISO-8859-1'); $posts = get_posts('numberposts=10&order=ASC&orderby=post_title'); foreach ($posts as $post) : setup_postdata( $post ); ?> <?php the_date(); echo "<br />"; ?> <?php the_title(); ?> <?php the_excerpt(); ?> <?php endforeach; ?> <h1>Lite v4</h1> <?php if ( ! is_user_logged_in() ) { // Display WordPress login form: wp_login_form($args); } else { wp_loginout(index.php); // Display "Log Out" link. echo " | "; wp_register('', ''); // Display "Site Admin" link. echo "<br />\n"; } ?> ```
I started writing a pretty long comment, but I figured I would write it as a solution instead. If you mix all your files in one big jumble, then it probably wont work. But if you put WordPress in a subdirectory, then it would work (that's how I used to do it). REMEMBER!!! If you already have a working WordPress-installation and want to move the posts, then you can't simply move the files. You'd have to follow the right procedure, which is [explained here](https://codex.wordpress.org/Moving_WordPress). Example of correct file-structure, mixing a static website with WordPress: ``` |-your-index.php |-your-page-1.php |-your-page-2.php |-your-css | |-your-styles.css | |-your-js | |-your-js-file.js | |-wp <-- Put your entire WP-installation in a folder |-wp-content | |-themes | |-uploads | |-... | |-... | |-wp-includes | |-... | |-... | |-wp-admin | |-... | |-... | |-wp-config.php |-wp-blog-header.php |-... |-... ``` This way you can call ``` <?php require( $_SERVER['document_root'] . '/wp/wp-blog-header.php'); ?> ``` Then you can keep your own static files and your WordPress-installation seperate and make it work. This is how I used to do it, and that worked. --- **Flipside** I can see (by Googling a bit), that it looks like that @Bob's suggestion has become more popular. [Here's an example, using wp-load](https://www.creare.co.uk/blog/wp/how-to-display-recent-posts-outside-wordpress). I must admit, that I don't know what the difference is between the two. [This solution](https://wordpress.stackexchange.com/questions/47928/external-wordpress-pages-using-wp-blog-header) suggest a third way of doing it. But all things considered... Regardless of which way you load WordPress, then I think that it's your file structure that is your current challenge (if I'm not mistaken). WordPress needs it's own isolated environment (folder), so it can make it's URL and call the files as intended. --- **Final word** But as I suggested in my comment. I used to do this, - and I wish I never did. I wish I had baked my static website into a WordPress-theme.
318,226
<p>I have never used XMLRPC for any activity for my WordPress sites and also not going to do so.</p> <p>There are many articles on disabling XMLRPC on your site for additional security. In the use case scenario that I discussed when if that service is not required, why to disbale it or make it more secure ? I just wish to simply delete the xmlrpc.php. Will it cause any errors if I delete it ?</p>
[ { "answer_id": 318241, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 2, "selected": false, "text": "<p>As mentioned in comments, if you delete the file, updating WP will bring it back.</p>\n\n<p>It is best to block it at server level.\nIn <code>nginx</code> I do following:</p>\n\n<pre><code># Disable xmlrpc.php it is being abused by script kiddies\nlocation ~ xmlrpc.php {\n deny all;\n access_log off;\n log_not_found off;\n return 444;\n}\n</code></pre>\n" }, { "answer_id": 318254, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>You shouldn't delete that file - it will be restored after update - so deleting it makes no sense (and it shouldn't be treated as security fix).</p>\n\n<p>You can disable XMLRPC using filter:</p>\n\n<pre><code>add_filter('xmlrpc_enabled', '__return_false');\n</code></pre>\n\n<p>And even block access to that file. Below code for Apache (sandrodz showed code for nginx):</p>\n\n<pre><code>&lt;Files xmlrpc.php&gt;\n Order deny,allow\n Deny from all\n&lt;/Files&gt;\n</code></pre>\n" } ]
2018/11/02
[ "https://wordpress.stackexchange.com/questions/318226", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147821/" ]
I have never used XMLRPC for any activity for my WordPress sites and also not going to do so. There are many articles on disabling XMLRPC on your site for additional security. In the use case scenario that I discussed when if that service is not required, why to disbale it or make it more secure ? I just wish to simply delete the xmlrpc.php. Will it cause any errors if I delete it ?
You shouldn't delete that file - it will be restored after update - so deleting it makes no sense (and it shouldn't be treated as security fix). You can disable XMLRPC using filter: ``` add_filter('xmlrpc_enabled', '__return_false'); ``` And even block access to that file. Below code for Apache (sandrodz showed code for nginx): ``` <Files xmlrpc.php> Order deny,allow Deny from all </Files> ```
318,249
<p>I'm starting to go a little mad here, I must be missing something obious but I have tried many solutions.</p> <p>My problem: I want to have 6 related products under each product. (Understanding if a category has more then 6 products in it)</p> <p>I currently have the related products grabbing it's shared category. But when I load a product, it may show 1 related product, or 4, or 3. Every load its a different number of related products. Very odd.</p> <p>Here is my code.</p> <pre><code>if ( ! defined( 'ABSPATH' ) ) { exit; } global $product, $woocommerce_loop; if ( empty( $product ) || ! $product-&gt;exists() ) { return; } if ( ! $related = $product-&gt;get_related( 6 ) ) { return; } $cats_array = array(0); // get categories $terms = wp_get_post_terms( $product-&gt;id, 'product_cat' ); // select only the category which doesn't have any children foreach ( $terms as $term ) { $children = get_term_children( $term-&gt;term_id, 'product_cat' ); if ( !sizeof( $children ) ) $cats_array[] = $term-&gt;term_id; } $args = apply_filters( 'woocommerce_related_products_args', array( 'post_type' =&gt; 'product', 'ignore_sticky_posts' =&gt; 1, 'no_found_rows' =&gt; 1, 'posts_per_page' =&gt; 6, 'orderby' =&gt; $orderby, 'post__in' =&gt; $related, 'post__not_in' =&gt; array( $product-&gt;get_id() ), 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'id', 'terms' =&gt; $cats_array ), ) ) ); $products = new WP_Query( $args ); $woocommerce_loop['name'] = 'related'; $woocommerce_loop['columns'] = apply_filters('woocommerce_related_products_columns', 6); </code></pre> <p>If anyone has any advice that would be greatly appreciated. Thank you</p>
[ { "answer_id": 318241, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 2, "selected": false, "text": "<p>As mentioned in comments, if you delete the file, updating WP will bring it back.</p>\n\n<p>It is best to block it at server level.\nIn <code>nginx</code> I do following:</p>\n\n<pre><code># Disable xmlrpc.php it is being abused by script kiddies\nlocation ~ xmlrpc.php {\n deny all;\n access_log off;\n log_not_found off;\n return 444;\n}\n</code></pre>\n" }, { "answer_id": 318254, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>You shouldn't delete that file - it will be restored after update - so deleting it makes no sense (and it shouldn't be treated as security fix).</p>\n\n<p>You can disable XMLRPC using filter:</p>\n\n<pre><code>add_filter('xmlrpc_enabled', '__return_false');\n</code></pre>\n\n<p>And even block access to that file. Below code for Apache (sandrodz showed code for nginx):</p>\n\n<pre><code>&lt;Files xmlrpc.php&gt;\n Order deny,allow\n Deny from all\n&lt;/Files&gt;\n</code></pre>\n" } ]
2018/11/02
[ "https://wordpress.stackexchange.com/questions/318249", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153434/" ]
I'm starting to go a little mad here, I must be missing something obious but I have tried many solutions. My problem: I want to have 6 related products under each product. (Understanding if a category has more then 6 products in it) I currently have the related products grabbing it's shared category. But when I load a product, it may show 1 related product, or 4, or 3. Every load its a different number of related products. Very odd. Here is my code. ``` if ( ! defined( 'ABSPATH' ) ) { exit; } global $product, $woocommerce_loop; if ( empty( $product ) || ! $product->exists() ) { return; } if ( ! $related = $product->get_related( 6 ) ) { return; } $cats_array = array(0); // get categories $terms = wp_get_post_terms( $product->id, 'product_cat' ); // select only the category which doesn't have any children foreach ( $terms as $term ) { $children = get_term_children( $term->term_id, 'product_cat' ); if ( !sizeof( $children ) ) $cats_array[] = $term->term_id; } $args = apply_filters( 'woocommerce_related_products_args', array( 'post_type' => 'product', 'ignore_sticky_posts' => 1, 'no_found_rows' => 1, 'posts_per_page' => 6, 'orderby' => $orderby, 'post__in' => $related, 'post__not_in' => array( $product->get_id() ), 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $cats_array ), ) ) ); $products = new WP_Query( $args ); $woocommerce_loop['name'] = 'related'; $woocommerce_loop['columns'] = apply_filters('woocommerce_related_products_columns', 6); ``` If anyone has any advice that would be greatly appreciated. Thank you
You shouldn't delete that file - it will be restored after update - so deleting it makes no sense (and it shouldn't be treated as security fix). You can disable XMLRPC using filter: ``` add_filter('xmlrpc_enabled', '__return_false'); ``` And even block access to that file. Below code for Apache (sandrodz showed code for nginx): ``` <Files xmlrpc.php> Order deny,allow Deny from all </Files> ```
318,273
<p>Since <code>order allow,deny</code> is deprecated in 2.4 I wanted to rewrite the rules in my .htaccess file to use the new rules. Previously I was using:</p> <pre><code>&lt;files wp-config.php&gt; order allow,deny deny from all &lt;/files&gt; </code></pre> <p>Which I've rewritten to:</p> <pre><code>&lt;FilesMatch "wp-config.php"&gt; Require all denied &lt;/FilesMatch&gt; </code></pre> <p><strong>How do I confirm that my method is actually working?</strong> I'm not certain how hackers might gain access to this file so I don't know how to test it.</p>
[ { "answer_id": 318287, "author": "scytale", "author_id": 128374, "author_profile": "https://wordpress.stackexchange.com/users/128374", "pm_score": 1, "selected": false, "text": "<p>The old method works for me, and any requests result in a 403 status response instead of execution of the php script. I've not checked your 2nd method, but if it works it will similarly respond with 403 denied/forbidden.</p>\n\n<p>To test you simply have to insert the URL of your \"wp-config.php\" in the address bar of your browser e.g. <a href=\"http://example.com/wp-config.php\" rel=\"nofollow noreferrer\">http://example.com/wp-config.php</a> . Depending on browser and/or sites custom 403 settings your browser will display \"forbidden\", \"access denied\" etc.</p>\n\n<p>Note you can also move wp-config.php <strong>one</strong> directory up from where Wordpress installed it - and if this is then above Webroot/public_html it will no longer be \"directly\" accessible by hackers. More on this here <a href=\"https://wordpress.stackexchange.com/questions/58391/is-moving-wp-config-outside-the-web-root-really-beneficial\">Is moving wp-config outside the web root really beneficial?</a></p>\n" }, { "answer_id": 318296, "author": "jarrodwhitley", "author_id": 69042, "author_profile": "https://wordpress.stackexchange.com/users/69042", "pm_score": 0, "selected": false, "text": "<p>I discovered that by looking at my server's error logs I could see where the server denied permission to me when I attempted to visit <a href=\"http://example.com/wp-config.php\" rel=\"nofollow noreferrer\">http://example.com/wp-config.php</a></p>\n\n<p>It looked like this:</p>\n\n<blockquote>\n <p>[Fri Nov 02 17:52:22.222222 2018] [authz_core:error] [pid 222] [client 22.222.222.222:22222] AH01630: client denied by server configuration: /nas/wp/www/sites/example/wp-config.php</p>\n</blockquote>\n" } ]
2018/11/02
[ "https://wordpress.stackexchange.com/questions/318273", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69042/" ]
Since `order allow,deny` is deprecated in 2.4 I wanted to rewrite the rules in my .htaccess file to use the new rules. Previously I was using: ``` <files wp-config.php> order allow,deny deny from all </files> ``` Which I've rewritten to: ``` <FilesMatch "wp-config.php"> Require all denied </FilesMatch> ``` **How do I confirm that my method is actually working?** I'm not certain how hackers might gain access to this file so I don't know how to test it.
The old method works for me, and any requests result in a 403 status response instead of execution of the php script. I've not checked your 2nd method, but if it works it will similarly respond with 403 denied/forbidden. To test you simply have to insert the URL of your "wp-config.php" in the address bar of your browser e.g. <http://example.com/wp-config.php> . Depending on browser and/or sites custom 403 settings your browser will display "forbidden", "access denied" etc. Note you can also move wp-config.php **one** directory up from where Wordpress installed it - and if this is then above Webroot/public\_html it will no longer be "directly" accessible by hackers. More on this here [Is moving wp-config outside the web root really beneficial?](https://wordpress.stackexchange.com/questions/58391/is-moving-wp-config-outside-the-web-root-really-beneficial)
318,318
<p>I've made quite an extensive <code>page.php</code> using ACF-repeaters and the flexible content module (1000+ lines of code). The code is getting really spaghetti-like, and I'm not sure how to structure it so it's easier to read and maintain. </p> <p>Here's a pseudo-code-version of it:</p> <pre><code>$all_fields = get_fields(); foreach( $all_fields as $field ): if( $field == 'field_1' ): // Deal with field_1 elseif( $field == 'field_2' ): // Deal with field_2 elseif( $field == 'field_3' ): // Deal with field_3 ... ... etc. ... etc. endif; endforeach; </code></pre> <p>Now I'm facing a challenge that will require me to structure the code better; I will need another page-template (<code>page-foobar.php</code>), that includes the same ACF-code as shown above. </p> <p>On the one hand side, then I thought about making this whole thing into a (or several) functions and then sticking it in <code>functions.php</code>. But then I'm polluting the <code>functions.php</code>-file, which would suck. </p> <p>Ideally, I would do this 'the WordPress way', if there is such a thing for what I'm doing, but I haven't heard of such a thing. So if there isn't one, - then I'd prefer to have a folder in my theme called 'acf-modules', and then a file for each field, containing a function like this:</p> <pre><code>function field_1( $field_information ){ // Deal with $field_information } </code></pre> <p>But should I then make an action in <code>functions.php</code>, requiring each file upon WordPress' <code>init</code>-hook? Is that really the cleanest/best way to do this? </p>
[ { "answer_id": 318324, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>Well, structuring is partly a matter of taste, but it in this case it seems to be a good idea to include all the functions in a separate file. That includes the code that you would have in both template files. And rather than the chain of <code>elseif</code> you could use <a href=\"http://php.net/manual/en/control-structures.switch.php\" rel=\"nofollow noreferrer\">PHP's switch statement</a>. So you would have:</p>\n\n<p>In your <code>functions.php</code> (just plain, not depending on a hook)</p>\n\n<pre><code>require_once (get_template_directory() . '/field-functions.php');\n</code></pre>\n\n<p>In your template files</p>\n\n<pre><code>deal_with_fields ();\n</code></pre>\n\n<p>In your <code>field-functions.php</code></p>\n\n<pre><code>function deal_with_fields () {\n $all_fields = get_fields (); \n foreach ($all_fields as $field) {\n switch ($field) {\n case 'field_1' : deal_with_field_1 ($field); break;\n case 'field_2' : deal_with_field_2 ($field); break;\n ....\n }\n }\n }\n\nfunction deal_with_field_1 ($field) {\n do your thing;\n }\n\nfunction deal_with_field_2 ($field) .... \n</code></pre>\n" }, { "answer_id": 320434, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 0, "selected": false, "text": "<p>I just ran into the same problem again. Last time, I solve it using @cjbj's answer. This time I did something smarter, easier to deal with. </p>\n\n<p>The downside of cjbj's answer is, that if you want a <em>rendered</em> file, then the functions <code>deal_with_field_1</code> and <code>deal_with_field_2</code> doesn't really work (unless you include something inside them or does a <code>echo file_get_contents(...)</code>. </p>\n\n<p>What I did this time, was to have a switch-function in my <code>functions.php</code> and then keep all the sections in seperate files in a folder in the theme. </p>\n\n<p>The switch-function looks like this: </p>\n\n<pre><code>function custom_acf_sections( $acf_sections ){\n foreach( $acf_sections as $section ){\n switch( $section['acf_fc_layout'] ){\n case \"section_1\":\n include( $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/THEMENAME/acf-sections/section_1.php' );\n break;\n case \"section_2\":\n include( $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/THEMENAME/acf-sections/section_2.php' );\n break;\n case \"section_3\":\n include( $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/THEMENAME/acf-sections/section_3.php' );\n break;\n }\n }\n}\n</code></pre>\n\n<p>It's almost the same as @cjbj's answer, - but I didn't figure it out until I had the same problem for the second time. So I figured I would share my solution. </p>\n" } ]
2018/11/03
[ "https://wordpress.stackexchange.com/questions/318318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128304/" ]
I've made quite an extensive `page.php` using ACF-repeaters and the flexible content module (1000+ lines of code). The code is getting really spaghetti-like, and I'm not sure how to structure it so it's easier to read and maintain. Here's a pseudo-code-version of it: ``` $all_fields = get_fields(); foreach( $all_fields as $field ): if( $field == 'field_1' ): // Deal with field_1 elseif( $field == 'field_2' ): // Deal with field_2 elseif( $field == 'field_3' ): // Deal with field_3 ... ... etc. ... etc. endif; endforeach; ``` Now I'm facing a challenge that will require me to structure the code better; I will need another page-template (`page-foobar.php`), that includes the same ACF-code as shown above. On the one hand side, then I thought about making this whole thing into a (or several) functions and then sticking it in `functions.php`. But then I'm polluting the `functions.php`-file, which would suck. Ideally, I would do this 'the WordPress way', if there is such a thing for what I'm doing, but I haven't heard of such a thing. So if there isn't one, - then I'd prefer to have a folder in my theme called 'acf-modules', and then a file for each field, containing a function like this: ``` function field_1( $field_information ){ // Deal with $field_information } ``` But should I then make an action in `functions.php`, requiring each file upon WordPress' `init`-hook? Is that really the cleanest/best way to do this?
Well, structuring is partly a matter of taste, but it in this case it seems to be a good idea to include all the functions in a separate file. That includes the code that you would have in both template files. And rather than the chain of `elseif` you could use [PHP's switch statement](http://php.net/manual/en/control-structures.switch.php). So you would have: In your `functions.php` (just plain, not depending on a hook) ``` require_once (get_template_directory() . '/field-functions.php'); ``` In your template files ``` deal_with_fields (); ``` In your `field-functions.php` ``` function deal_with_fields () { $all_fields = get_fields (); foreach ($all_fields as $field) { switch ($field) { case 'field_1' : deal_with_field_1 ($field); break; case 'field_2' : deal_with_field_2 ($field); break; .... } } } function deal_with_field_1 ($field) { do your thing; } function deal_with_field_2 ($field) .... ```
318,320
<p>My <code>wp config create</code> command:</p> <pre><code>wp core config --dbname=wordpress --dbuser=wordpress --dbpass='this is not the real password' </code></pre> <p>Running it:</p> <pre><code>$ wp core config --dbname=wordpress --dbuser=wordpress --dbpass='this is not the real password' ERROR 1045 (28000): Access denied for user 'wordpress'@'localhost' (using password: YES) </code></pre> <p>Some evidence about why I think the problem is that wp-cli is trying to use the '\@localhost version' of the user I'm specifying; from the MariaDB 'monitor':</p> <pre><code>MariaDB [(none)]&gt; SELECT Host, User FROM mysql.user; +-----------+-----------+ | Host | User | +-----------+-----------+ | % | wordpress | | 127.0.0.1 | root | | ::1 | root | | localhost | | | localhost | root | +-----------+-----------+ </code></pre> <p>This didn't work either:</p> <pre><code>$ wp core config --dbhost=\% --dbname=wordpress --dbuser=wordpress --dbpass='this is not the real password' ERROR 2005 (HY000): Unknown MySQL server host '%' (8) </code></pre> <p>How can I tell wp-cli to use the '% version' of the <em>wordpress</em> user?</p> <p>A seemingly relevant GitHub issue for the <em>wp-cli</em> project:</p> <ul> <li><a href="https://github.com/wp-cli/wp-cli/issues/4505" rel="nofollow noreferrer">wp config create ERROR 1045 (28000): Access denied for user · Issue #4505 · wp-cli/wp-cli</a></li> </ul>
[ { "answer_id": 318324, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>Well, structuring is partly a matter of taste, but it in this case it seems to be a good idea to include all the functions in a separate file. That includes the code that you would have in both template files. And rather than the chain of <code>elseif</code> you could use <a href=\"http://php.net/manual/en/control-structures.switch.php\" rel=\"nofollow noreferrer\">PHP's switch statement</a>. So you would have:</p>\n\n<p>In your <code>functions.php</code> (just plain, not depending on a hook)</p>\n\n<pre><code>require_once (get_template_directory() . '/field-functions.php');\n</code></pre>\n\n<p>In your template files</p>\n\n<pre><code>deal_with_fields ();\n</code></pre>\n\n<p>In your <code>field-functions.php</code></p>\n\n<pre><code>function deal_with_fields () {\n $all_fields = get_fields (); \n foreach ($all_fields as $field) {\n switch ($field) {\n case 'field_1' : deal_with_field_1 ($field); break;\n case 'field_2' : deal_with_field_2 ($field); break;\n ....\n }\n }\n }\n\nfunction deal_with_field_1 ($field) {\n do your thing;\n }\n\nfunction deal_with_field_2 ($field) .... \n</code></pre>\n" }, { "answer_id": 320434, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 0, "selected": false, "text": "<p>I just ran into the same problem again. Last time, I solve it using @cjbj's answer. This time I did something smarter, easier to deal with. </p>\n\n<p>The downside of cjbj's answer is, that if you want a <em>rendered</em> file, then the functions <code>deal_with_field_1</code> and <code>deal_with_field_2</code> doesn't really work (unless you include something inside them or does a <code>echo file_get_contents(...)</code>. </p>\n\n<p>What I did this time, was to have a switch-function in my <code>functions.php</code> and then keep all the sections in seperate files in a folder in the theme. </p>\n\n<p>The switch-function looks like this: </p>\n\n<pre><code>function custom_acf_sections( $acf_sections ){\n foreach( $acf_sections as $section ){\n switch( $section['acf_fc_layout'] ){\n case \"section_1\":\n include( $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/THEMENAME/acf-sections/section_1.php' );\n break;\n case \"section_2\":\n include( $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/THEMENAME/acf-sections/section_2.php' );\n break;\n case \"section_3\":\n include( $_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/THEMENAME/acf-sections/section_3.php' );\n break;\n }\n }\n}\n</code></pre>\n\n<p>It's almost the same as @cjbj's answer, - but I didn't figure it out until I had the same problem for the second time. So I figured I would share my solution. </p>\n" } ]
2018/11/03
[ "https://wordpress.stackexchange.com/questions/318320", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22798/" ]
My `wp config create` command: ``` wp core config --dbname=wordpress --dbuser=wordpress --dbpass='this is not the real password' ``` Running it: ``` $ wp core config --dbname=wordpress --dbuser=wordpress --dbpass='this is not the real password' ERROR 1045 (28000): Access denied for user 'wordpress'@'localhost' (using password: YES) ``` Some evidence about why I think the problem is that wp-cli is trying to use the '\@localhost version' of the user I'm specifying; from the MariaDB 'monitor': ``` MariaDB [(none)]> SELECT Host, User FROM mysql.user; +-----------+-----------+ | Host | User | +-----------+-----------+ | % | wordpress | | 127.0.0.1 | root | | ::1 | root | | localhost | | | localhost | root | +-----------+-----------+ ``` This didn't work either: ``` $ wp core config --dbhost=\% --dbname=wordpress --dbuser=wordpress --dbpass='this is not the real password' ERROR 2005 (HY000): Unknown MySQL server host '%' (8) ``` How can I tell wp-cli to use the '% version' of the *wordpress* user? A seemingly relevant GitHub issue for the *wp-cli* project: * [wp config create ERROR 1045 (28000): Access denied for user · Issue #4505 · wp-cli/wp-cli](https://github.com/wp-cli/wp-cli/issues/4505)
Well, structuring is partly a matter of taste, but it in this case it seems to be a good idea to include all the functions in a separate file. That includes the code that you would have in both template files. And rather than the chain of `elseif` you could use [PHP's switch statement](http://php.net/manual/en/control-structures.switch.php). So you would have: In your `functions.php` (just plain, not depending on a hook) ``` require_once (get_template_directory() . '/field-functions.php'); ``` In your template files ``` deal_with_fields (); ``` In your `field-functions.php` ``` function deal_with_fields () { $all_fields = get_fields (); foreach ($all_fields as $field) { switch ($field) { case 'field_1' : deal_with_field_1 ($field); break; case 'field_2' : deal_with_field_2 ($field); break; .... } } } function deal_with_field_1 ($field) { do your thing; } function deal_with_field_2 ($field) .... ```
318,325
<p>I want to make the code to display the list of the page title in footer. I made the following code in <code>functions.php</code>:</p> <pre><code> add_action('yamada_action', 'list_page_2'); function list_page_2() { global $title_yama; $title_yama = ''; $args = array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', ); $queries_yama = new WP_Query($args); if($queries_yama-&gt;have_posts()): while ($queries_yama-&gt;have_posts()):$queries_yama-&gt;the_post(); $title_yama .= '&lt;li class="aaa"&gt;&lt;a href="' .get_permalink(). '"&gt;'.the_title().'&lt;/a&gt;&lt;/li&gt;'; endwhile; endif; wp_reset_query(); return $title_yama; } </code></pre> <p>and I inputed in <code>footer.php</code> the following code:</p> <pre><code> &lt;?php do_action('yamada_action'); ?&gt; </code></pre> <p>However, the code displays just text as title.</p> <p>How should I make the code in order to output including HTML code?</p>
[ { "answer_id": 318326, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>It seems you are <a href=\"https://wordpress.stackexchange.com/questions/265952/whats-the-difference-between-hooks-filters-and-actions\">confusing actions and filters</a> here. You are using an action. That means if you want to output some html you have to that inside the function. Now your are returning the value, but nothing is done with it.</p>\n\n<p>So in the last line of your function you should have <code>echo $title_yama</code> rather than <code>return $title_yama</code>.</p>\n\n<p>Also, in your code you are accessing a global variable <code>$title_yama</code>, which you are then erasing. That doesn't seem to make much sense.</p>\n" }, { "answer_id": 318327, "author": "yurha", "author_id": 153486, "author_profile": "https://wordpress.stackexchange.com/users/153486", "pm_score": -1, "selected": false, "text": "<p>get_permalink() returns permalink of the current post as a variable, but does not echo it out.\nTry <code>&lt;a href=\"' . echo esc_url(get_the_permalink()). '\"&gt;</code>\ninstead of</p>\n\n<pre><code>&lt;a href=\"' .get_permalink(). '\"&gt;\n</code></pre>\n" }, { "answer_id": 318357, "author": "X-MUK-625", "author_id": 129234, "author_profile": "https://wordpress.stackexchange.com/users/129234", "pm_score": 1, "selected": true, "text": "<p>Thank you very much for your advice.\nI can solve this problrems as follows.</p>\n\n<p>function.php</p>\n\n<pre><code>add_action('yamada_action', 'list_page_2');\n\nfunction list_page_2() {\n\n $title_yama = '';\n\n $args = array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n );\n $queries_yama = new WP_Query($args);\n if($queries_yama-&gt;have_posts()): while ($queries_yama-&gt;have_posts()):$queries_yama-&gt;the_post();\n $title_yama .= '&lt;li class=\"aaa\"&gt;&lt;a href=\"'.esc_url(get_the_permalink()). '\"&gt;'.get_the_title().'&lt;/a&gt;&lt;/li&gt;';\n endwhile; endif;\n wp_reset_query();\n echo $title_yama;\n}\n</code></pre>\n\n<p>footer.php</p>\n\n<pre><code> &lt;?php do_action('yamada_action'); ?&gt;\n</code></pre>\n\n<p>I fixed it as follows.</p>\n\n<ol>\n<li>delete <code>global $title_yama;</code></li>\n<li>fixed href attribute <code>get_permalink()</code> to <code>esc_url(get_the_permalink())</code></li>\n<li>fixed inside <code>&lt;a&gt;</code> tag <code>the_title()</code> to <code>get_the_title()</code></li>\n<li>fixed <code>return</code> to <code>echo</code></li>\n</ol>\n" } ]
2018/11/03
[ "https://wordpress.stackexchange.com/questions/318325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129234/" ]
I want to make the code to display the list of the page title in footer. I made the following code in `functions.php`: ``` add_action('yamada_action', 'list_page_2'); function list_page_2() { global $title_yama; $title_yama = ''; $args = array( 'post_type' => 'page', 'post_status' => 'publish', ); $queries_yama = new WP_Query($args); if($queries_yama->have_posts()): while ($queries_yama->have_posts()):$queries_yama->the_post(); $title_yama .= '<li class="aaa"><a href="' .get_permalink(). '">'.the_title().'</a></li>'; endwhile; endif; wp_reset_query(); return $title_yama; } ``` and I inputed in `footer.php` the following code: ``` <?php do_action('yamada_action'); ?> ``` However, the code displays just text as title. How should I make the code in order to output including HTML code?
Thank you very much for your advice. I can solve this problrems as follows. function.php ``` add_action('yamada_action', 'list_page_2'); function list_page_2() { $title_yama = ''; $args = array( 'post_type' => 'page', 'post_status' => 'publish', ); $queries_yama = new WP_Query($args); if($queries_yama->have_posts()): while ($queries_yama->have_posts()):$queries_yama->the_post(); $title_yama .= '<li class="aaa"><a href="'.esc_url(get_the_permalink()). '">'.get_the_title().'</a></li>'; endwhile; endif; wp_reset_query(); echo $title_yama; } ``` footer.php ``` <?php do_action('yamada_action'); ?> ``` I fixed it as follows. 1. delete `global $title_yama;` 2. fixed href attribute `get_permalink()` to `esc_url(get_the_permalink())` 3. fixed inside `<a>` tag `the_title()` to `get_the_title()` 4. fixed `return` to `echo`
318,341
<p>I'm having a little problem figuring out how to execute shortcodes stored in a mail content option of a plugin.</p> <p>The thing is, I have a field in my options page named '_message' that works with WYSIWYG Editor, and I want to save shortcodes there and then execute them before send the email.</p> <p>There is some way of detect shortcodes in strings?. Ex:</p> <p><code>$message = 'blablabla [sale_products] blablaba'; do_shortcode($message);</code></p> <p>If you have another suggestion of how can this be done, that would be great! </p>
[ { "answer_id": 318326, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>It seems you are <a href=\"https://wordpress.stackexchange.com/questions/265952/whats-the-difference-between-hooks-filters-and-actions\">confusing actions and filters</a> here. You are using an action. That means if you want to output some html you have to that inside the function. Now your are returning the value, but nothing is done with it.</p>\n\n<p>So in the last line of your function you should have <code>echo $title_yama</code> rather than <code>return $title_yama</code>.</p>\n\n<p>Also, in your code you are accessing a global variable <code>$title_yama</code>, which you are then erasing. That doesn't seem to make much sense.</p>\n" }, { "answer_id": 318327, "author": "yurha", "author_id": 153486, "author_profile": "https://wordpress.stackexchange.com/users/153486", "pm_score": -1, "selected": false, "text": "<p>get_permalink() returns permalink of the current post as a variable, but does not echo it out.\nTry <code>&lt;a href=\"' . echo esc_url(get_the_permalink()). '\"&gt;</code>\ninstead of</p>\n\n<pre><code>&lt;a href=\"' .get_permalink(). '\"&gt;\n</code></pre>\n" }, { "answer_id": 318357, "author": "X-MUK-625", "author_id": 129234, "author_profile": "https://wordpress.stackexchange.com/users/129234", "pm_score": 1, "selected": true, "text": "<p>Thank you very much for your advice.\nI can solve this problrems as follows.</p>\n\n<p>function.php</p>\n\n<pre><code>add_action('yamada_action', 'list_page_2');\n\nfunction list_page_2() {\n\n $title_yama = '';\n\n $args = array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n );\n $queries_yama = new WP_Query($args);\n if($queries_yama-&gt;have_posts()): while ($queries_yama-&gt;have_posts()):$queries_yama-&gt;the_post();\n $title_yama .= '&lt;li class=\"aaa\"&gt;&lt;a href=\"'.esc_url(get_the_permalink()). '\"&gt;'.get_the_title().'&lt;/a&gt;&lt;/li&gt;';\n endwhile; endif;\n wp_reset_query();\n echo $title_yama;\n}\n</code></pre>\n\n<p>footer.php</p>\n\n<pre><code> &lt;?php do_action('yamada_action'); ?&gt;\n</code></pre>\n\n<p>I fixed it as follows.</p>\n\n<ol>\n<li>delete <code>global $title_yama;</code></li>\n<li>fixed href attribute <code>get_permalink()</code> to <code>esc_url(get_the_permalink())</code></li>\n<li>fixed inside <code>&lt;a&gt;</code> tag <code>the_title()</code> to <code>get_the_title()</code></li>\n<li>fixed <code>return</code> to <code>echo</code></li>\n</ol>\n" } ]
2018/11/03
[ "https://wordpress.stackexchange.com/questions/318341", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153499/" ]
I'm having a little problem figuring out how to execute shortcodes stored in a mail content option of a plugin. The thing is, I have a field in my options page named '\_message' that works with WYSIWYG Editor, and I want to save shortcodes there and then execute them before send the email. There is some way of detect shortcodes in strings?. Ex: `$message = 'blablabla [sale_products] blablaba'; do_shortcode($message);` If you have another suggestion of how can this be done, that would be great!
Thank you very much for your advice. I can solve this problrems as follows. function.php ``` add_action('yamada_action', 'list_page_2'); function list_page_2() { $title_yama = ''; $args = array( 'post_type' => 'page', 'post_status' => 'publish', ); $queries_yama = new WP_Query($args); if($queries_yama->have_posts()): while ($queries_yama->have_posts()):$queries_yama->the_post(); $title_yama .= '<li class="aaa"><a href="'.esc_url(get_the_permalink()). '">'.get_the_title().'</a></li>'; endwhile; endif; wp_reset_query(); echo $title_yama; } ``` footer.php ``` <?php do_action('yamada_action'); ?> ``` I fixed it as follows. 1. delete `global $title_yama;` 2. fixed href attribute `get_permalink()` to `esc_url(get_the_permalink())` 3. fixed inside `<a>` tag `the_title()` to `get_the_title()` 4. fixed `return` to `echo`
318,361
<p>I'm setting up the wordpress for my webcomic/graphic novel and I'm just hitting a little snag when it comes to the navigation. Here's what I want, a very basic webcomic navigation scheme:</p> <p>&lt;&lt; First | &lt; Previous | Next > | Last >></p> <p>Each of these would be linking to the respective comic pages (which are seperate posts) dynamically. Ideally I wouldn't show the "Last" link on the actual latest page. </p> <p>I've been messing with these functions:</p> <p>previous_post_link(); next_post_link();</p> <p>Which show the navigation like this, for example: </p> <p>« Page 2 Page 4 » </p> <p>(With "Page 2" and "Page 4" being the post titles, when I'm on page 3)</p> <p>It's not ideal but sort of works, I guess. I'm sure there's a way to get these links to say what I want them to. It's the "Last" part that I'm really having trouble with.</p> <p>I'd prefer not to work with the Webcomic or Comic Easel plugins, if at all possible, since basic Wordpress works pretty great for what I want from it.</p>
[ { "answer_id": 318368, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>This <a href=\"https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154\" rel=\"nofollow noreferrer\">gist</a> should get you started.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Easy Pagination Deamon\nPlugin URI: http://wordpress.org/extend/plugins/stats/\nDescription: Offers the deamon_pagination($range) template tag for a sematically correct pagination.\nAuthor: Franz Josef Kaiser\nAuthor URI: http://say-hello-code.com\nVersion: 0.1\nLicense: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html\nText Domain: pagination_deamon_lang\n\nCopyright 20010-2011 by Franz Josef Kaiser\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n// ==========================================\n Styles see https://gist.github.com/818523\n// ==========================================\n\n// Secure: don't load this file directly\nif( !class_exists('WP') ) :\n header( 'Status: 403 Forbidden' );\n header( 'HTTP/1.1 403 Forbidden' );\n exit();\nendif;\n\n!defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.');\n!defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.');\n!defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.');\n\n /**\n * Register styles\n */\n if ( !is_admin() ) {\n wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' );\n }\n\n if ( !function_exists('oxo_pagination_styles') ) :\n /**\n * Print styles\n */\n function oxo_pagination_styles() {\n if ( !is_admin() )\n wp_print_styles('pagination');\n }\n endif;\n\n if ( !function_exists('oxo_pagination') ) :\n /**\n * Wordpress pagination for archives/search/etc.\n * \n * Semantically correct pagination inside an unordered list\n * \n * Displays: First « 1 2 3 4 » Last\n * First/Last only appears if not on first/last page\n * Shows next/previous links «/»\n * Accepts a range attribute (default = 5) to adjust the number\n * of direct page links that link to the pages above/below the current one.\n * \n * @param (int) $range\n */\n function oxo_pagination( $range = 5 ) {\n // $paged - number of the current page\n global $paged, $wp_query;\n // How much pages do we have?\n if ( !$max_page )\n $max_page = $wp_query-&gt;max_num_pages;\n // We need the pagination only if there is more than 1 page\n if ( $max_page &gt; 1 )\n if ( !$paged ) $paged = 1;\n\n echo \"\\n\".'&lt;ul class=\"pagination\"&gt;'.\"\\n\";\n // On the first page, don't put the First page link\n if ( $paged != 1 )\n echo '&lt;li class=\"page-num page-num-first\"&gt;&lt;a href='.get_pagenum_link(1).'&gt;'.__('First', PAGE_LANG).' &lt;/a&gt;&lt;/li&gt;';\n\n // To the previous page\n echo '&lt;li class=\"page-num page-num-prev\"&gt;';\n previous_posts_link(' &amp;laquo; '); // «\n echo '&lt;/li&gt;';\n\n // We need the sliding effect only if there are more pages than is the sliding range\n if ( $max_page &gt; $range ) :\n // When closer to the beginning\n if ( $paged &lt; $range ) :\n for ( $i = 1; $i &lt;= ($range + 1); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // When closer to the end\n elseif ( $paged &gt;= ( $max_page - ceil($range/2)) ) :\n for ( $i = $max_page - $range; $i &lt;= $max_page; $i++ ){\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n // Somewhere in the middle\n elseif ( $paged &gt;= $range &amp;&amp; $paged &lt; ( $max_page - ceil($range/2)) ) :\n for ( $i = ($paged - ceil($range/2)); $i &lt;= ($paged + ceil($range/2)); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // Less pages than the range, no sliding effect needed\n else :\n for ( $i = 1; $i &lt;= $max_page; $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n\n // Next page\n echo '&lt;li class=\"page-num page-num-next\"&gt;';\n next_posts_link(' &amp;raquo; '); // »\n echo '&lt;/li&gt;';\n\n // On the last page, don't put the Last page link\n if ( $paged != $max_page )\n echo '&lt;li class=\"page-num page-num-last\"&gt;&lt;a href='.get_pagenum_link($max_page).'&gt; '.__('Last', PAGE_LANG).'&lt;/a&gt;&lt;/li&gt;';\n\n echo \"\\n\".'&lt;/ul&gt;'.\"\\n\";\n }\n endif;\n?&gt;\n</code></pre>\n" }, { "answer_id": 318389, "author": "Harsh Barach", "author_id": 112248, "author_profile": "https://wordpress.stackexchange.com/users/112248", "pm_score": 1, "selected": false, "text": "<p>Well, it is very easy to create pagination links like <strong>First Previous..Next Last</strong>.</p>\n\n<p>You should place below code in your <code>functions.php</code>.</p>\n\n<pre><code>&lt;?php\nfunction pagination($pages = '', $range = 4)\n{ \n $showItems = ($range * 2)+1; \n\n global $paged;\n if(empty($paged)) $paged = 1;\n\n if($pages == '')\n {\n global $wp_query;\n $pages = $wp_query-&gt;max_num_pages;\n if(!$pages)\n {\n $pages = 1;\n }\n } \n\n if(1 != $pages)\n {\n\n if($paged &gt; 2 &amp;&amp; $paged &gt; $range+1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link(1).\"'&gt;&amp;laquo; First&lt;/a&gt;\";\n if($paged &gt; 1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($paged - 1).\"'&gt;&amp;lsaquo; Previous&lt;/a&gt;\";\n\n for ($i=1; $i &lt;= $pages; $i++)\n {\n if (1 != $pages &amp;&amp;( !($i &gt;= $paged+$range+1 || $i &lt;= $paged-$range-1) || $pages &lt;= $showItems ))\n {\n echo ($paged == $i)? \"&lt;span class=\\\"current\\\"&gt;\".$i.\"&lt;/span&gt;\":\"&lt;a href='\".get_pagenum_link($i).\"' class=\\\"inactive\\\"&gt;\".$i.\"&lt;/a&gt;\";\n }\n }\n\n if ($paged &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href=\\\"\".get_pagenum_link($paged + 1).\"\\\"&gt;Next &amp;rsaquo;&lt;/a&gt;\"; \n if ($paged &lt; $pages-1 &amp;&amp; $paged+$range-1 &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($pages).\"'&gt;Last &amp;raquo;&lt;/a&gt;\";\n echo \"&lt;/div&gt;\\n\";\n }\n}\n?&gt;\n</code></pre>\n\n<p>And you can call from your respective templates by placing below code.</p>\n\n<pre><code>&lt;?php\n if (function_exists(\"pagination\"))\n {\n pagination($additional_loop-&gt;max_num_pages);\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 318581, "author": "Kohlo", "author_id": 153517, "author_profile": "https://wordpress.stackexchange.com/users/153517", "pm_score": 0, "selected": false, "text": "<p>We found a somewhat easy fix, which isn't 100% perfect from the original idea but does the job well enough without figuring out a way to make the code work driving me crazy. I'll post them here just in case anyone else comes across this and wants a quick and dirty way to get a comic navigation on Wordpress without dedicated plugins.</p>\n\n<p>For single posts:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; |\n &lt;?php next_post_link('%link', 'Next &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;'); ?&gt; |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>For main page:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; | Current |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>The one snag we hit here is that if you're on the first or last post, it'll show 2 pipes next to each other as the previous/next links aren't shown there, which is something I can live with for now. If this bothers you, the pipes are optional so they can be removed completely to show the navigation as:\n&lt;&lt; First &lt; Previous Next > Last >></p>\n" } ]
2018/11/04
[ "https://wordpress.stackexchange.com/questions/318361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153517/" ]
I'm setting up the wordpress for my webcomic/graphic novel and I'm just hitting a little snag when it comes to the navigation. Here's what I want, a very basic webcomic navigation scheme: << First | < Previous | Next > | Last >> Each of these would be linking to the respective comic pages (which are seperate posts) dynamically. Ideally I wouldn't show the "Last" link on the actual latest page. I've been messing with these functions: previous\_post\_link(); next\_post\_link(); Which show the navigation like this, for example: « Page 2 Page 4 » (With "Page 2" and "Page 4" being the post titles, when I'm on page 3) It's not ideal but sort of works, I guess. I'm sure there's a way to get these links to say what I want them to. It's the "Last" part that I'm really having trouble with. I'd prefer not to work with the Webcomic or Comic Easel plugins, if at all possible, since basic Wordpress works pretty great for what I want from it.
This [gist](https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154) should get you started. ``` <?php /* Plugin Name: Easy Pagination Deamon Plugin URI: http://wordpress.org/extend/plugins/stats/ Description: Offers the deamon_pagination($range) template tag for a sematically correct pagination. Author: Franz Josef Kaiser Author URI: http://say-hello-code.com Version: 0.1 License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html Text Domain: pagination_deamon_lang Copyright 20010-2011 by Franz Josef Kaiser This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 */ // ========================================== Styles see https://gist.github.com/818523 // ========================================== // Secure: don't load this file directly if( !class_exists('WP') ) : header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); endif; !defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.'); !defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.'); !defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.'); /** * Register styles */ if ( !is_admin() ) { wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' ); } if ( !function_exists('oxo_pagination_styles') ) : /** * Print styles */ function oxo_pagination_styles() { if ( !is_admin() ) wp_print_styles('pagination'); } endif; if ( !function_exists('oxo_pagination') ) : /** * Wordpress pagination for archives/search/etc. * * Semantically correct pagination inside an unordered list * * Displays: First « 1 2 3 4 » Last * First/Last only appears if not on first/last page * Shows next/previous links «/» * Accepts a range attribute (default = 5) to adjust the number * of direct page links that link to the pages above/below the current one. * * @param (int) $range */ function oxo_pagination( $range = 5 ) { // $paged - number of the current page global $paged, $wp_query; // How much pages do we have? if ( !$max_page ) $max_page = $wp_query->max_num_pages; // We need the pagination only if there is more than 1 page if ( $max_page > 1 ) if ( !$paged ) $paged = 1; echo "\n".'<ul class="pagination">'."\n"; // On the first page, don't put the First page link if ( $paged != 1 ) echo '<li class="page-num page-num-first"><a href='.get_pagenum_link(1).'>'.__('First', PAGE_LANG).' </a></li>'; // To the previous page echo '<li class="page-num page-num-prev">'; previous_posts_link(' &laquo; '); // « echo '</li>'; // We need the sliding effect only if there are more pages than is the sliding range if ( $max_page > $range ) : // When closer to the beginning if ( $paged < $range ) : for ( $i = 1; $i <= ($range + 1); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // When closer to the end elseif ( $paged >= ( $max_page - ceil($range/2)) ) : for ( $i = $max_page - $range; $i <= $max_page; $i++ ){ $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Somewhere in the middle elseif ( $paged >= $range && $paged < ( $max_page - ceil($range/2)) ) : for ( $i = ($paged - ceil($range/2)); $i <= ($paged + ceil($range/2)); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // Less pages than the range, no sliding effect needed else : for ( $i = 1; $i <= $max_page; $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Next page echo '<li class="page-num page-num-next">'; next_posts_link(' &raquo; '); // » echo '</li>'; // On the last page, don't put the Last page link if ( $paged != $max_page ) echo '<li class="page-num page-num-last"><a href='.get_pagenum_link($max_page).'> '.__('Last', PAGE_LANG).'</a></li>'; echo "\n".'</ul>'."\n"; } endif; ?> ```
318,411
<p>I have two Custom post types: <strong>question</strong> and <strong>answer</strong>. "Questions" are hierarchical and they are parent posts for answers - which are child posts. For every answer, there's a parent question. When someone asks a question, every answer given is correctly attributed to the same question. This has already been nicely done in the website. While I am building the APP, I can pull in all questions, but when it comes to answers, I can't seem to filter out answer by parent question.</p> <p>All questions can be obtained like this: <a href="https://domain.com/wp-json/wp/v2/questions" rel="nofollow noreferrer">https://domain.com/wp-json/wp/v2/questions</a></p> <p>For answers, I am using custom endpoint with this code:</p> <pre><code>add_action( 'rest_api_init', 'custom_api_get_all_posts' ); function custom_api_get_all_posts() { register_rest_route( 'app/v1', '/answers', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'custom_api_get_all_posts_callback' )); } function custom_api_get_all_posts_callback( $request ) { // Initialize the array that will receive the posts' data. $posts_data = array(); // Receive and set the page parameter from the $request for pagination purposes $paged = $request-&gt;get_param( 'page' ); $paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1; // Get the posts using the 'post' and 'news' post types // $avatar_url = get_avatar_url ( get_the_author_meta('ID'), $size = '50' ); $posts = get_posts( array( 'paged' =&gt; $paged, 'posts_per_page' =&gt; 10, 'post_type' =&gt; 'answer', )); if ( is_array( $filter ) &amp;&amp; array_key_exists( 'question', $filter ) ) { $args['post_parent_id'] = $filter['question']; } // Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object foreach( $posts as $post ) { $id = $post-&gt;ID; $posts_data[] = (object) array( 'id' =&gt; $id, 'slug' =&gt; $post-&gt;post_name, 'type' =&gt; $post-&gt;post_type, 'title' =&gt; $post-&gt;post_title, 'content' =&gt; $post-&gt;post_content, 'question' =&gt; $post-&gt;post_parent, ); } return $posts_data; } </code></pre> <p>And by this, I can get all answers with their IDs, Answer Title, Content, and Parent Question Id in GET response at <a href="https://domain.com/wp-json/app/v1/answers" rel="nofollow noreferrer">https://domain.com/wp-json/app/v1/answers</a></p> <p><strong>QUESTION</strong>: How do I have to modify the code to be able to filter out specific answers based on question ID, something like: <a href="https://domain.com/wp-json/app/v1/answers?question=1234" rel="nofollow noreferrer">https://domain.com/wp-json/app/v1/answers?question=1234</a> where 1234 is an ID for a parent question whose answers we need to display. All suggested filter plugins have failed to work, I've tried different forms of codes for so many hours, I really appreciate your help :)</p> <p>Thanks! (Both question and answer are CPTs, and I am using WP Version - 4.9.8)</p>
[ { "answer_id": 318368, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>This <a href=\"https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154\" rel=\"nofollow noreferrer\">gist</a> should get you started.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Easy Pagination Deamon\nPlugin URI: http://wordpress.org/extend/plugins/stats/\nDescription: Offers the deamon_pagination($range) template tag for a sematically correct pagination.\nAuthor: Franz Josef Kaiser\nAuthor URI: http://say-hello-code.com\nVersion: 0.1\nLicense: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html\nText Domain: pagination_deamon_lang\n\nCopyright 20010-2011 by Franz Josef Kaiser\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n// ==========================================\n Styles see https://gist.github.com/818523\n// ==========================================\n\n// Secure: don't load this file directly\nif( !class_exists('WP') ) :\n header( 'Status: 403 Forbidden' );\n header( 'HTTP/1.1 403 Forbidden' );\n exit();\nendif;\n\n!defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.');\n!defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.');\n!defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.');\n\n /**\n * Register styles\n */\n if ( !is_admin() ) {\n wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' );\n }\n\n if ( !function_exists('oxo_pagination_styles') ) :\n /**\n * Print styles\n */\n function oxo_pagination_styles() {\n if ( !is_admin() )\n wp_print_styles('pagination');\n }\n endif;\n\n if ( !function_exists('oxo_pagination') ) :\n /**\n * Wordpress pagination for archives/search/etc.\n * \n * Semantically correct pagination inside an unordered list\n * \n * Displays: First « 1 2 3 4 » Last\n * First/Last only appears if not on first/last page\n * Shows next/previous links «/»\n * Accepts a range attribute (default = 5) to adjust the number\n * of direct page links that link to the pages above/below the current one.\n * \n * @param (int) $range\n */\n function oxo_pagination( $range = 5 ) {\n // $paged - number of the current page\n global $paged, $wp_query;\n // How much pages do we have?\n if ( !$max_page )\n $max_page = $wp_query-&gt;max_num_pages;\n // We need the pagination only if there is more than 1 page\n if ( $max_page &gt; 1 )\n if ( !$paged ) $paged = 1;\n\n echo \"\\n\".'&lt;ul class=\"pagination\"&gt;'.\"\\n\";\n // On the first page, don't put the First page link\n if ( $paged != 1 )\n echo '&lt;li class=\"page-num page-num-first\"&gt;&lt;a href='.get_pagenum_link(1).'&gt;'.__('First', PAGE_LANG).' &lt;/a&gt;&lt;/li&gt;';\n\n // To the previous page\n echo '&lt;li class=\"page-num page-num-prev\"&gt;';\n previous_posts_link(' &amp;laquo; '); // «\n echo '&lt;/li&gt;';\n\n // We need the sliding effect only if there are more pages than is the sliding range\n if ( $max_page &gt; $range ) :\n // When closer to the beginning\n if ( $paged &lt; $range ) :\n for ( $i = 1; $i &lt;= ($range + 1); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // When closer to the end\n elseif ( $paged &gt;= ( $max_page - ceil($range/2)) ) :\n for ( $i = $max_page - $range; $i &lt;= $max_page; $i++ ){\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n // Somewhere in the middle\n elseif ( $paged &gt;= $range &amp;&amp; $paged &lt; ( $max_page - ceil($range/2)) ) :\n for ( $i = ($paged - ceil($range/2)); $i &lt;= ($paged + ceil($range/2)); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // Less pages than the range, no sliding effect needed\n else :\n for ( $i = 1; $i &lt;= $max_page; $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n\n // Next page\n echo '&lt;li class=\"page-num page-num-next\"&gt;';\n next_posts_link(' &amp;raquo; '); // »\n echo '&lt;/li&gt;';\n\n // On the last page, don't put the Last page link\n if ( $paged != $max_page )\n echo '&lt;li class=\"page-num page-num-last\"&gt;&lt;a href='.get_pagenum_link($max_page).'&gt; '.__('Last', PAGE_LANG).'&lt;/a&gt;&lt;/li&gt;';\n\n echo \"\\n\".'&lt;/ul&gt;'.\"\\n\";\n }\n endif;\n?&gt;\n</code></pre>\n" }, { "answer_id": 318389, "author": "Harsh Barach", "author_id": 112248, "author_profile": "https://wordpress.stackexchange.com/users/112248", "pm_score": 1, "selected": false, "text": "<p>Well, it is very easy to create pagination links like <strong>First Previous..Next Last</strong>.</p>\n\n<p>You should place below code in your <code>functions.php</code>.</p>\n\n<pre><code>&lt;?php\nfunction pagination($pages = '', $range = 4)\n{ \n $showItems = ($range * 2)+1; \n\n global $paged;\n if(empty($paged)) $paged = 1;\n\n if($pages == '')\n {\n global $wp_query;\n $pages = $wp_query-&gt;max_num_pages;\n if(!$pages)\n {\n $pages = 1;\n }\n } \n\n if(1 != $pages)\n {\n\n if($paged &gt; 2 &amp;&amp; $paged &gt; $range+1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link(1).\"'&gt;&amp;laquo; First&lt;/a&gt;\";\n if($paged &gt; 1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($paged - 1).\"'&gt;&amp;lsaquo; Previous&lt;/a&gt;\";\n\n for ($i=1; $i &lt;= $pages; $i++)\n {\n if (1 != $pages &amp;&amp;( !($i &gt;= $paged+$range+1 || $i &lt;= $paged-$range-1) || $pages &lt;= $showItems ))\n {\n echo ($paged == $i)? \"&lt;span class=\\\"current\\\"&gt;\".$i.\"&lt;/span&gt;\":\"&lt;a href='\".get_pagenum_link($i).\"' class=\\\"inactive\\\"&gt;\".$i.\"&lt;/a&gt;\";\n }\n }\n\n if ($paged &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href=\\\"\".get_pagenum_link($paged + 1).\"\\\"&gt;Next &amp;rsaquo;&lt;/a&gt;\"; \n if ($paged &lt; $pages-1 &amp;&amp; $paged+$range-1 &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($pages).\"'&gt;Last &amp;raquo;&lt;/a&gt;\";\n echo \"&lt;/div&gt;\\n\";\n }\n}\n?&gt;\n</code></pre>\n\n<p>And you can call from your respective templates by placing below code.</p>\n\n<pre><code>&lt;?php\n if (function_exists(\"pagination\"))\n {\n pagination($additional_loop-&gt;max_num_pages);\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 318581, "author": "Kohlo", "author_id": 153517, "author_profile": "https://wordpress.stackexchange.com/users/153517", "pm_score": 0, "selected": false, "text": "<p>We found a somewhat easy fix, which isn't 100% perfect from the original idea but does the job well enough without figuring out a way to make the code work driving me crazy. I'll post them here just in case anyone else comes across this and wants a quick and dirty way to get a comic navigation on Wordpress without dedicated plugins.</p>\n\n<p>For single posts:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; |\n &lt;?php next_post_link('%link', 'Next &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;'); ?&gt; |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>For main page:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; | Current |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>The one snag we hit here is that if you're on the first or last post, it'll show 2 pipes next to each other as the previous/next links aren't shown there, which is something I can live with for now. If this bothers you, the pipes are optional so they can be removed completely to show the navigation as:\n&lt;&lt; First &lt; Previous Next > Last >></p>\n" } ]
2018/11/04
[ "https://wordpress.stackexchange.com/questions/318411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113108/" ]
I have two Custom post types: **question** and **answer**. "Questions" are hierarchical and they are parent posts for answers - which are child posts. For every answer, there's a parent question. When someone asks a question, every answer given is correctly attributed to the same question. This has already been nicely done in the website. While I am building the APP, I can pull in all questions, but when it comes to answers, I can't seem to filter out answer by parent question. All questions can be obtained like this: <https://domain.com/wp-json/wp/v2/questions> For answers, I am using custom endpoint with this code: ``` add_action( 'rest_api_init', 'custom_api_get_all_posts' ); function custom_api_get_all_posts() { register_rest_route( 'app/v1', '/answers', array( 'methods' => 'GET', 'callback' => 'custom_api_get_all_posts_callback' )); } function custom_api_get_all_posts_callback( $request ) { // Initialize the array that will receive the posts' data. $posts_data = array(); // Receive and set the page parameter from the $request for pagination purposes $paged = $request->get_param( 'page' ); $paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1; // Get the posts using the 'post' and 'news' post types // $avatar_url = get_avatar_url ( get_the_author_meta('ID'), $size = '50' ); $posts = get_posts( array( 'paged' => $paged, 'posts_per_page' => 10, 'post_type' => 'answer', )); if ( is_array( $filter ) && array_key_exists( 'question', $filter ) ) { $args['post_parent_id'] = $filter['question']; } // Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object foreach( $posts as $post ) { $id = $post->ID; $posts_data[] = (object) array( 'id' => $id, 'slug' => $post->post_name, 'type' => $post->post_type, 'title' => $post->post_title, 'content' => $post->post_content, 'question' => $post->post_parent, ); } return $posts_data; } ``` And by this, I can get all answers with their IDs, Answer Title, Content, and Parent Question Id in GET response at <https://domain.com/wp-json/app/v1/answers> **QUESTION**: How do I have to modify the code to be able to filter out specific answers based on question ID, something like: <https://domain.com/wp-json/app/v1/answers?question=1234> where 1234 is an ID for a parent question whose answers we need to display. All suggested filter plugins have failed to work, I've tried different forms of codes for so many hours, I really appreciate your help :) Thanks! (Both question and answer are CPTs, and I am using WP Version - 4.9.8)
This [gist](https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154) should get you started. ``` <?php /* Plugin Name: Easy Pagination Deamon Plugin URI: http://wordpress.org/extend/plugins/stats/ Description: Offers the deamon_pagination($range) template tag for a sematically correct pagination. Author: Franz Josef Kaiser Author URI: http://say-hello-code.com Version: 0.1 License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html Text Domain: pagination_deamon_lang Copyright 20010-2011 by Franz Josef Kaiser This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 */ // ========================================== Styles see https://gist.github.com/818523 // ========================================== // Secure: don't load this file directly if( !class_exists('WP') ) : header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); endif; !defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.'); !defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.'); !defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.'); /** * Register styles */ if ( !is_admin() ) { wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' ); } if ( !function_exists('oxo_pagination_styles') ) : /** * Print styles */ function oxo_pagination_styles() { if ( !is_admin() ) wp_print_styles('pagination'); } endif; if ( !function_exists('oxo_pagination') ) : /** * Wordpress pagination for archives/search/etc. * * Semantically correct pagination inside an unordered list * * Displays: First « 1 2 3 4 » Last * First/Last only appears if not on first/last page * Shows next/previous links «/» * Accepts a range attribute (default = 5) to adjust the number * of direct page links that link to the pages above/below the current one. * * @param (int) $range */ function oxo_pagination( $range = 5 ) { // $paged - number of the current page global $paged, $wp_query; // How much pages do we have? if ( !$max_page ) $max_page = $wp_query->max_num_pages; // We need the pagination only if there is more than 1 page if ( $max_page > 1 ) if ( !$paged ) $paged = 1; echo "\n".'<ul class="pagination">'."\n"; // On the first page, don't put the First page link if ( $paged != 1 ) echo '<li class="page-num page-num-first"><a href='.get_pagenum_link(1).'>'.__('First', PAGE_LANG).' </a></li>'; // To the previous page echo '<li class="page-num page-num-prev">'; previous_posts_link(' &laquo; '); // « echo '</li>'; // We need the sliding effect only if there are more pages than is the sliding range if ( $max_page > $range ) : // When closer to the beginning if ( $paged < $range ) : for ( $i = 1; $i <= ($range + 1); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // When closer to the end elseif ( $paged >= ( $max_page - ceil($range/2)) ) : for ( $i = $max_page - $range; $i <= $max_page; $i++ ){ $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Somewhere in the middle elseif ( $paged >= $range && $paged < ( $max_page - ceil($range/2)) ) : for ( $i = ($paged - ceil($range/2)); $i <= ($paged + ceil($range/2)); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // Less pages than the range, no sliding effect needed else : for ( $i = 1; $i <= $max_page; $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Next page echo '<li class="page-num page-num-next">'; next_posts_link(' &raquo; '); // » echo '</li>'; // On the last page, don't put the Last page link if ( $paged != $max_page ) echo '<li class="page-num page-num-last"><a href='.get_pagenum_link($max_page).'> '.__('Last', PAGE_LANG).'</a></li>'; echo "\n".'</ul>'."\n"; } endif; ?> ```
318,431
<p>When I'm trying to sort my blog posts or my woocommerce in alphabetical order nothing changes. If I access the /?orderby=title-asc or ?orderby=title-desc it brings me the same results.</p> <p>Any sugestions?</p>
[ { "answer_id": 318368, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>This <a href=\"https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154\" rel=\"nofollow noreferrer\">gist</a> should get you started.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Easy Pagination Deamon\nPlugin URI: http://wordpress.org/extend/plugins/stats/\nDescription: Offers the deamon_pagination($range) template tag for a sematically correct pagination.\nAuthor: Franz Josef Kaiser\nAuthor URI: http://say-hello-code.com\nVersion: 0.1\nLicense: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html\nText Domain: pagination_deamon_lang\n\nCopyright 20010-2011 by Franz Josef Kaiser\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n// ==========================================\n Styles see https://gist.github.com/818523\n// ==========================================\n\n// Secure: don't load this file directly\nif( !class_exists('WP') ) :\n header( 'Status: 403 Forbidden' );\n header( 'HTTP/1.1 403 Forbidden' );\n exit();\nendif;\n\n!defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.');\n!defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.');\n!defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.');\n\n /**\n * Register styles\n */\n if ( !is_admin() ) {\n wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' );\n }\n\n if ( !function_exists('oxo_pagination_styles') ) :\n /**\n * Print styles\n */\n function oxo_pagination_styles() {\n if ( !is_admin() )\n wp_print_styles('pagination');\n }\n endif;\n\n if ( !function_exists('oxo_pagination') ) :\n /**\n * Wordpress pagination for archives/search/etc.\n * \n * Semantically correct pagination inside an unordered list\n * \n * Displays: First « 1 2 3 4 » Last\n * First/Last only appears if not on first/last page\n * Shows next/previous links «/»\n * Accepts a range attribute (default = 5) to adjust the number\n * of direct page links that link to the pages above/below the current one.\n * \n * @param (int) $range\n */\n function oxo_pagination( $range = 5 ) {\n // $paged - number of the current page\n global $paged, $wp_query;\n // How much pages do we have?\n if ( !$max_page )\n $max_page = $wp_query-&gt;max_num_pages;\n // We need the pagination only if there is more than 1 page\n if ( $max_page &gt; 1 )\n if ( !$paged ) $paged = 1;\n\n echo \"\\n\".'&lt;ul class=\"pagination\"&gt;'.\"\\n\";\n // On the first page, don't put the First page link\n if ( $paged != 1 )\n echo '&lt;li class=\"page-num page-num-first\"&gt;&lt;a href='.get_pagenum_link(1).'&gt;'.__('First', PAGE_LANG).' &lt;/a&gt;&lt;/li&gt;';\n\n // To the previous page\n echo '&lt;li class=\"page-num page-num-prev\"&gt;';\n previous_posts_link(' &amp;laquo; '); // «\n echo '&lt;/li&gt;';\n\n // We need the sliding effect only if there are more pages than is the sliding range\n if ( $max_page &gt; $range ) :\n // When closer to the beginning\n if ( $paged &lt; $range ) :\n for ( $i = 1; $i &lt;= ($range + 1); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // When closer to the end\n elseif ( $paged &gt;= ( $max_page - ceil($range/2)) ) :\n for ( $i = $max_page - $range; $i &lt;= $max_page; $i++ ){\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n // Somewhere in the middle\n elseif ( $paged &gt;= $range &amp;&amp; $paged &lt; ( $max_page - ceil($range/2)) ) :\n for ( $i = ($paged - ceil($range/2)); $i &lt;= ($paged + ceil($range/2)); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // Less pages than the range, no sliding effect needed\n else :\n for ( $i = 1; $i &lt;= $max_page; $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n\n // Next page\n echo '&lt;li class=\"page-num page-num-next\"&gt;';\n next_posts_link(' &amp;raquo; '); // »\n echo '&lt;/li&gt;';\n\n // On the last page, don't put the Last page link\n if ( $paged != $max_page )\n echo '&lt;li class=\"page-num page-num-last\"&gt;&lt;a href='.get_pagenum_link($max_page).'&gt; '.__('Last', PAGE_LANG).'&lt;/a&gt;&lt;/li&gt;';\n\n echo \"\\n\".'&lt;/ul&gt;'.\"\\n\";\n }\n endif;\n?&gt;\n</code></pre>\n" }, { "answer_id": 318389, "author": "Harsh Barach", "author_id": 112248, "author_profile": "https://wordpress.stackexchange.com/users/112248", "pm_score": 1, "selected": false, "text": "<p>Well, it is very easy to create pagination links like <strong>First Previous..Next Last</strong>.</p>\n\n<p>You should place below code in your <code>functions.php</code>.</p>\n\n<pre><code>&lt;?php\nfunction pagination($pages = '', $range = 4)\n{ \n $showItems = ($range * 2)+1; \n\n global $paged;\n if(empty($paged)) $paged = 1;\n\n if($pages == '')\n {\n global $wp_query;\n $pages = $wp_query-&gt;max_num_pages;\n if(!$pages)\n {\n $pages = 1;\n }\n } \n\n if(1 != $pages)\n {\n\n if($paged &gt; 2 &amp;&amp; $paged &gt; $range+1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link(1).\"'&gt;&amp;laquo; First&lt;/a&gt;\";\n if($paged &gt; 1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($paged - 1).\"'&gt;&amp;lsaquo; Previous&lt;/a&gt;\";\n\n for ($i=1; $i &lt;= $pages; $i++)\n {\n if (1 != $pages &amp;&amp;( !($i &gt;= $paged+$range+1 || $i &lt;= $paged-$range-1) || $pages &lt;= $showItems ))\n {\n echo ($paged == $i)? \"&lt;span class=\\\"current\\\"&gt;\".$i.\"&lt;/span&gt;\":\"&lt;a href='\".get_pagenum_link($i).\"' class=\\\"inactive\\\"&gt;\".$i.\"&lt;/a&gt;\";\n }\n }\n\n if ($paged &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href=\\\"\".get_pagenum_link($paged + 1).\"\\\"&gt;Next &amp;rsaquo;&lt;/a&gt;\"; \n if ($paged &lt; $pages-1 &amp;&amp; $paged+$range-1 &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($pages).\"'&gt;Last &amp;raquo;&lt;/a&gt;\";\n echo \"&lt;/div&gt;\\n\";\n }\n}\n?&gt;\n</code></pre>\n\n<p>And you can call from your respective templates by placing below code.</p>\n\n<pre><code>&lt;?php\n if (function_exists(\"pagination\"))\n {\n pagination($additional_loop-&gt;max_num_pages);\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 318581, "author": "Kohlo", "author_id": 153517, "author_profile": "https://wordpress.stackexchange.com/users/153517", "pm_score": 0, "selected": false, "text": "<p>We found a somewhat easy fix, which isn't 100% perfect from the original idea but does the job well enough without figuring out a way to make the code work driving me crazy. I'll post them here just in case anyone else comes across this and wants a quick and dirty way to get a comic navigation on Wordpress without dedicated plugins.</p>\n\n<p>For single posts:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; |\n &lt;?php next_post_link('%link', 'Next &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;'); ?&gt; |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>For main page:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; | Current |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>The one snag we hit here is that if you're on the first or last post, it'll show 2 pipes next to each other as the previous/next links aren't shown there, which is something I can live with for now. If this bothers you, the pipes are optional so they can be removed completely to show the navigation as:\n&lt;&lt; First &lt; Previous Next > Last >></p>\n" } ]
2018/11/05
[ "https://wordpress.stackexchange.com/questions/318431", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147952/" ]
When I'm trying to sort my blog posts or my woocommerce in alphabetical order nothing changes. If I access the /?orderby=title-asc or ?orderby=title-desc it brings me the same results. Any sugestions?
This [gist](https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154) should get you started. ``` <?php /* Plugin Name: Easy Pagination Deamon Plugin URI: http://wordpress.org/extend/plugins/stats/ Description: Offers the deamon_pagination($range) template tag for a sematically correct pagination. Author: Franz Josef Kaiser Author URI: http://say-hello-code.com Version: 0.1 License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html Text Domain: pagination_deamon_lang Copyright 20010-2011 by Franz Josef Kaiser This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 */ // ========================================== Styles see https://gist.github.com/818523 // ========================================== // Secure: don't load this file directly if( !class_exists('WP') ) : header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); endif; !defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.'); !defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.'); !defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.'); /** * Register styles */ if ( !is_admin() ) { wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' ); } if ( !function_exists('oxo_pagination_styles') ) : /** * Print styles */ function oxo_pagination_styles() { if ( !is_admin() ) wp_print_styles('pagination'); } endif; if ( !function_exists('oxo_pagination') ) : /** * Wordpress pagination for archives/search/etc. * * Semantically correct pagination inside an unordered list * * Displays: First « 1 2 3 4 » Last * First/Last only appears if not on first/last page * Shows next/previous links «/» * Accepts a range attribute (default = 5) to adjust the number * of direct page links that link to the pages above/below the current one. * * @param (int) $range */ function oxo_pagination( $range = 5 ) { // $paged - number of the current page global $paged, $wp_query; // How much pages do we have? if ( !$max_page ) $max_page = $wp_query->max_num_pages; // We need the pagination only if there is more than 1 page if ( $max_page > 1 ) if ( !$paged ) $paged = 1; echo "\n".'<ul class="pagination">'."\n"; // On the first page, don't put the First page link if ( $paged != 1 ) echo '<li class="page-num page-num-first"><a href='.get_pagenum_link(1).'>'.__('First', PAGE_LANG).' </a></li>'; // To the previous page echo '<li class="page-num page-num-prev">'; previous_posts_link(' &laquo; '); // « echo '</li>'; // We need the sliding effect only if there are more pages than is the sliding range if ( $max_page > $range ) : // When closer to the beginning if ( $paged < $range ) : for ( $i = 1; $i <= ($range + 1); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // When closer to the end elseif ( $paged >= ( $max_page - ceil($range/2)) ) : for ( $i = $max_page - $range; $i <= $max_page; $i++ ){ $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Somewhere in the middle elseif ( $paged >= $range && $paged < ( $max_page - ceil($range/2)) ) : for ( $i = ($paged - ceil($range/2)); $i <= ($paged + ceil($range/2)); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // Less pages than the range, no sliding effect needed else : for ( $i = 1; $i <= $max_page; $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Next page echo '<li class="page-num page-num-next">'; next_posts_link(' &raquo; '); // » echo '</li>'; // On the last page, don't put the Last page link if ( $paged != $max_page ) echo '<li class="page-num page-num-last"><a href='.get_pagenum_link($max_page).'> '.__('Last', PAGE_LANG).'</a></li>'; echo "\n".'</ul>'."\n"; } endif; ?> ```
318,444
<p>I am using Automattic's plugin to implement AMP on my website. Currently, to make my videos responsive, I wrap YouTube videos around a custom div. So, a YouTube video on my website looks like this:-</p> <pre><code>&lt;div class="yt"&gt; &lt;iframe&gt;....YT video code...&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>The problem is the <code>&lt;div class="yt"&gt;</code> and the closing <code>&lt;/div&gt;</code> both appear on the AMP pages too. How can I remove them? Already tried asking on the official support. No replies yet.</p>
[ { "answer_id": 318368, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>This <a href=\"https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154\" rel=\"nofollow noreferrer\">gist</a> should get you started.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Easy Pagination Deamon\nPlugin URI: http://wordpress.org/extend/plugins/stats/\nDescription: Offers the deamon_pagination($range) template tag for a sematically correct pagination.\nAuthor: Franz Josef Kaiser\nAuthor URI: http://say-hello-code.com\nVersion: 0.1\nLicense: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html\nText Domain: pagination_deamon_lang\n\nCopyright 20010-2011 by Franz Josef Kaiser\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n// ==========================================\n Styles see https://gist.github.com/818523\n// ==========================================\n\n// Secure: don't load this file directly\nif( !class_exists('WP') ) :\n header( 'Status: 403 Forbidden' );\n header( 'HTTP/1.1 403 Forbidden' );\n exit();\nendif;\n\n!defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.');\n!defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.');\n!defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.');\n\n /**\n * Register styles\n */\n if ( !is_admin() ) {\n wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' );\n }\n\n if ( !function_exists('oxo_pagination_styles') ) :\n /**\n * Print styles\n */\n function oxo_pagination_styles() {\n if ( !is_admin() )\n wp_print_styles('pagination');\n }\n endif;\n\n if ( !function_exists('oxo_pagination') ) :\n /**\n * Wordpress pagination for archives/search/etc.\n * \n * Semantically correct pagination inside an unordered list\n * \n * Displays: First « 1 2 3 4 » Last\n * First/Last only appears if not on first/last page\n * Shows next/previous links «/»\n * Accepts a range attribute (default = 5) to adjust the number\n * of direct page links that link to the pages above/below the current one.\n * \n * @param (int) $range\n */\n function oxo_pagination( $range = 5 ) {\n // $paged - number of the current page\n global $paged, $wp_query;\n // How much pages do we have?\n if ( !$max_page )\n $max_page = $wp_query-&gt;max_num_pages;\n // We need the pagination only if there is more than 1 page\n if ( $max_page &gt; 1 )\n if ( !$paged ) $paged = 1;\n\n echo \"\\n\".'&lt;ul class=\"pagination\"&gt;'.\"\\n\";\n // On the first page, don't put the First page link\n if ( $paged != 1 )\n echo '&lt;li class=\"page-num page-num-first\"&gt;&lt;a href='.get_pagenum_link(1).'&gt;'.__('First', PAGE_LANG).' &lt;/a&gt;&lt;/li&gt;';\n\n // To the previous page\n echo '&lt;li class=\"page-num page-num-prev\"&gt;';\n previous_posts_link(' &amp;laquo; '); // «\n echo '&lt;/li&gt;';\n\n // We need the sliding effect only if there are more pages than is the sliding range\n if ( $max_page &gt; $range ) :\n // When closer to the beginning\n if ( $paged &lt; $range ) :\n for ( $i = 1; $i &lt;= ($range + 1); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // When closer to the end\n elseif ( $paged &gt;= ( $max_page - ceil($range/2)) ) :\n for ( $i = $max_page - $range; $i &lt;= $max_page; $i++ ){\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n // Somewhere in the middle\n elseif ( $paged &gt;= $range &amp;&amp; $paged &lt; ( $max_page - ceil($range/2)) ) :\n for ( $i = ($paged - ceil($range/2)); $i &lt;= ($paged + ceil($range/2)); $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n // Less pages than the range, no sliding effect needed\n else :\n for ( $i = 1; $i &lt;= $max_page; $i++ ) {\n $class = $i == $paged ? 'current' : '';\n echo '&lt;li class=\"page-num\"&gt;&lt;a class=\"paged-num-link '.$class.'\" href=\"'.get_pagenum_link($i).'\"&gt; '.$i.' &lt;/a&gt;&lt;/li&gt;';\n }\n endif;\n\n // Next page\n echo '&lt;li class=\"page-num page-num-next\"&gt;';\n next_posts_link(' &amp;raquo; '); // »\n echo '&lt;/li&gt;';\n\n // On the last page, don't put the Last page link\n if ( $paged != $max_page )\n echo '&lt;li class=\"page-num page-num-last\"&gt;&lt;a href='.get_pagenum_link($max_page).'&gt; '.__('Last', PAGE_LANG).'&lt;/a&gt;&lt;/li&gt;';\n\n echo \"\\n\".'&lt;/ul&gt;'.\"\\n\";\n }\n endif;\n?&gt;\n</code></pre>\n" }, { "answer_id": 318389, "author": "Harsh Barach", "author_id": 112248, "author_profile": "https://wordpress.stackexchange.com/users/112248", "pm_score": 1, "selected": false, "text": "<p>Well, it is very easy to create pagination links like <strong>First Previous..Next Last</strong>.</p>\n\n<p>You should place below code in your <code>functions.php</code>.</p>\n\n<pre><code>&lt;?php\nfunction pagination($pages = '', $range = 4)\n{ \n $showItems = ($range * 2)+1; \n\n global $paged;\n if(empty($paged)) $paged = 1;\n\n if($pages == '')\n {\n global $wp_query;\n $pages = $wp_query-&gt;max_num_pages;\n if(!$pages)\n {\n $pages = 1;\n }\n } \n\n if(1 != $pages)\n {\n\n if($paged &gt; 2 &amp;&amp; $paged &gt; $range+1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link(1).\"'&gt;&amp;laquo; First&lt;/a&gt;\";\n if($paged &gt; 1 &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($paged - 1).\"'&gt;&amp;lsaquo; Previous&lt;/a&gt;\";\n\n for ($i=1; $i &lt;= $pages; $i++)\n {\n if (1 != $pages &amp;&amp;( !($i &gt;= $paged+$range+1 || $i &lt;= $paged-$range-1) || $pages &lt;= $showItems ))\n {\n echo ($paged == $i)? \"&lt;span class=\\\"current\\\"&gt;\".$i.\"&lt;/span&gt;\":\"&lt;a href='\".get_pagenum_link($i).\"' class=\\\"inactive\\\"&gt;\".$i.\"&lt;/a&gt;\";\n }\n }\n\n if ($paged &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href=\\\"\".get_pagenum_link($paged + 1).\"\\\"&gt;Next &amp;rsaquo;&lt;/a&gt;\"; \n if ($paged &lt; $pages-1 &amp;&amp; $paged+$range-1 &lt; $pages &amp;&amp; $showItems &lt; $pages) echo \"&lt;a href='\".get_pagenum_link($pages).\"'&gt;Last &amp;raquo;&lt;/a&gt;\";\n echo \"&lt;/div&gt;\\n\";\n }\n}\n?&gt;\n</code></pre>\n\n<p>And you can call from your respective templates by placing below code.</p>\n\n<pre><code>&lt;?php\n if (function_exists(\"pagination\"))\n {\n pagination($additional_loop-&gt;max_num_pages);\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 318581, "author": "Kohlo", "author_id": 153517, "author_profile": "https://wordpress.stackexchange.com/users/153517", "pm_score": 0, "selected": false, "text": "<p>We found a somewhat easy fix, which isn't 100% perfect from the original idea but does the job well enough without figuring out a way to make the code work driving me crazy. I'll post them here just in case anyone else comes across this and wants a quick and dirty way to get a comic navigation on Wordpress without dedicated plugins.</p>\n\n<p>For single posts:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; |\n &lt;?php next_post_link('%link', 'Next &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;'); ?&gt; |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>For main page:\n<code>&lt;div class=\"comicsnav\"&gt;\n &lt;a href=\"STATIC-URL-TO-FIRST-POST\"&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; First&lt;/a&gt; |\n &lt;?php previous_post_link('%link', '&lt;i class=\"fa fa-angle-left\"&gt;&lt;/i&gt; Prev'); ?&gt; | Current |\n &lt;a href=\"STATIC-URL-TO-MAIN-PAGE\"&gt;Last &lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;i class=\"fa fa-angle-right\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;?php wp_get_recent_posts(); ?&gt;\n&lt;/div&gt;</code></p>\n\n<p>The one snag we hit here is that if you're on the first or last post, it'll show 2 pipes next to each other as the previous/next links aren't shown there, which is something I can live with for now. If this bothers you, the pipes are optional so they can be removed completely to show the navigation as:\n&lt;&lt; First &lt; Previous Next > Last >></p>\n" } ]
2018/11/05
[ "https://wordpress.stackexchange.com/questions/318444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142951/" ]
I am using Automattic's plugin to implement AMP on my website. Currently, to make my videos responsive, I wrap YouTube videos around a custom div. So, a YouTube video on my website looks like this:- ``` <div class="yt"> <iframe>....YT video code...</iframe> </div> ``` The problem is the `<div class="yt">` and the closing `</div>` both appear on the AMP pages too. How can I remove them? Already tried asking on the official support. No replies yet.
This [gist](https://gist.github.com/franz-josef-kaiser/818457/c7bf3ce2d12e1340fd44527b3a4a2a8e66fed154) should get you started. ``` <?php /* Plugin Name: Easy Pagination Deamon Plugin URI: http://wordpress.org/extend/plugins/stats/ Description: Offers the deamon_pagination($range) template tag for a sematically correct pagination. Author: Franz Josef Kaiser Author URI: http://say-hello-code.com Version: 0.1 License: GPL v2 - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html Text Domain: pagination_deamon_lang Copyright 20010-2011 by Franz Josef Kaiser This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 */ // ========================================== Styles see https://gist.github.com/818523 // ========================================== // Secure: don't load this file directly if( !class_exists('WP') ) : header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); endif; !defined('PAGE_LANG') ? define( 'PAGE_LANG', 'pagination_deamon_lang' ) : wp_die('The constant PAGE_LANG is already defined.'); !defined('PAGE_VERSION') ? define( 'PAGE_VERSION', 0.1 ) : wp_die('The constant PAGE_VERSION is already defined.'); !defined('PAGE_PATH') ? define( 'PAGE_PATH', trailingslashit(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__))) ) : wp_die('The constant PAGE_PATH is already defined.'); /** * Register styles */ if ( !is_admin() ) { wp_register_style( 'pagination', PAGE_PATH.'pagination.css', false, PAGE_VERSION, 'screen' ); } if ( !function_exists('oxo_pagination_styles') ) : /** * Print styles */ function oxo_pagination_styles() { if ( !is_admin() ) wp_print_styles('pagination'); } endif; if ( !function_exists('oxo_pagination') ) : /** * Wordpress pagination for archives/search/etc. * * Semantically correct pagination inside an unordered list * * Displays: First « 1 2 3 4 » Last * First/Last only appears if not on first/last page * Shows next/previous links «/» * Accepts a range attribute (default = 5) to adjust the number * of direct page links that link to the pages above/below the current one. * * @param (int) $range */ function oxo_pagination( $range = 5 ) { // $paged - number of the current page global $paged, $wp_query; // How much pages do we have? if ( !$max_page ) $max_page = $wp_query->max_num_pages; // We need the pagination only if there is more than 1 page if ( $max_page > 1 ) if ( !$paged ) $paged = 1; echo "\n".'<ul class="pagination">'."\n"; // On the first page, don't put the First page link if ( $paged != 1 ) echo '<li class="page-num page-num-first"><a href='.get_pagenum_link(1).'>'.__('First', PAGE_LANG).' </a></li>'; // To the previous page echo '<li class="page-num page-num-prev">'; previous_posts_link(' &laquo; '); // « echo '</li>'; // We need the sliding effect only if there are more pages than is the sliding range if ( $max_page > $range ) : // When closer to the beginning if ( $paged < $range ) : for ( $i = 1; $i <= ($range + 1); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // When closer to the end elseif ( $paged >= ( $max_page - ceil($range/2)) ) : for ( $i = $max_page - $range; $i <= $max_page; $i++ ){ $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Somewhere in the middle elseif ( $paged >= $range && $paged < ( $max_page - ceil($range/2)) ) : for ( $i = ($paged - ceil($range/2)); $i <= ($paged + ceil($range/2)); $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } // Less pages than the range, no sliding effect needed else : for ( $i = 1; $i <= $max_page; $i++ ) { $class = $i == $paged ? 'current' : ''; echo '<li class="page-num"><a class="paged-num-link '.$class.'" href="'.get_pagenum_link($i).'"> '.$i.' </a></li>'; } endif; // Next page echo '<li class="page-num page-num-next">'; next_posts_link(' &raquo; '); // » echo '</li>'; // On the last page, don't put the Last page link if ( $paged != $max_page ) echo '<li class="page-num page-num-last"><a href='.get_pagenum_link($max_page).'> '.__('Last', PAGE_LANG).'</a></li>'; echo "\n".'</ul>'."\n"; } endif; ?> ```
318,447
<p>I created a numeric pagination that loads the posts via AJAX.</p> <p>This is the PHP and jQuery code:</p> <pre><code>// PHP Code function ajax_pagination_enqueue_scripts() { wp_enqueue_script( 'ajax-pagination', get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true ); wp_localize_script( 'ajax-pagination', 'ajax_pagination_vars', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ), 'query_vars' =&gt; json_encode( $wp_query-&gt;query ) )); } add_action( 'wp_enqueue_scripts', 'ajax_pagination_enqueue_scripts' ); function ajax_pagination_load() { $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true ); $query_vars['paged'] = $_POST['page']; $posts = new WP_Query( $query_vars ); $GLOBALS['wp_query'] = $posts; if( $posts-&gt;have_posts() ) : while( $posts-&gt;have_posts() : $posts-&gt;the_post() ) : get_template_part( 'content', get_post_format() ); endwhile; else: get_template_part( 'content', 'none' ); endif; die(); } add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination_load' ); add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination_load' ); // jQuery Code (function($) { $(document).on( 'click', '.nav-button a', function( event ) { event.preventDefault(); var page = $(this).data('page'); $.ajax({ url: ajax_pagination_vars.ajaxurl, type: 'post', data: { action: 'ajax_pagination', query_vars: ajax_pagination_vars.query_vars, page: page }, success: function( response ) { $('.main-content').html(response); } }) }) })(jQuery); </code></pre> <p>The code works, but when I refresh the page the posts are loaded again from the first page.</p> <p>Ex: If I click the button that loads the page 2 when I refresh the page the posts are displayed from the page 1.</p> <p>There is a way to remain on the same page even after the page refresh?</p> <p>Thanks.</p>
[ { "answer_id": 318448, "author": "Maidul", "author_id": 21142, "author_profile": "https://wordpress.stackexchange.com/users/21142", "pm_score": -1, "selected": false, "text": "<p>You can set a cookie or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage\" rel=\"nofollow noreferrer\">local storage</a> to set the current page, as there is no way to track the paged variable you pass with ajax on page reload.\nUpdate js code to check for cookie or local storage on page reload and get result based on that.On your ajax success function set localstorage like this.</p>\n\n<pre><code>// Store current page number\nlocalStorage.setItem('page', 2);\n</code></pre>\n\n<p>And on page reload check local storage</p>\n\n<pre><code>//Get current page number\nvar currentPage = localStorage.getItem('page');\n</code></pre>\n" }, { "answer_id": 318449, "author": "Cristiano Baptista", "author_id": 108188, "author_profile": "https://wordpress.stackexchange.com/users/108188", "pm_score": 2, "selected": true, "text": "<p>When you refresh the page, there is currently no state you can use to know you're on page 2.</p>\n\n<p>You could use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/History\" rel=\"nofollow noreferrer\">History API</a> to update the page URL without refreshing the page:</p>\n\n<pre><code>history.pushState(data, title, 'https://yourpage.com/?page=2');\n</code></pre>\n\n<p>You can also set some state on the user browser using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage\" rel=\"nofollow noreferrer\">SessionStorage</a> instead of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage\" rel=\"nofollow noreferrer\">LocalStorage API</a>, because the session will not persist when the user closes the browser tab:</p>\n\n<pre><code>// Store current page\nsessionStorage.setItem('page', 2);\n\n// Get current page on page load/refresh\nvar currentPage = sessionStorage.getItem('page');\n</code></pre>\n\n<p>This second method has its issues since the user can go to a different page and then get back to the paginated page and get the second page of results, instead of getting the first one, so you need to be careful about this approach.</p>\n" } ]
2018/11/05
[ "https://wordpress.stackexchange.com/questions/318447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140507/" ]
I created a numeric pagination that loads the posts via AJAX. This is the PHP and jQuery code: ``` // PHP Code function ajax_pagination_enqueue_scripts() { wp_enqueue_script( 'ajax-pagination', get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true ); wp_localize_script( 'ajax-pagination', 'ajax_pagination_vars', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'query_vars' => json_encode( $wp_query->query ) )); } add_action( 'wp_enqueue_scripts', 'ajax_pagination_enqueue_scripts' ); function ajax_pagination_load() { $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true ); $query_vars['paged'] = $_POST['page']; $posts = new WP_Query( $query_vars ); $GLOBALS['wp_query'] = $posts; if( $posts->have_posts() ) : while( $posts->have_posts() : $posts->the_post() ) : get_template_part( 'content', get_post_format() ); endwhile; else: get_template_part( 'content', 'none' ); endif; die(); } add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination_load' ); add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination_load' ); // jQuery Code (function($) { $(document).on( 'click', '.nav-button a', function( event ) { event.preventDefault(); var page = $(this).data('page'); $.ajax({ url: ajax_pagination_vars.ajaxurl, type: 'post', data: { action: 'ajax_pagination', query_vars: ajax_pagination_vars.query_vars, page: page }, success: function( response ) { $('.main-content').html(response); } }) }) })(jQuery); ``` The code works, but when I refresh the page the posts are loaded again from the first page. Ex: If I click the button that loads the page 2 when I refresh the page the posts are displayed from the page 1. There is a way to remain on the same page even after the page refresh? Thanks.
When you refresh the page, there is currently no state you can use to know you're on page 2. You could use the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History) to update the page URL without refreshing the page: ``` history.pushState(data, title, 'https://yourpage.com/?page=2'); ``` You can also set some state on the user browser using the [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) instead of the [LocalStorage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage), because the session will not persist when the user closes the browser tab: ``` // Store current page sessionStorage.setItem('page', 2); // Get current page on page load/refresh var currentPage = sessionStorage.getItem('page'); ``` This second method has its issues since the user can go to a different page and then get back to the paginated page and get the second page of results, instead of getting the first one, so you need to be careful about this approach.
318,515
<p>I try to call a function everytime a user login to website.</p> <p>I succeeded with the <code>wp_login</code> hook for user who fill the login form.</p> <p>However I can't find a hook for an user which has the "remember me" option activated when he come back to website (so he already have a login cookie).</p> <p>I checked <code>wp_validate_auth_cookie()</code> function but this one is fired on each page: is Wordpress doing a check for "remember me" cookie on each page and then set user logged?</p> <p>Thanks</p>
[ { "answer_id": 318521, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>Don't use <code>wp_login</code> hook. Use <code>wp_signon</code> function instead.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_signon/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_signon/</a></p>\n\n<pre><code>wp_signon( array $credentials = array(), string|bool $secure_cookie = '' )\n</code></pre>\n\n<blockquote>\n <p>The credentials is an array that has ‘user_login’, ‘user_password’,\n and ‘remember’ indices. If the credentials is not given, then the log\n in form will be assumed and used if set.</p>\n</blockquote>\n" }, { "answer_id": 318523, "author": "Maidul", "author_id": 21142, "author_profile": "https://wordpress.stackexchange.com/users/21142", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow noreferrer\">wp_login</a> hook pass two parameters: $user->user_login (string) and $user ( <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\">WP_User</a> ). \"remember me\" option on login form did not pass on wp_login hook, its used on the <a href=\"https://codex.wordpress.org/Function_Reference/wp_signon\" rel=\"nofollow noreferrer\">wp_signon</a> function to set the cookie on the browser.</p>\n\n<pre><code>wp_set_auth_cookie($user-&gt;ID, $credentials['remember'], $secure_cookie);\n</code></pre>\n\n<p>So you can't access that using wp_login hook.</p>\n" }, { "answer_id": 360302, "author": "Ynhockey", "author_id": 33019, "author_profile": "https://wordpress.stackexchange.com/users/33019", "pm_score": 0, "selected": false, "text": "<p>It's not 100% clear what you are trying to do, but in order to get the Remember Me status, you can do the following:</p>\n\n<ol>\n<li>Call <code>wp_set_auth_cookie( $user_id, $remember )</code>, where <code>$remember</code> is the Remember Me status.</li>\n<li>If you need to customize the actual session length based on the Remember Me setting, add a filter for the cookie expiration: <code>add_filter( 'auth_cookie_expiration', 'get_expiration' ), 10, 3 );</code> with:</li>\n</ol>\n\n<pre><code>function get_expiration( $expiration, $user_id, $remember ) {\n // $remember will be passed from wp_set_auth_cookie()\n if ( $remember ) {\n // ...\n } else {\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 363354, "author": "Akhil", "author_id": 173882, "author_profile": "https://wordpress.stackexchange.com/users/173882", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question but from what I understand, OP needs to call a custom function <em>every</em> time a user logs in (regardless of if it's via the login form or automatically logging in as a result of checking the Remember Me option during a prior login).<br>\nThis can be achieved by using the 'authenticate' filter. More information can be found in this helpful guide that I found. </p>\n\n<p><a href=\"https://usersinsights.com/wordpress-user-login-hooks/\" rel=\"nofollow noreferrer\">https://usersinsights.com/wordpress-user-login-hooks/</a></p>\n" } ]
2018/11/06
[ "https://wordpress.stackexchange.com/questions/318515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147005/" ]
I try to call a function everytime a user login to website. I succeeded with the `wp_login` hook for user who fill the login form. However I can't find a hook for an user which has the "remember me" option activated when he come back to website (so he already have a login cookie). I checked `wp_validate_auth_cookie()` function but this one is fired on each page: is Wordpress doing a check for "remember me" cookie on each page and then set user logged? Thanks
Don't use `wp_login` hook. Use `wp_signon` function instead. <https://developer.wordpress.org/reference/functions/wp_signon/> ``` wp_signon( array $credentials = array(), string|bool $secure_cookie = '' ) ``` > > The credentials is an array that has ‘user\_login’, ‘user\_password’, > and ‘remember’ indices. If the credentials is not given, then the log > in form will be assumed and used if set. > > >
318,534
<p>I was trying to display product thumbnails in 230px (as per recommendations by GTmetrix).</p> <p>Since, I am using storefront the default value is declared in storefront/inc/class-storefront.php</p> <p>The code is as follows:</p> <pre><code>add_theme_support( 'woocommerce', apply_filters( 'storefront_woocommerce_args', array( 'single_image_width' =&gt; 416, 'thumbnail_image_width' =&gt; 324, 'product_grid' =&gt; array( 'default_columns' =&gt; 3, 'default_rows' =&gt; 4, 'min_columns' =&gt; 1, 'max_columns' =&gt; 6, 'min_rows' =&gt; 1 </code></pre> <p>) ) ) );</p> <p>I tried assigning single_image_width with the value of 230 and it made no difference. So, I marked out the line and added the following code in my functions.php file:</p> <pre><code>add_theme_support( 'woocommerce', array( 'thumbnail_image_width' =&gt; 230 ) ); } </code></pre> <p>This doesn't seem to make a difference either. What am I doing wrong?</p> <p>For reference this is the images I am trying to resize. I used woocommerce shortcodes to display it in the site. <a href="https://i.stack.imgur.com/TkCkt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TkCkt.png" alt="enter image description here"></a></p> <p>I would really appreciate the help.</p> <p>Thank you, - KG. </p>
[ { "answer_id": 318521, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>Don't use <code>wp_login</code> hook. Use <code>wp_signon</code> function instead.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_signon/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_signon/</a></p>\n\n<pre><code>wp_signon( array $credentials = array(), string|bool $secure_cookie = '' )\n</code></pre>\n\n<blockquote>\n <p>The credentials is an array that has ‘user_login’, ‘user_password’,\n and ‘remember’ indices. If the credentials is not given, then the log\n in form will be assumed and used if set.</p>\n</blockquote>\n" }, { "answer_id": 318523, "author": "Maidul", "author_id": 21142, "author_profile": "https://wordpress.stackexchange.com/users/21142", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow noreferrer\">wp_login</a> hook pass two parameters: $user->user_login (string) and $user ( <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\">WP_User</a> ). \"remember me\" option on login form did not pass on wp_login hook, its used on the <a href=\"https://codex.wordpress.org/Function_Reference/wp_signon\" rel=\"nofollow noreferrer\">wp_signon</a> function to set the cookie on the browser.</p>\n\n<pre><code>wp_set_auth_cookie($user-&gt;ID, $credentials['remember'], $secure_cookie);\n</code></pre>\n\n<p>So you can't access that using wp_login hook.</p>\n" }, { "answer_id": 360302, "author": "Ynhockey", "author_id": 33019, "author_profile": "https://wordpress.stackexchange.com/users/33019", "pm_score": 0, "selected": false, "text": "<p>It's not 100% clear what you are trying to do, but in order to get the Remember Me status, you can do the following:</p>\n\n<ol>\n<li>Call <code>wp_set_auth_cookie( $user_id, $remember )</code>, where <code>$remember</code> is the Remember Me status.</li>\n<li>If you need to customize the actual session length based on the Remember Me setting, add a filter for the cookie expiration: <code>add_filter( 'auth_cookie_expiration', 'get_expiration' ), 10, 3 );</code> with:</li>\n</ol>\n\n<pre><code>function get_expiration( $expiration, $user_id, $remember ) {\n // $remember will be passed from wp_set_auth_cookie()\n if ( $remember ) {\n // ...\n } else {\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 363354, "author": "Akhil", "author_id": 173882, "author_profile": "https://wordpress.stackexchange.com/users/173882", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question but from what I understand, OP needs to call a custom function <em>every</em> time a user logs in (regardless of if it's via the login form or automatically logging in as a result of checking the Remember Me option during a prior login).<br>\nThis can be achieved by using the 'authenticate' filter. More information can be found in this helpful guide that I found. </p>\n\n<p><a href=\"https://usersinsights.com/wordpress-user-login-hooks/\" rel=\"nofollow noreferrer\">https://usersinsights.com/wordpress-user-login-hooks/</a></p>\n" } ]
2018/11/06
[ "https://wordpress.stackexchange.com/questions/318534", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153654/" ]
I was trying to display product thumbnails in 230px (as per recommendations by GTmetrix). Since, I am using storefront the default value is declared in storefront/inc/class-storefront.php The code is as follows: ``` add_theme_support( 'woocommerce', apply_filters( 'storefront_woocommerce_args', array( 'single_image_width' => 416, 'thumbnail_image_width' => 324, 'product_grid' => array( 'default_columns' => 3, 'default_rows' => 4, 'min_columns' => 1, 'max_columns' => 6, 'min_rows' => 1 ``` ) ) ) ); I tried assigning single\_image\_width with the value of 230 and it made no difference. So, I marked out the line and added the following code in my functions.php file: ``` add_theme_support( 'woocommerce', array( 'thumbnail_image_width' => 230 ) ); } ``` This doesn't seem to make a difference either. What am I doing wrong? For reference this is the images I am trying to resize. I used woocommerce shortcodes to display it in the site. [![enter image description here](https://i.stack.imgur.com/TkCkt.png)](https://i.stack.imgur.com/TkCkt.png) I would really appreciate the help. Thank you, - KG.
Don't use `wp_login` hook. Use `wp_signon` function instead. <https://developer.wordpress.org/reference/functions/wp_signon/> ``` wp_signon( array $credentials = array(), string|bool $secure_cookie = '' ) ``` > > The credentials is an array that has ‘user\_login’, ‘user\_password’, > and ‘remember’ indices. If the credentials is not given, then the log > in form will be assumed and used if set. > > >
318,583
<p>There are a few websites that I stumble upon now and then that have animated intros like the one here: www.monotwo.com </p> <p>How do I do that in WordPress?</p> <p>And how would I integrate this into a customs theme?</p> <p>Thanks.</p>
[ { "answer_id": 318521, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>Don't use <code>wp_login</code> hook. Use <code>wp_signon</code> function instead.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_signon/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_signon/</a></p>\n\n<pre><code>wp_signon( array $credentials = array(), string|bool $secure_cookie = '' )\n</code></pre>\n\n<blockquote>\n <p>The credentials is an array that has ‘user_login’, ‘user_password’,\n and ‘remember’ indices. If the credentials is not given, then the log\n in form will be assumed and used if set.</p>\n</blockquote>\n" }, { "answer_id": 318523, "author": "Maidul", "author_id": 21142, "author_profile": "https://wordpress.stackexchange.com/users/21142", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow noreferrer\">wp_login</a> hook pass two parameters: $user->user_login (string) and $user ( <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\">WP_User</a> ). \"remember me\" option on login form did not pass on wp_login hook, its used on the <a href=\"https://codex.wordpress.org/Function_Reference/wp_signon\" rel=\"nofollow noreferrer\">wp_signon</a> function to set the cookie on the browser.</p>\n\n<pre><code>wp_set_auth_cookie($user-&gt;ID, $credentials['remember'], $secure_cookie);\n</code></pre>\n\n<p>So you can't access that using wp_login hook.</p>\n" }, { "answer_id": 360302, "author": "Ynhockey", "author_id": 33019, "author_profile": "https://wordpress.stackexchange.com/users/33019", "pm_score": 0, "selected": false, "text": "<p>It's not 100% clear what you are trying to do, but in order to get the Remember Me status, you can do the following:</p>\n\n<ol>\n<li>Call <code>wp_set_auth_cookie( $user_id, $remember )</code>, where <code>$remember</code> is the Remember Me status.</li>\n<li>If you need to customize the actual session length based on the Remember Me setting, add a filter for the cookie expiration: <code>add_filter( 'auth_cookie_expiration', 'get_expiration' ), 10, 3 );</code> with:</li>\n</ol>\n\n<pre><code>function get_expiration( $expiration, $user_id, $remember ) {\n // $remember will be passed from wp_set_auth_cookie()\n if ( $remember ) {\n // ...\n } else {\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 363354, "author": "Akhil", "author_id": 173882, "author_profile": "https://wordpress.stackexchange.com/users/173882", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question but from what I understand, OP needs to call a custom function <em>every</em> time a user logs in (regardless of if it's via the login form or automatically logging in as a result of checking the Remember Me option during a prior login).<br>\nThis can be achieved by using the 'authenticate' filter. More information can be found in this helpful guide that I found. </p>\n\n<p><a href=\"https://usersinsights.com/wordpress-user-login-hooks/\" rel=\"nofollow noreferrer\">https://usersinsights.com/wordpress-user-login-hooks/</a></p>\n" } ]
2018/11/07
[ "https://wordpress.stackexchange.com/questions/318583", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153687/" ]
There are a few websites that I stumble upon now and then that have animated intros like the one here: www.monotwo.com How do I do that in WordPress? And how would I integrate this into a customs theme? Thanks.
Don't use `wp_login` hook. Use `wp_signon` function instead. <https://developer.wordpress.org/reference/functions/wp_signon/> ``` wp_signon( array $credentials = array(), string|bool $secure_cookie = '' ) ``` > > The credentials is an array that has ‘user\_login’, ‘user\_password’, > and ‘remember’ indices. If the credentials is not given, then the log > in form will be assumed and used if set. > > >
318,590
<p>I have a very basic question which can be done easily with raw sql query where instead of * we can name the columns of database we want output like </p> <pre><code> select id,name,date from tableA where id&gt;'100' </code></pre> <p>but same thing in <code>Wp_Query</code> is giving whole lot of junk data which is completely irrelevant to us. We can filter those data with <code>php</code> but the problem is it will definitely kill database as it is making lot of calls behind the scene.</p> <p>We checked with <code>var_dump</code> and it was huge data 99% of not useful to us. We want to list only id and name column not columns like <code>PING_STATUS,COMMENT_STATUS,MENU_ORDER,COMMENT_STATUS</code> etc</p> <pre><code> while ( $has_more_images ) { $args = array( 'posts_per_page' =&gt; '100', 'offset' =&gt; $offset, 'post_type' =&gt; 'attachment', 'post_status' =&gt; 'any', 'orderby' =&gt;'ID', 'order' =&gt; 'ASC', 'no_found_rows' =&gt; true ); $the_query = new WP_Query( $args ); var_dump( $the_query ); } </code></pre>
[ { "answer_id": 318521, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 1, "selected": false, "text": "<p>Don't use <code>wp_login</code> hook. Use <code>wp_signon</code> function instead.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_signon/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_signon/</a></p>\n\n<pre><code>wp_signon( array $credentials = array(), string|bool $secure_cookie = '' )\n</code></pre>\n\n<blockquote>\n <p>The credentials is an array that has ‘user_login’, ‘user_password’,\n and ‘remember’ indices. If the credentials is not given, then the log\n in form will be assumed and used if set.</p>\n</blockquote>\n" }, { "answer_id": 318523, "author": "Maidul", "author_id": 21142, "author_profile": "https://wordpress.stackexchange.com/users/21142", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login\" rel=\"nofollow noreferrer\">wp_login</a> hook pass two parameters: $user->user_login (string) and $user ( <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\">WP_User</a> ). \"remember me\" option on login form did not pass on wp_login hook, its used on the <a href=\"https://codex.wordpress.org/Function_Reference/wp_signon\" rel=\"nofollow noreferrer\">wp_signon</a> function to set the cookie on the browser.</p>\n\n<pre><code>wp_set_auth_cookie($user-&gt;ID, $credentials['remember'], $secure_cookie);\n</code></pre>\n\n<p>So you can't access that using wp_login hook.</p>\n" }, { "answer_id": 360302, "author": "Ynhockey", "author_id": 33019, "author_profile": "https://wordpress.stackexchange.com/users/33019", "pm_score": 0, "selected": false, "text": "<p>It's not 100% clear what you are trying to do, but in order to get the Remember Me status, you can do the following:</p>\n\n<ol>\n<li>Call <code>wp_set_auth_cookie( $user_id, $remember )</code>, where <code>$remember</code> is the Remember Me status.</li>\n<li>If you need to customize the actual session length based on the Remember Me setting, add a filter for the cookie expiration: <code>add_filter( 'auth_cookie_expiration', 'get_expiration' ), 10, 3 );</code> with:</li>\n</ol>\n\n<pre><code>function get_expiration( $expiration, $user_id, $remember ) {\n // $remember will be passed from wp_set_auth_cookie()\n if ( $remember ) {\n // ...\n } else {\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 363354, "author": "Akhil", "author_id": 173882, "author_profile": "https://wordpress.stackexchange.com/users/173882", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question but from what I understand, OP needs to call a custom function <em>every</em> time a user logs in (regardless of if it's via the login form or automatically logging in as a result of checking the Remember Me option during a prior login).<br>\nThis can be achieved by using the 'authenticate' filter. More information can be found in this helpful guide that I found. </p>\n\n<p><a href=\"https://usersinsights.com/wordpress-user-login-hooks/\" rel=\"nofollow noreferrer\">https://usersinsights.com/wordpress-user-login-hooks/</a></p>\n" } ]
2018/11/07
[ "https://wordpress.stackexchange.com/questions/318590", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153612/" ]
I have a very basic question which can be done easily with raw sql query where instead of \* we can name the columns of database we want output like ``` select id,name,date from tableA where id>'100' ``` but same thing in `Wp_Query` is giving whole lot of junk data which is completely irrelevant to us. We can filter those data with `php` but the problem is it will definitely kill database as it is making lot of calls behind the scene. We checked with `var_dump` and it was huge data 99% of not useful to us. We want to list only id and name column not columns like `PING_STATUS,COMMENT_STATUS,MENU_ORDER,COMMENT_STATUS` etc ``` while ( $has_more_images ) { $args = array( 'posts_per_page' => '100', 'offset' => $offset, 'post_type' => 'attachment', 'post_status' => 'any', 'orderby' =>'ID', 'order' => 'ASC', 'no_found_rows' => true ); $the_query = new WP_Query( $args ); var_dump( $the_query ); } ```
Don't use `wp_login` hook. Use `wp_signon` function instead. <https://developer.wordpress.org/reference/functions/wp_signon/> ``` wp_signon( array $credentials = array(), string|bool $secure_cookie = '' ) ``` > > The credentials is an array that has ‘user\_login’, ‘user\_password’, > and ‘remember’ indices. If the credentials is not given, then the log > in form will be assumed and used if set. > > >
318,666
<p>In my WordPress installation <code>(4.9.8.)</code> the editor role isn't allowed to edit the privacy page.</p> <p>It would work with following in my <code>functions.php</code>:</p> <pre><code>$role_object = get_role( 'editor' ); $role_object-&gt;add_cap( 'manage_privacy_options', true ); $role_object-&gt;add_cap( 'manage_options' ); // this needs to be active in order that before cap works </code></pre> <p>But now the editor has lot more rights than just editing the privacy page.</p> <p>Is there another way to <code>grant access to the editor user role</code> with some lines of PHP code?</p> <hr> <p>As a workaround I make usage of this Plugin now: <a href="https://wordpress.org/plugins/manage-privacy-options/" rel="noreferrer">https://wordpress.org/plugins/manage-privacy-options/</a></p> <p>Another kind of workaround is just to choose no privacy page in the privacy settings.</p>
[ { "answer_id": 325784, "author": "Sven", "author_id": 32946, "author_profile": "https://wordpress.stackexchange.com/users/32946", "pm_score": 5, "selected": true, "text": "<p>Editing the privacy policy page is restricted to <code>manage_privacy_options</code> as pointed out in a comment in the WordPress core file <code>wp-includes/capabilities.php</code>:</p>\n\n<pre><code>/*\n * Setting the privacy policy page requires `manage_privacy_options`,\n * so editing it should require that too.\n */\nif ( (int) get_option( 'wp_page_for_privacy_policy' ) === $post-&gt;ID ) {\n $caps = array_merge( $caps, map_meta_cap( 'manage_privacy_options', $user_id ) );\n}\n</code></pre>\n\n<p>To allow users <strike>with the roles <code>editor</code> and <code>administrator</code></strike> who can edit pages (in single and also multisite instances) to edit and delete the privacy policy page one has to overwrite the <code>$caps</code> array:</p>\n\n<pre><code>add_action('map_meta_cap', 'custom_manage_privacy_options', 1, 4);\nfunction custom_manage_privacy_options($caps, $cap, $user_id, $args)\n{\n if (!is_user_logged_in()) return $caps;\n\n if ('manage_privacy_options' === $cap) {\n $manage_name = is_multisite() ? 'manage_network' : 'manage_options';\n $caps = array_diff($caps, [ $manage_name ]);\n }\n return $caps;\n}\n</code></pre>\n\n<p>Update: Allow users with the role <code>editor</code> or <code>administrator</code> to edit and delete the privacy policy page (which is not possible per default in multisite instances):</p>\n\n<pre><code>add_action('map_meta_cap', 'custom_manage_privacy_options', 1, 4);\nfunction custom_manage_privacy_options($caps, $cap, $user_id, $args)\n{\n if (!is_user_logged_in()) return $caps;\n\n $user_meta = get_userdata($user_id);\n if (array_intersect(['editor', 'administrator'], $user_meta-&gt;roles)) {\n if ('manage_privacy_options' === $cap) {\n $manage_name = is_multisite() ? 'manage_network' : 'manage_options';\n $caps = array_diff($caps, [ $manage_name ]);\n }\n }\n return $caps;\n}\n</code></pre>\n" }, { "answer_id": 359853, "author": "Nicolas Prigent", "author_id": 183663, "author_profile": "https://wordpress.stackexchange.com/users/183663", "pm_score": 2, "selected": false, "text": "<p>Thanks @Sven for the nice workaround, it works well but I had an issue when the user is not yet logged_in, the map_meta_cap action is fired anyway, which resulted on a \"502 bad getaway\" error. I added a <code>is_user_logged_in()</code> test before like so :</p>\n\n<pre><code>if (is_user_logged_in()){\n add_action('map_meta_cap', 'custom_manage_privacy_options', 1, 4);\n}\n</code></pre>\n\n<p>Maybe it's my server configuration (nginx) that results on this bug, but if someone get the same error, here is a solution.</p>\n" }, { "answer_id": 386937, "author": "Preguntón", "author_id": 205222, "author_profile": "https://wordpress.stackexchange.com/users/205222", "pm_score": 0, "selected": false, "text": "<p>The provided answer did the trick. However, this line:</p>\n<pre><code>if (array_intersect(['editor', 'administrator'], $user_meta-&gt;roles)) {\n</code></pre>\n<p>Was generating this error:</p>\n<pre><code>array_intersect(): Expected parameter 2 to be an array, null given in\n</code></pre>\n<p>So I tweaked the code a bit to ensure that both values were valid arrays (full code):</p>\n<pre><code>add_action('map_meta_cap', 'custom_manage_privacy_options', 1, 4);\nfunction custom_manage_privacy_options($caps, $cap, $user_id, $args) {\n if ( !is_user_logged_in() ) return $caps;\n\n$target_roles = array('editor', 'administrator');\n$user_meta = get_userdata($user_id);\n$user_roles = ( array ) $user_meta-&gt;roles;\n\nif ( array_intersect($target_roles, $user_roles) ) {\n if ('manage_privacy_options' === $cap) {\n $manage_name = is_multisite() ? 'manage_network' : 'manage_options';\n $caps = array_diff($caps, [ $manage_name ]);\n }\n}\n\nreturn $caps;\n}\n</code></pre>\n" } ]
2018/11/08
[ "https://wordpress.stackexchange.com/questions/318666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136930/" ]
In my WordPress installation `(4.9.8.)` the editor role isn't allowed to edit the privacy page. It would work with following in my `functions.php`: ``` $role_object = get_role( 'editor' ); $role_object->add_cap( 'manage_privacy_options', true ); $role_object->add_cap( 'manage_options' ); // this needs to be active in order that before cap works ``` But now the editor has lot more rights than just editing the privacy page. Is there another way to `grant access to the editor user role` with some lines of PHP code? --- As a workaround I make usage of this Plugin now: <https://wordpress.org/plugins/manage-privacy-options/> Another kind of workaround is just to choose no privacy page in the privacy settings.
Editing the privacy policy page is restricted to `manage_privacy_options` as pointed out in a comment in the WordPress core file `wp-includes/capabilities.php`: ``` /* * Setting the privacy policy page requires `manage_privacy_options`, * so editing it should require that too. */ if ( (int) get_option( 'wp_page_for_privacy_policy' ) === $post->ID ) { $caps = array_merge( $caps, map_meta_cap( 'manage_privacy_options', $user_id ) ); } ``` To allow users with the roles `editor` and `administrator` who can edit pages (in single and also multisite instances) to edit and delete the privacy policy page one has to overwrite the `$caps` array: ``` add_action('map_meta_cap', 'custom_manage_privacy_options', 1, 4); function custom_manage_privacy_options($caps, $cap, $user_id, $args) { if (!is_user_logged_in()) return $caps; if ('manage_privacy_options' === $cap) { $manage_name = is_multisite() ? 'manage_network' : 'manage_options'; $caps = array_diff($caps, [ $manage_name ]); } return $caps; } ``` Update: Allow users with the role `editor` or `administrator` to edit and delete the privacy policy page (which is not possible per default in multisite instances): ``` add_action('map_meta_cap', 'custom_manage_privacy_options', 1, 4); function custom_manage_privacy_options($caps, $cap, $user_id, $args) { if (!is_user_logged_in()) return $caps; $user_meta = get_userdata($user_id); if (array_intersect(['editor', 'administrator'], $user_meta->roles)) { if ('manage_privacy_options' === $cap) { $manage_name = is_multisite() ? 'manage_network' : 'manage_options'; $caps = array_diff($caps, [ $manage_name ]); } } return $caps; } ```
318,678
<p>How do I change the WordPress template used for the WooCommerce category pages?</p> <p>I can change the product pages by using the single-product.php template, but the category pages just use <strong>page.php</strong> which I don't want to modify because it is so sidely used.</p> <p>How do I modify this template and only affect category pages? I am <strong>NOT</strong> interested in overriding the WooCommerce templates, I want to edit the surrounding template that contains the header, footer, etc.</p>
[ { "answer_id": 318680, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>WooCommerce categories are called <code>product_cat</code>. If you check the <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">WP template hierarchy</a>, you see that for (custom) taxonomy archives, <code>taxonomy-$taxonomy.php</code> works.</p>\n\n<p>So in your case, creating a <code>taxonomy-product_cat.php</code> should work.</p>\n\n<p>You can copy the content from taxonomy.php, archive.php or index.php and start your work from there.</p>\n" }, { "answer_id": 364897, "author": "Daniele Zerosi", "author_id": 151184, "author_profile": "https://wordpress.stackexchange.com/users/151184", "pm_score": 2, "selected": false, "text": "<p>I had same problem and the solution is this</p>\n\n<pre><code>function mytheme_add_woocommerce_support() {\n add_theme_support( 'woocommerce' );\n}\n\nadd_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' );\n</code></pre>\n" } ]
2018/11/08
[ "https://wordpress.stackexchange.com/questions/318678", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88708/" ]
How do I change the WordPress template used for the WooCommerce category pages? I can change the product pages by using the single-product.php template, but the category pages just use **page.php** which I don't want to modify because it is so sidely used. How do I modify this template and only affect category pages? I am **NOT** interested in overriding the WooCommerce templates, I want to edit the surrounding template that contains the header, footer, etc.
I had same problem and the solution is this ``` function mytheme_add_woocommerce_support() { add_theme_support( 'woocommerce' ); } add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' ); ```
318,704
<p>I am trying to update the field when post status changes to published. It is getting the values properly but not updating when I check the what update field is returning.</p> <p>It shows some number.</p> <p>Please help not sure whether I should use this along with <code>transition_post_status</code></p> <hr> <p><strong>Update - I have tried below hooks</strong> // the action is getting triggered but the fields are not updating </p> <p><em>1. <strong>publish</strong> //works but no update is happening</em></p> <p><em>2. <strong>save_post</strong> &amp;&amp; <strong>save_post_l</strong> //works but no update is happening.</em></p> <hr> <pre><code>add_action('transition_post_status', 'updated_to_publish', 10, 3); function updated_to_publish($new_status, $old_status, $post) { if ($new_status == 'publish')) // I have removed the check for post type { $post_id = $post-&gt;ID; if (get_field('advanced_option_edit_seo', $post_id)) { if (defined('WPSEO_VERSION')) { $metatitle = get_field('seo_title', $post_id); $metadesc = get_field('seo_meta_description', $post_id); $metakeywords = get_field('seo_keyword', $post_id); update_post_meta($post_id, '_yoast_wpseo_title', $metatitle ); update_post_meta($post_id, '_yoast_wpseo_metadesc', $metadesc ); update_post_meta($post_id, '_yoast_wpseo_focuskw', $metakeywords); } } } else { return; } } </code></pre> <p><hr></p> <hr> <h2>Update</h2> <p>I was able to solve the issue by using '<code>wp_insert_post</code>' action . Can I know why other actions failed but '<code>wp_insert_post</code>' worked? </p> <p>code that i used for testing </p> <pre><code>add_action('transition_post_status', 'updated_to_publish', 10, 3); function updated_to_publish($new_status, $old_status, $post) { if (($new_status == 'publish') &amp;&amp; ($post-&gt;post_type == 'l')) { $post_id = $post-&gt;ID; error_log( var_export( $post_id, 1 ) ); if (get_field('advanced_option_edit_seo', $post_id)) { if (defined('WPSEO_VERSION')) { // ACF field $metatitle = get_field('seo_title', $post_id); error_log( var_export( $metatitle, 1 ) ); $metadesc = get_field('seo_meta_description', $post_id); error_log( var_export( $metadesc, 1 ) ); $metakeywords = get_field('seo_keyword', $post_id); error_log( var_export( $metakeywords, 1 ) ); //plugin is activated //old values $metadesc_old = get_post_meta($post-&gt;ID, '_yoast_wpseo_metadesc', true); error_log( var_export( $metadesc_old, 1 ) ); $metatitle_old = get_post_meta($post-&gt;ID, '_yoast_wpseo_title', true); error_log( var_export( $metatitle_old, 1 ) ); $metakeywords_old = get_post_meta($post-&gt;ID, '_yoast_wpseo_focuskw', true); error_log( var_export( $metakeywords_old, 1 ) ); update_post_meta($post_id, '_yoast_wpseo_title', $metatitle, $metatitle_old); error_log( var_export( $tyone, 1 ) ); update_post_meta($post_id, '_yoast_wpseo_metadesc', $metadesc, $metadesc_old); error_log( var_export( $tytwo, 1 ) ); update_post_meta($post_id, '_yoast_wpseo_focuskw', $metakeywords, $metakeywords_old); error_log( var_export( $tythree, 1 ) ); } } } else { return; } //Do something } </code></pre>
[ { "answer_id": 318912, "author": "mithun raval", "author_id": 153875, "author_profile": "https://wordpress.stackexchange.com/users/153875", "pm_score": 0, "selected": false, "text": "<p>try \"wpseo_title\" Filter for updating wpseo_title.</p>\n\n<pre><code>add_filter('wpseo_title', 'filter_product_wpseo_title');\n\nfunction filter_product_wpseo_title($title) {\nglobal $post;\n$post_id = $post-&gt;ID;\n if (get_field('advanced_option_edit_seo', $post_id)) {\n\n if (defined('WPSEO_VERSION')) {\n\n $title = get_field('seo_title', $post_id);\n\n }\n\n }\n\n\n return $title;\n}\n</code></pre>\n\n<p>for more seo data update example: <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">https://yoast.com/wordpress/plugins/seo/api/</a></p>\n" }, { "answer_id": 318985, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 0, "selected": false, "text": "<p>Your original function relies on the $_POST['post_type'] being set to the appropriate value. As a general rule, you should avoid using global variables - if you use only want the function gives to you, you don't have to think about the contexts in what it should be called.</p>\n\n<p>In this case, that's what's happened. You're function relies on a global variable $_POST['post_type'], and while that works in one 'state' (publishing a post) it doesn't in another (a cron job, updating a post). In short, $_POST['post_type'] isn't always what you think it should be.</p>\n\n<p>The following retrieves the post type from the passed $post variable:</p>\n\n<pre><code>add_action('transition_post_status', 'updated_to_publish', 10, 3);\n</code></pre>\n\n<p>function updated_to_publish($new_status, $old_status, $post)\n{</p>\n\n<pre><code>if (($new_status == 'publish') &amp;&amp; (get_post_type( $post ) == 'l')) {\n\n $post_id = $post-&gt;ID;\n\n if (get_field('advanced_option_edit_seo', $post_id)) {\n\n if (defined('WPSEO_VERSION')) {\n\n //Code goes here\n\n }\n }\n\n} else {\n return;\n}\n</code></pre>\n\n<p>}</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/143364/if-problems-with-transition-post-status\">Visit this link</a> from where I just have copied the answer</p>\n" }, { "answer_id": 319235, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>So I installed the <a href=\"https://yoast.com/wordpress/plugins/seo/\" rel=\"nofollow noreferrer\">Yoast SEO plugin</a>, and tested your code, and now I can positively say \"<strong><em>neither no nor yes, but you could</em></strong>\" to this question:</p>\n\n<blockquote>\n <p>Please help not sure whether I should use this along with\n <code>transition_post_status</code></p>\n</blockquote>\n\n<p><code>transition_post_status</code> is fired <em>before</em> the <code>wp_insert_post</code> action is fired, and the Yoast SEO plugin is actually saving (adding/updating) all its custom fields via the <code>wp_insert_post</code> action:</p>\n\n<pre><code>// See WPSEO_Metabox::save_postdata() (in wordpress-seo/admin/metabox/class-metabox.php)\nadd_action( 'wp_insert_post', array( $this, 'save_postdata' ) );\n</code></pre>\n\n<p>So your code itself works, and the fields do get updated (if the new and current values are not the same and that all the <code>if</code> conditions are met, of course); however the Yoast SEO plugin overrides the value via the <code>WPSEO_Metabox::save_postdata()</code> function, which should answer this question:</p>\n\n<blockquote>\n <p>I was able to solve the issue by using '<code>wp_insert_post</code>' action . Can\n I know why other actions failed but '<code>wp_insert_post</code>' worked?</p>\n</blockquote>\n\n<p><strong>Why did I say <em>neither no nor yes, but you could</em>?</strong></p>\n\n<p>Because you can use <code>transition_post_status</code> along with <code>wp_insert_post</code> like so:</p>\n\n<pre><code>add_action( 'transition_post_status', 'do_updated_to_publish', 10, 2 );\nfunction do_updated_to_publish( $new_status, $old_status ) {\n if ( $new_status !== $old_status &amp;&amp; 'publish' === $new_status ) {\n add_action( 'wp_insert_post', 'updated_to_publish', 10, 2 );\n }\n}\n\nfunction updated_to_publish( $post_id, $post ) {\n // Remove it; it will be re-added via the do_updated_to_publish() function,\n // if necessary or when applicable.\n remove_action( 'wp_insert_post', 'updated_to_publish', 10, 2 );\n\n if ( ! defined( 'WPSEO_VERSION' ) || 'l' !== $post-&gt;post_type ) {\n return;\n }\n\n if ( get_field( 'advanced_option_edit_seo', $post_id ) ) {\n // Make your update_post_meta() calls here.\n update_post_meta( $post_id, '_yoast_wpseo_focuskw', 'test' );\n error_log( 'focuskw updated for post #' . $post_id );\n }\n}\n</code></pre>\n\n<p>Tried and tested working with Yoast SEO version 9.1.</p>\n" } ]
2018/11/08
[ "https://wordpress.stackexchange.com/questions/318704", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I am trying to update the field when post status changes to published. It is getting the values properly but not updating when I check the what update field is returning. It shows some number. Please help not sure whether I should use this along with `transition_post_status` --- **Update - I have tried below hooks** // the action is getting triggered but the fields are not updating *1. **publish** //works but no update is happening* *2. **save\_post** && **save\_post\_l** //works but no update is happening.* --- ``` add_action('transition_post_status', 'updated_to_publish', 10, 3); function updated_to_publish($new_status, $old_status, $post) { if ($new_status == 'publish')) // I have removed the check for post type { $post_id = $post->ID; if (get_field('advanced_option_edit_seo', $post_id)) { if (defined('WPSEO_VERSION')) { $metatitle = get_field('seo_title', $post_id); $metadesc = get_field('seo_meta_description', $post_id); $metakeywords = get_field('seo_keyword', $post_id); update_post_meta($post_id, '_yoast_wpseo_title', $metatitle ); update_post_meta($post_id, '_yoast_wpseo_metadesc', $metadesc ); update_post_meta($post_id, '_yoast_wpseo_focuskw', $metakeywords); } } } else { return; } } ``` --- --- Update ------ I was able to solve the issue by using '`wp_insert_post`' action . Can I know why other actions failed but '`wp_insert_post`' worked? code that i used for testing ``` add_action('transition_post_status', 'updated_to_publish', 10, 3); function updated_to_publish($new_status, $old_status, $post) { if (($new_status == 'publish') && ($post->post_type == 'l')) { $post_id = $post->ID; error_log( var_export( $post_id, 1 ) ); if (get_field('advanced_option_edit_seo', $post_id)) { if (defined('WPSEO_VERSION')) { // ACF field $metatitle = get_field('seo_title', $post_id); error_log( var_export( $metatitle, 1 ) ); $metadesc = get_field('seo_meta_description', $post_id); error_log( var_export( $metadesc, 1 ) ); $metakeywords = get_field('seo_keyword', $post_id); error_log( var_export( $metakeywords, 1 ) ); //plugin is activated //old values $metadesc_old = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true); error_log( var_export( $metadesc_old, 1 ) ); $metatitle_old = get_post_meta($post->ID, '_yoast_wpseo_title', true); error_log( var_export( $metatitle_old, 1 ) ); $metakeywords_old = get_post_meta($post->ID, '_yoast_wpseo_focuskw', true); error_log( var_export( $metakeywords_old, 1 ) ); update_post_meta($post_id, '_yoast_wpseo_title', $metatitle, $metatitle_old); error_log( var_export( $tyone, 1 ) ); update_post_meta($post_id, '_yoast_wpseo_metadesc', $metadesc, $metadesc_old); error_log( var_export( $tytwo, 1 ) ); update_post_meta($post_id, '_yoast_wpseo_focuskw', $metakeywords, $metakeywords_old); error_log( var_export( $tythree, 1 ) ); } } } else { return; } //Do something } ```
So I installed the [Yoast SEO plugin](https://yoast.com/wordpress/plugins/seo/), and tested your code, and now I can positively say "***neither no nor yes, but you could***" to this question: > > Please help not sure whether I should use this along with > `transition_post_status` > > > `transition_post_status` is fired *before* the `wp_insert_post` action is fired, and the Yoast SEO plugin is actually saving (adding/updating) all its custom fields via the `wp_insert_post` action: ``` // See WPSEO_Metabox::save_postdata() (in wordpress-seo/admin/metabox/class-metabox.php) add_action( 'wp_insert_post', array( $this, 'save_postdata' ) ); ``` So your code itself works, and the fields do get updated (if the new and current values are not the same and that all the `if` conditions are met, of course); however the Yoast SEO plugin overrides the value via the `WPSEO_Metabox::save_postdata()` function, which should answer this question: > > I was able to solve the issue by using '`wp_insert_post`' action . Can > I know why other actions failed but '`wp_insert_post`' worked? > > > **Why did I say *neither no nor yes, but you could*?** Because you can use `transition_post_status` along with `wp_insert_post` like so: ``` add_action( 'transition_post_status', 'do_updated_to_publish', 10, 2 ); function do_updated_to_publish( $new_status, $old_status ) { if ( $new_status !== $old_status && 'publish' === $new_status ) { add_action( 'wp_insert_post', 'updated_to_publish', 10, 2 ); } } function updated_to_publish( $post_id, $post ) { // Remove it; it will be re-added via the do_updated_to_publish() function, // if necessary or when applicable. remove_action( 'wp_insert_post', 'updated_to_publish', 10, 2 ); if ( ! defined( 'WPSEO_VERSION' ) || 'l' !== $post->post_type ) { return; } if ( get_field( 'advanced_option_edit_seo', $post_id ) ) { // Make your update_post_meta() calls here. update_post_meta( $post_id, '_yoast_wpseo_focuskw', 'test' ); error_log( 'focuskw updated for post #' . $post_id ); } } ``` Tried and tested working with Yoast SEO version 9.1.
318,751
<p>I'm using the Gutenberg editor as a replacement for a whiteboard in a classroom. I'm able to make the classroom more interactive by having students work directly inside the Gutenberg editor. As a long-term user of Wordpress it's truly wonderful to see this happen, with non-tech-savy users able to interact with the editor so easily.</p> <p>To provide some missing functionality I'd like to run a custom script inside the editor. It's a simple script which adds some styles if certain conditions are fulfilled. I currently run this script on the front-end using <code>wp_register_script</code> and <code>wp_enqueue_script</code> which is loaded onto the <code>wp_enqueue_scripts</code> action hook.</p> <p>Is it possible to load this script inside the Gutenberg editor, so that while my students are editing the post we can also have the script working?</p>
[ { "answer_id": 318760, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>I'm using the Gutenberg editor as a replacement for a whiteboard in a classroom. I'm \n able to make the classroom more interactive by having students work directly inside the \n Gutenberg editor.</p>\n</blockquote>\n\n<p>What a cool use of WordPress you describe there!</p>\n\n<blockquote>\n <p>Is it possible to load this script inside the Gutenberg editor, so that while my students are editing the post we can also have the script working?</p>\n</blockquote>\n\n<p>It seems that WordPress 5.0+ will provide us with two hooks for this:</p>\n\n<pre><code>/**\n * Fires after block assets have been enqueued for the editing interface.\n *\n * Call `add_action` on any hook before 'admin_enqueue_scripts'.\n *\n * In the function call you supply, simply use `wp_enqueue_script` and\n * `wp_enqueue_style` to add your functionality to the block editor.\n *\n * @since 5.0.0\n */\ndo_action( 'enqueue_block_editor_assets' );\n</code></pre>\n\n<p>and also for both editor and front-end:</p>\n\n<pre><code>/**\n * Fires after enqueuing block assets for both editor and front-end.\n *\n * Call `add_action` on any hook before 'wp_enqueue_scripts'.\n *\n * In the function call you supply, simply use `wp_enqueue_script` and\n * `wp_enqueue_style` to add your functionality to the Gutenberg editor.\n *\n * @since 5.0.0\n */\n do_action( 'enqueue_block_assets' );\n</code></pre>\n\n<p>Update: From the <a href=\"https://wordpress.org/gutenberg/handbook/packages/packages-blocks/#getting-started\" rel=\"noreferrer\">Gutenberg Handbook</a>:</p>\n\n<blockquote>\n <p>The <code>enqueue_block_editor_assets</code> hook is only run in the Gutenberg\n editor context when the editor is ready to receive additional scripts\n and stylesheets. There is also an <code>enqueue_block_assets</code> hook which is\n run under both the editor and front-end contexts. This should be used\n to enqueue stylesheets common to the front-end and the editor.</p>\n</blockquote>\n\n<p>So you could try to enqueue your scripts in the callback of either of those hooks as needed. It's also possible to add specific blocks as dependency.</p>\n" }, { "answer_id": 373227, "author": "Zakaria Binsaifullah", "author_id": 158754, "author_profile": "https://wordpress.stackexchange.com/users/158754", "pm_score": 0, "selected": false, "text": "<p>You can enqueue any style or script using this hook- <strong>enqueue_block_assets</strong>. The script/style inside this hook works for both backend &amp; front end. So, the example will be something like the following codes-</p>\n<pre><code>function sgb_external_scripts() {\nwp_enqueue_script(\n 'frontend-js',\n plugins_url( $sharedBlockPath, __FILE__ ),\n [ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],\n filemtime( plugin_dir_path( __FILE__ ) . $sharedBlockPath )\n );\n }\nadd_action( 'enqueue_block_assets', 'sgb_external_scripts' );\n</code></pre>\n<p>You can apply a trick to enqueue any style/scripts just for backend/editor. In this case, it will look like the following codes-</p>\n<pre><code>function sgb_external_scripts() {\n if( is_admin() ){\n wp_enqueue_script(\n 'frontend-js',\n plugins_url( $sharedBlockPath, __FILE__ ),\n [ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],\n filemtime( plugin_dir_path( __FILE__ ) . $sharedBlockPath )\n );\n }\n}\nadd_action( 'enqueue_block_assets', 'sgb_external_scripts' );\n</code></pre>\n" } ]
2018/11/09
[ "https://wordpress.stackexchange.com/questions/318751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34991/" ]
I'm using the Gutenberg editor as a replacement for a whiteboard in a classroom. I'm able to make the classroom more interactive by having students work directly inside the Gutenberg editor. As a long-term user of Wordpress it's truly wonderful to see this happen, with non-tech-savy users able to interact with the editor so easily. To provide some missing functionality I'd like to run a custom script inside the editor. It's a simple script which adds some styles if certain conditions are fulfilled. I currently run this script on the front-end using `wp_register_script` and `wp_enqueue_script` which is loaded onto the `wp_enqueue_scripts` action hook. Is it possible to load this script inside the Gutenberg editor, so that while my students are editing the post we can also have the script working?
> > I'm using the Gutenberg editor as a replacement for a whiteboard in a classroom. I'm > able to make the classroom more interactive by having students work directly inside the > Gutenberg editor. > > > What a cool use of WordPress you describe there! > > Is it possible to load this script inside the Gutenberg editor, so that while my students are editing the post we can also have the script working? > > > It seems that WordPress 5.0+ will provide us with two hooks for this: ``` /** * Fires after block assets have been enqueued for the editing interface. * * Call `add_action` on any hook before 'admin_enqueue_scripts'. * * In the function call you supply, simply use `wp_enqueue_script` and * `wp_enqueue_style` to add your functionality to the block editor. * * @since 5.0.0 */ do_action( 'enqueue_block_editor_assets' ); ``` and also for both editor and front-end: ``` /** * Fires after enqueuing block assets for both editor and front-end. * * Call `add_action` on any hook before 'wp_enqueue_scripts'. * * In the function call you supply, simply use `wp_enqueue_script` and * `wp_enqueue_style` to add your functionality to the Gutenberg editor. * * @since 5.0.0 */ do_action( 'enqueue_block_assets' ); ``` Update: From the [Gutenberg Handbook](https://wordpress.org/gutenberg/handbook/packages/packages-blocks/#getting-started): > > The `enqueue_block_editor_assets` hook is only run in the Gutenberg > editor context when the editor is ready to receive additional scripts > and stylesheets. There is also an `enqueue_block_assets` hook which is > run under both the editor and front-end contexts. This should be used > to enqueue stylesheets common to the front-end and the editor. > > > So you could try to enqueue your scripts in the callback of either of those hooks as needed. It's also possible to add specific blocks as dependency.
318,783
<p>New to WordPress programming (coming from a more conventional environment) and trying to understand some of its "unique" qualities.</p> <p>There is a directory page on our website and this code resides, that is in <code>functions.php</code>, tweaks the results if condition is true. </p> <pre><code>if( $query-&gt;is_post_type_archive( 'directory' ) ){ ...//do stuff } </code></pre> <p>I would like to know how to access the "value of <code>is_post_type_archive</code> that is "directory." When I use test for the value...</p> <pre><code>var_dumb($query-&gt;is_post_type_archive()); </code></pre> <p>..I get <code>bool(true)</code> which makes sense. But how/where is the value "directory" stored/passed/accessed?</p>
[ { "answer_id": 318785, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>First up, the first thing you should do is read the <a href=\"https://developer.wordpress.org\" rel=\"nofollow noreferrer\">developer docs</a>. This question touches on a lot of topics, and it's not going to be possible to explain them all in one answer.</p>\n\n<p>Anyway, <code>directory</code> would be a <a href=\"https://developer.wordpress.org/plugins/post-types/\" rel=\"nofollow noreferrer\">Custom Post Type</a> registered by the theme or a plugin. </p>\n\n<p>When a post type is <a href=\"https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/\" rel=\"nofollow noreferrer\">registered</a> the developer can tell WordPress what the URL path for its archive should be.</p>\n\n<p>WordPress will then create a <a href=\"https://developer.wordpress.org/reference/functions/add_rewrite_rule/\" rel=\"nofollow noreferrer\">rewrite rule</a> so that when a user visits that URL, WordPress receives a parameter that tells it that the user is requesting the archive for that post type.</p>\n\n<p>When the user visits that URL WordPress will query the posts it needs to show for that post type archive. It will do that with a <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\"><code>WP_Query()</code></a> object. As part of this query WordPress will set the <code>is_post_type_archive</code> property of that object to <code>true</code>, and the <code>post_type</code> property to <code>directory</code>.</p>\n\n<p>Developers can change the behaviour of post queries using the <code>pre_get_posts</code> <a href=\"https://developer.wordpress.org/plugins/hooks/filters/\" rel=\"nofollow noreferrer\">filter</a>. Since WordPress can run more than one post query on any given request, any functions used on this filter will receive the current <code>WP_Query</code> object as a parameter. The developer can then choose to modify the only the main query for the post type archive by checking if <code>$query-&gt;is_post_type_archive( 'directory' )</code> is <code>true</code> for the current query.</p>\n" }, { "answer_id": 318787, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>You found a regular WordPress object, <code>$query</code>, which is well documented in the <a href=\"https://developer.wordpress.org/reference/\" rel=\"nofollow noreferrer\">Code Reference</a> on <a href=\"https://developer.wordpress.org/reference/classes/wp_query/is_post_type_archive/\" rel=\"nofollow noreferrer\">its own page</a>:</p>\n<blockquote>\n<p><code>WP_Query::is_post_type_archive( mixed $post_types = '' )</code></p>\n<p>Is the query for an existing post type archive page?</p>\n<h2>Description</h2>\n<h3>Parameters</h3>\n<p><strong>$post_types</strong>\n(mixed) (Optional) Post type or array of posts types to check against.</p>\n<p>Default value: ''</p>\n</blockquote>\n<p>The <a href=\"https://developer.wordpress.org/reference/classes/wp_query/is_post_type_archive/#source\" rel=\"nofollow noreferrer\">source code</a> is given there as well. So what does <code>is_post_type_archive($post_types)</code> do?</p>\n<ul>\n<li><p><code>is_post_type_archive()</code> returns <code>true</code> if the current page is a post type archive of any kind</p>\n</li>\n<li><p><code>is_post_type_archive('foo')</code> returns <code>true</code> if the current page if a post type archive for the <a href=\"https://developer.wordpress.org/themes/basics/post-types/\" rel=\"nofollow noreferrer\">(custom) post type</a> <code>foo</code> (could be <code>post</code>, <code>page</code>, etc)</p>\n</li>\n<li><p><code>is_post_type_archive(['foo', 'bar'])</code> returns <code>true</code> if the current page is a post type archive for any of those (custom) post types <code>foo</code>, <code>bar</code>.</p>\n</li>\n</ul>\n" } ]
2018/11/09
[ "https://wordpress.stackexchange.com/questions/318783", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153797/" ]
New to WordPress programming (coming from a more conventional environment) and trying to understand some of its "unique" qualities. There is a directory page on our website and this code resides, that is in `functions.php`, tweaks the results if condition is true. ``` if( $query->is_post_type_archive( 'directory' ) ){ ...//do stuff } ``` I would like to know how to access the "value of `is_post_type_archive` that is "directory." When I use test for the value... ``` var_dumb($query->is_post_type_archive()); ``` ..I get `bool(true)` which makes sense. But how/where is the value "directory" stored/passed/accessed?
First up, the first thing you should do is read the [developer docs](https://developer.wordpress.org). This question touches on a lot of topics, and it's not going to be possible to explain them all in one answer. Anyway, `directory` would be a [Custom Post Type](https://developer.wordpress.org/plugins/post-types/) registered by the theme or a plugin. When a post type is [registered](https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/) the developer can tell WordPress what the URL path for its archive should be. WordPress will then create a [rewrite rule](https://developer.wordpress.org/reference/functions/add_rewrite_rule/) so that when a user visits that URL, WordPress receives a parameter that tells it that the user is requesting the archive for that post type. When the user visits that URL WordPress will query the posts it needs to show for that post type archive. It will do that with a [`WP_Query()`](https://developer.wordpress.org/reference/classes/wp_query/) object. As part of this query WordPress will set the `is_post_type_archive` property of that object to `true`, and the `post_type` property to `directory`. Developers can change the behaviour of post queries using the `pre_get_posts` [filter](https://developer.wordpress.org/plugins/hooks/filters/). Since WordPress can run more than one post query on any given request, any functions used on this filter will receive the current `WP_Query` object as a parameter. The developer can then choose to modify the only the main query for the post type archive by checking if `$query->is_post_type_archive( 'directory' )` is `true` for the current query.
318,801
<p>In May of 2016, I implemented several redirects on a client site using <code>.htaccess</code>. The client verified that all of the <code>.htaccess</code> redirects were working to their satisfaction before we closed out the project. </p> <p>This week, I was notified by the client that these redirects no longer work. They don't know when this began to fail and, after a few hours of research, I can't find any reason why they wouldn't continue to work.</p> <p>The client does not want to use a plugin for this.</p> <p>I'm including the <code>.htaccess</code> file for review and suggestions. </p> <pre><code># Disable XMLRPC &lt;Files "xmlrpc.php"&gt; Order Deny,Allow Deny from all &lt;/Files&gt; # End Disable XMLRPC # Force HTTPS RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # Redirects # Change "www" to "www" when moved to live RedirectMatch 301 ^/watermeloncakes/ //www.clienturl.com/watermelon-cakes-1/ RedirectMatch 301 ^/watermelon-cakes/ //www.clienturl.com/watermelon-cakes-1/ RedirectMatch 301 ^/edible-arrangements-coupons/ //www.clienturl.com/fruit-arrangements-coupons/ RedirectMatch 301 ^/edible-arrangements/ //www.clienturl.com/fruit-arrangements/ RedirectMatch 301 ^/edible-arrangements-5-reasons/ //www.clienturl.com/fruit-arrangements-5-reasons/ RedirectMatch 301 ^/candy/ //www.clienturl.com/blog/christmas-candy-platters RedirectMatch 301 ^/candy //www.clienturl.com/blog/christmas-candy-platters RedirectMatch 301 ^/pumpkin-carving-instruction-ray-villafane/ //www.clienturl.com/blog/shop/ray-villafanes-3d-pumpkin-carving/ RedirectMatch 301 ^/4thofjulyideas/ //www.clienturl.com/4th-of-july-ideas/ RedirectMatch 301 ^/pumpkin-carving-tattoos/ //www.clienturl.com/blog/shop/pumpkin-carving-patterns-tattoos/ RedirectMatch 302 ^/transfer-pattern-paper-carving-pumpkins-watermelons/ //www.clienturl.com/blog/product-category/patterns-and-transfer-papers/ RedirectMatch 302 ^/u-and-v-fruit-carving-tools/ //www.clienturl.com/blog/shop/u-v-fruit-carving-tools/ RedirectMatch 302 ^/fruit-carving-knife-set/ //www.clienturl.com/blog/shop/kom-kom-fruit-carving-knife-set/ RedirectMatch 302 ^/thai-pro-fruit-carving-knife/ //www.clienturl.com/blog/shop/thai-pro-carving-knife/ RedirectMatch 302 ^/13-pc-fruit-carving-tools/ //www.clienturl.com/blog/shop/pro-fruit-carving-tools-13-piece/ RedirectMatch 302 ^/corrugated-u-cutters-and-melon-baller/ //www.clienturl.com/blog/shop/corrugated-u-cutters/ RedirectMatch 301 ^/shop/ //www.clienturl.com/blog/shop/ RedirectMatch 301 ^/pp-resources/ //www.clienturl.com/blog/pumpkin-portraits-resources-members/ RedirectMatch 301 ^/dvd-lessons-and-tool-sets/ //www.clienturl.com/blog/shop/ RedirectMatch 301 ^/message-sent-success/ //www.clienturl.com/blog/your-message-successfully-sent/ RedirectMatch 301 ^/which-lessons-tools-for-you/ //www.clienturl.com/blog/best-lessons-for-you/ RedirectMatch 301 ^/fabric //www.clienturl.com/blog/shop/pattern-transfer-fabric/ RedirectMatch 301 ^/101 //www.clienturl.com/vegetable-and-fruit-carving-course-101 RedirectMatch 301 ^/weave //www.clienturl.com/blog/shop/melon-basket-weave/ RedirectMatch 301 ^/twirl //www.clienturl.com/blog/shop/twisty-twirl-tool/ RedirectMatch 301 ^/vegcurl //www.clienturl.com/blog/shop/vegetable-curler/ RedirectMatch 301 ^/wavy //www.clienturl.com/blog/shop/wavy-peeler/ #IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti* #&lt;Limit GET POST&gt; #The next line modified by DenyIP #order allow,deny #The next line modified by DenyIP #deny from all #allow from all #&lt;/Limit&gt; #&lt;Limit PUT DELETE&gt; #order deny,allow #deny from all #&lt;/Limit&gt; #AuthName vegetablefruitcarving.com # stop hotlinking and serve alternate content # &lt;IfModule mod_rewrite.c&gt; # RewriteEngine on # RewriteCond %{HTTP_REFERER} !^$ # RewriteCond %{HTTP_REFERER} !^http://(www\.)?vegetablefruitcarving\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?vegetablefruitcarving\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?sbox\.vegetablefruitcarving\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?twitter\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?twitter\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?facebook\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?facebook\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?pinterest\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?pinterest\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?youtube\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?youtube\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?flickr\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?flickr\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?plus.google\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?plus.google\.com/.*$ [NC] # RewriteRule .*\.(gif|jpg|png|pdf)$ //altlab.com/hotlinking.html [R,NC,L] # &lt;/ifModule&gt; &lt;Files 403.shtml&gt; order allow,deny allow from all &lt;/Files&gt; deny from 79.29.221.71 # BEGIN WPSuperCache &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / #If you serve pages from behind a proxy you may want to change 'RewriteCond %{HTTPS} on' to something more sensible AddDefaultCharset UTF-8 RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{HTTPS} on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html.gz -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html.gz" [L] RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{HTTPS} !on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html.gz -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html.gz" [L] RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTPS} on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html" [L] RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTPS} !on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html" [L] &lt;/IfModule&gt; # END WPSuperCache # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 318807, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 0, "selected": false, "text": "<p>Enable the <strong>Apache mod_rewrite module.</strong><br>\nAnd enable the <strong>ReWriteEngine</strong> in the <strong>mod_rewrite module</strong>.<br><br>\nBelow an example of how to use RewriteRule:</p>\n\n<pre><code># Turning on the rewrite engine is necessary for the following rules and\n# features. \"+FollowSymLinks\" must be enabled for this to work symbolically.\n\n&lt;IfModule mod_rewrite.c&gt;\nOptions +FollowSymLinks\nRewriteEngine on\n\nRewriteRule ^panda$ /tiger [R=301,L]\nRewriteRule ^house$ /car [R=301,L]\nRewriteRule ^monkey$ /deer [R=301,L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Also some other advice, I see you're using <strong>WP Super Cache</strong> and I would like to recommend <strong>WP Fastest Cache</strong> this is one of the best free caching plugins out there. See: <a href=\"https://wordpress.org/plugins/wp-fastest-cache/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-fastest-cache/</a></p>\n\n<p>And if your theme supports this, you could use this in combination with <strong>Fast Velocity Minify</strong> see: <a href=\"https://wordpress.org/plugins/fast-velocity-minify/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/fast-velocity-minify/</a></p>\n\n<p>With this combination, our company <a href=\"https://advanzadirect.nl\" rel=\"nofollow noreferrer\">website</a> tend to score almost a perfect 100 on gtmetrix.com, using <strong>WP Fastest Cache</strong> and <strong>Fast Velocity Minify</strong></p>\n\n<p>Also, keep things simple, there is also a plugin called <strong>Redirection</strong> who is doing the same thing you're trying to achieve. I highly recommend this plugin for any redirect: <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/redirection/</a></p>\n" }, { "answer_id": 318818, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<blockquote>\n<pre><code>RedirectMatch 301 ^/watermeloncakes/ //www.clienturl.com/watermelon-cakes-1/\n</code></pre>\n</blockquote>\n\n<p>(I assuming <code>www.clienturl.com</code> is the <em>hostname</em> for this site.)</p>\n\n<p>Well, here's the thing... this would never have worked on any version of Apache!? Because protocol-relative URLs are not supported by mod_alias <code>RedirectMatch</code> (or <code>Redirect</code>) or mod_rewrite for that matter.</p>\n\n<p>From the <a href=\"https://httpd.apache.org/docs/2.4/mod/mod_alias.html#redirect\" rel=\"nofollow noreferrer\">Apache docs</a>:</p>\n\n<blockquote>\n <p>The new URL may be either an absolute URL beginning with a scheme and hostname, or a URL-path beginning with a slash. In this latter case the scheme and hostname of the current server will be added.</p>\n</blockquote>\n\n<p>A protocol-relative URL such as <code>//www.clienturl.com/watermelon-cakes-1/</code> will simply be seen as root-relative (\"a URL-path beginning with a slash\"), so the above directive would result in a malformed redirect to:</p>\n\n<pre><code>https://www.clienturl.com//www.clienturl.com/watermelon-cakes-1/\n</code></pre>\n\n<p>It's possible that another redirect later corrected this (perhaps in WordPress itself)!? But there is no evidence of this in your <code>.htaccess</code> file. </p>\n\n<p>It is Apache that constructs this absolute URL when it creates the <code>Location</code> header to send back to the client. It doesn't send back a protocol-relative URL and expect the client to resolve it (which you could do if you manually assigned a value to the <code>Location</code> header in your server-side script).</p>\n\n<p>If these directives ever worked, then it looks like someone has either removed the protocol (<code>https:</code> or <code>http:</code>?) from the target URL, or added the hostname (<code>//www.clienturl.com</code>)? Is it possible that these were initially redirects to <code>http:</code> and someone thought they'd try to avoid the \"double redirect\" (since you are forcing HTTPS) by making them \"protocol relative\"?</p>\n\n<p>The above directive would need to either use a full absolute URL:</p>\n\n<pre><code>RedirectMatch 301 ^/watermeloncakes/ https://www.clienturl.com/watermelon-cakes-1/\n</code></pre>\n\n<p>Or use a root-relative URL:</p>\n\n<pre><code>RedirectMatch 301 ^/watermeloncakes/ /watermelon-cakes-1/\n</code></pre>\n\n<h3>Use mod_rewrite instead</h3>\n\n<p>However, you should really be using mod_rewrite <code>RewriteRule</code> for these redirects instead of a mod_alias <code>RedirectMatch</code> (or <code>Redirect</code>) directive. Simply because you should avoid mixing redirects/rewrites from both modules and you are already using mod_rewrite throughout your <code>.htaccess</code> file - WordPress itself uses mod_rewrite to implement its front-controller model.</p>\n\n<p>For example:</p>\n\n<pre><code>RewriteRule ^watermeloncakes/ /watermelon-cakes-1/ [R=301,L]\n</code></pre>\n\n<p>(There is no need to repeat the <code>RewriteEngine</code> directive.)</p>\n\n<p>Apache modules execute independently and at different times throughout the request. mod_rewrite executes <em>before</em> mod_alias, regardless of the apparent order of the directives in the <code>.htaccess</code> file. You could, for instance, place all the <code>RedirectMatch</code> directives at the end of the file and it would make no difference to the execution order.</p>\n\n<p>So, by mixing redirects from both modules you can end up with unexpected conflicts, since mod_rewrite will always take priority, regardless of the order. But also, all the mod_rewrite directives are being processed first, before the mod_alias redirects - everything is being processed on every request (regardless of whether there is a redirect or not). If you use mod_rewrite then the redirect occurs immediately and the remaining directives are bypassed.</p>\n\n<h3>Use WordPress instead (preferable)</h3>\n\n<p>However, since all these redirects look as if they are probably just correcting URLs, URLs that would otherwise trigger 404s then it would be preferable to perform these redirects in your server-side code (ie. WordPress) instead. For example, once WordPress has determined the URL would result in a 404, then check your redirects. Doing it this way avoids any of the redirect code \"slowing down\" normal site usage.</p>\n" } ]
2018/11/09
[ "https://wordpress.stackexchange.com/questions/318801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64749/" ]
In May of 2016, I implemented several redirects on a client site using `.htaccess`. The client verified that all of the `.htaccess` redirects were working to their satisfaction before we closed out the project. This week, I was notified by the client that these redirects no longer work. They don't know when this began to fail and, after a few hours of research, I can't find any reason why they wouldn't continue to work. The client does not want to use a plugin for this. I'm including the `.htaccess` file for review and suggestions. ``` # Disable XMLRPC <Files "xmlrpc.php"> Order Deny,Allow Deny from all </Files> # End Disable XMLRPC # Force HTTPS RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # Redirects # Change "www" to "www" when moved to live RedirectMatch 301 ^/watermeloncakes/ //www.clienturl.com/watermelon-cakes-1/ RedirectMatch 301 ^/watermelon-cakes/ //www.clienturl.com/watermelon-cakes-1/ RedirectMatch 301 ^/edible-arrangements-coupons/ //www.clienturl.com/fruit-arrangements-coupons/ RedirectMatch 301 ^/edible-arrangements/ //www.clienturl.com/fruit-arrangements/ RedirectMatch 301 ^/edible-arrangements-5-reasons/ //www.clienturl.com/fruit-arrangements-5-reasons/ RedirectMatch 301 ^/candy/ //www.clienturl.com/blog/christmas-candy-platters RedirectMatch 301 ^/candy //www.clienturl.com/blog/christmas-candy-platters RedirectMatch 301 ^/pumpkin-carving-instruction-ray-villafane/ //www.clienturl.com/blog/shop/ray-villafanes-3d-pumpkin-carving/ RedirectMatch 301 ^/4thofjulyideas/ //www.clienturl.com/4th-of-july-ideas/ RedirectMatch 301 ^/pumpkin-carving-tattoos/ //www.clienturl.com/blog/shop/pumpkin-carving-patterns-tattoos/ RedirectMatch 302 ^/transfer-pattern-paper-carving-pumpkins-watermelons/ //www.clienturl.com/blog/product-category/patterns-and-transfer-papers/ RedirectMatch 302 ^/u-and-v-fruit-carving-tools/ //www.clienturl.com/blog/shop/u-v-fruit-carving-tools/ RedirectMatch 302 ^/fruit-carving-knife-set/ //www.clienturl.com/blog/shop/kom-kom-fruit-carving-knife-set/ RedirectMatch 302 ^/thai-pro-fruit-carving-knife/ //www.clienturl.com/blog/shop/thai-pro-carving-knife/ RedirectMatch 302 ^/13-pc-fruit-carving-tools/ //www.clienturl.com/blog/shop/pro-fruit-carving-tools-13-piece/ RedirectMatch 302 ^/corrugated-u-cutters-and-melon-baller/ //www.clienturl.com/blog/shop/corrugated-u-cutters/ RedirectMatch 301 ^/shop/ //www.clienturl.com/blog/shop/ RedirectMatch 301 ^/pp-resources/ //www.clienturl.com/blog/pumpkin-portraits-resources-members/ RedirectMatch 301 ^/dvd-lessons-and-tool-sets/ //www.clienturl.com/blog/shop/ RedirectMatch 301 ^/message-sent-success/ //www.clienturl.com/blog/your-message-successfully-sent/ RedirectMatch 301 ^/which-lessons-tools-for-you/ //www.clienturl.com/blog/best-lessons-for-you/ RedirectMatch 301 ^/fabric //www.clienturl.com/blog/shop/pattern-transfer-fabric/ RedirectMatch 301 ^/101 //www.clienturl.com/vegetable-and-fruit-carving-course-101 RedirectMatch 301 ^/weave //www.clienturl.com/blog/shop/melon-basket-weave/ RedirectMatch 301 ^/twirl //www.clienturl.com/blog/shop/twisty-twirl-tool/ RedirectMatch 301 ^/vegcurl //www.clienturl.com/blog/shop/vegetable-curler/ RedirectMatch 301 ^/wavy //www.clienturl.com/blog/shop/wavy-peeler/ #IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti* #<Limit GET POST> #The next line modified by DenyIP #order allow,deny #The next line modified by DenyIP #deny from all #allow from all #</Limit> #<Limit PUT DELETE> #order deny,allow #deny from all #</Limit> #AuthName vegetablefruitcarving.com # stop hotlinking and serve alternate content # <IfModule mod_rewrite.c> # RewriteEngine on # RewriteCond %{HTTP_REFERER} !^$ # RewriteCond %{HTTP_REFERER} !^http://(www\.)?vegetablefruitcarving\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?vegetablefruitcarving\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?sbox\.vegetablefruitcarving\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?twitter\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?twitter\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?facebook\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?facebook\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?pinterest\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?pinterest\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?youtube\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?youtube\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?flickr\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?flickr\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^http://(www\.)?plus.google\.com/.*$ [NC] # RewriteCond %{HTTP_REFERER} !^https://(www\.)?plus.google\.com/.*$ [NC] # RewriteRule .*\.(gif|jpg|png|pdf)$ //altlab.com/hotlinking.html [R,NC,L] # </ifModule> <Files 403.shtml> order allow,deny allow from all </Files> deny from 79.29.221.71 # BEGIN WPSuperCache <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / #If you serve pages from behind a proxy you may want to change 'RewriteCond %{HTTPS} on' to something more sensible AddDefaultCharset UTF-8 RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{HTTPS} on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html.gz -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html.gz" [L] RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{HTTPS} !on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html.gz -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html.gz" [L] RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTPS} on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index-https.html" [L] RewriteCond %{REQUEST_URI} !^.*[^/]$ RewriteCond %{REQUEST_URI} !^.*//.*$ RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{QUERY_STRING} !.*=.* RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp-postpass_).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTPS} !on RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html -f RewriteRule ^(.*) "/wp-content/cache/supercache/%{SERVER_NAME}/$1/index.html" [L] </IfModule> # END WPSuperCache # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ```
> > > ``` > RedirectMatch 301 ^/watermeloncakes/ //www.clienturl.com/watermelon-cakes-1/ > > ``` > > (I assuming `www.clienturl.com` is the *hostname* for this site.) Well, here's the thing... this would never have worked on any version of Apache!? Because protocol-relative URLs are not supported by mod\_alias `RedirectMatch` (or `Redirect`) or mod\_rewrite for that matter. From the [Apache docs](https://httpd.apache.org/docs/2.4/mod/mod_alias.html#redirect): > > The new URL may be either an absolute URL beginning with a scheme and hostname, or a URL-path beginning with a slash. In this latter case the scheme and hostname of the current server will be added. > > > A protocol-relative URL such as `//www.clienturl.com/watermelon-cakes-1/` will simply be seen as root-relative ("a URL-path beginning with a slash"), so the above directive would result in a malformed redirect to: ``` https://www.clienturl.com//www.clienturl.com/watermelon-cakes-1/ ``` It's possible that another redirect later corrected this (perhaps in WordPress itself)!? But there is no evidence of this in your `.htaccess` file. It is Apache that constructs this absolute URL when it creates the `Location` header to send back to the client. It doesn't send back a protocol-relative URL and expect the client to resolve it (which you could do if you manually assigned a value to the `Location` header in your server-side script). If these directives ever worked, then it looks like someone has either removed the protocol (`https:` or `http:`?) from the target URL, or added the hostname (`//www.clienturl.com`)? Is it possible that these were initially redirects to `http:` and someone thought they'd try to avoid the "double redirect" (since you are forcing HTTPS) by making them "protocol relative"? The above directive would need to either use a full absolute URL: ``` RedirectMatch 301 ^/watermeloncakes/ https://www.clienturl.com/watermelon-cakes-1/ ``` Or use a root-relative URL: ``` RedirectMatch 301 ^/watermeloncakes/ /watermelon-cakes-1/ ``` ### Use mod\_rewrite instead However, you should really be using mod\_rewrite `RewriteRule` for these redirects instead of a mod\_alias `RedirectMatch` (or `Redirect`) directive. Simply because you should avoid mixing redirects/rewrites from both modules and you are already using mod\_rewrite throughout your `.htaccess` file - WordPress itself uses mod\_rewrite to implement its front-controller model. For example: ``` RewriteRule ^watermeloncakes/ /watermelon-cakes-1/ [R=301,L] ``` (There is no need to repeat the `RewriteEngine` directive.) Apache modules execute independently and at different times throughout the request. mod\_rewrite executes *before* mod\_alias, regardless of the apparent order of the directives in the `.htaccess` file. You could, for instance, place all the `RedirectMatch` directives at the end of the file and it would make no difference to the execution order. So, by mixing redirects from both modules you can end up with unexpected conflicts, since mod\_rewrite will always take priority, regardless of the order. But also, all the mod\_rewrite directives are being processed first, before the mod\_alias redirects - everything is being processed on every request (regardless of whether there is a redirect or not). If you use mod\_rewrite then the redirect occurs immediately and the remaining directives are bypassed. ### Use WordPress instead (preferable) However, since all these redirects look as if they are probably just correcting URLs, URLs that would otherwise trigger 404s then it would be preferable to perform these redirects in your server-side code (ie. WordPress) instead. For example, once WordPress has determined the URL would result in a 404, then check your redirects. Doing it this way avoids any of the redirect code "slowing down" normal site usage.
318,804
<p>I am using this code to display all custom post types along with their count on the "At a Glance" dashboard widget:</p> <pre><code>add_action( 'dashboard_glance_items', 'cpad_at_glance_content_table_end' ); function cpad_at_glance_content_table_end() { $args = array( 'public' =&gt; true, '_builtin' =&gt; false, ); $output = 'object'; $operator = 'and'; $post_types = get_post_types( $args, $output, $operator ); foreach ( $post_types as $post_type ) { $num_posts = wp_count_posts( $post_type-&gt;name ); $num = number_format_i18n( $num_posts-&gt;publish ); $text = _n( $post_type-&gt;labels-&gt;singular_name, $post_type-&gt;labels-&gt;name, intval( $num_posts-&gt;publish ) ); if ( current_user_can( 'edit_posts' ) ) { $output = '&lt;a href="edit.php?post_type=' . $post_type-&gt;name . '"&gt;' . $num . ' ' . $text . '&lt;/a&gt;'; echo '&lt;li class="post-count ' . $post_type-&gt;name . '-count"&gt;' . $output . '&lt;/li&gt;'; } else { $output = '&lt;span&gt;' . $num . ' ' . $text . '&lt;/span&gt;'; echo '&lt;li class="post-count ' . $post_type-&gt;name . '-count"&gt;' . $output . '&lt;/li&gt;'; } } } </code></pre> <p>Is there a way to only display the count of posts belonging to the current logged in author?</p>
[ { "answer_id": 318813, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>I think what you're after is:</p>\n\n<pre><code> // The user is logged, retrieve the user id (this needs to go above your foreach)\n $user_ID = get_current_user_id(); \n // Now we have got the user's id, we can pass it to the foreach of your function(this needs to go into your foreach: \n echo '&lt;li&gt;Number of '.$post_type-&gt;name.' posts published by me: ' . count_user_posts( $user_ID , $post_type-&gt;name ).'&lt;/li&gt;';\n</code></pre>\n" }, { "answer_id": 318864, "author": "quantum_leap", "author_id": 153810, "author_profile": "https://wordpress.stackexchange.com/users/153810", "pm_score": 0, "selected": false, "text": "<p>I have modified the answer from @rudtek and I am displaying the code here. Basically, the <code>count_user_posts</code> function needed the <code>name</code> method passed on the post type, otherwise, the output was '0'.</p>\n\n<pre><code>add_action( 'dashboard_glance_items', 'cpad_at_glance_content_table_end' );\nfunction cpad_at_glance_content_table_end() {\n$args = array(\n 'public' =&gt; true,\n '_builtin' =&gt; false,\n);\n$output = 'object';\n$operator = 'and';\n\n$post_types = get_post_types( $args, $output, $operator );\nforeach ( $post_types as $post_type ) {\n $user_ID = get_current_user_id();\n $num_posts = count_user_posts( $user_ID , $post_type-&gt;name );\n $text = _n( $post_type-&gt;labels-&gt;singular_name, $post_type-&gt;labels-&gt;name, intval( $num_posts-&gt;publish ) );\n if ( current_user_can( 'edit_posts' ) ) {\n\n $output = '&lt;a href=\"edit.php?post_type=' . $post_type-&gt;name . '\"&gt;' . $num_posts . ' ' . $text . '&lt;/a&gt;';\n echo '&lt;li class=\"post-count ' . $post_type-&gt;name . '-count\"&gt;' . $output . '&lt;/li&gt;';\n } else {\n $output = '&lt;span&gt;' . $num_posts . ' ' . $text . '&lt;/span&gt;';\n echo '&lt;li class=\"post-count ' . $post_type-&gt;name . '-count\"&gt;' . $output . '&lt;/li&gt;';\n }\n }\n}\n</code></pre>\n" } ]
2018/11/09
[ "https://wordpress.stackexchange.com/questions/318804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153810/" ]
I am using this code to display all custom post types along with their count on the "At a Glance" dashboard widget: ``` add_action( 'dashboard_glance_items', 'cpad_at_glance_content_table_end' ); function cpad_at_glance_content_table_end() { $args = array( 'public' => true, '_builtin' => false, ); $output = 'object'; $operator = 'and'; $post_types = get_post_types( $args, $output, $operator ); foreach ( $post_types as $post_type ) { $num_posts = wp_count_posts( $post_type->name ); $num = number_format_i18n( $num_posts->publish ); $text = _n( $post_type->labels->singular_name, $post_type->labels->name, intval( $num_posts->publish ) ); if ( current_user_can( 'edit_posts' ) ) { $output = '<a href="edit.php?post_type=' . $post_type->name . '">' . $num . ' ' . $text . '</a>'; echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>'; } else { $output = '<span>' . $num . ' ' . $text . '</span>'; echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>'; } } } ``` Is there a way to only display the count of posts belonging to the current logged in author?
I think what you're after is: ``` // The user is logged, retrieve the user id (this needs to go above your foreach) $user_ID = get_current_user_id(); // Now we have got the user's id, we can pass it to the foreach of your function(this needs to go into your foreach: echo '<li>Number of '.$post_type->name.' posts published by me: ' . count_user_posts( $user_ID , $post_type->name ).'</li>'; ```
318,816
<p>I installed the Siteimprove plugin to my client's WordPress website and I need to provide editor access to the plugin. Editors by default do not have any access to plugins. I tried to add the following to my <code>functions.php</code>:</p> <pre><code>if (!current_user_can('manage_options')) { add_menu_page( 'Siteimprove Plugin', 'Siteimprove', 'manage_options', 'siteimprove', 'siteimprove_settings_form' ); } </code></pre> <p>This is the code from the Siteimprove plugin that adds it to the menu:</p> <pre><code>/** * Register menu for settings form page. */ public function register_menu() { // Add top level menu page. add_menu_page( __('Siteimprove Plugin'), __('Siteimprove'), 'manage_options', 'siteimprove', 'Siteimprove_Admin_Settings::siteimprove_settings_form' ); } </code></pre> <p>I created a test editor account and this is not working. Am I missing something to get this working? Thanks for your help!</p>
[ { "answer_id": 318820, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": 1, "selected": false, "text": "<p>I have read the about this function and I see you need to parameter <code>capability</code> to allows the user can see the menu as an <code>admin</code> or <code>editor</code>.</p>\n\n<p>Read more the function to know detail: <a href=\"https://developer.wordpress.org/reference/functions/add_menu_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_menu_page/</a></p>\n\n<p>And you can try this the following code.</p>\n\n<pre><code>/**\n * Register menu for settings form page.\n */\npublic function register_menu() {\n // Add top level menu page.\n add_menu_page(\n __('Siteimprove Plugin'),\n __('Siteimprove'),\n 'edit_posts',//change this line 'manage_options' to 'edit_posts'\n 'siteimprove',\n 'Siteimprove_Admin_Settings::siteimprove_settings_form'\n );\n}\n</code></pre>\n\n<p>I hope it works for you. Good luck!</p>\n" }, { "answer_id": 318821, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>When adding a menu item, there's a capability check for 'manage_options'. You would need to change that permission to something specific for the editor:</p>\n\n<pre><code> add_menu_page(\n 'Siteimprove Plugin',\n 'Siteimprove',\n 'edit_others_pages',\n 'siteimprove',\n 'siteimprove_settings_form'\n );\n</code></pre>\n\n<p>You also removed the class from the method that is run to generate the page, so you should add that back how it was in the first snippet:</p>\n\n<pre><code> add_menu_page(\n 'Siteimprove Plugin',\n 'Siteimprove',\n 'edit_others_pages',\n 'siteimprove',\n 'Siteimprove_Admin_Settings::siteimprove_settings_form'\n );\n</code></pre>\n\n<p>You can reference <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow noreferrer\">WordPress Roles and Capabilities</a> for more indepth information in the Codex.</p>\n\n<p>In looking into the plugin itself, I don't think just changing that is going to resolve your issues though as the plugin has other checks for the admin user in the functionality it has.</p>\n\n<p>The first step I would take is to check the current user's role to first make sure they are the role you want to provide the menu and access for. To do that I would write something like this:</p>\n\n<pre><code> function wpse_318816_get_current_user_role() {\n if ( is_user_logged_in() ) {\n $user = wp_get_current_user();\n return in_array( 'editor', $user-&gt;roles );\n }\n }\n</code></pre>\n\n<p>This uses the WordPress methods <code>is_user_logged_in()</code> and <code>wp_get_current_user()</code> to check if they are logged in, and obtain the user object. In the user object there's a property for roles containing an array of roles available. We can check here if the current user's role is the editor, and then add our menu like so:</p>\n\n<pre><code> // Adds the siteimprove menu for the editor role's capability.\n function wpse_318816_add_editor_menu() {\n if ( wpse_318816_get_current_user_role() ) {\n add_menu_page(\n 'Siteimprove Plugin',\n 'Siteimprove',\n 'edit_others_pages',\n 'siteimprove',\n 'Siteimprove_Admin_Settings::siteimprove_settings_form'\n );\n }\n }\n\n add_action( 'admin_init', 'wpse_318816_add_editor_menu' );\n</code></pre>\n\n<p>This handles adding the menu in the dashboard for the editor, but then you run into the actual functionality used in the plugin there not working. Your best bet at this point is to remap the capability for the editor on that page.</p>\n\n<p>To do so, you would make use of the <code>map_meta_cap</code> <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\">filter</a>, and check if manage_options is being used for the specific cases you want. This prevents the editor from having too much access elsewhere in your site - ie admin privileges when they should only be editors. Using the filter, something like this should help allow the capability that the editor role has of edit_others_pages to be used for the manage_options capability which is for admins:</p>\n\n<pre><code> // Remaps edit capability to the user role.\n function wpse_318816_add_editor_cap( $caps = array(), $cap = '', $user_id = 0, $args = array() ) {\n global $pagenow;\n\n if ( $cap !== 'manage_options' ) {\n return $caps;\n }\n\n // Remove the filter to prevent resursive loops.\n remove_filter( 'map_meta_cap', 'wpse_318816_add_editor_cap', 11 );\n\n // Abort for admin.\n if ( current_user_can( 'administrator' ) ) {\n return $caps;\n }\n\n if ( wpse_318816_get_current_user_role() ) {\n\n // Check if you're on the adminpage for siteimprove.\n if ( ( $pagenow === 'admin.php' &amp;&amp; $_GET['page'] === 'siteimprove' ) ||\n\n // Check if you're submitting the token request form.\n ( $pagenow === 'options.php' &amp;&amp; $_POST['option_page'] === 'siteimprove' ) ) {\n\n // Set caps to edit_others_pages for the editor role.\n $caps = array( 'edit_others_pages' );\n\n // Re-add the filter.\n add_filter( 'map_meta_cap', 'wpse_318816_add_editor_cap', 11, 4 );\n\n // Remove the menu page as we are remapping manage_options to edit_others_pages.\n remove_menu_page( 'siteimprove' );\n }\n }\n\n return $caps;\n }\n\n add_filter( 'map_meta_cap', 'wpse_318816_add_editor_cap', 11, 4 );\n</code></pre>\n\n<p>One caveat I saw was of course in this particular instance the menu item is added back, so two menus are displayed. To resolve this I just removed the custom menu we added with remove_menu_page() when the user is the plugin's pages etc.</p>\n\n<p>I would suggest using this code as a plugin opposed to just adding stuff into your theme's <code>functions.php</code> file, so you don't loose the changes on updates and whatnot. I went ahead and <a href=\"https://gist.github.com/timelsass/87b24de86a9cce6633bbc55ed4213a5f\" rel=\"nofollow noreferrer\">created a gist so you can view the full code</a>. You can also <a href=\"https://gist.github.com/timelsass/87b24de86a9cce6633bbc55ed4213a5f/archive/7a3671d04677eb02b02139c71019656b6d31adf6.zip\" rel=\"nofollow noreferrer\">download and install the .zip</a> and install it as a plugin to test and modify further for your own needs.</p>\n" } ]
2018/11/10
[ "https://wordpress.stackexchange.com/questions/318816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115186/" ]
I installed the Siteimprove plugin to my client's WordPress website and I need to provide editor access to the plugin. Editors by default do not have any access to plugins. I tried to add the following to my `functions.php`: ``` if (!current_user_can('manage_options')) { add_menu_page( 'Siteimprove Plugin', 'Siteimprove', 'manage_options', 'siteimprove', 'siteimprove_settings_form' ); } ``` This is the code from the Siteimprove plugin that adds it to the menu: ``` /** * Register menu for settings form page. */ public function register_menu() { // Add top level menu page. add_menu_page( __('Siteimprove Plugin'), __('Siteimprove'), 'manage_options', 'siteimprove', 'Siteimprove_Admin_Settings::siteimprove_settings_form' ); } ``` I created a test editor account and this is not working. Am I missing something to get this working? Thanks for your help!
I have read the about this function and I see you need to parameter `capability` to allows the user can see the menu as an `admin` or `editor`. Read more the function to know detail: <https://developer.wordpress.org/reference/functions/add_menu_page/> And you can try this the following code. ``` /** * Register menu for settings form page. */ public function register_menu() { // Add top level menu page. add_menu_page( __('Siteimprove Plugin'), __('Siteimprove'), 'edit_posts',//change this line 'manage_options' to 'edit_posts' 'siteimprove', 'Siteimprove_Admin_Settings::siteimprove_settings_form' ); } ``` I hope it works for you. Good luck!
318,824
<p>Total newbie here. I'm a pretty good user of applications, but have never written a single line of code. Installed XAMPP and WP, purchased a template from Envato and plan on working on it over the weekend. Followed instructions for both WP and XAMPP, and all seems to be fine. Running solely on local machine, MAC running Mojave.</p> <p>Go to install the .zip file on WP, and it asks for credentials for FTP. Not sure what I need to put in here, or what to do to change in order to install the .zip file for my template site.</p> <p>Any suggestions or recommendations are appreciated in advance.</p> <p>JVN</p>
[ { "answer_id": 318830, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 4, "selected": false, "text": "<p>Congratulation Jon, welcome to the WordPress world!</p>\n\n<p>To fix the issue, just add the following line of code in your installed WordPress's <code>wp-config.php</code> file. It's a PHP constant declaration which tells the WordPress to avoid the FTP. That's it.</p>\n\n<pre><code>define( 'FS_METHOD', 'direct' );\n</code></pre>\n\n<p>For more info: <a href=\"https://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants\" rel=\"noreferrer\">https://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants</a></p>\n" }, { "answer_id": 386783, "author": "Claudee", "author_id": 205055, "author_profile": "https://wordpress.stackexchange.com/users/205055", "pm_score": 0, "selected": false, "text": "<p>In my case Im using a Linux machine (Debian) and I reckon there must be an authorization step included into this process to get the update done.\nSo, this is what I got in the first trial:</p>\n<p>Downloading update from <a href=\"https://downloads.wordpress.org/release/wordpress-5.7.1-no-content.zip%E2%80%A6\" rel=\"nofollow noreferrer\">https://downloads.wordpress.org/release/wordpress-5.7.1-no-content.zip…</a></p>\n<p>The authenticity of wordpress-5.7.1-no-content.zip could not be verified as no signature was found.</p>\n<p>Unpacking the update…</p>\n<p>Could not create directory.</p>\n<p>Installation failed.</p>\n<p>Thanks in advance!</p>\n<p>So my solution was Updating WP manually. Here the details to follow:\n<a href=\"https://wordpress.org/support/article/updating-wordpress/#manual-update\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/updating-wordpress/#manual-update</a></p>\n" }, { "answer_id": 405214, "author": "Yan Lieb", "author_id": 221688, "author_profile": "https://wordpress.stackexchange.com/users/221688", "pm_score": 0, "selected": false, "text": "<p>In my case, only adding the 'define' line in my wp-config wasn't working.</p>\n<p>I also had to give full permission to admin &amp; everyone to read/write my xampp folder and its subfolder :</p>\n<ul>\n<li>right-click on the folder itself</li>\n<li>give permission to modify by clicking on the lock</li>\n<li>change admin &amp; everyone permission to read and write in the 'sharing &amp; permissions' menu</li>\n<li>click on the ... below (next to + and - buttons) and select (apply to enclosed items)</li>\n</ul>\n<p>I don't know if this is related, but after this change, my MySql Database stopped working. I found this debug for that issue :</p>\n<ul>\n<li>open terminal and enter :\nsudo /Applications/XAMPP/xamppfiles/bin/mysql.server start</li>\n</ul>\n<p>Hope this helps.</p>\n" } ]
2018/11/10
[ "https://wordpress.stackexchange.com/questions/318824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153823/" ]
Total newbie here. I'm a pretty good user of applications, but have never written a single line of code. Installed XAMPP and WP, purchased a template from Envato and plan on working on it over the weekend. Followed instructions for both WP and XAMPP, and all seems to be fine. Running solely on local machine, MAC running Mojave. Go to install the .zip file on WP, and it asks for credentials for FTP. Not sure what I need to put in here, or what to do to change in order to install the .zip file for my template site. Any suggestions or recommendations are appreciated in advance. JVN
Congratulation Jon, welcome to the WordPress world! To fix the issue, just add the following line of code in your installed WordPress's `wp-config.php` file. It's a PHP constant declaration which tells the WordPress to avoid the FTP. That's it. ``` define( 'FS_METHOD', 'direct' ); ``` For more info: <https://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants>
318,853
<p>When I activate WooCommerce plugin, the lost your password does not work and can't sent password reset email to users. But when I deactivate WooCommerce, the lost your password link at login page starts working. Is it possible to not use WooCommerce link because it is not working and changes the reset link.</p>
[ { "answer_id": 318857, "author": "jaze", "author_id": 146919, "author_profile": "https://wordpress.stackexchange.com/users/146919", "pm_score": 2, "selected": false, "text": "<p>I hope think this may work.</p>\n\n<p>Insert this code into php file or php insert plugin, WooCommerce will no longer change password reset link.</p>\n\n<pre><code>function reset_pass_url() {\n $siteURL = get_option('siteurl');\n return \"{$siteURL}/wp-login.php?action=lostpassword\";\n}\nadd_filter( 'lostpassword_url', 'reset_pass_url', 11, 0 );\n</code></pre>\n" }, { "answer_id": 334762, "author": "Dan Wich", "author_id": 157603, "author_profile": "https://wordpress.stackexchange.com/users/157603", "pm_score": 2, "selected": false, "text": "<p>If you'd like to do this without code, open the WordPress admin and then click \"WooCommerce\", \"Settings\", \"Advanced\". Under \"Account Endpoints\", delete \"lost-password\" from the \"Lost password\" field.</p>\n" }, { "answer_id": 354781, "author": "Simon Josef Kok", "author_id": 57687, "author_profile": "https://wordpress.stackexchange.com/users/57687", "pm_score": 1, "selected": false, "text": "<p>Another way to do this is to add this to your theme's functions.php file:</p>\n\n<pre><code>remove_filter('lostpassword_url', 'wc_lostpassword_url', 10, 1);\n</code></pre>\n\n<p>This removes the modification added by WooCommerce.</p>\n" } ]
2018/11/10
[ "https://wordpress.stackexchange.com/questions/318853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146919/" ]
When I activate WooCommerce plugin, the lost your password does not work and can't sent password reset email to users. But when I deactivate WooCommerce, the lost your password link at login page starts working. Is it possible to not use WooCommerce link because it is not working and changes the reset link.
I hope think this may work. Insert this code into php file or php insert plugin, WooCommerce will no longer change password reset link. ``` function reset_pass_url() { $siteURL = get_option('siteurl'); return "{$siteURL}/wp-login.php?action=lostpassword"; } add_filter( 'lostpassword_url', 'reset_pass_url', 11, 0 ); ```
318,892
<p>I am currently using Wordpress, and an element of user_registered returns the time of registration of the user. I have set the correct timezone, but don't know how to get the user_registered output to match my current time. So far, this is what I have.</p> <pre><code> date_default_timezone_set('America/Los_Angeles'); $users = get_users(); foreach( $users as $user ) { $udata = get_userdata( $user-&gt;ID ); $registered = $udata-&gt;user_registered; printf( '%s member since %s&lt;br&gt;', $udata-&gt;data-&gt;display_name, date( "Y-m-d H:i:s", strtotime( $registered ) ) ); } echo('date below &lt;br&gt;'); echo date('Y-m-d H:i:s'); </code></pre> <p>The date default timezone indeed changes the timezone (last echo) However, what I want to change is the output of user_registered. (which is the stored time).</p> <p>How do I globally change the way the time is being displayed when called? In other words if I call for the date/timestamp through plugin or direct, it will always give me the output of America/Los_Angeles.</p> <p>Thanks in advance. I'm a noob. FYI the echo and printf stuff is purely for temporary display. I want to change the way user_registered is rendered when called from plugin or direct.</p> <p>If javascript or jquery is an option i'm all ears.</p>
[ { "answer_id": 318989, "author": "Amir", "author_id": 80135, "author_profile": "https://wordpress.stackexchange.com/users/80135", "pm_score": -1, "selected": false, "text": "<p>On the <strong>Settings > General</strong> page, find the section labeled <strong>Timezone</strong>. Select a city in the same timezone as you.</p>\n" }, { "answer_id": 393730, "author": "ggedde", "author_id": 166772, "author_profile": "https://wordpress.stackexchange.com/users/166772", "pm_score": 0, "selected": false, "text": "<p>You can get the time offset from WordPress Settings using</p>\n<pre><code>get_option( 'gmt_offset' )\n</code></pre>\n<p>So I found the easiest method is to do this:</p>\n<pre><code>gmdate( 'Y-m-d H:i:s', strtotime( get_option( 'gmt_offset' ) . ' hours', strtotime( $udata-&gt;user_registered ) ) )\n</code></pre>\n" } ]
2018/11/11
[ "https://wordpress.stackexchange.com/questions/318892", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153866/" ]
I am currently using Wordpress, and an element of user\_registered returns the time of registration of the user. I have set the correct timezone, but don't know how to get the user\_registered output to match my current time. So far, this is what I have. ``` date_default_timezone_set('America/Los_Angeles'); $users = get_users(); foreach( $users as $user ) { $udata = get_userdata( $user->ID ); $registered = $udata->user_registered; printf( '%s member since %s<br>', $udata->data->display_name, date( "Y-m-d H:i:s", strtotime( $registered ) ) ); } echo('date below <br>'); echo date('Y-m-d H:i:s'); ``` The date default timezone indeed changes the timezone (last echo) However, what I want to change is the output of user\_registered. (which is the stored time). How do I globally change the way the time is being displayed when called? In other words if I call for the date/timestamp through plugin or direct, it will always give me the output of America/Los\_Angeles. Thanks in advance. I'm a noob. FYI the echo and printf stuff is purely for temporary display. I want to change the way user\_registered is rendered when called from plugin or direct. If javascript or jquery is an option i'm all ears.
You can get the time offset from WordPress Settings using ``` get_option( 'gmt_offset' ) ``` So I found the easiest method is to do this: ``` gmdate( 'Y-m-d H:i:s', strtotime( get_option( 'gmt_offset' ) . ' hours', strtotime( $udata->user_registered ) ) ) ```
318,920
<p>I'm new here, and new using Wordpress I'm creating a website, <a href="https://www.maispersona.com" rel="nofollow noreferrer">https://www.maispersona.com</a> and I'm trying to modify my search page layout. (You can get into the website and search something to see)</p> <p>I'm using the Elementor plugin. But I'm getting an issue when I try to remove a grey colored div, with a search result information on the search page result.</p> <p>Can you help me please? Sorry for my English is not my native language.</p> <p><a href="https://i.stack.imgur.com/VG9zA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VG9zA.png" alt="Here on the picture, you can see the header of the search result page, I want to remove this gray div and the information &quot;n Search Results Found"></a></p> <p>Here on the picture, you can see the header of the search result page, I want to remove this gray div and the information "n Search Results Found</p> <p>Thank You a lot</p>
[ { "answer_id": 318989, "author": "Amir", "author_id": 80135, "author_profile": "https://wordpress.stackexchange.com/users/80135", "pm_score": -1, "selected": false, "text": "<p>On the <strong>Settings > General</strong> page, find the section labeled <strong>Timezone</strong>. Select a city in the same timezone as you.</p>\n" }, { "answer_id": 393730, "author": "ggedde", "author_id": 166772, "author_profile": "https://wordpress.stackexchange.com/users/166772", "pm_score": 0, "selected": false, "text": "<p>You can get the time offset from WordPress Settings using</p>\n<pre><code>get_option( 'gmt_offset' )\n</code></pre>\n<p>So I found the easiest method is to do this:</p>\n<pre><code>gmdate( 'Y-m-d H:i:s', strtotime( get_option( 'gmt_offset' ) . ' hours', strtotime( $udata-&gt;user_registered ) ) )\n</code></pre>\n" } ]
2018/11/11
[ "https://wordpress.stackexchange.com/questions/318920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153892/" ]
I'm new here, and new using Wordpress I'm creating a website, <https://www.maispersona.com> and I'm trying to modify my search page layout. (You can get into the website and search something to see) I'm using the Elementor plugin. But I'm getting an issue when I try to remove a grey colored div, with a search result information on the search page result. Can you help me please? Sorry for my English is not my native language. [![Here on the picture, you can see the header of the search result page, I want to remove this gray div and the information "n Search Results Found](https://i.stack.imgur.com/VG9zA.png)](https://i.stack.imgur.com/VG9zA.png) Here on the picture, you can see the header of the search result page, I want to remove this gray div and the information "n Search Results Found Thank You a lot
You can get the time offset from WordPress Settings using ``` get_option( 'gmt_offset' ) ``` So I found the easiest method is to do this: ``` gmdate( 'Y-m-d H:i:s', strtotime( get_option( 'gmt_offset' ) . ' hours', strtotime( $udata->user_registered ) ) ) ```
318,965
<p>I want to remove it COMPLETELY. Not only the label "Archive: " but EVERYTHING. It should not appear. I've been looking for the solution for hours to no avail.</p> <p>Please help. Thank you!</p>
[ { "answer_id": 318989, "author": "Amir", "author_id": 80135, "author_profile": "https://wordpress.stackexchange.com/users/80135", "pm_score": -1, "selected": false, "text": "<p>On the <strong>Settings > General</strong> page, find the section labeled <strong>Timezone</strong>. Select a city in the same timezone as you.</p>\n" }, { "answer_id": 393730, "author": "ggedde", "author_id": 166772, "author_profile": "https://wordpress.stackexchange.com/users/166772", "pm_score": 0, "selected": false, "text": "<p>You can get the time offset from WordPress Settings using</p>\n<pre><code>get_option( 'gmt_offset' )\n</code></pre>\n<p>So I found the easiest method is to do this:</p>\n<pre><code>gmdate( 'Y-m-d H:i:s', strtotime( get_option( 'gmt_offset' ) . ' hours', strtotime( $udata-&gt;user_registered ) ) )\n</code></pre>\n" } ]
2018/11/12
[ "https://wordpress.stackexchange.com/questions/318965", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153772/" ]
I want to remove it COMPLETELY. Not only the label "Archive: " but EVERYTHING. It should not appear. I've been looking for the solution for hours to no avail. Please help. Thank you!
You can get the time offset from WordPress Settings using ``` get_option( 'gmt_offset' ) ``` So I found the easiest method is to do this: ``` gmdate( 'Y-m-d H:i:s', strtotime( get_option( 'gmt_offset' ) . ' hours', strtotime( $udata->user_registered ) ) ) ```
319,028
<p>I'm trying to override a method (<code>my_packages</code>) from the <code>WP Job Manager Paid Listings</code> plugin by extending it's class from within a custom plugin</p> <p>Here is how the source code (none-related code removed) is set up...</p> <pre><code>class WC_Paid_Listings_Orders { private static $instance; public static function get_instance() { return null === self::$instance ? ( self::$instance = new self ) : self::$instance; } public function __construct() { add_action( 'woocommerce_before_my_account', array( $this, 'my_packages' ) ); } public function my_packages() { // This is what I want to unhook } } </code></pre> <p>How would I 'unhook' <code>my_packages</code>? This is what I have thus far (and failing with)! I'm guessing it's to do with the instance? I've tries all sorts of iterations from examples on here but to no avail - Operating at the edge of my knowledge here I'm afraid.</p> <pre><code>class cvl_override_defaults extends WC_Paid_Listings_Orders { public function __construct() { remove_action('woocommerce_before_my_account', array( $this, 'my_packages')); add_action( 'woocommerce_before_my_account', array( $this, 'new_my_packages' ) ); } public function new_my_packages() { // New output goes in here } } </code></pre> <p>TIA!</p>
[ { "answer_id": 319032, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": true, "text": "<p>Problem lies in this line:</p>\n\n<pre><code>remove_action('woocommerce_before_my_account', array( $this, 'my_packages'));\n</code></pre>\n\n<p>This won't remove action registered by parent class, because <code>$this</code> is a different object in this case, so you won't remove any action at all.</p>\n\n<p>So how to remove such action? Since you can't access the same <code>$this</code> value in your class, you'll have to iterate through all filters and remove the given one manually.</p>\n\n<p>Here's a good example how to do that:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/239431/34172\">https://wordpress.stackexchange.com/a/239431/34172</a></p>\n" }, { "answer_id": 319086, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>When an action is added using a specific instance of a class (when you see <code>$this</code>), to remove the action you need to pass the <em>same instance</em> of the class to <code>remove_action()</code>.</p>\n\n<p>Since <code>WC_Paid_Listings_Orders</code> is a Singleton (it appears), there is only one instance of the class, and you can get that instance using the <code>get_instance()</code> method. You can then use that instance to remove the action.</p>\n\n<pre><code>$wc_paid_listings_orders = WC_Paid_Listings_Orders::get_instance();\nremove_action( $wc_paid_listings_orders, 'my_packages' );\n</code></pre>\n" } ]
2018/11/12
[ "https://wordpress.stackexchange.com/questions/319028", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57057/" ]
I'm trying to override a method (`my_packages`) from the `WP Job Manager Paid Listings` plugin by extending it's class from within a custom plugin Here is how the source code (none-related code removed) is set up... ``` class WC_Paid_Listings_Orders { private static $instance; public static function get_instance() { return null === self::$instance ? ( self::$instance = new self ) : self::$instance; } public function __construct() { add_action( 'woocommerce_before_my_account', array( $this, 'my_packages' ) ); } public function my_packages() { // This is what I want to unhook } } ``` How would I 'unhook' `my_packages`? This is what I have thus far (and failing with)! I'm guessing it's to do with the instance? I've tries all sorts of iterations from examples on here but to no avail - Operating at the edge of my knowledge here I'm afraid. ``` class cvl_override_defaults extends WC_Paid_Listings_Orders { public function __construct() { remove_action('woocommerce_before_my_account', array( $this, 'my_packages')); add_action( 'woocommerce_before_my_account', array( $this, 'new_my_packages' ) ); } public function new_my_packages() { // New output goes in here } } ``` TIA!
Problem lies in this line: ``` remove_action('woocommerce_before_my_account', array( $this, 'my_packages')); ``` This won't remove action registered by parent class, because `$this` is a different object in this case, so you won't remove any action at all. So how to remove such action? Since you can't access the same `$this` value in your class, you'll have to iterate through all filters and remove the given one manually. Here's a good example how to do that: <https://wordpress.stackexchange.com/a/239431/34172>
319,035
<p>I would like to display a dropdown list of categories (or other taxonomy) inside of a Gutenberg block. I can only think of two ways to do this:</p> <ol> <li>Create an array of the taxonomy in php and use <code>wp_localize_script</code> to make that data available to my block javascript.</li> <li>Use <code>fetch()</code>? in the block to reach out to the api at <em>/wp-json/wp/v2/categories/</em> and get all the categories. </li> </ol> <p>Are one of these the preferred method? Is there some other kind of built-in or better way to do this? </p> <h2>Edit</h2> <p>As I continue to research this, I learned of another method available in the Gutenberg plugin and presumably available once this editor becomes part of core: <a href="https://wordpress.org/gutenberg/handbook/packages/packages-api-fetch/" rel="noreferrer"><code>wp.apiFetch()</code></a>. Apparently, it's a wrapper around fetch which hides away some of the unnecessary parts. Now I'm wondering if this is the preferred method.</p> <ol start="3"> <li>Use <code>wp.apiFetch()</code> in the block to reach out to the REST api at <em>/wp/v2/categories</em> and get all the categories. </li> </ol> <h1>The Catch</h1> <p>On first glance, it seems to make more sense to use the apiFetch() function. However, because that's asynchronous, the data doesn't get loaded into the JSX element. I'm not sure how to make that data load into the element. </p>
[ { "answer_id": 320481, "author": "Chad Holden", "author_id": 154908, "author_profile": "https://wordpress.stackexchange.com/users/154908", "pm_score": 1, "selected": false, "text": "<p>Load the elements into a constant using a function like this: </p>\n\n<pre><code>const postSelections = [];\n\nconst allPosts = wp.apiFetch({path: \"/wp/v2/posts\"}).then(posts =&gt; {\n postSelections.push({label: \"Select a Post\", value: 0});\n $.each( posts, function( key, val ) {\n postSelections.push({label: val.title.rendered, value: val.id});\n });\n return postSelections;\n});\n</code></pre>\n\n<p>Then use postSelections as your element \"options\".</p>\n\n<pre><code> el(\n wp.components.SelectControl,\n {\n label: __('Select a Post'),\n help: 'Select a post to display as a banner.',\n options: postSelections,\n value: selectedPost,\n onChange: onChangePost\n }\n ),\n</code></pre>\n" }, { "answer_id": 336924, "author": "Aaron", "author_id": 167262, "author_profile": "https://wordpress.stackexchange.com/users/167262", "pm_score": 6, "selected": true, "text": "<p>You don't need <code>apiFetch</code> or localization to get a list of all categories. You can do this with the <code>wp.data</code> module:</p>\n\n<pre><code>wp.data.select('core').getEntityRecords('taxonomy', 'category');\n</code></pre>\n\n<p>See the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core/\" rel=\"noreferrer\">Gutenberg Handbook</a> entry on Core Data for more details.</p>\n" } ]
2018/11/12
[ "https://wordpress.stackexchange.com/questions/319035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2044/" ]
I would like to display a dropdown list of categories (or other taxonomy) inside of a Gutenberg block. I can only think of two ways to do this: 1. Create an array of the taxonomy in php and use `wp_localize_script` to make that data available to my block javascript. 2. Use `fetch()`? in the block to reach out to the api at */wp-json/wp/v2/categories/* and get all the categories. Are one of these the preferred method? Is there some other kind of built-in or better way to do this? Edit ---- As I continue to research this, I learned of another method available in the Gutenberg plugin and presumably available once this editor becomes part of core: [`wp.apiFetch()`](https://wordpress.org/gutenberg/handbook/packages/packages-api-fetch/). Apparently, it's a wrapper around fetch which hides away some of the unnecessary parts. Now I'm wondering if this is the preferred method. 3. Use `wp.apiFetch()` in the block to reach out to the REST api at */wp/v2/categories* and get all the categories. The Catch ========= On first glance, it seems to make more sense to use the apiFetch() function. However, because that's asynchronous, the data doesn't get loaded into the JSX element. I'm not sure how to make that data load into the element.
You don't need `apiFetch` or localization to get a list of all categories. You can do this with the `wp.data` module: ``` wp.data.select('core').getEntityRecords('taxonomy', 'category'); ``` See the [Gutenberg Handbook](https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core/) entry on Core Data for more details.
319,054
<p>So I have a metabox which I want to trigger some Javascript when a post is saved (to refresh the page in this use case.) </p> <p>In Classic Editor, this can be done via a simple redirect hooked to <code>save_post</code> (with a high priority)</p> <p>But since Gutenberg converts the saving process for existing metaboxes into individual AJAX calls now, it needs to be javascript, so how do I either:</p> <ul> <li><p>Listen for an event where all the saving processes are complete and then trigger the javascript? If so what is this event called? Is there a reference to these events anywhere yet? <strong>OR</strong></p></li> <li><p>Trigger javascript inside the metabox saving AJAX process, which can then check the state of the parent page saving process before continuing?</p></li> </ul>
[ { "answer_id": 319071, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Okay, so way way more hacky solution than I wanted, but got it working...</p>\n\n<p>Here is a slightly simplified and abstracted way of doing it from my code, in case anyone ever needs to do the same (as I'm sure more plugins will in the near future.)</p>\n\n<pre><code> var reload_check = false; var publish_button_click = false;\n jQuery(document).ready(function($) {\n add_publish_button_click = setInterval(function() {\n $publish_button = jQuery('.edit-post-header__settings .editor-post-publish-button');\n if ($publish_button &amp;&amp; !publish_button_click) {\n publish_button_click = true;\n $publish_button.on('click', function() {\n var reloader = setInterval(function() {\n if (reload_check) {return;} else {reload_check = true;}\n postsaving = wp.data.select('core/editor').isSavingPost();\n autosaving = wp.data.select('core/editor').isAutosavingPost();\n success = wp.data.select('core/editor').didPostSaveRequestSucceed();\n console.log('Saving: '+postsaving+' - Autosaving: '+autosaving+' - Success: '+success);\n if (postsaving || autosaving || !success) {classic_reload_check = false; return;}\n clearInterval(reloader);\n\n value = document.getElementById('metabox_input_id').value;\n if (value == 'trigger_value') {\n if (confirm('Page reload required. Refresh the page now?')) {\n window.location.href = window.location.href+'&amp;refreshed=1';\n }\n }\n }, 1000);\n });\n }\n }, 500);\n });\n</code></pre>\n\n<p>...just need to change <code>metabox_input_id</code> and <code>trigger_value</code> to match as needed. :-)</p>\n" }, { "answer_id": 331317, "author": "tomyam", "author_id": 44794, "author_profile": "https://wordpress.stackexchange.com/users/44794", "pm_score": 4, "selected": false, "text": "<p>Not sure if there is a better way, but I am listening to <code>subscribe</code> rather than adding an event listener to the button:</p>\n\n<pre><code>wp.data.subscribe(function () {\n var isSavingPost = wp.data.select('core/editor').isSavingPost();\n var isAutosavingPost = wp.data.select('core/editor').isAutosavingPost();\n\n if (isSavingPost &amp;&amp; !isAutosavingPost) {\n // Here goes your AJAX code ......\n\n }\n})\n</code></pre>\n\n<p>Official docs of the Post Editor data: <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core-editor/\" rel=\"noreferrer\">https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core-editor/</a></p>\n" }, { "answer_id": 363924, "author": "Phillip Kamikaze", "author_id": 185975, "author_profile": "https://wordpress.stackexchange.com/users/185975", "pm_score": 1, "selected": false, "text": "<p>You need collect <strong>unsubscribe</strong> function from subscribe and call to <strong>avoid multiples time call.</strong></p>\n\n<pre><code>const unsubscribe = wp.data.subscribe(function () {\n let select = wp.data.select('core/editor');\n var isSavingPost = select.isSavingPost();\n var isAutosavingPost = select.isAutosavingPost();\n var didPostSaveRequestSucceed = select.didPostSaveRequestSucceed();\n if (isSavingPost &amp;&amp; !isAutosavingPost &amp;&amp; didPostSaveRequestSucceed) {\n console.log(\"isSavingPost &amp;&amp; !isAutosavingPost &amp;&amp; didPostSaveRequestSucceed\");\n unsubscribe();\n\n\n // your AJAX HERE();\n\n }\n });\n</code></pre>\n" }, { "answer_id": 390543, "author": "andergmartins", "author_id": 171971, "author_profile": "https://wordpress.stackexchange.com/users/171971", "pm_score": 2, "selected": false, "text": "<p>In order to trigger the action (in this case an Ajax request) AFTER the post save is COMPLETE, you can use an interval to wait until the isSavingPost returns false again.</p>\n<pre><code>let intervalCheckPostIsSaved;\nlet ajaxRequest;\n\nwp.data.subscribe(function () {\n let editor = wp.data.select('core/editor');\n\n if (editor.isSavingPost()\n &amp;&amp; !editor.isAutosavingPost()\n &amp;&amp; editor.didPostSaveRequestSucceed()) {\n\n if (!intervalCheckPostIsSaved) {\n intervalCheckPostIsSaved = setInterval(function () {\n if (!wp.data.select('core/editor').isSavingPost()) {\n if (ajaxRequest) {\n ajaxRequest.abort();\n }\n\n ajaxRequest = $.ajax({\n url: ajaxurl,\n type: 'POST',\n data: {},\n success: function (data) {\n ajaxRequest = null;\n }\n });\n\n clearInterval(intervalCheckPostIsSaved);\n intervalCheckPostIsSaved = null;\n }\n }, 800);\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 413267, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 0, "selected": false, "text": "<p>If someone is still interested I came up with a simple way to actually execute something right AFTER the block editor (Gutenberg) finishes a post publish/update:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const editor = window.wp.data.dispatch('core/editor')\nconst savePost = editor.savePost\n\neditor.savePost = function () {\n return savePost()\n .then(() =&gt; {\n // Do something after the post was actually asynchronous saved.\n console.log('The post was saved.')\n })\n}\n</code></pre>\n<p>Basically the snippet above overrides the native <code>savePost()</code> function.<br />\nSo you override it with your own function, call <code>savePost()</code> again inside it and take advantage of the promise returned just by using <code>then</code>.</p>\n" } ]
2018/11/13
[ "https://wordpress.stackexchange.com/questions/319054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76440/" ]
So I have a metabox which I want to trigger some Javascript when a post is saved (to refresh the page in this use case.) In Classic Editor, this can be done via a simple redirect hooked to `save_post` (with a high priority) But since Gutenberg converts the saving process for existing metaboxes into individual AJAX calls now, it needs to be javascript, so how do I either: * Listen for an event where all the saving processes are complete and then trigger the javascript? If so what is this event called? Is there a reference to these events anywhere yet? **OR** * Trigger javascript inside the metabox saving AJAX process, which can then check the state of the parent page saving process before continuing?
Okay, so way way more hacky solution than I wanted, but got it working... Here is a slightly simplified and abstracted way of doing it from my code, in case anyone ever needs to do the same (as I'm sure more plugins will in the near future.) ``` var reload_check = false; var publish_button_click = false; jQuery(document).ready(function($) { add_publish_button_click = setInterval(function() { $publish_button = jQuery('.edit-post-header__settings .editor-post-publish-button'); if ($publish_button && !publish_button_click) { publish_button_click = true; $publish_button.on('click', function() { var reloader = setInterval(function() { if (reload_check) {return;} else {reload_check = true;} postsaving = wp.data.select('core/editor').isSavingPost(); autosaving = wp.data.select('core/editor').isAutosavingPost(); success = wp.data.select('core/editor').didPostSaveRequestSucceed(); console.log('Saving: '+postsaving+' - Autosaving: '+autosaving+' - Success: '+success); if (postsaving || autosaving || !success) {classic_reload_check = false; return;} clearInterval(reloader); value = document.getElementById('metabox_input_id').value; if (value == 'trigger_value') { if (confirm('Page reload required. Refresh the page now?')) { window.location.href = window.location.href+'&refreshed=1'; } } }, 1000); }); } }, 500); }); ``` ...just need to change `metabox_input_id` and `trigger_value` to match as needed. :-)
319,057
<p>I've tried to find the information on the Internet and stackoverflow, but there is nothing about it.</p> <p>So I've migrated my website(html,css,js) to WordPress(index.php,header.php,footer.php etc) and I can't figure out how to change a view of posts before adding them to my site.</p> <p>I can see 4 ways of doing that:</p> <p>1)Download WP plugin to add and customize posts. But I'll only be able to customize it by using the admin area, I can't do it with HTML and CSS, very few options(color,picture etc)</p> <p>2)Create a separate file(sidebar.php) and add to it my posts. But if my client wants to add posts himself, he won't be able to do that, and again very few options. <a href="https://prnt.sc/lhmhoy" rel="nofollow noreferrer">example</a></p> <p>3)Use the standard "Posts-Add New" in the admin area. But in that case, I can't figure out how to cusomize it, what shall I do?Go into the "wp-admin" folder which is in the WordPress file and find HTML,CSS which are responsible for changing posts view and change them? Because if I don't change them, this happens <a href="https://prnt.sc/lhmk36" rel="nofollow noreferrer">example</a></p> <p>4) Migrate my website to WordPress by using a blank theme <a href="https://underscores.me/" rel="nofollow noreferrer">example</a>. There is a posts page(posts.php,I don't remeber how it's called exactly) and try to find a code snippet which is responsible for a posts view</p> <p>My question is how to change a view of posts in WordPress? And this is what I want to make <a href="https://prnt.sc/lhmm7d" rel="nofollow noreferrer">example</a> <a href="http://www.themechampion.com/demo/industriallive/" rel="nofollow noreferrer">link to the website</a></p>
[ { "answer_id": 319071, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Okay, so way way more hacky solution than I wanted, but got it working...</p>\n\n<p>Here is a slightly simplified and abstracted way of doing it from my code, in case anyone ever needs to do the same (as I'm sure more plugins will in the near future.)</p>\n\n<pre><code> var reload_check = false; var publish_button_click = false;\n jQuery(document).ready(function($) {\n add_publish_button_click = setInterval(function() {\n $publish_button = jQuery('.edit-post-header__settings .editor-post-publish-button');\n if ($publish_button &amp;&amp; !publish_button_click) {\n publish_button_click = true;\n $publish_button.on('click', function() {\n var reloader = setInterval(function() {\n if (reload_check) {return;} else {reload_check = true;}\n postsaving = wp.data.select('core/editor').isSavingPost();\n autosaving = wp.data.select('core/editor').isAutosavingPost();\n success = wp.data.select('core/editor').didPostSaveRequestSucceed();\n console.log('Saving: '+postsaving+' - Autosaving: '+autosaving+' - Success: '+success);\n if (postsaving || autosaving || !success) {classic_reload_check = false; return;}\n clearInterval(reloader);\n\n value = document.getElementById('metabox_input_id').value;\n if (value == 'trigger_value') {\n if (confirm('Page reload required. Refresh the page now?')) {\n window.location.href = window.location.href+'&amp;refreshed=1';\n }\n }\n }, 1000);\n });\n }\n }, 500);\n });\n</code></pre>\n\n<p>...just need to change <code>metabox_input_id</code> and <code>trigger_value</code> to match as needed. :-)</p>\n" }, { "answer_id": 331317, "author": "tomyam", "author_id": 44794, "author_profile": "https://wordpress.stackexchange.com/users/44794", "pm_score": 4, "selected": false, "text": "<p>Not sure if there is a better way, but I am listening to <code>subscribe</code> rather than adding an event listener to the button:</p>\n\n<pre><code>wp.data.subscribe(function () {\n var isSavingPost = wp.data.select('core/editor').isSavingPost();\n var isAutosavingPost = wp.data.select('core/editor').isAutosavingPost();\n\n if (isSavingPost &amp;&amp; !isAutosavingPost) {\n // Here goes your AJAX code ......\n\n }\n})\n</code></pre>\n\n<p>Official docs of the Post Editor data: <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core-editor/\" rel=\"noreferrer\">https://wordpress.org/gutenberg/handbook/designers-developers/developers/data/data-core-editor/</a></p>\n" }, { "answer_id": 363924, "author": "Phillip Kamikaze", "author_id": 185975, "author_profile": "https://wordpress.stackexchange.com/users/185975", "pm_score": 1, "selected": false, "text": "<p>You need collect <strong>unsubscribe</strong> function from subscribe and call to <strong>avoid multiples time call.</strong></p>\n\n<pre><code>const unsubscribe = wp.data.subscribe(function () {\n let select = wp.data.select('core/editor');\n var isSavingPost = select.isSavingPost();\n var isAutosavingPost = select.isAutosavingPost();\n var didPostSaveRequestSucceed = select.didPostSaveRequestSucceed();\n if (isSavingPost &amp;&amp; !isAutosavingPost &amp;&amp; didPostSaveRequestSucceed) {\n console.log(\"isSavingPost &amp;&amp; !isAutosavingPost &amp;&amp; didPostSaveRequestSucceed\");\n unsubscribe();\n\n\n // your AJAX HERE();\n\n }\n });\n</code></pre>\n" }, { "answer_id": 390543, "author": "andergmartins", "author_id": 171971, "author_profile": "https://wordpress.stackexchange.com/users/171971", "pm_score": 2, "selected": false, "text": "<p>In order to trigger the action (in this case an Ajax request) AFTER the post save is COMPLETE, you can use an interval to wait until the isSavingPost returns false again.</p>\n<pre><code>let intervalCheckPostIsSaved;\nlet ajaxRequest;\n\nwp.data.subscribe(function () {\n let editor = wp.data.select('core/editor');\n\n if (editor.isSavingPost()\n &amp;&amp; !editor.isAutosavingPost()\n &amp;&amp; editor.didPostSaveRequestSucceed()) {\n\n if (!intervalCheckPostIsSaved) {\n intervalCheckPostIsSaved = setInterval(function () {\n if (!wp.data.select('core/editor').isSavingPost()) {\n if (ajaxRequest) {\n ajaxRequest.abort();\n }\n\n ajaxRequest = $.ajax({\n url: ajaxurl,\n type: 'POST',\n data: {},\n success: function (data) {\n ajaxRequest = null;\n }\n });\n\n clearInterval(intervalCheckPostIsSaved);\n intervalCheckPostIsSaved = null;\n }\n }, 800);\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 413267, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 0, "selected": false, "text": "<p>If someone is still interested I came up with a simple way to actually execute something right AFTER the block editor (Gutenberg) finishes a post publish/update:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const editor = window.wp.data.dispatch('core/editor')\nconst savePost = editor.savePost\n\neditor.savePost = function () {\n return savePost()\n .then(() =&gt; {\n // Do something after the post was actually asynchronous saved.\n console.log('The post was saved.')\n })\n}\n</code></pre>\n<p>Basically the snippet above overrides the native <code>savePost()</code> function.<br />\nSo you override it with your own function, call <code>savePost()</code> again inside it and take advantage of the promise returned just by using <code>then</code>.</p>\n" } ]
2018/11/13
[ "https://wordpress.stackexchange.com/questions/319057", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153976/" ]
I've tried to find the information on the Internet and stackoverflow, but there is nothing about it. So I've migrated my website(html,css,js) to WordPress(index.php,header.php,footer.php etc) and I can't figure out how to change a view of posts before adding them to my site. I can see 4 ways of doing that: 1)Download WP plugin to add and customize posts. But I'll only be able to customize it by using the admin area, I can't do it with HTML and CSS, very few options(color,picture etc) 2)Create a separate file(sidebar.php) and add to it my posts. But if my client wants to add posts himself, he won't be able to do that, and again very few options. [example](https://prnt.sc/lhmhoy) 3)Use the standard "Posts-Add New" in the admin area. But in that case, I can't figure out how to cusomize it, what shall I do?Go into the "wp-admin" folder which is in the WordPress file and find HTML,CSS which are responsible for changing posts view and change them? Because if I don't change them, this happens [example](https://prnt.sc/lhmk36) 4) Migrate my website to WordPress by using a blank theme [example](https://underscores.me/). There is a posts page(posts.php,I don't remeber how it's called exactly) and try to find a code snippet which is responsible for a posts view My question is how to change a view of posts in WordPress? And this is what I want to make [example](https://prnt.sc/lhmm7d) [link to the website](http://www.themechampion.com/demo/industriallive/)
Okay, so way way more hacky solution than I wanted, but got it working... Here is a slightly simplified and abstracted way of doing it from my code, in case anyone ever needs to do the same (as I'm sure more plugins will in the near future.) ``` var reload_check = false; var publish_button_click = false; jQuery(document).ready(function($) { add_publish_button_click = setInterval(function() { $publish_button = jQuery('.edit-post-header__settings .editor-post-publish-button'); if ($publish_button && !publish_button_click) { publish_button_click = true; $publish_button.on('click', function() { var reloader = setInterval(function() { if (reload_check) {return;} else {reload_check = true;} postsaving = wp.data.select('core/editor').isSavingPost(); autosaving = wp.data.select('core/editor').isAutosavingPost(); success = wp.data.select('core/editor').didPostSaveRequestSucceed(); console.log('Saving: '+postsaving+' - Autosaving: '+autosaving+' - Success: '+success); if (postsaving || autosaving || !success) {classic_reload_check = false; return;} clearInterval(reloader); value = document.getElementById('metabox_input_id').value; if (value == 'trigger_value') { if (confirm('Page reload required. Refresh the page now?')) { window.location.href = window.location.href+'&refreshed=1'; } } }, 1000); }); } }, 500); }); ``` ...just need to change `metabox_input_id` and `trigger_value` to match as needed. :-)
319,129
<p>I thought this question would be an easy find on the internet… however, it seems no one has ever ran into this issue before.</p> <p>There's no problem in listing a search query when you enter your search term, <strong>I needed posts and pages to be differentiated in a way</strong>. For example: I'd like results that are posts (articles) to display the author, read time, and post date, but I do not like these metas to appear on results that are pages.</p> <p>Here's a code: </p> <pre><code> $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $searchArgs = array( 's' =&gt; $s, 'paged' =&gt; $paged, 'showposts' =&gt; -1, ); $searchQuery = new WP_Query( $searchArgs ); if ( $searchQuery-&gt;have_posts() ) : echo '&lt;h2&gt;'; echo 'result: '.search_query(); echo '&lt;/h2&gt;'; while ( $searchQuery-&gt;have_posts() ) : $searchQuery-&gt;the_post(); echo 'link: '.get_the_permalink(); echo 'Title: '.get_the_title(); echo 'Post Summary: '.get_the_excerpt(); $how = ( is_single() ) ? 'this result is a post' : 'your method did not work'; //always return false $how = ( is_page() ) ? 'this result is a page' : 'your method did not work'; //always return false. echo 'Post Type: '.$how; // &lt;------ How to do? //***Problem***: is_single() or is_page() does not work, by the way (both return false). //I've crossed-checked that the results are actually either a post or a page. endwhile; endif; if ( function_exists('custom_pagination') ) { custom_pagination($searchQuery-&gt;max_num_pages,"",$paged); } </code></pre> <p>So my problem is, is_page() and is_single() does not work within the Search Query I made. </p> <p>How do you do this the right way?</p>
[ { "answer_id": 319132, "author": "vm7488", "author_id": 71492, "author_profile": "https://wordpress.stackexchange.com/users/71492", "pm_score": 0, "selected": false, "text": "<p>…Figured it out… 5 minutes later…</p>\n\n<pre><code> $queryIsPost = (get_post_type() === 'post') ? true : false; //the solution\n $queryIsPage = (get_post_type() === 'page') ? true : false; //the solution\n\n $searchArgs = array(\n 's' =&gt; $s,\n 'paged' =&gt; $paged,\n 'showposts' =&gt; -1,\n );\n $searchQuery = new WP_Query( $searchArgs );\n if ( $searchQuery-&gt;have_posts() ) :\n echo '&lt;h2&gt;';\n echo 'result: '.search_query();\n echo '&lt;/h2&gt;';\n while ( $searchQuery-&gt;have_posts() ) : $searchQuery-&gt;the_post();\n echo 'link: '.get_the_permalink();\n echo 'Title: '.get_the_title();\n echo 'Post Summary: '.get_the_excerpt();\n if ($queryIsPost) {\n $thePostType = \"Post\";\n } elseif ($queryIsPage) {\n $thePostType = \"Page\";\n } else {\n $thePostType = \"Error. Not determined\";\n }\n echo 'Post Type: '.$thePostType;\n\n endwhile;\n endif;\n</code></pre>\n" }, { "answer_id": 319222, "author": "Justin Downey", "author_id": 154096, "author_profile": "https://wordpress.stackexchange.com/users/154096", "pm_score": 1, "selected": false, "text": "<p>That will only tell you if it's a Post or a Page. What if it's a category, tag, archive, or custom post type? Here's how I'd write that, if you care.</p>\n\n<pre><code>function xyz_get_post_type_name() {\n $wp_type = get_post_type( get_the_ID() );\n switch ($wp_type) {\n case 'post' :\n $type_name = 'Article';\n break;\n case 'page' :\n $type_name = 'Web Page';\n break;\n case 'quote' :\n $type_name = 'Testimonial';\n break;\n case 'post_tag' :\n $type_name = 'Topic';\n break;\n default : \n $type_name = ucfirst($wp_type);\n break;\n } // END switch\n return $type_name;\n} // END xyz_get_post_type_name()\n</code></pre>\n\n<p>Then just echo that function inside your loop wherever you want it.</p>\n\n<pre><code>while ( $searchQuery-&gt;have_posts() ) : $searchQuery-&gt;the_post();\n echo 'Post Type Name: ' . xyz_get_post_type_name();\nendwhile;\n</code></pre>\n\n<p>The switch statement would also allow you to give these post types a \"pretty\" name and default to just their actual name (first letter capitalized).</p>\n" } ]
2018/11/13
[ "https://wordpress.stackexchange.com/questions/319129", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71492/" ]
I thought this question would be an easy find on the internet… however, it seems no one has ever ran into this issue before. There's no problem in listing a search query when you enter your search term, **I needed posts and pages to be differentiated in a way**. For example: I'd like results that are posts (articles) to display the author, read time, and post date, but I do not like these metas to appear on results that are pages. Here's a code: ``` $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $searchArgs = array( 's' => $s, 'paged' => $paged, 'showposts' => -1, ); $searchQuery = new WP_Query( $searchArgs ); if ( $searchQuery->have_posts() ) : echo '<h2>'; echo 'result: '.search_query(); echo '</h2>'; while ( $searchQuery->have_posts() ) : $searchQuery->the_post(); echo 'link: '.get_the_permalink(); echo 'Title: '.get_the_title(); echo 'Post Summary: '.get_the_excerpt(); $how = ( is_single() ) ? 'this result is a post' : 'your method did not work'; //always return false $how = ( is_page() ) ? 'this result is a page' : 'your method did not work'; //always return false. echo 'Post Type: '.$how; // <------ How to do? //***Problem***: is_single() or is_page() does not work, by the way (both return false). //I've crossed-checked that the results are actually either a post or a page. endwhile; endif; if ( function_exists('custom_pagination') ) { custom_pagination($searchQuery->max_num_pages,"",$paged); } ``` So my problem is, is\_page() and is\_single() does not work within the Search Query I made. How do you do this the right way?
That will only tell you if it's a Post or a Page. What if it's a category, tag, archive, or custom post type? Here's how I'd write that, if you care. ``` function xyz_get_post_type_name() { $wp_type = get_post_type( get_the_ID() ); switch ($wp_type) { case 'post' : $type_name = 'Article'; break; case 'page' : $type_name = 'Web Page'; break; case 'quote' : $type_name = 'Testimonial'; break; case 'post_tag' : $type_name = 'Topic'; break; default : $type_name = ucfirst($wp_type); break; } // END switch return $type_name; } // END xyz_get_post_type_name() ``` Then just echo that function inside your loop wherever you want it. ``` while ( $searchQuery->have_posts() ) : $searchQuery->the_post(); echo 'Post Type Name: ' . xyz_get_post_type_name(); endwhile; ``` The switch statement would also allow you to give these post types a "pretty" name and default to just their actual name (first letter capitalized).
319,139
<p>I have a site we needed some custom php coding to connect to an external database to grab product review urls for several vendors that sell our products. The basic idea we are trying to accomplish is to have the user register their product and then extend their warranty if they are willing to leave a review. I'm using xyzscripts.com's "Insert PHP" plugin to accomplish this. The theme initially had only jQuery loaded so as to keep from creating a child theme we are loading jQueryUI in the php script. So we have jQuery loaded in the header and jQueryUI loaded in the body of the document. Im not quite sure if this is being caused because of the order the scripts are being loaded or if some other conflicting javascript is causing the error. You can see the error in the image below.</p> <p><strong>Chrome's Console Output On Calling The Dialog</strong></p> <p><a href="https://i.stack.imgur.com/sZh0D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sZh0D.png" alt="Console Error"></a></p> <p><strong>Relevant Code</strong></p> <pre><code>&lt;script&gt; jQuery.ajax({ type: 'GET', url: "&lt;?=$ajax_handler?&gt;?method=check_warranty&amp;model="+model, success: function(response) { if (response == '') duration = '6'; else duration = response; jQuery('#warranty_length').val(duration); jQuery('#warranty_dialog').dialog({ width:'700px', height:'408px', position:'absolute', top:'300px' }).html("HTML TO DISPLAY REVIEW LINK BUTTON"); jQuery('.titlebar-close').hide(); } }); &lt;/script&gt; </code></pre> <p>As you can see the code is pretty straightforward. After the user fills out the form I make an ajax call that queries our database with the Model and Vendor to get the appropriate review link for that product and then creates a link to the review page for that Vendor and Model.</p> <p>I'm trying to determine if the error is being caused by one of three things.</p> <ol> <li>There is an issue with the order jQuery &amp; jQueryUI are being loaded.</li> <li>There is an issue with my code (I have successfully used this script on some of our other sites).</li> <li>If there's possibly other javascript in the theme that is conflicting with my script.</li> </ol> <p>I can provide any other relevant code you need on the php script if necessary. The url to page is:</p> <p><a href="http://www.kriegermfg.com/register-test/" rel="noreferrer">http://www.kriegermfg.com/register-test/</a></p> <p>Any help will be greatly appreciated.</p> <p><strong>Edit</strong> Just to give some further context this is jQueryUI is failing.</p> <p><a href="https://i.stack.imgur.com/U8wSs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U8wSs.png" alt="enter image description here"></a></p>
[ { "answer_id": 319141, "author": "firxworx", "author_id": 134244, "author_profile": "https://wordpress.stackexchange.com/users/134244", "pm_score": 2, "selected": false, "text": "<p>Your JS looks to be written inline vs. in its own JS file or at least enqueued on its own. In other words, it doesn't look like its being loaded properly re WordPress. </p>\n\n<p>Note the WP function <code>wp_enqueue_script()</code> has a dependency parameter where you can pass an array of script handles (as registered via <code>wp_register_script()</code>). The parameters of this function helps you ensure that you load header + footer scripts in the desired location (header vs. footer) and desired order. </p>\n\n<p>Docs: </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a> \n<a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_register_script/</a> </p>\n\n<p>In the JS itself, make use of <code>$( document ).ready()</code>: </p>\n\n<p><a href=\"http://learn.jquery.com/using-jquery-core/document-ready/\" rel=\"nofollow noreferrer\">http://learn.jquery.com/using-jquery-core/document-ready/</a></p>\n\n<p>Your code is sitting in the markup before JQuery UI is loaded, which is a potential issue right there to resolve. If it was in its own file and properly enqueued in your theme's functions.php (or by a site plugin) then it could specify JQuery UI's handle as a dependency and WordPress will always load it after. </p>\n\n<p>If you still have issues I would also disable your other plugins + any other bits of JS you've tossed in there (temporarily) to see if you can get this to work. If so, you could re-enable them one-by-one to identify the culprit. </p>\n\n<p>It also looks like both Contact Form 7 and your theme/plugins are loading JQuery UI, and both depend on date pickers, etc. Contact Form 7's core is loading before the JQuery UI (and loading its other JQuery UI dependencies after) but I don't have enough experience with that plugin to know off-hand if that is a potential source of issues (it might also be something to look into).</p>\n" }, { "answer_id": 383544, "author": "kub1x", "author_id": 164216, "author_profile": "https://wordpress.stackexchange.com/users/164216", "pm_score": 1, "selected": false, "text": "<p>I got here debugging the same error on my WP installation. The previous answer was for developer of plugin/theme, so being an admin, I needed a little different approach. I had to find the source of the problem myself.</p>\n<p>As I learned <a href=\"https://wordpress.stackexchange.com/a/83372/164216\">here</a> I used following line in my <code>config.php</code> to get unminified version of Javascript sources.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('SCRIPT_DEBUG', true);\n</code></pre>\n<p><strong>TL;DR</strong> In browser I then caught the file to be failing as <code>sotrtable.js</code>. Then I went to my hosting server and searched the wordpress root directory for it using <a href=\"https://github.com/ggreer/the_silver_searcher\" rel=\"nofollow noreferrer\">the silver searcher</a>: <code>ag -l sortable</code>. There I noticed that in <code>wp-content/themes/OurCustomTheme/functions.php</code> there is a call of <code>wp_enqueue_script('jquery-ui', '//code.jquery.com/ui/1.11.4/jquery-ui.js', array(), '20120206')</code> pulling a fixed version of <a href=\"https://jqueryui.com/\" rel=\"nofollow noreferrer\">jQuery ui</a> from CDN. I replaced it with <code>wp_enqueue_script('jquery-ui-core')</code> which is current version of the lib that comes along with WordPress installation and is imported in <code>wp-includes/script-loader.php</code>.</p>\n<p>I'm describing the whole problem to show others, what kind of resolution process is ahead of them, when they bump into such Javascript exception <strong>caused by theme or plugin pulling incorrect version of some JS sources and overriding the correct one</strong>.</p>\n" }, { "answer_id": 387575, "author": "Said Erraoudy", "author_id": 75060, "author_profile": "https://wordpress.stackexchange.com/users/75060", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://wordpress.org/plugins/enable-jquery-migrate-helper/\" rel=\"nofollow noreferrer\">jQuery Migrate Helper</a> fixed it. I’ll troubleshoot which plugin is causing the issue later.</p>\n" } ]
2018/11/13
[ "https://wordpress.stackexchange.com/questions/319139", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154032/" ]
I have a site we needed some custom php coding to connect to an external database to grab product review urls for several vendors that sell our products. The basic idea we are trying to accomplish is to have the user register their product and then extend their warranty if they are willing to leave a review. I'm using xyzscripts.com's "Insert PHP" plugin to accomplish this. The theme initially had only jQuery loaded so as to keep from creating a child theme we are loading jQueryUI in the php script. So we have jQuery loaded in the header and jQueryUI loaded in the body of the document. Im not quite sure if this is being caused because of the order the scripts are being loaded or if some other conflicting javascript is causing the error. You can see the error in the image below. **Chrome's Console Output On Calling The Dialog** [![Console Error](https://i.stack.imgur.com/sZh0D.png)](https://i.stack.imgur.com/sZh0D.png) **Relevant Code** ``` <script> jQuery.ajax({ type: 'GET', url: "<?=$ajax_handler?>?method=check_warranty&model="+model, success: function(response) { if (response == '') duration = '6'; else duration = response; jQuery('#warranty_length').val(duration); jQuery('#warranty_dialog').dialog({ width:'700px', height:'408px', position:'absolute', top:'300px' }).html("HTML TO DISPLAY REVIEW LINK BUTTON"); jQuery('.titlebar-close').hide(); } }); </script> ``` As you can see the code is pretty straightforward. After the user fills out the form I make an ajax call that queries our database with the Model and Vendor to get the appropriate review link for that product and then creates a link to the review page for that Vendor and Model. I'm trying to determine if the error is being caused by one of three things. 1. There is an issue with the order jQuery & jQueryUI are being loaded. 2. There is an issue with my code (I have successfully used this script on some of our other sites). 3. If there's possibly other javascript in the theme that is conflicting with my script. I can provide any other relevant code you need on the php script if necessary. The url to page is: <http://www.kriegermfg.com/register-test/> Any help will be greatly appreciated. **Edit** Just to give some further context this is jQueryUI is failing. [![enter image description here](https://i.stack.imgur.com/U8wSs.png)](https://i.stack.imgur.com/U8wSs.png)
Your JS looks to be written inline vs. in its own JS file or at least enqueued on its own. In other words, it doesn't look like its being loaded properly re WordPress. Note the WP function `wp_enqueue_script()` has a dependency parameter where you can pass an array of script handles (as registered via `wp_register_script()`). The parameters of this function helps you ensure that you load header + footer scripts in the desired location (header vs. footer) and desired order. Docs: <https://developer.wordpress.org/reference/functions/wp_enqueue_script/> <https://developer.wordpress.org/reference/functions/wp_register_script/> In the JS itself, make use of `$( document ).ready()`: <http://learn.jquery.com/using-jquery-core/document-ready/> Your code is sitting in the markup before JQuery UI is loaded, which is a potential issue right there to resolve. If it was in its own file and properly enqueued in your theme's functions.php (or by a site plugin) then it could specify JQuery UI's handle as a dependency and WordPress will always load it after. If you still have issues I would also disable your other plugins + any other bits of JS you've tossed in there (temporarily) to see if you can get this to work. If so, you could re-enable them one-by-one to identify the culprit. It also looks like both Contact Form 7 and your theme/plugins are loading JQuery UI, and both depend on date pickers, etc. Contact Form 7's core is loading before the JQuery UI (and loading its other JQuery UI dependencies after) but I don't have enough experience with that plugin to know off-hand if that is a potential source of issues (it might also be something to look into).
319,181
<p>I am having some trouble getting rewrite rules to work as I want in my a WordPress plugin.</p> <p>I added a rewrite rule:</p> <pre><code>add_rewrite_rule('some_url','some_redirected_url', 'top'); </code></pre> <p>The rule is written to .htaccess and the rule works as expected; when inspecting the $_SERVER variable I get the following:</p> <blockquote> <p>$_SERVER['REDIRECT_URL']='some_redirected_url'</p> <p>$_SERVER['REQUEST_URI']='some_url'</p> </blockquote> <p>However, WordPress is parsing $_SERVER['REQUEST_URI'] for request arguments so the redirected request is not parsed.</p> <p>In other words, if I go to <a href="http://myserver/some_url" rel="nofollow noreferrer">http://myserver/some_url</a> the request is not working, even if the redirect works. If I go directly to <a href="http://myserver/some_redirected_url" rel="nofollow noreferrer">http://myserver/some_redirected_url</a> everything works correctly.</p> <p>How can I make WordPress parse the redirected URL?</p>
[ { "answer_id": 319141, "author": "firxworx", "author_id": 134244, "author_profile": "https://wordpress.stackexchange.com/users/134244", "pm_score": 2, "selected": false, "text": "<p>Your JS looks to be written inline vs. in its own JS file or at least enqueued on its own. In other words, it doesn't look like its being loaded properly re WordPress. </p>\n\n<p>Note the WP function <code>wp_enqueue_script()</code> has a dependency parameter where you can pass an array of script handles (as registered via <code>wp_register_script()</code>). The parameters of this function helps you ensure that you load header + footer scripts in the desired location (header vs. footer) and desired order. </p>\n\n<p>Docs: </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a> \n<a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_register_script/</a> </p>\n\n<p>In the JS itself, make use of <code>$( document ).ready()</code>: </p>\n\n<p><a href=\"http://learn.jquery.com/using-jquery-core/document-ready/\" rel=\"nofollow noreferrer\">http://learn.jquery.com/using-jquery-core/document-ready/</a></p>\n\n<p>Your code is sitting in the markup before JQuery UI is loaded, which is a potential issue right there to resolve. If it was in its own file and properly enqueued in your theme's functions.php (or by a site plugin) then it could specify JQuery UI's handle as a dependency and WordPress will always load it after. </p>\n\n<p>If you still have issues I would also disable your other plugins + any other bits of JS you've tossed in there (temporarily) to see if you can get this to work. If so, you could re-enable them one-by-one to identify the culprit. </p>\n\n<p>It also looks like both Contact Form 7 and your theme/plugins are loading JQuery UI, and both depend on date pickers, etc. Contact Form 7's core is loading before the JQuery UI (and loading its other JQuery UI dependencies after) but I don't have enough experience with that plugin to know off-hand if that is a potential source of issues (it might also be something to look into).</p>\n" }, { "answer_id": 383544, "author": "kub1x", "author_id": 164216, "author_profile": "https://wordpress.stackexchange.com/users/164216", "pm_score": 1, "selected": false, "text": "<p>I got here debugging the same error on my WP installation. The previous answer was for developer of plugin/theme, so being an admin, I needed a little different approach. I had to find the source of the problem myself.</p>\n<p>As I learned <a href=\"https://wordpress.stackexchange.com/a/83372/164216\">here</a> I used following line in my <code>config.php</code> to get unminified version of Javascript sources.</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('SCRIPT_DEBUG', true);\n</code></pre>\n<p><strong>TL;DR</strong> In browser I then caught the file to be failing as <code>sotrtable.js</code>. Then I went to my hosting server and searched the wordpress root directory for it using <a href=\"https://github.com/ggreer/the_silver_searcher\" rel=\"nofollow noreferrer\">the silver searcher</a>: <code>ag -l sortable</code>. There I noticed that in <code>wp-content/themes/OurCustomTheme/functions.php</code> there is a call of <code>wp_enqueue_script('jquery-ui', '//code.jquery.com/ui/1.11.4/jquery-ui.js', array(), '20120206')</code> pulling a fixed version of <a href=\"https://jqueryui.com/\" rel=\"nofollow noreferrer\">jQuery ui</a> from CDN. I replaced it with <code>wp_enqueue_script('jquery-ui-core')</code> which is current version of the lib that comes along with WordPress installation and is imported in <code>wp-includes/script-loader.php</code>.</p>\n<p>I'm describing the whole problem to show others, what kind of resolution process is ahead of them, when they bump into such Javascript exception <strong>caused by theme or plugin pulling incorrect version of some JS sources and overriding the correct one</strong>.</p>\n" }, { "answer_id": 387575, "author": "Said Erraoudy", "author_id": 75060, "author_profile": "https://wordpress.stackexchange.com/users/75060", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://wordpress.org/plugins/enable-jquery-migrate-helper/\" rel=\"nofollow noreferrer\">jQuery Migrate Helper</a> fixed it. I’ll troubleshoot which plugin is causing the issue later.</p>\n" } ]
2018/11/14
[ "https://wordpress.stackexchange.com/questions/319181", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153999/" ]
I am having some trouble getting rewrite rules to work as I want in my a WordPress plugin. I added a rewrite rule: ``` add_rewrite_rule('some_url','some_redirected_url', 'top'); ``` The rule is written to .htaccess and the rule works as expected; when inspecting the $\_SERVER variable I get the following: > > $\_SERVER['REDIRECT\_URL']='some\_redirected\_url' > > > $\_SERVER['REQUEST\_URI']='some\_url' > > > However, WordPress is parsing $\_SERVER['REQUEST\_URI'] for request arguments so the redirected request is not parsed. In other words, if I go to <http://myserver/some_url> the request is not working, even if the redirect works. If I go directly to <http://myserver/some_redirected_url> everything works correctly. How can I make WordPress parse the redirected URL?
Your JS looks to be written inline vs. in its own JS file or at least enqueued on its own. In other words, it doesn't look like its being loaded properly re WordPress. Note the WP function `wp_enqueue_script()` has a dependency parameter where you can pass an array of script handles (as registered via `wp_register_script()`). The parameters of this function helps you ensure that you load header + footer scripts in the desired location (header vs. footer) and desired order. Docs: <https://developer.wordpress.org/reference/functions/wp_enqueue_script/> <https://developer.wordpress.org/reference/functions/wp_register_script/> In the JS itself, make use of `$( document ).ready()`: <http://learn.jquery.com/using-jquery-core/document-ready/> Your code is sitting in the markup before JQuery UI is loaded, which is a potential issue right there to resolve. If it was in its own file and properly enqueued in your theme's functions.php (or by a site plugin) then it could specify JQuery UI's handle as a dependency and WordPress will always load it after. If you still have issues I would also disable your other plugins + any other bits of JS you've tossed in there (temporarily) to see if you can get this to work. If so, you could re-enable them one-by-one to identify the culprit. It also looks like both Contact Form 7 and your theme/plugins are loading JQuery UI, and both depend on date pickers, etc. Contact Form 7's core is loading before the JQuery UI (and loading its other JQuery UI dependencies after) but I don't have enough experience with that plugin to know off-hand if that is a potential source of issues (it might also be something to look into).
319,214
<p>EDIT: Turns out the solution was to simply re-install wordpress (it was a new blog anyways). Still not sure what the issue really was but that solved it.</p> <p>I have tried every single fix on stackexchange and other websites and nothing has resolved the issue. </p> <p>I have checked to see that wp_ is in front of all my tables. I have updated http:// to https:// everywhere in the database. I have tried the FORCE_SSL_ADMIN thing with/without $_SERVER['HTTPS']='on' etc. etc.</p> <p>I currently have this in my wp-config.php. I have tried placing it at the top at the bottom, and everywhere in between:</p> <pre><code>define('FORCE_SSL_ADMIN', true); if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') $_SERVER['HTTPS']='on'; </code></pre> <p>I currently have this in my htaccess above the wordpress stuff (have also tried putting it below):</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTPS} off RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] </code></pre> <p>I know the issue is because user capabilities are not getting set with https for some reason. I just don't know why or how to fix it. </p> <p>For example, all these capabilities are set with http but not https:</p> <pre><code>[switch_themes] =&gt; 1 [edit_themes] =&gt; 1 [activate_plugins] =&gt; 1 [edit_plugins] =&gt; 1 [edit_users] =&gt; 1 [edit_files] =&gt; 1 </code></pre> <p>etc.</p> <p>I get: "Sorry, you are not allowed to access this page." no matter what I've tried.</p> <p>I am about ready to throw in the towel and just offer to pay somebody because I've spent 3 days on this now but I figured I'd ask on here first.</p> <p>Any help would be appreciated!</p>
[ { "answer_id": 319196, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 1, "selected": false, "text": "<p>Please, enable the debug mode in WordPress maybe there will be answer. To enable it, open your wp-config.php file and look for define(‘WP_DEBUG’, false);. Change it to:</p>\n\n<p>'define('WP_DEBUG', true);'</p>\n\n<p>In order to enable the error logging to a file on the server you need to add yet one more similar line:</p>\n\n<p>'define( 'WP_DEBUG_LOG', true );'</p>\n\n<p>In this case the errors will be saved to a debug.log log file inside the /wp-content/directory.</p>\n\n<p>Depending on whether you want your errors to be only logged or also displayed on the screen you should also have this line there, immediately after the line mentioned above:</p>\n\n<p>'define( 'WP_DEBUG_DISPLAY', true );'</p>\n\n<p>The wp-config.php is located in your WordPress root directory. It’s the same file where the database configuration settings are. You will have to access it by FTP or SFTP in order to edit it.</p>\n" }, { "answer_id": 319537, "author": "MastaBaba", "author_id": 43252, "author_profile": "https://wordpress.stackexchange.com/users/43252", "pm_score": 0, "selected": false, "text": "<p>The site was running on NGINX with the old hosting provider and on Apache with the new hosting provider.</p>\n\n<p>The uploads folder had a .htaccess file (which NGINX doesn't read) which was preventing requests from referrers that were not the http version of the site. Perhaps a leftover from some Wordpress upgrade, or perhaps added by hand over the 8 years the site has been live. This meant that, now that the site was running on Apache, direct requests (with no referrer) were fine, and cached versions served via Jetpack were also fine.</p>\n\n<p>I still don't understand how, then, images in the list view were showing, as they do not seem to be served by Jetpack's CDN, but so be it.</p>\n" }, { "answer_id": 342958, "author": "Steve", "author_id": 25717, "author_profile": "https://wordpress.stackexchange.com/users/25717", "pm_score": 0, "selected": false, "text": "<p>Late answer, but I had a similar issue and it was caused by a technician renaming <code>wp-admin/admin-ajax.php</code> when the site was under attack and not reverting it to the original name.</p>\n" }, { "answer_id": 348641, "author": "Rob Ruifrok", "author_id": 175394, "author_profile": "https://wordpress.stackexchange.com/users/175394", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem: cropped header images for the custom header were shown in listview, but not in grid view.</p>\n\n<p>The ajax response containing the image data has an item 'context', wich was set to 'custom-header' for the cropped images and blank for other images.</p>\n\n<p>in wp-includes\\js\\media-models.js a validator: function( attachment ) \nis defined and contains the comment line :\"//Filter out contextually created attachments (e.g. headers, logos, etc.).\"</p>\n\n<p>The following solved the (my) problem:</p>\n\n<pre><code>add_filter('wp_prepare_attachment_for_js', 'pas_context_aan', 10, 3 );\nfunction pas_context_aan($response, $attachment, $meta) {\n if ($response['context'] == 'custom-header') $response['context'] = ''; \n return $response;\n}\n</code></pre>\n" } ]
2018/11/14
[ "https://wordpress.stackexchange.com/questions/319214", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154094/" ]
EDIT: Turns out the solution was to simply re-install wordpress (it was a new blog anyways). Still not sure what the issue really was but that solved it. I have tried every single fix on stackexchange and other websites and nothing has resolved the issue. I have checked to see that wp\_ is in front of all my tables. I have updated http:// to https:// everywhere in the database. I have tried the FORCE\_SSL\_ADMIN thing with/without $\_SERVER['HTTPS']='on' etc. etc. I currently have this in my wp-config.php. I have tried placing it at the top at the bottom, and everywhere in between: ``` define('FORCE_SSL_ADMIN', true); if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') $_SERVER['HTTPS']='on'; ``` I currently have this in my htaccess above the wordpress stuff (have also tried putting it below): ``` RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTPS} off RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] ``` I know the issue is because user capabilities are not getting set with https for some reason. I just don't know why or how to fix it. For example, all these capabilities are set with http but not https: ``` [switch_themes] => 1 [edit_themes] => 1 [activate_plugins] => 1 [edit_plugins] => 1 [edit_users] => 1 [edit_files] => 1 ``` etc. I get: "Sorry, you are not allowed to access this page." no matter what I've tried. I am about ready to throw in the towel and just offer to pay somebody because I've spent 3 days on this now but I figured I'd ask on here first. Any help would be appreciated!
Please, enable the debug mode in WordPress maybe there will be answer. To enable it, open your wp-config.php file and look for define(‘WP\_DEBUG’, false);. Change it to: 'define('WP\_DEBUG', true);' In order to enable the error logging to a file on the server you need to add yet one more similar line: 'define( 'WP\_DEBUG\_LOG', true );' In this case the errors will be saved to a debug.log log file inside the /wp-content/directory. Depending on whether you want your errors to be only logged or also displayed on the screen you should also have this line there, immediately after the line mentioned above: 'define( 'WP\_DEBUG\_DISPLAY', true );' The wp-config.php is located in your WordPress root directory. It’s the same file where the database configuration settings are. You will have to access it by FTP or SFTP in order to edit it.
319,215
<p>i am using ACF to <a href="https://www.advancedcustomfields.com/resources/date-picker/" rel="nofollow noreferrer">display an internationalized date</a> with this code :</p> <pre><code>&lt;?php $dateformatstring = "l j F Y"; $unixtimestamp = strtotime(get_field('date')); ?&gt; &lt;?php echo date_i18n($dateformatstring, $unixtimestamp); ?&gt; </code></pre> <p>but i wish i could separate each part into span for example to obtain a result like this : </p> <pre><code>&lt;span&gt;*day number*&lt;/span&gt;&lt;span&gt;*week day*&lt;/span&gt;&lt;span&gt;*month*&lt;/span&gt;&lt;span&gt;*year*&lt;/span&gt; </code></pre> <p>but despite many attemps, i couldn't make it -_- Thanks for your help ;-)</p>
[ { "answer_id": 319216, "author": "studiok7", "author_id": 150027, "author_profile": "https://wordpress.stackexchange.com/users/150027", "pm_score": 2, "selected": false, "text": "<p>thanks to @kero, i managed to do something like this :</p>\n\n<pre><code>&lt;?php\n $dayNumber = \"l\";\n $weekDay = \"j\";\n $month = \"F\";\n $year = \"Y\";\n $unixtimestamp = strtotime(get_field('date'));\n?&gt;\n\n&lt;?php echo '&lt;span&gt;' . date_i18n($dayNumber, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n&lt;?php echo '&lt;span&gt;' . date_i18n($weekDay, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n&lt;?php echo '&lt;span&gt;' . date_i18n($month, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n&lt;?php echo '&lt;span&gt;' . date_i18n($year, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n</code></pre>\n\n<p>Not sure it is the best way to do it but it works. Thanks !</p>\n" }, { "answer_id": 359559, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 1, "selected": false, "text": "<p>There's another way to do it <a href=\"https://support.advancedcustomfields.com/forums/topic/how-to-split-the-date-picker-value/\" rel=\"nofollow noreferrer\">as demonstrated here</a>:</p>\n\n<ul>\n<li>In ACF settings, use 'Custom Format' to separate the items you want to add HTML to with a comma\n\n<ul>\n<li><code>M,d</code></li>\n</ul></li>\n<li>In your output file, set up your date output as a variable\n\n<ul>\n<li><code>$date = get_field(‘date’);</code></li>\n</ul></li>\n<li>Next, <a href=\"https://www.php.net/manual/en/function.explode.php\" rel=\"nofollow noreferrer\"><code>explode</code></a> the variable you created\n\n<ul>\n<li><code>$dateArray = explode(‘,’, $date)</code></li>\n</ul></li>\n<li>Use the array you created to add HTML to each piece of your date\n\n<ul>\n<li><code>&lt;p class=\"month\"&gt;&lt;?php echo $dateArray[0]; ?&gt;&lt;/p&gt;</code></li>\n<li><code>&lt;p class=\"date\"&gt;&lt;?php echo $myArray[1]; ?&gt;&lt;/p&gt;</code></li>\n</ul></li>\n<li>Profit!</li>\n</ul>\n" } ]
2018/11/14
[ "https://wordpress.stackexchange.com/questions/319215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150027/" ]
i am using ACF to [display an internationalized date](https://www.advancedcustomfields.com/resources/date-picker/) with this code : ``` <?php $dateformatstring = "l j F Y"; $unixtimestamp = strtotime(get_field('date')); ?> <?php echo date_i18n($dateformatstring, $unixtimestamp); ?> ``` but i wish i could separate each part into span for example to obtain a result like this : ``` <span>*day number*</span><span>*week day*</span><span>*month*</span><span>*year*</span> ``` but despite many attemps, i couldn't make it -\_- Thanks for your help ;-)
thanks to @kero, i managed to do something like this : ``` <?php $dayNumber = "l"; $weekDay = "j"; $month = "F"; $year = "Y"; $unixtimestamp = strtotime(get_field('date')); ?> <?php echo '<span>' . date_i18n($dayNumber, $unixtimestamp) . '</span>'; ?> <?php echo '<span>' . date_i18n($weekDay, $unixtimestamp) . '</span>'; ?> <?php echo '<span>' . date_i18n($month, $unixtimestamp) . '</span>'; ?> <?php echo '<span>' . date_i18n($year, $unixtimestamp) . '</span>'; ?> ``` Not sure it is the best way to do it but it works. Thanks !
319,259
<p>I want to get all post which was posted on X Days, I don't want 7 days old post or 1 Month old posts, Because it will return all posts which will be older 7 days or one month. Like Today is 15 SEP, I want to get all posts which was post on 5 SEP. Only 5 sep not older then 5 SEP. Only one Day posts. I have try code like this</p> <pre><code>$args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'post', 'date_query' =&gt; array( 'after' =&gt; date('Y-m-d', strtotime('-10 days')) ) ); </code></pre> <p>But its return 10 days old posts. Any help to get post for X days?</p>
[ { "answer_id": 319216, "author": "studiok7", "author_id": 150027, "author_profile": "https://wordpress.stackexchange.com/users/150027", "pm_score": 2, "selected": false, "text": "<p>thanks to @kero, i managed to do something like this :</p>\n\n<pre><code>&lt;?php\n $dayNumber = \"l\";\n $weekDay = \"j\";\n $month = \"F\";\n $year = \"Y\";\n $unixtimestamp = strtotime(get_field('date'));\n?&gt;\n\n&lt;?php echo '&lt;span&gt;' . date_i18n($dayNumber, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n&lt;?php echo '&lt;span&gt;' . date_i18n($weekDay, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n&lt;?php echo '&lt;span&gt;' . date_i18n($month, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n&lt;?php echo '&lt;span&gt;' . date_i18n($year, $unixtimestamp) . '&lt;/span&gt;'; ?&gt;\n</code></pre>\n\n<p>Not sure it is the best way to do it but it works. Thanks !</p>\n" }, { "answer_id": 359559, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 1, "selected": false, "text": "<p>There's another way to do it <a href=\"https://support.advancedcustomfields.com/forums/topic/how-to-split-the-date-picker-value/\" rel=\"nofollow noreferrer\">as demonstrated here</a>:</p>\n\n<ul>\n<li>In ACF settings, use 'Custom Format' to separate the items you want to add HTML to with a comma\n\n<ul>\n<li><code>M,d</code></li>\n</ul></li>\n<li>In your output file, set up your date output as a variable\n\n<ul>\n<li><code>$date = get_field(‘date’);</code></li>\n</ul></li>\n<li>Next, <a href=\"https://www.php.net/manual/en/function.explode.php\" rel=\"nofollow noreferrer\"><code>explode</code></a> the variable you created\n\n<ul>\n<li><code>$dateArray = explode(‘,’, $date)</code></li>\n</ul></li>\n<li>Use the array you created to add HTML to each piece of your date\n\n<ul>\n<li><code>&lt;p class=\"month\"&gt;&lt;?php echo $dateArray[0]; ?&gt;&lt;/p&gt;</code></li>\n<li><code>&lt;p class=\"date\"&gt;&lt;?php echo $myArray[1]; ?&gt;&lt;/p&gt;</code></li>\n</ul></li>\n<li>Profit!</li>\n</ul>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100690/" ]
I want to get all post which was posted on X Days, I don't want 7 days old post or 1 Month old posts, Because it will return all posts which will be older 7 days or one month. Like Today is 15 SEP, I want to get all posts which was post on 5 SEP. Only 5 sep not older then 5 SEP. Only one Day posts. I have try code like this ``` $args = array( 'posts_per_page' => -1, 'post_type' => 'post', 'date_query' => array( 'after' => date('Y-m-d', strtotime('-10 days')) ) ); ``` But its return 10 days old posts. Any help to get post for X days?
thanks to @kero, i managed to do something like this : ``` <?php $dayNumber = "l"; $weekDay = "j"; $month = "F"; $year = "Y"; $unixtimestamp = strtotime(get_field('date')); ?> <?php echo '<span>' . date_i18n($dayNumber, $unixtimestamp) . '</span>'; ?> <?php echo '<span>' . date_i18n($weekDay, $unixtimestamp) . '</span>'; ?> <?php echo '<span>' . date_i18n($month, $unixtimestamp) . '</span>'; ?> <?php echo '<span>' . date_i18n($year, $unixtimestamp) . '</span>'; ?> ``` Not sure it is the best way to do it but it works. Thanks !
319,271
<p>A client of mine has installed contact form 7 for their contact forms but they're getting an error in the From field "(configuration error) Invalid mailbox syntax is used."</p> <p>The form looks like this:</p> <pre><code>[text text-54 placeholder "Your Name"][text text-54 placeholder "Your Company"] [email* email-317 placeholder "Email Address"][tel tel-646 placeholder "Phone Number"] [textarea textarea-820 class:large-input placeholder "Tell us about your requirements"] [submit "Request Callback"] </code></pre> <p>Now in the from field in the mail section they had </p> <pre><code>&lt;[email your-email]&gt; so I changed it to &lt;[email* email-317]&gt; </code></pre> <p>But I'm still getting the error? Thought that should have fixed it, can anybody spot anything else wrong with it?</p>
[ { "answer_id": 319275, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 0, "selected": false, "text": "<p><strong>Invalid mailbox syntax is used Error</strong></p>\n\n<p>You can find Invalid mailbox syntax is used error under the To, From, Subject or Additional Headers fields, that are located in the Mail Contact Form tab.</p>\n\n<p>solve “Your contact form has a configuration issue” error</p>\n\n<p>You have to solve this error. Otherwise, your email might not reach the addressee.</p>\n\n<p>To cope with this error you might need to accomplish the next steps.</p>\n\n<p>1] First, add valid email address to the To field (e. g., [email protected]).</p>\n\n<p>2] Make sure that you use correct syntax in the From field (e. g., [your name] &lt;[your-email]>).</p>\n\n<p>3] Fill in your email subject to add information on your email (e.g., Site Name – [your-subject]).</p>\n\n<p>4] You can add new fields to your contact form (e.g. phone number, city, etc.). Add the necessary content in the Additional Headers block (for instance, Phone: [phone]).</p>\n\n<p><strong>“This field can be empty depending on user input” Error</strong></p>\n\n<p>You can face This field can be empty depending on user input error if you’ve left Additional Headers or Subject fields empty.\nIf you don’t want to use these fields, you may leave them empty, as they won’t influence sending messages.\nBut if you face this error in To, From or Message fields, you’ll have Failed to send your message error when submitting a contact form.\nFill in the fields correctly to avoid these kinds of errors.</p>\n" }, { "answer_id": 319291, "author": "Asrsagar", "author_id": 129292, "author_profile": "https://wordpress.stackexchange.com/users/129292", "pm_score": -1, "selected": false, "text": "<p>Please check the screenshot and follow this link <a href=\"https://contactform7.com/configuration-validator-faq/\" rel=\"nofollow noreferrer\">https://contactform7.com/configuration-validator-faq/</a>. <a href=\"https://i.stack.imgur.com/cHAjT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cHAjT.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 319298, "author": "E. Fitzpatrick", "author_id": 77682, "author_profile": "https://wordpress.stackexchange.com/users/77682", "pm_score": 0, "selected": false, "text": "<p>The from field should be <code>&lt;[your-email]&gt;</code> - where you have specified it as a required field is only required for creating the field in the first place, not for transmitting the data in the mail section.</p>\n\n<p>My general way for setting Contact Form 7 up is to use <code>Website Name &lt;[email protected]&gt;</code> in the from field, and then using the email submitted in the form in a <code>Reply-To</code> header instead.</p>\n\n<p>Please refer to the <a href=\"https://contactform7.com/configuration-validator-faq/\" rel=\"nofollow noreferrer\">Contact Form 7 documentation</a> for more information.</p>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154129/" ]
A client of mine has installed contact form 7 for their contact forms but they're getting an error in the From field "(configuration error) Invalid mailbox syntax is used." The form looks like this: ``` [text text-54 placeholder "Your Name"][text text-54 placeholder "Your Company"] [email* email-317 placeholder "Email Address"][tel tel-646 placeholder "Phone Number"] [textarea textarea-820 class:large-input placeholder "Tell us about your requirements"] [submit "Request Callback"] ``` Now in the from field in the mail section they had ``` <[email your-email]> so I changed it to <[email* email-317]> ``` But I'm still getting the error? Thought that should have fixed it, can anybody spot anything else wrong with it?
**Invalid mailbox syntax is used Error** You can find Invalid mailbox syntax is used error under the To, From, Subject or Additional Headers fields, that are located in the Mail Contact Form tab. solve “Your contact form has a configuration issue” error You have to solve this error. Otherwise, your email might not reach the addressee. To cope with this error you might need to accomplish the next steps. 1] First, add valid email address to the To field (e. g., [email protected]). 2] Make sure that you use correct syntax in the From field (e. g., [your name] <[your-email]>). 3] Fill in your email subject to add information on your email (e.g., Site Name – [your-subject]). 4] You can add new fields to your contact form (e.g. phone number, city, etc.). Add the necessary content in the Additional Headers block (for instance, Phone: [phone]). **“This field can be empty depending on user input” Error** You can face This field can be empty depending on user input error if you’ve left Additional Headers or Subject fields empty. If you don’t want to use these fields, you may leave them empty, as they won’t influence sending messages. But if you face this error in To, From or Message fields, you’ll have Failed to send your message error when submitting a contact form. Fill in the fields correctly to avoid these kinds of errors.
319,297
<p>I am trying to filter a query to only show posts that are posted by a user with the administrator role.</p> <p>I've created a pre_get_posts action, and trying to use $query->set to filter the posts only in the category pages...</p> <p>So far I have this</p> <pre><code>function remove_unvetted_authors() { $query-&gt;set( 'role', 'administrator' ); } if (is_category()) { add_action( 'pre_get_posts', 'remove_unvetted_authors' ); } </code></pre> <p>but it's throwing a 500 error. I'm know 'role' isn't actually an arg for wp_query, but I can't find one that looks at the user role. :/</p> <p>I also tried this:</p> <pre><code>function remove_unvetted_authors() { $ids = get_users( array('role' =&gt; 'administrator' ,'fields' =&gt; 'ID') ); $query-&gt;set( 'author', '$ids' ); } add_action( 'pre_get_posts', 'remove_unvetted_authors' ); </code></pre> <p>But this also throws a 500 error</p>
[ { "answer_id": 319301, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<pre><code>function remove_unvetted_authors() {\n $ids = get_users( array('role' =&gt; 'administrator' ,'fields' =&gt; 'ID') );\n $query-&gt;set( 'author', '$ids' );\n}\n\nadd_action( 'pre_get_posts', 'remove_unvetted_authors' );\n</code></pre>\n\n<p>This is going in the right direction but has a specific that is wrong. <code>'$ids'</code> - due to the single quotes, the variable does not get evaluated. Also <a href=\"https://developer.wordpress.org/reference/functions/get_users/#return\" rel=\"nofollow noreferrer\"><code>get_users()</code></a> returns an <strong>array</strong>. <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#author-parameters\" rel=\"nofollow noreferrer\"><code>author</code></a> expects an <strong>int</strong>.</p>\n\n<p>Instead, with <code>author__in</code> (and no single quotes) it should work:</p>\n\n<pre><code>function remove_unvetted_authors() {\n $ids = get_users( array('role' =&gt; 'administrator' ,'fields' =&gt; 'ID') );\n $query-&gt;set( 'author__in', $ids );\n}\n</code></pre>\n" }, { "answer_id": 319303, "author": "Prasad Wandre", "author_id": 153566, "author_profile": "https://wordpress.stackexchange.com/users/153566", "pm_score": -1, "selected": false, "text": "<p>Please try to check below code:</p>\n\n<pre><code>function remove_unvetted_authors() {\n// Query user data on admins\n$administrators = new WP_User_Query( array( 'role' =&gt; 'administrator' ) ); \n\n// Save admin IDs\nforeach( $administrators-&gt;results as $u )\n $user_ids[] = $u-&gt;ID;\n\n// Little cleanup\nunset( $u, $administrators);\n\n// Get all posts by these authors\n$query = new WP_Query( array( \n 'post_type' =&gt; 'post',\n 'author' =&gt; $user_ids \n) );\n$posts = $query-&gt;posts;\n\n//collect all post ids of that author by loop\n$post_ids = array();\nforeach($posts as $post) {\n $post_ids[] = $post-&gt;ID; \n}\n\n$query-&gt;set('post__in', $post_ids);\n}\n\nadd_action( 'pre_get_posts', 'remove_unvetted_authors' );\n</code></pre>\n" }, { "answer_id": 319304, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>There's quite a few issues with this code:</p>\n\n<ol>\n<li><code>$query</code> is not defined in your callback function.</li>\n<li><code>role</code> is not a valid argument for a query.</li>\n<li>You're passing the <code>$ids</code> variable incorrectly.</li>\n<li>To query for multiple authors you need to use <code>author__in</code>.</li>\n<li>You're checking <code>is_category()</code> incorrectly.</li>\n</ol>\n\n<p>For the first issue, the problem is that you're not getting <code>$query</code> from anywhere. You need to accept it as a parameter in the callback function:</p>\n\n<pre><code>function remove_unvetted_authors( $query ) {\n // $query-&gt;set( 'property', 'value' );\n}\n</code></pre>\n\n<p>If you don't do that, <code>$query</code> is undefined, and trying to use <code>-&gt;set()</code> on an undefined variable will result in a 500 error. This is the issue responsible for that error code. But, even if you fix that it still won't work until you resolve the other issues.</p>\n\n<p>For the second issue, you can't query posts by author role like that. You will need to do what you're trying in your second example and query the author ids.</p>\n\n<p>For the third issue, you're passing <code>$ids</code> incorrectly. It's a variable, so shouldn't have quotes around it:</p>\n\n<pre><code>$query-&gt;set( 'author', $ids );\n</code></pre>\n\n<p>That wouldn't throw a 500 error, but it still won't work.</p>\n\n<p>The fourth issue is that you can't query multiple authors with the <code>author</code> argument. You need to use <code>author__in</code>:</p>\n\n<pre><code>$query-&gt;set( 'author__in', $ids );\n</code></pre>\n\n<p>Lastly, you're using <code>is_category()</code> incorrectly. The way you've structured it now, <code>remove_unvetted_authors()</code> would apply to <em>all</em> queries when you're viewing a category. </p>\n\n<p>This would include menus and widgets. But, as written, even that wouldn't work correctly. This is because <code>is_category()</code> will not work outside a hooked function, because whether or not it is a category hasn't been determined yet when functions.php is run.</p>\n\n<p>You only want to affect the main category queries, and you only want to do it on the front-end. So you should check <code>is_admin()</code> and also <code>$query-&gt;is_category()</code>.</p>\n\n<p>So after fixing all those issues, your code would look like this:</p>\n\n<pre><code>function remove_unvetted_authors( $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_category() ) {\n $user_ids = get_users( [\n 'role' =&gt; 'administrator',\n 'fields' =&gt; 'ID'\n ] );\n\n $query-&gt;set( 'author__in', $user_ids );\n }\n}\nadd_action( 'pre_get_posts', 'remove_unvetted_authors' );\n</code></pre>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111198/" ]
I am trying to filter a query to only show posts that are posted by a user with the administrator role. I've created a pre\_get\_posts action, and trying to use $query->set to filter the posts only in the category pages... So far I have this ``` function remove_unvetted_authors() { $query->set( 'role', 'administrator' ); } if (is_category()) { add_action( 'pre_get_posts', 'remove_unvetted_authors' ); } ``` but it's throwing a 500 error. I'm know 'role' isn't actually an arg for wp\_query, but I can't find one that looks at the user role. :/ I also tried this: ``` function remove_unvetted_authors() { $ids = get_users( array('role' => 'administrator' ,'fields' => 'ID') ); $query->set( 'author', '$ids' ); } add_action( 'pre_get_posts', 'remove_unvetted_authors' ); ``` But this also throws a 500 error
There's quite a few issues with this code: 1. `$query` is not defined in your callback function. 2. `role` is not a valid argument for a query. 3. You're passing the `$ids` variable incorrectly. 4. To query for multiple authors you need to use `author__in`. 5. You're checking `is_category()` incorrectly. For the first issue, the problem is that you're not getting `$query` from anywhere. You need to accept it as a parameter in the callback function: ``` function remove_unvetted_authors( $query ) { // $query->set( 'property', 'value' ); } ``` If you don't do that, `$query` is undefined, and trying to use `->set()` on an undefined variable will result in a 500 error. This is the issue responsible for that error code. But, even if you fix that it still won't work until you resolve the other issues. For the second issue, you can't query posts by author role like that. You will need to do what you're trying in your second example and query the author ids. For the third issue, you're passing `$ids` incorrectly. It's a variable, so shouldn't have quotes around it: ``` $query->set( 'author', $ids ); ``` That wouldn't throw a 500 error, but it still won't work. The fourth issue is that you can't query multiple authors with the `author` argument. You need to use `author__in`: ``` $query->set( 'author__in', $ids ); ``` Lastly, you're using `is_category()` incorrectly. The way you've structured it now, `remove_unvetted_authors()` would apply to *all* queries when you're viewing a category. This would include menus and widgets. But, as written, even that wouldn't work correctly. This is because `is_category()` will not work outside a hooked function, because whether or not it is a category hasn't been determined yet when functions.php is run. You only want to affect the main category queries, and you only want to do it on the front-end. So you should check `is_admin()` and also `$query->is_category()`. So after fixing all those issues, your code would look like this: ``` function remove_unvetted_authors( $query ) { if ( ! is_admin() && $query->is_category() ) { $user_ids = get_users( [ 'role' => 'administrator', 'fields' => 'ID' ] ); $query->set( 'author__in', $user_ids ); } } add_action( 'pre_get_posts', 'remove_unvetted_authors' ); ```
319,306
<p>Under the appearance admin menu, I have customizer added by the theme, and theme options added by a plugin. I'm using this code to hide both menus ( submenu's of Appearance )for ALL admins apart from a certain USERNAME. </p> <pre><code>function hide_menu() { global $current_user; $current_user = wp_get_current_user(); $user_name = $current_user-&gt;user_login; //check condition for the user means show menu for this user if(is_admin() &amp;&amp; $user_name != 'USERNAME') { remove_submenu_page( 'themes.php', 'customize' ); remove_submenu_page( 'themes.php', 'core-settings' ); } } add_action('admin_head', 'hide-menu'); </code></pre> <p>The code its self works fine, I can hide parent menu's. But I can't seem to hide the two sub menu's that I want to hide. </p> <p>The two menu's point to URLs : </p> <pre><code>domainname.com/wp-admin/customize.php domainname.com/wp-admin/themes.php?page=core-settings </code></pre> <p>Submenu Debug :</p> <pre><code>[6] =&gt; Array ( [0] =&gt; Customise [1] =&gt; customize [2] =&gt; customize.php?return=%2Fwp-admin%2Findex.php [3] =&gt; [4] =&gt; hide-if-no-customize ) [21] =&gt; Array ( [0] =&gt; Theme Settings [1] =&gt; manage_options [2] =&gt; core-settings [3] =&gt; Theme Settings ) </code></pre> <p>I've looked at dubug mode but im not sure what im looking at, could someone please give a solution and an explanation as to why it works.</p>
[ { "answer_id": 319554, "author": "coolpasta", "author_id": 143406, "author_profile": "https://wordpress.stackexchange.com/users/143406", "pm_score": 4, "selected": true, "text": "<p>Direct answer:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n global $current_user;\n $current_user = wp_get_current_user();\n $user_name = $current_user-&gt;user_login;\n\n //check condition for the user means show menu for this user\n if(is_admin() &amp;&amp; $user_name != 'USERNAME') {\n //We need this because the submenu's link (key from the array too) will always be generated with the current SERVER_URI in mind.\n $customizer_url = add_query_arg( 'return', urlencode( remove_query_arg( wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI'] ) ) ), 'customize.php' );\n remove_submenu_page( 'themes.php', $customizer_url );\n }\n}, 999 );\n</code></pre>\n\n<p>You have to respect the full-path naming. </p>\n\n<hr>\n\n<p>The long answer, this:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n $page = remove_submenu_page( 'themes.php', 'customize.php' );\n}, 999 );\n</code></pre>\n\n<p>Doesn't work. But this:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n $page = remove_submenu_page( 'themes.php', 'widgets.php' );\n}, 999 );\n</code></pre>\n\n<p>Works. If we just look at the links, then we can see that it <strong>should work</strong>, but check this out. In <code>wp-admin/menu.php, line 164</code>, we have:</p>\n\n<pre><code>$submenu['themes.php'][6] = array( __( 'Customize' ), 'customize', esc_url( $customize_url ), '', 'hide-if-no-customize' );\n</code></pre>\n\n<p>If we comment this out, bang, the <code>Customize</code> link dissapears, but if we go on ahead and paste this code and go to our <code>wp-admin/index.php</code>, we can see that there's no <code>customize.php</code> in the array:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n global $submenu;\n var_dump( $submenu );\n}, 999 );\n</code></pre>\n\n<p>The others are here. So what's going on? If we dump the <code>$submenu</code> right after it's created, we can see that it's there:</p>\n\n<pre><code>[themes.php] =&gt; Array\n (\n [5] =&gt; Array\n (\n [0] =&gt; Themes\n [1] =&gt; switch_themes\n [2] =&gt; themes.php\n )\n\n [6] =&gt; Array\n (\n [0] =&gt; Customize\n [1] =&gt; customize\n [2] =&gt; customize.php?return=%2Fwordpress%2Fwp-admin%2Findex.php\n [3] =&gt; \n [4] =&gt; hide-if-no-customize\n )\n\n [10] =&gt; Array\n (\n [0] =&gt; Menus\n [1] =&gt; edit_theme_options\n [2] =&gt; nav-menus.php\n )\n\n )\n</code></pre>\n\n<p>...so, somewhere, it gets lost, <strong>or so you would think</strong>, at the end of this file, we see that, yet again, we include another file:</p>\n\n<pre><code>require_once(ABSPATH . 'wp-admin/includes/menu.php');\n</code></pre>\n\n<p>If we then go at the end of this file and we dump the <code>$menu</code>, what we get is..surprisingly, a menu without 'customizer' in it. But it was there just moments ago.</p>\n\n<p>Surprisingly, if we do:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n global $submenu;\n var_dump( $submenu );\n}, 999 );\n</code></pre>\n\n<p>It's clear, the <code>customize.php</code> is there...except...it generates itself with some parameters after: <code>customize.php?return=%2Fwordpress%2Fwp-admin%2Findex.php</code> (this depends on your site).</p>\n\n<p>Interesting, so if we do:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwordpress%2Fwp-admin%2Findex.php' );\n}, 999 )\n</code></pre>\n\n<p>Or, in your case:</p>\n\n<pre><code>add_action( 'admin_menu', function() {\n remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Findex.php' );\n}, 999 )\n</code></pre>\n\n<p>It works.</p>\n\n<p>So what did we learn today? WP Core is a bad piece of crap, ok, it's true but it's your mistake for not looking at what <code>remove_submenu_page</code> looks for.</p>\n\n<pre><code>function remove_submenu_page( $menu_slug, $submenu_slug ) {\n global $submenu;\n\n if ( !isset( $submenu[$menu_slug] ) )\n return false;\n\n foreach ( $submenu[$menu_slug] as $i =&gt; $item ) {\n if ( $submenu_slug == $item[2] ) {\n unset( $submenu[$menu_slug][$i] );\n return $item;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>It first checks to see if the menu exists, in our case <code>themes.php</code> and then it goes over each item from, say, <code>Appearance</code>, each being an array itself, then it looks for the third item, which corresponds to the <code>[2] =&gt; customize.php...</code> item, so, of course it's not going to find our <code>customize.php</code>, that's why we need to provide it the full link. It's just a simple mistake.</p>\n" }, { "answer_id": 349306, "author": "FooBar", "author_id": 50042, "author_profile": "https://wordpress.stackexchange.com/users/50042", "pm_score": 2, "selected": false, "text": "<h2>This would work in WordPress 5</h2>\n\n<pre><code>add_action( 'admin_menu', function() {\n remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode($_SERVER['SCRIPT_NAME']));\n});\n</code></pre>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319306", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62291/" ]
Under the appearance admin menu, I have customizer added by the theme, and theme options added by a plugin. I'm using this code to hide both menus ( submenu's of Appearance )for ALL admins apart from a certain USERNAME. ``` function hide_menu() { global $current_user; $current_user = wp_get_current_user(); $user_name = $current_user->user_login; //check condition for the user means show menu for this user if(is_admin() && $user_name != 'USERNAME') { remove_submenu_page( 'themes.php', 'customize' ); remove_submenu_page( 'themes.php', 'core-settings' ); } } add_action('admin_head', 'hide-menu'); ``` The code its self works fine, I can hide parent menu's. But I can't seem to hide the two sub menu's that I want to hide. The two menu's point to URLs : ``` domainname.com/wp-admin/customize.php domainname.com/wp-admin/themes.php?page=core-settings ``` Submenu Debug : ``` [6] => Array ( [0] => Customise [1] => customize [2] => customize.php?return=%2Fwp-admin%2Findex.php [3] => [4] => hide-if-no-customize ) [21] => Array ( [0] => Theme Settings [1] => manage_options [2] => core-settings [3] => Theme Settings ) ``` I've looked at dubug mode but im not sure what im looking at, could someone please give a solution and an explanation as to why it works.
Direct answer: ``` add_action( 'admin_menu', function() { global $current_user; $current_user = wp_get_current_user(); $user_name = $current_user->user_login; //check condition for the user means show menu for this user if(is_admin() && $user_name != 'USERNAME') { //We need this because the submenu's link (key from the array too) will always be generated with the current SERVER_URI in mind. $customizer_url = add_query_arg( 'return', urlencode( remove_query_arg( wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI'] ) ) ), 'customize.php' ); remove_submenu_page( 'themes.php', $customizer_url ); } }, 999 ); ``` You have to respect the full-path naming. --- The long answer, this: ``` add_action( 'admin_menu', function() { $page = remove_submenu_page( 'themes.php', 'customize.php' ); }, 999 ); ``` Doesn't work. But this: ``` add_action( 'admin_menu', function() { $page = remove_submenu_page( 'themes.php', 'widgets.php' ); }, 999 ); ``` Works. If we just look at the links, then we can see that it **should work**, but check this out. In `wp-admin/menu.php, line 164`, we have: ``` $submenu['themes.php'][6] = array( __( 'Customize' ), 'customize', esc_url( $customize_url ), '', 'hide-if-no-customize' ); ``` If we comment this out, bang, the `Customize` link dissapears, but if we go on ahead and paste this code and go to our `wp-admin/index.php`, we can see that there's no `customize.php` in the array: ``` add_action( 'admin_menu', function() { global $submenu; var_dump( $submenu ); }, 999 ); ``` The others are here. So what's going on? If we dump the `$submenu` right after it's created, we can see that it's there: ``` [themes.php] => Array ( [5] => Array ( [0] => Themes [1] => switch_themes [2] => themes.php ) [6] => Array ( [0] => Customize [1] => customize [2] => customize.php?return=%2Fwordpress%2Fwp-admin%2Findex.php [3] => [4] => hide-if-no-customize ) [10] => Array ( [0] => Menus [1] => edit_theme_options [2] => nav-menus.php ) ) ``` ...so, somewhere, it gets lost, **or so you would think**, at the end of this file, we see that, yet again, we include another file: ``` require_once(ABSPATH . 'wp-admin/includes/menu.php'); ``` If we then go at the end of this file and we dump the `$menu`, what we get is..surprisingly, a menu without 'customizer' in it. But it was there just moments ago. Surprisingly, if we do: ``` add_action( 'admin_menu', function() { global $submenu; var_dump( $submenu ); }, 999 ); ``` It's clear, the `customize.php` is there...except...it generates itself with some parameters after: `customize.php?return=%2Fwordpress%2Fwp-admin%2Findex.php` (this depends on your site). Interesting, so if we do: ``` add_action( 'admin_menu', function() { remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwordpress%2Fwp-admin%2Findex.php' ); }, 999 ) ``` Or, in your case: ``` add_action( 'admin_menu', function() { remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Findex.php' ); }, 999 ) ``` It works. So what did we learn today? WP Core is a bad piece of crap, ok, it's true but it's your mistake for not looking at what `remove_submenu_page` looks for. ``` function remove_submenu_page( $menu_slug, $submenu_slug ) { global $submenu; if ( !isset( $submenu[$menu_slug] ) ) return false; foreach ( $submenu[$menu_slug] as $i => $item ) { if ( $submenu_slug == $item[2] ) { unset( $submenu[$menu_slug][$i] ); return $item; } } return false; } ``` It first checks to see if the menu exists, in our case `themes.php` and then it goes over each item from, say, `Appearance`, each being an array itself, then it looks for the third item, which corresponds to the `[2] => customize.php...` item, so, of course it's not going to find our `customize.php`, that's why we need to provide it the full link. It's just a simple mistake.
319,308
<p>I'm using the Advanced Custom Fields plugin and I have created some options pages with:</p> <pre><code>if (function_exists('acf_add_options_page')) { website_settings_init(); } function website_settings_init() { $website_settings = acf_add_options_page(array( 'page_title' =&gt; 'Website Settings', 'menu_title' =&gt; 'Website Settings', 'menu-slug' =&gt; 'website-settings', 'post_id' =&gt; 'website-settings', 'redirect' =&gt; false )); $form_settings = acf_add_options_sub_page(array( 'page_title' =&gt; 'Form Settings', 'menu_title' =&gt; 'Form Settings', 'menu-slug' =&gt; 'form-settings', 'post_id' =&gt; 'form-settings', 'parent_slug' =&gt; $website_settings['menu_slug'] )); $contact_details = acf_add_options_sub_page(array( 'page_title' =&gt; 'Contact Details', 'menu_title' =&gt; 'Contact Details', 'menu-slug' =&gt; 'contact-details', 'post_id' =&gt; 'contact-details', 'parent_slug' =&gt; $website_settings['menu_slug'] )); } </code></pre> <p>I have a field group that is visible if Options Page = Form Settings.</p> <p>One of these fields is 'thank_you_page' which returns a Page ID.</p> <p>I read <a href="https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/" rel="nofollow noreferrer">https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/</a> which describes how you can get values from an options page field using <code>get_field('field_name', 'option');</code></p> <p>I have tried:</p> <pre><code>get_field('thank_you_page', 'option'); </code></pre> <p>This returns <code>null</code>. I've tried both <code>'option'</code> and <code>'options'</code>. However, if I try:</p> <pre><code>get_field('thank_you_page', 'form-settings'); </code></pre> <p>I get the saved Page ID. What am I misunderstanding/doing wrong? Is it because it is an options sub page?</p> <p>I'm using Wordpress 4.9.8 and ACF Pro 5.7.7</p> <p>Thanks</p>
[ { "answer_id": 324917, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 3, "selected": true, "text": "<p>I just had the same problem. It's <strong><em>insanely</em></strong> poorly documented on <a href=\"https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/\" rel=\"nofollow noreferrer\">ACF's pages</a> (as in, not there at all). </p>\n\n<p>The core of your problem is, that you have spaces in your options-page names. And when you access it, using the 'ID', then you have to use the <code>'page_title'</code>, but where all spaces are replaced by underscores.</p>\n\n<p>Please note, that it's <strong><em>not</em></strong> all lowercase. It's written exactly as you've done it, but just replacing the spaces with underscores. </p>\n\n<hr>\n\n<h2>Working example:</h2>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>if( function_exists( 'acf_add_options_page' ) ){\n\n acf_add_options_page( array(\n 'page_title' =&gt; 'Some settings',\n 'menu_title' =&gt; 'Some settings',\n 'menu_slug' =&gt; 'some_settings',\n 'icon_url' =&gt; 'dashicons-admin-generic',\n 'capability' =&gt; 'edit_posts',\n 'redirect' =&gt; true,\n 'position' =&gt; '7.4',\n ) );\n\n acf_add_options_sub_page( array(\n 'page_title' =&gt; 'Acf page with spaces',\n 'menu_title' =&gt; 'Acf page with spaces',\n 'parent_slug' =&gt; 'acf_page_with_spaces',\n ) );\n\n} // endif\n</code></pre>\n\n<p>Where you want to access the fields (like <code>page.php</code> or <code>single.php</code>).</p>\n\n<pre><code>&lt;?php if( have_rows( 'Acf_page_with_spaces', 'option' ) ): ?&gt;\n &lt;?php\n while( have_rows( 'Acf_page_with_spaces', 'option' ) ):\n the_row();\n $foo = get_sub_field( 'foo' );\n $bar = get_sub_field( 'bar' );\n ?&gt;\n\n &lt;h1&gt;&lt;?php echo $foo; ?&gt;&lt;/h1&gt;\n &lt;p&gt;&lt;?php echo $bar; ?&gt;&lt;/p&gt;\n\n &lt;?php endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>There's something about this, that doesn't make any sense, - but that's how it works. </p>\n\n<hr>\n\n<h2>Extra note</h2>\n\n<p>This snippet helped me debugging this issue:</p>\n\n<pre><code>&lt;?php\necho '&lt;pre&gt;';\nprint_r(acf_get_options_pages());\necho '&lt;/pre&gt;';\n?&gt;\n</code></pre>\n\n<p>It prints all the registered options-pages. </p>\n" }, { "answer_id": 410027, "author": "Elly Post", "author_id": 74113, "author_profile": "https://wordpress.stackexchange.com/users/74113", "pm_score": 0, "selected": false, "text": "<p>Note that after struggling with a related issue for a long time, if you remove the <code>post_id</code> array parameter from the <code>acf_add_options_page</code> that will solve it by using default ACF options keys in the <code>wp_options</code> table. (You will need to resave your options on the admin edit options page for this to work, since the database keys will have changed.)</p>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39063/" ]
I'm using the Advanced Custom Fields plugin and I have created some options pages with: ``` if (function_exists('acf_add_options_page')) { website_settings_init(); } function website_settings_init() { $website_settings = acf_add_options_page(array( 'page_title' => 'Website Settings', 'menu_title' => 'Website Settings', 'menu-slug' => 'website-settings', 'post_id' => 'website-settings', 'redirect' => false )); $form_settings = acf_add_options_sub_page(array( 'page_title' => 'Form Settings', 'menu_title' => 'Form Settings', 'menu-slug' => 'form-settings', 'post_id' => 'form-settings', 'parent_slug' => $website_settings['menu_slug'] )); $contact_details = acf_add_options_sub_page(array( 'page_title' => 'Contact Details', 'menu_title' => 'Contact Details', 'menu-slug' => 'contact-details', 'post_id' => 'contact-details', 'parent_slug' => $website_settings['menu_slug'] )); } ``` I have a field group that is visible if Options Page = Form Settings. One of these fields is 'thank\_you\_page' which returns a Page ID. I read <https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/> which describes how you can get values from an options page field using `get_field('field_name', 'option');` I have tried: ``` get_field('thank_you_page', 'option'); ``` This returns `null`. I've tried both `'option'` and `'options'`. However, if I try: ``` get_field('thank_you_page', 'form-settings'); ``` I get the saved Page ID. What am I misunderstanding/doing wrong? Is it because it is an options sub page? I'm using Wordpress 4.9.8 and ACF Pro 5.7.7 Thanks
I just had the same problem. It's ***insanely*** poorly documented on [ACF's pages](https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/) (as in, not there at all). The core of your problem is, that you have spaces in your options-page names. And when you access it, using the 'ID', then you have to use the `'page_title'`, but where all spaces are replaced by underscores. Please note, that it's ***not*** all lowercase. It's written exactly as you've done it, but just replacing the spaces with underscores. --- Working example: ---------------- In `functions.php`: ``` if( function_exists( 'acf_add_options_page' ) ){ acf_add_options_page( array( 'page_title' => 'Some settings', 'menu_title' => 'Some settings', 'menu_slug' => 'some_settings', 'icon_url' => 'dashicons-admin-generic', 'capability' => 'edit_posts', 'redirect' => true, 'position' => '7.4', ) ); acf_add_options_sub_page( array( 'page_title' => 'Acf page with spaces', 'menu_title' => 'Acf page with spaces', 'parent_slug' => 'acf_page_with_spaces', ) ); } // endif ``` Where you want to access the fields (like `page.php` or `single.php`). ``` <?php if( have_rows( 'Acf_page_with_spaces', 'option' ) ): ?> <?php while( have_rows( 'Acf_page_with_spaces', 'option' ) ): the_row(); $foo = get_sub_field( 'foo' ); $bar = get_sub_field( 'bar' ); ?> <h1><?php echo $foo; ?></h1> <p><?php echo $bar; ?></p> <?php endwhile; ?> <?php endif; ?> ``` There's something about this, that doesn't make any sense, - but that's how it works. --- Extra note ---------- This snippet helped me debugging this issue: ``` <?php echo '<pre>'; print_r(acf_get_options_pages()); echo '</pre>'; ?> ``` It prints all the registered options-pages.
319,337
<p>The default web address for a domain is:</p> <pre><code>https://www.example.com </code></pre> <p>If I set this as the 'Site Address (URL)' in Wordpress then it seems to take care of the necessary http -> https and non-www -> www redirection on it's own.</p> <p>The problem is though is that Wordpress redirects the following first:</p> <pre><code>http://example.com to http://www.example.com </code></pre> <p>Before this one:</p> <pre><code>http://example.com to https://example.com </code></pre> <p>Which means that our <a href="https://www.globalsign.com/en/blog/what-is-hsts-and-how-do-i-use-it/" rel="nofollow noreferrer">HSTS</a> preload status and eligibility is failing which we check <a href="https://hstspreload.org" rel="nofollow noreferrer">here</a>.</p> <p>We are needing to ensure that the https redirect happens BEFORE the www redirect.</p> <hr> <p>I have no idea how best to do this but I would probably prefer some sort of theme function that hooks into the default functionality and modifies it accordingly.</p> <p>I did try setting the default site address to <code>http://example.com</code> and then handling the https and www redirect in the .htaccess but this doesn't seem ideal and can get messy (plus I could only get the https redirect to work and not the www redirect afterwards).</p> <p>Surely there must be plenty of other HSTS eligible Wordpress websites that use a default <code>https://www</code> start to the website?</p>
[ { "answer_id": 319338, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>Just do it in your .htaccess, it will be alot simpler. The important thing is that the rules are <strong>above</strong> WordPress' rules. Setting <strong>L</strong> also states, that this shall be the last rule evaluated if a match was found</p>\n\n<pre><code># Redirect to https\nRewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]\n\n# Redirect non-www to www\nRewriteCond %{HTTP_HOST} ^example\\.com [NC]\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n" }, { "answer_id": 319437, "author": "zigojacko", "author_id": 29524, "author_profile": "https://wordpress.stackexchange.com/users/29524", "pm_score": 0, "selected": false, "text": "<p>If anyone else is struggling to get their Wordpress website (as default address <a href=\"https://www\" rel=\"nofollow noreferrer\">https://www</a>) to pass the <a href=\"https://hstspreload.org\" rel=\"nofollow noreferrer\">HSTS preload</a> check for subdomains so you can submit your site to the browser preload list of sites, then I eventually managed to get this resolved by using <a href=\"https://wordpress.org/plugins/jsm-force-ssl/\" rel=\"nofollow noreferrer\">this plugin</a> that I referred to in <a href=\"https://wordpress.stackexchange.com/questions/319337/force-wordpress-https-redirect-before-www-redirect-based-on-site-address-url/319338?noredirect=1#comment471887_319338\">my answer above</a>. This handles all https redirection across Wordpress and does it well so Wordpress can't interfere with anything.</p>\n" }, { "answer_id": 388132, "author": "Chris", "author_id": 206347, "author_profile": "https://wordpress.stackexchange.com/users/206347", "pm_score": 1, "selected": false, "text": "<pre><code># Redirect to https\nRewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]\n\n# Redirect non-www to www\nRewriteCond %{HTTP_HOST} ^example\\.com [NC]\nRewriteRule (.*) https://www.example.com/$1 [R=301,L]\n</code></pre>\n<p>Just tried it and it worked fine. Just remember to also set Wordpress Address and Site Address in Wordpress. I think the infinite loops &quot;in above comments&quot; came from that.</p>\n<p>Always test the main url and then also one like example.com/about.html, as I have picked up sometimes that the root domain redirects well, but by having the pages added, it gives problems if redirects not done correctly.</p>\n<p>Feel free to reply on my comment.</p>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29524/" ]
The default web address for a domain is: ``` https://www.example.com ``` If I set this as the 'Site Address (URL)' in Wordpress then it seems to take care of the necessary http -> https and non-www -> www redirection on it's own. The problem is though is that Wordpress redirects the following first: ``` http://example.com to http://www.example.com ``` Before this one: ``` http://example.com to https://example.com ``` Which means that our [HSTS](https://www.globalsign.com/en/blog/what-is-hsts-and-how-do-i-use-it/) preload status and eligibility is failing which we check [here](https://hstspreload.org). We are needing to ensure that the https redirect happens BEFORE the www redirect. --- I have no idea how best to do this but I would probably prefer some sort of theme function that hooks into the default functionality and modifies it accordingly. I did try setting the default site address to `http://example.com` and then handling the https and www redirect in the .htaccess but this doesn't seem ideal and can get messy (plus I could only get the https redirect to work and not the www redirect afterwards). Surely there must be plenty of other HSTS eligible Wordpress websites that use a default `https://www` start to the website?
Just do it in your .htaccess, it will be alot simpler. The important thing is that the rules are **above** WordPress' rules. Setting **L** also states, that this shall be the last rule evaluated if a match was found ``` # Redirect to https RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] # Redirect non-www to www RewriteCond %{HTTP_HOST} ^example\.com [NC] RewriteRule (.*) https://www.example.com/$1 [R=301,L] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ```
319,346
<p>In WooCommerce admin settings (/wp-admin/admin.php?page=wc-settings) there are several fields to set the store address (street, city, country).</p> <p>How can one retrieve this in a theme's templates? I wouldn't want to hardcode such informations into the theme.</p>
[ { "answer_id": 319351, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 0, "selected": false, "text": "<p>There's not a specific function in WooCommerce to return shop (or other) URLs (at least that I know of). But there is a function <code>wc_get_page_id()</code> that will get the page ID by name, and the ID can be used in WP's <code>get_permalink()</code> function to return the URL.</p>\n\n<p>Here are some examples:</p>\n\n<p>Shop page URL:</p>\n\n<p><code>echo get_permalink( wc_get_page_id( 'shop' ) );</code></p>\n\n<p>Cart page URL:</p>\n\n<p><code>echo get_permalink( wc_get_page_id( 'cart' ) );</code></p>\n\n<p>Checkout page URL:</p>\n\n<p><code>echo get_permalink( wc_get_page_id( 'checkout' ) );</code></p>\n\n<p>My Account page URL:</p>\n\n<p><code>echo get_permalink( wc_get_page_id( 'myaccount' ) );</code></p>\n" }, { "answer_id": 319420, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 5, "selected": true, "text": "<p>The physical address of the store (and many other settings) are stored in WP's options table (wp_options where \"wp_\" is the table prefix being used on the site).</p>\n\n<p>The option names are:</p>\n\n<ul>\n<li>woocommerce_store_address</li>\n<li>woocommerce_store_address_2</li>\n<li>woocommerce_store_city</li>\n<li>woocommerce_store_postcode</li>\n<li>woocommerce_default_country</li>\n</ul>\n\n<p>The tricky thing is the woocommerce_default_country value. That stores the country AND state/province info depending on your selection in the \"Country/State\" dropdown selector in the settings. If it's just a country, it will be the country code, but if it's country \"plus\" something, it will be separated by a colon \":\" (such as \"US:IL\").</p>\n\n<p>So the following is a generic way of doing a US address. Other countries/provinces may vary slightly depending on (1) what's in the woocommerce_default_country value (which may be just a country alone) and (2) how you want to output the info.</p>\n\n<pre><code>// The main address pieces:\n$store_address = get_option( 'woocommerce_store_address' );\n$store_address_2 = get_option( 'woocommerce_store_address_2' );\n$store_city = get_option( 'woocommerce_store_city' );\n$store_postcode = get_option( 'woocommerce_store_postcode' );\n\n// The country/state\n$store_raw_country = get_option( 'woocommerce_default_country' );\n\n// Split the country/state\n$split_country = explode( \":\", $store_raw_country );\n\n// Country and state separated:\n$store_country = $split_country[0];\n$store_state = $split_country[1];\n\necho $store_address . \"&lt;br /&gt;\";\necho ( $store_address_2 ) ? $store_address_2 . \"&lt;br /&gt;\" : '';\necho $store_city . ', ' . $store_state . ' ' . $store_postcode . \"&lt;br /&gt;\";\necho $store_country;\n</code></pre>\n\n<p>This certainly could be condensed quite a bit and made neater, but I was verbose in the code for clarity.</p>\n\n<p>Also, depending on the store location, etc, you may or may not want to include the country/state info at all, or you may want to alter what it output based on the saved value. For example, in the case of US addresses, the country is \"US\", not \"USA\", and the state info is the abbreviated mail code (i.e. \"IL\" for Illinois). So the actual value and how you intend to use it will determine what you want to do with it for output. (Hope that makes sense.)</p>\n" }, { "answer_id": 334608, "author": "passatgt", "author_id": 8038, "author_profile": "https://wordpress.stackexchange.com/users/8038", "pm_score": 4, "selected": false, "text": "<p>Instead of the <code>get_option()</code> method mentioned above, it's much better to use the built-in functions via the main instance of WooCommerce <code>WC()</code>, thereby accessing the methods of the <a href=\"https://docs.woocommerce.com/wc-apidocs/class-WC_Countries.html\" rel=\"noreferrer\"><code>WC_Countries</code></a> class:</p>\n\n<pre><code>WC()-&gt;countries-&gt;get_base_address();\nWC()-&gt;countries-&gt;get_base_address_2();\nWC()-&gt;countries-&gt;get_base_city();\nWC()-&gt;countries-&gt;get_base_postcode();\nWC()-&gt;countries-&gt;get_base_state();\nWC()-&gt;countries-&gt;get_base_country();\n</code></pre>\n\n<p>For one, the place where the information is stored could change, but the method to get it stays the same. And secondly, in case a plugin changes the value using filters. Looking at the <a href=\"https://docs.woocommerce.com/wc-apidocs/source-class-WC_Countries.html#168-177\" rel=\"noreferrer\">source</a> the latter gets obvious:</p>\n\n<pre><code>public function get_base_address() {\n $base_address = get_option( 'woocommerce_store_address', '' );\n return apply_filters( 'woocommerce_countries_base_address', $base_address );\n}\n</code></pre>\n\n<p>Additional information: </p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/q/275905/22534\">What's the difference between <code>WC()</code> and <code>$woocommerce</code></a> </li>\n<li><a href=\"https://docs.woocommerce.com/document/class-reference/\" rel=\"noreferrer\">Classes in WooCommerce</a></li>\n</ul>\n" }, { "answer_id": 351664, "author": "Cédric Moris Kelly", "author_id": 177690, "author_profile": "https://wordpress.stackexchange.com/users/177690", "pm_score": 0, "selected": false, "text": "<p>To get the shop country full name :</p>\n\n<pre><code>WC()-&gt;countries-&gt;countries[WC()-&gt;countries-&gt;get_base_country()];\n</code></pre>\n" } ]
2018/11/15
[ "https://wordpress.stackexchange.com/questions/319346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77030/" ]
In WooCommerce admin settings (/wp-admin/admin.php?page=wc-settings) there are several fields to set the store address (street, city, country). How can one retrieve this in a theme's templates? I wouldn't want to hardcode such informations into the theme.
The physical address of the store (and many other settings) are stored in WP's options table (wp\_options where "wp\_" is the table prefix being used on the site). The option names are: * woocommerce\_store\_address * woocommerce\_store\_address\_2 * woocommerce\_store\_city * woocommerce\_store\_postcode * woocommerce\_default\_country The tricky thing is the woocommerce\_default\_country value. That stores the country AND state/province info depending on your selection in the "Country/State" dropdown selector in the settings. If it's just a country, it will be the country code, but if it's country "plus" something, it will be separated by a colon ":" (such as "US:IL"). So the following is a generic way of doing a US address. Other countries/provinces may vary slightly depending on (1) what's in the woocommerce\_default\_country value (which may be just a country alone) and (2) how you want to output the info. ``` // The main address pieces: $store_address = get_option( 'woocommerce_store_address' ); $store_address_2 = get_option( 'woocommerce_store_address_2' ); $store_city = get_option( 'woocommerce_store_city' ); $store_postcode = get_option( 'woocommerce_store_postcode' ); // The country/state $store_raw_country = get_option( 'woocommerce_default_country' ); // Split the country/state $split_country = explode( ":", $store_raw_country ); // Country and state separated: $store_country = $split_country[0]; $store_state = $split_country[1]; echo $store_address . "<br />"; echo ( $store_address_2 ) ? $store_address_2 . "<br />" : ''; echo $store_city . ', ' . $store_state . ' ' . $store_postcode . "<br />"; echo $store_country; ``` This certainly could be condensed quite a bit and made neater, but I was verbose in the code for clarity. Also, depending on the store location, etc, you may or may not want to include the country/state info at all, or you may want to alter what it output based on the saved value. For example, in the case of US addresses, the country is "US", not "USA", and the state info is the abbreviated mail code (i.e. "IL" for Illinois). So the actual value and how you intend to use it will determine what you want to do with it for output. (Hope that makes sense.)
319,373
<p>I have added this to my <code>functions.php</code> and need to use <code>ajaxURL</code> in all of enqueued scripts in the template (instead of enqueuing only one script here</p> <pre><code>add_action( 'wp_enqueue_scripts', 'ajaxify_enqueue_scripts' ); function ajaxify_enqueue_scripts() { wp_localize_script( 'ajaxify', 'ajaxURL', array('ajax_url' =&gt; get_template_directory_uri() . '/app/login.php' )); } add_action( 'wp_ajax_nopriv_set_ajaxify', 'set_ajaxify' ); add_action( 'wp_ajax_set_ajaxify', 'set_ajaxify' ); </code></pre> <p>but when I try to call an ajax method I am getting this error</p> <pre><code>Uncaught ReferenceError: ajaxURL is not defined </code></pre> <p>Is there any way to add the <code>ajaxURL</code> to all scripts?</p>
[ { "answer_id": 319374, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 1, "selected": false, "text": "<p>To have the ajaxurl variable available on the frontend the easiest way is to add this snippet to you theme’s function.php file:</p>\n\n<pre><code>add_action('wp_head', 'myplugin_ajaxurl');\nfunction myplugin_ajaxurl() {\n echo '&lt;script type=\"text/javascript\"&gt;\n var ajaxurl = \"' . admin_url('admin-ajax.php') . '\";\n &lt;/script&gt;';\n}\n</code></pre>\n\n<p>This get the url of the ajax submission page and creates a variable in the head of the HTML with it. Now ‘ajaxurl’ is available in your theme so you can start making it more modern and dynamic.</p>\n" }, { "answer_id": 319376, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 3, "selected": true, "text": "<p>You can conditionally echo the code on only few templates or specific pages. Here is an example:</p>\n\n<pre><code>add_action ( 'wp_head', 'my_js_variables' );\nfunction my_js_variables(){\n // for specific page templates\n $current_template = get_page_template();\n\n // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php\n if( !isset($current_template) || ( $current_template != 'template-x1.php' &amp;&amp; $current_template != 'template-x2.php' ) ){ return; } ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var ajaxurl = &lt;?php echo json_encode( admin_url( \"admin-ajax.php\" ) ); ?&gt;; \n var ajaxnonce = &lt;?php echo json_encode( wp_create_nonce( \"itr_ajax_nonce\" ) ); ?&gt;;\n var myarray = &lt;?php echo json_encode( array(\n 'foo' =&gt; 'bar',\n 'available' =&gt; TRUE,\n 'ship' =&gt; array( 1, 2, 3, ),\n ) ); ?&gt;\n &lt;/script&gt;\n&lt;?php\n}\n</code></pre>\n" } ]
2018/11/16
[ "https://wordpress.stackexchange.com/questions/319373", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31793/" ]
I have added this to my `functions.php` and need to use `ajaxURL` in all of enqueued scripts in the template (instead of enqueuing only one script here ``` add_action( 'wp_enqueue_scripts', 'ajaxify_enqueue_scripts' ); function ajaxify_enqueue_scripts() { wp_localize_script( 'ajaxify', 'ajaxURL', array('ajax_url' => get_template_directory_uri() . '/app/login.php' )); } add_action( 'wp_ajax_nopriv_set_ajaxify', 'set_ajaxify' ); add_action( 'wp_ajax_set_ajaxify', 'set_ajaxify' ); ``` but when I try to call an ajax method I am getting this error ``` Uncaught ReferenceError: ajaxURL is not defined ``` Is there any way to add the `ajaxURL` to all scripts?
You can conditionally echo the code on only few templates or specific pages. Here is an example: ``` add_action ( 'wp_head', 'my_js_variables' ); function my_js_variables(){ // for specific page templates $current_template = get_page_template(); // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){ return; } ?> <script type="text/javascript"> var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>; var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>; var myarray = <?php echo json_encode( array( 'foo' => 'bar', 'available' => TRUE, 'ship' => array( 1, 2, 3, ), ) ); ?> </script> <?php } ```
319,378
<p>In Woocommerce Category page default sort dropdown has like below options. <a href="https://i.stack.imgur.com/Qt6Yh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qt6Yh.png" alt="enter image description here"></a></p> <p>My question is what/how products sort by Popularity ? <strong>Not a code</strong> What is the <strong>measurement</strong> ? like if sort Price: Low to High,then we know those product sort Low price to High then How about <strong>Popularity</strong> ? </p>
[ { "answer_id": 319374, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 1, "selected": false, "text": "<p>To have the ajaxurl variable available on the frontend the easiest way is to add this snippet to you theme’s function.php file:</p>\n\n<pre><code>add_action('wp_head', 'myplugin_ajaxurl');\nfunction myplugin_ajaxurl() {\n echo '&lt;script type=\"text/javascript\"&gt;\n var ajaxurl = \"' . admin_url('admin-ajax.php') . '\";\n &lt;/script&gt;';\n}\n</code></pre>\n\n<p>This get the url of the ajax submission page and creates a variable in the head of the HTML with it. Now ‘ajaxurl’ is available in your theme so you can start making it more modern and dynamic.</p>\n" }, { "answer_id": 319376, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 3, "selected": true, "text": "<p>You can conditionally echo the code on only few templates or specific pages. Here is an example:</p>\n\n<pre><code>add_action ( 'wp_head', 'my_js_variables' );\nfunction my_js_variables(){\n // for specific page templates\n $current_template = get_page_template();\n\n // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php\n if( !isset($current_template) || ( $current_template != 'template-x1.php' &amp;&amp; $current_template != 'template-x2.php' ) ){ return; } ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var ajaxurl = &lt;?php echo json_encode( admin_url( \"admin-ajax.php\" ) ); ?&gt;; \n var ajaxnonce = &lt;?php echo json_encode( wp_create_nonce( \"itr_ajax_nonce\" ) ); ?&gt;;\n var myarray = &lt;?php echo json_encode( array(\n 'foo' =&gt; 'bar',\n 'available' =&gt; TRUE,\n 'ship' =&gt; array( 1, 2, 3, ),\n ) ); ?&gt;\n &lt;/script&gt;\n&lt;?php\n}\n</code></pre>\n" } ]
2018/11/16
[ "https://wordpress.stackexchange.com/questions/319378", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152021/" ]
In Woocommerce Category page default sort dropdown has like below options. [![enter image description here](https://i.stack.imgur.com/Qt6Yh.png)](https://i.stack.imgur.com/Qt6Yh.png) My question is what/how products sort by Popularity ? **Not a code** What is the **measurement** ? like if sort Price: Low to High,then we know those product sort Low price to High then How about **Popularity** ?
You can conditionally echo the code on only few templates or specific pages. Here is an example: ``` add_action ( 'wp_head', 'my_js_variables' ); function my_js_variables(){ // for specific page templates $current_template = get_page_template(); // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){ return; } ?> <script type="text/javascript"> var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>; var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>; var myarray = <?php echo json_encode( array( 'foo' => 'bar', 'available' => TRUE, 'ship' => array( 1, 2, 3, ), ) ); ?> </script> <?php } ```
319,416
<p>I have downloaded a theme and installed it. Here the theme has custom fields for limited numbers. For ex. <code>author_name</code>, <code>comments</code> but, I want all the wp_posts to be displayed.</p> <p>And prior to that, actually I have a database associated with this. So basically I want my piece of code to read the whole database and represent it in columns in my wordpress page. For ex. <code>author_name</code>, <code>ping_status</code>, <code>post_status</code> etc. </p> <p>So basically I want to write a function, that can access my database and pull the data from database and dump back in my wordpress page.</p> <p>I don't know if I put it in the right words, but please do help me get through this.</p>
[ { "answer_id": 319374, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 1, "selected": false, "text": "<p>To have the ajaxurl variable available on the frontend the easiest way is to add this snippet to you theme’s function.php file:</p>\n\n<pre><code>add_action('wp_head', 'myplugin_ajaxurl');\nfunction myplugin_ajaxurl() {\n echo '&lt;script type=\"text/javascript\"&gt;\n var ajaxurl = \"' . admin_url('admin-ajax.php') . '\";\n &lt;/script&gt;';\n}\n</code></pre>\n\n<p>This get the url of the ajax submission page and creates a variable in the head of the HTML with it. Now ‘ajaxurl’ is available in your theme so you can start making it more modern and dynamic.</p>\n" }, { "answer_id": 319376, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 3, "selected": true, "text": "<p>You can conditionally echo the code on only few templates or specific pages. Here is an example:</p>\n\n<pre><code>add_action ( 'wp_head', 'my_js_variables' );\nfunction my_js_variables(){\n // for specific page templates\n $current_template = get_page_template();\n\n // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php\n if( !isset($current_template) || ( $current_template != 'template-x1.php' &amp;&amp; $current_template != 'template-x2.php' ) ){ return; } ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var ajaxurl = &lt;?php echo json_encode( admin_url( \"admin-ajax.php\" ) ); ?&gt;; \n var ajaxnonce = &lt;?php echo json_encode( wp_create_nonce( \"itr_ajax_nonce\" ) ); ?&gt;;\n var myarray = &lt;?php echo json_encode( array(\n 'foo' =&gt; 'bar',\n 'available' =&gt; TRUE,\n 'ship' =&gt; array( 1, 2, 3, ),\n ) ); ?&gt;\n &lt;/script&gt;\n&lt;?php\n}\n</code></pre>\n" } ]
2018/11/16
[ "https://wordpress.stackexchange.com/questions/319416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154200/" ]
I have downloaded a theme and installed it. Here the theme has custom fields for limited numbers. For ex. `author_name`, `comments` but, I want all the wp\_posts to be displayed. And prior to that, actually I have a database associated with this. So basically I want my piece of code to read the whole database and represent it in columns in my wordpress page. For ex. `author_name`, `ping_status`, `post_status` etc. So basically I want to write a function, that can access my database and pull the data from database and dump back in my wordpress page. I don't know if I put it in the right words, but please do help me get through this.
You can conditionally echo the code on only few templates or specific pages. Here is an example: ``` add_action ( 'wp_head', 'my_js_variables' ); function my_js_variables(){ // for specific page templates $current_template = get_page_template(); // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){ return; } ?> <script type="text/javascript"> var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>; var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>; var myarray = <?php echo json_encode( array( 'foo' => 'bar', 'available' => TRUE, 'ship' => array( 1, 2, 3, ), ) ); ?> </script> <?php } ```
319,428
<p>I am trying to make a page that queries every post of a specific category ("attractions").</p> <p>I have been able to get the posts successfully, I just need to make the modals work. </p> <p>I have made a button inside of my loop which has the title of whatever post the loop is on. I want it so whenever people click on that button, it opens a modal that displays all of the fields from ACF I list in the code.</p> <p>I am having some issues, though. For some reason I can't get the javascript to work. Right now it's all in the page template file, but I have tried enqueuing the script through the functions.php etc. </p> <p>My guess is that I am trying to do documents.getElementsByClassName instead of documents.getElementById. I want to use id, but since the loop is what is creating the buttons, I dont know how to make the ids unique. I am thinking something along the lines of making the id the counter of the loop or something, and then storing it in a variable I can reference in the script so I can do getElementsById($someVariable)</p> <p>Thanks for taking a look! </p> <pre><code>&lt;?php get_header(); $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'category_name' =&gt; 'attractions', 'posts_per_page' =&gt; 10, ); $arr_posts = new WP_Query( $args ); if ( $arr_posts-&gt;have_posts() ) : while ( $arr_posts-&gt;have_posts() ) : $arr_posts-&gt;the_post(); get_posts($args); //vars below ?&gt; &lt;div class=attractions-wrap&gt; &lt;button class="openAttractions"&gt;&lt;?php the_title(); ?&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="attractionsModal"&gt; &lt;div class=modal-content&gt; &lt;span class="close"&gt;&amp;times;&lt;/span&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;div id="attraction-descrption" class="description"&gt; &lt;h3&gt;Description&lt;/h2&gt; &lt;p&gt;&lt;?php the_field('description_field'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id="attraction-opening-hours" class="opening-hours"&gt; &lt;h3&gt;Opening Hours&lt;/h2&gt; &lt;p&gt;&lt;?php the_field('opening_hours_field'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id="attraction-practical-information" class="practical-information"&gt; &lt;h3&gt;Practical Information&lt;/h2&gt; &lt;p&gt;&lt;?php the_field('practical_information_field'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;script type="text/javascript"&gt; // Get the modal var modal = document.getElementsByClassName('attractionsModal'); // Get the button that opens the modal var btn = document.getElementsByClassName("openAttractions"); // Get the &lt;span&gt; element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on &lt;span&gt; (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } &lt;/script&gt; </code></pre>
[ { "answer_id": 319374, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 1, "selected": false, "text": "<p>To have the ajaxurl variable available on the frontend the easiest way is to add this snippet to you theme’s function.php file:</p>\n\n<pre><code>add_action('wp_head', 'myplugin_ajaxurl');\nfunction myplugin_ajaxurl() {\n echo '&lt;script type=\"text/javascript\"&gt;\n var ajaxurl = \"' . admin_url('admin-ajax.php') . '\";\n &lt;/script&gt;';\n}\n</code></pre>\n\n<p>This get the url of the ajax submission page and creates a variable in the head of the HTML with it. Now ‘ajaxurl’ is available in your theme so you can start making it more modern and dynamic.</p>\n" }, { "answer_id": 319376, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 3, "selected": true, "text": "<p>You can conditionally echo the code on only few templates or specific pages. Here is an example:</p>\n\n<pre><code>add_action ( 'wp_head', 'my_js_variables' );\nfunction my_js_variables(){\n // for specific page templates\n $current_template = get_page_template();\n\n // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php\n if( !isset($current_template) || ( $current_template != 'template-x1.php' &amp;&amp; $current_template != 'template-x2.php' ) ){ return; } ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var ajaxurl = &lt;?php echo json_encode( admin_url( \"admin-ajax.php\" ) ); ?&gt;; \n var ajaxnonce = &lt;?php echo json_encode( wp_create_nonce( \"itr_ajax_nonce\" ) ); ?&gt;;\n var myarray = &lt;?php echo json_encode( array(\n 'foo' =&gt; 'bar',\n 'available' =&gt; TRUE,\n 'ship' =&gt; array( 1, 2, 3, ),\n ) ); ?&gt;\n &lt;/script&gt;\n&lt;?php\n}\n</code></pre>\n" } ]
2018/11/16
[ "https://wordpress.stackexchange.com/questions/319428", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153268/" ]
I am trying to make a page that queries every post of a specific category ("attractions"). I have been able to get the posts successfully, I just need to make the modals work. I have made a button inside of my loop which has the title of whatever post the loop is on. I want it so whenever people click on that button, it opens a modal that displays all of the fields from ACF I list in the code. I am having some issues, though. For some reason I can't get the javascript to work. Right now it's all in the page template file, but I have tried enqueuing the script through the functions.php etc. My guess is that I am trying to do documents.getElementsByClassName instead of documents.getElementById. I want to use id, but since the loop is what is creating the buttons, I dont know how to make the ids unique. I am thinking something along the lines of making the id the counter of the loop or something, and then storing it in a variable I can reference in the script so I can do getElementsById($someVariable) Thanks for taking a look! ``` <?php get_header(); $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category_name' => 'attractions', 'posts_per_page' => 10, ); $arr_posts = new WP_Query( $args ); if ( $arr_posts->have_posts() ) : while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); get_posts($args); //vars below ?> <div class=attractions-wrap> <button class="openAttractions"><?php the_title(); ?></button> </div> <div class="attractionsModal"> <div class=modal-content> <span class="close">&times;</span> <h2><?php the_title(); ?></h2> <div id="attraction-descrption" class="description"> <h3>Description</h2> <p><?php the_field('description_field'); ?></p> </div> <div id="attraction-opening-hours" class="opening-hours"> <h3>Opening Hours</h2> <p><?php the_field('opening_hours_field'); ?></p> </div> <div id="attraction-practical-information" class="practical-information"> <h3>Practical Information</h2> <p><?php the_field('practical_information_field'); ?></p> </div> </div> </div> <?php endwhile; endif; ?> <script type="text/javascript"> // Get the modal var modal = document.getElementsByClassName('attractionsModal'); // Get the button that opens the modal var btn = document.getElementsByClassName("openAttractions"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> ```
You can conditionally echo the code on only few templates or specific pages. Here is an example: ``` add_action ( 'wp_head', 'my_js_variables' ); function my_js_variables(){ // for specific page templates $current_template = get_page_template(); // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){ return; } ?> <script type="text/javascript"> var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>; var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>; var myarray = <?php echo json_encode( array( 'foo' => 'bar', 'available' => TRUE, 'ship' => array( 1, 2, 3, ), ) ); ?> </script> <?php } ```
319,448
<p>I want to add a sentence at the beginning of all posts of content directly into the post_content WordPress database. How do I? Either through the <code>function.php</code> or the MySQL command.</p>
[ { "answer_id": 319449, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>Rather than insert it directly into the db, why don't you add it to the content when displayed using <code>the_content</code> filter? That way, you don't make any db changes you might want to undo later.</p>\n\n<pre><code>add_filter( 'the_content', 'my_extra_line' );\nfunction my_extra_line( $content ) {\n\n if ( \"post\" == get_post_type() ) {\n // If the content is a post, add an extra line to the content.\n $content = \"My extra line of content. \" . $content;\n }\n\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 319572, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<p>I'd go for solution posted by @butlerblog - it's a lot easier to manage and change in the future and it's better WP practice. </p>\n\n<p>But... If you're asking... Here are the ways you can do this:</p>\n\n<h2>1. WP way:</h2>\n\n<pre><code>function prepend_content_to_posts() {\n $to_prepend = 'This will be prepended';\n\n $posts = get_posts( array( 'posts_per_page' =&gt; -1 ) );\n foreach ( $posts as $post ) {\n wp_update_post( array(\n 'ID' =&gt; $post-&gt;ID,\n 'post_content' =&gt; $to_prepend . $post-&gt;post_content\n ) );\n }\n}\n</code></pre>\n\n<p>Then you'll have to call that function. Be careful not to call it twice - it will add your content twice in such case.</p>\n\n<h2>2. MySQL way:</h2>\n\n<pre><code>UPDATE wp_posts\n SET post_content = CONCAT('&lt;YOUR STRING TO PREPEND&gt;', post_content) \n WHERE post_type = 'post' AND post_status = 'publish'\n</code></pre>\n\n<p>Be careful to change table prefix according to your config.</p>\n" } ]
2018/11/16
[ "https://wordpress.stackexchange.com/questions/319448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154216/" ]
I want to add a sentence at the beginning of all posts of content directly into the post\_content WordPress database. How do I? Either through the `function.php` or the MySQL command.
I'd go for solution posted by @butlerblog - it's a lot easier to manage and change in the future and it's better WP practice. But... If you're asking... Here are the ways you can do this: 1. WP way: ---------- ``` function prepend_content_to_posts() { $to_prepend = 'This will be prepended'; $posts = get_posts( array( 'posts_per_page' => -1 ) ); foreach ( $posts as $post ) { wp_update_post( array( 'ID' => $post->ID, 'post_content' => $to_prepend . $post->post_content ) ); } } ``` Then you'll have to call that function. Be careful not to call it twice - it will add your content twice in such case. 2. MySQL way: ------------- ``` UPDATE wp_posts SET post_content = CONCAT('<YOUR STRING TO PREPEND>', post_content) WHERE post_type = 'post' AND post_status = 'publish' ``` Be careful to change table prefix according to your config.
319,474
<p>I'm working on a client's build, and I'd like to change as little as possible. I'm not too familiar with all this, my apologies - I'll try to show where I'm at.</p> <p>The client wants a form submission to prompt a PDF download. There are two different PDFs, two instances of the same form. Fill out form instance 1, get PDF A - Form instance 2, PDF B.</p> <p>Here's how those instances show up:</p> <pre><code>&lt;div id="whitepaper" class="home_whitepaper_bg w-clearfix"&gt; &lt;?php $lpcnt=0; if(have_rows('whitepaper_list')): ?&gt; &lt;?php while(have_rows('whitepaper_list')): the_row(); $lpcnt++; ?&gt; &lt;!-- Making rows for content, looping through and counting loops = lpcnt --&gt; &lt;!-- ... Other content ... --&gt; &lt;?php the_sub_field('whitepaper_download_form'); ?&gt; &lt;?php $pdf=get_permalink().'?download='.get_sub_field('whitepaper_pdf'); ?&gt; &lt;a data-fancybox data-src="#whitepaper_popup_&lt;?php echo $lpcnt; ?&gt;" data-redirect="&lt;?php echo $pdf; ?&gt;" href="javascript:;" class="whitepaper_download_link w-inline-block w-clearfix"&gt; &lt;!-- Here's the buttons for fancybox popups. They use the loop count to build a specific url - this is info I want later! --&gt; </code></pre> <p>And in the popup window:</p> <pre><code> &lt;div id="whitepaper_popup_&lt;?php echo $lpcnt; ?&gt;" class="whitepaper_popup"&gt; &lt;!-- using that loop count to get a specific div id! --&gt; &lt;div class="popup_whitepaper"&gt; &lt;div class="whitepaper_form"&gt; &lt;!-- I could put a &lt;?php echo do_shortcode...&gt; here, no? Their current solution is to grab a javascript code from an ACF field. I have had a lot of trouble figuring out how to put the CF7 form in that field. --&gt; &lt;?php the_sub_field('download_form'); ?&gt; &lt;div class="w-clearfix"&gt;&lt;/div&gt; &lt;/div&gt; &lt;button data-fancybox-close="" class="fancybox-close-small"&gt;&lt;/button&gt; &lt;div class="w-clearfix"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Right. So there's that. Then, using CF7's new DOM events, I should be able to setup a redirect or simliar?</p> <p>in functions.php:</p> <pre><code>add_action( 'wp_footer', 'mycustom_wp_footer' ); function mycustom_wp_footer() { ?&gt; &lt;script type="text/javascript"&gt; document.addEventListener( 'wpcf7mailsent', function( event ) { if ( 'FORM ID' == event.detail.contactFormId ) { location = &lt;!-- specific url derived from $lpcnt? --&gt;; } }, false ); &lt;/script&gt; &lt;?php } </code></pre> <p>I'm not sure if I'm on the right track or not - also, can't figure out exactly how I can get the right URL into my wpcf7mailsent event listener.</p>
[ { "answer_id": 319627, "author": "Parth Shah", "author_id": 154328, "author_profile": "https://wordpress.stackexchange.com/users/154328", "pm_score": 1, "selected": true, "text": "<p>You don't need much code for it. just goto contact form > select contact form > additional setting, paste below code.<br>\n<code>document.addEventListener( 'wpcf7mailsent', function( event ) {\nlocation = 'YOUR_PDF_URL';}, false );\n</code></p>\n" }, { "answer_id": 369781, "author": "Maxime Culea", "author_id": 68415, "author_profile": "https://wordpress.stackexchange.com/users/68415", "pm_score": 1, "selected": false, "text": "<p>I had the need to add a download CTA after the content of all case studies of a website, but &quot;in exchange&quot; of user's data for:</p>\n<ul>\n<li>display a CF7 form on your page, I had the same one on all case studies post type single which I hooked after the content</li>\n<li>find a way to get the wanted PDF url for people to download, as for me all case studies have a different PDF, I simply added an ACF field, filtered on PDF only, which returns the file url</li>\n<li>based on <a href=\"https://contactform7.com/dom-events/\" rel=\"nofollow noreferrer\">CF7 Dom events</a>, choose the action you prefer to make the dowload happens, as I am not sending any confirmation email, I prefer working on the wpcf7submit event. Note that wpcf7submit event is fired only if the form has been validated</li>\n</ul>\n<p>So the code looks like this:</p>\n<pre><code>&lt;?php \n// For simplicity, using an anonymous functions\nadd_action( 'wp_print_footer_scripts', function () {\n // Check the wanted singular post type loading\n if ( is_admin() || ! is_singular( 'case-study' ) ) {\n return;\n }\n\n // Check if the ACF PDF field is not empty for use\n $pdf_link = get_field( 'pdf' );\n if ( empty( $pdf_link ) ) {\n return;\n }\n\n // Hook on the &quot;wpcf7submit&quot; CF7 Dom event to force the download\n printf( &quot;&lt;script&gt;document.addEventListener( 'wpcf7submit', function( event ) { window.open('%s'); }, false );&lt;/script&gt;&quot;, $pdf_link );\n} );\n</code></pre>\n" }, { "answer_id": 374916, "author": "Semir", "author_id": 194703, "author_profile": "https://wordpress.stackexchange.com/users/194703", "pm_score": 1, "selected": false, "text": "<p>Try this plugin:</p>\n<ol>\n<li>Download the plugin</li>\n<li>Install</li>\n<li>Set the form id and PDF attachment under CF7 file download settings.</li>\n</ol>\n<p><a href=\"https://wordpress.org/plugins/cf7-file-download/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/cf7-file-download/</a></p>\n" } ]
2018/11/17
[ "https://wordpress.stackexchange.com/questions/319474", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154223/" ]
I'm working on a client's build, and I'd like to change as little as possible. I'm not too familiar with all this, my apologies - I'll try to show where I'm at. The client wants a form submission to prompt a PDF download. There are two different PDFs, two instances of the same form. Fill out form instance 1, get PDF A - Form instance 2, PDF B. Here's how those instances show up: ``` <div id="whitepaper" class="home_whitepaper_bg w-clearfix"> <?php $lpcnt=0; if(have_rows('whitepaper_list')): ?> <?php while(have_rows('whitepaper_list')): the_row(); $lpcnt++; ?> <!-- Making rows for content, looping through and counting loops = lpcnt --> <!-- ... Other content ... --> <?php the_sub_field('whitepaper_download_form'); ?> <?php $pdf=get_permalink().'?download='.get_sub_field('whitepaper_pdf'); ?> <a data-fancybox data-src="#whitepaper_popup_<?php echo $lpcnt; ?>" data-redirect="<?php echo $pdf; ?>" href="javascript:;" class="whitepaper_download_link w-inline-block w-clearfix"> <!-- Here's the buttons for fancybox popups. They use the loop count to build a specific url - this is info I want later! --> ``` And in the popup window: ``` <div id="whitepaper_popup_<?php echo $lpcnt; ?>" class="whitepaper_popup"> <!-- using that loop count to get a specific div id! --> <div class="popup_whitepaper"> <div class="whitepaper_form"> <!-- I could put a <?php echo do_shortcode...> here, no? Their current solution is to grab a javascript code from an ACF field. I have had a lot of trouble figuring out how to put the CF7 form in that field. --> <?php the_sub_field('download_form'); ?> <div class="w-clearfix"></div> </div> <button data-fancybox-close="" class="fancybox-close-small"></button> <div class="w-clearfix"></div> </div> </div> ``` Right. So there's that. Then, using CF7's new DOM events, I should be able to setup a redirect or simliar? in functions.php: ``` add_action( 'wp_footer', 'mycustom_wp_footer' ); function mycustom_wp_footer() { ?> <script type="text/javascript"> document.addEventListener( 'wpcf7mailsent', function( event ) { if ( 'FORM ID' == event.detail.contactFormId ) { location = <!-- specific url derived from $lpcnt? -->; } }, false ); </script> <?php } ``` I'm not sure if I'm on the right track or not - also, can't figure out exactly how I can get the right URL into my wpcf7mailsent event listener.
You don't need much code for it. just goto contact form > select contact form > additional setting, paste below code. `document.addEventListener( 'wpcf7mailsent', function( event ) { location = 'YOUR_PDF_URL';}, false );`
319,485
<p>I am creating a custom theme with my own HTML. I am trying to override woocommerce template. I have created a template named with <code>woocommerce.php</code> but it still shows template with default structure.</p> <p>I checked the system status and it says that <code>Your theme has a woocommerce.php file, you will not be able to override the woocommerce/archive-product.php custom template since woocommerce.php has priority over archive-product.php. This is intended to prevent display issues.</code></p> <p>But when I load the <code>shop page</code> it opens up with default structure. </p> <p>Some screenshots</p> <ol> <li><a href="https://prnt.sc/ljfqge" rel="nofollow noreferrer">Folder Structure</a></li> <li><a href="https://prnt.sc/ljfqzi" rel="nofollow noreferrer">WooCommerece system status</a></li> <li><a href="https://prnt.sc/ljfrn5" rel="nofollow noreferrer">woocommerece.php</a></li> </ol>
[ { "answer_id": 319683, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": false, "text": "<p>It's a custom theme, so first of all you should check if WooCommerce support is declared in the <code>functions.php</code>. </p>\n\n<p>WooCommerce can be integrated with the theme by using <code>woocommerce_content()</code> (<code>woocommerce.php</code> file) or by template overrides, but in both cases the declaration of support in the theme is required.</p>\n\n<pre><code>function wpse319485_add_woocommerce_support() {\n add_theme_support( 'woocommerce' );\n}\nadd_action( 'after_setup_theme', 'wpse319485_add_woocommerce_support' );\n</code></pre>\n" }, { "answer_id": 324699, "author": "Sanjay Goswami", "author_id": 53934, "author_profile": "https://wordpress.stackexchange.com/users/53934", "pm_score": 3, "selected": true, "text": "<p>I fix that by disabling Woocommerce template debug mode in config.php.</p>\n<pre><code>define( 'WC_TEMPLATE_DEBUG_MODE', false );\n</code></pre>\n<p>You can check if the template debug mode is set via:</p>\n<p>WP Dashboard -&gt; WooCommerce -&gt; System Status -&gt; Tools</p>\n" } ]
2018/11/17
[ "https://wordpress.stackexchange.com/questions/319485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/53934/" ]
I am creating a custom theme with my own HTML. I am trying to override woocommerce template. I have created a template named with `woocommerce.php` but it still shows template with default structure. I checked the system status and it says that `Your theme has a woocommerce.php file, you will not be able to override the woocommerce/archive-product.php custom template since woocommerce.php has priority over archive-product.php. This is intended to prevent display issues.` But when I load the `shop page` it opens up with default structure. Some screenshots 1. [Folder Structure](https://prnt.sc/ljfqge) 2. [WooCommerece system status](https://prnt.sc/ljfqzi) 3. [woocommerece.php](https://prnt.sc/ljfrn5)
I fix that by disabling Woocommerce template debug mode in config.php. ``` define( 'WC_TEMPLATE_DEBUG_MODE', false ); ``` You can check if the template debug mode is set via: WP Dashboard -> WooCommerce -> System Status -> Tools
319,494
<p>hy all, I have streaming site, and want to make a toggle button to switch to Dark/light mode using jQuery. please look to my code, what is wrong with my code, bcz this is not work for me.</p> <p>in footer.php (above &lt;/body>)</p> <pre><code>&lt;div class="gelap-terang"&gt;&lt;/div&gt; &lt;script&gt; jQuery.noConflict(); jQuery(document).ready(function(){ jQuery(".gelap-terang").hide(); jQuery("#gelap-terang").click(function(){ jQuery(".gelap-terang").toggle(); }); }); &lt;/script&gt; </code></pre> <p>in player.php</p> <pre><code>... &lt;div class="player_nav"&gt; &lt;button id="gelap-terang"&gt;Change Mode&lt;/button&gt; &lt;/div&gt; ... </code></pre> <p>CSS code</p> <pre><code>.gelap-terang { height:100%; width:100%; background-color:black; opacity:.8; position:fixed; top:0;left:0; z-index:1;display:none;} #player2, .player_nav { z-index:99; position:relative;} </code></pre> <p>the button is perfect look in the below of player video, but the <strong>&lt;div class="gelap-terang"></strong> is not appear when I click the button. I tried to delete the "display:none;" in the .gelap-terang CSS code, the <strong>&lt;div class="gelap-terang"></strong> is appear and look good, but not switch (hide) when I click the button.</p>
[ { "answer_id": 319497, "author": "BlesssMe", "author_id": 154241, "author_profile": "https://wordpress.stackexchange.com/users/154241", "pm_score": -1, "selected": false, "text": "<p>I found this Solution <a href=\"https://stackoverflow.com/questions/33212905/custom-jquery-is-not-working-in-wordpress\">https://stackoverflow.com/questions/33212905/custom-jquery-is-not-working-in-wordpress</a>\nI tried to put </p>\n\n<blockquote>\n <p>&lt;?php wp_enqueue_script(\"jquery\"); ?></p>\n</blockquote>\n\n<p><strong>EDIT:</strong> into <strong>function.php</strong> and deleted <strong>jQuery.noConflict ();</strong> from my jQuery code</p>\n\n<p>it's works fine now</p>\n" }, { "answer_id": 319517, "author": "Manjot", "author_id": 86449, "author_profile": "https://wordpress.stackexchange.com/users/86449", "pm_score": 2, "selected": true, "text": "<p>error is coming because of jQuery.noConflict();<br>\nYou do not need to add jQuery.noConflict(); in wordpress files because by default wordpress supports jQuery but if you want to use $ then you can use this way without using wp_enqueue_script(\"jquery\")</p>\n\n<p>If the script is being loaded in the footer (which you should be doing in the vast majority of cases) you can wrap the code in an anonymous function (technically any IIFE) where you pass in jQuery to be mapped to $.</p>\n\n<pre><code> (function($) {\n\n // $ Works! You can test it with next line if you like\n // console.log($);\n\n })( jQuery );\n</code></pre>\n\n<p>If you absolutely need to load the scripts in the header, you'll probably need to use a document ready function anyway, so you can just pass in $ there.</p>\n\n<pre><code> jQuery(document).ready(function( $ ) {\n\n // $ Works! You can test it with next line if you like\n // console.log($);\n\n }); \n</code></pre>\n" } ]
2018/11/17
[ "https://wordpress.stackexchange.com/questions/319494", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154241/" ]
hy all, I have streaming site, and want to make a toggle button to switch to Dark/light mode using jQuery. please look to my code, what is wrong with my code, bcz this is not work for me. in footer.php (above </body>) ``` <div class="gelap-terang"></div> <script> jQuery.noConflict(); jQuery(document).ready(function(){ jQuery(".gelap-terang").hide(); jQuery("#gelap-terang").click(function(){ jQuery(".gelap-terang").toggle(); }); }); </script> ``` in player.php ``` ... <div class="player_nav"> <button id="gelap-terang">Change Mode</button> </div> ... ``` CSS code ``` .gelap-terang { height:100%; width:100%; background-color:black; opacity:.8; position:fixed; top:0;left:0; z-index:1;display:none;} #player2, .player_nav { z-index:99; position:relative;} ``` the button is perfect look in the below of player video, but the **<div class="gelap-terang">** is not appear when I click the button. I tried to delete the "display:none;" in the .gelap-terang CSS code, the **<div class="gelap-terang">** is appear and look good, but not switch (hide) when I click the button.
error is coming because of jQuery.noConflict(); You do not need to add jQuery.noConflict(); in wordpress files because by default wordpress supports jQuery but if you want to use $ then you can use this way without using wp\_enqueue\_script("jquery") If the script is being loaded in the footer (which you should be doing in the vast majority of cases) you can wrap the code in an anonymous function (technically any IIFE) where you pass in jQuery to be mapped to $. ``` (function($) { // $ Works! You can test it with next line if you like // console.log($); })( jQuery ); ``` If you absolutely need to load the scripts in the header, you'll probably need to use a document ready function anyway, so you can just pass in $ there. ``` jQuery(document).ready(function( $ ) { // $ Works! You can test it with next line if you like // console.log($); }); ```
319,495
<p>I suddenly can't access <code>company.co.za/wp-admin</code>, as it redirects to</p> <pre><code>http://company.co.za/wp-login.php?redirect_to=http%3A%2F%company.co.za%2Fwp-admin%2F&amp;reauth=1 </code></pre> <p>with error 500</p> <p>What should I do to resolve this?</p> <p>I know I can try disabling all plugins, but how do I do that without loggin into wp dashboard? Is there some other step I should take?</p> <p>Thank you</p>
[ { "answer_id": 319523, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>500 errors are hard to diagnose; they are sort of generic. Sometimes the access logs will give you hints. And they are not consistent - they come and go sometimes.</p>\n\n<p>I'd temporarily rename the plugins folder to disable them, then look at the site. If the problem does not reoccur, then put the plugin folders back one-two at a time to identify.</p>\n\n<p>If possible, also change to one of the 'twenty' themes temporarily. And, check with your hosting support to see if they have ideas that are specific to your site.</p>\n" }, { "answer_id": 320351, "author": "Frank D", "author_id": 154814, "author_profile": "https://wordpress.stackexchange.com/users/154814", "pm_score": 1, "selected": false, "text": "<p>Did you just add a plugin or change a theme? if you cannot access anything, go to phpmyadmin through the cpanel through your hosting provider.</p>\n<ol>\n<li>Find your wp database.</li>\n<li>Go to <code>wp_options</code> table.</li>\n<li>If you changed plugins, run the SQL: UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';</li>\n</ol>\n<p>-or-</p>\n<p>Find Option_name 'active_plugins' and remove the plugin from the code. Each plugin will start with 0;#; I typically copy and paste this whole thing into notepad in case it is not the plugin that does it.</p>\n<p><a href=\"https://i.stack.imgur.com/91g3V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/91g3V.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/wNeD6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wNeD6.png\" alt=\"enter image description here\" /></a></p>\n<p>*** If you changed themes ***\n3) Find Option_name 'template' and change the value to the name of the theme you had it before\n4) Find Option_name 'Stylesheet' and change the value to the name of theme (typically a theme will have the same name stylesheet)\n<a href=\"https://i.stack.imgur.com/QFc4P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QFc4P.png\" alt=\"enter image description here\" /></a></p>\n<p>hope that helps!</p>\n" }, { "answer_id": 324224, "author": "Neelima Naidu", "author_id": 157972, "author_profile": "https://wordpress.stackexchange.com/users/157972", "pm_score": 3, "selected": true, "text": "<p>There are so many for internal server error. The main reasons for internal server errors are.</p>\n\n<ol>\n<li>Corrupt .htaccess file</li>\n<li>PHP Memory limit</li>\n<li>Corrupted plugin</li>\n<li>Incompatible PHP version</li>\n<li>Corrupted core files</li>\n</ol>\n\n<p>In oder to fix this issue, you need to investigate in step by step order.</p>\n\n<p>To solve this issue first of all you need to enable Debug mode and check the issue. after that try with restoring .htacess file, enabling default theme, disabling plugins etc.</p>\n\n<p>if you still facing 500 internal server issue, check the tutorial on wpera --> <a href=\"https://www.wpera.net/500-internal-server-error/\" rel=\"nofollow noreferrer\"><a href=\"https://www.wpera.net/500-internal-server-error/\" rel=\"nofollow noreferrer\">https://www.wpera.net/500-internal-server-error/</a></a></p>\n" }, { "answer_id": 332359, "author": "TomC", "author_id": 36980, "author_profile": "https://wordpress.stackexchange.com/users/36980", "pm_score": 1, "selected": false, "text": "<p>I've had this a few times and think it was caused by Wordpress auto updates. My fix is to FTP in to the site and rename the <code>plugins</code> folder to <code>plugins.old</code> or something similar then access the dashboard, check that you're running the latest version of Wordpress, one site told me I was running an old insecure version of PHP(5) and so I upgraded to 7.2 and then renamed the <code>plugins</code> folder back to normal and everything works fine again.</p>\n" }, { "answer_id": 391292, "author": "Mike Pluginstore", "author_id": 208466, "author_profile": "https://wordpress.stackexchange.com/users/208466", "pm_score": 0, "selected": false, "text": "<p>Simple fix --- download a copy of the latest WordPress (wordpress.org)\nOpen the downloaded wp zip-file and drag only the includes folder to your desktop.</p>\n<p>zip that new includes folder then upload it to replace the old (renamed Includes folder)</p>\n<p>Final step - Login and delete the old includes folder.</p>\n<p>You may now log in to your admin account.</p>\n" } ]
2018/11/17
[ "https://wordpress.stackexchange.com/questions/319495", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120533/" ]
I suddenly can't access `company.co.za/wp-admin`, as it redirects to ``` http://company.co.za/wp-login.php?redirect_to=http%3A%2F%company.co.za%2Fwp-admin%2F&reauth=1 ``` with error 500 What should I do to resolve this? I know I can try disabling all plugins, but how do I do that without loggin into wp dashboard? Is there some other step I should take? Thank you
There are so many for internal server error. The main reasons for internal server errors are. 1. Corrupt .htaccess file 2. PHP Memory limit 3. Corrupted plugin 4. Incompatible PHP version 5. Corrupted core files In oder to fix this issue, you need to investigate in step by step order. To solve this issue first of all you need to enable Debug mode and check the issue. after that try with restoring .htacess file, enabling default theme, disabling plugins etc. if you still facing 500 internal server issue, check the tutorial on wpera --> [<https://www.wpera.net/500-internal-server-error/>](https://www.wpera.net/500-internal-server-error/)
319,550
<p>I have written my custom <code>WP_Query</code> and using loop to display post content. I use <code>get_the_category()</code> to display categories of current post and it works fine. Now for some post types there are custom taxonomies instead of categories. </p> <p><strong>Code to get categories</strong>:</p> <pre><code>$categories = get_the_category(); if(!empty($categories)){ foreach($categories as $index =&gt; $cat){ echo $cat-&gt;name; } } </code></pre> <p>Now I need to pull all taxonomies and print them in comma separated format.</p> <p>I tried this:</p> <pre><code>$taxonomies = get_the_taxonomies(); if(!empty($taxonomies)){ foreach($taxonomies as $taxonomy){ echo $taxonomy; } } </code></pre> <p>It works and shows in this format "Taxonomy Label: Term (hyperlinked)". If the terms are more than one than it adds "and" between terms. I need only terms and if they are multiple then they should be separated by comma.</p> <p>I <strong>want to know</strong>:</p> <ol> <li>The best approach to achieve those results</li> <li>Is it recommended to to use above method?</li> <li>Can I use <code>regex</code> to extract value?</li> <li>How can I get rid off hyperlink?</li> </ol> <p>Thanks</p>
[ { "answer_id": 319551, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>Take a look at these:</p>\n\n<pre><code>$taxonomies = get_post_taxonomies( );\nprint_r( $taxonomies );\necho implode( $taxonomies, ', ' );\n</code></pre>\n" }, { "answer_id": 319553, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<p>The first problem with your code, I guess, is that you use <a href=\"https://codex.wordpress.org/Function_Reference/get_post_taxonomies\" rel=\"nofollow noreferrer\"><code>get_the_taxonomies</code></a> function, which will:</p>\n\n<blockquote>\n <p>Retrieve all taxonomies of a post with just the names.</p>\n</blockquote>\n\n<p>So its result will be like this:</p>\n\n<pre><code>Array\n(\n [0] =&gt; category\n [1] =&gt; post_tag\n [2] =&gt; post_format\n)\n</code></pre>\n\n<p>And I'm pretty sure that you want to get terms assigned to given post from all taxonomies, and not the taxonomies names...</p>\n\n<p>So most probably you want to do something like this:</p>\n\n<pre><code>$terms = wp_get_object_terms( get_the_ID(), array_keys( get_the_taxonomies() ) );\nforeach ( $terms as $i =&gt; $term ) {\n echo ($i ? ', ' : '') . $term-&gt;name;\n}\n</code></pre>\n\n<p>And quick answers to your questions:</p>\n\n<ol>\n<li>One of possible solutions above - it's hard to say if it's the best one. </li>\n<li>No, your method is not a solution, I guess.</li>\n<li>There is no need to use regex. You should avoid using regex when there is no need for that.</li>\n<li>You can get rid of hyperlinks by getting term objects and printing them by yourself (as shown above).</li>\n</ol>\n" } ]
2018/11/18
[ "https://wordpress.stackexchange.com/questions/319550", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132878/" ]
I have written my custom `WP_Query` and using loop to display post content. I use `get_the_category()` to display categories of current post and it works fine. Now for some post types there are custom taxonomies instead of categories. **Code to get categories**: ``` $categories = get_the_category(); if(!empty($categories)){ foreach($categories as $index => $cat){ echo $cat->name; } } ``` Now I need to pull all taxonomies and print them in comma separated format. I tried this: ``` $taxonomies = get_the_taxonomies(); if(!empty($taxonomies)){ foreach($taxonomies as $taxonomy){ echo $taxonomy; } } ``` It works and shows in this format "Taxonomy Label: Term (hyperlinked)". If the terms are more than one than it adds "and" between terms. I need only terms and if they are multiple then they should be separated by comma. I **want to know**: 1. The best approach to achieve those results 2. Is it recommended to to use above method? 3. Can I use `regex` to extract value? 4. How can I get rid off hyperlink? Thanks
The first problem with your code, I guess, is that you use [`get_the_taxonomies`](https://codex.wordpress.org/Function_Reference/get_post_taxonomies) function, which will: > > Retrieve all taxonomies of a post with just the names. > > > So its result will be like this: ``` Array ( [0] => category [1] => post_tag [2] => post_format ) ``` And I'm pretty sure that you want to get terms assigned to given post from all taxonomies, and not the taxonomies names... So most probably you want to do something like this: ``` $terms = wp_get_object_terms( get_the_ID(), array_keys( get_the_taxonomies() ) ); foreach ( $terms as $i => $term ) { echo ($i ? ', ' : '') . $term->name; } ``` And quick answers to your questions: 1. One of possible solutions above - it's hard to say if it's the best one. 2. No, your method is not a solution, I guess. 3. There is no need to use regex. You should avoid using regex when there is no need for that. 4. You can get rid of hyperlinks by getting term objects and printing them by yourself (as shown above).
319,576
<p>I am working on a WordPress website in which there are a lot of wordpress plugins installed.</p> <p>The plugins installed on the wordpress website has the following options:</p> <p><a href="https://i.stack.imgur.com/iaLC9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iaLC9.jpg" alt="enter image description here"></a></p> <p>When I click on View details option, I am getting the blank screen as shown below in an image but when I open in a new window or tab, it works.</p> <p>On checking console, I am getting the following error <strong>(when clicking on View Details fails to open on the same page):</strong></p> <pre><code>Blocked a frame with origin from accessing a cross-origin frame. at Contents at Function.map at a.fn.init.n.fn.(anonymous function) [as contents] and many other places. </code></pre> <p><a href="https://i.stack.imgur.com/8g3ea.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8g3ea.png" alt="enter image description here"></a></p> <p><strong>Problem Statement</strong>:</p> <p>I am wondering which file I need to modify in wordpress in order to solve this error. This error seems to exist in every wordpress plugins. It works in a new tab or window but fails to work in the same page.</p> <p>At this moment, <strong>I only have the wordpress admin access</strong>. I am wondering where I need to go in wordpress in order to resolve this issue. <strong>Do I need server access as well</strong> in order to make modifications in the files ? </p>
[ { "answer_id": 319551, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>Take a look at these:</p>\n\n<pre><code>$taxonomies = get_post_taxonomies( );\nprint_r( $taxonomies );\necho implode( $taxonomies, ', ' );\n</code></pre>\n" }, { "answer_id": 319553, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<p>The first problem with your code, I guess, is that you use <a href=\"https://codex.wordpress.org/Function_Reference/get_post_taxonomies\" rel=\"nofollow noreferrer\"><code>get_the_taxonomies</code></a> function, which will:</p>\n\n<blockquote>\n <p>Retrieve all taxonomies of a post with just the names.</p>\n</blockquote>\n\n<p>So its result will be like this:</p>\n\n<pre><code>Array\n(\n [0] =&gt; category\n [1] =&gt; post_tag\n [2] =&gt; post_format\n)\n</code></pre>\n\n<p>And I'm pretty sure that you want to get terms assigned to given post from all taxonomies, and not the taxonomies names...</p>\n\n<p>So most probably you want to do something like this:</p>\n\n<pre><code>$terms = wp_get_object_terms( get_the_ID(), array_keys( get_the_taxonomies() ) );\nforeach ( $terms as $i =&gt; $term ) {\n echo ($i ? ', ' : '') . $term-&gt;name;\n}\n</code></pre>\n\n<p>And quick answers to your questions:</p>\n\n<ol>\n<li>One of possible solutions above - it's hard to say if it's the best one. </li>\n<li>No, your method is not a solution, I guess.</li>\n<li>There is no need to use regex. You should avoid using regex when there is no need for that.</li>\n<li>You can get rid of hyperlinks by getting term objects and printing them by yourself (as shown above).</li>\n</ol>\n" } ]
2018/11/18
[ "https://wordpress.stackexchange.com/questions/319576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151467/" ]
I am working on a WordPress website in which there are a lot of wordpress plugins installed. The plugins installed on the wordpress website has the following options: [![enter image description here](https://i.stack.imgur.com/iaLC9.jpg)](https://i.stack.imgur.com/iaLC9.jpg) When I click on View details option, I am getting the blank screen as shown below in an image but when I open in a new window or tab, it works. On checking console, I am getting the following error **(when clicking on View Details fails to open on the same page):** ``` Blocked a frame with origin from accessing a cross-origin frame. at Contents at Function.map at a.fn.init.n.fn.(anonymous function) [as contents] and many other places. ``` [![enter image description here](https://i.stack.imgur.com/8g3ea.png)](https://i.stack.imgur.com/8g3ea.png) **Problem Statement**: I am wondering which file I need to modify in wordpress in order to solve this error. This error seems to exist in every wordpress plugins. It works in a new tab or window but fails to work in the same page. At this moment, **I only have the wordpress admin access**. I am wondering where I need to go in wordpress in order to resolve this issue. **Do I need server access as well** in order to make modifications in the files ?
The first problem with your code, I guess, is that you use [`get_the_taxonomies`](https://codex.wordpress.org/Function_Reference/get_post_taxonomies) function, which will: > > Retrieve all taxonomies of a post with just the names. > > > So its result will be like this: ``` Array ( [0] => category [1] => post_tag [2] => post_format ) ``` And I'm pretty sure that you want to get terms assigned to given post from all taxonomies, and not the taxonomies names... So most probably you want to do something like this: ``` $terms = wp_get_object_terms( get_the_ID(), array_keys( get_the_taxonomies() ) ); foreach ( $terms as $i => $term ) { echo ($i ? ', ' : '') . $term->name; } ``` And quick answers to your questions: 1. One of possible solutions above - it's hard to say if it's the best one. 2. No, your method is not a solution, I guess. 3. There is no need to use regex. You should avoid using regex when there is no need for that. 4. You can get rid of hyperlinks by getting term objects and printing them by yourself (as shown above).
319,585
<p>I have a specific dropdown field on variable products on my WooCommerce site that only ever has one option available. Example: the customer chooses the item “type”, then “color”, and finally “part number”, where “part number” dropdown always has just one option.</p> <p>I want to configure the site to remove the choose an option requirement from the “part number” dropdown and instead, automatically select the single option available.</p> <p>Is there a way to do this? It seems that WooCommerce needs an option that allows you to auto select a variation attribute when there is only one possible attribute available for the combination.</p>
[ { "answer_id": 319604, "author": "Aparna_29", "author_id": 84165, "author_profile": "https://wordpress.stackexchange.com/users/84165", "pm_score": 2, "selected": false, "text": "<p>Following code solves the purpose:</p>\n\n<pre><code>add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1);\nfunction fun_select_default_option( $args)\n{\n\n if(count($args['options']) &gt; 0) //Check the count of available options in dropdown\n $args['selected'] = $args['options'][0];\n return $args;\n}\n</code></pre>\n" }, { "answer_id": 335059, "author": "SHEESHRAM", "author_id": 141392, "author_profile": "https://wordpress.stackexchange.com/users/141392", "pm_score": 0, "selected": false, "text": "<p>Refer to the <a href=\"https://stackoverflow.com/questions/51181479/remove-choose-an-option-from-variable-product-dropdowns-in-woocommerce-3\">Original</a> answer.</p>\n\n<p>So there is 2 different case:</p>\n\n<p>1) Removing this html option completelly**:</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'filter_dropdown_option_html', 12, 2 );\nfunction filter_dropdown_option_html( $html, $args ) {\n $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );\n $show_option_none_html = '&lt;option value=\"\"&gt;' . esc_html( $show_option_none_text ) . '&lt;/option&gt;';\n\n $html = str_replace($show_option_none_html, '', $html);\n\n return $html;\n}\n</code></pre>\n\n<p>Code goes in <code>function.php</code> file of your active child theme (or active theme). Tested and works.</p>\n\n<p>2) Remove only the text \"Select an option\" (you will have an option without label name):</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'filter_dropdown_option_html', 12, 2 );\nfunction filter_dropdown_option_html( $html, $args ) {\n $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );\n $show_option_none_text = esc_html( $show_option_none_text );\n\n $html = str_replace($show_option_none_text, '', $html);\n\n return $html;\n}\n</code></pre>\n" }, { "answer_id": 396414, "author": "Shafaq", "author_id": 119270, "author_profile": "https://wordpress.stackexchange.com/users/119270", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/G3uMQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G3uMQ.png\" alt=\"the function above screenshot\" /></a></p>\n<p>the function above should be select green color as in the screenshot but its get selected by variation id that comes first,\ncan someone tell me how can i select fist display variation by default ?</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154317/" ]
I have a specific dropdown field on variable products on my WooCommerce site that only ever has one option available. Example: the customer chooses the item “type”, then “color”, and finally “part number”, where “part number” dropdown always has just one option. I want to configure the site to remove the choose an option requirement from the “part number” dropdown and instead, automatically select the single option available. Is there a way to do this? It seems that WooCommerce needs an option that allows you to auto select a variation attribute when there is only one possible attribute available for the combination.
Following code solves the purpose: ``` add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1); function fun_select_default_option( $args) { if(count($args['options']) > 0) //Check the count of available options in dropdown $args['selected'] = $args['options'][0]; return $args; } ```
319,612
<p>I'm trying to load a slider in my header, but only on the homepage. </p> <p>I'm using The Ultralight template if that helps. </p> <p>I'm trying to (in template-functions.php) do the following: </p> <pre><code>&lt;?php if ( is_page( 'home' ) ) : ?&gt; dynamic_sidebar( 'Homepage Widget' ); &lt;?php endif; ?&gt; </code></pre> <p>But this doesn't work. Now from a quick google, it seems I need to enqueue the request, but when I try this, I get a syntax error: </p> <pre><code>&lt;?php add_action( 'wp', 'wpse47305_check_home' ); function wpse47305_check_home() { if ( is_home() ) add_action( 'wp_enqueue_scripts', 'my_scripts' ); } function my_scripts() { dynamic_sidebar( 'Homepage Widget' ); } ?&gt; </code></pre> <p>Edit: So this doesn't seemingly add my sidebar in where I was expecting it to load in. I presume i've misunderstood the concept here. </p>
[ { "answer_id": 319604, "author": "Aparna_29", "author_id": 84165, "author_profile": "https://wordpress.stackexchange.com/users/84165", "pm_score": 2, "selected": false, "text": "<p>Following code solves the purpose:</p>\n\n<pre><code>add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1);\nfunction fun_select_default_option( $args)\n{\n\n if(count($args['options']) &gt; 0) //Check the count of available options in dropdown\n $args['selected'] = $args['options'][0];\n return $args;\n}\n</code></pre>\n" }, { "answer_id": 335059, "author": "SHEESHRAM", "author_id": 141392, "author_profile": "https://wordpress.stackexchange.com/users/141392", "pm_score": 0, "selected": false, "text": "<p>Refer to the <a href=\"https://stackoverflow.com/questions/51181479/remove-choose-an-option-from-variable-product-dropdowns-in-woocommerce-3\">Original</a> answer.</p>\n\n<p>So there is 2 different case:</p>\n\n<p>1) Removing this html option completelly**:</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'filter_dropdown_option_html', 12, 2 );\nfunction filter_dropdown_option_html( $html, $args ) {\n $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );\n $show_option_none_html = '&lt;option value=\"\"&gt;' . esc_html( $show_option_none_text ) . '&lt;/option&gt;';\n\n $html = str_replace($show_option_none_html, '', $html);\n\n return $html;\n}\n</code></pre>\n\n<p>Code goes in <code>function.php</code> file of your active child theme (or active theme). Tested and works.</p>\n\n<p>2) Remove only the text \"Select an option\" (you will have an option without label name):</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'filter_dropdown_option_html', 12, 2 );\nfunction filter_dropdown_option_html( $html, $args ) {\n $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' );\n $show_option_none_text = esc_html( $show_option_none_text );\n\n $html = str_replace($show_option_none_text, '', $html);\n\n return $html;\n}\n</code></pre>\n" }, { "answer_id": 396414, "author": "Shafaq", "author_id": 119270, "author_profile": "https://wordpress.stackexchange.com/users/119270", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/G3uMQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G3uMQ.png\" alt=\"the function above screenshot\" /></a></p>\n<p>the function above should be select green color as in the screenshot but its get selected by variation id that comes first,\ncan someone tell me how can i select fist display variation by default ?</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154336/" ]
I'm trying to load a slider in my header, but only on the homepage. I'm using The Ultralight template if that helps. I'm trying to (in template-functions.php) do the following: ``` <?php if ( is_page( 'home' ) ) : ?> dynamic_sidebar( 'Homepage Widget' ); <?php endif; ?> ``` But this doesn't work. Now from a quick google, it seems I need to enqueue the request, but when I try this, I get a syntax error: ``` <?php add_action( 'wp', 'wpse47305_check_home' ); function wpse47305_check_home() { if ( is_home() ) add_action( 'wp_enqueue_scripts', 'my_scripts' ); } function my_scripts() { dynamic_sidebar( 'Homepage Widget' ); } ?> ``` Edit: So this doesn't seemingly add my sidebar in where I was expecting it to load in. I presume i've misunderstood the concept here.
Following code solves the purpose: ``` add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1); function fun_select_default_option( $args) { if(count($args['options']) > 0) //Check the count of available options in dropdown $args['selected'] = $args['options'][0]; return $args; } ```
319,619
<p>I am an amateur WP developer building a site for my wife :) I am using Helium theme and the site is in RTL direction. I have a right side bar.</p> <p>After making some changes by changing the main page content from text <a href="https://i.stack.imgur.com/cGAfc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cGAfc.png" alt="enter image description here"></a> to SiteOrigin widgets buttons defined on top of "widgets for shrotcodes", <a href="https://i.stack.imgur.com/p2e6R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p2e6R.png" alt="enter image description here"></a> the side bar starts <strong>flickering</strong> upon scrolling of the page: <a href="https://youtu.be/CM-tg5r8l1s" rel="nofollow noreferrer">An example clip</a></p> <p>This is the new main page content:</p> <pre><code> [do_widget id=sow-button-10] [wonderplugin_cond deviceinclude="Mobile"] אל המאמרים שלי בשבילכם - גוללו מטה! [/wonderplugin_cond] [do_widget id=sow-button-11] [do_widget id=sow-button-12] [do_widget id=sow-button-13] [do_widget id=sow-button-14] [do_widget id=sow-button-15] [do_widget id=sow-button-16] </code></pre> <p>And this is the customized css:</p> <pre><code>body {background-color: white;} .site_ttl{ color: #3264ff; font-family: "David"; } h1.entry-title{ font-size:48px; color: #3264ff; margin-left: auto; margin-right: auto; } #toggle_nav{ font-size:14px; color:white; text-align: center; text-decoration: underline; } @media only screen and (min-width: 600px) { #primary.content-area { width: calc(100% - 400px); float: left; margin-bottom: 0px } } @media only screen and (max-width: 600px) { #primary.content-area { width: calc(100% - 100px); float: left; margin-bottom: 0px } } .sidebar.clearfix.floating { right: 0; left: initial; margin-left: 0; } /*-------------------*/ /*-------------------*/ /*To adjust the sidebar widget spacing*/ .sidebar .widget { margin-bottom: 0px; } /*-------------------*/ /*-------------------*/ /*To adjust the the h' titles spacing*/ h1 { margin-bottom: 0px; } h2 { margin-bottom: 0px; } h3 { margin-bottom: 0px; } h4 { margin-bottom: 0px; } h4 { margin-top: 0px; } ul {margin-top: 0px} ul {margin-bottom: 0px} /*-------------------*/ /*hide triple line menu symbol*/ #main-menu{ visibility: hidden } </code></pre> <p>Please advise :)</p> <p>Thanks!</p>
[ { "answer_id": 319623, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p>You would need to know since when / which change it starts flickering. // you said since the content change. So try to change back step by step until you know which content component exactly causes this.</p></li>\n<li><p>Debug that change which caused that flickering.</p></li>\n</ol>\n\n<p>There are playing a lot of factors in here: Theme, Theme CSS, Custom CSS, Theme JS, Widgets CSS and JS (maybe from another Plugin?) which make that unpredictable to give a correct answer. So just guessing.</p>\n" }, { "answer_id": 319707, "author": "dushkin", "author_id": 148343, "author_profile": "https://wordpress.stackexchange.com/users/148343", "pm_score": 0, "selected": false, "text": "<p>I know it is only a workaround, but maybe it can help someone in the future...</p>\n\n<p>I found out that changing to the SiteOrigin widgets was not the issue.\nAs I started to remove several lines from the bottom of the original text based page, I reached a position where the sidebar stopped flickering and returned to be shown normally again.</p>\n\n<p>So my work around was to add empty lines (eventually I need only 5 lines) after the new SiteOrigin buttons and problem was solved.</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319619", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148343/" ]
I am an amateur WP developer building a site for my wife :) I am using Helium theme and the site is in RTL direction. I have a right side bar. After making some changes by changing the main page content from text [![enter image description here](https://i.stack.imgur.com/cGAfc.png)](https://i.stack.imgur.com/cGAfc.png) to SiteOrigin widgets buttons defined on top of "widgets for shrotcodes", [![enter image description here](https://i.stack.imgur.com/p2e6R.png)](https://i.stack.imgur.com/p2e6R.png) the side bar starts **flickering** upon scrolling of the page: [An example clip](https://youtu.be/CM-tg5r8l1s) This is the new main page content: ``` [do_widget id=sow-button-10] [wonderplugin_cond deviceinclude="Mobile"] אל המאמרים שלי בשבילכם - גוללו מטה! [/wonderplugin_cond] [do_widget id=sow-button-11] [do_widget id=sow-button-12] [do_widget id=sow-button-13] [do_widget id=sow-button-14] [do_widget id=sow-button-15] [do_widget id=sow-button-16] ``` And this is the customized css: ``` body {background-color: white;} .site_ttl{ color: #3264ff; font-family: "David"; } h1.entry-title{ font-size:48px; color: #3264ff; margin-left: auto; margin-right: auto; } #toggle_nav{ font-size:14px; color:white; text-align: center; text-decoration: underline; } @media only screen and (min-width: 600px) { #primary.content-area { width: calc(100% - 400px); float: left; margin-bottom: 0px } } @media only screen and (max-width: 600px) { #primary.content-area { width: calc(100% - 100px); float: left; margin-bottom: 0px } } .sidebar.clearfix.floating { right: 0; left: initial; margin-left: 0; } /*-------------------*/ /*-------------------*/ /*To adjust the sidebar widget spacing*/ .sidebar .widget { margin-bottom: 0px; } /*-------------------*/ /*-------------------*/ /*To adjust the the h' titles spacing*/ h1 { margin-bottom: 0px; } h2 { margin-bottom: 0px; } h3 { margin-bottom: 0px; } h4 { margin-bottom: 0px; } h4 { margin-top: 0px; } ul {margin-top: 0px} ul {margin-bottom: 0px} /*-------------------*/ /*hide triple line menu symbol*/ #main-menu{ visibility: hidden } ``` Please advise :) Thanks!
1. You would need to know since when / which change it starts flickering. // you said since the content change. So try to change back step by step until you know which content component exactly causes this. 2. Debug that change which caused that flickering. There are playing a lot of factors in here: Theme, Theme CSS, Custom CSS, Theme JS, Widgets CSS and JS (maybe from another Plugin?) which make that unpredictable to give a correct answer. So just guessing.
319,631
<p>Theme: Education LMS</p> <p>How can I remove the theme information from my footer copyright area, or how can I edit the do_action function? So that only display what I want to display in footer.</p> <pre><code> &lt;div class="col-sm-6"&gt; &lt;div class="site-info"&gt; &lt;?php do_action( 'education_lms_footer_copyright' ); ?&gt; &lt;/div&gt;&lt;!-- .site-info --&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'menu-2', 'menu_id' =&gt; 'footer-menu', 'menu_class' =&gt; 'pull-right list-unstyled list-inline mb-0' ) ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;' </code></pre> <p>I Found this, please tell me is this the right part?</p> <pre><code>&lt;php /** * Add theme dashboard page */ add_action('admin_menu', 'education_lms_theme_info'); function education_lms_theme_info() { $theme_data = wp_get_theme(); add_theme_page( sprintf( esc_html__( '%s Dashboard', 'education-lms' ), $theme_data-&gt;Name ), sprintf( '%s', $theme_data-&gt;Name), 'edit_theme_options', 'education_lms', 'education_lms_theme_info_page'); } if ( ! function_exists( 'education_lms_admin_scripts' ) ) : /** * Enqueue scripts for admin page only: Theme info page */ function education_lms_admin_scripts( $hook ) { if ( $hook === 'widgets.php' || $hook === 'appearance_page_education_lms' ) { wp_enqueue_style('education_lms-admin-css', get_template_directory_uri() . '/assets/css/admin.css'); } } endif; add_action('admin_enqueue_scripts', 'education_lms_admin_scripts'); function education_lms_theme_info_page() { $theme_data = wp_get_theme(); // Check for current viewing tab $tab = null; if ( isset( $_GET['tab'] ) ) { $tab = $_GET['tab']; } else { $tab = null; } ?&gt; &lt;div class="wrap about-wrap theme_info_wrapper"&gt; &lt;h1&gt;&lt;?php printf(esc_html__('Welcome to %1$1s - Version %2$2s', 'education-lms'), $theme_data-&gt;Name, $theme_data-&gt;Version ); ?&gt;&lt;/h1&gt; &lt;div class="about-text"&gt;&lt;?php echo $theme_data-&gt;Description &gt;&lt;/div&gt; &lt;h2 class="nav-tab-wrapper"&gt; &lt;a href="?page=education_lms" class="nav-tab&lt;?php echo is_null($tab) ? ' nav-tab-active' : null; ?&gt;"&gt;&lt;?php echo $theme_data-&gt;Name; ?&gt;&lt;/a&gt; &lt;?php ?&gt; &lt;a href="&lt;?php echo esc_url( add_query_arg( array( 'page'=&gt;'education_lms', 'tab' =&gt; 'free_pro' ), admin_url( 'themes.php' ) ) ); ?&gt;" class="nav-tab&lt;?php echo $tab == 'free_pro' ? ' nav-tab-active' : null; ?&gt;"&gt;&lt;?php esc_html_e( 'Free vs PRO', 'education-lms' ); ?&gt;&lt;/span&gt;&lt;/a&gt; &lt;?php ?&gt; &lt;/h2&gt; &lt;?php if ( is_null($tab) ) { ?&gt; &lt;div class="theme_info info-tab-content"&gt; &lt;div class="theme_info_column clearfix"&gt; &lt;div class="theme_info_left"&gt; &lt;div class="theme_link"&gt; &lt;h3&gt;&lt;?php esc_html_e( 'Theme Customizer', 'education-lms' ); ?&gt;&lt;/h3&gt; &lt;p class="about"&gt;&lt;?php printf(esc_html__('%s supports the Theme Customizer for all theme settings. Click "Customize" to start customize your site.', 'education-lms'), $theme_data-&gt;Name); ?&gt;&lt;/p&gt; &lt;p&gt; &lt;a href="&lt;?php echo admin_url('customize.php'); ?&gt;" class="button button-primary"&gt;&lt;?php esc_html_e('Start Customize', 'education-lms'); ?&gt;&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="theme_link"&gt; &lt;h3&gt;&lt;?php esc_html_e( 'Theme Documentation', 'education-lms' ); ?&gt;&lt;/h3&gt; &lt;p class="about"&gt;&lt;?php printf(esc_html__('Need any help to setup and configure %s? Please have a look at our documentations instructions.', 'education-lms'), $theme_data-&gt;Name); ?&gt;&lt;/p&gt; &lt;p&gt; &lt;a href="http://docs.filathemes.com/education-lms/" target="_blank" class="button button-secondary"&gt;&lt;?php esc_html_e('Online Documentation', 'education-lms'); ?&gt;&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="theme_info_right"&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/screenshot.png" alt="&lt;?php esc_html_e( 'Theme Screenshot', 'education-lms' ); ?&gt;" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ( $tab == 'free_pro' ) { ?&gt; &lt;div id="free_pro" class="freepro-tab-content info-tab-content"&gt; &lt;table class="free-pro-table"&gt; &lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Free&lt;/th&gt;&lt;th&gt; PRO&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Responsive Design&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Translation Ready&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Upload Your Own Logo&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Unlimited Slide&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;LearnPress - WordPress LMS&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Elementor Compatible&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;WooCommerce Compatible&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Custom Widgets&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Header Topbar&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Header Cover Image&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Social Icons&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Footer Widget&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Demo Content Ready&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Retina Logo&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Sticky Header&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Header Transparent&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;2 Header Layout&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Slider Advanced Styling&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Course Grid/List Layout&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Multi Color Options&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Back To Top&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;600+ Google fonts&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;Footer Copyright &amp; Layout&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h4&gt;24/7/365 Support&lt;/h4&gt; &lt;/td&gt; &lt;td class="only-pro"&gt;&lt;span class="dashicons-before dashicons-no-alt"&gt;&lt;/span&gt;&lt;/td&gt; &lt;td class="only-lite"&gt;&lt;span class="dashicons-before dashicons-yes"&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="ti-about-page-text-center"&gt;&lt;td&gt;&lt;/td&gt;&lt;td colspan="2"&gt;&lt;a href="https://www.filathemes.com/downloads/education-lms-pro/" target="_blank" class="button button-primary button-hero"&gt;Get Pro now!&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;!-- END .theme_info --&gt; &lt;?php } function education_lms_admin_notice(){ if ( version_compare(PHP_VERSION, '5.4.0') &lt; 0 ) { ?&gt; &lt;div class="warning notice notice-warning notice-alt is-dismissible"&gt; &lt;p&gt;&lt;strong&gt;&lt;?php esc_html_e('The Education LMS theme require PHP version 5.4 or greater.', 'education-lms'); ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } } function education_lms_one_activation_admin_notice(){ global $pagenow; if ( is_admin() &amp;&amp; ('themes.php' == $pagenow) &amp;&amp; isset( $_GET['activated'] ) ) { add_action( 'admin_notices', 'education_lms_admin_notice' ); } } /* activation notice */ add_action( 'load-themes.php', 'education_lms_one_activation_admin_notice' ); function education_lms_review_notice(){ global $pagenow; if ( is_admin() &amp;&amp; 'themes.php' == $pagenow ) { ?&gt; &lt;span id="footer-thankyou"&gt; &lt;?php $reviewurl = 'https://wordpress.org/support/theme/education-lms/reviews/#new-post'; printf( __( 'You have been using &lt;b&gt;Education LMS&lt;/b&gt; theme, do you like it? If so, please leave us &lt;a href="%s" target="_blank"&gt;a review&lt;/a&gt; with your feedback. Thank you!', 'education-lms' ), esc_url( $reviewurl ) ); ?&gt; &lt;/span&gt; &lt;?php } } add_filter('admin_footer_text', 'education_lms_review_notice'); </code></pre>
[ { "answer_id": 319632, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 0, "selected": false, "text": "<p>you would need to overwrite the PHP function in your child-themes functions.php. \nYou can search in your parent theme for the original function <code>education_lms_footer_copyright</code>.</p>\n\n<p>OR just type in your own information in the template if this would be sufficient for your needs.</p>\n" }, { "answer_id": 319633, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/remove_all_actions/\" rel=\"nofollow noreferrer\"><code>remove_all_actions()</code></a>, but you have to make sure the theme's actions are actually set before you want to remove them. Setting a high enough priority could work.</p>\n\n<pre><code>add_action('init', 'WPSE_remove_lms_footer_copyright', 9999);\nfunction WPSE_remove_lms_footer_copyright() {\n remove_all_actions('education_lms_footer_copyright');\n}\n</code></pre>\n\n<p>Where to put this code? If you already have a custom plugin, you can use it there. If you don't, you can create a child theme and could use it there.</p>\n\n<p>But if you already have a child theme, it will be much easier to copy the (presumably) footer.php and simply remove this line.</p>\n" }, { "answer_id": 319634, "author": "Fabian Marz", "author_id": 77421, "author_profile": "https://wordpress.stackexchange.com/users/77421", "pm_score": 1, "selected": false, "text": "<p>Instead of removing all actions as suggested by @kero, you should remove the desired hooks only using <a href=\"https://developer.wordpress.org/reference/functions/remove_action/\" rel=\"nofollow noreferrer\"><code>remove_action</code></a>. Removing all hooks will prevent 3rd party code from adding their code too when removed after they added their stuff (possibly including yours).</p>\n\n<p>To remove a specific hook you should search for the code which registers the action. In this case:</p>\n\n<pre><code>// theme-functions.php:322\nadd_action( 'education_lms_footer_copyright', 'education_lms_footer_info' );\n</code></pre>\n\n<p>Then add your own code in your <code>functions.php</code> to remove the hook:</p>\n\n<pre><code>remove_action( 'education_lms_footer_copyright', 'education_lms_footer_info' );\n</code></pre>\n\n<p>To add custom code at the copyright position you could use something like:</p>\n\n<pre><code>add_action( 'education_lms_footer_copyright', function () {\n echo 'My copyright code';\n} );\n</code></pre>\n\n<p>Sometimes you might need to pass a priority (3rd parameter) if the hook was registered with another than the default of <code>10</code>.</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319631", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154244/" ]
Theme: Education LMS How can I remove the theme information from my footer copyright area, or how can I edit the do\_action function? So that only display what I want to display in footer. ``` <div class="col-sm-6"> <div class="site-info"> <?php do_action( 'education_lms_footer_copyright' ); ?> </div><!-- .site-info --> </div> <div class="col-sm-6"> <?php wp_nav_menu( array( 'theme_location' => 'menu-2', 'menu_id' => 'footer-menu', 'menu_class' => 'pull-right list-unstyled list-inline mb-0' ) ); ?> </div> </div> </div>' ``` I Found this, please tell me is this the right part? ``` <php /** * Add theme dashboard page */ add_action('admin_menu', 'education_lms_theme_info'); function education_lms_theme_info() { $theme_data = wp_get_theme(); add_theme_page( sprintf( esc_html__( '%s Dashboard', 'education-lms' ), $theme_data->Name ), sprintf( '%s', $theme_data->Name), 'edit_theme_options', 'education_lms', 'education_lms_theme_info_page'); } if ( ! function_exists( 'education_lms_admin_scripts' ) ) : /** * Enqueue scripts for admin page only: Theme info page */ function education_lms_admin_scripts( $hook ) { if ( $hook === 'widgets.php' || $hook === 'appearance_page_education_lms' ) { wp_enqueue_style('education_lms-admin-css', get_template_directory_uri() . '/assets/css/admin.css'); } } endif; add_action('admin_enqueue_scripts', 'education_lms_admin_scripts'); function education_lms_theme_info_page() { $theme_data = wp_get_theme(); // Check for current viewing tab $tab = null; if ( isset( $_GET['tab'] ) ) { $tab = $_GET['tab']; } else { $tab = null; } ?> <div class="wrap about-wrap theme_info_wrapper"> <h1><?php printf(esc_html__('Welcome to %1$1s - Version %2$2s', 'education-lms'), $theme_data->Name, $theme_data->Version ); ?></h1> <div class="about-text"><?php echo $theme_data->Description ></div> <h2 class="nav-tab-wrapper"> <a href="?page=education_lms" class="nav-tab<?php echo is_null($tab) ? ' nav-tab-active' : null; ?>"><?php echo $theme_data->Name; ?></a> <?php ?> <a href="<?php echo esc_url( add_query_arg( array( 'page'=>'education_lms', 'tab' => 'free_pro' ), admin_url( 'themes.php' ) ) ); ?>" class="nav-tab<?php echo $tab == 'free_pro' ? ' nav-tab-active' : null; ?>"><?php esc_html_e( 'Free vs PRO', 'education-lms' ); ?></span></a> <?php ?> </h2> <?php if ( is_null($tab) ) { ?> <div class="theme_info info-tab-content"> <div class="theme_info_column clearfix"> <div class="theme_info_left"> <div class="theme_link"> <h3><?php esc_html_e( 'Theme Customizer', 'education-lms' ); ?></h3> <p class="about"><?php printf(esc_html__('%s supports the Theme Customizer for all theme settings. Click "Customize" to start customize your site.', 'education-lms'), $theme_data->Name); ?></p> <p> <a href="<?php echo admin_url('customize.php'); ?>" class="button button-primary"><?php esc_html_e('Start Customize', 'education-lms'); ?></a> </p> </div> <div class="theme_link"> <h3><?php esc_html_e( 'Theme Documentation', 'education-lms' ); ?></h3> <p class="about"><?php printf(esc_html__('Need any help to setup and configure %s? Please have a look at our documentations instructions.', 'education-lms'), $theme_data->Name); ?></p> <p> <a href="http://docs.filathemes.com/education-lms/" target="_blank" class="button button-secondary"><?php esc_html_e('Online Documentation', 'education-lms'); ?></a> </p> </div> </div> <div class="theme_info_right"> <img src="<?php echo get_template_directory_uri(); ?>/screenshot.png" alt="<?php esc_html_e( 'Theme Screenshot', 'education-lms' ); ?>" /> </div> </div> </div> <?php } ?> <?php if ( $tab == 'free_pro' ) { ?> <div id="free_pro" class="freepro-tab-content info-tab-content"> <table class="free-pro-table"> <thead><tr><th></th><th>Free</th><th> PRO</th></tr></thead> <tbody> <tr> <td> <h4>Responsive Design</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Translation Ready</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Upload Your Own Logo</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Unlimited Slide</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>LearnPress - WordPress LMS</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Elementor Compatible</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>WooCommerce Compatible</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Custom Widgets</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Header Topbar</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Header Cover Image</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Social Icons</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Footer Widget</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Demo Content Ready</h4> </td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Retina Logo</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Sticky Header</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Header Transparent</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>2 Header Layout</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Slider Advanced Styling</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Course Grid/List Layout</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Multi Color Options</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Back To Top</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>600+ Google fonts</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>Footer Copyright & Layout</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr> <td> <h4>24/7/365 Support</h4> </td> <td class="only-pro"><span class="dashicons-before dashicons-no-alt"></span></td> <td class="only-lite"><span class="dashicons-before dashicons-yes"></span></td> </tr> <tr class="ti-about-page-text-center"><td></td><td colspan="2"><a href="https://www.filathemes.com/downloads/education-lms-pro/" target="_blank" class="button button-primary button-hero">Get Pro now!</a></td></tr> </tbody> </table> </div> <?php } ?> </div> <!-- END .theme_info --> <?php } function education_lms_admin_notice(){ if ( version_compare(PHP_VERSION, '5.4.0') < 0 ) { ?> <div class="warning notice notice-warning notice-alt is-dismissible"> <p><strong><?php esc_html_e('The Education LMS theme require PHP version 5.4 or greater.', 'education-lms'); ?></strong></p> </div> <?php } } function education_lms_one_activation_admin_notice(){ global $pagenow; if ( is_admin() && ('themes.php' == $pagenow) && isset( $_GET['activated'] ) ) { add_action( 'admin_notices', 'education_lms_admin_notice' ); } } /* activation notice */ add_action( 'load-themes.php', 'education_lms_one_activation_admin_notice' ); function education_lms_review_notice(){ global $pagenow; if ( is_admin() && 'themes.php' == $pagenow ) { ?> <span id="footer-thankyou"> <?php $reviewurl = 'https://wordpress.org/support/theme/education-lms/reviews/#new-post'; printf( __( 'You have been using <b>Education LMS</b> theme, do you like it? If so, please leave us <a href="%s" target="_blank">a review</a> with your feedback. Thank you!', 'education-lms' ), esc_url( $reviewurl ) ); ?> </span> <?php } } add_filter('admin_footer_text', 'education_lms_review_notice'); ```
Instead of removing all actions as suggested by @kero, you should remove the desired hooks only using [`remove_action`](https://developer.wordpress.org/reference/functions/remove_action/). Removing all hooks will prevent 3rd party code from adding their code too when removed after they added their stuff (possibly including yours). To remove a specific hook you should search for the code which registers the action. In this case: ``` // theme-functions.php:322 add_action( 'education_lms_footer_copyright', 'education_lms_footer_info' ); ``` Then add your own code in your `functions.php` to remove the hook: ``` remove_action( 'education_lms_footer_copyright', 'education_lms_footer_info' ); ``` To add custom code at the copyright position you could use something like: ``` add_action( 'education_lms_footer_copyright', function () { echo 'My copyright code'; } ); ``` Sometimes you might need to pass a priority (3rd parameter) if the hook was registered with another than the default of `10`.
319,642
<p>Please bear with me as I am a front-end developer trying to grapple with PHP.</p> <p>I am attempting to add a gravity form to specific pages on my website website by adding a function to my <code>functions.php</code> file. It doesn't matter where it is placed on the page since the form will be initially hidden and then used for an exit-intent popup. <a href="https://docs.gravityforms.com/embedding-a-form/" rel="nofollow noreferrer">Gravity form's documentation</a> says that a Gravity form can be embedded via PHP function call. This is their given example:</p> <pre><code>gravity_form( 1, false, false, false, '', false ); </code></pre> <p>After searching through already asked questions I found <a href="https://wordpress.stackexchange.com/questions/138473/if-is-pagepage-id-not-working">this post</a> about conditional PHP that would only call the function on the specified page. I tried to put this all together. The result is below:</p> <pre><code>function add_split_test_forms() { if (is_page('Homepage')): gravity_form(19, false, false, false, '', false); endif; } </code></pre> <p>I added &quot;add_split_test_forms&quot; because I assume this is just me naming the function (correct me if I'm wrong there).</p> <p>Unfortunately, this is not working. I tried other variations such as using the page id instead of the page name, but the result is the same.</p> <p>I went back to the post regarding conditional PHP and tried the other upvoted answer (the accepted answer) which resulted in me trying this code:</p> <pre><code>function add_split_test_forms() { global $post; &lt;?php if( $post-&gt;ID == 5457) { ?&gt; gravity_form(19, false, false, false, '', false); endif; &lt;?php } ?&gt; } </code></pre> <p>This just broke everything so I also tried:</p> <pre><code>function add_split_test_forms() { global $post; if( $post-&gt;ID == 5457) { gravity_form(19, false, false, false, '', false); endif; } } </code></pre> <p>This <em>also</em> broke everything. So... now I'm back to the first example that was, at a minimum, not bringing the entire site down.</p> <p>At the end of that documentation page it says:</p> <blockquote> <p>When embedding a form via a function call you must also manually include the necessary Gravity Forms related Javascript and CSS via the built in WordPress enqueue capabilities. Gravity Forms does not include these by default when calling a form via a function call and they are necessary for forms that contain conditional logic or the date picker field.</p> <p>We strongly recommend you enqueue the scripts rather than including them as hardcoded calls in your theme. Implementing it this way will insure that Gravity Forms does not include them on the page if they are already present. It is also a good practice to only load these scripts on the front end.</p> <p>Gravity Forms 1.5 introduced the gravity_form_enqueue_scripts() function which allows you to easily enqueue the necessary Gravity Forms’ scripts and styles when manually embedding a form. This is also useful if you are using a GF widget and do not wish for the styles and scripts to be loaded inline.</p> </blockquote> <p>When I looked at the documentation for <code>gravity_form_enqueue_scripts</code> it provided this example <code>gravity_form_enqueue_scripts( 4, true );</code> and said:</p> <blockquote> <p>This script should be placed in the theme’s header.php file just before the wp_head() function is called.</p> </blockquote> <p>But can't I just add it to the functions.php file? When I tried:</p> <pre><code>function add_split_test_forms() { if (is_page('Homepage')): gravity_form_enqueue_scripts( 19, true ); gravity_form(19, false, false, false, '', false); endif; } </code></pre> <p>AND</p> <pre><code>gravity_form_enqueue_scripts( 19, true ); function add_split_test_forms() { if (is_page('Homepage')): gravity_form(19, false, false, false, '', false); endif; } </code></pre> <p>Neither way works. Do I need to hook into the <code>wp_head()</code> somehow in my <code>functions.php</code> file to add <code>gravity_form_enqueue_scripts( 19, true );</code>?</p> <p><strong>Important notes to preempt what questions I can think of:</strong></p> <ul> <li>This being added to the end of my <code>functions.php</code> file before the closing <code>?&gt;</code>.</li> <li>Yes this form exists and functions correctly on other pages.</li> <li>I've looked at the the other posts here regarding page-conditional PHP functions and none of them address this issue.</li> <li>Per the Gravity Forms documentation, I'm not even getting the &quot;Oops! We could not locate your form.&quot; error. There is absolutely zero output (as far as I can tell). Not visible changes to the page either.</li> <li>I also looked through the posts under the little-used tag of <a href="https://wordpress.stackexchange.com/questions/tagged/page-specific-settings">[page-specific-settings]</a>.</li> </ul>
[ { "answer_id": 319643, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 0, "selected": false, "text": "<p>if you got following in your <code>functions.php</code></p>\n\n<pre><code>function add_split_test_forms()\n{\n if (is_page('Homepage')):\n gravity_form(19, false, false, false, '', false);\n endif;\n}\n</code></pre>\n\n<p>you will at least need to <strong>run this function once</strong>: add a line <code>add_split_test_forms()</code> in your <code>functions.php</code>.</p>\n\n<p>if your condition <code>if (is_page('Homepage')):</code> is correct. (I prefer <code>if ( is_front_page()):</code> should also work.)\nThen your form should appear in the markup, like you said.</p>\n" }, { "answer_id": 319645, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>I'd recommend that you use the <a href=\"https://developer.wordpress.org/reference/hooks/the_content/\" rel=\"nofollow noreferrer\"><code>the_content</code> filter hook</a> to add your form:</p>\n\n<pre><code>add_filter( 'the_content', 'add_split_test_forms' );\n\nfunction add_split_test_forms( $content ) {\n if ( is_page( 'Homepage' ) ) {\n $content .= gravity_form( 19, false, false, false, '', false, 1, true );\n return $content;\n }\n}\n</code></pre>\n\n<p>... and the <a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts</code> action hook</a> to enqueue the scripts:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse319642_add_scripts_for_form_19' );\nfunction wpse319642_add_scripts_for_form_19() {\n // 2nd param is 'false' b/c you've set AJAX to 'false' in the gravity_form() call\n gravity_form_enqueue_scripts( 19, false );\n}\n</code></pre>\n\n<p>All this code can go in your theme's <code>functions.php</code> file.</p>\n\n<p>This code is <strong>untested</strong>, but I think it should work.</p>\n\n<p>(Echoing @majick's comment, though: Is there a compelling reason to not simply use the Gravity Forms shortcode to embed the form in the WordPress editor?)</p>\n" }, { "answer_id": 319647, "author": "jarrodwhitley", "author_id": 69042, "author_profile": "https://wordpress.stackexchange.com/users/69042", "pm_score": -1, "selected": true, "text": "<p>Ok I figured it out. I just need to hook into <code>wp_footer</code>. The only thing that gets added to <code>header.php</code> is the <code>gravity_form_enqueue_scripts()</code> function. Per the documentation:</p>\n\n<blockquote>\n <p>This function will enqueue the necessary styles and scripts for the specified Gravity Form. This is useful when manually embedding a form outside the WordPress loop using the function call or to force the stylesheets and scripts to load in the header when using the Form Widget.</p>\n</blockquote>\n\n<pre><code>function add_split_test_forms()\n{\n if (is_page([4904,2559,356,358,360,376,362,364,366,354,372,374])):\n gravity_form(19, false, false, false, '', false);\n endif;\n}\nadd_action( 'wp_footer', 'add_split_test_forms' );\n</code></pre>\n\n<p><strong>Edit:</strong> Jacob suggested below that forms should never go in the <code>&lt;head&gt;</code> but rather in the footer. I've changed my answer to reflect that.</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319642", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69042/" ]
Please bear with me as I am a front-end developer trying to grapple with PHP. I am attempting to add a gravity form to specific pages on my website website by adding a function to my `functions.php` file. It doesn't matter where it is placed on the page since the form will be initially hidden and then used for an exit-intent popup. [Gravity form's documentation](https://docs.gravityforms.com/embedding-a-form/) says that a Gravity form can be embedded via PHP function call. This is their given example: ``` gravity_form( 1, false, false, false, '', false ); ``` After searching through already asked questions I found [this post](https://wordpress.stackexchange.com/questions/138473/if-is-pagepage-id-not-working) about conditional PHP that would only call the function on the specified page. I tried to put this all together. The result is below: ``` function add_split_test_forms() { if (is_page('Homepage')): gravity_form(19, false, false, false, '', false); endif; } ``` I added "add\_split\_test\_forms" because I assume this is just me naming the function (correct me if I'm wrong there). Unfortunately, this is not working. I tried other variations such as using the page id instead of the page name, but the result is the same. I went back to the post regarding conditional PHP and tried the other upvoted answer (the accepted answer) which resulted in me trying this code: ``` function add_split_test_forms() { global $post; <?php if( $post->ID == 5457) { ?> gravity_form(19, false, false, false, '', false); endif; <?php } ?> } ``` This just broke everything so I also tried: ``` function add_split_test_forms() { global $post; if( $post->ID == 5457) { gravity_form(19, false, false, false, '', false); endif; } } ``` This *also* broke everything. So... now I'm back to the first example that was, at a minimum, not bringing the entire site down. At the end of that documentation page it says: > > When embedding a form via a function call you must also manually include the necessary Gravity Forms related Javascript and CSS via the built in WordPress enqueue capabilities. Gravity Forms does not include these by default when calling a form via a function call and they are necessary for forms that contain conditional logic or the date picker field. > > > We strongly recommend you enqueue the scripts rather than including them as hardcoded calls in your theme. Implementing it this way will insure that Gravity Forms does not include them on the page if they are already present. It is also a good practice to only load these scripts on the front end. > > > Gravity Forms 1.5 introduced the gravity\_form\_enqueue\_scripts() function which allows you to easily enqueue the necessary Gravity Forms’ scripts and styles when manually embedding a form. This is also useful if you are using a GF widget and do not wish for the styles and scripts to be loaded inline. > > > When I looked at the documentation for `gravity_form_enqueue_scripts` it provided this example `gravity_form_enqueue_scripts( 4, true );` and said: > > This script should be placed in the theme’s header.php file just before the wp\_head() function is called. > > > But can't I just add it to the functions.php file? When I tried: ``` function add_split_test_forms() { if (is_page('Homepage')): gravity_form_enqueue_scripts( 19, true ); gravity_form(19, false, false, false, '', false); endif; } ``` AND ``` gravity_form_enqueue_scripts( 19, true ); function add_split_test_forms() { if (is_page('Homepage')): gravity_form(19, false, false, false, '', false); endif; } ``` Neither way works. Do I need to hook into the `wp_head()` somehow in my `functions.php` file to add `gravity_form_enqueue_scripts( 19, true );`? **Important notes to preempt what questions I can think of:** * This being added to the end of my `functions.php` file before the closing `?>`. * Yes this form exists and functions correctly on other pages. * I've looked at the the other posts here regarding page-conditional PHP functions and none of them address this issue. * Per the Gravity Forms documentation, I'm not even getting the "Oops! We could not locate your form." error. There is absolutely zero output (as far as I can tell). Not visible changes to the page either. * I also looked through the posts under the little-used tag of [[page-specific-settings]](https://wordpress.stackexchange.com/questions/tagged/page-specific-settings).
Ok I figured it out. I just need to hook into `wp_footer`. The only thing that gets added to `header.php` is the `gravity_form_enqueue_scripts()` function. Per the documentation: > > This function will enqueue the necessary styles and scripts for the specified Gravity Form. This is useful when manually embedding a form outside the WordPress loop using the function call or to force the stylesheets and scripts to load in the header when using the Form Widget. > > > ``` function add_split_test_forms() { if (is_page([4904,2559,356,358,360,376,362,364,366,354,372,374])): gravity_form(19, false, false, false, '', false); endif; } add_action( 'wp_footer', 'add_split_test_forms' ); ``` **Edit:** Jacob suggested below that forms should never go in the `<head>` but rather in the footer. I've changed my answer to reflect that.
319,658
<p>I have modified the CSS on the admin and login pages. But the problem is that sometimes the custom CSS is loaded last, and this makes the change visible. The CSS can change during the loading of the page.</p> <p>Is there any way to edit the CSS before the page renders? I cannot edit the core and plugin files because I want to be able to update without breaking it.</p> <p>Any suggestions?</p>
[ { "answer_id": 319659, "author": "coolpasta", "author_id": 143406, "author_profile": "https://wordpress.stackexchange.com/users/143406", "pm_score": 0, "selected": false, "text": "<p>You have to open up the place where you're generating that CSS, this could be complex or simple. It all depends on how you decide to generate your CSS based on business logic.</p>\n\n<p>I have no idea how you're loading your CSS, regardless, here's how I do it - first, create your page:</p>\n\n<pre><code>public function addAdminMenuPage()\n{\n $this-&gt;hook_suffix = add_theme_page(\n esc_html__( 'Page Title', 'my-project' ),\n esc_html__( 'Page Title', 'my-project' ),\n 'manage_options', 'my-page-handle',\n [ $this, 'myPageContent' ]\n );\n}\nadd_action( 'admin_menu', [$this, 'addAdminMenuPage' ], 80 );\n</code></pre>\n\n<p>Then, <strong>enqueue its CSS completely based on the suffix, making sure that your CSS only loads on that page, in the correct order:</strong></p>\n\n<pre><code>public function generatePageCSS( $page )\n{\n //Very important, will only load your CSS on the right page, not in all the admin area.\n if( !$page == $this-&gt;hook_suffix ) {\n return;\n }\n //This will allow you to keep a lot of the logic in different parts.\n do_action( 'page-' . $page . '-css', $page );\n}\n\nadd_action( 'admin_enqueue_scripts', [$this, 'enqueuePageCSS'] );\n</code></pre>\n\n<p>This means that for all your CSS logic, you'll be using the <code>page-my-page-handle-css</code>, it could be multiple enqueues of CSS, inline writes to the page and so on. But now you got all the CSS that's to come set in the right order, which seems to have been your original issue.</p>\n\n<p>So, you're adding your page on the <code>admin_menu</code> hook, then, you enqueue your scripts on the <code>admin_enqueue_scripts</code> hook with checking if the generated suffix from that <code>add_theme_page</code> matches the current page title that's passed down from <code>admin_enqueue_scripts</code>, your \"main class\" to run this would be:</p>\n\n<pre><code>class MyAdminPage\n{\n public function __construct()\n {\n add_action( 'admin_menu', [$this, 'addAdminMenuPage' ], 80 );\n add_action( 'admin_enqueue_scripts', [$this, 'enqueuePageCSS'] );\n }\n ..\n ..\n //Here you'll put the hooking functions\n ..\n ..\n}\n</code></pre>\n\n<p>And, again, as long as you keep that <code>generatePageCSS</code> \"open\" with hooks, probably, you're good to go.</p>\n" }, { "answer_id": 319660, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>What theme are you using?</p>\n\n<p>I would probably start with making a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a>. This will give you more control over when styles are loaded. Here is an example of loading the parent theme styles and then your child theme styles.</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n\n<p>If you need to add styles specifically for the admin area you can enqueue styles like this...</p>\n\n<pre><code>function my_admin_styles(){\n wp_enqueue_style(\n 'admin_css', \n get_stylesheet_directory_uri() . '/css/my-admin.css', array(), filemtime( get_stylesheet_directory() . '/css/my-admin.css') \n );\n}\n\nadd_action('admin_enqueue_scripts', 'my_admin_styles');\n</code></pre>\n\n<p>The above code would go in your child theme's functions.php.</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319658", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143279/" ]
I have modified the CSS on the admin and login pages. But the problem is that sometimes the custom CSS is loaded last, and this makes the change visible. The CSS can change during the loading of the page. Is there any way to edit the CSS before the page renders? I cannot edit the core and plugin files because I want to be able to update without breaking it. Any suggestions?
What theme are you using? I would probably start with making a [child theme](https://codex.wordpress.org/Child_Themes). This will give you more control over when styles are loaded. Here is an example of loading the parent theme styles and then your child theme styles. ``` function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ``` If you need to add styles specifically for the admin area you can enqueue styles like this... ``` function my_admin_styles(){ wp_enqueue_style( 'admin_css', get_stylesheet_directory_uri() . '/css/my-admin.css', array(), filemtime( get_stylesheet_directory() . '/css/my-admin.css') ); } add_action('admin_enqueue_scripts', 'my_admin_styles'); ``` The above code would go in your child theme's functions.php.
319,667
<p>I am using PowerMag 2.5 as parent and can't seem to find a way to get a working child theme. As far as I am now, I can only extend css in the style.css but as far as overriding, nothing has worked. When I copy over e.g. the header.php from parent to child and make some edits to the code it does not work. The very big functions.php from the parent theme is overwhelming me and I do not know how to get it working.</p> <p><strong>child > style.css</strong></p> <pre><code>/* Theme Name: PowerMag Child Theme URI: https://themeforest.net/item/powermag-the-most-muscular-magazinereviews-theme/4740939 Description: PowerMag Child Theme Author: djwd Author URI: http://themeforest.net/user/djwd Template: powermag Version: 1.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: dark,light,three-columns,two-columns,left-sidebar,right-sidebar,featured-image-header,featured-images,full-width-template,rtl-language-support,sticky-post,theme-options,threaded-comments,translation-ready,post-formats,custom-menu,custom-background,flexible-width Text Domain: powermag-child */ </code></pre> <p><strong>child > functions.php</strong></p> <pre><code>&lt;?php // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } </code></pre> <p><strong>parent > functions.php</strong></p> <p>The file is to big for posting so I uploaded it <a href="http://s000.tinyupload.com/index.php?file_id=46948101599565413452" rel="nofollow noreferrer">here</a></p>
[ { "answer_id": 319659, "author": "coolpasta", "author_id": 143406, "author_profile": "https://wordpress.stackexchange.com/users/143406", "pm_score": 0, "selected": false, "text": "<p>You have to open up the place where you're generating that CSS, this could be complex or simple. It all depends on how you decide to generate your CSS based on business logic.</p>\n\n<p>I have no idea how you're loading your CSS, regardless, here's how I do it - first, create your page:</p>\n\n<pre><code>public function addAdminMenuPage()\n{\n $this-&gt;hook_suffix = add_theme_page(\n esc_html__( 'Page Title', 'my-project' ),\n esc_html__( 'Page Title', 'my-project' ),\n 'manage_options', 'my-page-handle',\n [ $this, 'myPageContent' ]\n );\n}\nadd_action( 'admin_menu', [$this, 'addAdminMenuPage' ], 80 );\n</code></pre>\n\n<p>Then, <strong>enqueue its CSS completely based on the suffix, making sure that your CSS only loads on that page, in the correct order:</strong></p>\n\n<pre><code>public function generatePageCSS( $page )\n{\n //Very important, will only load your CSS on the right page, not in all the admin area.\n if( !$page == $this-&gt;hook_suffix ) {\n return;\n }\n //This will allow you to keep a lot of the logic in different parts.\n do_action( 'page-' . $page . '-css', $page );\n}\n\nadd_action( 'admin_enqueue_scripts', [$this, 'enqueuePageCSS'] );\n</code></pre>\n\n<p>This means that for all your CSS logic, you'll be using the <code>page-my-page-handle-css</code>, it could be multiple enqueues of CSS, inline writes to the page and so on. But now you got all the CSS that's to come set in the right order, which seems to have been your original issue.</p>\n\n<p>So, you're adding your page on the <code>admin_menu</code> hook, then, you enqueue your scripts on the <code>admin_enqueue_scripts</code> hook with checking if the generated suffix from that <code>add_theme_page</code> matches the current page title that's passed down from <code>admin_enqueue_scripts</code>, your \"main class\" to run this would be:</p>\n\n<pre><code>class MyAdminPage\n{\n public function __construct()\n {\n add_action( 'admin_menu', [$this, 'addAdminMenuPage' ], 80 );\n add_action( 'admin_enqueue_scripts', [$this, 'enqueuePageCSS'] );\n }\n ..\n ..\n //Here you'll put the hooking functions\n ..\n ..\n}\n</code></pre>\n\n<p>And, again, as long as you keep that <code>generatePageCSS</code> \"open\" with hooks, probably, you're good to go.</p>\n" }, { "answer_id": 319660, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>What theme are you using?</p>\n\n<p>I would probably start with making a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a>. This will give you more control over when styles are loaded. Here is an example of loading the parent theme styles and then your child theme styles.</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n\n<p>If you need to add styles specifically for the admin area you can enqueue styles like this...</p>\n\n<pre><code>function my_admin_styles(){\n wp_enqueue_style(\n 'admin_css', \n get_stylesheet_directory_uri() . '/css/my-admin.css', array(), filemtime( get_stylesheet_directory() . '/css/my-admin.css') \n );\n}\n\nadd_action('admin_enqueue_scripts', 'my_admin_styles');\n</code></pre>\n\n<p>The above code would go in your child theme's functions.php.</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154358/" ]
I am using PowerMag 2.5 as parent and can't seem to find a way to get a working child theme. As far as I am now, I can only extend css in the style.css but as far as overriding, nothing has worked. When I copy over e.g. the header.php from parent to child and make some edits to the code it does not work. The very big functions.php from the parent theme is overwhelming me and I do not know how to get it working. **child > style.css** ``` /* Theme Name: PowerMag Child Theme URI: https://themeforest.net/item/powermag-the-most-muscular-magazinereviews-theme/4740939 Description: PowerMag Child Theme Author: djwd Author URI: http://themeforest.net/user/djwd Template: powermag Version: 1.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: dark,light,three-columns,two-columns,left-sidebar,right-sidebar,featured-image-header,featured-images,full-width-template,rtl-language-support,sticky-post,theme-options,threaded-comments,translation-ready,post-formats,custom-menu,custom-background,flexible-width Text Domain: powermag-child */ ``` **child > functions.php** ``` <?php // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' ); function enqueue_parent_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } ``` **parent > functions.php** The file is to big for posting so I uploaded it [here](http://s000.tinyupload.com/index.php?file_id=46948101599565413452)
What theme are you using? I would probably start with making a [child theme](https://codex.wordpress.org/Child_Themes). This will give you more control over when styles are loaded. Here is an example of loading the parent theme styles and then your child theme styles. ``` function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ``` If you need to add styles specifically for the admin area you can enqueue styles like this... ``` function my_admin_styles(){ wp_enqueue_style( 'admin_css', get_stylesheet_directory_uri() . '/css/my-admin.css', array(), filemtime( get_stylesheet_directory() . '/css/my-admin.css') ); } add_action('admin_enqueue_scripts', 'my_admin_styles'); ``` The above code would go in your child theme's functions.php.
319,672
<p>I'm trying to sort custom posts in alphabetical order, and I've just now realized that capital letters are being sorted before lowercase. Two restaurants start with 'Cal' and 'CAT' with 'CAT' being returned as the first in alphabetical order.</p> <p>Here're my $args:</p> <pre><code>$args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'chef', 'meta_key' =&gt; 'restaurant', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'ASC' ); </code></pre> <p>I've also tried changing the 'orderby' to 'LOWER(restaurant)' but had no success with that.</p>
[ { "answer_id": 319659, "author": "coolpasta", "author_id": 143406, "author_profile": "https://wordpress.stackexchange.com/users/143406", "pm_score": 0, "selected": false, "text": "<p>You have to open up the place where you're generating that CSS, this could be complex or simple. It all depends on how you decide to generate your CSS based on business logic.</p>\n\n<p>I have no idea how you're loading your CSS, regardless, here's how I do it - first, create your page:</p>\n\n<pre><code>public function addAdminMenuPage()\n{\n $this-&gt;hook_suffix = add_theme_page(\n esc_html__( 'Page Title', 'my-project' ),\n esc_html__( 'Page Title', 'my-project' ),\n 'manage_options', 'my-page-handle',\n [ $this, 'myPageContent' ]\n );\n}\nadd_action( 'admin_menu', [$this, 'addAdminMenuPage' ], 80 );\n</code></pre>\n\n<p>Then, <strong>enqueue its CSS completely based on the suffix, making sure that your CSS only loads on that page, in the correct order:</strong></p>\n\n<pre><code>public function generatePageCSS( $page )\n{\n //Very important, will only load your CSS on the right page, not in all the admin area.\n if( !$page == $this-&gt;hook_suffix ) {\n return;\n }\n //This will allow you to keep a lot of the logic in different parts.\n do_action( 'page-' . $page . '-css', $page );\n}\n\nadd_action( 'admin_enqueue_scripts', [$this, 'enqueuePageCSS'] );\n</code></pre>\n\n<p>This means that for all your CSS logic, you'll be using the <code>page-my-page-handle-css</code>, it could be multiple enqueues of CSS, inline writes to the page and so on. But now you got all the CSS that's to come set in the right order, which seems to have been your original issue.</p>\n\n<p>So, you're adding your page on the <code>admin_menu</code> hook, then, you enqueue your scripts on the <code>admin_enqueue_scripts</code> hook with checking if the generated suffix from that <code>add_theme_page</code> matches the current page title that's passed down from <code>admin_enqueue_scripts</code>, your \"main class\" to run this would be:</p>\n\n<pre><code>class MyAdminPage\n{\n public function __construct()\n {\n add_action( 'admin_menu', [$this, 'addAdminMenuPage' ], 80 );\n add_action( 'admin_enqueue_scripts', [$this, 'enqueuePageCSS'] );\n }\n ..\n ..\n //Here you'll put the hooking functions\n ..\n ..\n}\n</code></pre>\n\n<p>And, again, as long as you keep that <code>generatePageCSS</code> \"open\" with hooks, probably, you're good to go.</p>\n" }, { "answer_id": 319660, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>What theme are you using?</p>\n\n<p>I would probably start with making a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a>. This will give you more control over when styles are loaded. Here is an example of loading the parent theme styles and then your child theme styles.</p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n</code></pre>\n\n<p>If you need to add styles specifically for the admin area you can enqueue styles like this...</p>\n\n<pre><code>function my_admin_styles(){\n wp_enqueue_style(\n 'admin_css', \n get_stylesheet_directory_uri() . '/css/my-admin.css', array(), filemtime( get_stylesheet_directory() . '/css/my-admin.css') \n );\n}\n\nadd_action('admin_enqueue_scripts', 'my_admin_styles');\n</code></pre>\n\n<p>The above code would go in your child theme's functions.php.</p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319672", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43473/" ]
I'm trying to sort custom posts in alphabetical order, and I've just now realized that capital letters are being sorted before lowercase. Two restaurants start with 'Cal' and 'CAT' with 'CAT' being returned as the first in alphabetical order. Here're my $args: ``` $args = array( 'numberposts' => -1, 'post_type' => 'chef', 'meta_key' => 'restaurant', 'orderby' => 'meta_value', 'order' => 'ASC' ); ``` I've also tried changing the 'orderby' to 'LOWER(restaurant)' but had no success with that.
What theme are you using? I would probably start with making a [child theme](https://codex.wordpress.org/Child_Themes). This will give you more control over when styles are loaded. Here is an example of loading the parent theme styles and then your child theme styles. ``` function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ``` If you need to add styles specifically for the admin area you can enqueue styles like this... ``` function my_admin_styles(){ wp_enqueue_style( 'admin_css', get_stylesheet_directory_uri() . '/css/my-admin.css', array(), filemtime( get_stylesheet_directory() . '/css/my-admin.css') ); } add_action('admin_enqueue_scripts', 'my_admin_styles'); ``` The above code would go in your child theme's functions.php.
319,677
<p>I was in process of deploying my wordpress website <code>mysite.com/NewSite</code> to <code>mysite.com</code> during the deployment I messed up something and my main site has started redirecting from <code>mysite.com</code> to <code>mysite.com/NewSite</code>.</p> <p>I have deleted everything from root folder, checked cpanel redirects section etc but everything looks fine. I also created <code>.htaccess</code> file under public_html folder but still no luck.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I know this more kind of a descriptive question. This is kind of super urgent as site is down which an issue. You help is required.</p>
[ { "answer_id": 319681, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>According to the Codex instructions:</p>\n\n<p><a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a></p>\n\n<p>If you add these defines to your wp-config.php</p>\n\n<pre><code>define( 'WP_HOME', 'http://example.com' );\ndefine( 'WP_SITEURL', 'http://example.com' );\n</code></pre>\n\n<p>These will override the options saved in your <code>wp_options</code> table, you should then remove the /NewSite suffix from your General Settings page. (Or if wp-admin is accessible now you may be able to just do that already.)</p>\n\n<p>Alternatively you could edit the database directly and change the <code>home</code> and <code>siteurl</code> values in <code>wp_options</code> and that will achieve the same thing.</p>\n" }, { "answer_id": 319687, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I've never liked changing the domain name within the wp-settings.php file. I always change it directly in the wp-options table (in two places)...since that is where it will be defined (and read from in Settings). My theory is why not change it in the original spot (the wp-options table) rather than adjusting the values in the wp-settings file.</p>\n\n<p>So, my first thing would be to remove those values from wp-config.php, then make sure the proper URL is in the wp-options table. And then to use a standard htaccess file according to the codex. Make sure you supply the full URL, with the protocol (as in <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> ).</p>\n\n<p>Changing the permanlinks value will sometimes rewrite the htaccess file, but I always just use the standard htaccess from the Codex. </p>\n" } ]
2018/11/19
[ "https://wordpress.stackexchange.com/questions/319677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47833/" ]
I was in process of deploying my wordpress website `mysite.com/NewSite` to `mysite.com` during the deployment I messed up something and my main site has started redirecting from `mysite.com` to `mysite.com/NewSite`. I have deleted everything from root folder, checked cpanel redirects section etc but everything looks fine. I also created `.htaccess` file under public\_html folder but still no luck. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` I know this more kind of a descriptive question. This is kind of super urgent as site is down which an issue. You help is required.
According to the Codex instructions: <https://codex.wordpress.org/Changing_The_Site_URL> If you add these defines to your wp-config.php ``` define( 'WP_HOME', 'http://example.com' ); define( 'WP_SITEURL', 'http://example.com' ); ``` These will override the options saved in your `wp_options` table, you should then remove the /NewSite suffix from your General Settings page. (Or if wp-admin is accessible now you may be able to just do that already.) Alternatively you could edit the database directly and change the `home` and `siteurl` values in `wp_options` and that will achieve the same thing.
319,690
<p>I am looking to replace a few text strings for only two specific pages on a wordpress site. It should not affect those strings on any other pages. I'd prefer to do this via adding some code to functions.php</p> <p>I think using part of this code would be the first part, just need help with the rest <a href="https://wordpress.stackexchange.com/a/278357">https://wordpress.stackexchange.com/a/278357</a></p>
[ { "answer_id": 319694, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 0, "selected": false, "text": "<p><strong>Some Example Here is how to replace all instances of a string in WordPress.\nJust add the following code to your theme’s functions.php file:</strong></p>\n<pre><code>function replace_text($text) {\n $text = str_replace('look-for-this-string', 'replace-with-this-string', $text);\n $text = str_replace('look-for-that-string', 'replace-with-that-string', $text);\n return $text;\n} \nadd_filter('the_content', 'replace_text');\n</code></pre>\n<p>More info on <a href=\"http://php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.str-replace.php</a></p>\n" }, { "answer_id": 372164, "author": "Bhagyashree Vaidya", "author_id": 180237, "author_profile": "https://wordpress.stackexchange.com/users/180237", "pm_score": 0, "selected": false, "text": "<p>I have run through the same issue from past 18 hours. I had tried multiple permutations and combinations of codes and finally, this worked for me. Put this code in the Appearance &gt;&gt; Theme Editor &gt;&gt; <code>functions.php</code> fie:</p>\n<pre><code>function replace_text( $text ) {\n if( is_page( 1709 ) ) {\n $text = str_replace('old_text', 'new_text', $text);\n $text = str_replace('old_text', 'new_text', $text);\n }\n\nreturn $text;\n}\n\nadd_filter('the_content', 'replace_text');\n</code></pre>\n<ul>\n<li><code>old_text</code> is the text you want to replace and <code>new_text</code> you want to replace it with.</li>\n<li>To determine the id, please edit the page, you will find the id in the URL.</li>\n</ul>\n" }, { "answer_id": 381178, "author": "dylzee", "author_id": 190737, "author_profile": "https://wordpress.stackexchange.com/users/190737", "pm_score": 1, "selected": false, "text": "<p>I can't comment so I'll answer and slightly adjust Bhagyashree's which is exactly what you'll need to do based on your question. Except you may want to know how to include the 2 pages rather than duplicating the function. And also passing in an array of strings to replace.</p>\n<pre><code>function replace_some_text( $content ) {\n \n // Notice the || we're saying if is page1 OR page2. Also changed to is_single.\n if( is_single( 2020 ) || is_single( 2021 ) {\n\n $text_strings_to_replace = array( 'first_string', 'second_string', 'third_string_to_replace' );\n\n $content = str_replace( $text_strings_to_replace, 'new_text', $content );\n \n}\n\n return $content;\n}\n\nadd_filter('the_content', 'replace_some_text');\n</code></pre>\n<p>Little explanation. Basically, we hook into a WordPress filter hook <code>[add_filter][1]</code> that allows us to filter all the content on the page.</p>\n<p>We filter the $content inside our function, in this case using a PHP function <code>[str_replace][1]</code> to search the content for our array of strings and replace them with 'new_text'.</p>\n" } ]
2018/11/20
[ "https://wordpress.stackexchange.com/questions/319690", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136330/" ]
I am looking to replace a few text strings for only two specific pages on a wordpress site. It should not affect those strings on any other pages. I'd prefer to do this via adding some code to functions.php I think using part of this code would be the first part, just need help with the rest <https://wordpress.stackexchange.com/a/278357>
I can't comment so I'll answer and slightly adjust Bhagyashree's which is exactly what you'll need to do based on your question. Except you may want to know how to include the 2 pages rather than duplicating the function. And also passing in an array of strings to replace. ``` function replace_some_text( $content ) { // Notice the || we're saying if is page1 OR page2. Also changed to is_single. if( is_single( 2020 ) || is_single( 2021 ) { $text_strings_to_replace = array( 'first_string', 'second_string', 'third_string_to_replace' ); $content = str_replace( $text_strings_to_replace, 'new_text', $content ); } return $content; } add_filter('the_content', 'replace_some_text'); ``` Little explanation. Basically, we hook into a WordPress filter hook `[add_filter][1]` that allows us to filter all the content on the page. We filter the $content inside our function, in this case using a PHP function `[str_replace][1]` to search the content for our array of strings and replace them with 'new\_text'.
319,744
<p>Travis is giving me ~ <strong>Assignments must be the first block of code on a line</strong> for this specific line of code: </p> <pre><code>$validate_string = $pf_param_string = substr( $pf_param_string, 0, - 1 ); </code></pre> <p>It seems fine to me or am I doing the assignments wrong?</p>
[ { "answer_id": 319745, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>According to <a href=\"https://stackoverflow.com/questions/46579215/how-to-fix-assignments-must-be-the-first-block-of-code-on-a-line\">this answer on StackOverflow</a>, it could be the problem with multiple assignments in one line. Refactoring to</p>\n\n<pre><code>$validate_string = substr( $pf_param_string, 0, - 1 );\n$pf_param_string = $validate_string;\n</code></pre>\n\n<p>should solve this.</p>\n" }, { "answer_id": 319746, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You're not supposed to assign multiple variables on a single line. Do them separately:</p>\n\n<pre><code>$pf_param_string = substr( $pf_param_string, 0, - 1 );\n$validate_string = $pf_param_string;\n</code></pre>\n\n<p>Or, if you don't need both variables, just skip one of them:</p>\n\n<pre><code>$validate_string = substr( $pf_param_string, 0, - 1 );\n</code></pre>\n" } ]
2018/11/20
[ "https://wordpress.stackexchange.com/questions/319744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136971/" ]
Travis is giving me ~ **Assignments must be the first block of code on a line** for this specific line of code: ``` $validate_string = $pf_param_string = substr( $pf_param_string, 0, - 1 ); ``` It seems fine to me or am I doing the assignments wrong?
You're not supposed to assign multiple variables on a single line. Do them separately: ``` $pf_param_string = substr( $pf_param_string, 0, - 1 ); $validate_string = $pf_param_string; ``` Or, if you don't need both variables, just skip one of them: ``` $validate_string = substr( $pf_param_string, 0, - 1 ); ```
319,770
<p>I am developing a Woocommerce dependent plugin which works, and a settings page which behaves funky and throws a Class 'WC_Settings_Page' not found Fatal Error</p> <pre><code>if ( !defined( 'ABSPATH' ) ) {exit;} if ( !class_exists( 'WooCommerce_Chilexpress_Tags_Settings' ) ) { class WooCommerce_Chilexpress_Tags_Settings extends WC_Settings_Page{ ... } function my_plugin_add_settings() { return new WooCommerce_Chilexpress_Tags_Settings(); } } add_filter( 'woocommerce_get_settings_pages', 'my_plugin_add_settings', 15 ); </code></pre> <p>this code is in a includes/mysettings.php which is loaded during the plugin init, which alphabetically is woocommerce-chilexpress-etiquetas, so it should be loaded after woocommerce</p> <p>For a reason I don't understand yet, my plugin settings are loaded always before WooCommerce Settings though throwing me a PHP Fatal Error:</p> <pre><code>PHP Fatal error: Class 'WC_Settings_Page' not found </code></pre> <p>The obvious dirty fix was to insert the WC_Settings_Page code into my own settings. I am trying now to clean this up but somehow it won't work...</p> <p>So the (yes I know very broad) question is: What could I miss?</p>
[ { "answer_id": 319792, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 2, "selected": false, "text": "<p>See working example: <a href=\"https://gist.github.com/bekarice/34aaeda2d4729ef87ad7\" rel=\"nofollow noreferrer\">https://gist.github.com/bekarice/34aaeda2d4729ef87ad7</a> <br>\nYou should do something like this:</p>\n\n<pre><code>// If this file is called directly, abort.\ndefined('ABSPATH') or exit();\n\n\nif ( !class_exists( 'WooCommerce_Chilexpress_Tags_Settings' ) ) {\n\n function my_plugin_add_settings() {\n\n class WooCommerce_Chilexpress_Tags_Settings extends WC_Settings_Page {\n // Your class and your code / logic \n }\n\n return new WooCommerce_Chilexpress_Tags_Settings();\n\n }\n\n add_filter( 'woocommerce_get_settings_pages', 'my_plugin_add_settings', 15 );\n\n}\n</code></pre>\n" }, { "answer_id": 319793, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The problem is, by the time your <code>WooCommerce_Chilexpress_Tags_Settings</code> is defined, <code>WC_Settings_Page</code> has indeed not yet loaded; hence you got the fatal error.</p>\n\n<p>And if you want to do it the same way that WooCommerce does it, place the <code>WooCommerce_Chilexpress_Tags_Settings</code> in a separate PHP file, e.g. <code>includes/class-woocommerce-chilexpress-tags-tettings.php</code>, and initialize the class from that file &mdash; i.e. <code>return</code> an instance of <code>WooCommerce_Chilexpress_Tags_Settings</code> like so:</p>\n\n<pre><code>&lt;?php\n// class-woocommerce-chilexpress-tags-tettings.php\n\ndefined( 'ABSPATH' ) || exit;\n\nclass WooCommerce_Chilexpress_Tags_Settings extends WC_Settings_Page {\n\n ...\n}\n\nreturn new WooCommerce_Chilexpress_Tags_Settings();\n</code></pre>\n\n<p>and <code>include</code> it from <code>my_plugin_add_settings()</code>:</p>\n\n<pre><code>function my_plugin_add_settings( $settings ) {\n $settings[] = include 'path/to/includes/class-woocommerce-chilexpress-tags-tettings.php';\n\n return $settings;\n}\nadd_filter( 'woocommerce_get_settings_pages', 'my_plugin_add_settings' );\n</code></pre>\n\n<p><em>And if you noticed, you need to return the <code>$settings</code> from <code>my_plugin_add_settings()</code>.</em></p>\n" } ]
2018/11/20
[ "https://wordpress.stackexchange.com/questions/319770", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114144/" ]
I am developing a Woocommerce dependent plugin which works, and a settings page which behaves funky and throws a Class 'WC\_Settings\_Page' not found Fatal Error ``` if ( !defined( 'ABSPATH' ) ) {exit;} if ( !class_exists( 'WooCommerce_Chilexpress_Tags_Settings' ) ) { class WooCommerce_Chilexpress_Tags_Settings extends WC_Settings_Page{ ... } function my_plugin_add_settings() { return new WooCommerce_Chilexpress_Tags_Settings(); } } add_filter( 'woocommerce_get_settings_pages', 'my_plugin_add_settings', 15 ); ``` this code is in a includes/mysettings.php which is loaded during the plugin init, which alphabetically is woocommerce-chilexpress-etiquetas, so it should be loaded after woocommerce For a reason I don't understand yet, my plugin settings are loaded always before WooCommerce Settings though throwing me a PHP Fatal Error: ``` PHP Fatal error: Class 'WC_Settings_Page' not found ``` The obvious dirty fix was to insert the WC\_Settings\_Page code into my own settings. I am trying now to clean this up but somehow it won't work... So the (yes I know very broad) question is: What could I miss?
The problem is, by the time your `WooCommerce_Chilexpress_Tags_Settings` is defined, `WC_Settings_Page` has indeed not yet loaded; hence you got the fatal error. And if you want to do it the same way that WooCommerce does it, place the `WooCommerce_Chilexpress_Tags_Settings` in a separate PHP file, e.g. `includes/class-woocommerce-chilexpress-tags-tettings.php`, and initialize the class from that file — i.e. `return` an instance of `WooCommerce_Chilexpress_Tags_Settings` like so: ``` <?php // class-woocommerce-chilexpress-tags-tettings.php defined( 'ABSPATH' ) || exit; class WooCommerce_Chilexpress_Tags_Settings extends WC_Settings_Page { ... } return new WooCommerce_Chilexpress_Tags_Settings(); ``` and `include` it from `my_plugin_add_settings()`: ``` function my_plugin_add_settings( $settings ) { $settings[] = include 'path/to/includes/class-woocommerce-chilexpress-tags-tettings.php'; return $settings; } add_filter( 'woocommerce_get_settings_pages', 'my_plugin_add_settings' ); ``` *And if you noticed, you need to return the `$settings` from `my_plugin_add_settings()`.*
319,775
<p>I'm looping through all users with</p> <pre><code>$allusers = get_users($args); foreach ( $allusers as $user ): </code></pre> <p>And then I have an email user button (firstname and lastname are inserted into the subject), and a callback button (firstname and lastname are inserted into a hidden Contact Form 7 field)</p> <p>The email link in my template is:</p> <pre><code>&lt;a href="mailto:[email protected]?subject=&lt;?php echo $user-&gt;first_name; ?&gt; &lt;?php echo $user-&gt;last_name; ?&gt;"&gt;Email&lt;/a&gt; </code></pre> <p>This works fine; it shows the correct user firstname and lastname in the loop. But the contact form field shows the last user in the loop, not the current one. This is what I have in my template: </p> <pre><code>&lt;script type="text/javascript"&gt; jQuery(document).ready(function($) { $('.callback').val('&lt;?php echo $user-&gt;first_name; ?&gt; &lt;?php echo $user-&gt;last_name; ?&gt;'); }); &lt;/script&gt; &lt;?php echo do_shortcode( '[contact-form-7 id="12345"]' ); ?&gt; </code></pre> <p>I have used this for inserting a variable into a Contact Form 7: <a href="https://stackoverflow.com/questions/22943559/include-php-variable-in-contact-form-7-field">https://stackoverflow.com/questions/22943559/include-php-variable-in-contact-form-7-field</a></p> <p>Why is my callback form variable displaying a different result to the email link variable, and how can I fix it?</p>
[ { "answer_id": 319785, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<p>I've only seen some parts of your code, but I guess I know where the problem lies... </p>\n\n<p>If this is what you're printing in the loop:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\njQuery(document).ready(function($) {\n $('.callback').val('&lt;?php echo $user-&gt;first_name; ?&gt; &lt;?php echo $user-&gt;last_name; ?&gt;');\n});\n&lt;/script&gt;\n&lt;?php echo do_shortcode( '[contact-form-7 id=\"12345\"]' ); ?&gt;\n</code></pre>\n\n<p>And you want to output multiple forms on the same page and every form should contain different user, then you can't do it like that. Why? Because of this part:</p>\n\n<pre><code>$('.callback')\n</code></pre>\n\n<p>Your forms and JS code is printed by PHP and everything works fine. But then, the JS is run ono the client-side in client browser, when the page is loaded. So the first JS code runs, selects all elements with class \"callback\" and sets its value. Then the second one runs and sets value of all \"callback\"s again... And so on... </p>\n\n<h2>So how to deal with that?</h2>\n\n<p>One way to do this, the easiest fix, would be wrapping forms with div:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\njQuery(document).ready(function($) {\n $('.callback', '#user-form-&lt;?php echo $user-&gt;ID; ?&gt;').val('&lt;?php echo $user-&gt;first_name; ?&gt; &lt;?php echo $user-&gt;last_name; ?&gt;');\n});\n&lt;/script&gt;\n&lt;div id=\"user-form-&lt;?php echo $user-&gt;ID; ?&gt;\"&gt;\n &lt;?php echo do_shortcode( '[contact-form-7 id=\"12345\"]' ); ?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>This way you can identify every form and set the fields inside that form only.</p>\n" }, { "answer_id": 319791, "author": "Ryan Hoover", "author_id": 104462, "author_profile": "https://wordpress.stackexchange.com/users/104462", "pm_score": 0, "selected": false, "text": "<p>If <code>get_users()</code> is returning results in a different order depending on when you call it, most likely something is changing the default <code>order</code> and <code>orderby</code> parameters.</p>\n\n<p>I'd specifically declare them to ensure that you get the same order every time. In your <code>$args</code>, add</p>\n\n<pre><code>$args = [\n ....\n 'orderby' =&gt; 'login',\n 'order' =&gt; 'ASC',\n];\n</code></pre>\n" } ]
2018/11/20
[ "https://wordpress.stackexchange.com/questions/319775", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111367/" ]
I'm looping through all users with ``` $allusers = get_users($args); foreach ( $allusers as $user ): ``` And then I have an email user button (firstname and lastname are inserted into the subject), and a callback button (firstname and lastname are inserted into a hidden Contact Form 7 field) The email link in my template is: ``` <a href="mailto:[email protected]?subject=<?php echo $user->first_name; ?> <?php echo $user->last_name; ?>">Email</a> ``` This works fine; it shows the correct user firstname and lastname in the loop. But the contact form field shows the last user in the loop, not the current one. This is what I have in my template: ``` <script type="text/javascript"> jQuery(document).ready(function($) { $('.callback').val('<?php echo $user->first_name; ?> <?php echo $user->last_name; ?>'); }); </script> <?php echo do_shortcode( '[contact-form-7 id="12345"]' ); ?> ``` I have used this for inserting a variable into a Contact Form 7: <https://stackoverflow.com/questions/22943559/include-php-variable-in-contact-form-7-field> Why is my callback form variable displaying a different result to the email link variable, and how can I fix it?
I've only seen some parts of your code, but I guess I know where the problem lies... If this is what you're printing in the loop: ``` <script type="text/javascript"> jQuery(document).ready(function($) { $('.callback').val('<?php echo $user->first_name; ?> <?php echo $user->last_name; ?>'); }); </script> <?php echo do_shortcode( '[contact-form-7 id="12345"]' ); ?> ``` And you want to output multiple forms on the same page and every form should contain different user, then you can't do it like that. Why? Because of this part: ``` $('.callback') ``` Your forms and JS code is printed by PHP and everything works fine. But then, the JS is run ono the client-side in client browser, when the page is loaded. So the first JS code runs, selects all elements with class "callback" and sets its value. Then the second one runs and sets value of all "callback"s again... And so on... So how to deal with that? ------------------------- One way to do this, the easiest fix, would be wrapping forms with div: ``` <script type="text/javascript"> jQuery(document).ready(function($) { $('.callback', '#user-form-<?php echo $user->ID; ?>').val('<?php echo $user->first_name; ?> <?php echo $user->last_name; ?>'); }); </script> <div id="user-form-<?php echo $user->ID; ?>"> <?php echo do_shortcode( '[contact-form-7 id="12345"]' ); ?> </div> ``` This way you can identify every form and set the fields inside that form only.
319,794
<p>I have a strange problem, when I try to enter the source of an image tag using PHP it shows me the following error in the inspector</p> <pre><code>&lt;img src=(unknown) alt=""&gt; </code></pre> <p>this code fragment gives me the correct url, checked by seeing the CPanel and pasting and copying the address,but when I try to enter it via php the image is not shown</p> <pre><code>$image = wp_get_attachment_image_src( $post_thumbnail_id); //echo($image[0]); ?&gt; &lt;img src="&lt;?php $image[0]; ?&gt;" alt=""&gt; </code></pre> <p>The next thing I did was an echo of image[0] and it gave me the url of the image, I copied it and pasted it in the tag and that's when it showed me the image</p> <pre><code>&lt;img src="mysite.com/wp-content/uploads/2018/11/957a...150x150.jpg" alt=""&gt; </code></pre> <p>I saw the page in Incognito Window and I did not show the image either.</p> <p>Any clues?</p>
[ { "answer_id": 319795, "author": "Carlos Longarela", "author_id": 141152, "author_profile": "https://wordpress.stackexchange.com/users/141152", "pm_score": 1, "selected": true, "text": "<p>I think that you need echo the image, try this:</p>\n\n<pre><code>&lt;php\n$image = wp_get_attachment_image_src( $post_thumbnail_id ); \n//echo( $image[0] );\n?&gt;\n&lt;img src=\"&lt;?php echo $image[0]; ?&gt;\" alt=\"\"&gt;\n</code></pre>\n" }, { "answer_id": 319797, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>If you only want the URL of the image, use <code>wp_get_attachment_image_url()</code>. It saves you having to do the <code>[0]</code> thing:</p>\n\n<pre><code>&lt;img src=\"&lt;?php echo wp_get_attachment_image_url( $post_thumbnail_id ); ?&gt;\" alt=\"\"&gt;\n</code></pre>\n\n<p>However, if you want to output an image tag for an attachment, you're much better off using <code>wp_get_attachment_image()</code>:</p>\n\n<pre><code>echo wp_get_attachment_image( $post_thumbnail_id, 'full' );\n</code></pre>\n\n<p>This will give you the full <code>&lt;img&gt;</code> tag, but including the alt text, width &amp; height attributes, and <code>srcset</code> attribute. The alt text in particular is important.</p>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319794", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154440/" ]
I have a strange problem, when I try to enter the source of an image tag using PHP it shows me the following error in the inspector ``` <img src=(unknown) alt=""> ``` this code fragment gives me the correct url, checked by seeing the CPanel and pasting and copying the address,but when I try to enter it via php the image is not shown ``` $image = wp_get_attachment_image_src( $post_thumbnail_id); //echo($image[0]); ?> <img src="<?php $image[0]; ?>" alt=""> ``` The next thing I did was an echo of image[0] and it gave me the url of the image, I copied it and pasted it in the tag and that's when it showed me the image ``` <img src="mysite.com/wp-content/uploads/2018/11/957a...150x150.jpg" alt=""> ``` I saw the page in Incognito Window and I did not show the image either. Any clues?
I think that you need echo the image, try this: ``` <php $image = wp_get_attachment_image_src( $post_thumbnail_id ); //echo( $image[0] ); ?> <img src="<?php echo $image[0]; ?>" alt=""> ```
319,810
<p>So I went through the forum to find a solution before I post a question, however I have yet to find it. I'm new to wordpress and I'm having a lot of fun learning on how to build my own website. However I am unable to add my css to my website this the code I have below. </p> <p><strong>functions.php</strong></p> <pre><code>&lt;?php function fearnothing_script_enqueue(){ wp_enqueue_style("style", get_stylesheet_uri()."css/ fearnothing.css",false, 'all'); } add_action('wp_enqueue_scripts', 'fearnothing_script_enqueue'); </code></pre> <p><strong>header.php</strong> </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;lonely spaceship&lt;/title&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body&gt; </code></pre> <p></p> <p><strong>footer.php</strong></p> <pre><code> &lt;footer&gt; &lt;p&gt;&lt;/p&gt; &lt;/footer&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; </code></pre> <p></p> <p><strong>fearnothing.css</strong></p> <pre><code> html, body { margin: 0; color: #91f213; background-color:black; font: sans-serif; } body{ padding: 20px; } h1{ color: yellow; } </code></pre>
[ { "answer_id": 319814, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 3, "selected": true, "text": "<p>I don't know if you try to add a css file in your theme or plugin. I will provide both examples. Use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a> in combination with <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\">get_theme_file_uri</a> to enqueu a stylesheet in your theme directory.\n<br><br>\n<strong>For a theme, see example</strong></p>\n\n<pre><code>function add_styles() {\n wp_enqueue_style( 'fontawesome-style', get_theme_file_uri( '/assets/css/all.css' ), array(), null );\n}\nadd_action( 'wp_enqueue_scripts', 'add_styles' );\n</code></pre>\n\n<p><br>\n<strong>For a plugin, see example</strong></p>\n\n<pre><code>function add_styles() {\n wp_enqueue_style( 'example-styles-plugin', plugins_url('/assets/css/admin.css', __FILE__), array(), null );\n}\nadd_action( 'wp_enqueue_scripts', 'add_styles' );\n</code></pre>\n\n<p><br>\n<strong>For both, add an external URL:</strong></p>\n\n<pre><code>function add_styles() {\n // Add Google Fonts\n wp_enqueue_style('google_fonts', 'https://fonts.googleapis.com/css?family=Poppins:300,500,700', array(), null );\n}\nadd_action( 'wp_enqueue_scripts', 'add_styles' );\n</code></pre>\n" }, { "answer_id": 319815, "author": "Mahafuz", "author_id": 115945, "author_profile": "https://wordpress.stackexchange.com/users/115945", "pm_score": 1, "selected": false, "text": "<p>I'm glad to know that you are having fun learning and building your own websites.</p>\n\n<p>Here is the deal:\n<code>get_stylesheet_uri()</code> function returns the current theme stylesheet. It adds the style.css file from your current theme directory.</p>\n\n<p>The solution:\nIf you want to enqueue any kind of assets file like CSS or JS on your theme, you have to use get_template_directory_uri() functions instead of get_stylesheet_uri().</p>\n\n<p>Your code should be like this:</p>\n\n<pre><code>function fearnothing_script_enqueue(){\n wp_enqueue_style(\"style\", get_template_directory_uri().\"/assets-file/css/fearnothing.css\",false, 'all');\n\n\n}\n\nadd_action('wp_enqueue_scripts', 'fearnothing_script_enqueue');\n</code></pre>\n\n<p><code>get_template_directory_uri()</code> function Retrieve theme directory URI.\nFor more information, you might take a look on codex documentation <a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 360122, "author": "Ngonidzashe Gweje", "author_id": 183884, "author_profile": "https://wordpress.stackexchange.com/users/183884", "pm_score": 0, "selected": false, "text": "<pre><code>function add_styles() {\n wp_enqueue_style( 'fontawesome-style', get_theme_file_uri( '/assets/css/all.css' ), array(), null );\n}\nadd_action( 'wp_enqueue_scripts', 'add_styles' );\n</code></pre>\n\n<p>This is how i do it.</p>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319810", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
So I went through the forum to find a solution before I post a question, however I have yet to find it. I'm new to wordpress and I'm having a lot of fun learning on how to build my own website. However I am unable to add my css to my website this the code I have below. **functions.php** ``` <?php function fearnothing_script_enqueue(){ wp_enqueue_style("style", get_stylesheet_uri()."css/ fearnothing.css",false, 'all'); } add_action('wp_enqueue_scripts', 'fearnothing_script_enqueue'); ``` **header.php** ``` <!DOCTYPE html> <html> <head> <title>lonely spaceship</title> <?php wp_head(); ?> </head> <body> ``` **footer.php** ``` <footer> <p></p> </footer> <?php wp_footer(); ?> </body> ``` **fearnothing.css** ``` html, body { margin: 0; color: #91f213; background-color:black; font: sans-serif; } body{ padding: 20px; } h1{ color: yellow; } ```
I don't know if you try to add a css file in your theme or plugin. I will provide both examples. Use [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) in combination with [get\_theme\_file\_uri](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) to enqueu a stylesheet in your theme directory. **For a theme, see example** ``` function add_styles() { wp_enqueue_style( 'fontawesome-style', get_theme_file_uri( '/assets/css/all.css' ), array(), null ); } add_action( 'wp_enqueue_scripts', 'add_styles' ); ``` **For a plugin, see example** ``` function add_styles() { wp_enqueue_style( 'example-styles-plugin', plugins_url('/assets/css/admin.css', __FILE__), array(), null ); } add_action( 'wp_enqueue_scripts', 'add_styles' ); ``` **For both, add an external URL:** ``` function add_styles() { // Add Google Fonts wp_enqueue_style('google_fonts', 'https://fonts.googleapis.com/css?family=Poppins:300,500,700', array(), null ); } add_action( 'wp_enqueue_scripts', 'add_styles' ); ```
319,819
<p>Im trying to display a custom taxonomy for a custom post type. So this taxonomy is specific to this custom post type. Unfortunately I cant get them to display. Here is my code in functions.php to register the custom taxonomy:</p> <pre><code>add_action('init', 'products_categories', 0); function products_categories(){ $labels = array ('name' =&gt; _x('Product Categories','taxonomy general name'), 'singular_name' =&gt;_x('Product Category','taxonomy singular name'), 'serch_items' =&gt; __('Search Product Categories'), 'popular_items' =&gt; ('Popular Product Categories'), 'all_items' =&gt; __('All Product Categories'), 'parent_item' =&gt; null, 'parent_item_colon' =&gt; null, 'edit_item' =&gt; __('Edit Product Category'), 'update_item' =&gt; __('Update Product Category'), 'add_new_item' =&gt; __('Add Product Category'), 'new_item_name' =&gt; __('New Product Category'), 'separate_items_with_commas' =&gt; __('Seperate Product Categories with commas'), 'add_or_remove_items' =&gt; __('Add or remove Product Categories'), 'choose_from_most_used' =&gt; __('Most Used Product Categories'), 'menu_name' =&gt; __('Product Categories'), ); register_taxonomy('product_categories', 'products', array( 'hierarchical' =&gt; false, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'product_category' ), )); } </code></pre> <p>And here im trying to display them:</p> <pre><code>&lt;?php } $terms = get_terms('taxonomy'=&gt;'product_category', 'hide_empty'=&gt; false,); foreach ( $terms as $term) { ?&gt; &lt;a href=""&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/a&gt; &lt;?php }?&gt; </code></pre> <p>Do I need to have this running in a query of some sort first?</p>
[ { "answer_id": 319822, "author": "Greg Winiarski", "author_id": 154460, "author_profile": "https://wordpress.stackexchange.com/users/154460", "pm_score": 2, "selected": true, "text": "<p>it looks like your get_terms() call is incorrect, the argument is not an array and you have a typo in taxonomy name ('product_category' instead of 'product_categories') it should be</p>\n\n<pre><code>&lt;?php \n$terms = get_terms( array( \n 'taxonomy'=&gt;'product_categories', \n 'hide_empty'=&gt; false \n) ); \n?&gt;\n</code></pre>\n\n<p>If this will not help it would be best if you could let us know if you are seeing any error message and if you do paste the error here.</p>\n" }, { "answer_id": 319823, "author": "vikrant zilpe", "author_id": 153928, "author_profile": "https://wordpress.stackexchange.com/users/153928", "pm_score": 0, "selected": false, "text": "<p>I managed to solve this and I will post the answer:</p>\n\n<pre><code>&lt;?php\n $args = array('number' =&gt; '1',);\n $terms = get_terms('recipes', $args );\n foreach( $terms as $term ){\n echo '&lt;div class=\"title\"&gt;' . $term-&gt;name . 'recipe&lt;/div&gt;';\n } \n</code></pre>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319819", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93537/" ]
Im trying to display a custom taxonomy for a custom post type. So this taxonomy is specific to this custom post type. Unfortunately I cant get them to display. Here is my code in functions.php to register the custom taxonomy: ``` add_action('init', 'products_categories', 0); function products_categories(){ $labels = array ('name' => _x('Product Categories','taxonomy general name'), 'singular_name' =>_x('Product Category','taxonomy singular name'), 'serch_items' => __('Search Product Categories'), 'popular_items' => ('Popular Product Categories'), 'all_items' => __('All Product Categories'), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __('Edit Product Category'), 'update_item' => __('Update Product Category'), 'add_new_item' => __('Add Product Category'), 'new_item_name' => __('New Product Category'), 'separate_items_with_commas' => __('Seperate Product Categories with commas'), 'add_or_remove_items' => __('Add or remove Product Categories'), 'choose_from_most_used' => __('Most Used Product Categories'), 'menu_name' => __('Product Categories'), ); register_taxonomy('product_categories', 'products', array( 'hierarchical' => false, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'update_count_callback' => '_update_post_term_count', 'query_var' => true, 'rewrite' => array( 'slug' => 'product_category' ), )); } ``` And here im trying to display them: ``` <?php } $terms = get_terms('taxonomy'=>'product_category', 'hide_empty'=> false,); foreach ( $terms as $term) { ?> <a href=""><?php echo $term->name; ?></a> <?php }?> ``` Do I need to have this running in a query of some sort first?
it looks like your get\_terms() call is incorrect, the argument is not an array and you have a typo in taxonomy name ('product\_category' instead of 'product\_categories') it should be ``` <?php $terms = get_terms( array( 'taxonomy'=>'product_categories', 'hide_empty'=> false ) ); ?> ``` If this will not help it would be best if you could let us know if you are seeing any error message and if you do paste the error here.
319,824
<p>In functions.php, I want to access the DB once to get an ACF object, and then "save" it locally to prevent further requests to the DB.</p> <p>I thought of first calling the following function in the "init' hook.</p> <p>Then, supposedly, when I call it on later hooks the $current_store var is already set because of the use of the "static" keyword, and the function will stop on the first "if" - returning the already saved static var.</p> <p>It doesn't work - when accessing the function on later hooks 'isset($current_store)' returns false.</p> <p>What am I doing wrong?</p> <pre><code>function get_current_store() { if (isset($current_store)) { return $current_store; } $store_url_parts = explode('.', $_SERVER['HTTP_HOST']); $store_subdomain = $store_url_parts[0]; $store_url_parts_reversed = array_reverse($store_url_parts); if (in_array("il", $store_url_parts_reversed)) { $domain = $store_url_parts_reversed[2]; } else { $domain = $store_url_parts_reversed[2]; } if ($store_subdomain == $domain) { $current_store = 'main'; return $current_store; } if ($stores_page = get_page_by_title('Stores', OBJECT, 'option')) { $stores_page_id = $stores_page-&gt;ID; if (function_exists('have_rows')) { if (have_rows('stores', $stores_page_id)) { $store_url_parts = get_store_url_parts(); $store_subdomain = $store_url_parts[0]; $stores = array(); while (have_rows('stores', $stores_page_id)) { the_row(); $store = get_row(true); $stores[] = $store; } $subdomains = array_column($stores, 'store_subdomain'); $current_store_id = array_search($store_subdomain, $subdomains); static $current_store = array(); if ($current_store_id !== false) { $current_store = $stores[$current_store_id]; } else { $current_store = false; } return $current_store; } } } </code></pre> <p>}</p>
[ { "answer_id": 319826, "author": "Greg Winiarski", "author_id": 154460, "author_profile": "https://wordpress.stackexchange.com/users/154460", "pm_score": -1, "selected": false, "text": "<p>if the $current_store is some kind of global variable then your function should start with</p>\n\n<pre><code>function get_current_store() {\n global $current_store\n // the rest of your source code here ...\n</code></pre>\n" }, { "answer_id": 319831, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>This is a good use case for the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow noreferrer\">Object Cache</a>:</p>\n\n<blockquote>\n <p>WP_Object_Cache is WordPress' class for caching data which may be\n computationally expensive to regenerate, such as the result of complex\n database queries.</p>\n</blockquote>\n\n<p>You can store things in the cache with <code>wp_cache_set()</code> and retrieve them with <code>wp_cache_get()</code>. You just need to give it a key and value, as well as a group name unique to your theme/plugin or set of functionality to avoid conflicts:</p>\n\n<pre><code>function get_current_store()\n{\n // Check if the current store is cached.\n $cache = wp_cache_get( 'current_store', 'my_plugin' );\n\n // If it is, return the cached store.\n if ( $cache ) {\n return $cache;\n }\n\n // Otherwise do the work to figure out $current_store;\n\n // Then cache it.\n wp_cache_set( 'current_store', $current_store, 'my_plugin' );\n\n return $current_store;\n}\n</code></pre>\n\n<p>Now no matter how many times you run <code>get_current_store()</code> on a page it will only do the work of generating the current store variable once.</p>\n" }, { "answer_id": 319869, "author": "Asaf Moshe", "author_id": 152801, "author_profile": "https://wordpress.stackexchange.com/users/152801", "pm_score": 0, "selected": false, "text": "<p>Jacob Peattie answer is a great alternative.</p>\n\n<p>But if someone iterested, the problem with my original code is that <code>static $current_store</code> needs to be declared at the beggining of the function.</p>\n\n<p>This code works:</p>\n\n<pre><code>function get_current_store()\n{\n static $current_store;\n\n if (isset($current_store)) {\n return $current_store;\n } else {\n $store_url_parts = explode('.', $_SERVER['HTTP_HOST']);\n $store_subdomain = $store_url_parts[0];\n\n $store_url_parts_reversed = array_reverse($store_url_parts);\n\n if (in_array(\"il\", $store_url_parts_reversed)) {\n $domain = $store_url_parts_reversed[2];\n } else {\n $domain = $store_url_parts_reversed[2];\n }\n\n if ($store_subdomain == $domain) {\n $current_store = 'main';\n\n return $current_store;\n }\n\n if ($stores_page = get_page_by_title('Stores', OBJECT, 'option')) {\n $stores_page_id = $stores_page-&gt;ID;\n\n if (function_exists('have_rows')) {\n if (have_rows('stores', $stores_page_id)) {\n $store_url_parts = get_store_url_parts();\n $store_subdomain = $store_url_parts[0];\n $stores = array();\n\n while (have_rows('stores', $stores_page_id)) {\n the_row();\n\n $store = get_row(true);\n\n $stores[] = $store;\n }\n\n $subdomains = array_column($stores, 'store_subdomain');\n\n $current_store_id = array_search($store_subdomain, $subdomains);\n\n $current_store = array();\n\n if ($current_store_id !== false) {\n $current_store = $stores[$current_store_id];\n } else {\n $current_store = false;\n }\n }\n }\n return $current_store;\n }\n }\n}\n</code></pre>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152801/" ]
In functions.php, I want to access the DB once to get an ACF object, and then "save" it locally to prevent further requests to the DB. I thought of first calling the following function in the "init' hook. Then, supposedly, when I call it on later hooks the $current\_store var is already set because of the use of the "static" keyword, and the function will stop on the first "if" - returning the already saved static var. It doesn't work - when accessing the function on later hooks 'isset($current\_store)' returns false. What am I doing wrong? ``` function get_current_store() { if (isset($current_store)) { return $current_store; } $store_url_parts = explode('.', $_SERVER['HTTP_HOST']); $store_subdomain = $store_url_parts[0]; $store_url_parts_reversed = array_reverse($store_url_parts); if (in_array("il", $store_url_parts_reversed)) { $domain = $store_url_parts_reversed[2]; } else { $domain = $store_url_parts_reversed[2]; } if ($store_subdomain == $domain) { $current_store = 'main'; return $current_store; } if ($stores_page = get_page_by_title('Stores', OBJECT, 'option')) { $stores_page_id = $stores_page->ID; if (function_exists('have_rows')) { if (have_rows('stores', $stores_page_id)) { $store_url_parts = get_store_url_parts(); $store_subdomain = $store_url_parts[0]; $stores = array(); while (have_rows('stores', $stores_page_id)) { the_row(); $store = get_row(true); $stores[] = $store; } $subdomains = array_column($stores, 'store_subdomain'); $current_store_id = array_search($store_subdomain, $subdomains); static $current_store = array(); if ($current_store_id !== false) { $current_store = $stores[$current_store_id]; } else { $current_store = false; } return $current_store; } } } ``` }
This is a good use case for the [Object Cache](https://codex.wordpress.org/Class_Reference/WP_Object_Cache): > > WP\_Object\_Cache is WordPress' class for caching data which may be > computationally expensive to regenerate, such as the result of complex > database queries. > > > You can store things in the cache with `wp_cache_set()` and retrieve them with `wp_cache_get()`. You just need to give it a key and value, as well as a group name unique to your theme/plugin or set of functionality to avoid conflicts: ``` function get_current_store() { // Check if the current store is cached. $cache = wp_cache_get( 'current_store', 'my_plugin' ); // If it is, return the cached store. if ( $cache ) { return $cache; } // Otherwise do the work to figure out $current_store; // Then cache it. wp_cache_set( 'current_store', $current_store, 'my_plugin' ); return $current_store; } ``` Now no matter how many times you run `get_current_store()` on a page it will only do the work of generating the current store variable once.
319,861
<p>is it possible to show only the first line of content <code>&lt;?php the_content(); ?&gt;</code> or alternative only content between <code>&lt;b&gt;text&lt;/b&gt;</code>?</p>
[ { "answer_id": 319864, "author": "miguelcalderons", "author_id": 153649, "author_profile": "https://wordpress.stackexchange.com/users/153649", "pm_score": 2, "selected": false, "text": "<p>What you can do is work with this <code>the_excerpt()</code> change this instead of <code>the_content();</code></p>\n\n<p>And give the amount of words that you want, add this in functions.php after you add the_excerpt();</p>\n\n<pre><code>function custom_excerpt_length( $length ) {\n return 20;\n}\nadd_filter( 'excerpt_length', 'custom_excerpt_length', 999 );\n</code></pre>\n\n<p>More info here: <a href=\"https://developer.wordpress.org/reference/functions/the_excerpt/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_excerpt/</a></p>\n\n<p>After that force the first line, using this for example. </p>\n\n<pre><code>.post p {\n width: 100px;\n white-space:nowrap;\n overflow:hidden;\n}\n</code></pre>\n\n<p>add the width of the content.(even if its responsive just change the css as you want).</p>\n" }, { "answer_id": 319866, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": true, "text": "<p>you could also do something like:</p>\n\n<pre><code>function rt_before_after($content) {\n\n $replace = \"&lt;/b&gt;\";\n $shortcontent = strstr($content, $replace, true).$replace;\n\n if ($shortcontent === false) $shortcontent = $content;\n\n return $shortcontent;\n}\nadd_filter('the_content', 'rt_before_after');\n</code></pre>\n\n<p>It should look for the first <code>&lt;/b&gt;</code> in your content and return everything before that. it then adds the <code>&lt;/b&gt;</code> back. The function takes that string and replaces your content. </p>\n" }, { "answer_id": 319877, "author": "joloshop", "author_id": 153850, "author_profile": "https://wordpress.stackexchange.com/users/153850", "pm_score": 0, "selected": false, "text": "<p>Found a solution! I use this code:</p>\n\n<pre><code> function awesome_excerpt($text, $raw_excerpt) {\n if( ! $raw_excerpt ) {\n $content = apply_filters( 'the_content', get_the_content() );\n $text = substr( $content, 0, strpos( $content, '&lt;/p&gt;' ) + 4 );\n }\n return $text;\n}\nadd_filter( 'wp_trim_excerpt', 'awesome_excerpt', 10, 2 );\n</code></pre>\n\n<p>and than use <code>&lt;?php the_excerpt(); ?&gt;</code></p>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153850/" ]
is it possible to show only the first line of content `<?php the_content(); ?>` or alternative only content between `<b>text</b>`?
you could also do something like: ``` function rt_before_after($content) { $replace = "</b>"; $shortcontent = strstr($content, $replace, true).$replace; if ($shortcontent === false) $shortcontent = $content; return $shortcontent; } add_filter('the_content', 'rt_before_after'); ``` It should look for the first `</b>` in your content and return everything before that. it then adds the `</b>` back. The function takes that string and replaces your content.
319,878
<p>I've stumbled across something that I can't seem to find any documentation on regarding WP 'get_posts' function.</p> <p>I've got a web application that has multiple custom post-types and multiple custom user roles. They're all necessary for an assortment of reasons. Different users types within the organization need to see different things and be able to edit different aspects of the custom post-types.</p> <p>In the custom post-type edit screens, I have metaboxes that display user provided data, however, users with backend access, using different custom user roles, need to be able to correct or modify the data that users have supplied or to manually create an entry.</p> <p>I use the following 'get_posts()' method to generate dropdowns based on entries from other custom post-types:</p> <pre><code>&lt;select name="mwss_session"&gt; &lt;option value=""&gt;Please select a Session&lt;/option&gt; &lt;?php $get_sessions = get_posts( array( 'post_type' =&gt; 'seasonal_sessions', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'mwss_session_status', 'meta_value' =&gt; 'true', 'meta_compare' =&gt; '=' ) ); $selected_session = $mwss_session; foreach( $get_sessions as $active_session ) { $session_name = get_the_title( $active_session-&gt;ID ); echo '&lt;option value="' . $session_name . '"'; if( $selected_session === $session_name ){ echo 'selected'; } echo '&gt;' . $session_name . '&lt;/option&gt;'; } ?&gt; &lt;/select&gt; </code></pre> <p>It works as you'd expect it to. You visit the edit screen and the dropdown is populated with 'Sessions' whose 'status' is set to 'true'. This same get_posts() method works on the front end as well, logged in or not.</p> <p>However, when visiting the edit.php screen for this post type using one of the custom user roles I created, this dropdown and others using the same method, all fail to return results.</p> <p>Here's an example of one of the custom user roles capabilities:</p> <pre><code>$result = add_role( 'mwss_sitesuper', __('Site Supervisor'), array( //WordPress Capabilities 'level_9' =&gt; false, 'level_8' =&gt; true, 'level_7' =&gt; true, 'level_6' =&gt; true, 'level_5' =&gt; true, 'level_4' =&gt; true, 'level_3' =&gt; true, 'level_2' =&gt; true, 'level_1' =&gt; true, 'level_0' =&gt; true, 'read' =&gt; true, 'read_private_pages' =&gt; true, 'read_private_posts' =&gt; true, 'create_posts' =&gt; true, 'publish_posts' =&gt; true, 'edit_users' =&gt; true, 'edit_posts' =&gt; true, 'edit_pages' =&gt; true, 'edit_published_posts' =&gt; true, 'edit_published_pages' =&gt; true, 'edit_private_pages' =&gt; true, 'edit_private_posts' =&gt; true, 'edit_others_posts' =&gt; true, 'edit_others_pages' =&gt; true, 'publish_posts' =&gt; true, 'publish_pages' =&gt; true, 'delete_posts' =&gt; true, 'delete_pages' =&gt; true, 'delete_private_pages' =&gt; true, 'delete_private_posts' =&gt; true, 'delete_published_pages' =&gt; true, 'delete_published_posts' =&gt; true, 'delete_others_posts' =&gt; true, 'delete_others_pages' =&gt; true, 'manage_options' =&gt; false, 'manage_categories' =&gt; false, 'manage_links' =&gt; false, 'moderate_comments' =&gt; true, 'unfiltered_html' =&gt; false, 'upload_files' =&gt; false, 'export' =&gt; false, 'import' =&gt; false, 'list_users' =&gt; true, 'edit_themes' =&gt; false, 'install_plugins' =&gt; false, 'update_plugin' =&gt; false, 'update_core' =&gt; false ) ); </code></pre> <p>Any idea why get_posts() only works with Administrator or Editor roles in the back end, but works for all user roles on the front end?</p> <p><strong>Update:</strong> After delving pretty deeply into capabilities, I've come to the conclusion that this is something unrelated. On the front end, regardless of the user's capabilities or role, the same 'get_posts' function is returning results. So if a user role as low as subscriber, or if all of the custom user roles are able to view the dropdown on the front end populated with the expected 'sessions', they then theoretically have the capability to do so, right? Or am I missing something? The issue appears to be isolated to metaboxes within CPT. If I use WP_Query, it works, but WP_Query will disrupt the rest of the admin loop.</p>
[ { "answer_id": 319881, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 0, "selected": false, "text": "<p>Try adding <code>read_seasonal_sessions</code> to your capabilities array and setting that to true. Each new CPT gets 7 new capabilities to add to user roles. (see <code>capability_type</code> on <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow noreferrer\">register_post_type()</a>)</p>\n\n<p>OR</p>\n\n<p>Add <code>map_meta_cap</code> to your register_post_type function (if you have it) and set it to true. (see <code>map_meta_cap</code> under <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow noreferrer\">register_post_type()</a>)</p>\n\n<p>By default, <code>map_meta_cap</code> is <code>null</code>, so I don't think it's mapping the post capabilities directly to your CPT.</p>\n" }, { "answer_id": 369276, "author": "Mort 1305", "author_id": 188811, "author_profile": "https://wordpress.stackexchange.com/users/188811", "pm_score": 1, "selected": false, "text": "<p>I have this problem as well, @tony-djukic. I have an administrator user that can see two posts of a custom post type. I have two subscriber users, each are able to only see the opposite post as the other. Here's what I'm using to (apparently not) get all the posts:</p>\n<pre>\nget_posts(array(\n 'numberposts' => -1,\n 'post_type' => 'my-cpt',\n 'post_status' => get_post_stati(),\n))\n</pre>\n<p>After searching for several of hours in each of the past couple of days for a solution, I came across your (1.5-year-old) unanswered question. With no other option, I traced the code. Here's my work...</p>\n<p><strong>1.)</strong> According to the documentation, the <code>get_posts()</code> <a href=\"https://developer.wordpress.org/reference/functions/get_posts/#source\" rel=\"nofollow noreferrer\">method</a> returns the result of <code>WP_Query-&gt;query()</code> with an array of arguments passed (which is of no importance when considering the issue at hand).</p>\n<p><strong>2.)</strong> The documentation says that the <code>WP_Query-&gt;query()</code> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/query/#source\" rel=\"nofollow noreferrer\">method</a> is a pretty simple wrapper that initializes the <code>WP_Query</code> object before returning the results of <code>WP_Query-&gt;get_posts()</code>.</p>\n<p><strong>3.)</strong> Next, the <code>WP_Query-&gt;get_posts()</code> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/get_posts/#source\" rel=\"nofollow noreferrer\">method</a> is called. Somewhere around line 2434, the <em>read_post</em> and <em>edit_post</em> capabilities come into play. Mind you, this is not the <em>read_CPT</em> or <em>edit_CPT</em> primitives of the custom post type, but rather the primitives for the <em>post</em> type. Those non-altered primitives are then checked in a <code>current_user_can</code> call (see lines 3087, 3096, 3105, and 3111). In other words, if your user does not have the <em>read_post</em> and <em>edit_post</em> capabilities, the posts checked in the <code>current_user_can()</code> call will not be included in the results. This is quite counter to the purpose of custom capabilities: the capabilities checked should be the <em>read_CPT</em> or <em>edit_CPT</em> capabilities so this is quite obviously some kind of accident on the coder's part. After all, granting these permission will likely allow your user to edit posts (as well as your custom post type).</p>\n<p><strong>NOTE:</strong> The reason why the user is able to read on the front-end is more because of the <code>public=TRUE</code> given when registering the post type, not necessarily because of the capability given to the user. What I think I see in the code is that the higher-level capabilities play a role in <code>protected</code> and <code>private</code> posts more than they do for those CPT's defined as being registered as <code>public</code>.</p>\n<p><strong>LONG-TERM FIX:</strong> WordPress should define these two variables (on lines 2434 and 2435) after performing a check to determine if a CPT is being queried: obviously, this was overlooked in the coding. What should happen is these variables representing capabilities should be set in the succeeding checks occurring on lines 2437-2443. Namely, that code block should be:</p>\n<pre>\nif ( ! empty( $post_type_object ) ) {\n $edit_cap = $post_type_object->cap->edit_post;\n $read_cap = $post_type_object->cap->read_post;\n $edit_others_cap = $post_type_object->cap->edit_others_posts;\n $read_private_cap = $post_type_object->cap->read_private_posts;\n} else {\n $edit_cap = 'edit_'. $post_type_cap;\n $read_cap = 'read_'. $post_type_cap;\n $edit_others_cap = 'edit_others_' . $post_type_cap . 's';\n $read_private_cap = 'read_private_' . $post_type_cap . 's';\n}\n</pre>\n<p><strong>SHORT-TERM FIX:</strong> After all that, I came up with the following temporary solution. The <code>user_has_cap</code> <a href=\"https://developer.wordpress.org/reference/hooks/user_has_cap/\" rel=\"nofollow noreferrer\">filter</a> can be implemented in an early hook. The ID of the object to the hook is passed in <code>$args[2]</code> of the hook, which can be checked to see if it is the ID of an object having a custom post type. If it is, then the result of the <code>user_can</code> <a href=\"https://developer.wordpress.org/reference/functions/user_can/\" rel=\"nofollow noreferrer\">method</a> on that custom capability can be returned. The whole thing could look something like this:</p>\n<pre>\nadd_filter('user_has_cap' function($allcaps, $caps, $args, $user){\n $pt = get_post_type($args[2]);\n if(ctype_digit($args[2])\n && $pt !== FALSE\n ) {\n $pt_obj = get_post_type_object($pt);\n if(!is_null($pt_obj)\n && !$pt_obj->_builtin\n ) {\n foreach($caps as $cap) {\n $type = substr($cap, strrpos($cap, '_')+1);\n if($type === 'post'\n || $type === 'posts'\n ) {\n // $pt_obj->cap set by get_post_type_capabilities()\n $allcaps[$cap] = user_can($user, $pt_obj->cap->$cap, $args);\n }\n }\n }\n }\n return $allcaps;\n}, 0, 4);\n</pre>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60844/" ]
I've stumbled across something that I can't seem to find any documentation on regarding WP 'get\_posts' function. I've got a web application that has multiple custom post-types and multiple custom user roles. They're all necessary for an assortment of reasons. Different users types within the organization need to see different things and be able to edit different aspects of the custom post-types. In the custom post-type edit screens, I have metaboxes that display user provided data, however, users with backend access, using different custom user roles, need to be able to correct or modify the data that users have supplied or to manually create an entry. I use the following 'get\_posts()' method to generate dropdowns based on entries from other custom post-types: ``` <select name="mwss_session"> <option value="">Please select a Session</option> <?php $get_sessions = get_posts( array( 'post_type' => 'seasonal_sessions', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_key' => 'mwss_session_status', 'meta_value' => 'true', 'meta_compare' => '=' ) ); $selected_session = $mwss_session; foreach( $get_sessions as $active_session ) { $session_name = get_the_title( $active_session->ID ); echo '<option value="' . $session_name . '"'; if( $selected_session === $session_name ){ echo 'selected'; } echo '>' . $session_name . '</option>'; } ?> </select> ``` It works as you'd expect it to. You visit the edit screen and the dropdown is populated with 'Sessions' whose 'status' is set to 'true'. This same get\_posts() method works on the front end as well, logged in or not. However, when visiting the edit.php screen for this post type using one of the custom user roles I created, this dropdown and others using the same method, all fail to return results. Here's an example of one of the custom user roles capabilities: ``` $result = add_role( 'mwss_sitesuper', __('Site Supervisor'), array( //WordPress Capabilities 'level_9' => false, 'level_8' => true, 'level_7' => true, 'level_6' => true, 'level_5' => true, 'level_4' => true, 'level_3' => true, 'level_2' => true, 'level_1' => true, 'level_0' => true, 'read' => true, 'read_private_pages' => true, 'read_private_posts' => true, 'create_posts' => true, 'publish_posts' => true, 'edit_users' => true, 'edit_posts' => true, 'edit_pages' => true, 'edit_published_posts' => true, 'edit_published_pages' => true, 'edit_private_pages' => true, 'edit_private_posts' => true, 'edit_others_posts' => true, 'edit_others_pages' => true, 'publish_posts' => true, 'publish_pages' => true, 'delete_posts' => true, 'delete_pages' => true, 'delete_private_pages' => true, 'delete_private_posts' => true, 'delete_published_pages' => true, 'delete_published_posts' => true, 'delete_others_posts' => true, 'delete_others_pages' => true, 'manage_options' => false, 'manage_categories' => false, 'manage_links' => false, 'moderate_comments' => true, 'unfiltered_html' => false, 'upload_files' => false, 'export' => false, 'import' => false, 'list_users' => true, 'edit_themes' => false, 'install_plugins' => false, 'update_plugin' => false, 'update_core' => false ) ); ``` Any idea why get\_posts() only works with Administrator or Editor roles in the back end, but works for all user roles on the front end? **Update:** After delving pretty deeply into capabilities, I've come to the conclusion that this is something unrelated. On the front end, regardless of the user's capabilities or role, the same 'get\_posts' function is returning results. So if a user role as low as subscriber, or if all of the custom user roles are able to view the dropdown on the front end populated with the expected 'sessions', they then theoretically have the capability to do so, right? Or am I missing something? The issue appears to be isolated to metaboxes within CPT. If I use WP\_Query, it works, but WP\_Query will disrupt the rest of the admin loop.
I have this problem as well, @tony-djukic. I have an administrator user that can see two posts of a custom post type. I have two subscriber users, each are able to only see the opposite post as the other. Here's what I'm using to (apparently not) get all the posts: ``` get_posts(array( 'numberposts' => -1, 'post_type' => 'my-cpt', 'post_status' => get_post_stati(), )) ``` After searching for several of hours in each of the past couple of days for a solution, I came across your (1.5-year-old) unanswered question. With no other option, I traced the code. Here's my work... **1.)** According to the documentation, the `get_posts()` [method](https://developer.wordpress.org/reference/functions/get_posts/#source) returns the result of `WP_Query->query()` with an array of arguments passed (which is of no importance when considering the issue at hand). **2.)** The documentation says that the `WP_Query->query()` [method](https://developer.wordpress.org/reference/classes/wp_query/query/#source) is a pretty simple wrapper that initializes the `WP_Query` object before returning the results of `WP_Query->get_posts()`. **3.)** Next, the `WP_Query->get_posts()` [method](https://developer.wordpress.org/reference/classes/wp_query/get_posts/#source) is called. Somewhere around line 2434, the *read\_post* and *edit\_post* capabilities come into play. Mind you, this is not the *read\_CPT* or *edit\_CPT* primitives of the custom post type, but rather the primitives for the *post* type. Those non-altered primitives are then checked in a `current_user_can` call (see lines 3087, 3096, 3105, and 3111). In other words, if your user does not have the *read\_post* and *edit\_post* capabilities, the posts checked in the `current_user_can()` call will not be included in the results. This is quite counter to the purpose of custom capabilities: the capabilities checked should be the *read\_CPT* or *edit\_CPT* capabilities so this is quite obviously some kind of accident on the coder's part. After all, granting these permission will likely allow your user to edit posts (as well as your custom post type). **NOTE:** The reason why the user is able to read on the front-end is more because of the `public=TRUE` given when registering the post type, not necessarily because of the capability given to the user. What I think I see in the code is that the higher-level capabilities play a role in `protected` and `private` posts more than they do for those CPT's defined as being registered as `public`. **LONG-TERM FIX:** WordPress should define these two variables (on lines 2434 and 2435) after performing a check to determine if a CPT is being queried: obviously, this was overlooked in the coding. What should happen is these variables representing capabilities should be set in the succeeding checks occurring on lines 2437-2443. Namely, that code block should be: ``` if ( ! empty( $post_type_object ) ) { $edit_cap = $post_type_object->cap->edit_post; $read_cap = $post_type_object->cap->read_post; $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_cap = 'edit_'. $post_type_cap; $read_cap = 'read_'. $post_type_cap; $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } ``` **SHORT-TERM FIX:** After all that, I came up with the following temporary solution. The `user_has_cap` [filter](https://developer.wordpress.org/reference/hooks/user_has_cap/) can be implemented in an early hook. The ID of the object to the hook is passed in `$args[2]` of the hook, which can be checked to see if it is the ID of an object having a custom post type. If it is, then the result of the `user_can` [method](https://developer.wordpress.org/reference/functions/user_can/) on that custom capability can be returned. The whole thing could look something like this: ``` add_filter('user_has_cap' function($allcaps, $caps, $args, $user){ $pt = get_post_type($args[2]); if(ctype_digit($args[2]) && $pt !== FALSE ) { $pt_obj = get_post_type_object($pt); if(!is_null($pt_obj) && !$pt_obj->_builtin ) { foreach($caps as $cap) { $type = substr($cap, strrpos($cap, '_')+1); if($type === 'post' || $type === 'posts' ) { // $pt_obj->cap set by get_post_type_capabilities() $allcaps[$cap] = user_can($user, $pt_obj->cap->$cap, $args); } } } } return $allcaps; }, 0, 4); ```
319,885
<p>I am trying to put three menu items before the <code>Dashboard</code> menu item in admin dashboard. Problem is that <code>Dashboard</code> has menu position <code>2</code>.</p> <p>I can manage to put in two menu items before with position <code>0</code> and <code>1</code>, but <code>2</code> collides with Dashboard.</p> <p>So my thought was to move the Dashboard position. Is this possible? Can I change <code>Dashboard</code> menu position from <code>2</code> to something else (like 3, 4 or 5)?</p> <p>Is there a hook for this?</p>
[ { "answer_id": 319881, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 0, "selected": false, "text": "<p>Try adding <code>read_seasonal_sessions</code> to your capabilities array and setting that to true. Each new CPT gets 7 new capabilities to add to user roles. (see <code>capability_type</code> on <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow noreferrer\">register_post_type()</a>)</p>\n\n<p>OR</p>\n\n<p>Add <code>map_meta_cap</code> to your register_post_type function (if you have it) and set it to true. (see <code>map_meta_cap</code> under <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow noreferrer\">register_post_type()</a>)</p>\n\n<p>By default, <code>map_meta_cap</code> is <code>null</code>, so I don't think it's mapping the post capabilities directly to your CPT.</p>\n" }, { "answer_id": 369276, "author": "Mort 1305", "author_id": 188811, "author_profile": "https://wordpress.stackexchange.com/users/188811", "pm_score": 1, "selected": false, "text": "<p>I have this problem as well, @tony-djukic. I have an administrator user that can see two posts of a custom post type. I have two subscriber users, each are able to only see the opposite post as the other. Here's what I'm using to (apparently not) get all the posts:</p>\n<pre>\nget_posts(array(\n 'numberposts' => -1,\n 'post_type' => 'my-cpt',\n 'post_status' => get_post_stati(),\n))\n</pre>\n<p>After searching for several of hours in each of the past couple of days for a solution, I came across your (1.5-year-old) unanswered question. With no other option, I traced the code. Here's my work...</p>\n<p><strong>1.)</strong> According to the documentation, the <code>get_posts()</code> <a href=\"https://developer.wordpress.org/reference/functions/get_posts/#source\" rel=\"nofollow noreferrer\">method</a> returns the result of <code>WP_Query-&gt;query()</code> with an array of arguments passed (which is of no importance when considering the issue at hand).</p>\n<p><strong>2.)</strong> The documentation says that the <code>WP_Query-&gt;query()</code> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/query/#source\" rel=\"nofollow noreferrer\">method</a> is a pretty simple wrapper that initializes the <code>WP_Query</code> object before returning the results of <code>WP_Query-&gt;get_posts()</code>.</p>\n<p><strong>3.)</strong> Next, the <code>WP_Query-&gt;get_posts()</code> <a href=\"https://developer.wordpress.org/reference/classes/wp_query/get_posts/#source\" rel=\"nofollow noreferrer\">method</a> is called. Somewhere around line 2434, the <em>read_post</em> and <em>edit_post</em> capabilities come into play. Mind you, this is not the <em>read_CPT</em> or <em>edit_CPT</em> primitives of the custom post type, but rather the primitives for the <em>post</em> type. Those non-altered primitives are then checked in a <code>current_user_can</code> call (see lines 3087, 3096, 3105, and 3111). In other words, if your user does not have the <em>read_post</em> and <em>edit_post</em> capabilities, the posts checked in the <code>current_user_can()</code> call will not be included in the results. This is quite counter to the purpose of custom capabilities: the capabilities checked should be the <em>read_CPT</em> or <em>edit_CPT</em> capabilities so this is quite obviously some kind of accident on the coder's part. After all, granting these permission will likely allow your user to edit posts (as well as your custom post type).</p>\n<p><strong>NOTE:</strong> The reason why the user is able to read on the front-end is more because of the <code>public=TRUE</code> given when registering the post type, not necessarily because of the capability given to the user. What I think I see in the code is that the higher-level capabilities play a role in <code>protected</code> and <code>private</code> posts more than they do for those CPT's defined as being registered as <code>public</code>.</p>\n<p><strong>LONG-TERM FIX:</strong> WordPress should define these two variables (on lines 2434 and 2435) after performing a check to determine if a CPT is being queried: obviously, this was overlooked in the coding. What should happen is these variables representing capabilities should be set in the succeeding checks occurring on lines 2437-2443. Namely, that code block should be:</p>\n<pre>\nif ( ! empty( $post_type_object ) ) {\n $edit_cap = $post_type_object->cap->edit_post;\n $read_cap = $post_type_object->cap->read_post;\n $edit_others_cap = $post_type_object->cap->edit_others_posts;\n $read_private_cap = $post_type_object->cap->read_private_posts;\n} else {\n $edit_cap = 'edit_'. $post_type_cap;\n $read_cap = 'read_'. $post_type_cap;\n $edit_others_cap = 'edit_others_' . $post_type_cap . 's';\n $read_private_cap = 'read_private_' . $post_type_cap . 's';\n}\n</pre>\n<p><strong>SHORT-TERM FIX:</strong> After all that, I came up with the following temporary solution. The <code>user_has_cap</code> <a href=\"https://developer.wordpress.org/reference/hooks/user_has_cap/\" rel=\"nofollow noreferrer\">filter</a> can be implemented in an early hook. The ID of the object to the hook is passed in <code>$args[2]</code> of the hook, which can be checked to see if it is the ID of an object having a custom post type. If it is, then the result of the <code>user_can</code> <a href=\"https://developer.wordpress.org/reference/functions/user_can/\" rel=\"nofollow noreferrer\">method</a> on that custom capability can be returned. The whole thing could look something like this:</p>\n<pre>\nadd_filter('user_has_cap' function($allcaps, $caps, $args, $user){\n $pt = get_post_type($args[2]);\n if(ctype_digit($args[2])\n && $pt !== FALSE\n ) {\n $pt_obj = get_post_type_object($pt);\n if(!is_null($pt_obj)\n && !$pt_obj->_builtin\n ) {\n foreach($caps as $cap) {\n $type = substr($cap, strrpos($cap, '_')+1);\n if($type === 'post'\n || $type === 'posts'\n ) {\n // $pt_obj->cap set by get_post_type_capabilities()\n $allcaps[$cap] = user_can($user, $pt_obj->cap->$cap, $args);\n }\n }\n }\n }\n return $allcaps;\n}, 0, 4);\n</pre>\n" } ]
2018/11/21
[ "https://wordpress.stackexchange.com/questions/319885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143279/" ]
I am trying to put three menu items before the `Dashboard` menu item in admin dashboard. Problem is that `Dashboard` has menu position `2`. I can manage to put in two menu items before with position `0` and `1`, but `2` collides with Dashboard. So my thought was to move the Dashboard position. Is this possible? Can I change `Dashboard` menu position from `2` to something else (like 3, 4 or 5)? Is there a hook for this?
I have this problem as well, @tony-djukic. I have an administrator user that can see two posts of a custom post type. I have two subscriber users, each are able to only see the opposite post as the other. Here's what I'm using to (apparently not) get all the posts: ``` get_posts(array( 'numberposts' => -1, 'post_type' => 'my-cpt', 'post_status' => get_post_stati(), )) ``` After searching for several of hours in each of the past couple of days for a solution, I came across your (1.5-year-old) unanswered question. With no other option, I traced the code. Here's my work... **1.)** According to the documentation, the `get_posts()` [method](https://developer.wordpress.org/reference/functions/get_posts/#source) returns the result of `WP_Query->query()` with an array of arguments passed (which is of no importance when considering the issue at hand). **2.)** The documentation says that the `WP_Query->query()` [method](https://developer.wordpress.org/reference/classes/wp_query/query/#source) is a pretty simple wrapper that initializes the `WP_Query` object before returning the results of `WP_Query->get_posts()`. **3.)** Next, the `WP_Query->get_posts()` [method](https://developer.wordpress.org/reference/classes/wp_query/get_posts/#source) is called. Somewhere around line 2434, the *read\_post* and *edit\_post* capabilities come into play. Mind you, this is not the *read\_CPT* or *edit\_CPT* primitives of the custom post type, but rather the primitives for the *post* type. Those non-altered primitives are then checked in a `current_user_can` call (see lines 3087, 3096, 3105, and 3111). In other words, if your user does not have the *read\_post* and *edit\_post* capabilities, the posts checked in the `current_user_can()` call will not be included in the results. This is quite counter to the purpose of custom capabilities: the capabilities checked should be the *read\_CPT* or *edit\_CPT* capabilities so this is quite obviously some kind of accident on the coder's part. After all, granting these permission will likely allow your user to edit posts (as well as your custom post type). **NOTE:** The reason why the user is able to read on the front-end is more because of the `public=TRUE` given when registering the post type, not necessarily because of the capability given to the user. What I think I see in the code is that the higher-level capabilities play a role in `protected` and `private` posts more than they do for those CPT's defined as being registered as `public`. **LONG-TERM FIX:** WordPress should define these two variables (on lines 2434 and 2435) after performing a check to determine if a CPT is being queried: obviously, this was overlooked in the coding. What should happen is these variables representing capabilities should be set in the succeeding checks occurring on lines 2437-2443. Namely, that code block should be: ``` if ( ! empty( $post_type_object ) ) { $edit_cap = $post_type_object->cap->edit_post; $read_cap = $post_type_object->cap->read_post; $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_cap = 'edit_'. $post_type_cap; $read_cap = 'read_'. $post_type_cap; $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } ``` **SHORT-TERM FIX:** After all that, I came up with the following temporary solution. The `user_has_cap` [filter](https://developer.wordpress.org/reference/hooks/user_has_cap/) can be implemented in an early hook. The ID of the object to the hook is passed in `$args[2]` of the hook, which can be checked to see if it is the ID of an object having a custom post type. If it is, then the result of the `user_can` [method](https://developer.wordpress.org/reference/functions/user_can/) on that custom capability can be returned. The whole thing could look something like this: ``` add_filter('user_has_cap' function($allcaps, $caps, $args, $user){ $pt = get_post_type($args[2]); if(ctype_digit($args[2]) && $pt !== FALSE ) { $pt_obj = get_post_type_object($pt); if(!is_null($pt_obj) && !$pt_obj->_builtin ) { foreach($caps as $cap) { $type = substr($cap, strrpos($cap, '_')+1); if($type === 'post' || $type === 'posts' ) { // $pt_obj->cap set by get_post_type_capabilities() $allcaps[$cap] = user_can($user, $pt_obj->cap->$cap, $args); } } } } return $allcaps; }, 0, 4); ```
319,901
<p>I've tried to achieve it by using snippet from years ago, but it doesn't seem to work. I need to make it work with Gutenberg (WP 5.0).</p> <p>Is it possible to make it work?</p>
[ { "answer_id": 319904, "author": "LetTheWritersWrite", "author_id": 154481, "author_profile": "https://wordpress.stackexchange.com/users/154481", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/questions/26753/how-to-disable-edit-post-option-after-period-of-time\">How to disable edit post option after period of time?</a>\nSimilar to this explanation you pointed out:</p>\n\n<p>It's preferable to use <code>get_post_time()</code> instead accessing the global variable <code>$post-&gt;post_date</code>. This is really ugly and bad practice.By default it formats to UNIX EPOCH but to be safe pass the U argument.</p>\n\n<p>PHP has a built in function <code>date('U')</code> also in UNIX EPOCH</p>\n\n<pre><code>&lt;?php\nfunction disable_editing_after_twelvehours( $post_object ) {\n $currentTime = date('U');\n $postTime = get_post_time('U',false,$post_object-&gt;ID,false);\n\n $current_user = wp_get_current_user();\n if($current_user-&gt;role['contributor']){\n /*Subtract current time from post time and check if it is greater \n than \n 12hrs(43200 seconds)*/\n if(($currentTime - $postTime) &gt; 43200 {\n $current_user-&gt;cap[0] = false;\n }\n }\n}\nadd_action( 'the_post', 'disable_editing_after_twelvehours' );\n?&gt;\n</code></pre>\n\n<p>hooking it to the post should enable it to check all posts that load. Let me know if you have problems, as I wrote this really quick before losing my train of thought and getting busy.</p>\n" }, { "answer_id": 319907, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>The other suggestions (and the accepted answer in your link) temporarily change a user's capabilities globally. That is a hack. There is hook specifically designed for conditionally adjusting capabilities for specific content: <a href=\"https://developer.wordpress.org/reference/hooks/map_meta_cap/\" rel=\"nofollow noreferrer\"><code>map_meta_cap</code></a>.</p>\n\n<p>When WordPress checks whether a user can edit a post, it checks if the user can <code>edit_post</code>. WordPress decides which actual capability users have that this maps to using the <code>map_meta_cap()</code> function.</p>\n\n<p>For example, when checking if a user can edit a post, it checks if the post was authored by the current user. If it was, then it maps the 'meta capability' <code>edit_post</code> to the 'primitive capability' <code>edit_posts</code>. If the post was authored by someone else it maps it to <code>edit_others_posts</code>. Then it checks if the current user has the mapped capability.</p>\n\n<p>So we can hook into this process so that whenever WordPress maps <code>edit_post</code> we will check if the current user is a Contributor, and if the post is older than 12 hours. If both those things are true we will map <code>edit_post</code> to <code>do_not_allow</code>, meaning that the user will not be allowed to edit it:</p>\n\n<pre><code>function wpse_319901_contributor_can_edit( $caps, $cap, $user_id, $args ) {\n // Stop if this isn't a check for edit_post or delete_post.\n if ( $cap !== 'edit_post' || $cap !== 'delete_post' ) {\n return $caps;\n }\n\n // Get the current user's roles.\n $user = get_userdata( $user_id );\n $roles = $user-&gt;roles;\n\n // Stop if the user is not a Contributor.\n if ( ! in_array( 'contributor', $roles ) ) {\n return $caps;\n }\n\n // For edit_post the post ID will be the first argument in $args.\n $post = get_post( $args[0] );\n\n // Is the post older than 12 hours?\n if ( get_the_time( 'U', $post ) &lt; strtotime( '-12 hours' ) ) {\n // If so, do not allow the user to edit it.\n $caps[] = 'do_not_allow';\n }\n\n return $caps;\n}\nadd_filter( 'map_meta_cap', 'wpse_319901_contributor_can_edit', 10, 4 );\n</code></pre>\n\n<p>You can read more about capabilities and how meta capabilities are mapped to primitive capabilities <a href=\"https://kinsta.com/blog/wordpress-user-roles/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2018/11/22
[ "https://wordpress.stackexchange.com/questions/319901", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136124/" ]
I've tried to achieve it by using snippet from years ago, but it doesn't seem to work. I need to make it work with Gutenberg (WP 5.0). Is it possible to make it work?
The other suggestions (and the accepted answer in your link) temporarily change a user's capabilities globally. That is a hack. There is hook specifically designed for conditionally adjusting capabilities for specific content: [`map_meta_cap`](https://developer.wordpress.org/reference/hooks/map_meta_cap/). When WordPress checks whether a user can edit a post, it checks if the user can `edit_post`. WordPress decides which actual capability users have that this maps to using the `map_meta_cap()` function. For example, when checking if a user can edit a post, it checks if the post was authored by the current user. If it was, then it maps the 'meta capability' `edit_post` to the 'primitive capability' `edit_posts`. If the post was authored by someone else it maps it to `edit_others_posts`. Then it checks if the current user has the mapped capability. So we can hook into this process so that whenever WordPress maps `edit_post` we will check if the current user is a Contributor, and if the post is older than 12 hours. If both those things are true we will map `edit_post` to `do_not_allow`, meaning that the user will not be allowed to edit it: ``` function wpse_319901_contributor_can_edit( $caps, $cap, $user_id, $args ) { // Stop if this isn't a check for edit_post or delete_post. if ( $cap !== 'edit_post' || $cap !== 'delete_post' ) { return $caps; } // Get the current user's roles. $user = get_userdata( $user_id ); $roles = $user->roles; // Stop if the user is not a Contributor. if ( ! in_array( 'contributor', $roles ) ) { return $caps; } // For edit_post the post ID will be the first argument in $args. $post = get_post( $args[0] ); // Is the post older than 12 hours? if ( get_the_time( 'U', $post ) < strtotime( '-12 hours' ) ) { // If so, do not allow the user to edit it. $caps[] = 'do_not_allow'; } return $caps; } add_filter( 'map_meta_cap', 'wpse_319901_contributor_can_edit', 10, 4 ); ``` You can read more about capabilities and how meta capabilities are mapped to primitive capabilities [here](https://kinsta.com/blog/wordpress-user-roles/).
319,915
<p>Strange... I put an if statement for <code>$testvalue = 0</code>. The else part runs and when I echo the value of the <code>$testvalue</code> it gives me a 0.</p> <p>So what is the true value of <code>$testvalue</code>?</p> <p>I need to be able for the if the part to run.</p> <p>I am trying to use the <code>post_exists()</code> function to check if a post exists in the database. If it doesn't exist, I want to call the <code>insert_post()</code> function to auto create a new post or page. but I need this returning a 0 to work.</p> <p>any advice on why <code>$testvalue = 0</code> is not running the if part <code>(echo "before: " . $testvalue)</code></p> <pre><code>if ( ! is_admin() ) { require_once( ABSPATH . 'wp-admin/includes/post.php' ); } add_action('wp_footer', 'my_customoutput'); function my_customoutput(){ $checklinktitle = 'Events 321 Page'; $testvalue = post_exists( $checklinktitle ); if ($testvalue = 0) { echo 'Before: ' . $testvalue; } else { echo 'Firing of Else statement but the value of $testvalue is ' . $testvalue; } } </code></pre>
[ { "answer_id": 319916, "author": "Gufran Hasan", "author_id": 137328, "author_profile": "https://wordpress.stackexchange.com/users/137328", "pm_score": 0, "selected": false, "text": "<p>You need to check emptyness of value by using <a href=\"http://php.net/manual/en/function.empty.php\" rel=\"nofollow noreferrer\"><code>empty()</code></a> function.</p>\n\n<pre><code>if (empty($testvalue)) {\n echo 'Before: ' . $testvalue;\n} else {\n echo 'Firing of Else statement but the value of $testvalue is ' . $testvalue;\n}\n</code></pre>\n\n<p><strong>Note:</strong> The following values are considered to be empty:</p>\n\n<pre><code>\"\" (an empty string)\n0 (0 as an integer)\n0.0 (0 as a float)\n\"0\" (0 as a string)\nNULL\nFALSE\narray() (an empty array)\n</code></pre>\n\n<p>Or you can use <code>$testvalue == 0</code> as <strong>@Krishna Joshi</strong> suggested.</p>\n" }, { "answer_id": 319919, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're not checking the value correctly. A single <code>=</code> sign is the <a href=\"http://php.net/manual/en/language.operators.assignment.php\" rel=\"nofollow noreferrer\">assignment operator</a>. So when you write <code>$variable = 0</code> you are <em>setting</em> the variable to <code>0</code>. This happens regardless of whether or not you're in an <code>if</code> statement.</p>\n\n<p>So when you write <code>if ( $testvalue = 0 ) {</code> you're setting <code>$testvalue</code> to 0, which is essentially the same as false, so the condition will fail.</p>\n\n<p>To compare a value you need to use a <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">comparison operator</a>. You can see that link for more information, but essentially you need to use <code>==</code> to check if values are the same, or <code>===</code> to check if they're the same <em>and</em> the <a href=\"http://php.net/manual/en/language.types.php\" rel=\"nofollow noreferrer\">type</a>.</p>\n\n<pre><code>if ( 0 === $testvalue ) {\n echo 'Before: ' . $testvalue;\n} else {\n echo 'Firing of Else statement but the value of $testvalue is ' . $testvalue;\n}\n</code></pre>\n\n<p>Note that I've used a <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions\" rel=\"nofollow noreferrer\">yoda condition</a>. From the WordPress PHP Coding Standards:</p>\n\n<blockquote>\n <p>When doing logical comparisons involving variables, always put the\n variable on the right side and put constants, literals, or function\n calls on the left side.</p>\n</blockquote>\n" } ]
2018/11/22
[ "https://wordpress.stackexchange.com/questions/319915", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154499/" ]
Strange... I put an if statement for `$testvalue = 0`. The else part runs and when I echo the value of the `$testvalue` it gives me a 0. So what is the true value of `$testvalue`? I need to be able for the if the part to run. I am trying to use the `post_exists()` function to check if a post exists in the database. If it doesn't exist, I want to call the `insert_post()` function to auto create a new post or page. but I need this returning a 0 to work. any advice on why `$testvalue = 0` is not running the if part `(echo "before: " . $testvalue)` ``` if ( ! is_admin() ) { require_once( ABSPATH . 'wp-admin/includes/post.php' ); } add_action('wp_footer', 'my_customoutput'); function my_customoutput(){ $checklinktitle = 'Events 321 Page'; $testvalue = post_exists( $checklinktitle ); if ($testvalue = 0) { echo 'Before: ' . $testvalue; } else { echo 'Firing of Else statement but the value of $testvalue is ' . $testvalue; } } ```
You're not checking the value correctly. A single `=` sign is the [assignment operator](http://php.net/manual/en/language.operators.assignment.php). So when you write `$variable = 0` you are *setting* the variable to `0`. This happens regardless of whether or not you're in an `if` statement. So when you write `if ( $testvalue = 0 ) {` you're setting `$testvalue` to 0, which is essentially the same as false, so the condition will fail. To compare a value you need to use a [comparison operator](http://php.net/manual/en/language.operators.comparison.php). You can see that link for more information, but essentially you need to use `==` to check if values are the same, or `===` to check if they're the same *and* the [type](http://php.net/manual/en/language.types.php). ``` if ( 0 === $testvalue ) { echo 'Before: ' . $testvalue; } else { echo 'Firing of Else statement but the value of $testvalue is ' . $testvalue; } ``` Note that I've used a [yoda condition](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions). From the WordPress PHP Coding Standards: > > When doing logical comparisons involving variables, always put the > variable on the right side and put constants, literals, or function > calls on the left side. > > >
319,922
<p>I have 8 Instagram URLs in this <a href="https://blog.wwf.sg/ocean/2018/11/netflix-documentaries-our-planet-okja-dogs/" rel="nofollow noreferrer">post</a> out of which 3 are not converted into embed/iframes.</p> <p>I'm using Gutenberg's Instagram embed blog to add the URL's.<a href="https://blog.wwf.sg/ocean/2018/11/netflix-documentaries-our-planet-okja-dogs/#" rel="nofollow noreferrer">https://blog.wwf.sg/ocean/2018/11/netflix-documentaries-our-planet-okja-dogs/#</a></p> <p>I see the block code in the classic editor which is same as other instagram blocks which render properly but for <a href="https://www.instagram.com/p/BqDzw0CF3pC/" rel="nofollow noreferrer">https://www.instagram.com/p/BqDzw0CF3pC/</a> it just returns URL.</p> <pre><code>&lt;!-- wp:core-embed/instagram {"url":"https://www.instagram.com/p/BqDzw0CF3pC/","type":"rich","providerNameSlug":"instagram","className":""} --&gt; &lt;figure class="wp-block-embed-instagram wp-block-embed is-type-rich is-provider-instagram"&gt; &lt;div class="wp-block-embed__wrapper"&gt; https://www.instagram.com/p/BqDzw0CF3pC/ &lt;/div&gt; &lt;/figure&gt; &lt;!-- /wp:core-embed/instagram --&gt; </code></pre> <p>I tried using shortcode also it's the same result only the below 3 Instagram posts don't render. </p> <p><code>[embed]https://www.instagram.com/p/BqDzw0CF3pC/[/embed]</code></p> <p>I need help debugging this weired issue</p> <ul> <li><a href="http://www.instagram.com/p/BMY9o6yA6m1" rel="nofollow noreferrer">http://www.instagram.com/p/BMY9o6yA6m1</a></li> <li><a href="http://www.instagram.com/p/BeqpirDAbol" rel="nofollow noreferrer">http://www.instagram.com/p/BeqpirDAbol</a></li> <li><a href="https://www.instagram.com/p/BqDzw0CF3pC/" rel="nofollow noreferrer">https://www.instagram.com/p/BqDzw0CF3pC/</a></li> </ul>
[ { "answer_id": 319931, "author": "Manoj H L", "author_id": 36203, "author_profile": "https://wordpress.stackexchange.com/users/36203", "pm_score": 3, "selected": true, "text": "<p>Figured it out. </p>\n\n<p>Embed shortcode stores the oemebd data as post meta using md5 hash.</p>\n\n<p><a href=\"https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/class-wp-embed.php#L198\" rel=\"nofollow noreferrer\">wp-includes/class-wp-embed.php</a></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Check for a cached result (stored in the post meta)\n$key_suffix = md5( $url . serialize( $attr ) );\n$cachekey = '_oembed_' . $key_suffix;\n$cachekey_time = '_oembed_time_' . $key_suffix;\n</code></pre>\n\n<p>And has a cache mechanism to fetch new data only after a day.</p>\n\n<p>I deleted the post meta and then it started working.</p>\n" }, { "answer_id": 369335, "author": "Sh Svyatoslav", "author_id": 190223, "author_profile": "https://wordpress.stackexchange.com/users/190223", "pm_score": 0, "selected": false, "text": "<p>I had the same problem, for me the solution was to add this code to theme.</p>\n<pre><code>if ( !isset( $content_width ) ) $content_width = 550;\n</code></pre>\n<p>More info <a href=\"https://www.wpexplorer.com/wordpress-oembed/\" rel=\"nofollow noreferrer\">https://www.wpexplorer.com/wordpress-oembed/</a></p>\n<p>Hope it helps someone.</p>\n" } ]
2018/11/22
[ "https://wordpress.stackexchange.com/questions/319922", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36203/" ]
I have 8 Instagram URLs in this [post](https://blog.wwf.sg/ocean/2018/11/netflix-documentaries-our-planet-okja-dogs/) out of which 3 are not converted into embed/iframes. I'm using Gutenberg's Instagram embed blog to add the URL's.<https://blog.wwf.sg/ocean/2018/11/netflix-documentaries-our-planet-okja-dogs/#> I see the block code in the classic editor which is same as other instagram blocks which render properly but for <https://www.instagram.com/p/BqDzw0CF3pC/> it just returns URL. ``` <!-- wp:core-embed/instagram {"url":"https://www.instagram.com/p/BqDzw0CF3pC/","type":"rich","providerNameSlug":"instagram","className":""} --> <figure class="wp-block-embed-instagram wp-block-embed is-type-rich is-provider-instagram"> <div class="wp-block-embed__wrapper"> https://www.instagram.com/p/BqDzw0CF3pC/ </div> </figure> <!-- /wp:core-embed/instagram --> ``` I tried using shortcode also it's the same result only the below 3 Instagram posts don't render. `[embed]https://www.instagram.com/p/BqDzw0CF3pC/[/embed]` I need help debugging this weired issue * <http://www.instagram.com/p/BMY9o6yA6m1> * <http://www.instagram.com/p/BeqpirDAbol> * <https://www.instagram.com/p/BqDzw0CF3pC/>
Figured it out. Embed shortcode stores the oemebd data as post meta using md5 hash. [wp-includes/class-wp-embed.php](https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/class-wp-embed.php#L198) ```php // Check for a cached result (stored in the post meta) $key_suffix = md5( $url . serialize( $attr ) ); $cachekey = '_oembed_' . $key_suffix; $cachekey_time = '_oembed_time_' . $key_suffix; ``` And has a cache mechanism to fetch new data only after a day. I deleted the post meta and then it started working.
319,971
<p>I've been reviewing tutorials on creating blocks for Gutenberg but I am unclear how to handle a particular use case - conditional blocks.</p> <p>I am looking at creating a custom post type for which I will register my own block type. These blocks will only be displayed if certain conditions are true. These conditions will be either boolean flags or integer comparisons (the values coming from wither custom user variables (meta) or session values).</p> <p>If all conditions are true the block should be rendered but if one or more are false then (obviously) nothing is shown.</p> <p>I cannot quite get my head around where I would place the logic for this. Admittedly my grasp of this new Gutenberg system is a bit shaky which is probably why I need some assistance.</p> <h3>For example:</h3> <pre><code>&lt;p logic=&quot;IF(is_logged_in,SHOW,HIDE)&quot;&gt;My wonderful secret bit just for members.&lt;/p&gt; </code></pre>
[ { "answer_id": 342130, "author": "David", "author_id": 104457, "author_profile": "https://wordpress.stackexchange.com/users/104457", "pm_score": 0, "selected": false, "text": "<p>If you want to give the editor control over what blocks are displayed to logged in users or not you could use this plugin: <a href=\"https://wordpress.org/plugins/block-options/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/block-options/</a></p>\n\n<p>Then you do not need to code it into your block as every block will have the option of being only for your members or not.</p>\n" }, { "answer_id": 343333, "author": "SkyShab", "author_id": 63263, "author_profile": "https://wordpress.stackexchange.com/users/63263", "pm_score": 3, "selected": false, "text": "<p>In the edit method for your custom block, when rendering the components you can use the \"conditional + &amp;&amp;\" pattern:</p>\n\n<pre><code> &lt;PanelBody title={ __( 'My Panel' ) } &gt;\n\n { myCustomBool &amp;&amp;\n &lt;MyComponent\n value={theValue}\n onChange={ value =&gt; {\n myChangeCallback(value);\n } }\n /&gt;\n }\n { 'marmots' !== myCustomThing &amp;&amp;\n &lt;MyOtherComponent\n value={theValue}\n onChange={ value =&gt; {\n myOtherCallback(value);\n } }\n /&gt;\n }\n\n &lt;/PanelBody&gt;\n</code></pre>\n\n<p>In the above example, the conditionals just before the \"&amp;&amp;\" will determine whether the component that follows will be rendered. </p>\n\n<p>This is sometimes referred to as a \"short circuit conditional\". </p>\n" }, { "answer_id": 384948, "author": "Morgan", "author_id": 180735, "author_profile": "https://wordpress.stackexchange.com/users/180735", "pm_score": 2, "selected": false, "text": "<p>I've worked a lot on Conditional Blocks, the hardest part is finding where to start with Gutenberg.</p>\n<p>You'd want to add custom attributes (settings) to each block using JavaScript. Everything is stored in block attributes.</p>\n<p>Here's a good example of adding additional settings to existing blocks. <a href=\"https://jeffreycarandang.com/extending-gutenberg-core-blocks-with-custom-attributes-and-controls/\" rel=\"nofollow noreferrer\">https://jeffreycarandang.com/extending-gutenberg-core-blocks-with-custom-attributes-and-controls/</a></p>\n<p>Once the attributes are saved to the block then you can pick up on them in PHP using the &quot;render_block&quot; filter hook. Each block will run through this filter, it's your chance to alter the block content based on the attributes.</p>\n<p><a href=\"https://developer.wordpress.org/reference/hooks/render_block/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/render_block/</a></p>\n<p>Here's a very simplified example.<code>$block_content</code> is the html that will be displayed. <code>$block</code> contains the block data.</p>\n<pre><code>function my_conditional_render( $block_content, $block ) {\n if ( $block['attrs']['myCustomToggle'] === true ) {\n return ''; // Don't render this block.\n }\n \n return $block_content;\n}\n \nadd_filter( 'render_block', 'my_conditional_render', 10, 2 );\n\n</code></pre>\n<p>This method is very similar to how I've created the plugin <a href=\"https://conditionalblocks.com/\" rel=\"nofollow noreferrer\">https://conditionalblocks.com/</a> with a bunch of pre-made conditions </p>\n" } ]
2018/11/22
[ "https://wordpress.stackexchange.com/questions/319971", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
I've been reviewing tutorials on creating blocks for Gutenberg but I am unclear how to handle a particular use case - conditional blocks. I am looking at creating a custom post type for which I will register my own block type. These blocks will only be displayed if certain conditions are true. These conditions will be either boolean flags or integer comparisons (the values coming from wither custom user variables (meta) or session values). If all conditions are true the block should be rendered but if one or more are false then (obviously) nothing is shown. I cannot quite get my head around where I would place the logic for this. Admittedly my grasp of this new Gutenberg system is a bit shaky which is probably why I need some assistance. ### For example: ``` <p logic="IF(is_logged_in,SHOW,HIDE)">My wonderful secret bit just for members.</p> ```
In the edit method for your custom block, when rendering the components you can use the "conditional + &&" pattern: ``` <PanelBody title={ __( 'My Panel' ) } > { myCustomBool && <MyComponent value={theValue} onChange={ value => { myChangeCallback(value); } } /> } { 'marmots' !== myCustomThing && <MyOtherComponent value={theValue} onChange={ value => { myOtherCallback(value); } } /> } </PanelBody> ``` In the above example, the conditionals just before the "&&" will determine whether the component that follows will be rendered. This is sometimes referred to as a "short circuit conditional".
320,000
<p>I'm looking for adding a custom css in the admin panel by targeting user id cause I have another administrator but I want to hide something from him by css. I'm using this code to put some stylesheet files in the admin panel, but its for all users </p> <pre><code>add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo ' &lt;link rel="stylesheet" type="text/css" href="../../admincss.css?v=1.3"&gt;'; } </code></pre>
[ { "answer_id": 320002, "author": "Gamal Elwazeery", "author_id": 154315, "author_profile": "https://wordpress.stackexchange.com/users/154315", "pm_score": -1, "selected": true, "text": "<p>done it</p>\n\n<pre><code>add_action('admin_head', 'my_custom_fonts');\n\nfunction my_custom_fonts() {\n global $current_user;\n $user_id = get_current_user_id();\nif(is_admin() &amp;&amp; $user_id == '2'){\n echo ' &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"../../new.css\"&gt;';\n }\n\n\n}\n</code></pre>\n" }, { "answer_id": 320003, "author": "Parth Shah", "author_id": 154328, "author_profile": "https://wordpress.stackexchange.com/users/154328", "pm_score": 0, "selected": false, "text": "<p>Use below code into functions.php file. Make sure you are using it right way \nuse admin_enqueue_scripts</p>\n\n<pre><code>add_action('admin_enqueue_scripts', 'FUNCTION_NAME');function FUNCTION_NAME() {\n global $current_user;\n $user_id = get_current_user_id();\n if(is_admin() &amp;&amp; $user_id == '2'){\n wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );\n}}\n</code></pre>\n" } ]
2018/11/23
[ "https://wordpress.stackexchange.com/questions/320000", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154315/" ]
I'm looking for adding a custom css in the admin panel by targeting user id cause I have another administrator but I want to hide something from him by css. I'm using this code to put some stylesheet files in the admin panel, but its for all users ``` add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo ' <link rel="stylesheet" type="text/css" href="../../admincss.css?v=1.3">'; } ```
done it ``` add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { global $current_user; $user_id = get_current_user_id(); if(is_admin() && $user_id == '2'){ echo ' <link rel="stylesheet" type="text/css" href="../../new.css">'; } } ```
320,016
<p><br> I'm having troubles with the mysqli driver used by wordpress, where it is converting each and every integer value to a string within <code>$wpdb-&gt;get_results("SELECT...")</code>.<br> I know that it is possible so use the the option MYSQLI_OPT_INT_AND_FLOAT_NATIVE with the mysqli driver (<code>$mysqli-&gt;options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);</code>) but I don't seem to find a way to set this option in wordpress.<br> How do I do that?<br></p> <p>Thank you</p> <p><strong>EDIT</strong></p> <p>Based on the comments below, I'b better further explain what I'm trying to achieve.<br> I'm developing a plugin to add reactive/responsive functionalities to wordpress both in the backend and in the frontend (exactly like Gutenberg). In my plugin I need to access a variety of structures in the database, and I'm doing that using using AJAX along with VueJS which makes extensive use of observables.<br> Let's say, for example that I have a structure like this in the database:</p> <pre><code>CREATE TABLE IF NOT EXISTS `a_table` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(190) NOT NULL DEFAULT 'New name', `anInteger` INT NOT NULL DEFAULT '123', `aBoolean` BOOLEAN NOT NULL DEFAULT TRUE PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`));" </code></pre> <p>and that I'm accessing the table via AJAX to bind the data to something like this in Vue:</p> <pre><code>&lt;template&gt; &lt;el-form :model="aTable" ref="tableForm"&gt; &lt;el-row&gt; &lt;el-col :span="4"&gt; &lt;el-form-item label="Name" prop="name"&gt; &lt;el-input v-model="aTable.name"&gt; &lt;/el-input&gt; &lt;/el-form-item&gt; &lt;/el-col&gt; &lt;el-col :span="2"&gt; &lt;el-form-item label="BoolVal" prop="aBoolean"&gt; &lt;el-switch v-model="aTable.aBoolean"&gt;&lt;/el-switch&gt; &lt;/el-form-item&gt; &lt;/el-col&gt; &lt;el-col :span="8"&gt; &lt;el-form-item label="NumberVal" prop="anInteger"&gt; &lt;el-input-number v-model="aTable.anInteger"&gt;&lt;/el-input-number&gt; &lt;/el-form-item&gt; &lt;/el-col&gt; &lt;/el-row&gt; &lt;/el-form&gt; &lt;/template&gt; &lt;script&gt; export default { props: { aTable: { type: Object, default: function() { return {}; } } }, data() { return { }; }, methods: { } }; &lt;/script&gt; //AJAX and other glue code omitted </code></pre> <p>With this set up, the input filed "name" is correctly bound and displays the string "new name", while the boolean switch shows always false (VueJS is expecting a boolean or, at least, an integer, and is getting a string instead!). This forces me to manipulate the results I get from $wpdb before returning the dataset to the AJAX caller if I want VueJS understand correctly what I retrieve from the database, like this:</p> <pre><code>static function ajax_get_table() { global $wpdb; $response = $wpdb-&gt;get_results("SELECT * FROM `a_table` WHERE 1=1 ORDER BY `id`"); // MYSQLI_OPT_INT_AND_FLOAT_NATIVE Hack // mysql is returning each and every integer/boolean as a string // This hack is needed to retrieve correct data type array_walk($response, function(&amp;$item, $key) { array_walk($item, function(&amp;$subitem, $subkey) { // Integers if (in_array($subkey, ['id', 'anInteger'])) $subitem = intval($subitem); // Boolenas if (in_array($subkey, ['aBoolean'])) $subitem = boolval($subitem); }); }); // AJAX termination wp_send_json($response); die(); } </code></pre> <p>But this means that I have to know in advance each end every data type returned from the MYSQL query, which is by far an anti-pattern programming technique. </p> <p>That's why I'm wondering why is Wordpress stuck to this pre-PHP-5.3 limitation.</p>
[ { "answer_id": 320166, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>That's why I'm wondering why is Wordpress stuck to this pre-PHP-5.3\n limitation.</p>\n</blockquote>\n\n<p>Because WordPress has made the decision to support PHP 5.2 due to the large number of hosts that continue to use it. This is an ongoing debate and there's no point rehashing it all here.</p>\n\n<blockquote>\n <p>But this means that I have to know in advance each end every data type returned from the MYSQL query, which is by far an anti-pattern programming technique.</p>\n</blockquote>\n\n<p>What? MySQL in PHP, by default, only returns strings. So there you go. That's \"each and every data type\" that you need to know.</p>\n\n<p>Regardless, you <em>should</em> know what your query is likely to return before outputting it to a page. And you should be verifying and escaping it before outputting it in the browser or an API response.</p>\n\n<p>Most things like this have some sort of model that represents the data that sits between the front-end and the database. What <em>is</em> an anti-pattern is having your front-end so tightly coupled to the minutiae of how the data is stored.</p>\n" }, { "answer_id": 374295, "author": "Paul Phillips", "author_id": 13527, "author_profile": "https://wordpress.stackexchange.com/users/13527", "pm_score": 0, "selected": false, "text": "<p>This is how you do it:</p>\n<pre><code>$wpdb-&gt;dbh-&gt;options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);\n</code></pre>\n<p>dbh is the native PHP mysqli object within ezSQL.</p>\n" } ]
2018/11/23
[ "https://wordpress.stackexchange.com/questions/320016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I'm having troubles with the mysqli driver used by wordpress, where it is converting each and every integer value to a string within `$wpdb->get_results("SELECT...")`. I know that it is possible so use the the option MYSQLI\_OPT\_INT\_AND\_FLOAT\_NATIVE with the mysqli driver (`$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);`) but I don't seem to find a way to set this option in wordpress. How do I do that? Thank you **EDIT** Based on the comments below, I'b better further explain what I'm trying to achieve. I'm developing a plugin to add reactive/responsive functionalities to wordpress both in the backend and in the frontend (exactly like Gutenberg). In my plugin I need to access a variety of structures in the database, and I'm doing that using using AJAX along with VueJS which makes extensive use of observables. Let's say, for example that I have a structure like this in the database: ``` CREATE TABLE IF NOT EXISTS `a_table` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(190) NOT NULL DEFAULT 'New name', `anInteger` INT NOT NULL DEFAULT '123', `aBoolean` BOOLEAN NOT NULL DEFAULT TRUE PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`));" ``` and that I'm accessing the table via AJAX to bind the data to something like this in Vue: ``` <template> <el-form :model="aTable" ref="tableForm"> <el-row> <el-col :span="4"> <el-form-item label="Name" prop="name"> <el-input v-model="aTable.name"> </el-input> </el-form-item> </el-col> <el-col :span="2"> <el-form-item label="BoolVal" prop="aBoolean"> <el-switch v-model="aTable.aBoolean"></el-switch> </el-form-item> </el-col> <el-col :span="8"> <el-form-item label="NumberVal" prop="anInteger"> <el-input-number v-model="aTable.anInteger"></el-input-number> </el-form-item> </el-col> </el-row> </el-form> </template> <script> export default { props: { aTable: { type: Object, default: function() { return {}; } } }, data() { return { }; }, methods: { } }; </script> //AJAX and other glue code omitted ``` With this set up, the input filed "name" is correctly bound and displays the string "new name", while the boolean switch shows always false (VueJS is expecting a boolean or, at least, an integer, and is getting a string instead!). This forces me to manipulate the results I get from $wpdb before returning the dataset to the AJAX caller if I want VueJS understand correctly what I retrieve from the database, like this: ``` static function ajax_get_table() { global $wpdb; $response = $wpdb->get_results("SELECT * FROM `a_table` WHERE 1=1 ORDER BY `id`"); // MYSQLI_OPT_INT_AND_FLOAT_NATIVE Hack // mysql is returning each and every integer/boolean as a string // This hack is needed to retrieve correct data type array_walk($response, function(&$item, $key) { array_walk($item, function(&$subitem, $subkey) { // Integers if (in_array($subkey, ['id', 'anInteger'])) $subitem = intval($subitem); // Boolenas if (in_array($subkey, ['aBoolean'])) $subitem = boolval($subitem); }); }); // AJAX termination wp_send_json($response); die(); } ``` But this means that I have to know in advance each end every data type returned from the MYSQL query, which is by far an anti-pattern programming technique. That's why I'm wondering why is Wordpress stuck to this pre-PHP-5.3 limitation.
> > That's why I'm wondering why is Wordpress stuck to this pre-PHP-5.3 > limitation. > > > Because WordPress has made the decision to support PHP 5.2 due to the large number of hosts that continue to use it. This is an ongoing debate and there's no point rehashing it all here. > > But this means that I have to know in advance each end every data type returned from the MYSQL query, which is by far an anti-pattern programming technique. > > > What? MySQL in PHP, by default, only returns strings. So there you go. That's "each and every data type" that you need to know. Regardless, you *should* know what your query is likely to return before outputting it to a page. And you should be verifying and escaping it before outputting it in the browser or an API response. Most things like this have some sort of model that represents the data that sits between the front-end and the database. What *is* an anti-pattern is having your front-end so tightly coupled to the minutiae of how the data is stored.
320,046
<p>How can the plugin directory path be returned into <code>&lt;script&gt; &lt;/script&gt;</code> instead of hard coding the path?</p> <p>Here is the custom-page.php:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;script type="text/javascript" src="http://local.wordpress.test/wp-content/plugins/path-to-file/script.js"&gt;&lt;/script&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 320048, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 3, "selected": true, "text": "<p>Take a look at this: <a href=\"https://wordpress.stackexchange.com/a/119084/121955\">https://wordpress.stackexchange.com/a/119084/121955</a></p>\n\n<pre><code>plugins_url( \"path/to/file\", __FILE__ );\n</code></pre>\n\n<p>EDITED:</p>\n\n<pre><code>&lt;script src=\"&lt;?php echo plugins_url( \"path/to/file\", __FILE__ ); ?&gt;\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 320058, "author": "65535", "author_id": 154419, "author_profile": "https://wordpress.stackexchange.com/users/154419", "pm_score": 2, "selected": false, "text": "<p>To make the plugin url available in javascript:</p>\n\n<pre><code>/**\n *register the javascript\n */\n wp_register_script( 'some_handle', plugins_url( \"plugin-name/path-to-file/script.js\") );\n\n /**\n *localize the plugin url.\n *someObjectName.pluginsUrl then can be used to return\n *the plugin url to the javascript\n */\n wp_localize_script('some_handle', 'someObjectName', array(\n 'pluginsUrl' =&gt; plugins_url( \"plugin-name/path-to-file/script.js\"),\n ));\n</code></pre>\n\n<p>From Javascript the plugin url can be returned in the following way:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n var url = someObjectName.pluginsUrl;\n alert( url );\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 320101, "author": "Joshua Trimm", "author_id": 128282, "author_profile": "https://wordpress.stackexchange.com/users/128282", "pm_score": 0, "selected": false, "text": "<p>Here is an example from one of my plugins I developed. </p>\n\n<pre><code> function insert_scripts()\n{\n wp_enqueue_script('jquery', '&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;', '1.0.0', true);\n\n wp_enqueue_script( 'test1', plugin_dir_url( __FILE__ ) . 'js/test1.js', array('jquery'), '1.0.0', true );\n wp_enqueue_script( 'test2', plugin_dir_url( __FILE__ ) . 'js/test2.js', array('jquery'), '1.0.0', true );\n}\n\nadd_action( 'wp_enqueue_scripts', 'xwp_insert_scripts' );\n</code></pre>\n\n<p>As per the code above, the scripts should load into the head. However, if modification have been made they could load else where. This funtion will need to be added to a functions.php file. NOTE: if you add this to the core theme functions.php file it will be modified upon update. Best bet is to create a child theme and use a custom functions.php file. </p>\n" }, { "answer_id": 320111, "author": "65535", "author_id": 154419, "author_profile": "https://wordpress.stackexchange.com/users/154419", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\" src=\"&lt;?php echo plugins_url( \"plugin-name/path-to-file/script.js\"); ?&gt;\"&gt;&lt;/script&gt;\n</code></pre>\n" } ]
2018/11/23
[ "https://wordpress.stackexchange.com/questions/320046", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154419/" ]
How can the plugin directory path be returned into `<script> </script>` instead of hard coding the path? Here is the custom-page.php: ``` <?php get_header(); ?> <script type="text/javascript" src="http://local.wordpress.test/wp-content/plugins/path-to-file/script.js"></script> <?php get_footer(); ?> ```
Take a look at this: <https://wordpress.stackexchange.com/a/119084/121955> ``` plugins_url( "path/to/file", __FILE__ ); ``` EDITED: ``` <script src="<?php echo plugins_url( "path/to/file", __FILE__ ); ?>"></script> ```
320,054
<p>I'm trying to use Wordpress paginate function to only show 3 pages at most(client wants it this way) so that when you go up a page it shows the current page you're on and the previous and next page:</p> <p><a href="https://i.stack.imgur.com/4MwdS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4MwdS.png" alt="This is the result they want"></a></p> <p>Unfortunately when I do it I get several pages including the last page:</p> <p><a href="https://i.stack.imgur.com/gJm8K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gJm8K.png" alt="This is the result I get from my code"></a> </p> <p>This is my current paginate code, please note the format is like this because I have Tabs that each need to be paged with different queries</p> <pre><code>echo '&lt;div id ="nav_pages"&gt;'; echo '&lt;div class="prev_first"&gt;&lt;/div&gt;'; echo '&lt;div class="pages"&gt;'; $pag_args1 = array( 'type' =&gt; 'list', 'prev_next' =&gt; False, 'end_size' =&gt; 1, 'add_args' =&gt; false, 'add_fragment' =&gt; '', 'show_all' =&gt; false, 'base' =&gt; '' . $url . '?paged1=%#%', 'format' =&gt; '?paged1=%#%', 'current' =&gt; $paged1, 'total' =&gt; $get_mining-&gt;max_num_pages); echo paginate_links( $pag_args1 ); echo '&lt;/div&gt;'; echo '&lt;div class="page_x_of_y2"&gt;Page &lt;span&gt;' . $paged1 . '&lt;/span&gt; of &lt;span&gt;' . $get_mining-&gt;max_num_pages . '&lt;/span&gt;&lt;/div&gt;'; echo '&lt;/div&gt;'; </code></pre> <p>Is there anyway I can modify this code to look like the pagination in the first image rather than what it looks like in the second one? Do I need to write a custom paginate function to achieve this? I dont agree with what the client wants as I feel like the latter is a better option but you know what they say: "The customer is always right" </p> <h2><strong>UPDATED PARTIAL SOLUTION</strong></h2> <p>So after doing bit more reseach I found this link:<a href="https://wordpress.stackexchange.com/questions/237753/getting-paginate-links-end-size-to-display-none">Getting paginate_links()'end_size' to display 0</a> This solution almost allows me to achieve the goal I want here is my modified code:</p> <pre><code>echo '&lt;div id ="nav_pages"&gt;'; echo '&lt;div class="prev_first"&gt;&lt;/div&gt;'; echo '&lt;div class="pages"&gt;'; $pag_args1 = array( 'type' =&gt; 'array', 'prev_next' =&gt; False, 'end_size' =&gt; 0, 'mid_size' =&gt; 1, 'add_args' =&gt; false, 'add_fragment' =&gt; '', 'show_all' =&gt; false, 'base' =&gt; '' . $url . '?paged1=%#%', 'format' =&gt; '?paged1=%#%', 'current' =&gt; $paged1, 'total' =&gt; $get_mining-&gt;max_num_pages); $paginate_links = paginate_links( $pag_args1 ); $c=$pag_args1['current']; $allowed=[sprintf('/?paged1=%d',$c-1),'current',sprintf('?paged1=%d',$c+1)]; $paginate_links=array_filter( $paginate_links, function( $value ) use ( $allowed ) { foreach( (array) $allowed as $tag ) { if( false !== strpos( $value, $tag ) ) return true; } return false; } ); if( ! empty( $paginate_links ) ) printf("&lt;ul class='page-numbers'&gt;\n\t&lt;li&gt;%s&lt;/li&gt;\n&lt;/ul&gt;\n",join( "&lt;/li&gt;\n\t&lt;li&gt;", $paginate_links)); echo '&lt;/div&gt;'; echo '&lt;div class="page_x_of_y2"&gt;Page &lt;span&gt;' . $paged1 . '&lt;/span&gt; of &lt;span&gt;' . $get_mining-&gt;max_num_pages . '&lt;/span&gt;&lt;/div&gt;'; echo '&lt;/div&gt;'; }//Endif </code></pre> <p>This almost achieves what I want, the only problem now is that it wont show the previous page when I go above page 1. I'm getting Closer!!</p>
[ { "answer_id": 320069, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 1, "selected": false, "text": "<p>Check the mid_size parameter in <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow noreferrer\">paginate_links</a></p>\n\n<blockquote>\n <p>mid_size: How many numbers to either side of current page, but not including current page. Default 2.</p>\n</blockquote>\n\n<p>So set it to: <code>'mid_size' =&gt; 1</code></p>\n\n<p>Also you probably don't want to show the first and last page, so set it to 0 (it's 1 by default): <code>'end_size' =&gt; 0</code></p>\n\n<p>Hope this helps.</p>\n\n<p>-</p>\n\n<p>EDIT:</p>\n\n<p>It seems like the end property does not hide the last element. The easiest way is to hide it is using CSS:</p>\n\n<pre><code>.dots ~ .dots + .page-numbers { display: none; }\n</code></pre>\n\n<p>Otherwise, to remove the actual output from the function you would need to tweak it. You can return an array changing the <code>type</code> argument, loop through the elements and remove the one you are not interested in.</p>\n" }, { "answer_id": 320333, "author": "Zayd Bhyat", "author_id": 93537, "author_profile": "https://wordpress.stackexchange.com/users/93537", "pm_score": 1, "selected": true, "text": "<p>Found the answer thanks to the link in the updated part of my question. Here is the solution to it:</p>\n\n<pre><code>echo '&lt;div id =\"nav_pages\"&gt;'; \n echo '&lt;div class=\"prev_first\"&gt;&lt;/div&gt;'; \n echo '&lt;div class=\"pages\"&gt;';\n$pag_args1 = array(\n'type' =&gt; 'array',\n'prev_next' =&gt; False,\n'end_size' =&gt; 0,\n'mid_size' =&gt; 1,\n'add_args' =&gt; false,\n'add_fragment' =&gt; '',\n'show_all' =&gt; false,\n'base' =&gt; '' . $url . '?paged1=%#%', \n 'format' =&gt; '?paged1=%#%',\n 'current' =&gt; $paged1,\n 'total' =&gt; $get_mining-&gt;max_num_pages);\n $paginate_links = paginate_links( $pag_args1 );\n $c=$pag_args1['current'];\n $allowed=[sprintf('?paged1=%d',$c-1),'current',sprintf('?paged1=%d',$c+1)];\n $paginate_links=array_filter(\n $paginate_links,\n function( $value ) use ( $allowed ) {\n foreach( (array) $allowed as $tag )\n {\n if( false !== strpos( $value, $tag ) )\n return true;\n }\n return false;\n }\n);\n\n if( ! empty( $paginate_links ) )\n printf(\"&lt;ul class='page-numbers'&gt;\\n\\t&lt;li&gt;%s&lt;/li&gt;\\n&lt;/ul&gt;\\n\",join( \"&lt;/li&gt;\\n\\t&lt;li&gt;\", $paginate_links));\n echo '&lt;/div&gt;';\n echo '&lt;div class=\"page_x_of_y2\"&gt;Page &lt;span&gt;' . $paged1 . '&lt;/span&gt; of &lt;span&gt;' . $get_mining-&gt;max_num_pages . '&lt;/span&gt;&lt;/div&gt;'; \n echo '&lt;/div&gt;';\n</code></pre>\n\n<p>So what I had to do was: </p>\n\n<ol>\n<li>Make the pagination arguments into an array</li>\n<li>Store the resultant Array in a variable and store the current page in a variable</li>\n<li>Create another variable with allowed values, in this case its the current page and a page up and down on either side.</li>\n<li>Filter the array with a function that allows only the allowed values</li>\n<li>Finally display the pagination array if there are pages to display.</li>\n</ol>\n\n<p>My solution looks like this now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Y9eYJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y9eYJ.png\" alt=\"Solution I wanted and achieved\"></a></p>\n" } ]
2018/11/23
[ "https://wordpress.stackexchange.com/questions/320054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93537/" ]
I'm trying to use Wordpress paginate function to only show 3 pages at most(client wants it this way) so that when you go up a page it shows the current page you're on and the previous and next page: [![This is the result they want](https://i.stack.imgur.com/4MwdS.png)](https://i.stack.imgur.com/4MwdS.png) Unfortunately when I do it I get several pages including the last page: [![This is the result I get from my code](https://i.stack.imgur.com/gJm8K.png)](https://i.stack.imgur.com/gJm8K.png) This is my current paginate code, please note the format is like this because I have Tabs that each need to be paged with different queries ``` echo '<div id ="nav_pages">'; echo '<div class="prev_first"></div>'; echo '<div class="pages">'; $pag_args1 = array( 'type' => 'list', 'prev_next' => False, 'end_size' => 1, 'add_args' => false, 'add_fragment' => '', 'show_all' => false, 'base' => '' . $url . '?paged1=%#%', 'format' => '?paged1=%#%', 'current' => $paged1, 'total' => $get_mining->max_num_pages); echo paginate_links( $pag_args1 ); echo '</div>'; echo '<div class="page_x_of_y2">Page <span>' . $paged1 . '</span> of <span>' . $get_mining->max_num_pages . '</span></div>'; echo '</div>'; ``` Is there anyway I can modify this code to look like the pagination in the first image rather than what it looks like in the second one? Do I need to write a custom paginate function to achieve this? I dont agree with what the client wants as I feel like the latter is a better option but you know what they say: "The customer is always right" **UPDATED PARTIAL SOLUTION** ---------------------------- So after doing bit more reseach I found this link:[Getting paginate\_links()'end\_size' to display 0](https://wordpress.stackexchange.com/questions/237753/getting-paginate-links-end-size-to-display-none) This solution almost allows me to achieve the goal I want here is my modified code: ``` echo '<div id ="nav_pages">'; echo '<div class="prev_first"></div>'; echo '<div class="pages">'; $pag_args1 = array( 'type' => 'array', 'prev_next' => False, 'end_size' => 0, 'mid_size' => 1, 'add_args' => false, 'add_fragment' => '', 'show_all' => false, 'base' => '' . $url . '?paged1=%#%', 'format' => '?paged1=%#%', 'current' => $paged1, 'total' => $get_mining->max_num_pages); $paginate_links = paginate_links( $pag_args1 ); $c=$pag_args1['current']; $allowed=[sprintf('/?paged1=%d',$c-1),'current',sprintf('?paged1=%d',$c+1)]; $paginate_links=array_filter( $paginate_links, function( $value ) use ( $allowed ) { foreach( (array) $allowed as $tag ) { if( false !== strpos( $value, $tag ) ) return true; } return false; } ); if( ! empty( $paginate_links ) ) printf("<ul class='page-numbers'>\n\t<li>%s</li>\n</ul>\n",join( "</li>\n\t<li>", $paginate_links)); echo '</div>'; echo '<div class="page_x_of_y2">Page <span>' . $paged1 . '</span> of <span>' . $get_mining->max_num_pages . '</span></div>'; echo '</div>'; }//Endif ``` This almost achieves what I want, the only problem now is that it wont show the previous page when I go above page 1. I'm getting Closer!!
Found the answer thanks to the link in the updated part of my question. Here is the solution to it: ``` echo '<div id ="nav_pages">'; echo '<div class="prev_first"></div>'; echo '<div class="pages">'; $pag_args1 = array( 'type' => 'array', 'prev_next' => False, 'end_size' => 0, 'mid_size' => 1, 'add_args' => false, 'add_fragment' => '', 'show_all' => false, 'base' => '' . $url . '?paged1=%#%', 'format' => '?paged1=%#%', 'current' => $paged1, 'total' => $get_mining->max_num_pages); $paginate_links = paginate_links( $pag_args1 ); $c=$pag_args1['current']; $allowed=[sprintf('?paged1=%d',$c-1),'current',sprintf('?paged1=%d',$c+1)]; $paginate_links=array_filter( $paginate_links, function( $value ) use ( $allowed ) { foreach( (array) $allowed as $tag ) { if( false !== strpos( $value, $tag ) ) return true; } return false; } ); if( ! empty( $paginate_links ) ) printf("<ul class='page-numbers'>\n\t<li>%s</li>\n</ul>\n",join( "</li>\n\t<li>", $paginate_links)); echo '</div>'; echo '<div class="page_x_of_y2">Page <span>' . $paged1 . '</span> of <span>' . $get_mining->max_num_pages . '</span></div>'; echo '</div>'; ``` So what I had to do was: 1. Make the pagination arguments into an array 2. Store the resultant Array in a variable and store the current page in a variable 3. Create another variable with allowed values, in this case its the current page and a page up and down on either side. 4. Filter the array with a function that allows only the allowed values 5. Finally display the pagination array if there are pages to display. My solution looks like this now: [![Solution I wanted and achieved](https://i.stack.imgur.com/Y9eYJ.png)](https://i.stack.imgur.com/Y9eYJ.png)
320,103
<p>I've been with this problem for a couple of days and the truth is that I can not find a solution. I have added code manually in wp-header.php and now I need to delete these lines that it generates automatically </p> <p>The lines I want to eliminate are:</p> <pre><code>&lt;link rel="stylesheet" id="create-css" href="http://www.myweb.com/wp-content/themes/movil/create.css?ver=4.9.8" type="text/css" media="all" data-inprogress=""&gt; &lt;script type="text/javascript" src="http://www.myweb.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://www.myweb.com/wp-includes/js/jquery/jquery.js?ver=1.12.4"&gt;&lt;/script&gt; </code></pre> <p>thaks!!</p>
[ { "answer_id": 320107, "author": "Toni Wheeler", "author_id": 154504, "author_profile": "https://wordpress.stackexchange.com/users/154504", "pm_score": 0, "selected": false, "text": "<p>It sounds like you should backup your site first. Then go in to the editor under appearance, and find the file your looking for. Its usually under appearance on the dashboard.</p>\n\n<p>Appearance > Editor</p>\n\n<p>Then you can delete the files in question. </p>\n\n<p>If they are styles and scripts, deleting them may break certain functions, or make your site look odd. </p>\n\n<p>If you are hosting the stylesheets and scripts on your website, and you have converted all other links on the website, you should probably just add an \"s\" into the http:// protocol, changing it to https://</p>\n" }, { "answer_id": 393599, "author": "Laloptk", "author_id": 210397, "author_profile": "https://wordpress.stackexchange.com/users/210397", "pm_score": 1, "selected": false, "text": "<p>Sounds like some filter is placing the create.css file there. Check your functions.php (or search for the following function inside the theme with your text editor in case some other file is enqueueing those assets) for <code>wp_enqueue_style</code> and see if you have that file enqueued.</p>\n<p>Other way of doing this is using the filter <code>wp_head</code>, so, you might have something like this in your functions.php or maybe elsewhere in your theme:</p>\n<pre><code>add_action( 'wp_head', 'my_callback_function');\n\nmy_callback_function() { ?&gt;\n &lt;link rel=&quot;stylesheet&quot; id=&quot;create-css&quot; href=&quot;http://www.myweb.com/wp-content/themes/movil/create.css?ver=4.9.8&quot; type=&quot;text/css&quot; media=&quot;all&quot; data-inprogress=&quot;&quot;&gt;\n&lt;?php\n}\n</code></pre>\n<p>If you want to delete the code above you can, but instead of manually placing the tag, you should use something like the code below, again, in your functions.php:</p>\n<pre><code>add_action('wp_enqueue_scripts', 'my_callback_function');\n\nfunction my_callback_function() {\n wp_enqueue_style('create-style', get_stylesheet_directory_uri() . '/create.css');\n}\n</code></pre>\n<p>The script tags you are seeing in your website normally come from the WordPress core, so you won't have to delete them, placing them again, or do anything, WordPress handles that for you and it will use http or https depending on your configuration.</p>\n<p>The possibility exists that someone overwrote the enqueueing of the scripts (if http doesn't change automatically to https when you configure https in your website, then something is not right) to use something different to what the WordPress core gives you, in which case you should search and see if somewhere in your theme the filter <code>wp_head</code> or the function <code>wp_enqueue_script</code> is being used to put those files there.</p>\n" } ]
2018/11/24
[ "https://wordpress.stackexchange.com/questions/320103", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154644/" ]
I've been with this problem for a couple of days and the truth is that I can not find a solution. I have added code manually in wp-header.php and now I need to delete these lines that it generates automatically The lines I want to eliminate are: ``` <link rel="stylesheet" id="create-css" href="http://www.myweb.com/wp-content/themes/movil/create.css?ver=4.9.8" type="text/css" media="all" data-inprogress=""> <script type="text/javascript" src="http://www.myweb.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1"></script> <script type="text/javascript" src="http://www.myweb.com/wp-includes/js/jquery/jquery.js?ver=1.12.4"></script> ``` thaks!!
Sounds like some filter is placing the create.css file there. Check your functions.php (or search for the following function inside the theme with your text editor in case some other file is enqueueing those assets) for `wp_enqueue_style` and see if you have that file enqueued. Other way of doing this is using the filter `wp_head`, so, you might have something like this in your functions.php or maybe elsewhere in your theme: ``` add_action( 'wp_head', 'my_callback_function'); my_callback_function() { ?> <link rel="stylesheet" id="create-css" href="http://www.myweb.com/wp-content/themes/movil/create.css?ver=4.9.8" type="text/css" media="all" data-inprogress=""> <?php } ``` If you want to delete the code above you can, but instead of manually placing the tag, you should use something like the code below, again, in your functions.php: ``` add_action('wp_enqueue_scripts', 'my_callback_function'); function my_callback_function() { wp_enqueue_style('create-style', get_stylesheet_directory_uri() . '/create.css'); } ``` The script tags you are seeing in your website normally come from the WordPress core, so you won't have to delete them, placing them again, or do anything, WordPress handles that for you and it will use http or https depending on your configuration. The possibility exists that someone overwrote the enqueueing of the scripts (if http doesn't change automatically to https when you configure https in your website, then something is not right) to use something different to what the WordPress core gives you, in which case you should search and see if somewhere in your theme the filter `wp_head` or the function `wp_enqueue_script` is being used to put those files there.
320,237
<p>I have added remove button for products in the checkout page.</p> <p>The code - </p> <pre><code>function add_delete( $product_title, $cart_item, $cart_item_key ) { if ( is_checkout() ) { /* Get Cart of the user */ $cart = WC()-&gt;cart-&gt;get_cart(); foreach ( $cart as $cart_key =&gt; $cart_value ){ if ( $cart_key == $cart_item_key ){ $product_id = $cart_item['product_id']; $_product = $cart_item['data'] ; /*Add delete icon */ $return_value = sprintf( '&lt;a href="%s" class="remove" title="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s"&gt;&amp;times;&lt;/a&gt;', esc_url( WC()-&gt;cart-&gt;get_remove_url( $cart_key ) ), __( 'Remove this item', 'woocommerce' ), esc_attr( $product_id ), esc_attr( $_product-&gt;get_sku() ), esc_attr( $cart_item_key ) ); /* Add product name */ $return_value .= '&amp;nbsp; &lt;span class = "product_name" &gt;' . $product_title . '&lt;/span&gt;' ; return $return_value; } } }else{ $_product = $cart_item['data'] ; $product_permalink = $_product-&gt;is_visible() ? $_product-&gt;get_permalink( $cart_item ) : ''; if ( ! $product_permalink ) { $return_value = $_product-&gt;get_title() . '&amp;nbsp;'; } else { $return_value = sprintf( '&lt;a href="%s"&gt;%s&lt;/a&gt;', esc_url( $product_permalink ), $_product-&gt;get_title()); } return $return_value; } } add_filter ('woocommerce_cart_item_name', 'add_delete' , 10, 3 ); </code></pre> <p>It is working just fine. But it refreshes the whole page to remove a product, unlike cart page.</p> <p>Cart page uses ajax to remove the product. And I am trying to do the same thing here. But, the problem is that I don't know much about Ajax.</p> <p>Here is what I tried.</p> <p>The JavaScript</p> <pre><code>jQuery(document).ready(function($){ $(document).on('click', 'tr.cart_item a.remove', function (e) { e.preventDefault(); var product_id = $(this).attr("data-product_id"), cart_item_key = $(this).attr("data-cart_item_key"), product_container = $(this).parents('.shop_table'); // Add loader product_container.block({ message: null, overlayCSS: { cursor: 'none' } }); $.ajax({ type: 'POST', dataType: 'json', url: wc_checkout_params.ajax_url, data: { action: "product_remove", product_id: product_id, cart_item_key: cart_item_key }, success: function(response) { if ( ! response || response.error ) return; var fragments = response.fragments; // Replace fragments if ( fragments ) { $.each( fragments, function( key, value ) { $( key ).replaceWith( value ); }); } } }); }); }); </code></pre> <p>And the PHP</p> <pre><code>function warp_ajax_product_remove() { // Get order review fragment ob_start(); foreach (WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $cart_item) { if($cart_item['product_id'] == $_POST['product_id'] &amp;&amp; $cart_item_key == $_POST['cart_item_key'] ) { WC()-&gt;cart-&gt;remove_cart_item($cart_item_key); } } WC()-&gt;cart-&gt;calculate_totals(); WC()-&gt;cart-&gt;maybe_set_cart_cookies(); woocommerce_order_review(); $woocommerce_order_review = ob_get_clean(); } add_action( 'wp_ajax_product_remove', 'warp_ajax_product_remove' ); add_action( 'wp_ajax_nopriv_product_remove', 'warp_ajax_product_remove' ); </code></pre> <p>It removes the product, but the checkout page is not updated. </p> <p>Can you guys please help me? Thank you</p>
[ { "answer_id": 320186, "author": "pixeline", "author_id": 82, "author_profile": "https://wordpress.stackexchange.com/users/82", "pm_score": 1, "selected": false, "text": "<p>If you want to use php inside the Post Content editing interface, it will not work (for security reasons), unless you install a plugin that allows it.</p>\n\n<p>If you mean that the php would be put in the template file, then you can use the functions <code>the_meta();</code>(<a href=\"https://codex.wordpress.org/Custom_Fields#Displaying_Custom_Fields\" rel=\"nofollow noreferrer\">doc</a>) and the more flexible <code>get_post_meta($post_id, $key, $single);</code>. </p>\n" }, { "answer_id": 320199, "author": "ElizAber", "author_id": 154667, "author_profile": "https://wordpress.stackexchange.com/users/154667", "pm_score": 0, "selected": false, "text": "<p>I set something like this up by creating a template page and uploading via ftp. The gist of the coding using Advanced Custom Fields worked using the following in the editor:</p>\n\n<pre><code>&lt;?php /* Template Name: CustomPageT1 */ ?&gt;\n&lt;?php get_header(); ?&gt;\n\n&lt;?php \n\n$posts = get_posts(array(\n 'posts_per_page' =&gt; -1,\n'post_type' =&gt; 'post',\n'category_name' =&gt; 'all-properties'\n));\n\nif( $posts ): ?&gt;\n\n\n&lt;?php foreach( $posts as $post ): \n\n setup_postdata( $post );\n\n ?&gt;\n\n&lt;?php the_post_thumbnail( 'small' ); ?&gt;&lt;br&gt;\n &lt;b&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/b&gt;&lt;br&gt;\n &lt;?php the_field('short_description'); ?&gt;&lt;br&gt;\n\n&lt;?php endforeach; ?&gt;\n\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n\n\n\n<p>Let me know if this is what you are looking for and if I can help with any further information. :)</p>\n" } ]
2018/11/26
[ "https://wordpress.stackexchange.com/questions/320237", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123392/" ]
I have added remove button for products in the checkout page. The code - ``` function add_delete( $product_title, $cart_item, $cart_item_key ) { if ( is_checkout() ) { /* Get Cart of the user */ $cart = WC()->cart->get_cart(); foreach ( $cart as $cart_key => $cart_value ){ if ( $cart_key == $cart_item_key ){ $product_id = $cart_item['product_id']; $_product = $cart_item['data'] ; /*Add delete icon */ $return_value = sprintf( '<a href="%s" class="remove" title="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s">&times;</a>', esc_url( WC()->cart->get_remove_url( $cart_key ) ), __( 'Remove this item', 'woocommerce' ), esc_attr( $product_id ), esc_attr( $_product->get_sku() ), esc_attr( $cart_item_key ) ); /* Add product name */ $return_value .= '&nbsp; <span class = "product_name" >' . $product_title . '</span>' ; return $return_value; } } }else{ $_product = $cart_item['data'] ; $product_permalink = $_product->is_visible() ? $_product->get_permalink( $cart_item ) : ''; if ( ! $product_permalink ) { $return_value = $_product->get_title() . '&nbsp;'; } else { $return_value = sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_title()); } return $return_value; } } add_filter ('woocommerce_cart_item_name', 'add_delete' , 10, 3 ); ``` It is working just fine. But it refreshes the whole page to remove a product, unlike cart page. Cart page uses ajax to remove the product. And I am trying to do the same thing here. But, the problem is that I don't know much about Ajax. Here is what I tried. The JavaScript ``` jQuery(document).ready(function($){ $(document).on('click', 'tr.cart_item a.remove', function (e) { e.preventDefault(); var product_id = $(this).attr("data-product_id"), cart_item_key = $(this).attr("data-cart_item_key"), product_container = $(this).parents('.shop_table'); // Add loader product_container.block({ message: null, overlayCSS: { cursor: 'none' } }); $.ajax({ type: 'POST', dataType: 'json', url: wc_checkout_params.ajax_url, data: { action: "product_remove", product_id: product_id, cart_item_key: cart_item_key }, success: function(response) { if ( ! response || response.error ) return; var fragments = response.fragments; // Replace fragments if ( fragments ) { $.each( fragments, function( key, value ) { $( key ).replaceWith( value ); }); } } }); }); }); ``` And the PHP ``` function warp_ajax_product_remove() { // Get order review fragment ob_start(); foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if($cart_item['product_id'] == $_POST['product_id'] && $cart_item_key == $_POST['cart_item_key'] ) { WC()->cart->remove_cart_item($cart_item_key); } } WC()->cart->calculate_totals(); WC()->cart->maybe_set_cart_cookies(); woocommerce_order_review(); $woocommerce_order_review = ob_get_clean(); } add_action( 'wp_ajax_product_remove', 'warp_ajax_product_remove' ); add_action( 'wp_ajax_nopriv_product_remove', 'warp_ajax_product_remove' ); ``` It removes the product, but the checkout page is not updated. Can you guys please help me? Thank you
If you want to use php inside the Post Content editing interface, it will not work (for security reasons), unless you install a plugin that allows it. If you mean that the php would be put in the template file, then you can use the functions `the_meta();`([doc](https://codex.wordpress.org/Custom_Fields#Displaying_Custom_Fields)) and the more flexible `get_post_meta($post_id, $key, $single);`.
320,244
<p>I tried with this code in <code>functions.php</code>of my website's child theme.</p> <pre><code>add_filter('admin_body_class', 'custom_body_class'); function custom_body_class($classes) { if (is_page(8)) $classes[] = 'home-admin-area'; return $classes; } </code></pre> <p>But the class "home-admin-area" is not added. Is there any error in this code?</p> <p>Edit 1: I used <code>is_page()</code> function for backend page which was wrong. I tried with this also but it somehow did not work.</p> <pre><code>add_filter('admin_body_class', 'custom_body_class'); function custom_body_class($classes) { if ($_GET['post']==8) $classes[] .= ' new-class '; return $classes; } </code></pre>
[ { "answer_id": 320245, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p><code>admin_body_class</code> passes its values as a string, not an array. (This differs from <code>body_class</code> which <em>does</em> pass an array. (See <a href=\"https://developer.wordpress.org/reference/hooks/admin_body_class/\" rel=\"nofollow noreferrer\">the documentation for <code>admin_body_class</code></a>)</p>\n\n<p>So what you need is:</p>\n\n<pre><code>add_filter('admin_body_class', 'custom_body_class');\nfunction custom_body_class($classes) {\n if (is_page(8))\n $classes .= ' home-admin-area';\n return $classes;\n}\n</code></pre>\n\n<p>Note how it's adding as a string with a leading space.</p>\n\n<p>However, not sure if this will work because I am wondering if you're using the correct filter for what you want to do. Your use of <code>is_page()</code> makes me wonder - is this something you're doing in the admin? Or is this a front end thing?</p>\n" }, { "answer_id": 320287, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 3, "selected": true, "text": "<p>Use <code>admin_body_class</code> both with global post_id and <code>get_current_screen</code> function:</p>\n\n<pre><code>add_filter('admin_body_class', 'wpse_320244_admin_body_class');\n\nfunction wpse_320244_admin_body_class($classes) {\n global $post;\n\n // get_current_screen() returns object with current admin screen\n // @link https://codex.wordpress.org/Function_Reference/get_current_screen\n $current_screen = get_current_screen();\n\n if($current_screen-&gt;base === \"post\" &amp;&amp; absint($post-&gt;ID) === 8) {\n $classes .= ' home-admin-area';\n }\n\n return $classes;\n}\n</code></pre>\n\n<p>You can also use $pagenow variable. It seems that this way would be preferable, because <code>get_current_screen()</code> maybe undefined in some cases:</p>\n\n<pre><code>add_filter('admin_body_class', 'wpse_320244_admin_body_class');\n\nfunction wpse_320244_admin_body_class($classes) {\n global $post, $pagenow;\n\n // $pagenow contains current admin-side php-file\n // absint converts type to int, so we can use strict comparison\n if($pagenow === 'post.php' &amp;&amp; absint($post-&gt;ID) === 8) {\n $classes .= ' home-admin-area';\n }\n\n return $classes;\n}\n</code></pre>\n" } ]
2018/11/26
[ "https://wordpress.stackexchange.com/questions/320244", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106457/" ]
I tried with this code in `functions.php`of my website's child theme. ``` add_filter('admin_body_class', 'custom_body_class'); function custom_body_class($classes) { if (is_page(8)) $classes[] = 'home-admin-area'; return $classes; } ``` But the class "home-admin-area" is not added. Is there any error in this code? Edit 1: I used `is_page()` function for backend page which was wrong. I tried with this also but it somehow did not work. ``` add_filter('admin_body_class', 'custom_body_class'); function custom_body_class($classes) { if ($_GET['post']==8) $classes[] .= ' new-class '; return $classes; } ```
Use `admin_body_class` both with global post\_id and `get_current_screen` function: ``` add_filter('admin_body_class', 'wpse_320244_admin_body_class'); function wpse_320244_admin_body_class($classes) { global $post; // get_current_screen() returns object with current admin screen // @link https://codex.wordpress.org/Function_Reference/get_current_screen $current_screen = get_current_screen(); if($current_screen->base === "post" && absint($post->ID) === 8) { $classes .= ' home-admin-area'; } return $classes; } ``` You can also use $pagenow variable. It seems that this way would be preferable, because `get_current_screen()` maybe undefined in some cases: ``` add_filter('admin_body_class', 'wpse_320244_admin_body_class'); function wpse_320244_admin_body_class($classes) { global $post, $pagenow; // $pagenow contains current admin-side php-file // absint converts type to int, so we can use strict comparison if($pagenow === 'post.php' && absint($post->ID) === 8) { $classes .= ' home-admin-area'; } return $classes; } ```
320,255
<p>I'm trying move an existing Wordpress site to run across two different servers, one with Apache and the main source code and the other that just has the database running on MYSQL.</p> <p>wp-config:</p> <pre><code>define('DB_NAME', 'wp-user'); define('DB_USER', 'wp-user'); define('DB_PASSWORD', 'password'); define('DB_HOST', 'xxx.xxx.xxx.xxx:3306'); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', ''); </code></pre> <p>I've already opened ports 3306 on both servers and created a new mysql user that comes from the Apache Server address.</p> <pre><code>CREATE USER 'wp-user'@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON wp-db . * TO 'wp-user'@'xxx.xxx.xxx.xxx'; FLUSH PRIVILEGES; </code></pre> <p>both servers have the same version of MYSQL running.</p> <p>I get the following error address:</p> <blockquote> <p>Error establishing a database connection</p> </blockquote> <p>EDIT:</p> <p>my.cnf:</p> <pre><code># For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html [mysqld] # # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock port = 3306 # skip-external-locking # skip-networking # bind-address # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 # Recommended in standard MySQL setup sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid </code></pre>
[ { "answer_id": 320245, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p><code>admin_body_class</code> passes its values as a string, not an array. (This differs from <code>body_class</code> which <em>does</em> pass an array. (See <a href=\"https://developer.wordpress.org/reference/hooks/admin_body_class/\" rel=\"nofollow noreferrer\">the documentation for <code>admin_body_class</code></a>)</p>\n\n<p>So what you need is:</p>\n\n<pre><code>add_filter('admin_body_class', 'custom_body_class');\nfunction custom_body_class($classes) {\n if (is_page(8))\n $classes .= ' home-admin-area';\n return $classes;\n}\n</code></pre>\n\n<p>Note how it's adding as a string with a leading space.</p>\n\n<p>However, not sure if this will work because I am wondering if you're using the correct filter for what you want to do. Your use of <code>is_page()</code> makes me wonder - is this something you're doing in the admin? Or is this a front end thing?</p>\n" }, { "answer_id": 320287, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 3, "selected": true, "text": "<p>Use <code>admin_body_class</code> both with global post_id and <code>get_current_screen</code> function:</p>\n\n<pre><code>add_filter('admin_body_class', 'wpse_320244_admin_body_class');\n\nfunction wpse_320244_admin_body_class($classes) {\n global $post;\n\n // get_current_screen() returns object with current admin screen\n // @link https://codex.wordpress.org/Function_Reference/get_current_screen\n $current_screen = get_current_screen();\n\n if($current_screen-&gt;base === \"post\" &amp;&amp; absint($post-&gt;ID) === 8) {\n $classes .= ' home-admin-area';\n }\n\n return $classes;\n}\n</code></pre>\n\n<p>You can also use $pagenow variable. It seems that this way would be preferable, because <code>get_current_screen()</code> maybe undefined in some cases:</p>\n\n<pre><code>add_filter('admin_body_class', 'wpse_320244_admin_body_class');\n\nfunction wpse_320244_admin_body_class($classes) {\n global $post, $pagenow;\n\n // $pagenow contains current admin-side php-file\n // absint converts type to int, so we can use strict comparison\n if($pagenow === 'post.php' &amp;&amp; absint($post-&gt;ID) === 8) {\n $classes .= ' home-admin-area';\n }\n\n return $classes;\n}\n</code></pre>\n" } ]
2018/11/26
[ "https://wordpress.stackexchange.com/questions/320255", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154745/" ]
I'm trying move an existing Wordpress site to run across two different servers, one with Apache and the main source code and the other that just has the database running on MYSQL. wp-config: ``` define('DB_NAME', 'wp-user'); define('DB_USER', 'wp-user'); define('DB_PASSWORD', 'password'); define('DB_HOST', 'xxx.xxx.xxx.xxx:3306'); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', ''); ``` I've already opened ports 3306 on both servers and created a new mysql user that comes from the Apache Server address. ``` CREATE USER 'wp-user'@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON wp-db . * TO 'wp-user'@'xxx.xxx.xxx.xxx'; FLUSH PRIVILEGES; ``` both servers have the same version of MYSQL running. I get the following error address: > > Error establishing a database connection > > > EDIT: my.cnf: ``` # For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html [mysqld] # # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock port = 3306 # skip-external-locking # skip-networking # bind-address # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 # Recommended in standard MySQL setup sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid ```
Use `admin_body_class` both with global post\_id and `get_current_screen` function: ``` add_filter('admin_body_class', 'wpse_320244_admin_body_class'); function wpse_320244_admin_body_class($classes) { global $post; // get_current_screen() returns object with current admin screen // @link https://codex.wordpress.org/Function_Reference/get_current_screen $current_screen = get_current_screen(); if($current_screen->base === "post" && absint($post->ID) === 8) { $classes .= ' home-admin-area'; } return $classes; } ``` You can also use $pagenow variable. It seems that this way would be preferable, because `get_current_screen()` maybe undefined in some cases: ``` add_filter('admin_body_class', 'wpse_320244_admin_body_class'); function wpse_320244_admin_body_class($classes) { global $post, $pagenow; // $pagenow contains current admin-side php-file // absint converts type to int, so we can use strict comparison if($pagenow === 'post.php' && absint($post->ID) === 8) { $classes .= ' home-admin-area'; } return $classes; } ```
320,271
<p>I'm setting up a google map on my site and I'm trying to set the enqueue my scripts up but am getting an error:</p> <p>I have placed this code in my functions.php (actual api key not used here):</p> <pre><code>function rt_load_acf_map() { // Register my scripts for my theme: wp_register_script( 'map-script', get_stylesheet_directory_uri() . '/js/acf-map.js', array( 'jquery' ) ); wp_register_script( 'googlemap', 'https://maps.googleapis.com/maps/api/js?123123123123' , '', '', false ); wp_register_script( 'slider-script', get_stylesheet_directory_uri() . '/js/slider.js', array( 'jquery' ) ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'map-script' ); wp_enqueue_script( 'googlemap' ); if(is_front_page()){ wp_enqueue_script( 'slider-script' ); } } add_action( 'wp_enqueue_scripts', 'rt_load_acf_map' ); </code></pre> <p>the map loads on the front end but with an overlay error:</p> <blockquote> <p>This page can't load Google Maps correctly.</p> </blockquote> <p>In my console I see this error:</p> <blockquote> <p>Google Maps JavaScript API warning: NoApiKeys <a href="https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys" rel="nofollow noreferrer">https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys</a></p> </blockquote> <p>and when I look at the page source i see that <code>&amp;#038</code> and then the version were added:</p> <pre><code>&lt;script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?123123123123&amp;#038;ver=4.9.8'&gt;&lt;/script&gt; </code></pre> <p>EDITS</p> <p>The api key is correct and working. That's not the issue.</p> <p>Secondly, when I remove the wp_register_script and its wp_enqueue and just use this line:</p> <pre><code>wp_enqueue_script( 'google-maps-api', '//maps.googleapis.com/maps/api/js?key=123123123123', array(), '', true ); </code></pre> <p>Everything works fine. </p> <p>I can't figure out why it's not working as wone line and with the http in front of google maps url.</p>
[ { "answer_id": 320282, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>Setting the <code>$ver</code> parameter to <code>false</code> (or, probably, <code>''</code>, as you've done), will append the current WordPress version to the <code>&lt;script&gt;</code> tag. To have no version number appended, use <code>null</code> instead:</p>\n\n<pre><code>wp_register_script( \n 'googlemap',\n 'https://maps.googleapis.com/maps/api/js?123123123123',\n array(),\n null,\n false\n);\n</code></pre>\n\n<p>(Also, the <code>$deps</code> parameter should be an empty array rather than an empty string, which is also addressed in the code above.)</p>\n\n<p><strong>However:</strong> I don't think this is the actual problem you're having. The error message in your question suggests that you don't have an API key for Google Maps, which is an issue you'll have to sort out with Google.</p>\n\n<h2>Reference</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\"><code>wp_register_script()</code> docs</a></p>\n" }, { "answer_id": 320363, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 3, "selected": true, "text": "<p>When you call google, the <code>key</code> variable name is missing. </p>\n\n<pre><code>wp_register_script( 'googlemap', 'https://maps.googleapis.com/maps/api/js?123123123123' , '', '', false );\n</code></pre>\n\n<p>Should be :</p>\n\n<pre><code>wp_register_script( 'googlemap', '//maps.googleapis.com/maps/api/js?key=123123123123123123123123' , '', '', false );\n</code></pre>\n" } ]
2018/11/26
[ "https://wordpress.stackexchange.com/questions/320271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
I'm setting up a google map on my site and I'm trying to set the enqueue my scripts up but am getting an error: I have placed this code in my functions.php (actual api key not used here): ``` function rt_load_acf_map() { // Register my scripts for my theme: wp_register_script( 'map-script', get_stylesheet_directory_uri() . '/js/acf-map.js', array( 'jquery' ) ); wp_register_script( 'googlemap', 'https://maps.googleapis.com/maps/api/js?123123123123' , '', '', false ); wp_register_script( 'slider-script', get_stylesheet_directory_uri() . '/js/slider.js', array( 'jquery' ) ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'map-script' ); wp_enqueue_script( 'googlemap' ); if(is_front_page()){ wp_enqueue_script( 'slider-script' ); } } add_action( 'wp_enqueue_scripts', 'rt_load_acf_map' ); ``` the map loads on the front end but with an overlay error: > > This page can't load Google Maps correctly. > > > In my console I see this error: > > Google Maps JavaScript API warning: NoApiKeys > <https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys> > > > and when I look at the page source i see that `&#038` and then the version were added: ``` <script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?123123123123&#038;ver=4.9.8'></script> ``` EDITS The api key is correct and working. That's not the issue. Secondly, when I remove the wp\_register\_script and its wp\_enqueue and just use this line: ``` wp_enqueue_script( 'google-maps-api', '//maps.googleapis.com/maps/api/js?key=123123123123', array(), '', true ); ``` Everything works fine. I can't figure out why it's not working as wone line and with the http in front of google maps url.
When you call google, the `key` variable name is missing. ``` wp_register_script( 'googlemap', 'https://maps.googleapis.com/maps/api/js?123123123123' , '', '', false ); ``` Should be : ``` wp_register_script( 'googlemap', '//maps.googleapis.com/maps/api/js?key=123123123123123123123123' , '', '', false ); ```
320,278
<p>I build a static page in my WordPress root folder. Now I'm trying to include a list of my categories with <code>echo clpr_categories_list();</code>.</p> <p>Its not working because I some how have to tell the static page where to find my theme. How do I do this? Searched everywhere.</p>
[ { "answer_id": 320282, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>Setting the <code>$ver</code> parameter to <code>false</code> (or, probably, <code>''</code>, as you've done), will append the current WordPress version to the <code>&lt;script&gt;</code> tag. To have no version number appended, use <code>null</code> instead:</p>\n\n<pre><code>wp_register_script( \n 'googlemap',\n 'https://maps.googleapis.com/maps/api/js?123123123123',\n array(),\n null,\n false\n);\n</code></pre>\n\n<p>(Also, the <code>$deps</code> parameter should be an empty array rather than an empty string, which is also addressed in the code above.)</p>\n\n<p><strong>However:</strong> I don't think this is the actual problem you're having. The error message in your question suggests that you don't have an API key for Google Maps, which is an issue you'll have to sort out with Google.</p>\n\n<h2>Reference</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\"><code>wp_register_script()</code> docs</a></p>\n" }, { "answer_id": 320363, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 3, "selected": true, "text": "<p>When you call google, the <code>key</code> variable name is missing. </p>\n\n<pre><code>wp_register_script( 'googlemap', 'https://maps.googleapis.com/maps/api/js?123123123123' , '', '', false );\n</code></pre>\n\n<p>Should be :</p>\n\n<pre><code>wp_register_script( 'googlemap', '//maps.googleapis.com/maps/api/js?key=123123123123123123123123' , '', '', false );\n</code></pre>\n" } ]
2018/11/26
[ "https://wordpress.stackexchange.com/questions/320278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153850/" ]
I build a static page in my WordPress root folder. Now I'm trying to include a list of my categories with `echo clpr_categories_list();`. Its not working because I some how have to tell the static page where to find my theme. How do I do this? Searched everywhere.
When you call google, the `key` variable name is missing. ``` wp_register_script( 'googlemap', 'https://maps.googleapis.com/maps/api/js?123123123123' , '', '', false ); ``` Should be : ``` wp_register_script( 'googlemap', '//maps.googleapis.com/maps/api/js?key=123123123123123123123123' , '', '', false ); ```
320,304
<p>Am try to implement data from database using AJAX based on a drop down list in WordPress. The codes returning 400 bad request in the console. I am hosted the page as localhost.</p> <p>Here is my theme's <code>functions.php</code> //I changed the Code</p> <pre><code> function my_enqueue_scripts() { wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', 'my_enqueue_scripts'); function fetchData(){ global $wpdb; // this can be improved $catId = isset($_REQUEST['catId']); if($catId){ $result_data = $wpdb-&gt;get_results("SELECT * FROM sub_category where categor_id = '".$catId."'"); foreach ($result_data as $data) { echo "&lt;option value='".$data-&gt;id."'&gt;'".$data-&gt;sub_category_name."'&lt;/option&gt;"; } } die(); } // add your ajax action to authenticated users only add_action('wp_ajax_fetch_data','fetchData'); </code></pre> <p><strong>Am also adding the jQuery part here:</strong></p> <pre><code>&lt;script type="text/javascript"&gt; jQuery(document).ready( function(){ jQuery('#category').on('change',function (){ console.log("start1"); var catId = document.getElementById('category').value; console.log(catId); jQuery.ajax({ type: 'POST', url: "&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;", data: { 'key':catId, 'action': "fetch_data" // very important }, success : function (data) { jQuery('#sub_cat').html(data); } }); }); }); &lt;/script&gt; &lt;form method="post" name="myform" id="myform"&gt; &lt;table width="200" border="0" cellpadding="10"&gt; &lt;tr&gt; &lt;th scope="col"&gt;&amp;nbsp;&lt;/th&gt; &lt;th scope="col"&gt;&amp;nbsp;&lt;/th&gt; &lt;th scope="col"&gt;&amp;nbsp;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Category&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;select name="category" id="category" &gt; &lt;option value=""&gt;Select the category&lt;/option&gt; &lt;?php global $wpdb; $result_fromDB = $wpdb-&gt;get_results("SELECT * FROM `category`"); foreach ($result_fromDB as $cat) { echo "&lt;option value='".$cat-&gt;id."' selected&gt;".$cat-&gt;name."&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Sub Category&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&amp;nbsp; &lt;div id="fetch_data"&gt;&lt;select name="sub_cat" id="sub_cat"&gt; &lt;option value=""&gt; Select Sub category&lt;/option&gt; &lt;!--Here I want to return the data--&gt; &lt;/select&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>Remembering that I am using internal scripts, Please give a solution.</p>
[ { "answer_id": 320309, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>You get 400 error, because there is no callback registered for your AJAX request.</p>\n\n<p>Here's how you do the request:</p>\n\n<pre><code>jQuery.ajax({\n type: 'POST',\n url: \"/mudratcr/wp-admin/admin-ajax.php\",\n data: {'key':catId},\n cache: false,\n success : function (data) {\n jQuery('#sub_cat').html(data); \n console.log(data);\n }\n});\n</code></pre>\n\n<p>So there is no <code>action</code> param in your request.</p>\n\n<p>And because you register your callback like below:</p>\n\n<pre><code>add_action( 'wp_ajax_data', 'fetchData' );\nadd_action( 'wp_ajax_nopriv_data', 'fetchData' );\n</code></pre>\n\n<p>you should pass \"data\" as action in your request:</p>\n\n<pre><code>jQuery.ajax({\n type: 'POST',\n url: \"/mudratcr/wp-admin/admin-ajax.php\",\n data: {key: catId, action: 'data'},\n cache: false,\n success : function (data) {\n jQuery('#sub_cat').html(data); \n console.log(data);\n }\n});\n</code></pre>\n\n<p>PS. I wouldn't use hardcoded URL to admin-ajax.php file in your JS. It would be much better if you localized your JS file and passed real admin-ajax.php file URL in there.</p>\n" }, { "answer_id": 320311, "author": "Mike", "author_id": 52894, "author_profile": "https://wordpress.stackexchange.com/users/52894", "pm_score": 2, "selected": true, "text": "<p>First, enqueue your script correctly, in <code>functions.php</code>:</p>\n\n<pre><code>function my_enqueue_scripts() {\n wp_enqueue_script('jquery');\n}\nadd_action('wp_enqueue_scripts', 'my_enqueue_scripts');\n</code></pre>\n\n<p>Then, <code>Authenticated</code> users only (see <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)</a>)\n(can also be in <code>functions.php</code>):</p>\n\n<pre><code>function fetchData(){\n\n // Not needed anymore, as you manage the case through the `add_action` method\n // if ( ! is_user_logged_in() ) {\n // return;\n // }\n\n // this can be improved\n $catId = isset($_REQUEST['catId']) ? $_REQUEST['catId'] : '';\n echo \"&lt;option&gt;$catId&lt;/option&gt;\"; // there was a typo here: `&lt;optio&gt;`\n\n die();\n}\n\n// add your ajax action to authenticated users only\nadd_action('wp_ajax_fetch_data','fetchData');\n\n// no need for the `nopriv_` action, this one is for anonymous users\n// add_action('wp_ajax_nopriv_fetch_data','fetchData');?&gt;\n</code></pre>\n\n<p>And finally, your JS script. You must add the <code>action</code> parameter, otherwise WordPress does not know which action to fire in the backend (the one used in <code>wp_ajax_fetch_data</code> -> <code>fetch_data</code>).\nAlso, for the url, try to use <code>admin_url( 'admin-ajax.php' );</code> instead:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\njQuery(document).ready( function(){\n\n jQuery('#category').on('change',function (){\n console.log(\"start1\");\n var catId = document.getElementById('category').value;\n console.log(catId);\n jQuery.ajax({\n type: 'POST',\n url: \"&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;\",\n data: {\n 'key':catId,\n 'action': \"fetch_data\" // very important\n },\n cache: false,\n success : function (data) {\n jQuery('#sub_cat').html(data); \n console.log(data);\n }\n });\n });\n});\n\n&lt;/script&gt;\n</code></pre>\n" } ]
2018/11/27
[ "https://wordpress.stackexchange.com/questions/320304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154128/" ]
Am try to implement data from database using AJAX based on a drop down list in WordPress. The codes returning 400 bad request in the console. I am hosted the page as localhost. Here is my theme's `functions.php` //I changed the Code ``` function my_enqueue_scripts() { wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', 'my_enqueue_scripts'); function fetchData(){ global $wpdb; // this can be improved $catId = isset($_REQUEST['catId']); if($catId){ $result_data = $wpdb->get_results("SELECT * FROM sub_category where categor_id = '".$catId."'"); foreach ($result_data as $data) { echo "<option value='".$data->id."'>'".$data->sub_category_name."'</option>"; } } die(); } // add your ajax action to authenticated users only add_action('wp_ajax_fetch_data','fetchData'); ``` **Am also adding the jQuery part here:** ``` <script type="text/javascript"> jQuery(document).ready( function(){ jQuery('#category').on('change',function (){ console.log("start1"); var catId = document.getElementById('category').value; console.log(catId); jQuery.ajax({ type: 'POST', url: "<?php echo admin_url( 'admin-ajax.php' ); ?>", data: { 'key':catId, 'action': "fetch_data" // very important }, success : function (data) { jQuery('#sub_cat').html(data); } }); }); }); </script> <form method="post" name="myform" id="myform"> <table width="200" border="0" cellpadding="10"> <tr> <th scope="col">&nbsp;</th> <th scope="col">&nbsp;</th> <th scope="col">&nbsp;</th> </tr> <tr> <td><label>Category</label></td> <td><select name="category" id="category" > <option value="">Select the category</option> <?php global $wpdb; $result_fromDB = $wpdb->get_results("SELECT * FROM `category`"); foreach ($result_fromDB as $cat) { echo "<option value='".$cat->id."' selected>".$cat->name."</option>"; } ?> </select> </td> <td></td> </tr> <tr> <td><label>Sub Category</label></td> <td>&nbsp; <div id="fetch_data"><select name="sub_cat" id="sub_cat"> <option value=""> Select Sub category</option> <!--Here I want to return the data--> </select></div> </td> </tr> </table> </form> ``` Remembering that I am using internal scripts, Please give a solution.
First, enqueue your script correctly, in `functions.php`: ``` function my_enqueue_scripts() { wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', 'my_enqueue_scripts'); ``` Then, `Authenticated` users only (see <https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)>) (can also be in `functions.php`): ``` function fetchData(){ // Not needed anymore, as you manage the case through the `add_action` method // if ( ! is_user_logged_in() ) { // return; // } // this can be improved $catId = isset($_REQUEST['catId']) ? $_REQUEST['catId'] : ''; echo "<option>$catId</option>"; // there was a typo here: `<optio>` die(); } // add your ajax action to authenticated users only add_action('wp_ajax_fetch_data','fetchData'); // no need for the `nopriv_` action, this one is for anonymous users // add_action('wp_ajax_nopriv_fetch_data','fetchData');?> ``` And finally, your JS script. You must add the `action` parameter, otherwise WordPress does not know which action to fire in the backend (the one used in `wp_ajax_fetch_data` -> `fetch_data`). Also, for the url, try to use `admin_url( 'admin-ajax.php' );` instead: ``` <script type="text/javascript"> jQuery(document).ready( function(){ jQuery('#category').on('change',function (){ console.log("start1"); var catId = document.getElementById('category').value; console.log(catId); jQuery.ajax({ type: 'POST', url: "<?php echo admin_url( 'admin-ajax.php' ); ?>", data: { 'key':catId, 'action': "fetch_data" // very important }, cache: false, success : function (data) { jQuery('#sub_cat').html(data); console.log(data); } }); }); }); </script> ```
320,331
<p>I am working on a blog with a pretty high number of authors. I want to keep them from accidentally sending a push message to our readers, since the button of the push-plugin we use looks dangerously similar to the "publish"-button. </p> <p>Is there a way to hide an element like this push-button for certain user groups by default? </p> <p>I can uncheck it in the view-menu above the editor, of course, but that doesn't change it for all other authors.</p>
[ { "answer_id": 320309, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>You get 400 error, because there is no callback registered for your AJAX request.</p>\n\n<p>Here's how you do the request:</p>\n\n<pre><code>jQuery.ajax({\n type: 'POST',\n url: \"/mudratcr/wp-admin/admin-ajax.php\",\n data: {'key':catId},\n cache: false,\n success : function (data) {\n jQuery('#sub_cat').html(data); \n console.log(data);\n }\n});\n</code></pre>\n\n<p>So there is no <code>action</code> param in your request.</p>\n\n<p>And because you register your callback like below:</p>\n\n<pre><code>add_action( 'wp_ajax_data', 'fetchData' );\nadd_action( 'wp_ajax_nopriv_data', 'fetchData' );\n</code></pre>\n\n<p>you should pass \"data\" as action in your request:</p>\n\n<pre><code>jQuery.ajax({\n type: 'POST',\n url: \"/mudratcr/wp-admin/admin-ajax.php\",\n data: {key: catId, action: 'data'},\n cache: false,\n success : function (data) {\n jQuery('#sub_cat').html(data); \n console.log(data);\n }\n});\n</code></pre>\n\n<p>PS. I wouldn't use hardcoded URL to admin-ajax.php file in your JS. It would be much better if you localized your JS file and passed real admin-ajax.php file URL in there.</p>\n" }, { "answer_id": 320311, "author": "Mike", "author_id": 52894, "author_profile": "https://wordpress.stackexchange.com/users/52894", "pm_score": 2, "selected": true, "text": "<p>First, enqueue your script correctly, in <code>functions.php</code>:</p>\n\n<pre><code>function my_enqueue_scripts() {\n wp_enqueue_script('jquery');\n}\nadd_action('wp_enqueue_scripts', 'my_enqueue_scripts');\n</code></pre>\n\n<p>Then, <code>Authenticated</code> users only (see <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)</a>)\n(can also be in <code>functions.php</code>):</p>\n\n<pre><code>function fetchData(){\n\n // Not needed anymore, as you manage the case through the `add_action` method\n // if ( ! is_user_logged_in() ) {\n // return;\n // }\n\n // this can be improved\n $catId = isset($_REQUEST['catId']) ? $_REQUEST['catId'] : '';\n echo \"&lt;option&gt;$catId&lt;/option&gt;\"; // there was a typo here: `&lt;optio&gt;`\n\n die();\n}\n\n// add your ajax action to authenticated users only\nadd_action('wp_ajax_fetch_data','fetchData');\n\n// no need for the `nopriv_` action, this one is for anonymous users\n// add_action('wp_ajax_nopriv_fetch_data','fetchData');?&gt;\n</code></pre>\n\n<p>And finally, your JS script. You must add the <code>action</code> parameter, otherwise WordPress does not know which action to fire in the backend (the one used in <code>wp_ajax_fetch_data</code> -> <code>fetch_data</code>).\nAlso, for the url, try to use <code>admin_url( 'admin-ajax.php' );</code> instead:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\njQuery(document).ready( function(){\n\n jQuery('#category').on('change',function (){\n console.log(\"start1\");\n var catId = document.getElementById('category').value;\n console.log(catId);\n jQuery.ajax({\n type: 'POST',\n url: \"&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;\",\n data: {\n 'key':catId,\n 'action': \"fetch_data\" // very important\n },\n cache: false,\n success : function (data) {\n jQuery('#sub_cat').html(data); \n console.log(data);\n }\n });\n });\n});\n\n&lt;/script&gt;\n</code></pre>\n" } ]
2018/11/27
[ "https://wordpress.stackexchange.com/questions/320331", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76017/" ]
I am working on a blog with a pretty high number of authors. I want to keep them from accidentally sending a push message to our readers, since the button of the push-plugin we use looks dangerously similar to the "publish"-button. Is there a way to hide an element like this push-button for certain user groups by default? I can uncheck it in the view-menu above the editor, of course, but that doesn't change it for all other authors.
First, enqueue your script correctly, in `functions.php`: ``` function my_enqueue_scripts() { wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', 'my_enqueue_scripts'); ``` Then, `Authenticated` users only (see <https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)>) (can also be in `functions.php`): ``` function fetchData(){ // Not needed anymore, as you manage the case through the `add_action` method // if ( ! is_user_logged_in() ) { // return; // } // this can be improved $catId = isset($_REQUEST['catId']) ? $_REQUEST['catId'] : ''; echo "<option>$catId</option>"; // there was a typo here: `<optio>` die(); } // add your ajax action to authenticated users only add_action('wp_ajax_fetch_data','fetchData'); // no need for the `nopriv_` action, this one is for anonymous users // add_action('wp_ajax_nopriv_fetch_data','fetchData');?> ``` And finally, your JS script. You must add the `action` parameter, otherwise WordPress does not know which action to fire in the backend (the one used in `wp_ajax_fetch_data` -> `fetch_data`). Also, for the url, try to use `admin_url( 'admin-ajax.php' );` instead: ``` <script type="text/javascript"> jQuery(document).ready( function(){ jQuery('#category').on('change',function (){ console.log("start1"); var catId = document.getElementById('category').value; console.log(catId); jQuery.ajax({ type: 'POST', url: "<?php echo admin_url( 'admin-ajax.php' ); ?>", data: { 'key':catId, 'action': "fetch_data" // very important }, cache: false, success : function (data) { jQuery('#sub_cat').html(data); console.log(data); } }); }); }); </script> ```
320,373
<p>I've searched through WordPress Development and couldn't find the answer, so I either didn't search very well or I couldn't figure out the actual term I needed to search for...</p> <p>I am trying to create a simple mu-plugin to remove update notices, nags and other random notifications created by many of the plugins I use across a lot of sites for clients. The plugin removes the notices for all except a single user.</p> <p>The code below works, but I know I'm not removing the core, plugins and themes notifications.</p> <p>That said, the issue I'm trying to tackle now (to no avail) is to be able to add multiple users who are able to see the notices (by username)... So, <code>AdminUser</code> and <code>AdminUser2</code> and <code>AdminUser3</code> should see the notices when they're logged in.</p> <p>I'm not much of a developer, so any help is much appreciated.</p> <pre><code>//Remove WordPress nags and notices from the WordPress dashboard for all but one user. REPLACE 'AdminUser' with your username function hide_wp_dashboard_notices() { $user = wp_get_current_user(); if($user &amp;&amp; isset($user-&gt;user_login) &amp;&amp; 'AdminUser' !== $user-&gt;user_login) { echo '&lt;style&gt;.update-nag, .updated, .error, .is-dismissible, .notice.woo-permalink-manager-banner, #try-gutenberg-panel, span.update-plugins, .yoast-issue-counter, table.wp-list-table.plugins .notice-warning { display: none !important; }&lt;/style&gt;'; } } add_action('admin_enqueue_scripts', 'hide_wp_dashboard_notices'); add_action('login_enqueue_scripts', 'hide_wp_dashboard_notices'); </code></pre>
[ { "answer_id": 320374, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Your question boils down to simple PHP. It is basically how to avoid</p>\n\n<pre><code>'AdminUser' !== $user-&gt;user_login || 'AdminUser2' !== $user-&gt;user_login || 'AdminUser3' !== $user-&gt;user_login || 'AdminUser4' !== $user-&gt;user_login || etc.\n</code></pre>\n\n<p>One way to solve this is use <a href=\"https://secure.php.net/in_array\" rel=\"nofollow noreferrer\"><code>in_array()</code></a> instead:</p>\n\n<pre><code>$allowed_users = [\n 'AdminUser',\n 'AdminUser2',\n 'AdminUser3',\n // etc\n];\n$user = wp_get_current_user();\n\nif($user &amp;&amp; isset($user-&gt;user_login) &amp;&amp; !in_array($user-&gt;user_login, $allowed_users)) {\n echo '&lt;style&gt;.update-nag, .updated, .error, .is-dismissible, .notice.woo-permalink-manager-banner, #try-gutenberg-panel, span.update-plugins, .yoast-issue-counter, table.wp-list-table.plugins .notice-warning { display: none !important; }&lt;/style&gt;';\n}\n</code></pre>\n" }, { "answer_id": 321142, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>I advise you to use custom capability as it is more correct WordPress way.</p>\n\n<pre><code>function wpse_320373_add_caps() {\n $allowed_users = ['admin', 'test'];\n\n // We add custom capability to each of allowed users after switch theme\n foreach ($allowed_users as $user_name) {\n $user = new WP_User('', $user_name);\n $user-&gt;add_cap( 'allow_notices' );\n }\n}\n\nadd_action( 'after_switch_theme', 'wpse_320373_add_caps' );\n\n\nfunction wpse_320373_notices() {\n $user = wp_get_current_user();\n\n // Check if the capability is set to current user\n if ( $user &amp;&amp; !$user-&gt;has_cap( 'allow_notices' ) ) {\n echo '&lt;style&gt;.update-nag, .updated, .error, .is-dismissible, .notice.woo-permalink-manager-banner, #try-gutenberg-panel, span.update-plugins, .yoast-issue-counter, table.wp-list-table.plugins .notice-warning { display: none !important; }&lt;/style&gt;';\n }\n}\nadd_action('admin_enqueue_scripts', 'wpse_320373_notices');\nadd_action('login_enqueue_scripts', 'wpse_320373_notices');\n</code></pre>\n\n<p>Add this code to functions.php, replace <code>allowed_users</code> logins array and and re-activate your theme to apply new settings.</p>\n\n<p>Note that capability setting is saved to the database, so it will be better to run this on theme/plugin activation but not every page load.</p>\n" } ]
2018/11/27
[ "https://wordpress.stackexchange.com/questions/320373", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14558/" ]
I've searched through WordPress Development and couldn't find the answer, so I either didn't search very well or I couldn't figure out the actual term I needed to search for... I am trying to create a simple mu-plugin to remove update notices, nags and other random notifications created by many of the plugins I use across a lot of sites for clients. The plugin removes the notices for all except a single user. The code below works, but I know I'm not removing the core, plugins and themes notifications. That said, the issue I'm trying to tackle now (to no avail) is to be able to add multiple users who are able to see the notices (by username)... So, `AdminUser` and `AdminUser2` and `AdminUser3` should see the notices when they're logged in. I'm not much of a developer, so any help is much appreciated. ``` //Remove WordPress nags and notices from the WordPress dashboard for all but one user. REPLACE 'AdminUser' with your username function hide_wp_dashboard_notices() { $user = wp_get_current_user(); if($user && isset($user->user_login) && 'AdminUser' !== $user->user_login) { echo '<style>.update-nag, .updated, .error, .is-dismissible, .notice.woo-permalink-manager-banner, #try-gutenberg-panel, span.update-plugins, .yoast-issue-counter, table.wp-list-table.plugins .notice-warning { display: none !important; }</style>'; } } add_action('admin_enqueue_scripts', 'hide_wp_dashboard_notices'); add_action('login_enqueue_scripts', 'hide_wp_dashboard_notices'); ```
Your question boils down to simple PHP. It is basically how to avoid ``` 'AdminUser' !== $user->user_login || 'AdminUser2' !== $user->user_login || 'AdminUser3' !== $user->user_login || 'AdminUser4' !== $user->user_login || etc. ``` One way to solve this is use [`in_array()`](https://secure.php.net/in_array) instead: ``` $allowed_users = [ 'AdminUser', 'AdminUser2', 'AdminUser3', // etc ]; $user = wp_get_current_user(); if($user && isset($user->user_login) && !in_array($user->user_login, $allowed_users)) { echo '<style>.update-nag, .updated, .error, .is-dismissible, .notice.woo-permalink-manager-banner, #try-gutenberg-panel, span.update-plugins, .yoast-issue-counter, table.wp-list-table.plugins .notice-warning { display: none !important; }</style>'; } ```