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
277,558
<p><a href="https://i.stack.imgur.com/bvUt0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bvUt0.png" alt="this is the directory"></a>I am trying to integrate an animation in my Wordpress home page, for this I am trying to load scripts from "skrollr" library, but my styles and scripts don't load.</p> <p>this is the code I added is function.php in the child theme:</p> <pre><code>function add_scripts() { wp_enqueue_style( 'main', get_stylesheet_directory_uri() . '/images/main.css' ); wp_enqueue_script( 'skrollr', get_template_directory_uri() . '/js/skrollr.min.js', '', '', false); } add_action ('wp_enqueue_scripts', 'add_scripts'); </code></pre> <p>and these are the errors that I get from the console: <a href="https://i.stack.imgur.com/5E9E1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5E9E1.png" alt="enter image description here"></a></p>
[ { "answer_id": 277548, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 1, "selected": false, "text": "<p>You can fix this by changes <code>site_url</code> and <code>home_url</code> in your database.</p>\n\n<p>If you have access to your database(phpmyadmin) go to <code>options</code> table and change <code>site_url</code> and <code>home_url</code> from HTTPS to HTTP.</p>\n\n<p>You can also change it through <code>wp-config</code> file. </p>\n\n<pre><code>define('WP_HOME','http://www.example.com');\ndefine('WP_SITEURL','http://www.example.com');\n</code></pre>\n\n<p>See: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a> for possible methods.\nHope this helps.</p>\n" }, { "answer_id": 277567, "author": "Shahzaib Khan", "author_id": 125791, "author_profile": "https://wordpress.stackexchange.com/users/125791", "pm_score": 1, "selected": false, "text": "<p>Best way to fix this problem real quick is via the database, within 10 seconds it be fixed.</p>\n\n<p>Open phpmyadmin via your cPanel and then run the following queries to update the site urls and home url:</p>\n\n<pre><code>UPDATE wp_options\nSET option_value=\"http://www.example.com/\" where option_name =\"siteurl\"\n</code></pre>\n\n<p>and also run another query:</p>\n\n<pre><code>UPDATE wp_options\nSET option_value=\"http://www.example.com/\" where option_name =\"home\"\n</code></pre>\n\n<p>Note: </p>\n\n<ul>\n<li><p>Replace <a href=\"http://www.example.com/\" rel=\"nofollow noreferrer\">http://www.example.com/</a> with your domain URLS</p></li>\n<li><p>Above queries will 100% function if you have your databsae extension as wp_ set.</p></li>\n</ul>\n" }, { "answer_id": 390348, "author": "Stanley", "author_id": 203842, "author_profile": "https://wordpress.stackexchange.com/users/203842", "pm_score": 0, "selected": false, "text": "<p>Access your website using HTTP protocol. You will not face this error.\n<a href=\"http://www.yourdomainname.com/wp-admin/\" rel=\"nofollow noreferrer\">http://www.yourdomainname.com/wp-admin/</a></p>\n<p>SSL is not installed on domain hence you are facing this issue.</p>\n<p>If you have added HTTPS instead of HTTP for WP_HOME and WP_SITEURL then please update it on web.config file. You will have to use HTTP.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126245/" ]
[![this is the directory](https://i.stack.imgur.com/bvUt0.png)](https://i.stack.imgur.com/bvUt0.png)I am trying to integrate an animation in my Wordpress home page, for this I am trying to load scripts from "skrollr" library, but my styles and scripts don't load. this is the code I added is function.php in the child theme: ``` function add_scripts() { wp_enqueue_style( 'main', get_stylesheet_directory_uri() . '/images/main.css' ); wp_enqueue_script( 'skrollr', get_template_directory_uri() . '/js/skrollr.min.js', '', '', false); } add_action ('wp_enqueue_scripts', 'add_scripts'); ``` and these are the errors that I get from the console: [![enter image description here](https://i.stack.imgur.com/5E9E1.png)](https://i.stack.imgur.com/5E9E1.png)
You can fix this by changes `site_url` and `home_url` in your database. If you have access to your database(phpmyadmin) go to `options` table and change `site_url` and `home_url` from HTTPS to HTTP. You can also change it through `wp-config` file. ``` define('WP_HOME','http://www.example.com'); define('WP_SITEURL','http://www.example.com'); ``` See: <https://codex.wordpress.org/Changing_The_Site_URL> for possible methods. Hope this helps.
277,559
<p>I want to redirect every user, depending on its user role, who wants to access home page (its my welcome login page).</p> <p>I don't want to redirect users just after they log in, but after they are logged in and if they maybe again access home page incidentally.</p> <p>Thanks</p>
[ { "answer_id": 277548, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 1, "selected": false, "text": "<p>You can fix this by changes <code>site_url</code> and <code>home_url</code> in your database.</p>\n\n<p>If you have access to your database(phpmyadmin) go to <code>options</code> table and change <code>site_url</code> and <code>home_url</code> from HTTPS to HTTP.</p>\n\n<p>You can also change it through <code>wp-config</code> file. </p>\n\n<pre><code>define('WP_HOME','http://www.example.com');\ndefine('WP_SITEURL','http://www.example.com');\n</code></pre>\n\n<p>See: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL</a> for possible methods.\nHope this helps.</p>\n" }, { "answer_id": 277567, "author": "Shahzaib Khan", "author_id": 125791, "author_profile": "https://wordpress.stackexchange.com/users/125791", "pm_score": 1, "selected": false, "text": "<p>Best way to fix this problem real quick is via the database, within 10 seconds it be fixed.</p>\n\n<p>Open phpmyadmin via your cPanel and then run the following queries to update the site urls and home url:</p>\n\n<pre><code>UPDATE wp_options\nSET option_value=\"http://www.example.com/\" where option_name =\"siteurl\"\n</code></pre>\n\n<p>and also run another query:</p>\n\n<pre><code>UPDATE wp_options\nSET option_value=\"http://www.example.com/\" where option_name =\"home\"\n</code></pre>\n\n<p>Note: </p>\n\n<ul>\n<li><p>Replace <a href=\"http://www.example.com/\" rel=\"nofollow noreferrer\">http://www.example.com/</a> with your domain URLS</p></li>\n<li><p>Above queries will 100% function if you have your databsae extension as wp_ set.</p></li>\n</ul>\n" }, { "answer_id": 390348, "author": "Stanley", "author_id": 203842, "author_profile": "https://wordpress.stackexchange.com/users/203842", "pm_score": 0, "selected": false, "text": "<p>Access your website using HTTP protocol. You will not face this error.\n<a href=\"http://www.yourdomainname.com/wp-admin/\" rel=\"nofollow noreferrer\">http://www.yourdomainname.com/wp-admin/</a></p>\n<p>SSL is not installed on domain hence you are facing this issue.</p>\n<p>If you have added HTTPS instead of HTTP for WP_HOME and WP_SITEURL then please update it on web.config file. You will have to use HTTP.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126244/" ]
I want to redirect every user, depending on its user role, who wants to access home page (its my welcome login page). I don't want to redirect users just after they log in, but after they are logged in and if they maybe again access home page incidentally. Thanks
You can fix this by changes `site_url` and `home_url` in your database. If you have access to your database(phpmyadmin) go to `options` table and change `site_url` and `home_url` from HTTPS to HTTP. You can also change it through `wp-config` file. ``` define('WP_HOME','http://www.example.com'); define('WP_SITEURL','http://www.example.com'); ``` See: <https://codex.wordpress.org/Changing_The_Site_URL> for possible methods. Hope this helps.
277,575
<p>media file has <code>//example.com/wp-content/uploads/2015/08/logo.png</code> without <code>http:</code>.</p> <p>How to change it?</p> <p><a href="https://i.stack.imgur.com/MxJmC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MxJmC.jpg" alt="picture URL without http://"></a></p> <p>I need full <code>http://</code> address in my posts</p>
[ { "answer_id": 277580, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>The URLs in your media library are protocol-relative. This means, no matter if you are on a secure protocol or simply HTTP, the link is always following the domain's protocol.</p>\n\n<p>Now, if you are experiencing problem, there is something you can do which is not recommended.</p>\n\n<p>First, make a back-up! There is <strong>\"No\"</strong> going back if you make a mistake. Back-up, and back-up everything.</p>\n\n<p>Then, download and install <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better search replace</a> plugin. This allows you to replace strings in your database, including serialized data.</p>\n\n<p>Head over to plugin's page, and replace:</p>\n\n<blockquote>\n <p>//yourdomain.com/</p>\n</blockquote>\n\n<p>with</p>\n\n<blockquote>\n <p><a href=\"https://yourdomain.com/\" rel=\"nofollow noreferrer\">https://yourdomain.com/</a></p>\n</blockquote>\n\n<p>Pay attention to slashes, spaces, etc. <em>\"Everything\"</em> matters here, even a capitalized letter might matter.</p>\n" }, { "answer_id": 277610, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 2, "selected": false, "text": "<p>I'm sure some plugin or your theme modifies your attachment url. \nTry to find <code>wp_get_attachment_url</code> hook in your code or simply create your own with high priority this way:</p>\n\n<pre><code>add_filter('wp_get_attachment_url', function($url) {\n return preg_replace(\"~^//(.+)$~\", \"https://$1\", $url);\n}, 999);\n</code></pre>\n\n<p>or better:</p>\n\n<pre><code>add_filter('wp_get_attachment_url', function($url) {\n return set_url_scheme($url, 'https');\n}, 999);\n</code></pre>\n\n<p>But I recommend you to find the reason of this attachment url behavior first.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277575", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126260/" ]
media file has `//example.com/wp-content/uploads/2015/08/logo.png` without `http:`. How to change it? [![picture URL without http://](https://i.stack.imgur.com/MxJmC.jpg)](https://i.stack.imgur.com/MxJmC.jpg) I need full `http://` address in my posts
I'm sure some plugin or your theme modifies your attachment url. Try to find `wp_get_attachment_url` hook in your code or simply create your own with high priority this way: ``` add_filter('wp_get_attachment_url', function($url) { return preg_replace("~^//(.+)$~", "https://$1", $url); }, 999); ``` or better: ``` add_filter('wp_get_attachment_url', function($url) { return set_url_scheme($url, 'https'); }, 999); ``` But I recommend you to find the reason of this attachment url behavior first.
277,599
<p>I need to capture a value displayed on the website to the user, and then store it in a variable. Ideally, I'd like to do this in functions.php. </p> <p>More specifically, we use dynamic phone number replacement on the sites, and we’d like to know which phone number is displayed to the user when they are submitting a contact form (via Gravity Forms).</p> <p>I can wrap the phone number in a class or ID, but am struggling to understand how to write a function to pull this value into a variable.</p> <p>I have submitted my question to Gravity Forms, but they will not assist. Thanks.</p>
[ { "answer_id": 277580, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>The URLs in your media library are protocol-relative. This means, no matter if you are on a secure protocol or simply HTTP, the link is always following the domain's protocol.</p>\n\n<p>Now, if you are experiencing problem, there is something you can do which is not recommended.</p>\n\n<p>First, make a back-up! There is <strong>\"No\"</strong> going back if you make a mistake. Back-up, and back-up everything.</p>\n\n<p>Then, download and install <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better search replace</a> plugin. This allows you to replace strings in your database, including serialized data.</p>\n\n<p>Head over to plugin's page, and replace:</p>\n\n<blockquote>\n <p>//yourdomain.com/</p>\n</blockquote>\n\n<p>with</p>\n\n<blockquote>\n <p><a href=\"https://yourdomain.com/\" rel=\"nofollow noreferrer\">https://yourdomain.com/</a></p>\n</blockquote>\n\n<p>Pay attention to slashes, spaces, etc. <em>\"Everything\"</em> matters here, even a capitalized letter might matter.</p>\n" }, { "answer_id": 277610, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 2, "selected": false, "text": "<p>I'm sure some plugin or your theme modifies your attachment url. \nTry to find <code>wp_get_attachment_url</code> hook in your code or simply create your own with high priority this way:</p>\n\n<pre><code>add_filter('wp_get_attachment_url', function($url) {\n return preg_replace(\"~^//(.+)$~\", \"https://$1\", $url);\n}, 999);\n</code></pre>\n\n<p>or better:</p>\n\n<pre><code>add_filter('wp_get_attachment_url', function($url) {\n return set_url_scheme($url, 'https');\n}, 999);\n</code></pre>\n\n<p>But I recommend you to find the reason of this attachment url behavior first.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277599", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126276/" ]
I need to capture a value displayed on the website to the user, and then store it in a variable. Ideally, I'd like to do this in functions.php. More specifically, we use dynamic phone number replacement on the sites, and we’d like to know which phone number is displayed to the user when they are submitting a contact form (via Gravity Forms). I can wrap the phone number in a class or ID, but am struggling to understand how to write a function to pull this value into a variable. I have submitted my question to Gravity Forms, but they will not assist. Thanks.
I'm sure some plugin or your theme modifies your attachment url. Try to find `wp_get_attachment_url` hook in your code or simply create your own with high priority this way: ``` add_filter('wp_get_attachment_url', function($url) { return preg_replace("~^//(.+)$~", "https://$1", $url); }, 999); ``` or better: ``` add_filter('wp_get_attachment_url', function($url) { return set_url_scheme($url, 'https'); }, 999); ``` But I recommend you to find the reason of this attachment url behavior first.
277,602
<p>I recently migrated a live wordpress site, watershedgeo.com, over to a development site using the temp url, <a href="http://vps3813.inmotionhosting.com/~watershedgeo/dev.watershedgeo.com/" rel="nofollow noreferrer">http://vps3813.inmotionhosting.com/~watershedgeo/dev.watershedgeo.com/</a>.</p> <p>I finally got it launched but the images and links don't show, they're all broken, but a lot of the images are showing their alt text. Here's the weird thing:</p> <p>If I inspect the images in chrome, they show the temp url as the src of the image, but if I change the root before wp-content to watershedgeo.com, they show up. However, if I inspect the images on the live site, they show the source as <a href="http://1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com/wp-content/uploads/2016/04/imageName" rel="nofollow noreferrer">http://1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com/wp-content/uploads/2016/04/imageName</a></p> <p>Is there a plugin or a way that I can change it so all the images use 1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com as the root so the images can show for development? All folders match, it's just the root that needs to be changed</p> <p>The temp url is what is in the site url for the database and the wp-config.php file.</p>
[ { "answer_id": 277580, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>The URLs in your media library are protocol-relative. This means, no matter if you are on a secure protocol or simply HTTP, the link is always following the domain's protocol.</p>\n\n<p>Now, if you are experiencing problem, there is something you can do which is not recommended.</p>\n\n<p>First, make a back-up! There is <strong>\"No\"</strong> going back if you make a mistake. Back-up, and back-up everything.</p>\n\n<p>Then, download and install <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better search replace</a> plugin. This allows you to replace strings in your database, including serialized data.</p>\n\n<p>Head over to plugin's page, and replace:</p>\n\n<blockquote>\n <p>//yourdomain.com/</p>\n</blockquote>\n\n<p>with</p>\n\n<blockquote>\n <p><a href=\"https://yourdomain.com/\" rel=\"nofollow noreferrer\">https://yourdomain.com/</a></p>\n</blockquote>\n\n<p>Pay attention to slashes, spaces, etc. <em>\"Everything\"</em> matters here, even a capitalized letter might matter.</p>\n" }, { "answer_id": 277610, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 2, "selected": false, "text": "<p>I'm sure some plugin or your theme modifies your attachment url. \nTry to find <code>wp_get_attachment_url</code> hook in your code or simply create your own with high priority this way:</p>\n\n<pre><code>add_filter('wp_get_attachment_url', function($url) {\n return preg_replace(\"~^//(.+)$~\", \"https://$1\", $url);\n}, 999);\n</code></pre>\n\n<p>or better:</p>\n\n<pre><code>add_filter('wp_get_attachment_url', function($url) {\n return set_url_scheme($url, 'https');\n}, 999);\n</code></pre>\n\n<p>But I recommend you to find the reason of this attachment url behavior first.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277602", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115321/" ]
I recently migrated a live wordpress site, watershedgeo.com, over to a development site using the temp url, <http://vps3813.inmotionhosting.com/~watershedgeo/dev.watershedgeo.com/>. I finally got it launched but the images and links don't show, they're all broken, but a lot of the images are showing their alt text. Here's the weird thing: If I inspect the images in chrome, they show the temp url as the src of the image, but if I change the root before wp-content to watershedgeo.com, they show up. However, if I inspect the images on the live site, they show the source as <http://1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com/wp-content/uploads/2016/04/imageName> Is there a plugin or a way that I can change it so all the images use 1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com as the root so the images can show for development? All folders match, it's just the root that needs to be changed The temp url is what is in the site url for the database and the wp-config.php file.
I'm sure some plugin or your theme modifies your attachment url. Try to find `wp_get_attachment_url` hook in your code or simply create your own with high priority this way: ``` add_filter('wp_get_attachment_url', function($url) { return preg_replace("~^//(.+)$~", "https://$1", $url); }, 999); ``` or better: ``` add_filter('wp_get_attachment_url', function($url) { return set_url_scheme($url, 'https'); }, 999); ``` But I recommend you to find the reason of this attachment url behavior first.
277,617
<p>How can I redirect users if they want to visit any other pages, but login page and password reset page?</p> <p>My login page is actually my homepage and I want to redirect all of them to login page if they are not logged in. Also to allow them to reset password if they have forgotten them.</p> <p>Thanks</p>
[ { "answer_id": 277623, "author": "Fabio Marzocca", "author_id": 65278, "author_profile": "https://wordpress.stackexchange.com/users/65278", "pm_score": 0, "selected": false, "text": "<p>You can add a rewrite rule into your .htaccess, checking for not-logged users, and redirect them to home page:</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]\nRewriteRule . /index.php [NC]\n</code></pre>\n\n<p>On your login page you should provide a link to reset forgotten password.</p>\n" }, { "answer_id": 277624, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>In Settings, Reading, enable the \"Visible only to registered users of this site\" button. All site visitors will see the login page.</p>\n\n<p>After login, users will be directed to thier user profile page. You can change that redirection with code similar to this, which will redirect to the site's home page. (In your case, you'd need to change your home page to something else so they don't need to log in twice.)</p>\n\n<pre><code>function go_here_after_login( $redirect_to, $request, $user ) { \n if (current_user_can( 'manage_options' )) {return $redirect_to;}\n else {return home_url();}\n\n return;\n}\nadd_filter ('login_redirect', 'go_here_after_login', 10, 3);\n</code></pre>\n\n<p>There are lots of googles on how to change your login screen.</p>\n\n<p>Note that you can use htaccess to require a login, but this method lets you use the WP User accounts you have on your site.</p>\n" }, { "answer_id": 277631, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": true, "text": "<p>You indicated that your login page is your home page. If you want all non-logged in users to then be directed to the home page to log in, you need to check a couple of things:</p>\n\n<ol>\n<li>Is the user logged in?</li>\n<li>Is the current page the home page?</li>\n</ol>\n\n<p>You can do these things with <code>is_user_logged_in()</code> and is_front_page(). If these are not true, then you can use <code>wp_redirect()</code> to redirect the user to the home page.</p>\n\n<p>Assuming your forgot password page is a \"page,\" you could use <code>is_page()</code> in your logic as well.</p>\n\n<p>You'll need to hook it to an action so that it fires late enough to allow checking the page, but early enough to still safely redirect the user (i.e. before headers are sent). <code>template_redirect</code> is ideal for this.</p>\n\n<pre><code>add_action( 'template_redirect', 'my_frontpage_redirect' );\nfunction my_frontpage_redirect() {\n if ( ! is_user_logged_in() ) {\n if ( ! is_front_page() &amp;&amp; ! is_page( 'my-password-reset' ) ) {\n wp_redirect( home_url() );\n exit();\n }\n }\n}\n</code></pre>\n\n<p>Adjust the slug in the <code>is_page()</code> call according to whatever the page slug is for your password reset.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126244/" ]
How can I redirect users if they want to visit any other pages, but login page and password reset page? My login page is actually my homepage and I want to redirect all of them to login page if they are not logged in. Also to allow them to reset password if they have forgotten them. Thanks
You indicated that your login page is your home page. If you want all non-logged in users to then be directed to the home page to log in, you need to check a couple of things: 1. Is the user logged in? 2. Is the current page the home page? You can do these things with `is_user_logged_in()` and is\_front\_page(). If these are not true, then you can use `wp_redirect()` to redirect the user to the home page. Assuming your forgot password page is a "page," you could use `is_page()` in your logic as well. You'll need to hook it to an action so that it fires late enough to allow checking the page, but early enough to still safely redirect the user (i.e. before headers are sent). `template_redirect` is ideal for this. ``` add_action( 'template_redirect', 'my_frontpage_redirect' ); function my_frontpage_redirect() { if ( ! is_user_logged_in() ) { if ( ! is_front_page() && ! is_page( 'my-password-reset' ) ) { wp_redirect( home_url() ); exit(); } } } ``` Adjust the slug in the `is_page()` call according to whatever the page slug is for your password reset.
277,618
<p>I have a page that contain all my servers data, it really sensitive information. Is there any strong way to hide it from google spiders and non login users.</p> <p>I found small solutions that's hide the page, but not secured at all, if someone search in the website directory he will get access to that page easily. Any hints here?!</p>
[ { "answer_id": 277620, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 3, "selected": true, "text": "<p>Use <a href=\"https://codex.wordpress.org/Using_Password_Protection\" rel=\"nofollow noreferrer\">password protection mechanism</a> </p>\n\n<p>Alterative you can use wordpress hook in your theme to show your post/page only for administrators this way:</p>\n\n<pre><code>add_action('wp', function() {\n if(is_page('my-data') &amp;&amp; !current_user_can('manage_options')) \n die(\"123\")\n});\n</code></pre>\n\n<p>Note: don't use this code. It is just for demonstration. Better use hook <code>template_redirect</code> or something else. </p>\n\n<p>We need more info about your environment to answer more specifically.</p>\n\n<p>Perhaps the best option for you would be set password by http-server.\nFor apache using .htacces with something:</p>\n\n<pre><code>AuthType Basic\nAuthName \"restricted area\"\nAuthUserFile .htpasswd\nrequire valid-user\n</code></pre>\n" }, { "answer_id": 277622, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Besides using a password protect mechanism, as mentioned in the other answer, you can also use htaccess rules, as explained in this Stack question: <a href=\"https://stackoverflow.com/questions/14603568/password-protect-a-specific-url\">https://stackoverflow.com/questions/14603568/password-protect-a-specific-url</a> </p>\n\n<p>Another resource that can help you with the password encryption is this place: <a href=\"http://tools.dynamicdrive.com/password/\" rel=\"nofollow noreferrer\">http://tools.dynamicdrive.com/password/</a> (that site and info has been around for years, so little chance of the link 'dying'). </p>\n" }, { "answer_id": 277633, "author": "Crazycoolcam", "author_id": 28144, "author_profile": "https://wordpress.stackexchange.com/users/28144", "pm_score": 1, "selected": false, "text": "<p>The strongest way is simply to not display it unless the user has been validated.</p>\n\n<p>If you have manually entered this info, or have access to make your sensitive info to use a custom-page template or with a shortcode, you can program your code to only selectively display after the user has been authenticated.</p>\n\n<p>For example (the shortcode method):</p>\n\n<pre><code>function my_data_func( $atts ){\n if(is_user_logged_in() &amp;&amp; current_user_can('manage_options')) {\n //display my server data via return statement.\n } else {\n return 'I am sorry. You must be logged in as an administrator to view this content.';\n }\n}\nadd_shortcode( 'my_data', 'my_data_func' ); //Ex. [my_data]\n</code></pre>\n\n<p>The page template method works in a similar way, but uses an extra file in the theme that you then specify your protected page to use.</p>\n" } ]
2017/08/21
[ "https://wordpress.stackexchange.com/questions/277618", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124400/" ]
I have a page that contain all my servers data, it really sensitive information. Is there any strong way to hide it from google spiders and non login users. I found small solutions that's hide the page, but not secured at all, if someone search in the website directory he will get access to that page easily. Any hints here?!
Use [password protection mechanism](https://codex.wordpress.org/Using_Password_Protection) Alterative you can use wordpress hook in your theme to show your post/page only for administrators this way: ``` add_action('wp', function() { if(is_page('my-data') && !current_user_can('manage_options')) die("123") }); ``` Note: don't use this code. It is just for demonstration. Better use hook `template_redirect` or something else. We need more info about your environment to answer more specifically. Perhaps the best option for you would be set password by http-server. For apache using .htacces with something: ``` AuthType Basic AuthName "restricted area" AuthUserFile .htpasswd require valid-user ```
277,649
<p>I submitted my site to Google and now the author page is showing up in the search results. </p> <pre><code>http://www.domain.com/author/myusername </code></pre> <p>How do I prevent my and others author names from showing up in search results? </p> <p>It would be best to disable completely the path "/author/" all together because it's not a blog but a product site (it only has pages). </p> <p>I did a search earlier and saw that there are plugins to do this but I'd rather not install a plugin (sometimes they are not updated) if there is another way but will if I have to. </p> <p>I also searched through the source code of the pages and did not see any links to the author page. </p>
[ { "answer_id": 315604, "author": "Cbinger", "author_id": 144946, "author_profile": "https://wordpress.stackexchange.com/users/144946", "pm_score": 2, "selected": false, "text": "<p>You can disable the access to author pages by adding this snippet to functions.php:</p>\n\n<pre><code>// Disable access to author page\nadd_action('template_redirect', 'my_custom_disable_author_page');\n\nfunction my_custom_disable_author_page() {\n global $wp_query;\n\n if ( is_author() ) {\n $wp_query-&gt;set_404();\n status_header(404);\n // Redirect to homepage\n // wp_redirect(get_option('home'));\n }\n}\n</code></pre>\n" }, { "answer_id": 332018, "author": "David Hobs", "author_id": 14403, "author_profile": "https://wordpress.stackexchange.com/users/14403", "pm_score": 5, "selected": true, "text": "<p>The above answer is good, but if redirecting to home page, it should specify a 301 status and exit after.</p>\n\n<pre><code>add_action('template_redirect', 'my_custom_disable_author_page');\n\nfunction my_custom_disable_author_page() {\n global $wp_query;\n\n if ( is_author() ) {\n // Redirect to homepage, set status to 301 permenant redirect. \n // Function defaults to 302 temporary redirect. \n wp_redirect(get_option('home'), 301); \n exit; \n }\n}\n</code></pre>\n\n<p>wp_redirect() documentation <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/wp_redirect/</a> </p>\n" }, { "answer_id": 332757, "author": "webdevlin", "author_id": 161101, "author_profile": "https://wordpress.stackexchange.com/users/161101", "pm_score": 3, "selected": false, "text": "<p>You can also add the redirect to the author template directly. In your WordPress theme, edit the <em>author.php</em> file to redirect users to your homepage. If your theme doesn't have a template for author pages, create a file named <em>author.php</em>.</p>\n<p><strong>author.php</strong>: (Using php header function)</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n//Redirect author pages to the homepage\nheader(&quot;HTTP/1.1 301 Moved Permanently&quot;);\nheader(&quot;Location: /&quot;);\ndie(); // avoid further PHP processing\n//That's all folks\n</code></pre>\n<p>The <code>die()</code> part is to avoid that anyone using a client which does NOT follow the redirect header sees the content of the page since WP would continue building the original author page and send its response to the client requesting it.</p>\n<hr />\n<p><strong>UPDATE</strong>:\nWordPress has a couple of built in functions to handle redirects: <em>wp_redirect()</em> and <em>wp_safe_redirect()</em>. <em>wp_redirect()</em> accepts a string as the redirect location and an integer as the redirect type (302 is the default). <em>wp_safe_redirect()</em> is the same as <em>wp_redirect()</em> except that it makes sure that the redirect location is found in a list of allowed hosts.</p>\n<p><strong>author.php</strong>: (Using WordPress wp_safe_redirect function)</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n//Redirect author pages to the homepage with WordPress redirect function\nwp_safe_redirect( get_home_url(), 301 );\nexit;\n//That's all folks\n</code></pre>\n<p>More information</p>\n<ul>\n<li>WordPress template hierarchy:\n<a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></li>\n<li>PHP header function: <a href=\"https://www.php.net/manual/en/function.header.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.header.php</a></li>\n<li>WordPress wp_safe_redirect function: <a href=\"https://codex.wordpress.org/Function_Reference/wp_safe_redirect\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_safe_redirect</a></li>\n</ul>\n" }, { "answer_id": 332758, "author": "Nouman Ejaz", "author_id": 161539, "author_profile": "https://wordpress.stackexchange.com/users/161539", "pm_score": 2, "selected": false, "text": "<p>You can disable the access to author pages if you add the following code in functions.php: file</p>\n\n<pre><code>add_action('template_redirect', 'my_custom_disable_author_page');\n\n function my_custom_disable_author_page() {\n global $wp_query;\n if ( is_author() ) {\n $wp_query-&gt;set_404();\n status_header(404);\n }\n }\n</code></pre>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29247/" ]
I submitted my site to Google and now the author page is showing up in the search results. ``` http://www.domain.com/author/myusername ``` How do I prevent my and others author names from showing up in search results? It would be best to disable completely the path "/author/" all together because it's not a blog but a product site (it only has pages). I did a search earlier and saw that there are plugins to do this but I'd rather not install a plugin (sometimes they are not updated) if there is another way but will if I have to. I also searched through the source code of the pages and did not see any links to the author page.
The above answer is good, but if redirecting to home page, it should specify a 301 status and exit after. ``` add_action('template_redirect', 'my_custom_disable_author_page'); function my_custom_disable_author_page() { global $wp_query; if ( is_author() ) { // Redirect to homepage, set status to 301 permenant redirect. // Function defaults to 302 temporary redirect. wp_redirect(get_option('home'), 301); exit; } } ``` wp\_redirect() documentation <https://developer.wordpress.org/reference/functions/wp_redirect/>
277,670
<p>I'm currently using the Hemingway theme as seen here: </p> <p>gamingprofessors.com</p> <p>Currently this theme provides a pleasing tag when generated, however I can't change what the tag reads as. At least individually. I know I can go into the functions.php and change the $more_link_text:</p> <pre><code>// Custom more-link text add_filter( 'the_content_more_link', 'hemingway_custom_more_link', 10, 2 ); function hemingway_custom_more_link( $more_link, $more_link_text ) { return str_replace( $more_link_text, __('Episode Summary and Extras', 'hemingway'), $more_link ); } </code></pre> <p>as I have done. However, I also am interested in writing normal blog posts and don't wish for them to take up large amounts of page real estate. The reason I chose "episode summary and extras" as the text is it's more obvious and entices a click vs "read more". However during a regular blog post this tag wouldn't make sense. Is there anyway to allow me to customize the tag and have it display, for example and without losing the formatting and colored box behind the tag currently? Also Hemingway doesn't support excerpts, at least not on blog posts as far as I can tell. So this isn't an option. I don't mind typing out the custom tag each post.</p>
[ { "answer_id": 277676, "author": "deflime", "author_id": 18907, "author_profile": "https://wordpress.stackexchange.com/users/18907", "pm_score": 2, "selected": true, "text": "<p>WordPress has the functionality <a href=\"https://codex.wordpress.org/Customizing_the_Read_More\" rel=\"nofollow noreferrer\">built-in</a> natively.</p>\n\n<p>Try updating the read more tag in the <code>Text</code> editor. Examples:</p>\n\n<pre><code>&lt;!--more Episode Summary and Extras --&gt;\n&lt;!--more Regular Blog Post --&gt;\n&lt;!--more Read More About My Cats --&gt;\n</code></pre>\n\n<p>This only works with <code>the_content()</code>, but it sounds like your theme's blog loop is using that.</p>\n" }, { "answer_id": 277753, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>You can make shortcode with custom more text and show it only on archive pages (not single.php). It allows customize you read more text. </p>\n\n<p>Something like this </p>\n\n<pre><code>add_shortcode('readmore', ...)\n\nif(!is_singular())\n do_shortcode('readmore');\n</code></pre>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126310/" ]
I'm currently using the Hemingway theme as seen here: gamingprofessors.com Currently this theme provides a pleasing tag when generated, however I can't change what the tag reads as. At least individually. I know I can go into the functions.php and change the $more\_link\_text: ``` // Custom more-link text add_filter( 'the_content_more_link', 'hemingway_custom_more_link', 10, 2 ); function hemingway_custom_more_link( $more_link, $more_link_text ) { return str_replace( $more_link_text, __('Episode Summary and Extras', 'hemingway'), $more_link ); } ``` as I have done. However, I also am interested in writing normal blog posts and don't wish for them to take up large amounts of page real estate. The reason I chose "episode summary and extras" as the text is it's more obvious and entices a click vs "read more". However during a regular blog post this tag wouldn't make sense. Is there anyway to allow me to customize the tag and have it display, for example and without losing the formatting and colored box behind the tag currently? Also Hemingway doesn't support excerpts, at least not on blog posts as far as I can tell. So this isn't an option. I don't mind typing out the custom tag each post.
WordPress has the functionality [built-in](https://codex.wordpress.org/Customizing_the_Read_More) natively. Try updating the read more tag in the `Text` editor. Examples: ``` <!--more Episode Summary and Extras --> <!--more Regular Blog Post --> <!--more Read More About My Cats --> ``` This only works with `the_content()`, but it sounds like your theme's blog loop is using that.
277,677
<p>i created website in local using word press theme, then uploaded on server but in server database have table like <strong>wp_2xxfpfb5qn_options</strong> and local have tables like &quot;doc_options&quot; so its not taking value from proper table, hence my theme not showing as i did changes in local theme. so what i have do for it?</p> <p>Now, it's showing please check this link <a href="http://clinic2.cruxbytes.com" rel="nofollow noreferrer">Site</a></p>
[ { "answer_id": 277676, "author": "deflime", "author_id": 18907, "author_profile": "https://wordpress.stackexchange.com/users/18907", "pm_score": 2, "selected": true, "text": "<p>WordPress has the functionality <a href=\"https://codex.wordpress.org/Customizing_the_Read_More\" rel=\"nofollow noreferrer\">built-in</a> natively.</p>\n\n<p>Try updating the read more tag in the <code>Text</code> editor. Examples:</p>\n\n<pre><code>&lt;!--more Episode Summary and Extras --&gt;\n&lt;!--more Regular Blog Post --&gt;\n&lt;!--more Read More About My Cats --&gt;\n</code></pre>\n\n<p>This only works with <code>the_content()</code>, but it sounds like your theme's blog loop is using that.</p>\n" }, { "answer_id": 277753, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>You can make shortcode with custom more text and show it only on archive pages (not single.php). It allows customize you read more text. </p>\n\n<p>Something like this </p>\n\n<pre><code>add_shortcode('readmore', ...)\n\nif(!is_singular())\n do_shortcode('readmore');\n</code></pre>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126317/" ]
i created website in local using word press theme, then uploaded on server but in server database have table like **wp\_2xxfpfb5qn\_options** and local have tables like "doc\_options" so its not taking value from proper table, hence my theme not showing as i did changes in local theme. so what i have do for it? Now, it's showing please check this link [Site](http://clinic2.cruxbytes.com)
WordPress has the functionality [built-in](https://codex.wordpress.org/Customizing_the_Read_More) natively. Try updating the read more tag in the `Text` editor. Examples: ``` <!--more Episode Summary and Extras --> <!--more Regular Blog Post --> <!--more Read More About My Cats --> ``` This only works with `the_content()`, but it sounds like your theme's blog loop is using that.
277,718
<p>I am having problem when I want to display my taxonomy template.<br> I have created one custom taxonomy 'Location' for my custom post type 'Project'. Moreover, I have created templates for it as :</p> <pre><code>taxonomy-{taxonomy_name}-{term}.php taxonomy-{taxonomy_name}.php taxonomy.php </code></pre> <p>None of them work... I just get my archive-{post_type}.php in all case. </p> <p>My targetted URLs are :<br> <code>mywebsite.com/holliday/united-kingdom/</code> (Location taxonomy)<br> <code>mywebsite.com/holliday/united-kingdom/london</code> (Location taxonomy child)</p> <p>I should have messed up or missed something when creating my taxonomy but can't get it right.</p> <p>Here is my code (register post type and register taxonomy) :</p> <pre><code>// Register Post Type (Holliday) $capability = 'publish_posts'; $cpt_args = array( 'menu_icon' =&gt; 'dashicons-groups', 'labels' =&gt; array( 'name' =&gt; __( 'Holliday', 'mon-plugin' ), 'singular_name' =&gt; __( 'Holliday', 'mon-plugin' ), 'add_new' =&gt; __( 'Add Holliday', 'mon-plugin' ), 'add_new_item' =&gt; __( 'Add Holliday', 'mon-plugin' ), 'edit' =&gt; __( 'Edit', 'mon-plugin' ), 'edit_item' =&gt; __( 'Edit Holliday', 'mon-plugin' ), 'new_item' =&gt; __( 'New Holliday', 'mon-plugin' ), 'view' =&gt; __( 'View Holliday', 'mon-plugin' ), 'view_item' =&gt; __( 'View Holliday', 'mon-plugin' ), 'search_items' =&gt; __( 'Search Holliday', 'mon-plugin' ), 'not_found' =&gt; __( 'No Holliday found', 'mon-plugin' ), 'not_found_in_trash'=&gt; __( 'No Holliday found in Trash', 'mon-plugin' ), 'parent' =&gt; __( 'Parent Holliday', 'mon-plugin' ), ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'holliday/%my_project_location%', ), 'supports' =&gt; array('title', 'custom-fields', 'excerpt', 'editor', 'author', 'thumbnail', 'comments'), 'capabilities' =&gt; array( 'publish_posts' =&gt; $capability, 'edit_posts' =&gt; $capability, 'edit_others_posts' =&gt; $capability, 'delete_posts' =&gt; $capability, 'delete_others_posts'=&gt; $capability, 'read_private_posts'=&gt; $capability, 'edit_post' =&gt; $capability, 'delete_post' =&gt; $capability, 'read_post' =&gt; $capability ), ); register_post_type( 'my_project', $cpt_args ); // Register Taxonomy (Location) $cats_args = array( 'labels' =&gt; array( 'name' =&gt; _x( 'Project Location', 'mon-plugin' ), 'singular_name' =&gt; _x( 'Location', 'mon-plugin' ), 'search_items' =&gt; __( 'Search Location', 'mon-plugin' ), 'all_items' =&gt; __( 'All Location', 'mon-plugin' ), 'parent_item' =&gt; __( 'Parent Location', 'mon-plugin' ), 'parent_item_colon' =&gt; __( 'Parent Location:', 'mon-plugin' ), 'edit_item' =&gt; __( 'Edit Location', 'mon-plugin' ), 'update_item' =&gt; __( 'Update Location', 'mon-plugin' ), 'add_new_item' =&gt; __( 'Add New Location', 'mon-plugin' ), 'new_item_name' =&gt; __( 'New Location Name', 'mon-plugin' ), 'menu_name' =&gt; __( 'Location', 'mon-plugin' ), ), 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'holliday', 'hierarchical' =&gt; true ) ); register_taxonomy( 'my_project_location', 'my_project', $cats_args ); </code></pre> <p>EDIT:<br> If I change my taxonomy slug into something else, I get my taxonomy template working.<br> Example: </p> <pre><code> taxonomy slug =&gt; "location" mywebsite.com/location/united-kingdom/ =&gt; Taxonomy template working ! </code></pre> <p>But I want my taxonomy to work with my custom post type. To get my taxonomy template when accessing <code>mywebsite.com/{custom-post-type}/{taxonomy}/</code><br> But this give me <code>archive-{custom-post-type}.php</code> file instead. </p> <p>Following the <a href="https://developer.wordpress.org/themes/basics/template-hierarchy/" rel="nofollow noreferrer">Template Hierarchy</a> I expect Wordpress to find me the taxonomy template before the archive template. </p> <p>Is there something I am missing ?<br> Thank you for your help.</p>
[ { "answer_id": 278029, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>There are a couple of different solutions if you want to have only the /holliday/project-location/ URL and not separate archive and taxonomy URLs.</p>\n\n<p><strong>Option 1:</strong></p>\n\n<p>Use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow noreferrer\"><code>template_include()</code> filter</a>. I think this code would work but have not tested:</p>\n\n<pre><code>add_filter( 'template_include', 'holliday_template', 99 );\n\nfunction holliday_template( $template ) {\n\n if ( is_post_type_archive( 'holliday' ) ) {\n $new_template = locate_template( array( 'taxonomy-my_project_location.php' ) );\n if ( '' != $new_template ) {\n return $new_template;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p><strong>Option 2</strong> (even simpler):</p>\n\n<p>Tell WP not to give your <code>holliday</code> CPT an archive. When you register the post type, just change <code>'has_archive' =&gt; true,</code> to <code>false</code>. That way, when WP looks for content at your desired URL, only the taxonomy archive exists. You will most likely need to use <code>unregister_post_type()</code> and re-register it to force the change.</p>\n" }, { "answer_id": 278092, "author": "jardindeden", "author_id": 116160, "author_profile": "https://wordpress.stackexchange.com/users/116160", "pm_score": 1, "selected": true, "text": "<p>Thank you WebElaine for your help ! I figured out a way to solve it.</p>\n\n<p>It looks a bit as you proposed in <strong>Option 2</strong>. Except that I used the filter <strong><code>parse_query</code></strong> to change my CPT <code>'has_archive'</code> to false when accessing my taxonomy. </p>\n\n<p>Here is the code : </p>\n\n<pre><code>function check_taxonomy_query( $query ) {\n if ($query-&gt;query['my_project_location'] &amp;&amp; !$query-&gt;query['my_project']) {\n $query-&gt;is_post_type_archive = false;\n }\n}\nadd_action( 'parse_query', 'check_taxonomy_query' ); \n</code></pre>\n\n<p><code>my_project_location</code> and <code>my_project</code> are the query vars used for my rewrite rules:</p>\n\n<pre><code>$newRules['holliday/?$'] = 'index.php?lang=en&amp;post_type=my_project';\n$newRules['holliday/([^/]+)/?$'] = 'index.php?lang=en&amp;post_type=my_project&amp;my_project_location=$matches[1]';\n$newRules['holliday/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&amp;post_type=my_project&amp;my_project_location=$matches[1]/$matches[2]';\n$newRules['holliday/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&amp;post_type=my_project&amp;my_project_location=$matches[1]/$matches[2]&amp;my_project=$matches[3]';\n</code></pre>\n\n<p>So in the <code>check_taxonomy_query</code> function, I simply check if I am in the case of the 2nd or 3rd line of my rewrite rules. If yes, I turn the post type archive down.</p>\n\n<p>Hope it could help someone ;)</p>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116160/" ]
I am having problem when I want to display my taxonomy template. I have created one custom taxonomy 'Location' for my custom post type 'Project'. Moreover, I have created templates for it as : ``` taxonomy-{taxonomy_name}-{term}.php taxonomy-{taxonomy_name}.php taxonomy.php ``` None of them work... I just get my archive-{post\_type}.php in all case. My targetted URLs are : `mywebsite.com/holliday/united-kingdom/` (Location taxonomy) `mywebsite.com/holliday/united-kingdom/london` (Location taxonomy child) I should have messed up or missed something when creating my taxonomy but can't get it right. Here is my code (register post type and register taxonomy) : ``` // Register Post Type (Holliday) $capability = 'publish_posts'; $cpt_args = array( 'menu_icon' => 'dashicons-groups', 'labels' => array( 'name' => __( 'Holliday', 'mon-plugin' ), 'singular_name' => __( 'Holliday', 'mon-plugin' ), 'add_new' => __( 'Add Holliday', 'mon-plugin' ), 'add_new_item' => __( 'Add Holliday', 'mon-plugin' ), 'edit' => __( 'Edit', 'mon-plugin' ), 'edit_item' => __( 'Edit Holliday', 'mon-plugin' ), 'new_item' => __( 'New Holliday', 'mon-plugin' ), 'view' => __( 'View Holliday', 'mon-plugin' ), 'view_item' => __( 'View Holliday', 'mon-plugin' ), 'search_items' => __( 'Search Holliday', 'mon-plugin' ), 'not_found' => __( 'No Holliday found', 'mon-plugin' ), 'not_found_in_trash'=> __( 'No Holliday found in Trash', 'mon-plugin' ), 'parent' => __( 'Parent Holliday', 'mon-plugin' ), ), 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => 'holliday/%my_project_location%', ), 'supports' => array('title', 'custom-fields', 'excerpt', 'editor', 'author', 'thumbnail', 'comments'), 'capabilities' => array( 'publish_posts' => $capability, 'edit_posts' => $capability, 'edit_others_posts' => $capability, 'delete_posts' => $capability, 'delete_others_posts'=> $capability, 'read_private_posts'=> $capability, 'edit_post' => $capability, 'delete_post' => $capability, 'read_post' => $capability ), ); register_post_type( 'my_project', $cpt_args ); // Register Taxonomy (Location) $cats_args = array( 'labels' => array( 'name' => _x( 'Project Location', 'mon-plugin' ), 'singular_name' => _x( 'Location', 'mon-plugin' ), 'search_items' => __( 'Search Location', 'mon-plugin' ), 'all_items' => __( 'All Location', 'mon-plugin' ), 'parent_item' => __( 'Parent Location', 'mon-plugin' ), 'parent_item_colon' => __( 'Parent Location:', 'mon-plugin' ), 'edit_item' => __( 'Edit Location', 'mon-plugin' ), 'update_item' => __( 'Update Location', 'mon-plugin' ), 'add_new_item' => __( 'Add New Location', 'mon-plugin' ), 'new_item_name' => __( 'New Location Name', 'mon-plugin' ), 'menu_name' => __( 'Location', 'mon-plugin' ), ), 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => 'holliday', 'hierarchical' => true ) ); register_taxonomy( 'my_project_location', 'my_project', $cats_args ); ``` EDIT: If I change my taxonomy slug into something else, I get my taxonomy template working. Example: ``` taxonomy slug => "location" mywebsite.com/location/united-kingdom/ => Taxonomy template working ! ``` But I want my taxonomy to work with my custom post type. To get my taxonomy template when accessing `mywebsite.com/{custom-post-type}/{taxonomy}/` But this give me `archive-{custom-post-type}.php` file instead. Following the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) I expect Wordpress to find me the taxonomy template before the archive template. Is there something I am missing ? Thank you for your help.
Thank you WebElaine for your help ! I figured out a way to solve it. It looks a bit as you proposed in **Option 2**. Except that I used the filter **`parse_query`** to change my CPT `'has_archive'` to false when accessing my taxonomy. Here is the code : ``` function check_taxonomy_query( $query ) { if ($query->query['my_project_location'] && !$query->query['my_project']) { $query->is_post_type_archive = false; } } add_action( 'parse_query', 'check_taxonomy_query' ); ``` `my_project_location` and `my_project` are the query vars used for my rewrite rules: ``` $newRules['holliday/?$'] = 'index.php?lang=en&post_type=my_project'; $newRules['holliday/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]'; $newRules['holliday/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]'; $newRules['holliday/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]&my_project=$matches[3]'; ``` So in the `check_taxonomy_query` function, I simply check if I am in the case of the 2nd or 3rd line of my rewrite rules. If yes, I turn the post type archive down. Hope it could help someone ;)
277,724
<p><a href="https://i.stack.imgur.com/Md1Uq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Md1Uq.png" alt="HTTPS ERROR"></a></p> <p>How to fix Mixed content for wordpress plugin and themes, my images already served with https</p> <p>i also test with <a href="https://www.whynopadlock.com/" rel="nofollow noreferrer">https://www.whynopadlock.com/</a></p>
[ { "answer_id": 278029, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>There are a couple of different solutions if you want to have only the /holliday/project-location/ URL and not separate archive and taxonomy URLs.</p>\n\n<p><strong>Option 1:</strong></p>\n\n<p>Use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow noreferrer\"><code>template_include()</code> filter</a>. I think this code would work but have not tested:</p>\n\n<pre><code>add_filter( 'template_include', 'holliday_template', 99 );\n\nfunction holliday_template( $template ) {\n\n if ( is_post_type_archive( 'holliday' ) ) {\n $new_template = locate_template( array( 'taxonomy-my_project_location.php' ) );\n if ( '' != $new_template ) {\n return $new_template;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p><strong>Option 2</strong> (even simpler):</p>\n\n<p>Tell WP not to give your <code>holliday</code> CPT an archive. When you register the post type, just change <code>'has_archive' =&gt; true,</code> to <code>false</code>. That way, when WP looks for content at your desired URL, only the taxonomy archive exists. You will most likely need to use <code>unregister_post_type()</code> and re-register it to force the change.</p>\n" }, { "answer_id": 278092, "author": "jardindeden", "author_id": 116160, "author_profile": "https://wordpress.stackexchange.com/users/116160", "pm_score": 1, "selected": true, "text": "<p>Thank you WebElaine for your help ! I figured out a way to solve it.</p>\n\n<p>It looks a bit as you proposed in <strong>Option 2</strong>. Except that I used the filter <strong><code>parse_query</code></strong> to change my CPT <code>'has_archive'</code> to false when accessing my taxonomy. </p>\n\n<p>Here is the code : </p>\n\n<pre><code>function check_taxonomy_query( $query ) {\n if ($query-&gt;query['my_project_location'] &amp;&amp; !$query-&gt;query['my_project']) {\n $query-&gt;is_post_type_archive = false;\n }\n}\nadd_action( 'parse_query', 'check_taxonomy_query' ); \n</code></pre>\n\n<p><code>my_project_location</code> and <code>my_project</code> are the query vars used for my rewrite rules:</p>\n\n<pre><code>$newRules['holliday/?$'] = 'index.php?lang=en&amp;post_type=my_project';\n$newRules['holliday/([^/]+)/?$'] = 'index.php?lang=en&amp;post_type=my_project&amp;my_project_location=$matches[1]';\n$newRules['holliday/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&amp;post_type=my_project&amp;my_project_location=$matches[1]/$matches[2]';\n$newRules['holliday/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&amp;post_type=my_project&amp;my_project_location=$matches[1]/$matches[2]&amp;my_project=$matches[3]';\n</code></pre>\n\n<p>So in the <code>check_taxonomy_query</code> function, I simply check if I am in the case of the 2nd or 3rd line of my rewrite rules. If yes, I turn the post type archive down.</p>\n\n<p>Hope it could help someone ;)</p>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277724", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117129/" ]
[![HTTPS ERROR](https://i.stack.imgur.com/Md1Uq.png)](https://i.stack.imgur.com/Md1Uq.png) How to fix Mixed content for wordpress plugin and themes, my images already served with https i also test with <https://www.whynopadlock.com/>
Thank you WebElaine for your help ! I figured out a way to solve it. It looks a bit as you proposed in **Option 2**. Except that I used the filter **`parse_query`** to change my CPT `'has_archive'` to false when accessing my taxonomy. Here is the code : ``` function check_taxonomy_query( $query ) { if ($query->query['my_project_location'] && !$query->query['my_project']) { $query->is_post_type_archive = false; } } add_action( 'parse_query', 'check_taxonomy_query' ); ``` `my_project_location` and `my_project` are the query vars used for my rewrite rules: ``` $newRules['holliday/?$'] = 'index.php?lang=en&post_type=my_project'; $newRules['holliday/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]'; $newRules['holliday/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]'; $newRules['holliday/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]&my_project=$matches[3]'; ``` So in the `check_taxonomy_query` function, I simply check if I am in the case of the 2nd or 3rd line of my rewrite rules. If yes, I turn the post type archive down. Hope it could help someone ;)
277,725
<p>I've a Custom Post Type called clock and a taxonomy called clock_category on my website. It is working well and All the clocks can be accessed from the REST endpoint <a href="https://myapp.dev/wp-json/wp/v2/clock" rel="noreferrer">https://myapp.dev/wp-json/wp/v2/clock</a></p> <p>But I don't know how to filter them by the Clock category, say I want to get all the clocks which are made of wood </p> <p>I tried different URLs but none of them seems to be working <a href="https://myapp.dev/wp-json/wp/v2/clock?clock_category=wood" rel="noreferrer">https://myapp.dev/wp-json/wp/v2/clock?clock_category=wood</a> <a href="https://myapp.dev/wp-json/wp/v2/clock?clock_category=10" rel="noreferrer">https://myapp.dev/wp-json/wp/v2/clock?clock_category=10</a></p> <p>and many more. All I got was the full result set.</p> <p>Here is the code</p> <pre><code>&lt;?php add_action( 'init', 'clock' ); function clock() { $labels = array( "name" =&gt; __( 'Clock', 'mywp' ), "singular_name" =&gt; __( 'clock', 'mywp' ), "menu_name" =&gt; __( 'Clock', 'mywp' ), "all_items" =&gt; __( 'All Clock', 'mywp' ), "add_new" =&gt; __( 'Add New Clock', 'mywp' ), "add_new_item" =&gt; __( 'Add New Clock', 'mywp' ), "edit_item" =&gt; __( 'Edit Clock', 'mywp' ), "new_item" =&gt; __( 'New Clock', 'mywp' ), "view_item" =&gt; __( 'View Clock', 'mywp' ), "search_items" =&gt; __( 'Search Clock', 'mywp' ), "not_found" =&gt; __( 'No Clock Found', 'mywp' ), "not_found_in_trash" =&gt; __( 'No Clock found in trash', 'mywp' ), "parent_item_colon" =&gt; __( 'Parent Clock', 'mywp' ), "featured_image" =&gt; __( 'Feature Image for Clock', 'mywp' ), "set_featured_image" =&gt; __( 'Set featured Clock image', 'mywp' ), "remove_featured_image" =&gt; __( 'Remove featured image for Clock', 'mywp' ), "use_featured_image" =&gt; __( 'Use featured image for Clock', 'mywp' ), "archives" =&gt; __( 'Clock archives', 'mywp' ), "insert_into_item" =&gt; __( 'Insert into Clock', 'mywp' ), "uploaded_to_this_item" =&gt; __( 'Uploaded to this Clock', 'mywp' ), "items_list_navigation" =&gt; __( 'Clock list navigation', 'mywp' ), "items_list" =&gt; __( 'Clock List', 'mywp' ), "parent_item_colon" =&gt; __( 'Parent Clock', 'mywp' ), ); $args = array( "label" =&gt; __( 'Clock', 'mywp' ), "labels" =&gt; $labels, "description" =&gt; "Clock", "public" =&gt; true, "publicly_queryable" =&gt; true, "show_ui" =&gt; true, "show_in_rest" =&gt; true, "rest_base" =&gt; "clock", "has_archive" =&gt; false, "show_in_menu" =&gt; true, "exclude_from_search" =&gt; false, "capability_type" =&gt; "post", "map_meta_cap" =&gt; true, "hierarchical" =&gt; false, "rewrite" =&gt; array( "slug" =&gt; "clock", "with_front" =&gt; true ), "query_var" =&gt; true, "supports" =&gt; array( "title", "editor", "thumbnail", "custom-fields", "page-attributes", "post-formats" ), "taxonomies" =&gt; array( ), ); register_post_type( "clock", $args ); </code></pre> <p>}</p> <pre><code>add_action( 'init', 'create_clock_tax' ); function create_clock_tax() { register_taxonomy( 'clock_category', 'clock', array( 'label' =&gt; __( 'Clock Category' ), 'rewrite' =&gt; array( 'slug' =&gt; 'clock_category' ), 'hierarchical' =&gt; true, ) ); } </code></pre> <p>Hope someone help me out on this. I've been trying to solve this for 5 hours and nothing seems to be working.</p>
[ { "answer_id": 277744, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We can check out the <code>/wp/v2/clock</code> endpoint's arguments here:</p>\n\n<pre><code>https://myapp.dev/wp-json/wp/v2/\n</code></pre>\n\n<p>If we add the <code>'show_in_rest' =&gt; true,</code> argument, when registering the custom <code>clock_category</code> taxonomy, it will add a support for this GET/POST argument:</p>\n\n<pre><code>clock_category: {\n required: false,\n default: [ ],\n description: \"Limit result set to all items that have the \n specified term assigned in the clock_category taxonomy.\",\n type: \"array\",\n items: {\n type: \"integer\"\n }\n},\n</code></pre>\n\n<p>and this GET argument:</p>\n\n<pre><code>clock_category_exclude: {\n required: false,\n default: [ ],\n description: \"Limit result set to all items except those that have the \n specified term assigned in the clock_category taxonomy.\",\n type: \"array\",\n items: {\n type: \"integer\"\n }\n}\n</code></pre>\n\n<p>It will also add the <code>/wp/v2/clock_category</code> endpoint.</p>\n\n<p>So to filter the clock posts by a single clock category ID:</p>\n\n<pre><code>https://myapp.dev/wp-json/wp/v2/clock?clock_category=10\n</code></pre>\n\n<p>or by multiple clock category IDs:</p>\n\n<pre><code>https://myapp.dev/wp-json/wp/v2/clock?clock_category=10,11,12\n</code></pre>\n\n<p>To exclude from a single category ID:</p>\n\n<pre><code>https://myapp.dev/wp-json/wp/v2/clock?clock_category_exclude=13\n</code></pre>\n\n<p>or exclude from multiple clock category IDs:</p>\n\n<pre><code>https://myapp.dev/wp-json/wp/v2/clock?clock_category_exclude=13,14\n</code></pre>\n" }, { "answer_id": 360344, "author": "RachieVee", "author_id": 42783, "author_profile": "https://wordpress.stackexchange.com/users/42783", "pm_score": 1, "selected": false, "text": "<p>I know that this is a super old question, but I just ran into the same issue, and perhaps this answer will help someone.</p>\n\n<p>If you want to filter a custom post type by a custom taxonomy through REST, you need to enable it in <strong>both</strong> the <code>register_post_type</code> and <code>register_taxonomy</code> arguments.</p>\n\n<p>I found the answer in the Core Handbook: <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/#registering-a-custom-taxonomy-with-rest-api-support\" rel=\"nofollow noreferrer\">Registering A Custom Taxonomy With REST API Support</a></p>\n\n<p>I was missing these parameters from my <code>register_taxonomy</code> function:</p>\n\n<pre><code> 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'genre' ),\n 'show_in_rest' =&gt; true,\n 'rest_base' =&gt; 'genre',\n 'rest_controller_class' =&gt; 'WP_REST_Terms_Controller',\n</code></pre>\n\n<p>It looks like the person who asked this question, is also missing those arguments in their <code>register_taxonomy</code> function, so it should work once he/she adds that.</p>\n\n<p>The <code>rest_controller_class</code> and <code>rest_base</code> are optional. Once I enabled it in my code, then the endpoint for my custom post type worked. Example url below:</p>\n\n<pre><code>https://localsite.com/wp-json/wp/v2/custom_post_type_name?taxonomy_name=935\n</code></pre>\n\n<p>Note that the \"taxonomy name\" is the name of taxonomy when you register it, not the slug for the taxonomies themselves.</p>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277725", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126346/" ]
I've a Custom Post Type called clock and a taxonomy called clock\_category on my website. It is working well and All the clocks can be accessed from the REST endpoint <https://myapp.dev/wp-json/wp/v2/clock> But I don't know how to filter them by the Clock category, say I want to get all the clocks which are made of wood I tried different URLs but none of them seems to be working <https://myapp.dev/wp-json/wp/v2/clock?clock_category=wood> <https://myapp.dev/wp-json/wp/v2/clock?clock_category=10> and many more. All I got was the full result set. Here is the code ``` <?php add_action( 'init', 'clock' ); function clock() { $labels = array( "name" => __( 'Clock', 'mywp' ), "singular_name" => __( 'clock', 'mywp' ), "menu_name" => __( 'Clock', 'mywp' ), "all_items" => __( 'All Clock', 'mywp' ), "add_new" => __( 'Add New Clock', 'mywp' ), "add_new_item" => __( 'Add New Clock', 'mywp' ), "edit_item" => __( 'Edit Clock', 'mywp' ), "new_item" => __( 'New Clock', 'mywp' ), "view_item" => __( 'View Clock', 'mywp' ), "search_items" => __( 'Search Clock', 'mywp' ), "not_found" => __( 'No Clock Found', 'mywp' ), "not_found_in_trash" => __( 'No Clock found in trash', 'mywp' ), "parent_item_colon" => __( 'Parent Clock', 'mywp' ), "featured_image" => __( 'Feature Image for Clock', 'mywp' ), "set_featured_image" => __( 'Set featured Clock image', 'mywp' ), "remove_featured_image" => __( 'Remove featured image for Clock', 'mywp' ), "use_featured_image" => __( 'Use featured image for Clock', 'mywp' ), "archives" => __( 'Clock archives', 'mywp' ), "insert_into_item" => __( 'Insert into Clock', 'mywp' ), "uploaded_to_this_item" => __( 'Uploaded to this Clock', 'mywp' ), "items_list_navigation" => __( 'Clock list navigation', 'mywp' ), "items_list" => __( 'Clock List', 'mywp' ), "parent_item_colon" => __( 'Parent Clock', 'mywp' ), ); $args = array( "label" => __( 'Clock', 'mywp' ), "labels" => $labels, "description" => "Clock", "public" => true, "publicly_queryable" => true, "show_ui" => true, "show_in_rest" => true, "rest_base" => "clock", "has_archive" => false, "show_in_menu" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "clock", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail", "custom-fields", "page-attributes", "post-formats" ), "taxonomies" => array( ), ); register_post_type( "clock", $args ); ``` } ``` add_action( 'init', 'create_clock_tax' ); function create_clock_tax() { register_taxonomy( 'clock_category', 'clock', array( 'label' => __( 'Clock Category' ), 'rewrite' => array( 'slug' => 'clock_category' ), 'hierarchical' => true, ) ); } ``` Hope someone help me out on this. I've been trying to solve this for 5 hours and nothing seems to be working.
We can check out the `/wp/v2/clock` endpoint's arguments here: ``` https://myapp.dev/wp-json/wp/v2/ ``` If we add the `'show_in_rest' => true,` argument, when registering the custom `clock_category` taxonomy, it will add a support for this GET/POST argument: ``` clock_category: { required: false, default: [ ], description: "Limit result set to all items that have the specified term assigned in the clock_category taxonomy.", type: "array", items: { type: "integer" } }, ``` and this GET argument: ``` clock_category_exclude: { required: false, default: [ ], description: "Limit result set to all items except those that have the specified term assigned in the clock_category taxonomy.", type: "array", items: { type: "integer" } } ``` It will also add the `/wp/v2/clock_category` endpoint. So to filter the clock posts by a single clock category ID: ``` https://myapp.dev/wp-json/wp/v2/clock?clock_category=10 ``` or by multiple clock category IDs: ``` https://myapp.dev/wp-json/wp/v2/clock?clock_category=10,11,12 ``` To exclude from a single category ID: ``` https://myapp.dev/wp-json/wp/v2/clock?clock_category_exclude=13 ``` or exclude from multiple clock category IDs: ``` https://myapp.dev/wp-json/wp/v2/clock?clock_category_exclude=13,14 ```
277,731
<p>I'm creating a custom php/js pages querying and displaying results from a separate non-wordpress DB on a 2nd page. The header and footer will be the same as my theme so I'm calling the theme's footer and header but I haven't figured out why my hook to customize the pages' title aren't working and am asking which hook to use to display my designated title. </p> <p>I don't need to call any content from wordpress besides the theme's header and footer (1 reason why I'm not using a page template). </p> <p>I thought to do </p> <pre><code>require('../wp-blog-header.php'); get_header(); add_filter( 'wp_title', 'mycustom_title', 4); function mycustom_title($teetitle) { $teetitle = 'My Custom Title Here'; return $teetitle; } </code></pre> <p>as described <a href="https://stackoverflow.com/questions/42009768/wordpress-set-custom-title-on-custom-page/42010001#42010001">here</a> and <a href="https://gist.github.com/skorasaurus/d2ea1ad0b0b0de75e7635ed57d0074b3" rel="nofollow noreferrer">(my full php file is here)</a></p> <p>I'm able to call the header using 'get_header' and my header.php file in my theme calls wp_head.</p> <p>At this point, I'm stumped because my hook to wp_title is not firing and is following the default logic of stating 'page not found' for a 404 in general-template.php</p> <p>I thought I could override by issuing a hook immediately after calling get_header in my php file ; <a href="https://stackoverflow.com/questions/9926292/set-custom-page-title-with-hook">https://stackoverflow.com/questions/9926292/set-custom-page-title-with-hook</a> but this is not working. </p> <p>When I issue $echo wp_title in the body later in the same file, wp_title gives me my modified title. </p> <p>I've also tried a couple default different themes (2013, 2012, etc) and the page title is not correct so I think there's something fundamental that I'm missing or that I'm not calling the correct hook. I've also tried placing my hook in my theme's function.php and had the same result. I've also tried using a priority of a 6 digit integer, and still had same result. </p>
[ { "answer_id": 277735, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": -1, "selected": false, "text": "<p>It doesn't work this way.\nYou should load all wordpress environment, than with <code>template_include</code> or <code>template_redirect</code> hooks use your own template with header.</p>\n\n<p>For example:</p>\n\n<pre><code>&lt;?php\n require('../wp-blog-header.php');\n\n add_action('template_include', function() {\n if($some_condition === true) {\n $new_template = locate_template( array( 'portfolio-page-template.php' ) );\n\n return $new_template;\n }\n });\n\n add_filter('wp_title', function($title) {\n return \"new title\";\n })\n</code></pre>\n" }, { "answer_id": 348256, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 1, "selected": true, "text": "<p>I ended up making a page template anyways and inserting the page title when making the post. </p>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48698/" ]
I'm creating a custom php/js pages querying and displaying results from a separate non-wordpress DB on a 2nd page. The header and footer will be the same as my theme so I'm calling the theme's footer and header but I haven't figured out why my hook to customize the pages' title aren't working and am asking which hook to use to display my designated title. I don't need to call any content from wordpress besides the theme's header and footer (1 reason why I'm not using a page template). I thought to do ``` require('../wp-blog-header.php'); get_header(); add_filter( 'wp_title', 'mycustom_title', 4); function mycustom_title($teetitle) { $teetitle = 'My Custom Title Here'; return $teetitle; } ``` as described [here](https://stackoverflow.com/questions/42009768/wordpress-set-custom-title-on-custom-page/42010001#42010001) and [(my full php file is here)](https://gist.github.com/skorasaurus/d2ea1ad0b0b0de75e7635ed57d0074b3) I'm able to call the header using 'get\_header' and my header.php file in my theme calls wp\_head. At this point, I'm stumped because my hook to wp\_title is not firing and is following the default logic of stating 'page not found' for a 404 in general-template.php I thought I could override by issuing a hook immediately after calling get\_header in my php file ; <https://stackoverflow.com/questions/9926292/set-custom-page-title-with-hook> but this is not working. When I issue $echo wp\_title in the body later in the same file, wp\_title gives me my modified title. I've also tried a couple default different themes (2013, 2012, etc) and the page title is not correct so I think there's something fundamental that I'm missing or that I'm not calling the correct hook. I've also tried placing my hook in my theme's function.php and had the same result. I've also tried using a priority of a 6 digit integer, and still had same result.
I ended up making a page template anyways and inserting the page title when making the post.
277,740
<p>I'm using Types plugin to create user metaboxes but it doesn't save. My HTML:</p> <pre><code>&lt;form id="new-user" action="" method="POST" name="new-user" novalidate="" enctype="multipart/form-data"&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="wpcf-nombre-u" id="nombre" placeholder="&lt;?php _e('Nombre', 'wm'); ?&gt;" &gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="wpcf-apellidos-u" id="apellidos" placeholder="&lt;?php _e('Apellidos', 'wm'); ?&gt;" &gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="password" name="wpcf-contrasena-u" id="contrasena" placeholder="&lt;?php _e('Contraseña', 'wm'); ?&gt;" &gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="password" name="wpcf-rep-contrasena-u" id="rep-contrasena" placeholder="&lt;?php _e('Repita contraseña', 'wm'); ?&gt;" &gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="email" name="wpcf-email-u" id="email" placeholder="Email" &gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="checkbox" name="sectores[]" id="sector-nutricion-deportiva" value="nutricion-deportiva"&gt; &lt;label for="sector-nutricion-deportiva"&gt;Nutrición deportiva&lt;/label&gt; &lt;input type="checkbox" name="sectores[]" id="sector-rutinas-de-gimnasio" value="rutinas-de-gimnasio"&gt; &lt;label for="sector-rutinas-de-gimnasio"&gt;Rutinas de gimnasio&lt;/label&gt; &lt;input type="checkbox" name="sectores[]" id="sector-clases-dirigidas" value="clases-dirigidas"&gt; &lt;label for="sector-clases-dirigidas"&gt;Clases dirigidas&lt;/label&gt; &lt;input type="checkbox" name="sectores[]" id="sector-entrenamiento-personal" value="entrenamiento-personal"&gt; &lt;label for="sector-entrenamiento-personal"&gt;Entrenamiento personal&lt;/label&gt; &lt;input type="checkbox" name="sectores[]" id="sector-deportes-de-equipo" value="deportes-de-equipo"&gt; &lt;label for="sector-deportes-de-equipo"&gt;Deportes de equipo&lt;/label&gt; &lt;input type="checkbox" name="sectores[]" id="sector-deportes-individuales" value="deportes-individuales"&gt; &lt;label for="sector-deportes-individuales"&gt;Deportes individuales&lt;/label&gt; &lt;input type="submit" value="¡Registrate ya!" /&gt; &lt;input type="hidden" name="task" value="register" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>PHP:</p> <pre><code>$err = ''; $success = ''; global $wpdb, $PasswordHash, $current_user, $user_ID; if( isset($_POST['task']) &amp;&amp; $_POST['task'] == 'register' ) { $nombre = $wpdb-&gt;escape(trim($_POST['wpcf-nombre-u'])); $apellidos = $wpdb-&gt;escape(trim($_POST['wpcf-apellidos-u'])); $contrasena = $wpdb-&gt;escape(trim($_POST['wpcf-contrasena-u'])); $rep_contrasena = $wpdb-&gt;escape(trim($_POST['wpcf-rep-contrasena-u'])); $email = $wpdb-&gt;escape(trim($_POST['wpcf-email-u'])); if( $email == "" || $contrasena == "" || $rep_contrasena == "" || $username == "" || $nombre == "" || $apellidos == "") { $err = 'Please don\'t leave the required fields.'; } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { $err = 'Invalid email address.'; } else if(email_exists($email) ) { $err = 'Email already exist.'; } else if($contrasena &lt;&gt; $rep_contrasena ){ $err = 'Password do not match.'; } else { $user_id = wp_insert_user( array ( 'first_name' =&gt; apply_filters('pre_user_first_name', $nombre), 'last_name' =&gt; apply_filters('pre_user_last_name', $apellidos), 'user_pass' =&gt; apply_filters('pre_user_user_pass', $contrasena), 'user_login' =&gt; apply_filters('pre_user_user_login', $username), 'user_email' =&gt; apply_filters('pre_user_user_email', $email), 'role' =&gt; 'subscriber' ) ); if( is_wp_error($user_id) ) { $err = 'Error on user creation.'; } else { $success = 'You\'re successfully register'; $sectores = $_POST['sectores']; $count = count($sectores); for($i=0; $i &lt; $count; $i++){ update_user_meta( $user_id, 'wpcf-sectores-de-experiencia-u', $sectores[$i] ); } } } } </code></pre> <p>My types backend is: <a href="https://i.stack.imgur.com/oQ0lR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oQ0lR.png" alt="enter image description here"></a></p>
[ { "answer_id": 277735, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": -1, "selected": false, "text": "<p>It doesn't work this way.\nYou should load all wordpress environment, than with <code>template_include</code> or <code>template_redirect</code> hooks use your own template with header.</p>\n\n<p>For example:</p>\n\n<pre><code>&lt;?php\n require('../wp-blog-header.php');\n\n add_action('template_include', function() {\n if($some_condition === true) {\n $new_template = locate_template( array( 'portfolio-page-template.php' ) );\n\n return $new_template;\n }\n });\n\n add_filter('wp_title', function($title) {\n return \"new title\";\n })\n</code></pre>\n" }, { "answer_id": 348256, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 1, "selected": true, "text": "<p>I ended up making a page template anyways and inserting the page title when making the post. </p>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277740", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126358/" ]
I'm using Types plugin to create user metaboxes but it doesn't save. My HTML: ``` <form id="new-user" action="" method="POST" name="new-user" novalidate="" enctype="multipart/form-data"> <div class="form-group"> <input type="text" name="wpcf-nombre-u" id="nombre" placeholder="<?php _e('Nombre', 'wm'); ?>" > </div> <div class="form-group"> <input type="text" name="wpcf-apellidos-u" id="apellidos" placeholder="<?php _e('Apellidos', 'wm'); ?>" > </div> <div class="form-group"> <input type="password" name="wpcf-contrasena-u" id="contrasena" placeholder="<?php _e('Contraseña', 'wm'); ?>" > </div> <div class="form-group"> <input type="password" name="wpcf-rep-contrasena-u" id="rep-contrasena" placeholder="<?php _e('Repita contraseña', 'wm'); ?>" > </div> <div class="form-group"> <input type="email" name="wpcf-email-u" id="email" placeholder="Email" > </div> <div class="form-group"> <input type="checkbox" name="sectores[]" id="sector-nutricion-deportiva" value="nutricion-deportiva"> <label for="sector-nutricion-deportiva">Nutrición deportiva</label> <input type="checkbox" name="sectores[]" id="sector-rutinas-de-gimnasio" value="rutinas-de-gimnasio"> <label for="sector-rutinas-de-gimnasio">Rutinas de gimnasio</label> <input type="checkbox" name="sectores[]" id="sector-clases-dirigidas" value="clases-dirigidas"> <label for="sector-clases-dirigidas">Clases dirigidas</label> <input type="checkbox" name="sectores[]" id="sector-entrenamiento-personal" value="entrenamiento-personal"> <label for="sector-entrenamiento-personal">Entrenamiento personal</label> <input type="checkbox" name="sectores[]" id="sector-deportes-de-equipo" value="deportes-de-equipo"> <label for="sector-deportes-de-equipo">Deportes de equipo</label> <input type="checkbox" name="sectores[]" id="sector-deportes-individuales" value="deportes-individuales"> <label for="sector-deportes-individuales">Deportes individuales</label> <input type="submit" value="¡Registrate ya!" /> <input type="hidden" name="task" value="register" /> </div> </form> ``` PHP: ``` $err = ''; $success = ''; global $wpdb, $PasswordHash, $current_user, $user_ID; if( isset($_POST['task']) && $_POST['task'] == 'register' ) { $nombre = $wpdb->escape(trim($_POST['wpcf-nombre-u'])); $apellidos = $wpdb->escape(trim($_POST['wpcf-apellidos-u'])); $contrasena = $wpdb->escape(trim($_POST['wpcf-contrasena-u'])); $rep_contrasena = $wpdb->escape(trim($_POST['wpcf-rep-contrasena-u'])); $email = $wpdb->escape(trim($_POST['wpcf-email-u'])); if( $email == "" || $contrasena == "" || $rep_contrasena == "" || $username == "" || $nombre == "" || $apellidos == "") { $err = 'Please don\'t leave the required fields.'; } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { $err = 'Invalid email address.'; } else if(email_exists($email) ) { $err = 'Email already exist.'; } else if($contrasena <> $rep_contrasena ){ $err = 'Password do not match.'; } else { $user_id = wp_insert_user( array ( 'first_name' => apply_filters('pre_user_first_name', $nombre), 'last_name' => apply_filters('pre_user_last_name', $apellidos), 'user_pass' => apply_filters('pre_user_user_pass', $contrasena), 'user_login' => apply_filters('pre_user_user_login', $username), 'user_email' => apply_filters('pre_user_user_email', $email), 'role' => 'subscriber' ) ); if( is_wp_error($user_id) ) { $err = 'Error on user creation.'; } else { $success = 'You\'re successfully register'; $sectores = $_POST['sectores']; $count = count($sectores); for($i=0; $i < $count; $i++){ update_user_meta( $user_id, 'wpcf-sectores-de-experiencia-u', $sectores[$i] ); } } } } ``` My types backend is: [![enter image description here](https://i.stack.imgur.com/oQ0lR.png)](https://i.stack.imgur.com/oQ0lR.png)
I ended up making a page template anyways and inserting the page title when making the post.
277,763
<p>I could see previous –next image option in the default Twenty Sixteen theme even without installation any plugins.</p> <p>But I would like to use Big Blue theme instead of default one and I could not see previous –next image option regardless that I’ve installed different plugins related gallery like Gallery Portfolio, NextGEN Gallery, PB SEO Friendly Images……</p> <p>What need to be done to see previous –next image option in Big Blue or any other (not only default ) themes?</p> <p>Thanks.</p> <p>//Edited //single.php</p> <pre><code>&lt;?php /** * The template for displaying all single posts. * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post * * @package Big Blue */ get_header(); ?&gt; &lt;header class="entry-header article-header &lt;?php if(has_post_thumbnail()){echo 'featured-image'; } ?&gt;"&gt; &lt;?php the_post_thumbnail( 'single-post-thumbnail', array( 'class' =&gt; 'single-post-thumbnail' ) ); ?&gt; &lt;div class="blue-overlay"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;div class="entry-detail"&gt; &lt;?php the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); ?&gt; &lt;?php $tags_list = get_the_tag_list( '', esc_html__( ', ', 'big-blue' ) ); ?&gt; &lt;div class="entry-meta"&gt; &lt;?php big_blue_posted_on(); ?&gt; &lt;/div&gt;&lt;!-- .entry-meta --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;div class="inner-wrapper"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-8"&gt; &lt;?php while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', 'single'); the_post_navigation(); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. ?&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;?php get_sidebar(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;?php get_footer(); </code></pre>
[ { "answer_id": 277735, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": -1, "selected": false, "text": "<p>It doesn't work this way.\nYou should load all wordpress environment, than with <code>template_include</code> or <code>template_redirect</code> hooks use your own template with header.</p>\n\n<p>For example:</p>\n\n<pre><code>&lt;?php\n require('../wp-blog-header.php');\n\n add_action('template_include', function() {\n if($some_condition === true) {\n $new_template = locate_template( array( 'portfolio-page-template.php' ) );\n\n return $new_template;\n }\n });\n\n add_filter('wp_title', function($title) {\n return \"new title\";\n })\n</code></pre>\n" }, { "answer_id": 348256, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 1, "selected": true, "text": "<p>I ended up making a page template anyways and inserting the page title when making the post. </p>\n" } ]
2017/08/22
[ "https://wordpress.stackexchange.com/questions/277763", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126051/" ]
I could see previous –next image option in the default Twenty Sixteen theme even without installation any plugins. But I would like to use Big Blue theme instead of default one and I could not see previous –next image option regardless that I’ve installed different plugins related gallery like Gallery Portfolio, NextGEN Gallery, PB SEO Friendly Images…… What need to be done to see previous –next image option in Big Blue or any other (not only default ) themes? Thanks. //Edited //single.php ``` <?php /** * The template for displaying all single posts. * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post * * @package Big Blue */ get_header(); ?> <header class="entry-header article-header <?php if(has_post_thumbnail()){echo 'featured-image'; } ?>"> <?php the_post_thumbnail( 'single-post-thumbnail', array( 'class' => 'single-post-thumbnail' ) ); ?> <div class="blue-overlay"></div> <div class="container"> <div class="entry-detail"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> <?php $tags_list = get_the_tag_list( '', esc_html__( ', ', 'big-blue' ) ); ?> <div class="entry-meta"> <?php big_blue_posted_on(); ?> </div><!-- .entry-meta --> </div> </div> </header><!-- .entry-header --> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <div class="inner-wrapper"> <div class="container"> <div class="row"> <div class="col-md-8"> <?php while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', 'single'); the_post_navigation(); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. ?> </div> <div class="col-md-4"> <?php get_sidebar(); ?> </div> </div> </div> </div> </main><!-- #main --> </div><!-- #primary --> <?php get_footer(); ```
I ended up making a page template anyways and inserting the page title when making the post.
277,786
<p>I want to try calling the pre-defined functions from the <a href="https://wordpress.org/plugins/front-end-pm/" rel="nofollow noreferrer">front end private messages plugin</a> in my custom template. But It shows that the function does not exist. But that function is working fine in the plugin.</p> <p>What should I do?</p>
[ { "answer_id": 277794, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": -1, "selected": true, "text": "<p>There can be various reason for the undefined function error:</p>\n\n<ul>\n<li><p>The plugin might load its function definitions later than <code>template_include</code> or in the admin backend only.</p></li>\n<li><p>You might have made a syntax error, for example if the plugin is using a <a href=\"http://php.net/manual/en/language.namespaces.php\" rel=\"nofollow noreferrer\">namespace</a>, but you are calling the function without that namespace. Or the function is really a class method, and you treat it as a function …</p></li>\n</ul>\n\n<p>Another question is: Why would you call that function directly? Templates should have as little dependencies as possible. Imagine someone finds a security problem in the plugin, and you have to turn it off. Do you really want to edit all your template files then? Probably not. :)</p>\n\n<p>It is much better to keep that dependency out of the template and call a custom action instead. For example, in your template you can replace the direct call with an action call:</p>\n\n<pre><code>do_action( 'frontend.message' );\n</code></pre>\n\n<p>In your theme's <code>functions.php</code>, you register a callback for that action:</p>\n\n<pre><code>add_action( 'frontend.message', 'my_frontend_message' );\n\nfunction my_frontend_message()\n{\n if ( ! function_exists( 'plugin_frontend_message' ) ) {\n\n // Show debug info for those who can do something about it.\n if ( current_user_can( 'manage_option' ) ) {\n print '&lt;p class=\"error\"&gt;Function plugin_frontend_message() not found.&lt;/p&gt;';\n }\n return;\n }\n\n print plugin_frontend_message();\n}\n</code></pre>\n\n<p>If you turn off the plugin now, nothing bad will happen, your visitors will just see nothing instead of a message.</p>\n" }, { "answer_id": 277796, "author": "Sebastian Kurzynowski", "author_id": 108925, "author_profile": "https://wordpress.stackexchange.com/users/108925", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Check documentation of plugin (to now more about function)</li>\n<li><p>Than check the function if is static You can use</p>\n\n<p><code>ClassName::FunctionName</code></p></li>\n<li><p>If not check if there is global object added by plugin </p>\n\n<p><code>global $plugin_name_object;\n$plugin_name_object-&gt;my_function();</code></p></li>\n<li><p>if not simply create <code>new object</code> of plugin and call this function.</p>\n\n<p><code>obj = new Plugin();\n $obj-&gt;my_function();</code></p></li>\n</ol>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277786", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126392/" ]
I want to try calling the pre-defined functions from the [front end private messages plugin](https://wordpress.org/plugins/front-end-pm/) in my custom template. But It shows that the function does not exist. But that function is working fine in the plugin. What should I do?
There can be various reason for the undefined function error: * The plugin might load its function definitions later than `template_include` or in the admin backend only. * You might have made a syntax error, for example if the plugin is using a [namespace](http://php.net/manual/en/language.namespaces.php), but you are calling the function without that namespace. Or the function is really a class method, and you treat it as a function … Another question is: Why would you call that function directly? Templates should have as little dependencies as possible. Imagine someone finds a security problem in the plugin, and you have to turn it off. Do you really want to edit all your template files then? Probably not. :) It is much better to keep that dependency out of the template and call a custom action instead. For example, in your template you can replace the direct call with an action call: ``` do_action( 'frontend.message' ); ``` In your theme's `functions.php`, you register a callback for that action: ``` add_action( 'frontend.message', 'my_frontend_message' ); function my_frontend_message() { if ( ! function_exists( 'plugin_frontend_message' ) ) { // Show debug info for those who can do something about it. if ( current_user_can( 'manage_option' ) ) { print '<p class="error">Function plugin_frontend_message() not found.</p>'; } return; } print plugin_frontend_message(); } ``` If you turn off the plugin now, nothing bad will happen, your visitors will just see nothing instead of a message.
277,787
<p>I'm trying to Show User List in WordPress Admin in Descending order by "ID" column.</p> <p>I tried below code</p> <pre><code>add_action('pre_user_search', 'change_user_order'); function change_user_order($query) { $query-&gt;query_orderby = ' ORDER BY ID DESC'; } </code></pre> <p>But its not working.</p>
[ { "answer_id": 277789, "author": "Bhagchandani", "author_id": 101627, "author_profile": "https://wordpress.stackexchange.com/users/101627", "pm_score": 0, "selected": false, "text": "<p>As per user @toni_lehtimaki <strong>pre_user_search</strong> is deprecated. Below code is working.</p>\n\n<pre><code>add_action('pre_user_query', 'change_user_order');\n\nfunction change_user_order($query) {\n\n $query-&gt;query_orderby = ' ORDER BY ID DESC';\n}\n</code></pre>\n" }, { "answer_id": 277815, "author": "toni_lehtimaki", "author_id": 47286, "author_profile": "https://wordpress.stackexchange.com/users/47286", "pm_score": 2, "selected": false, "text": "<p>I first thought that <code>pre_user_query</code> would be that hook for the job. But I think using the equivalent of <code>pre_get_posts</code>, which is <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_users/\" rel=\"nofollow noreferrer\"><code>pre_get_users</code></a>, would be suitable here. </p>\n\n<p>You also said you wanted to run this in admin. So we will check that before running this.</p>\n\n<pre><code>function my_custom_order_users_by_id( $query ) {\n\n //Check that we are in admin otherwise return\n if( !is_admin() ) {\n return;\n }\n\n // We are changing the query_vars to reorder\n $query-&gt;query_vars['orderby'] = 'ID';\n $query-&gt;query_vars['order'] = 'DESC';\n\n // We need to remember to return the altered query.\n return $query;\n}\n// Lets apply our function to hook.\nadd_action( 'pre_get_users', 'my_custom_order_users_by_id' );\n</code></pre>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277787", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124611/" ]
I'm trying to Show User List in WordPress Admin in Descending order by "ID" column. I tried below code ``` add_action('pre_user_search', 'change_user_order'); function change_user_order($query) { $query->query_orderby = ' ORDER BY ID DESC'; } ``` But its not working.
I first thought that `pre_user_query` would be that hook for the job. But I think using the equivalent of `pre_get_posts`, which is [`pre_get_users`](https://developer.wordpress.org/reference/hooks/pre_get_users/), would be suitable here. You also said you wanted to run this in admin. So we will check that before running this. ``` function my_custom_order_users_by_id( $query ) { //Check that we are in admin otherwise return if( !is_admin() ) { return; } // We are changing the query_vars to reorder $query->query_vars['orderby'] = 'ID'; $query->query_vars['order'] = 'DESC'; // We need to remember to return the altered query. return $query; } // Lets apply our function to hook. add_action( 'pre_get_users', 'my_custom_order_users_by_id' ); ```
277,804
<p>sorry for my english... So I want to get my data from a https live site back to localhost. Using duplicator plugin works fine exept that I run (especially in Chrome) to a problem with absolute setted image links, wich refer to <a href="https://localhost" rel="nofollow noreferrer">https://localhost</a> ... .</p> <p>I wonder if someone is out there who knows a solution for this issue. </p> <p>Many thanks in advance</p>
[ { "answer_id": 277789, "author": "Bhagchandani", "author_id": 101627, "author_profile": "https://wordpress.stackexchange.com/users/101627", "pm_score": 0, "selected": false, "text": "<p>As per user @toni_lehtimaki <strong>pre_user_search</strong> is deprecated. Below code is working.</p>\n\n<pre><code>add_action('pre_user_query', 'change_user_order');\n\nfunction change_user_order($query) {\n\n $query-&gt;query_orderby = ' ORDER BY ID DESC';\n}\n</code></pre>\n" }, { "answer_id": 277815, "author": "toni_lehtimaki", "author_id": 47286, "author_profile": "https://wordpress.stackexchange.com/users/47286", "pm_score": 2, "selected": false, "text": "<p>I first thought that <code>pre_user_query</code> would be that hook for the job. But I think using the equivalent of <code>pre_get_posts</code>, which is <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_users/\" rel=\"nofollow noreferrer\"><code>pre_get_users</code></a>, would be suitable here. </p>\n\n<p>You also said you wanted to run this in admin. So we will check that before running this.</p>\n\n<pre><code>function my_custom_order_users_by_id( $query ) {\n\n //Check that we are in admin otherwise return\n if( !is_admin() ) {\n return;\n }\n\n // We are changing the query_vars to reorder\n $query-&gt;query_vars['orderby'] = 'ID';\n $query-&gt;query_vars['order'] = 'DESC';\n\n // We need to remember to return the altered query.\n return $query;\n}\n// Lets apply our function to hook.\nadd_action( 'pre_get_users', 'my_custom_order_users_by_id' );\n</code></pre>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107825/" ]
sorry for my english... So I want to get my data from a https live site back to localhost. Using duplicator plugin works fine exept that I run (especially in Chrome) to a problem with absolute setted image links, wich refer to <https://localhost> ... . I wonder if someone is out there who knows a solution for this issue. Many thanks in advance
I first thought that `pre_user_query` would be that hook for the job. But I think using the equivalent of `pre_get_posts`, which is [`pre_get_users`](https://developer.wordpress.org/reference/hooks/pre_get_users/), would be suitable here. You also said you wanted to run this in admin. So we will check that before running this. ``` function my_custom_order_users_by_id( $query ) { //Check that we are in admin otherwise return if( !is_admin() ) { return; } // We are changing the query_vars to reorder $query->query_vars['orderby'] = 'ID'; $query->query_vars['order'] = 'DESC'; // We need to remember to return the altered query. return $query; } // Lets apply our function to hook. add_action( 'pre_get_users', 'my_custom_order_users_by_id' ); ```
277,828
<p>This is a rather simple question, so I'll keep it short.</p> <p>Update1: In this context <code>{page-structure}</code> means just that: <code>page1/page1-1/page1-1-1/{...}</code>.</p> <p>Update2: For further clarification, I want to do about the same <a href="https://www.advancedcustomfields.com/resources/post-object/" rel="nofollow noreferrer">the ACF Post Object field</a> is doing, except I want to do it dynamically based on the URL structure as explained below.</p> <p>I'm making a custom multilingual site, with a dual page structure (with and without <code>/en</code>). Any page at <code>mysite.com/en/{page-structure}</code> are getting its locale changed to <code>en_US</code> and the content (ACF) is fetched from the corresponding page at <code>mysite.com/{page-structure}</code>. Based on the locale different content is displayed.</p> <p>How can I on <code>mysite.com/en/{page-structure}</code> automatically get the $post Object from <code>mysite.com/{page-structure}</code> (i.e. without <code>en/</code>)?</p> <p>(Currently I'm using ACF to fetch fields from the corresponding page by rewriting the field requests, but it I could change the $post Object on the fly, it would make everything a little simpler.)</p>
[ { "answer_id": 277830, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 0, "selected": false, "text": "<p>Use the <code>$global</code> in before your <code>$post</code></p>\n\n<p>For example:</p>\n\n<pre><code>global $post;\necho $post-&gt;ID;\n</code></pre>\n" }, { "answer_id": 277831, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 1, "selected": false, "text": "<p>If I understand correctly the question, the right answer would be to use <a href=\"https://codex.wordpress.org/Function_Reference/url_to_postid\" rel=\"nofollow noreferrer\">url_to_postid</a> function.</p>\n\n<p>Then you can setup post id this way:</p>\n\n<pre><code>global $post; \n$post = get_post($post_id, OBJECT);\nsetup_postdata($post);\n\n// your code\n\nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 277834, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>This is how you can get the post object of a page with a matching path, minus the <code>/en</code> part:</p>\n\n<pre><code>$page_path = get_page_uri( get_queried_object_id() ); // en/page/child-page\n$target_page_path = str_replace( 'en/', '', $page_path ); // page/child-page\n$target_page = get_page_by_path( $target_page_path ); // WP_Post of target page.\n</code></pre>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277828", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59140/" ]
This is a rather simple question, so I'll keep it short. Update1: In this context `{page-structure}` means just that: `page1/page1-1/page1-1-1/{...}`. Update2: For further clarification, I want to do about the same [the ACF Post Object field](https://www.advancedcustomfields.com/resources/post-object/) is doing, except I want to do it dynamically based on the URL structure as explained below. I'm making a custom multilingual site, with a dual page structure (with and without `/en`). Any page at `mysite.com/en/{page-structure}` are getting its locale changed to `en_US` and the content (ACF) is fetched from the corresponding page at `mysite.com/{page-structure}`. Based on the locale different content is displayed. How can I on `mysite.com/en/{page-structure}` automatically get the $post Object from `mysite.com/{page-structure}` (i.e. without `en/`)? (Currently I'm using ACF to fetch fields from the corresponding page by rewriting the field requests, but it I could change the $post Object on the fly, it would make everything a little simpler.)
This is how you can get the post object of a page with a matching path, minus the `/en` part: ``` $page_path = get_page_uri( get_queried_object_id() ); // en/page/child-page $target_page_path = str_replace( 'en/', '', $page_path ); // page/child-page $target_page = get_page_by_path( $target_page_path ); // WP_Post of target page. ```
277,836
<p>I'm trying to make a code to display a image at the end of each post, but i need to show a specific image for each post category. I'm using the code below:</p> <pre><code>&lt;?php if (in_category('category1')||){ echo '&lt;img src="https://example.com/category1"&gt;'; } elseif (in_category('category2')){ echo '&lt;img src="https://example.com/category2"&gt;'; } elseif (in_category('category3')){ echo '&lt;img src="https://example.com/category3"&gt;'; } elseif (in_category('category4')){ echo '&lt;img src="https://example.com/category4"&gt;'; } ?&gt; </code></pre> <p>It's working, but my problem now is that some posts have all the categories, and I need to test the primary category of the post. Is there a function to do this?</p>
[ { "answer_id": 277830, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 0, "selected": false, "text": "<p>Use the <code>$global</code> in before your <code>$post</code></p>\n\n<p>For example:</p>\n\n<pre><code>global $post;\necho $post-&gt;ID;\n</code></pre>\n" }, { "answer_id": 277831, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 1, "selected": false, "text": "<p>If I understand correctly the question, the right answer would be to use <a href=\"https://codex.wordpress.org/Function_Reference/url_to_postid\" rel=\"nofollow noreferrer\">url_to_postid</a> function.</p>\n\n<p>Then you can setup post id this way:</p>\n\n<pre><code>global $post; \n$post = get_post($post_id, OBJECT);\nsetup_postdata($post);\n\n// your code\n\nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 277834, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>This is how you can get the post object of a page with a matching path, minus the <code>/en</code> part:</p>\n\n<pre><code>$page_path = get_page_uri( get_queried_object_id() ); // en/page/child-page\n$target_page_path = str_replace( 'en/', '', $page_path ); // page/child-page\n$target_page = get_page_by_path( $target_page_path ); // WP_Post of target page.\n</code></pre>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126419/" ]
I'm trying to make a code to display a image at the end of each post, but i need to show a specific image for each post category. I'm using the code below: ``` <?php if (in_category('category1')||){ echo '<img src="https://example.com/category1">'; } elseif (in_category('category2')){ echo '<img src="https://example.com/category2">'; } elseif (in_category('category3')){ echo '<img src="https://example.com/category3">'; } elseif (in_category('category4')){ echo '<img src="https://example.com/category4">'; } ?> ``` It's working, but my problem now is that some posts have all the categories, and I need to test the primary category of the post. Is there a function to do this?
This is how you can get the post object of a page with a matching path, minus the `/en` part: ``` $page_path = get_page_uri( get_queried_object_id() ); // en/page/child-page $target_page_path = str_replace( 'en/', '', $page_path ); // page/child-page $target_page = get_page_by_path( $target_page_path ); // WP_Post of target page. ```
277,837
<p><code>$wpdb-&gt;insert()</code> returns <code>false</code> which I've learned means that the insert failed. Now, I would like to know why it fails with the insert.</p> <p>According to this ticket <a href="https://core.trac.wordpress.org/ticket/32315" rel="noreferrer">https://core.trac.wordpress.org/ticket/32315</a> the problem could be that the value is either too long or contains bad characters.</p> <p>Here is the insert query:</p> <pre><code>$result = $wpdb-&gt;insert('table', $ins_args, array('%d', '%d', '%s', '%s', '%s', '%s')); </code></pre> <p>It's difficult to show the <code>$ins_args</code> array values since some values are pretty long. Specially the one for field named <code>value</code>. But I use type <code>longtext</code> for that field. And this insert is used a lot. And most times it works with success. So it really feels like a encoding or size problem.</p> <p>How do I get to know what the problem is? <code>$wpdb-&gt;last_error</code> is empty</p>
[ { "answer_id": 326322, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 4, "selected": false, "text": "<p><code>$wpdb-&gt;insert()</code> method returns <code>false</code> if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1).</p>\n\n<p>You can turn error echoing on and off with the <code>show_errors</code> and <code>hide_errors</code>, respectively.</p>\n\n<pre><code>&lt;?php $wpdb-&gt;show_errors(); ?&gt; \n&lt;?php $wpdb-&gt;hide_errors(); ?&gt; \n</code></pre>\n\n<p>You can also print the error (if any) generated by the most recent query with <code>print_error</code>.</p>\n\n<pre><code>&lt;?php $wpdb-&gt;print_error(); ?&gt; \n</code></pre>\n\n<p>You can also use <code>$last_error</code> field, which will contain the most recent error text generated by MySQL.</p>\n" }, { "answer_id": 373903, "author": "Brian C", "author_id": 18358, "author_profile": "https://wordpress.stackexchange.com/users/18358", "pm_score": 2, "selected": false, "text": "<p>Sadly, <code>wp-db.php</code> returns false with no error, if the data you are trying to write to a column is too long to fit. This becomes a nightmare to debug without explicitly checking each column's length (and it's hard to know the lengths, though wp-db.php does provide internal functions).</p>\n<p>I've created a tiny drop-in override which modifies wpdb behaviour to return an error in this scenario. To install it, you simply copy and paste it into your WordPress wp-content/db.php file. It overrides only a single, short, wpdb method (<code>process_fields()</code>) to add an error message identifying the column that is too long. Note that db.php will survive core upgrades, and you can simply remove the wp-content/db.php file at any time to revert to pure core wpdb.</p>\n<p>Although I use this myself, as usual, test before use and usage is at your own peril.</p>\n<p>The error code is originally taken from an <a href=\"https://wordpress.stackexchange.com/a/331206/18358\">idea by Liam Murphy here</a>.</p>\n<p><a href=\"https://gist.github.com/briancoogan/054cf3afcfb761d59e06020251bcd35c\" rel=\"nofollow noreferrer\">Gist for drop in db.php here</a></p>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277837", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3216/" ]
`$wpdb->insert()` returns `false` which I've learned means that the insert failed. Now, I would like to know why it fails with the insert. According to this ticket <https://core.trac.wordpress.org/ticket/32315> the problem could be that the value is either too long or contains bad characters. Here is the insert query: ``` $result = $wpdb->insert('table', $ins_args, array('%d', '%d', '%s', '%s', '%s', '%s')); ``` It's difficult to show the `$ins_args` array values since some values are pretty long. Specially the one for field named `value`. But I use type `longtext` for that field. And this insert is used a lot. And most times it works with success. So it really feels like a encoding or size problem. How do I get to know what the problem is? `$wpdb->last_error` is empty
`$wpdb->insert()` method returns `false` if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1). You can turn error echoing on and off with the `show_errors` and `hide_errors`, respectively. ``` <?php $wpdb->show_errors(); ?> <?php $wpdb->hide_errors(); ?> ``` You can also print the error (if any) generated by the most recent query with `print_error`. ``` <?php $wpdb->print_error(); ?> ``` You can also use `$last_error` field, which will contain the most recent error text generated by MySQL.
277,841
<p>I want to show all posts like <code>mywebsite.com/postname/1/</code>, <code>mywebsite.com/postname/2/</code> ...... <code>mywebsite.com/postname/7/</code> .. </p> <p>Below code works perfectly for me, the only problem is that it shows only first posts <code>mywebsite.com/postname/</code>... </p> <p>How can I do this? </p> <pre><code>&lt;?php /** * Template Name: Random Post * This template will only display the content you entered in the page editor */ ?&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;?php /* Random Post Picker Use on page to send viewer to random post optionally mod query */ // set arguments for WP_Query on published posts to get 1 at random $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'orderby' =&gt; 'rand', 'order' =&gt; 'DESC', // Using the date_query to filter posts from last week 'date_query' =&gt; array( array( 'after' =&gt; '2 week ago' ) ) ); // It's time! Go someplace random $my_random_post = new WP_Query ( $args ); while ( $my_random_post-&gt;have_posts () ) { $my_random_post-&gt;the_post (); // redirect to the random post wp_redirect ( get_permalink () ); exit; } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 277844, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You don't need to redirect the user to the random post page, and you can't even if you want, because you can't be redirected to multiple places at the same time.</p>\n\n<p>So, simply output your random posts inside your loop:</p>\n\n<pre><code>while ( $my_random_post-&gt;have_posts () ) {\n $my_random_post-&gt;the_post ();\n echo '&lt;a href=\"'.get_the_permalink().'\"&gt;'.get_the_title().'&lt;/a&gt;';\n}\n</code></pre>\n" }, { "answer_id": 277845, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 3, "selected": false, "text": "<p>Only 1 post is displaying on your side because of you are using <code>exit()</code> in your loop. In your code when WP_Query start and loop exit after one counter.\nRemove <code>exit()</code> and use this code:</p>\n\n<pre><code>&lt;?php\n/*\n * Random Post Picker\n * Use on page to send viewer to random post optionally mod query\n */\n\n// set arguments for WP_Query on published posts to get 1 at random\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'rand',\n 'order' =&gt; 'DESC',\n\n // Using the date_query to filter posts from last week\n 'date_query' =&gt; array(\n array(\n 'after' =&gt; '2 week ago'\n )\n )\n);\n\n// It's time! Go someplace random\n$my_random_post = new WP_Query ( $args );\nif($my_random_post-&gt;have_posts()){\n while ( $my_random_post-&gt;have_posts () ) {\n $my_random_post-&gt;the_post ();\n echo '&lt;a href=\"'.get_the_permalink().'\"&gt;'.get_the_title().'&lt;/a&gt;';\n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 277847, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Doing this in PHP is an awful idea:</p>\n\n<ul>\n<li>This page is impossible to cache</li>\n<li>ordering by random is <strong>extremely expensive</strong> to query, involving creating temporary database tables, and scans, as it has to copy the entire posts table, then randomly re-order the posts, then finally do the actual query on the new table before destroying it</li>\n<li>This opens you up to resource exhaustion attacks</li>\n</ul>\n\n<p>For example, this command will ping your random post URL repeatedly. Ran enough times on enough computers, it will bring down your database:</p>\n\n<pre><code>for i in `seq 1 20000`; do curl http://mywebsite.com/postname; done\n</code></pre>\n\n<p>If you're on a cheap shared host, it may be enough to call your URL in several browser tabs at the same time to trigger problems.</p>\n\n<p>Not to mention that your redirect sends out HTTP headers, but the code outputs tags beforehand, so headers have already been sent, breaking things and triggering PHP warnings.</p>\n\n<h2>The Super Fast Easy Alternative</h2>\n\n<p>So instead, do a normal query ordered by data, and output the data as JSON. Then in javascript on the browser, randomly pick one of those posts and do a client side redirect.</p>\n\n<p>This way the page can be cached, your database is protected, and the browser does all the heavy lifting. The database query will be <strong>very</strong> fast in comparison</p>\n\n<p>Now your problem is as simple as outputting a bit of data in a list, randomly picking something from the list in JS, then using <code>window.location= ...</code> to redirect. No WP knowledge necessary</p>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126422/" ]
I want to show all posts like `mywebsite.com/postname/1/`, `mywebsite.com/postname/2/` ...... `mywebsite.com/postname/7/` .. Below code works perfectly for me, the only problem is that it shows only first posts `mywebsite.com/postname/`... How can I do this? ``` <?php /** * Template Name: Random Post * This template will only display the content you entered in the page editor */ ?> <html> <head> </head> <body> <?php /* Random Post Picker Use on page to send viewer to random post optionally mod query */ // set arguments for WP_Query on published posts to get 1 at random $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'rand', 'order' => 'DESC', // Using the date_query to filter posts from last week 'date_query' => array( array( 'after' => '2 week ago' ) ) ); // It's time! Go someplace random $my_random_post = new WP_Query ( $args ); while ( $my_random_post->have_posts () ) { $my_random_post->the_post (); // redirect to the random post wp_redirect ( get_permalink () ); exit; } ?> </body> </html> ```
Only 1 post is displaying on your side because of you are using `exit()` in your loop. In your code when WP\_Query start and loop exit after one counter. Remove `exit()` and use this code: ``` <?php /* * Random Post Picker * Use on page to send viewer to random post optionally mod query */ // set arguments for WP_Query on published posts to get 1 at random $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'rand', 'order' => 'DESC', // Using the date_query to filter posts from last week 'date_query' => array( array( 'after' => '2 week ago' ) ) ); // It's time! Go someplace random $my_random_post = new WP_Query ( $args ); if($my_random_post->have_posts()){ while ( $my_random_post->have_posts () ) { $my_random_post->the_post (); echo '<a href="'.get_the_permalink().'">'.get_the_title().'</a>'; } } ?> ```
277,872
<p>For some reason I am unable to output the custom post type content using the following code. what am I missing here? It works fine for <code>get_the_title</code> yet using <code>get_the_content</code> using same parameters yields nothing.</p> <pre><code>&lt;?php $query = new WP_Query( ['post_type' =&gt; 'testimonials', 'posts_per_page' =&gt; -1 ] ); foreach($query-&gt;get_posts() as $testimonial): $meta = get_post_meta($testimonial-&gt;ID); foreach($meta as &amp;$m){ if(is_array($m)){ $m = $m[0]; } } ?&gt; &lt;div class="content"&gt;&lt;?=get_the_content($testimonial-&gt;ID); ?&gt;&lt;/div&gt; &lt;div class="author"&gt;- &lt;?=get_the_title($testimonial-&gt;ID); ?&gt; / &lt;span class="company_name"&gt;&lt;?=$meta['_testimonial_company_name'] ?&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="link"&gt;&lt;a href="&lt;?=home_url('/testimonials'); ?&gt;" title="View All Testimonials"&gt;View More&lt;/a&gt;&lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre>
[ { "answer_id": 277844, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You don't need to redirect the user to the random post page, and you can't even if you want, because you can't be redirected to multiple places at the same time.</p>\n\n<p>So, simply output your random posts inside your loop:</p>\n\n<pre><code>while ( $my_random_post-&gt;have_posts () ) {\n $my_random_post-&gt;the_post ();\n echo '&lt;a href=\"'.get_the_permalink().'\"&gt;'.get_the_title().'&lt;/a&gt;';\n}\n</code></pre>\n" }, { "answer_id": 277845, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 3, "selected": false, "text": "<p>Only 1 post is displaying on your side because of you are using <code>exit()</code> in your loop. In your code when WP_Query start and loop exit after one counter.\nRemove <code>exit()</code> and use this code:</p>\n\n<pre><code>&lt;?php\n/*\n * Random Post Picker\n * Use on page to send viewer to random post optionally mod query\n */\n\n// set arguments for WP_Query on published posts to get 1 at random\n$args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'rand',\n 'order' =&gt; 'DESC',\n\n // Using the date_query to filter posts from last week\n 'date_query' =&gt; array(\n array(\n 'after' =&gt; '2 week ago'\n )\n )\n);\n\n// It's time! Go someplace random\n$my_random_post = new WP_Query ( $args );\nif($my_random_post-&gt;have_posts()){\n while ( $my_random_post-&gt;have_posts () ) {\n $my_random_post-&gt;the_post ();\n echo '&lt;a href=\"'.get_the_permalink().'\"&gt;'.get_the_title().'&lt;/a&gt;';\n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 277847, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Doing this in PHP is an awful idea:</p>\n\n<ul>\n<li>This page is impossible to cache</li>\n<li>ordering by random is <strong>extremely expensive</strong> to query, involving creating temporary database tables, and scans, as it has to copy the entire posts table, then randomly re-order the posts, then finally do the actual query on the new table before destroying it</li>\n<li>This opens you up to resource exhaustion attacks</li>\n</ul>\n\n<p>For example, this command will ping your random post URL repeatedly. Ran enough times on enough computers, it will bring down your database:</p>\n\n<pre><code>for i in `seq 1 20000`; do curl http://mywebsite.com/postname; done\n</code></pre>\n\n<p>If you're on a cheap shared host, it may be enough to call your URL in several browser tabs at the same time to trigger problems.</p>\n\n<p>Not to mention that your redirect sends out HTTP headers, but the code outputs tags beforehand, so headers have already been sent, breaking things and triggering PHP warnings.</p>\n\n<h2>The Super Fast Easy Alternative</h2>\n\n<p>So instead, do a normal query ordered by data, and output the data as JSON. Then in javascript on the browser, randomly pick one of those posts and do a client side redirect.</p>\n\n<p>This way the page can be cached, your database is protected, and the browser does all the heavy lifting. The database query will be <strong>very</strong> fast in comparison</p>\n\n<p>Now your problem is as simple as outputting a bit of data in a list, randomly picking something from the list in JS, then using <code>window.location= ...</code> to redirect. No WP knowledge necessary</p>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1354/" ]
For some reason I am unable to output the custom post type content using the following code. what am I missing here? It works fine for `get_the_title` yet using `get_the_content` using same parameters yields nothing. ``` <?php $query = new WP_Query( ['post_type' => 'testimonials', 'posts_per_page' => -1 ] ); foreach($query->get_posts() as $testimonial): $meta = get_post_meta($testimonial->ID); foreach($meta as &$m){ if(is_array($m)){ $m = $m[0]; } } ?> <div class="content"><?=get_the_content($testimonial->ID); ?></div> <div class="author">- <?=get_the_title($testimonial->ID); ?> / <span class="company_name"><?=$meta['_testimonial_company_name'] ?></span></div> <div class="link"><a href="<?=home_url('/testimonials'); ?>" title="View All Testimonials">View More</a></div> <?php endforeach; ?> ```
Only 1 post is displaying on your side because of you are using `exit()` in your loop. In your code when WP\_Query start and loop exit after one counter. Remove `exit()` and use this code: ``` <?php /* * Random Post Picker * Use on page to send viewer to random post optionally mod query */ // set arguments for WP_Query on published posts to get 1 at random $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'rand', 'order' => 'DESC', // Using the date_query to filter posts from last week 'date_query' => array( array( 'after' => '2 week ago' ) ) ); // It's time! Go someplace random $my_random_post = new WP_Query ( $args ); if($my_random_post->have_posts()){ while ( $my_random_post->have_posts () ) { $my_random_post->the_post (); echo '<a href="'.get_the_permalink().'">'.get_the_title().'</a>'; } } ?> ```
277,874
<p>I have 2 menus.</p> <ol> <li>Main Navigation</li> <li>Footer Navigation</li> </ol> <p>And 3 locations:</p> <ol> <li>Top Bar Navigation</li> <li>Main Navigation</li> <li>Footer Navigation</li> </ol> <p>If I try to create a new menu, wp displays <strong>error</strong></p> <pre><code>A name is required for this term. </code></pre> <p>Obviously I am giving a name in <code>Menu Name</code> textbox... Is this a bug?<br /> Is there a limit to WP menus?<br /> How can I go about adding another menu to use on an existing page as submenu within the page itself?<br /> Thanx</p> <p><strong>EDIT 1</strong><br /> Do I need to add:</p> <pre><code>function register_shop_submenu() { register_nav_menu('shop-submenu',__( 'Shop Sub Menu' )); } add_action( 'init', 'register_shop_submenu' ); </code></pre> <p>to <code>functions.php</code>?<br /> Is that it??<br /> The admin button option exists in vain??</p> <p><strong>EDIT 2</strong><br /> The code above just added a new location.<br /> While <code>Manage Locations</code> tab on <code>admin panel</code> now displays:</p> <blockquote> <p>Your theme supports 4 menus. Select which menu appears in each location.</p> </blockquote> <p>Clicking the <code>use new menu</code> next to the <code>drop-down</code> of this new location yields same error....<br /> rrrrrrrrrrrrrrr</p>
[ { "answer_id": 279647, "author": "mperrin", "author_id": 127640, "author_profile": "https://wordpress.stackexchange.com/users/127640", "pm_score": 2, "selected": true, "text": "<p>I got the same issue and found that the plugin <code>user-activity-log</code> was at the origin of the problem.</p>\n\n<p>As I reported <a href=\"https://wordpress.org/support/topic/cant-create-new-menus-a-name-is-required-for-this-term\" rel=\"nofollow noreferrer\">here</a>,the problem is related to the hooks:</p>\n\n<ul>\n<li>ual_shook_created_term</li>\n<li>ual_shook_edited_term</li>\n<li>ual_shook_delete_term</li>\n</ul>\n\n<p>They return nothing instead of the given term when the taxonomy is ‘nav_menu’.</p>\n\n<p>If you don't use this plugin, check the others plugins that call for example the <code>pre_insert_term</code> filter. They should return something.</p>\n" }, { "answer_id": 312604, "author": "arku", "author_id": 149478, "author_profile": "https://wordpress.stackexchange.com/users/149478", "pm_score": 0, "selected": false, "text": "<p>In my case, it was related to qTranslateX plugin. Just select default language in your Admin Panel, it would save normally. If you will select non-default - you will get same error 'A name is required for this term.'</p>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277874", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52581/" ]
I have 2 menus. 1. Main Navigation 2. Footer Navigation And 3 locations: 1. Top Bar Navigation 2. Main Navigation 3. Footer Navigation If I try to create a new menu, wp displays **error** ``` A name is required for this term. ``` Obviously I am giving a name in `Menu Name` textbox... Is this a bug? Is there a limit to WP menus? How can I go about adding another menu to use on an existing page as submenu within the page itself? Thanx **EDIT 1** Do I need to add: ``` function register_shop_submenu() { register_nav_menu('shop-submenu',__( 'Shop Sub Menu' )); } add_action( 'init', 'register_shop_submenu' ); ``` to `functions.php`? Is that it?? The admin button option exists in vain?? **EDIT 2** The code above just added a new location. While `Manage Locations` tab on `admin panel` now displays: > > Your theme supports 4 menus. Select which menu appears in each > location. > > > Clicking the `use new menu` next to the `drop-down` of this new location yields same error.... rrrrrrrrrrrrrrr
I got the same issue and found that the plugin `user-activity-log` was at the origin of the problem. As I reported [here](https://wordpress.org/support/topic/cant-create-new-menus-a-name-is-required-for-this-term),the problem is related to the hooks: * ual\_shook\_created\_term * ual\_shook\_edited\_term * ual\_shook\_delete\_term They return nothing instead of the given term when the taxonomy is ‘nav\_menu’. If you don't use this plugin, check the others plugins that call for example the `pre_insert_term` filter. They should return something.
277,883
<p>The theme I am using has a function to embed videos from Facebook. The problem is that whenever I use it it loads the SDK in <code>uk_UA</code> for whatever reasons (Ukrainian).</p> <p>Nothing related to my Website or Facebook is using this language. After contacting the theme developers i was told it's not their fault and <em>might</em> be something related to the server configuration.</p> <p>I tried an hacky solution I found here with adding to the <em>funcitons.php</em> the following script</p> <pre><code>add_filter( 'the_content', 'facebook_sdk_replace' ); function facebook_sdk_replace( $content ) { if ( is_single() ) { $content = str_replace("/uk_UA/", "/en_US/", $content); } return $content; } </code></pre> <p>As it had no effect, the developer suggested I should add to the _header_php the following</p> <pre><code>&lt;div id="fb-root"&gt;&lt;/div&gt; &lt;script&gt;(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&amp;version=v2.6"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));&lt;/script&gt; </code></pre> <p>The problem I am facing is that by doing so, I am getting the following error:</p> <p><em>Cannot modify header information - headers already sent by...</em></p> <p>Therefore, I reverted back my <em>header.php</em>. Is there a way to fix this issue without altering the header?</p> <p>Later edit: The only code snippet I found is the following:</p> <pre><code> /* $buffy = ' &lt;div class="wpb_video_wrapper td-facebook-video"&gt; &lt;iframe src="' . td_global::$http_or_https . '://www.facebook.com/plugins/video.php?href=' . urlencode($videoUrl) . '&amp;show_text=0" width="' . $width . '" height="' . $height . '" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true" &gt;&lt;/iframe&gt; &lt;/div&gt; '; */ /** * cache &amp; oembed implementation */ $cache_key = self::get_facebook_id($videoUrl); $group = 'td_facebook_video'; if (td_remote_cache::is_expired($group, $cache_key) === true) { // cache is expired - do a request $facebook_api_json = td_remote_http::get_page('https://www.facebook.com/plugins/video/oembed.json/?url=' . urlencode($videoUrl) , __CLASS__); if ($facebook_api_json !== false) { $facebook_api = @json_decode($facebook_api_json); //json data decode if ($facebook_api === null and json_last_error() !== JSON_ERROR_NONE) { td_log::log(__FILE__, __FUNCTION__, 'json decode failed for facebook video embed api', $videoUrl); } if (is_object($facebook_api) and !empty($facebook_api-&gt;html)) { //add the html to the buffer $buffy = '&lt;div class="wpb_video_wrapper"&gt;' . $facebook_api-&gt;html . '&lt;/div&gt;'; //set the cache td_remote_cache::set($group, $cache_key, $facebook_api-&gt;html, self::$caching_time); } } else { td_log::log(__FILE__, __FUNCTION__, 'facebook api html data cannot be retrieved/json request failed', $videoUrl); } } else { // cache is valid $api_html_embed_data = td_remote_cache::get($group, $cache_key); $buffy = '&lt;div class="wpb_video_wrapper"&gt;' . $api_html_embed_data . '&lt;/div&gt;'; } break; </code></pre>
[ { "answer_id": 277955, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 1, "selected": false, "text": "<p>I've found your problem.</p>\n\n<p>You've inserted video from facebook on your page with facebook init script.</p>\n\n<p><a href=\"https://i.stack.imgur.com/A14QJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A14QJ.png\" alt=\"Take a look at language options\"></a></p>\n\n<p>Find the place where you insert this video and change uk_UA to en_US there.</p>\n" }, { "answer_id": 282865, "author": "Erythros", "author_id": 112590, "author_profile": "https://wordpress.stackexchange.com/users/112590", "pm_score": 1, "selected": true, "text": "<p>The reason for this issue was given on the <a href=\"https://core.trac.wordpress.org/ticket/40656\" rel=\"nofollow noreferrer\">wordpress core ticketing system</a>.</p>\n\n<blockquote>\n <p>This is probably something you should report to Facebook (good luck),\n as WordPress is correctly outputting the lang attribute on the html\n element. Facebook likely uses heuristics to determine if the actual\n page language is indeed English or not when en_US is used, similar to\n what Google Chrome does. This is the unfortunate situation that the\n web finds itself in when services cannot trust web standards due to\n incorrect implementations (ie. sites not in US English but still using\n en_US as the lang). In your situation you may be able to make use of\n the og:locale OpenGraph tag to persuade Facebook that your content\n really is in US English.</p>\n</blockquote>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112590/" ]
The theme I am using has a function to embed videos from Facebook. The problem is that whenever I use it it loads the SDK in `uk_UA` for whatever reasons (Ukrainian). Nothing related to my Website or Facebook is using this language. After contacting the theme developers i was told it's not their fault and *might* be something related to the server configuration. I tried an hacky solution I found here with adding to the *funcitons.php* the following script ``` add_filter( 'the_content', 'facebook_sdk_replace' ); function facebook_sdk_replace( $content ) { if ( is_single() ) { $content = str_replace("/uk_UA/", "/en_US/", $content); } return $content; } ``` As it had no effect, the developer suggested I should add to the \_header\_php the following ``` <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> ``` The problem I am facing is that by doing so, I am getting the following error: *Cannot modify header information - headers already sent by...* Therefore, I reverted back my *header.php*. Is there a way to fix this issue without altering the header? Later edit: The only code snippet I found is the following: ``` /* $buffy = ' <div class="wpb_video_wrapper td-facebook-video"> <iframe src="' . td_global::$http_or_https . '://www.facebook.com/plugins/video.php?href=' . urlencode($videoUrl) . '&show_text=0" width="' . $width . '" height="' . $height . '" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true" ></iframe> </div> '; */ /** * cache & oembed implementation */ $cache_key = self::get_facebook_id($videoUrl); $group = 'td_facebook_video'; if (td_remote_cache::is_expired($group, $cache_key) === true) { // cache is expired - do a request $facebook_api_json = td_remote_http::get_page('https://www.facebook.com/plugins/video/oembed.json/?url=' . urlencode($videoUrl) , __CLASS__); if ($facebook_api_json !== false) { $facebook_api = @json_decode($facebook_api_json); //json data decode if ($facebook_api === null and json_last_error() !== JSON_ERROR_NONE) { td_log::log(__FILE__, __FUNCTION__, 'json decode failed for facebook video embed api', $videoUrl); } if (is_object($facebook_api) and !empty($facebook_api->html)) { //add the html to the buffer $buffy = '<div class="wpb_video_wrapper">' . $facebook_api->html . '</div>'; //set the cache td_remote_cache::set($group, $cache_key, $facebook_api->html, self::$caching_time); } } else { td_log::log(__FILE__, __FUNCTION__, 'facebook api html data cannot be retrieved/json request failed', $videoUrl); } } else { // cache is valid $api_html_embed_data = td_remote_cache::get($group, $cache_key); $buffy = '<div class="wpb_video_wrapper">' . $api_html_embed_data . '</div>'; } break; ```
The reason for this issue was given on the [wordpress core ticketing system](https://core.trac.wordpress.org/ticket/40656). > > This is probably something you should report to Facebook (good luck), > as WordPress is correctly outputting the lang attribute on the html > element. Facebook likely uses heuristics to determine if the actual > page language is indeed English or not when en\_US is used, similar to > what Google Chrome does. This is the unfortunate situation that the > web finds itself in when services cannot trust web standards due to > incorrect implementations (ie. sites not in US English but still using > en\_US as the lang). In your situation you may be able to make use of > the og:locale OpenGraph tag to persuade Facebook that your content > really is in US English. > > >
277,894
<p>I would like to insert a full-width DIV at the topmost location in the site I'm building. The project is in overtime. All the other work is done, but I have been asked to add a small logo and a single link on top. This would be on all pages, so it's a modification to the header. I've looked at several plugins, but they seem to be creating a "notification bar" by positioning and z-index. The theme we're using is Velux, a child of Primer. </p>
[ { "answer_id": 277895, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Take a look at this question, and the first answer: <a href=\"https://wordpress.stackexchange.com/questions/219931/insert-html-just-after-body-tag\">Insert HTML just after &lt;body&gt; tag</a> </p>\n\n<p>You will have to modify <code>header.php</code> in the theme, since there aren't (normally, although perhaps in your theme) any hooks/filters available to output directly after the <code>&lt;body&gt;</code> tag. </p>\n\n<p>If not your own maintained theme, then a Child Theme is best, as you don't want to have your changes overwritten on a theme update.</p>\n" }, { "answer_id": 277896, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 2, "selected": true, "text": "<p>As I can see in <a href=\"https://github.com/godaddy/wp-primer-theme/blob/develop/header.php\" rel=\"nofollow noreferrer\">wp-primer-theme sources</a>: there are <code>do_action( 'primer_body' );</code> on the top of content and <code>do_action( 'primer_before_header' );</code> just below.</p>\n\n<p>You can update your child theme functions.php with your own action</p>\n\n<pre><code>add_action('primer_before_header', function() {\n echo '&lt;div class=\"logo\"&gt;&lt;/div&gt;';\n});\n</code></pre>\n" } ]
2017/08/23
[ "https://wordpress.stackexchange.com/questions/277894", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121627/" ]
I would like to insert a full-width DIV at the topmost location in the site I'm building. The project is in overtime. All the other work is done, but I have been asked to add a small logo and a single link on top. This would be on all pages, so it's a modification to the header. I've looked at several plugins, but they seem to be creating a "notification bar" by positioning and z-index. The theme we're using is Velux, a child of Primer.
As I can see in [wp-primer-theme sources](https://github.com/godaddy/wp-primer-theme/blob/develop/header.php): there are `do_action( 'primer_body' );` on the top of content and `do_action( 'primer_before_header' );` just below. You can update your child theme functions.php with your own action ``` add_action('primer_before_header', function() { echo '<div class="logo"></div>'; }); ```
277,910
<p>I have a single-site Wordpress installed on example.com. The DNS is configured so that www.example.com is an ALIAS of example.com. The client wants the user to see www. on their nav bar if they entered it, so this is important.</p> <p>I hosted their website on an apache server running cpanel. The cpanel has the domain set as example.com. Before I installed wordpress, typing www.example.com brought up the directory and kept the www. on the nav bar, so great.</p> <p>After I installed wordpress though, the www. is getting removed. When I did a redirect trace I found this odd 302 redirect:</p> <pre><code>http://www.example.com Status: 302 Found Code: 302 Date: Thu, 24 Aug 2017 00:23:08 GMT Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Location: https://example.com Content-Length: 346 Connection: close Content-Type: text/html; charset=iso-8859-1 </code></pre> <p>I modified wordpress's htaccess file to force ssl, but I thought this is a 301:</p> <pre><code>SSLOptions +StrictRequire SSLRequireSSL SSLRequire %{HTTP_HOST} eq "example.com" ErrorDocument 403 https://example.com </code></pre> <p>Okay, whatever. So I removed this section of code, the URL bar is still not preserving the www. This time I get a 301 redirect:</p> <pre><code>http://www.example.com Status: 301 Moved Permanently Code: 301 Date: Thu, 24 Aug 2017 00:35:22 GMT Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 X-Powered-By: PHP/5.6.16 Location: http://example.com/ Content-Length: 0 Connection: close Content-Type: text/html; charset=UTF-8 </code></pre> <p>I don't know where else to look. What do I need to do in cpanel, htaccess, or wordpress to have the URL bar preserve the www.</p>
[ { "answer_id": 277947, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 2, "selected": true, "text": "<p>You need to set the canonical hostname (ie. with <code>www</code>) in the WordPress dashboard... Under Settings > General and set the appropriate \"WordPress Address (URL)\" and \"Site Address (URL)\" properties.</p>\n\n<p>Alternatively, these values can be <em>hardcoded</em> in <code>wp_config.php</code> by defining the <code>WP_HOME</code> and <code>WP_SITEURL</code> constants respectively.</p>\n\n<p>Reference:<br>\n<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<blockquote>\n<pre><code>SSLOptions +StrictRequire\nSSLRequireSSL\nSSLRequire %{HTTP_HOST} eq \"example.com\"\nErrorDocument 403 https://example.com\n</code></pre>\n</blockquote>\n\n<p>Bit of an aside, but this is a very roundabout (not recommended) way of <em>redirecting</em> to HTTPS. Yes, this will trigger a 302 (temporary), not a 301 (permanent) redirect. This only redirects at all because of a side effect of <code>ErrorDocument</code>. And it only redirects to the document root, the requested URL is lost.</p>\n\n<p>This code actually blocks access to the HTTP-only site and triggers a 403 Forbidden. Because you have set an absolute URL as the 2nd argument to the custom 403, Apache triggers an external (302) redirect to the URL, the root of your site.</p>\n\n<p>If you don't have access to the server config, then this redirect is normally achieved using mod_rewrite in <code>.htaccess</code>. For example:</p>\n\n<pre><code>RewriteCond %{HTTPS} !on\nRewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>This would need to go <em>before</em> the existing WordPress directives in <code>.htaccess</code>.</p>\n\n<hr>\n\n<p>Once you have set the appropriate hostname within WordPress, you can handle both HTTPS and www redirection in <code>.htaccess</code> if you wish (it would be slightly more efficient). For example:</p>\n\n<pre><code>RewriteCond %{HTTPS} !on [OR]\nRewriteCond %{HTTP_HOST} !www\\.\nRewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>Make sure you clear your browser cache before testing.</p>\n\n<hr>\n\n<blockquote>\n <p>I need the www. preserved only if the user entered it to begin with.</p>\n</blockquote>\n\n<p>Unless you have a specific reason to do this, then this is generally a bad idea. It potentially creates <em>duplicate content</em>, although you can set a <code>rel=\"canonical\"</code> tag in the <code>head</code> section to alleviate this, and you can specify a preference in Google Search Console (to avoid both hosts being indexed). But the stats will be split between them. How are you setting cookies? If you want cookies shared between both www and non-www (login, sessions, etc.), you'll need to ensure that cookies are set on the apex domain, regardless of which host is accessed - I don't believe this is the default behaviour.</p>\n\n<p>Anyway, if you want to redirect HTTP to HTTPS but preserve whatever host has been accessed (www, non-www or xyz alias) then this is a much simpler redirect as you can reference the <code>HTTP_HOST</code> server variable. For example:</p>\n\n<pre><code>RewriteCond %{HTTPS} !on\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n</code></pre>\n" }, { "answer_id": 278048, "author": "Kumar", "author_id": 126470, "author_profile": "https://wordpress.stackexchange.com/users/126470", "pm_score": 0, "selected": false, "text": "<p>Changing the canonical hostname in wordpress means that now all traffic becomes www. In this particular use case, only if the user comes in as www. traffic should they continue to see www urls. Otherwise, they should just see example.com, just as they entered it. After doing some more research, I found that a way to do this is to add the following lines to wp_config.php.</p>\n\n<pre><code>define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST']);\ndefine('WP_HOME', 'http://' . $_SERVER['HTTP_HOST']);\n</code></pre>\n\n<p>My understanding of this code is that any url declared as an alias to example.com in both the DNS and Cpanel will be shown the wordpress site with the urls preserved. </p>\n\n<p>To piggyback on MrWhite's SSL advice, I modified his code slightly to accommodate the fact that two URLs (with and without www) need to be allowed:</p>\n\n<pre><code># Force SSL While Preserving www.#\nRewriteCond %{HTTPS} !on\nRewriteCond %{HTTP_HOST} www\\.\nRewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]\n\n# Force SSL for non-www. Traffic #\nRewriteCond %{HTTPS} !on\nRewriteCond %{HTTP_HOST} !www\\.\nRewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>If a third or fourth etc alias needs to be added the RewriteCond will need to be made more specific and additional Rewrite blocks will be needed.</p>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/277910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126470/" ]
I have a single-site Wordpress installed on example.com. The DNS is configured so that www.example.com is an ALIAS of example.com. The client wants the user to see www. on their nav bar if they entered it, so this is important. I hosted their website on an apache server running cpanel. The cpanel has the domain set as example.com. Before I installed wordpress, typing www.example.com brought up the directory and kept the www. on the nav bar, so great. After I installed wordpress though, the www. is getting removed. When I did a redirect trace I found this odd 302 redirect: ``` http://www.example.com Status: 302 Found Code: 302 Date: Thu, 24 Aug 2017 00:23:08 GMT Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Location: https://example.com Content-Length: 346 Connection: close Content-Type: text/html; charset=iso-8859-1 ``` I modified wordpress's htaccess file to force ssl, but I thought this is a 301: ``` SSLOptions +StrictRequire SSLRequireSSL SSLRequire %{HTTP_HOST} eq "example.com" ErrorDocument 403 https://example.com ``` Okay, whatever. So I removed this section of code, the URL bar is still not preserving the www. This time I get a 301 redirect: ``` http://www.example.com Status: 301 Moved Permanently Code: 301 Date: Thu, 24 Aug 2017 00:35:22 GMT Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 X-Powered-By: PHP/5.6.16 Location: http://example.com/ Content-Length: 0 Connection: close Content-Type: text/html; charset=UTF-8 ``` I don't know where else to look. What do I need to do in cpanel, htaccess, or wordpress to have the URL bar preserve the www.
You need to set the canonical hostname (ie. with `www`) in the WordPress dashboard... Under Settings > General and set the appropriate "WordPress Address (URL)" and "Site Address (URL)" properties. Alternatively, these values can be *hardcoded* in `wp_config.php` by defining the `WP_HOME` and `WP_SITEURL` constants respectively. Reference: <https://codex.wordpress.org/Changing_The_Site_URL> > > > ``` > SSLOptions +StrictRequire > SSLRequireSSL > SSLRequire %{HTTP_HOST} eq "example.com" > ErrorDocument 403 https://example.com > > ``` > > Bit of an aside, but this is a very roundabout (not recommended) way of *redirecting* to HTTPS. Yes, this will trigger a 302 (temporary), not a 301 (permanent) redirect. This only redirects at all because of a side effect of `ErrorDocument`. And it only redirects to the document root, the requested URL is lost. This code actually blocks access to the HTTP-only site and triggers a 403 Forbidden. Because you have set an absolute URL as the 2nd argument to the custom 403, Apache triggers an external (302) redirect to the URL, the root of your site. If you don't have access to the server config, then this redirect is normally achieved using mod\_rewrite in `.htaccess`. For example: ``` RewriteCond %{HTTPS} !on RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L] ``` This would need to go *before* the existing WordPress directives in `.htaccess`. --- Once you have set the appropriate hostname within WordPress, you can handle both HTTPS and www redirection in `.htaccess` if you wish (it would be slightly more efficient). For example: ``` RewriteCond %{HTTPS} !on [OR] RewriteCond %{HTTP_HOST} !www\. RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L] ``` Make sure you clear your browser cache before testing. --- > > I need the www. preserved only if the user entered it to begin with. > > > Unless you have a specific reason to do this, then this is generally a bad idea. It potentially creates *duplicate content*, although you can set a `rel="canonical"` tag in the `head` section to alleviate this, and you can specify a preference in Google Search Console (to avoid both hosts being indexed). But the stats will be split between them. How are you setting cookies? If you want cookies shared between both www and non-www (login, sessions, etc.), you'll need to ensure that cookies are set on the apex domain, regardless of which host is accessed - I don't believe this is the default behaviour. Anyway, if you want to redirect HTTP to HTTPS but preserve whatever host has been accessed (www, non-www or xyz alias) then this is a much simpler redirect as you can reference the `HTTP_HOST` server variable. For example: ``` RewriteCond %{HTTPS} !on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] ```
277,928
<p>I haven't been able to find this on google and I thought this was a common requirement.</p> <p>Is there a way to add a 5 stars (or whatever rating) to my products with a single plugin or PHP code? I need to show stars in every catalog so I can test my design.</p>
[ { "answer_id": 277935, "author": "Nikola Miljković", "author_id": 111583, "author_profile": "https://wordpress.stackexchange.com/users/111583", "pm_score": 2, "selected": false, "text": "<p>Since you need it just for visual purposes, it's better if you don't save the rating value to the database, but instead to just modify the value during runtime:</p>\n\n<pre><code>/**\n * Modifies WooCommerce product rating to force a defined value\n * \n * @return string Modified rating html\n */\nfunction wpse_get_modified_rating_html(){\n /** @var float Rating being shown */\n $rating = 5;\n /** @var int Total number of ratings */\n $count = 1;\n\n $html = '&lt;div class=\"star-rating\"&gt;';\n $html .= wc_get_star_rating_html( $rating, $count );\n $html .= '&lt;/div&gt;';\n\n return $html;\n}\nadd_filter( 'woocommerce_product_get_rating_html', 'wc_get_rating_html' );\n</code></pre>\n\n<p>You can add that code to your theme's <code>functions.php</code> or you could create a new plugin for that purpose.</p>\n\n<p>Remember to remove the code on production server, since it will force all ratings to show 5 stars!</p>\n" }, { "answer_id": 277950, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/users/111583/nikola-miljkovi%C4%87\">@Nikola</a>'s <a href=\"https://wordpress.stackexchange.com/a/277935/43098\">answer</a> gives you what you want to need without saving anything to the database. If <strong>you</strong> need to save the values to the database and directly execute SQL, you can do the following.</p>\n\n<p>Basically WooCommerce stores product reviews data as a postmeta under <a href=\"https://github.com/woocommerce/woocommerce/blob/bdba4f76362c3b3646c775c10e87f32dd062a25c/includes/data-stores/class-wc-product-data-store-cpt.php#L52-L54\" rel=\"noreferrer\">meta keys</a></p>\n\n<ul>\n<li>_wc_rating_count</li>\n<li>_wc_average_rating</li>\n<li>_wc_review_count</li>\n</ul>\n\n\n\n<pre><code>UPDATE fs_postmeta SET meta_value = 5\nWHERE meta_key = '_wc_average_rating' AND post_id = 564;\n\nUPDATE fs_postmeta SET meta_value = 105 \nWHERE meta_key = '_wc_review_count' AND post_id = 564;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: BK\nVersion: 0.0.1\n*/\n\nfunction bk_get_all_products( ) {\n\n $ps = new WP_Query( array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; '-1'\n ) );\n $arr = array();\n while($ps-&gt;have_posts()){\n $ps-&gt;the_post();\n $arr[] = get_the_ID();\n }\n return $arr;\n}\n\nadd_action('init','bk');\nfunction bk(){\n $products = bk_get_all_products();\n // $re = array(\n // \"1\" =&gt; 1,\n // \"2\" =&gt; 2,\n // \"3\" =&gt; 3,\n // \"4\" =&gt; 5,\n // \"5\" =&gt; 6,\n // );\n foreach ($products as $key =&gt; $value) {\n update_post_meta( $value, '_wc_average_rating', 1 );\n update_post_meta( $value, '_wc_review_count', 15 );\n // update_post_meta( $value, '_wc_rating_count', $re );\n }\n}\n</code></pre>\n\n<p>Remember with this we are not changing the reviews list that appears under product tabs.</p>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/277928", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126489/" ]
I haven't been able to find this on google and I thought this was a common requirement. Is there a way to add a 5 stars (or whatever rating) to my products with a single plugin or PHP code? I need to show stars in every catalog so I can test my design.
[@Nikola](https://wordpress.stackexchange.com/users/111583/nikola-miljkovi%C4%87)'s [answer](https://wordpress.stackexchange.com/a/277935/43098) gives you what you want to need without saving anything to the database. If **you** need to save the values to the database and directly execute SQL, you can do the following. Basically WooCommerce stores product reviews data as a postmeta under [meta keys](https://github.com/woocommerce/woocommerce/blob/bdba4f76362c3b3646c775c10e87f32dd062a25c/includes/data-stores/class-wc-product-data-store-cpt.php#L52-L54) * \_wc\_rating\_count * \_wc\_average\_rating * \_wc\_review\_count ``` UPDATE fs_postmeta SET meta_value = 5 WHERE meta_key = '_wc_average_rating' AND post_id = 564; UPDATE fs_postmeta SET meta_value = 105 WHERE meta_key = '_wc_review_count' AND post_id = 564; ``` or ``` <?php /* Plugin Name: BK Version: 0.0.1 */ function bk_get_all_products( ) { $ps = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => '-1' ) ); $arr = array(); while($ps->have_posts()){ $ps->the_post(); $arr[] = get_the_ID(); } return $arr; } add_action('init','bk'); function bk(){ $products = bk_get_all_products(); // $re = array( // "1" => 1, // "2" => 2, // "3" => 3, // "4" => 5, // "5" => 6, // ); foreach ($products as $key => $value) { update_post_meta( $value, '_wc_average_rating', 1 ); update_post_meta( $value, '_wc_review_count', 15 ); // update_post_meta( $value, '_wc_rating_count', $re ); } } ``` Remember with this we are not changing the reviews list that appears under product tabs.
277,939
<p>I have to run a php function for around 10 minutes. Now I am sheduling the job as a wp-cron-job. But it is getting timed out after 30seconds which is the maximum execution time for php. How to get rid of this timeout issue?</p>
[ { "answer_id": 277935, "author": "Nikola Miljković", "author_id": 111583, "author_profile": "https://wordpress.stackexchange.com/users/111583", "pm_score": 2, "selected": false, "text": "<p>Since you need it just for visual purposes, it's better if you don't save the rating value to the database, but instead to just modify the value during runtime:</p>\n\n<pre><code>/**\n * Modifies WooCommerce product rating to force a defined value\n * \n * @return string Modified rating html\n */\nfunction wpse_get_modified_rating_html(){\n /** @var float Rating being shown */\n $rating = 5;\n /** @var int Total number of ratings */\n $count = 1;\n\n $html = '&lt;div class=\"star-rating\"&gt;';\n $html .= wc_get_star_rating_html( $rating, $count );\n $html .= '&lt;/div&gt;';\n\n return $html;\n}\nadd_filter( 'woocommerce_product_get_rating_html', 'wc_get_rating_html' );\n</code></pre>\n\n<p>You can add that code to your theme's <code>functions.php</code> or you could create a new plugin for that purpose.</p>\n\n<p>Remember to remove the code on production server, since it will force all ratings to show 5 stars!</p>\n" }, { "answer_id": 277950, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/users/111583/nikola-miljkovi%C4%87\">@Nikola</a>'s <a href=\"https://wordpress.stackexchange.com/a/277935/43098\">answer</a> gives you what you want to need without saving anything to the database. If <strong>you</strong> need to save the values to the database and directly execute SQL, you can do the following.</p>\n\n<p>Basically WooCommerce stores product reviews data as a postmeta under <a href=\"https://github.com/woocommerce/woocommerce/blob/bdba4f76362c3b3646c775c10e87f32dd062a25c/includes/data-stores/class-wc-product-data-store-cpt.php#L52-L54\" rel=\"noreferrer\">meta keys</a></p>\n\n<ul>\n<li>_wc_rating_count</li>\n<li>_wc_average_rating</li>\n<li>_wc_review_count</li>\n</ul>\n\n\n\n<pre><code>UPDATE fs_postmeta SET meta_value = 5\nWHERE meta_key = '_wc_average_rating' AND post_id = 564;\n\nUPDATE fs_postmeta SET meta_value = 105 \nWHERE meta_key = '_wc_review_count' AND post_id = 564;\n</code></pre>\n\n<p>or </p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: BK\nVersion: 0.0.1\n*/\n\nfunction bk_get_all_products( ) {\n\n $ps = new WP_Query( array(\n 'post_type' =&gt; 'product',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; '-1'\n ) );\n $arr = array();\n while($ps-&gt;have_posts()){\n $ps-&gt;the_post();\n $arr[] = get_the_ID();\n }\n return $arr;\n}\n\nadd_action('init','bk');\nfunction bk(){\n $products = bk_get_all_products();\n // $re = array(\n // \"1\" =&gt; 1,\n // \"2\" =&gt; 2,\n // \"3\" =&gt; 3,\n // \"4\" =&gt; 5,\n // \"5\" =&gt; 6,\n // );\n foreach ($products as $key =&gt; $value) {\n update_post_meta( $value, '_wc_average_rating', 1 );\n update_post_meta( $value, '_wc_review_count', 15 );\n // update_post_meta( $value, '_wc_rating_count', $re );\n }\n}\n</code></pre>\n\n<p>Remember with this we are not changing the reviews list that appears under product tabs.</p>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/277939", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119861/" ]
I have to run a php function for around 10 minutes. Now I am sheduling the job as a wp-cron-job. But it is getting timed out after 30seconds which is the maximum execution time for php. How to get rid of this timeout issue?
[@Nikola](https://wordpress.stackexchange.com/users/111583/nikola-miljkovi%C4%87)'s [answer](https://wordpress.stackexchange.com/a/277935/43098) gives you what you want to need without saving anything to the database. If **you** need to save the values to the database and directly execute SQL, you can do the following. Basically WooCommerce stores product reviews data as a postmeta under [meta keys](https://github.com/woocommerce/woocommerce/blob/bdba4f76362c3b3646c775c10e87f32dd062a25c/includes/data-stores/class-wc-product-data-store-cpt.php#L52-L54) * \_wc\_rating\_count * \_wc\_average\_rating * \_wc\_review\_count ``` UPDATE fs_postmeta SET meta_value = 5 WHERE meta_key = '_wc_average_rating' AND post_id = 564; UPDATE fs_postmeta SET meta_value = 105 WHERE meta_key = '_wc_review_count' AND post_id = 564; ``` or ``` <?php /* Plugin Name: BK Version: 0.0.1 */ function bk_get_all_products( ) { $ps = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => '-1' ) ); $arr = array(); while($ps->have_posts()){ $ps->the_post(); $arr[] = get_the_ID(); } return $arr; } add_action('init','bk'); function bk(){ $products = bk_get_all_products(); // $re = array( // "1" => 1, // "2" => 2, // "3" => 3, // "4" => 5, // "5" => 6, // ); foreach ($products as $key => $value) { update_post_meta( $value, '_wc_average_rating', 1 ); update_post_meta( $value, '_wc_review_count', 15 ); // update_post_meta( $value, '_wc_rating_count', $re ); } } ``` Remember with this we are not changing the reviews list that appears under product tabs.
277,943
<p>I can't get any 'category' loops to load.</p> <p>Here is my work flow.</p> <p>I create a page called category.php and placed the following code (exactly like this):</p> <pre><code>&lt;?php /* * Template Name: Category */ if (!defined('ABSPATH')) exit; // Exit if accessed directly get_header(); ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;h1 class="entry-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;div class="entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;?php endwhile; // end of the loop. ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I then created a page called 'Category' in the WP Admin and then selected the template for category.php and nothing - zero.</p> <p>Why wouldn't this load posts that belong to the relevant category?</p> <p>Thanks for all help with this...</p>
[ { "answer_id": 277949, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You don't assign category templates to pages. They are templates that will be used <em>automatically</em> when you view a category.</p>\n\n<p>Read the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> documentation. You're using WordPress completely wrong. You don't create pages for archives, they exist automatically.</p>\n" }, { "answer_id": 277958, "author": "Henry", "author_id": 93691, "author_profile": "https://wordpress.stackexchange.com/users/93691", "pm_score": -1, "selected": false, "text": "<p>I know what went wrong: I had added categories to my pages (with functions.php code). Now I have to connect the categories to display with the archive template. I don't have an opportunity to test my theory but I'm sure it is that </p>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/277943", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
I can't get any 'category' loops to load. Here is my work flow. I create a page called category.php and placed the following code (exactly like this): ``` <?php /* * Template Name: Category */ if (!defined('ABSPATH')) exit; // Exit if accessed directly get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-content"> <?php the_content(); ?> <?php endwhile; // end of the loop. ?> <?php get_footer(); ?> ``` I then created a page called 'Category' in the WP Admin and then selected the template for category.php and nothing - zero. Why wouldn't this load posts that belong to the relevant category? Thanks for all help with this...
You don't assign category templates to pages. They are templates that will be used *automatically* when you view a category. Read the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) documentation. You're using WordPress completely wrong. You don't create pages for archives, they exist automatically.
277,953
<p>I'm trying to add a custom field of event_month when a post is published or saved. I'm using the save_post action and getting the contents of a custom field containing the date and trying to store this in a separate custom field with just the month. This works perfectly when saving a post that has already been created. I've shown my code below.</p> <pre><code>add_action('save_post', 'update_event_date'); function update_event_date($post_id){ $post_type = get_post_type($post_id); $event_datee = get_post_meta($post_id, '_EventStartDate', true); if ($post_type == 'tribe_events'){ $month = date("m",strtotime($event_datee)); update_post_meta($post_id, 'event_month', $month); } } </code></pre> <p>The problem arises when creating a new post. I think this is because the action fires before the <code>_EventStartDate</code> meta has been created and therefore the month can't be taken from this.</p> <p>The hook is firing correctly and as intended when saving/updating a post but doesn't correctly get the month from the meta when creating a new post.</p> <p>I'd really appreciate it if someone could provide me with some guidance.</p>
[ { "answer_id": 277954, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>Use <code>pre_post_update</code> instead of <code>save_post</code></p>\n\n<p>Full explanation <a href=\"https://wordpress.stackexchange.com/a/91185/126253\">here</a></p>\n" }, { "answer_id": 277993, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated\" rel=\"nofollow noreferrer\"><code>post_updated</code></a> action, if you want to access the post's data <em>after</em> it's been published. This hook passes the post's ID, inundated post object, and updated post object.</p>\n\n<pre><code>add_action( 'post_updated', 'update_event_date', 10, 3 );\nfunction update_event_date( $post_id, $post_after, $post_before ){\n\n $post_type = get_post_type( $post_id );\n $event_datee = get_post_meta( $post_id, '_EventStartDate', true );\n\n if ( $post_type == 'tribe_events' ) {\n\n $month = date( \"m\",strtotime( $event_datee ) );\n update_post_meta( $post_id, 'event_month', $month );\n\n }\n\n}\n</code></pre>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/277953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118170/" ]
I'm trying to add a custom field of event\_month when a post is published or saved. I'm using the save\_post action and getting the contents of a custom field containing the date and trying to store this in a separate custom field with just the month. This works perfectly when saving a post that has already been created. I've shown my code below. ``` add_action('save_post', 'update_event_date'); function update_event_date($post_id){ $post_type = get_post_type($post_id); $event_datee = get_post_meta($post_id, '_EventStartDate', true); if ($post_type == 'tribe_events'){ $month = date("m",strtotime($event_datee)); update_post_meta($post_id, 'event_month', $month); } } ``` The problem arises when creating a new post. I think this is because the action fires before the `_EventStartDate` meta has been created and therefore the month can't be taken from this. The hook is firing correctly and as intended when saving/updating a post but doesn't correctly get the month from the meta when creating a new post. I'd really appreciate it if someone could provide me with some guidance.
You can hook into [`post_updated`](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) action, if you want to access the post's data *after* it's been published. This hook passes the post's ID, inundated post object, and updated post object. ``` add_action( 'post_updated', 'update_event_date', 10, 3 ); function update_event_date( $post_id, $post_after, $post_before ){ $post_type = get_post_type( $post_id ); $event_datee = get_post_meta( $post_id, '_EventStartDate', true ); if ( $post_type == 'tribe_events' ) { $month = date( "m",strtotime( $event_datee ) ); update_post_meta( $post_id, 'event_month', $month ); } } ```
277,956
<p>I am using shortcode and in that I want to change the title by setting the value from the database using custom tables.I have tried using the_title filter as follows </p> <pre><code>add_filter('the_title','set_page_title', 10, 2); function set_page_title($title, $id){ if(in_the_loop()) { return 'sdfdsfdsf'; } return $title; } </code></pre> <p>But my problem is I want to change this only on a specific page not all page.</p> <p>This is my shortcode callback function </p> <pre><code>function bmg_company_detail_shortcode($args, $content) { global $wpdb; $table_name = $wpdb-&gt;prefix . 'bmg_company'; $company_id = $_GET['id']; $output = ''; $result = $wpdb-&gt;get_results($wpdb-&gt;prepare("SELECT id,maincategoryid,name,website,yearfounded,supportpageurl,contactpage,country,about, isactive,contact_name,contact_email,contact_phone,support_phone,open_times,support_email, username, password from $table_name where id=%s", $company_id)); if($result) { foreach($result as $row) { set_page_title('',$row-&gt;name); $output = ' &lt;h3 class="bmg-company-title"&gt;'. $row-&gt;name .'&lt;/h3&gt; '; } } return $output; } </code></pre> <p>I want to send the parameter to the function set_page_title but that doesn't work. I want this to happen only on page called company.</p>
[ { "answer_id": 277954, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>Use <code>pre_post_update</code> instead of <code>save_post</code></p>\n\n<p>Full explanation <a href=\"https://wordpress.stackexchange.com/a/91185/126253\">here</a></p>\n" }, { "answer_id": 277993, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated\" rel=\"nofollow noreferrer\"><code>post_updated</code></a> action, if you want to access the post's data <em>after</em> it's been published. This hook passes the post's ID, inundated post object, and updated post object.</p>\n\n<pre><code>add_action( 'post_updated', 'update_event_date', 10, 3 );\nfunction update_event_date( $post_id, $post_after, $post_before ){\n\n $post_type = get_post_type( $post_id );\n $event_datee = get_post_meta( $post_id, '_EventStartDate', true );\n\n if ( $post_type == 'tribe_events' ) {\n\n $month = date( \"m\",strtotime( $event_datee ) );\n update_post_meta( $post_id, 'event_month', $month );\n\n }\n\n}\n</code></pre>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/277956", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123210/" ]
I am using shortcode and in that I want to change the title by setting the value from the database using custom tables.I have tried using the\_title filter as follows ``` add_filter('the_title','set_page_title', 10, 2); function set_page_title($title, $id){ if(in_the_loop()) { return 'sdfdsfdsf'; } return $title; } ``` But my problem is I want to change this only on a specific page not all page. This is my shortcode callback function ``` function bmg_company_detail_shortcode($args, $content) { global $wpdb; $table_name = $wpdb->prefix . 'bmg_company'; $company_id = $_GET['id']; $output = ''; $result = $wpdb->get_results($wpdb->prepare("SELECT id,maincategoryid,name,website,yearfounded,supportpageurl,contactpage,country,about, isactive,contact_name,contact_email,contact_phone,support_phone,open_times,support_email, username, password from $table_name where id=%s", $company_id)); if($result) { foreach($result as $row) { set_page_title('',$row->name); $output = ' <h3 class="bmg-company-title">'. $row->name .'</h3> '; } } return $output; } ``` I want to send the parameter to the function set\_page\_title but that doesn't work. I want this to happen only on page called company.
You can hook into [`post_updated`](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) action, if you want to access the post's data *after* it's been published. This hook passes the post's ID, inundated post object, and updated post object. ``` add_action( 'post_updated', 'update_event_date', 10, 3 ); function update_event_date( $post_id, $post_after, $post_before ){ $post_type = get_post_type( $post_id ); $event_datee = get_post_meta( $post_id, '_EventStartDate', true ); if ( $post_type == 'tribe_events' ) { $month = date( "m",strtotime( $event_datee ) ); update_post_meta( $post_id, 'event_month', $month ); } } ```
278,015
<p>I am using the Zephyr theme for my site, but want to switch to a child theme as this seems to be recommended in case the theme is updated. I am worried I will lose my customization etc. </p> <p>Are there any safeguards against this?</p>
[ { "answer_id": 277954, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>Use <code>pre_post_update</code> instead of <code>save_post</code></p>\n\n<p>Full explanation <a href=\"https://wordpress.stackexchange.com/a/91185/126253\">here</a></p>\n" }, { "answer_id": 277993, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated\" rel=\"nofollow noreferrer\"><code>post_updated</code></a> action, if you want to access the post's data <em>after</em> it's been published. This hook passes the post's ID, inundated post object, and updated post object.</p>\n\n<pre><code>add_action( 'post_updated', 'update_event_date', 10, 3 );\nfunction update_event_date( $post_id, $post_after, $post_before ){\n\n $post_type = get_post_type( $post_id );\n $event_datee = get_post_meta( $post_id, '_EventStartDate', true );\n\n if ( $post_type == 'tribe_events' ) {\n\n $month = date( \"m\",strtotime( $event_datee ) );\n update_post_meta( $post_id, 'event_month', $month );\n\n }\n\n}\n</code></pre>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/278015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126536/" ]
I am using the Zephyr theme for my site, but want to switch to a child theme as this seems to be recommended in case the theme is updated. I am worried I will lose my customization etc. Are there any safeguards against this?
You can hook into [`post_updated`](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) action, if you want to access the post's data *after* it's been published. This hook passes the post's ID, inundated post object, and updated post object. ``` add_action( 'post_updated', 'update_event_date', 10, 3 ); function update_event_date( $post_id, $post_after, $post_before ){ $post_type = get_post_type( $post_id ); $event_datee = get_post_meta( $post_id, '_EventStartDate', true ); if ( $post_type == 'tribe_events' ) { $month = date( "m",strtotime( $event_datee ) ); update_post_meta( $post_id, 'event_month', $month ); } } ```
278,035
<p>I have a quite extensive database, 30000+ items, and using this:</p> <pre><code>$args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'books', 's' =&gt; $s ); $post_counts = count(get_posts($args)); </code></pre> <p>seems to take forever.</p> <pre><code>I solved this particular case with: $post_count = $wpdb-&gt;get_var("SELECT COUNT(*) FROM $wpdb-&gt;posts WHERE post_type = 'books' AND post_status = 'publish' AND post_title LIKE '%".$s."%'"); </code></pre> <p>But I have many queries that I'd like to count without having to write them by hand. Is there any way to count the posts with the $args using wordpress native functions without having to store the whole querie but only the count?</p>
[ { "answer_id": 278036, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>There is <code>$wpdb-&gt;num_rows</code> parameter. \nBut I suggest you do it with </p>\n\n<pre><code>$wpdb-&gt;get_var(\"SELECT COUNT(*) ... )\n</code></pre>\n\n<p>This should be much faster if I am not mistaken. It's related to mysql internal functions.</p>\n\n<blockquote>When doing COUNT, the server will only allocate memory to store the result of the count.</blockquote>\n\n<blockquote>When using mysql_num_rows, the server will process the entire result set, allocate memory for all those results</blockquote>\n" }, { "answer_id": 278046, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>Here's one thing you could do. Create a WP_Query object but only include ids:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'books',\n 's' =&gt; $s,\n 'fields' =&gt; 'ids',\n);\n\n$query = new WP_Query( $args );\n$post_counts = $query-&gt;post_count;\nwp_reset_postdata();\n</code></pre>\n\n<p>By using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter\" rel=\"nofollow noreferrer\"><code>fields =&gt; ids</code></a> you're only returning the IDs. Also, WP_Query already does a count and supplies it as a property: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\"><code>post_count</code></a>. Finally, since we are using a WP_Query we need to reset the globals with <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a>.</p>\n" }, { "answer_id": 278050, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>When <code>WP_Query</code> generates a SQL query with <code>SQL_CALC_FOUND_ROWS</code> and a <code>LIMIT</code> clause: </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS ... FROM ... WHERE ... LIMIT ...\n</code></pre>\n\n<p>then the total number of rows:</p>\n\n<pre><code>SELECT FOUND_ROWS();\n</code></pre>\n\n<p>is available from the <code>found_posts</code> property of <code>WP_Query</code>.</p>\n\n<hr>\n\n<p>This means we can fetch a single post with:</p>\n\n<pre><code>'posts_per_page' =&gt; 1 // not -1\n</code></pre>\n\n<p>and get the total count from</p>\n\n<pre><code>$total = $query-&gt;found_posts;\n</code></pre>\n\n<p>where <code>$query</code> is the <code>WP_Query</code> object.</p>\n\n<hr>\n\n<p>From the MySQL <a href=\"https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_found-rows\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>FOUND_ROWS(): </p>\n \n <p>For a SELECT with a LIMIT clause, the number of rows that would be\n returned were there no LIMIT clause</p>\n</blockquote>\n\n<p>It's also informative to look at <a href=\"https://developer.wordpress.org/reference/classes/wp_query/set_found_posts/\" rel=\"nofollow noreferrer\"><code>WP_Query::set_found_posts()</code></a> to see how the <code>found_posts</code> property is constructed.</p>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/278035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116224/" ]
I have a quite extensive database, 30000+ items, and using this: ``` $args = array( 'posts_per_page' => -1, 'post_type' => 'books', 's' => $s ); $post_counts = count(get_posts($args)); ``` seems to take forever. ``` I solved this particular case with: $post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'books' AND post_status = 'publish' AND post_title LIKE '%".$s."%'"); ``` But I have many queries that I'd like to count without having to write them by hand. Is there any way to count the posts with the $args using wordpress native functions without having to store the whole querie but only the count?
Here's one thing you could do. Create a WP\_Query object but only include ids: ``` $args = array( 'posts_per_page' => -1, 'post_type' => 'books', 's' => $s, 'fields' => 'ids', ); $query = new WP_Query( $args ); $post_counts = $query->post_count; wp_reset_postdata(); ``` By using [`fields => ids`](https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter) you're only returning the IDs. Also, WP\_Query already does a count and supplies it as a property: [`post_count`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties). Finally, since we are using a WP\_Query we need to reset the globals with [`wp_reset_postdata()`](https://codex.wordpress.org/Function_Reference/wp_reset_postdata).
278,051
<p>I have been trying to figure out how to add session variables to WordPress Custom Pages for the past few days but have still been unable to find a solution. From researching it seems WordPress does not allow you to move Session variables from one page to the next. I have tried removing all of the 'session_start();' from each page and adding the below to functions.php file.</p> <pre><code>add_action('init', 'myStartSession', 1); function myStartSession() { if(!session_id()) { session_start(); } } </code></pre> <p>Have also tried adding code below to the wp-config.php but to no avail.</p> <pre><code>if (!session_id()) session_start(); </code></pre> <p>The session will create a unique id for each user which will be checked on the next page to see if it equals the previous id. The first page code is as follows:</p> <pre><code>$_SESSION['t'] = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1'); session_write_close(); </code></pre> <p>The next page is:</p> <pre><code>$testValue = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1'); if ($testValue == $_SESSION['t']) {$passFlag = 1;} else {$passFlag = 0;} session_regenerate_id(); </code></pre> <p>'session_write_close();' is called further down on this page. Any help would be greatly appreciated and if you need any further information please don't hesitate to message. Thanks.</p>
[ { "answer_id": 278036, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 0, "selected": false, "text": "<p>There is <code>$wpdb-&gt;num_rows</code> parameter. \nBut I suggest you do it with </p>\n\n<pre><code>$wpdb-&gt;get_var(\"SELECT COUNT(*) ... )\n</code></pre>\n\n<p>This should be much faster if I am not mistaken. It's related to mysql internal functions.</p>\n\n<blockquote>When doing COUNT, the server will only allocate memory to store the result of the count.</blockquote>\n\n<blockquote>When using mysql_num_rows, the server will process the entire result set, allocate memory for all those results</blockquote>\n" }, { "answer_id": 278046, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>Here's one thing you could do. Create a WP_Query object but only include ids:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'books',\n 's' =&gt; $s,\n 'fields' =&gt; 'ids',\n);\n\n$query = new WP_Query( $args );\n$post_counts = $query-&gt;post_count;\nwp_reset_postdata();\n</code></pre>\n\n<p>By using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter\" rel=\"nofollow noreferrer\"><code>fields =&gt; ids</code></a> you're only returning the IDs. Also, WP_Query already does a count and supplies it as a property: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\"><code>post_count</code></a>. Finally, since we are using a WP_Query we need to reset the globals with <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a>.</p>\n" }, { "answer_id": 278050, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>When <code>WP_Query</code> generates a SQL query with <code>SQL_CALC_FOUND_ROWS</code> and a <code>LIMIT</code> clause: </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS ... FROM ... WHERE ... LIMIT ...\n</code></pre>\n\n<p>then the total number of rows:</p>\n\n<pre><code>SELECT FOUND_ROWS();\n</code></pre>\n\n<p>is available from the <code>found_posts</code> property of <code>WP_Query</code>.</p>\n\n<hr>\n\n<p>This means we can fetch a single post with:</p>\n\n<pre><code>'posts_per_page' =&gt; 1 // not -1\n</code></pre>\n\n<p>and get the total count from</p>\n\n<pre><code>$total = $query-&gt;found_posts;\n</code></pre>\n\n<p>where <code>$query</code> is the <code>WP_Query</code> object.</p>\n\n<hr>\n\n<p>From the MySQL <a href=\"https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_found-rows\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>FOUND_ROWS(): </p>\n \n <p>For a SELECT with a LIMIT clause, the number of rows that would be\n returned were there no LIMIT clause</p>\n</blockquote>\n\n<p>It's also informative to look at <a href=\"https://developer.wordpress.org/reference/classes/wp_query/set_found_posts/\" rel=\"nofollow noreferrer\"><code>WP_Query::set_found_posts()</code></a> to see how the <code>found_posts</code> property is constructed.</p>\n" } ]
2017/08/24
[ "https://wordpress.stackexchange.com/questions/278051", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126550/" ]
I have been trying to figure out how to add session variables to WordPress Custom Pages for the past few days but have still been unable to find a solution. From researching it seems WordPress does not allow you to move Session variables from one page to the next. I have tried removing all of the 'session\_start();' from each page and adding the below to functions.php file. ``` add_action('init', 'myStartSession', 1); function myStartSession() { if(!session_id()) { session_start(); } } ``` Have also tried adding code below to the wp-config.php but to no avail. ``` if (!session_id()) session_start(); ``` The session will create a unique id for each user which will be checked on the next page to see if it equals the previous id. The first page code is as follows: ``` $_SESSION['t'] = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1'); session_write_close(); ``` The next page is: ``` $testValue = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1'); if ($testValue == $_SESSION['t']) {$passFlag = 1;} else {$passFlag = 0;} session_regenerate_id(); ``` 'session\_write\_close();' is called further down on this page. Any help would be greatly appreciated and if you need any further information please don't hesitate to message. Thanks.
Here's one thing you could do. Create a WP\_Query object but only include ids: ``` $args = array( 'posts_per_page' => -1, 'post_type' => 'books', 's' => $s, 'fields' => 'ids', ); $query = new WP_Query( $args ); $post_counts = $query->post_count; wp_reset_postdata(); ``` By using [`fields => ids`](https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter) you're only returning the IDs. Also, WP\_Query already does a count and supplies it as a property: [`post_count`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties). Finally, since we are using a WP\_Query we need to reset the globals with [`wp_reset_postdata()`](https://codex.wordpress.org/Function_Reference/wp_reset_postdata).
278,076
<p>I would like to display the last 3 articles of category 'camping-camping' with a shortcode but the function does not seem valid, an idea ?</p> <pre><code>function derniers_articles_camping() { // the query $the_query = new WP_Query( array( 'category_name' =&gt; 'location-camping-var', 'posts_per_page' =&gt; 3, )); if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $contenu = ' </code></pre> <p></p> <pre><code>&lt;div class="effect-jazz"&gt;'.the_post_thumbnail();.'&lt;div class="jazz-try"&gt; &lt;div class="h3"&gt;&lt;a href="'.the_permalink();.'"&gt;'.the_title();.'&lt;/a&gt;&lt;/div&gt; &lt;p&gt;'the_resume(60);.'&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <pre><code> '; endwhile; wp_reset_postdata(); return $contenu; endif; } add_shortcode('camping', 'derniers_articles_camping'); </code></pre> <p>Thank you in advance for your help !</p>
[ { "answer_id": 278070, "author": "Atul", "author_id": 126565, "author_profile": "https://wordpress.stackexchange.com/users/126565", "pm_score": -1, "selected": false, "text": "<p>If there are only few images which are required for the plugin itself then store it under plugins own image folder. If you are making something else; where user will upload its own data then safely use uploads folder.</p>\n" }, { "answer_id": 278072, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>The only directory in which you have guaranteed write access is the uploads directory. Even your plugin's directory might be write protected, the same for <code>wp-content</code> (which doesn't even have to exist). </p>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278076", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109045/" ]
I would like to display the last 3 articles of category 'camping-camping' with a shortcode but the function does not seem valid, an idea ? ``` function derniers_articles_camping() { // the query $the_query = new WP_Query( array( 'category_name' => 'location-camping-var', 'posts_per_page' => 3, )); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); $contenu = ' ``` ``` <div class="effect-jazz">'.the_post_thumbnail();.'<div class="jazz-try"> <div class="h3"><a href="'.the_permalink();.'">'.the_title();.'</a></div> <p>'the_resume(60);.'</p> </div> </div> ``` ``` '; endwhile; wp_reset_postdata(); return $contenu; endif; } add_shortcode('camping', 'derniers_articles_camping'); ``` Thank you in advance for your help !
The only directory in which you have guaranteed write access is the uploads directory. Even your plugin's directory might be write protected, the same for `wp-content` (which doesn't even have to exist).
278,078
<p>Probably a silly one but hopefully someone has encountered this before.</p> <h2>The problem:</h2> <p>I have a local copy of my Wordpress site that works fine and a copy on the server. After uploading I get <code>Call to undefined function</code> from within the child theme's <code>header.php</code> referencing a function that should exist in its parent theme.</p> <h2>Full error message:</h2> <pre><code>Fatal error: Call to undefined function shapely_get_header_logo() in /home/twimp/training.twimp.co.uk/wp-content/themes/shapely-child/header.php on line 33 </code></pre> <h2>Background:</h2> <p>The server has recently had a Wordpress site running on it fine so I don't have particular reason to think its anything related to its configuration.</p> <p>I'm using a different theme from the last time it was uploaded so I started by uploading these two directories, my child theme and its parent. A lot of changes had been made with the plugins so I cleared the plugins directory and re-uploaded everything.</p> <p>I also completely wiped the database and imported from local and then modified the options table to put the correct server url back in.</p> <p>wp_config has not been touched and so it still points at the right database.</p> <h2>What I've tried:</h2> <p>I initially thought that maybe a file or two hadn't uploaded so I checked the FTP server side by side, starting with the files it should have been looking at. They all seem to be there.</p> <p>I thought perhaps it was a file permission problem so I reset all of the files in the wp_content directory.</p> <p>Just in case I was losing my mind, I have tried making small changes to the <code>header.php</code> just to confirm it is in fact the right file on the right server and the database is looking at the right files. All normal.</p> <p>I tried commenting out the erroneous function call but all that did was move the error down to the next function called.</p> <p>I checked the <code>style.css</code> to check its parent declaration was correct. I noticed there is a difference in file size between server and local but I've downloaded the file and it looks correct.</p> <p>I modified the <code>functions.php</code> on both parent and child simply to <code>var_dump</code> the current user. The child theme printed, the parent theme did not.</p> <p><strong>Conclusion:</strong> It seems as if my child theme is not aware of its parent when on the server but I can't figure out why that might be.</p> <h2>Child theme style.css</h2> <pre><code>/* Theme Name: Shapely Child Template: Shapely Version: 1.1.7 Author: colorlib Author URI: LINK */ </code></pre> <h2>Parent theme style.css</h2> <pre><code>/* Theme Name: Shapely Theme URI: LINK Author: colorlib Author URI: LINK ... */ </code></pre> <p>I apologise in advance if I've skipped over anything essential.</p> <p>Any and all help is greatly appreciated.</p>
[ { "answer_id": 278070, "author": "Atul", "author_id": 126565, "author_profile": "https://wordpress.stackexchange.com/users/126565", "pm_score": -1, "selected": false, "text": "<p>If there are only few images which are required for the plugin itself then store it under plugins own image folder. If you are making something else; where user will upload its own data then safely use uploads folder.</p>\n" }, { "answer_id": 278072, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>The only directory in which you have guaranteed write access is the uploads directory. Even your plugin's directory might be write protected, the same for <code>wp-content</code> (which doesn't even have to exist). </p>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278078", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122832/" ]
Probably a silly one but hopefully someone has encountered this before. The problem: ------------ I have a local copy of my Wordpress site that works fine and a copy on the server. After uploading I get `Call to undefined function` from within the child theme's `header.php` referencing a function that should exist in its parent theme. Full error message: ------------------- ``` Fatal error: Call to undefined function shapely_get_header_logo() in /home/twimp/training.twimp.co.uk/wp-content/themes/shapely-child/header.php on line 33 ``` Background: ----------- The server has recently had a Wordpress site running on it fine so I don't have particular reason to think its anything related to its configuration. I'm using a different theme from the last time it was uploaded so I started by uploading these two directories, my child theme and its parent. A lot of changes had been made with the plugins so I cleared the plugins directory and re-uploaded everything. I also completely wiped the database and imported from local and then modified the options table to put the correct server url back in. wp\_config has not been touched and so it still points at the right database. What I've tried: ---------------- I initially thought that maybe a file or two hadn't uploaded so I checked the FTP server side by side, starting with the files it should have been looking at. They all seem to be there. I thought perhaps it was a file permission problem so I reset all of the files in the wp\_content directory. Just in case I was losing my mind, I have tried making small changes to the `header.php` just to confirm it is in fact the right file on the right server and the database is looking at the right files. All normal. I tried commenting out the erroneous function call but all that did was move the error down to the next function called. I checked the `style.css` to check its parent declaration was correct. I noticed there is a difference in file size between server and local but I've downloaded the file and it looks correct. I modified the `functions.php` on both parent and child simply to `var_dump` the current user. The child theme printed, the parent theme did not. **Conclusion:** It seems as if my child theme is not aware of its parent when on the server but I can't figure out why that might be. Child theme style.css --------------------- ``` /* Theme Name: Shapely Child Template: Shapely Version: 1.1.7 Author: colorlib Author URI: LINK */ ``` Parent theme style.css ---------------------- ``` /* Theme Name: Shapely Theme URI: LINK Author: colorlib Author URI: LINK ... */ ``` I apologise in advance if I've skipped over anything essential. Any and all help is greatly appreciated.
The only directory in which you have guaranteed write access is the uploads directory. Even your plugin's directory might be write protected, the same for `wp-content` (which doesn't even have to exist).
278,081
<p>I have a plugin rejected by wordpress.org, one of the resasons is this:</p> <blockquote> <h2>Unsafe Requiring of Common Libraries Since you're using a common library, it's important that you enqueue it safely. Example(s):</h2> <p>require_once('jsonld.php');</p> <p>Since that is a common library, you need to detect IF the code is already included and not re-include it, as doing so will cause conflicts if two people call the same defines and functions.</p> </blockquote> <p>I understand about enqueueing jQuery and CSS - but this is a PHP script with multiple functions.</p> <ol> <li>If this script is common do I need to just reference it in the WP Core?</li> <li>Otherwise do I need to just look at the functions I'm calling and wrap them in a class (I'm uncertain about this) or can I refer to the whole php script?</li> <li>What is the standard way of doing this?</li> </ol> <p>Thanks</p> <p>Dan</p>
[ { "answer_id": 278082, "author": "Fabio Marzocca", "author_id": 65278, "author_profile": "https://wordpress.stackexchange.com/users/65278", "pm_score": 0, "selected": false, "text": "<p>You can check included files first.</p>\n\n<pre><code>$included_files = get_included_files();\n\nif (!in_array(\"jsonld.php\",$included files)) {\n\n require_once('jsonld.php');\n}\n</code></pre>\n" }, { "answer_id": 278083, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<ol>\n<li>No, it just means it's used by many plugins, not that Core includes it.</li>\n<li>Many of the functions in that library seem to use the <code>JsonLdProcessor</code> class that is also in that library, I'd check for that before including:</li>\n</ol>\n\n<p>&nbsp;</p>\n\n<pre><code>if ( ! class_exists( 'JsonLdProcessor' ) ) {\n require_once( 'jsonld.php' )\n}\n</code></pre>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17157/" ]
I have a plugin rejected by wordpress.org, one of the resasons is this: > > Unsafe Requiring of Common Libraries Since you're using a common library, it's important that you enqueue it safely. Example(s): > -------------------------------------------------------------------------------------------------------------------------------- > > > require\_once('jsonld.php'); > > > Since that is a common library, you need to detect IF the code is > already included and not re-include it, as doing so will cause > conflicts if two people call the same defines and functions. > > > I understand about enqueueing jQuery and CSS - but this is a PHP script with multiple functions. 1. If this script is common do I need to just reference it in the WP Core? 2. Otherwise do I need to just look at the functions I'm calling and wrap them in a class (I'm uncertain about this) or can I refer to the whole php script? 3. What is the standard way of doing this? Thanks Dan
1. No, it just means it's used by many plugins, not that Core includes it. 2. Many of the functions in that library seem to use the `JsonLdProcessor` class that is also in that library, I'd check for that before including: ``` if ( ! class_exists( 'JsonLdProcessor' ) ) { require_once( 'jsonld.php' ) } ```
278,096
<p>I have 4 users roles on my wordpress platform (role1, role2, role3, role4)</p> <p>I'm looking for to show front-end top bar only for Role1 Role2.</p> <p>how can i add a condition on this code to show it only for this 2 roles?</p> <pre><code>function wpc_show_admin_bar() { return true; } add_filter('show_admin_bar' , 'wpc_show_admin_bar'); </code></pre> <p>thanks</p>
[ { "answer_id": 278098, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 4, "selected": true, "text": "<p>You can disable the admin bar via function:</p>\n\n<pre><code>show_admin_bar(false);\n</code></pre>\n\n<p>So with that in mind, we can hook into <code>after_setup_theme</code> and hide the admin bar for all users except <code>administrator</code> and <code>contributor</code>:</p>\n\n<pre><code>function cc_wpse_278096_disable_admin_bar() {\n if (current_user_can('administrator') || current_user_can('contributor') ) {\n // user can view admin bar\n show_admin_bar(true); // this line isn't essentially needed by default...\n } else {\n // hide admin bar\n show_admin_bar(false);\n }\n}\nadd_action('after_setup_theme', 'cc_wpse_278096_disable_admin_bar');\n</code></pre>\n\n<p>I am only using <code>administrator</code> and <code>contributor</code> as example. You can of course change this and add more roles.</p>\n" }, { "answer_id": 403310, "author": "Gerard Reches", "author_id": 82961, "author_profile": "https://wordpress.stackexchange.com/users/82961", "pm_score": 2, "selected": false, "text": "<p>I see many people using the <code>after_setup_theme</code> action instead of the <code>show_admin_bar</code> filter, but this one works as well. I would say that the only difference is that the filter might be overwritten, but I see nothing wrong in that.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpc_show_admin_bar() {\n // Add the roles to exclude from having admin bar.\n $excluded_roles = [ 'role3', 'role4' ];\n\n return is_user_logged_in() &amp;&amp; ! array_intersect( wp_get_current_user()-&gt;roles, $excluded_roles);\n}\nadd_filter('show_admin_bar', 'wpc_show_admin_bar');\n</code></pre>\n<p>Nice and easy, you just need to add the roles you want to the <code>$excluded_roles</code> array. The function will only return true if the user is logged in and it doesn't have any of the excluded roles.</p>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278096", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119785/" ]
I have 4 users roles on my wordpress platform (role1, role2, role3, role4) I'm looking for to show front-end top bar only for Role1 Role2. how can i add a condition on this code to show it only for this 2 roles? ``` function wpc_show_admin_bar() { return true; } add_filter('show_admin_bar' , 'wpc_show_admin_bar'); ``` thanks
You can disable the admin bar via function: ``` show_admin_bar(false); ``` So with that in mind, we can hook into `after_setup_theme` and hide the admin bar for all users except `administrator` and `contributor`: ``` function cc_wpse_278096_disable_admin_bar() { if (current_user_can('administrator') || current_user_can('contributor') ) { // user can view admin bar show_admin_bar(true); // this line isn't essentially needed by default... } else { // hide admin bar show_admin_bar(false); } } add_action('after_setup_theme', 'cc_wpse_278096_disable_admin_bar'); ``` I am only using `administrator` and `contributor` as example. You can of course change this and add more roles.
278,099
<p>I'm creating a single page app with WP REST API and AngularJS. After solving a problem with nonces on <a href="https://wordpress.stackexchange.com/questions/278011/wp-rest-api-check-if-user-is-logged-in">this question</a>, now i'm facing something else. To test the chance of adding fields and making them protected against non-logged users, i tried to create a custom field which exposes the result of <code>wp_verify_nonce</code></p> <pre><code>if (isset($_SERVER['HTTP_X_WP_NONCE'])) { $nonce = $_SERVER['HTTP_X_WP_NONCE']; $nonce_verified = wp_verify_nonce($_SERVER['HTTP_X_WP_NONCE'], 'wp_rest'); } return array('nonce' =&gt; $nonce, 'nonce_verified' =&gt; $nonce_verified); </code></pre> <p>Of course, this is a test and will remain so. Nonce is exposed and so is <code>nonce_verified</code>. At this point, i tried to login/logout a user and require this endpoint and users/me. But it happened that my nonce is always verified, either with logged in or logged out user. Nonce itself changes while doing this; still, when logged out, it's the same for all of its lifetime.</p> <p>To create my nonce, i used a localized code as in my previous question:</p> <pre><code>wp_localize_script('angularjs', 'params', array( 'nonce' =&gt; wp_create_nonce('wp_rest'), )); </code></pre> <p>which is passed through javascript, as i saw in a tutorial about AngularJS. Although this nonce gets validated, query to <code>users/me</code> leads to a 403 when not logged, as expected.</p> <p>My theory is that a nonce for non-logged users is being created, so there is always a valid nonce available. Should i protect nonce creation with <code>is_user_logged_in()</code>? Or should i hook the nonce creation somewhere? Thank you.</p>
[ { "answer_id": 278100, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 1, "selected": false, "text": "<p>WordPress nonces are not real nonces, they remain valid for a period of 12 to 24 hours and will return the <strong>SAME</strong> value for <strong>all visitors</strong> (not logged in users) of the website. So you should NOT rely on WP nonces for security measures if you expect a new number for each action or you are working with guest users in your application.</p>\n\n<p>I explain in depth how this works here: <a href=\"https://www.bynicolas.com/code/wordpress-nonce/\" rel=\"nofollow noreferrer\">https://www.bynicolas.com/code/wordpress-nonce/</a></p>\n\n<p>You might also want to take a look at this project <a href=\"https://github.com/calevans/wp-simple-nonce\" rel=\"nofollow noreferrer\">https://github.com/calevans/wp-simple-nonce</a> if you wish to add true nonces to your project</p>\n\n<p><strong>EDIT</strong>\nfrom the codex <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WordPress_Nonces</a></p>\n\n<blockquote>\n <p>Nonces should never be relied on for authentication or authorization, access control.</p>\n</blockquote>\n" }, { "answer_id": 278108, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": true, "text": "<p>The true reason of not using nonces for non logged in users, is that it adds a pointless burden on their usage as they need to refresh the page when the nonce expire, and the only way they will know that they need to do it is when something do not work.</p>\n\n<p>There is probably no reason to avoid generating it, but if you expect that your \"app\" will be used/open for more then 12 hours (that is the \"tick\" time used to calculate wordpress nonces) then either you need to also have an automatic way to refresh the nonce (might be a good idea for logged in users as well) or avoid using it in the first place.</p>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278099", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119611/" ]
I'm creating a single page app with WP REST API and AngularJS. After solving a problem with nonces on [this question](https://wordpress.stackexchange.com/questions/278011/wp-rest-api-check-if-user-is-logged-in), now i'm facing something else. To test the chance of adding fields and making them protected against non-logged users, i tried to create a custom field which exposes the result of `wp_verify_nonce` ``` if (isset($_SERVER['HTTP_X_WP_NONCE'])) { $nonce = $_SERVER['HTTP_X_WP_NONCE']; $nonce_verified = wp_verify_nonce($_SERVER['HTTP_X_WP_NONCE'], 'wp_rest'); } return array('nonce' => $nonce, 'nonce_verified' => $nonce_verified); ``` Of course, this is a test and will remain so. Nonce is exposed and so is `nonce_verified`. At this point, i tried to login/logout a user and require this endpoint and users/me. But it happened that my nonce is always verified, either with logged in or logged out user. Nonce itself changes while doing this; still, when logged out, it's the same for all of its lifetime. To create my nonce, i used a localized code as in my previous question: ``` wp_localize_script('angularjs', 'params', array( 'nonce' => wp_create_nonce('wp_rest'), )); ``` which is passed through javascript, as i saw in a tutorial about AngularJS. Although this nonce gets validated, query to `users/me` leads to a 403 when not logged, as expected. My theory is that a nonce for non-logged users is being created, so there is always a valid nonce available. Should i protect nonce creation with `is_user_logged_in()`? Or should i hook the nonce creation somewhere? Thank you.
The true reason of not using nonces for non logged in users, is that it adds a pointless burden on their usage as they need to refresh the page when the nonce expire, and the only way they will know that they need to do it is when something do not work. There is probably no reason to avoid generating it, but if you expect that your "app" will be used/open for more then 12 hours (that is the "tick" time used to calculate wordpress nonces) then either you need to also have an automatic way to refresh the nonce (might be a good idea for logged in users as well) or avoid using it in the first place.
278,109
<p>I'm trying to exclude the latest two blog posts from a page. I know it's possible to do this with <code>offset</code> however doing that causes a bug in which some of the blog posts are repeated on the second page so not ideal. Currently I'm doing it manually using the post id so like this:</p> <pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1'; $args = array( 'posts_per_page' =&gt; 5, 'post__not_in' =&gt; array(827, 809), 'post_status' =&gt;"publish", 'post_type' =&gt;"post", 'orderby' =&gt;"post_date", 'cat' =&gt;'-1, -8, -9, -7, -6, -5, -4', 'paged' =&gt; $paged ); $postslist = get_posts( $args ); echo '&lt;div class="latest_new_posts main-news"&gt;'; </code></pre> <p>Can anybody think of a better way of doing this where I don't have to adjust the post id constantly?</p>
[ { "answer_id": 278100, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 1, "selected": false, "text": "<p>WordPress nonces are not real nonces, they remain valid for a period of 12 to 24 hours and will return the <strong>SAME</strong> value for <strong>all visitors</strong> (not logged in users) of the website. So you should NOT rely on WP nonces for security measures if you expect a new number for each action or you are working with guest users in your application.</p>\n\n<p>I explain in depth how this works here: <a href=\"https://www.bynicolas.com/code/wordpress-nonce/\" rel=\"nofollow noreferrer\">https://www.bynicolas.com/code/wordpress-nonce/</a></p>\n\n<p>You might also want to take a look at this project <a href=\"https://github.com/calevans/wp-simple-nonce\" rel=\"nofollow noreferrer\">https://github.com/calevans/wp-simple-nonce</a> if you wish to add true nonces to your project</p>\n\n<p><strong>EDIT</strong>\nfrom the codex <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WordPress_Nonces</a></p>\n\n<blockquote>\n <p>Nonces should never be relied on for authentication or authorization, access control.</p>\n</blockquote>\n" }, { "answer_id": 278108, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": true, "text": "<p>The true reason of not using nonces for non logged in users, is that it adds a pointless burden on their usage as they need to refresh the page when the nonce expire, and the only way they will know that they need to do it is when something do not work.</p>\n\n<p>There is probably no reason to avoid generating it, but if you expect that your \"app\" will be used/open for more then 12 hours (that is the \"tick\" time used to calculate wordpress nonces) then either you need to also have an automatic way to refresh the nonce (might be a good idea for logged in users as well) or avoid using it in the first place.</p>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126587/" ]
I'm trying to exclude the latest two blog posts from a page. I know it's possible to do this with `offset` however doing that causes a bug in which some of the blog posts are repeated on the second page so not ideal. Currently I'm doing it manually using the post id so like this: ``` $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1'; $args = array( 'posts_per_page' => 5, 'post__not_in' => array(827, 809), 'post_status' =>"publish", 'post_type' =>"post", 'orderby' =>"post_date", 'cat' =>'-1, -8, -9, -7, -6, -5, -4', 'paged' => $paged ); $postslist = get_posts( $args ); echo '<div class="latest_new_posts main-news">'; ``` Can anybody think of a better way of doing this where I don't have to adjust the post id constantly?
The true reason of not using nonces for non logged in users, is that it adds a pointless burden on their usage as they need to refresh the page when the nonce expire, and the only way they will know that they need to do it is when something do not work. There is probably no reason to avoid generating it, but if you expect that your "app" will be used/open for more then 12 hours (that is the "tick" time used to calculate wordpress nonces) then either you need to also have an automatic way to refresh the nonce (might be a good idea for logged in users as well) or avoid using it in the first place.
278,128
<p>I am trying to output related posts of the current post by <code>tag_ID</code>. With the current code, posts will output all posts from the <code>property</code> tag instead of specific tag.</p> <p>How can I only return posts based on the current posts <code>tag_ID</code>?</p> <pre><code>&lt;?php $post_tag = get_the_tags($post-&gt;ID)?&gt;//Not sure if correct &lt;?php $args = array( 'post_type' =&gt; 'property', 'tag' =&gt; $post_tag, ); $related_posts = new WP_Query( $args ); ?&gt; &lt;?php while ( $related_posts -&gt; have_posts() ) : $related_posts -&gt; the_post(); ?&gt; &lt;h2&gt;&lt;?php echo get_the_title()?&gt;&lt;/h2&gt; //etc &lt;?php endwhile; wp_reset_query(); ?&gt; </code></pre> <p><strong>Solution:</strong> Might not be the best solution but manages to query related posts that are within <code>city</code> and the current posts tag.</p> <pre><code>$tags = wp_get_post_terms( get_queried_object_id(), 'city', ['fields' =&gt; 'ids'] ); // Now pass the IDs to tag__in $args = array( 'post_type' =&gt; 'property', 'post__not_in' =&gt; array( $post-&gt;ID ), 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'city', 'terms' =&gt; $tags, ), ), ); $related_posts = new WP_Query( $args ); </code></pre>
[ { "answer_id": 278130, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p><code>get_the_tags()</code> returns an array of tags name, ID, and more. You should store only IDs in an array, and use it in your query.</p>\n\n<pre><code>$post_tag = get_the_tags ( $post-&gt;ID );\n// Define an empty array\n$ids = array();\n// Check if the post has any tags\nif ( $post_tag ) {\n foreach ( $post_tag as $tag ) {\n $ids[] = $tag-&gt;term_id; \n }\n}\n// Now pass the IDs to tag__in\n$args = array(\n 'post_type' =&gt; 'property',\n 'tag__in' =&gt; $ids,\n);\n// Now proceed with the rest of your query\n$related_posts = new WP_Query( $args );\n</code></pre>\n\n<p>Also, use <code>wp_reset_postdata();</code> instead of <code>wp_reset_query();</code> when you are using <code>WP_Query();</code>.</p>\n\n<h2>UPDATE</h2>\n\n<p>As pointed out by @birgire, WordPress offers the <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pluck/\" rel=\"nofollow noreferrer\"><code>wp_list_plunk()</code></a> function to extract a certain field of each object in a row, which has the same functionality as <a href=\"http://php.net/manual/en/function.array-column.php\" rel=\"nofollow noreferrer\"><code>array_column()</code></a> function.</p>\n\n<p>So, we can change this:</p>\n\n<pre><code>// Define an empty array\n$ids = array();\n// Check if the post has any tags\nif ( $post_tag ) {\n foreach ( $post_tag as $tag ) {\n $ids[] = $tag-&gt;term_id; \n }\n}\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>// Check if the post has any tags\nif ( $post_tag ) {\n $ids = wp_list_pluck( $post_tag, 'term_id' );\n}\n</code></pre>\n" }, { "answer_id": 382483, "author": "jasper_prikr", "author_id": 172271, "author_profile": "https://wordpress.stackexchange.com/users/172271", "pm_score": 1, "selected": false, "text": "<p>While Jack here gives a good example of how the tags can be obtained, I found a shorter way to obtain all tags in one Array.</p>\n<pre><code>$tags = wp_get_post_terms($post-&gt;ID, 'post_tag', array(&quot;fields&quot; =&gt; &quot;ids&quot;));\nvar_dump($tags); // Output: array(3) { [0]=&gt; int(47) [1]=&gt; int(43) [2]=&gt; int(42) }\n</code></pre>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87036/" ]
I am trying to output related posts of the current post by `tag_ID`. With the current code, posts will output all posts from the `property` tag instead of specific tag. How can I only return posts based on the current posts `tag_ID`? ``` <?php $post_tag = get_the_tags($post->ID)?>//Not sure if correct <?php $args = array( 'post_type' => 'property', 'tag' => $post_tag, ); $related_posts = new WP_Query( $args ); ?> <?php while ( $related_posts -> have_posts() ) : $related_posts -> the_post(); ?> <h2><?php echo get_the_title()?></h2> //etc <?php endwhile; wp_reset_query(); ?> ``` **Solution:** Might not be the best solution but manages to query related posts that are within `city` and the current posts tag. ``` $tags = wp_get_post_terms( get_queried_object_id(), 'city', ['fields' => 'ids'] ); // Now pass the IDs to tag__in $args = array( 'post_type' => 'property', 'post__not_in' => array( $post->ID ), 'tax_query' => array( array( 'taxonomy' => 'city', 'terms' => $tags, ), ), ); $related_posts = new WP_Query( $args ); ```
`get_the_tags()` returns an array of tags name, ID, and more. You should store only IDs in an array, and use it in your query. ``` $post_tag = get_the_tags ( $post->ID ); // Define an empty array $ids = array(); // Check if the post has any tags if ( $post_tag ) { foreach ( $post_tag as $tag ) { $ids[] = $tag->term_id; } } // Now pass the IDs to tag__in $args = array( 'post_type' => 'property', 'tag__in' => $ids, ); // Now proceed with the rest of your query $related_posts = new WP_Query( $args ); ``` Also, use `wp_reset_postdata();` instead of `wp_reset_query();` when you are using `WP_Query();`. UPDATE ------ As pointed out by @birgire, WordPress offers the [`wp_list_plunk()`](https://developer.wordpress.org/reference/functions/wp_list_pluck/) function to extract a certain field of each object in a row, which has the same functionality as [`array_column()`](http://php.net/manual/en/function.array-column.php) function. So, we can change this: ``` // Define an empty array $ids = array(); // Check if the post has any tags if ( $post_tag ) { foreach ( $post_tag as $tag ) { $ids[] = $tag->term_id; } } ``` To this: ``` // Check if the post has any tags if ( $post_tag ) { $ids = wp_list_pluck( $post_tag, 'term_id' ); } ```
278,136
<p>So, I have a plugin that uses Ajax to dynamically build the post content piece by piece for a custom post type. Once the user has build their page, they hit Update/Publish and Ajax sends the entire built page to a the main plugin PHP file where I am attempting to call <code>wp_insert_post()</code>.</p> <p>Here is my relevant code (and yes the var <code>new_content</code> is set and is correct):</p> <pre><code>jQuery.ajax({ url: ajaxurl, method: 'POST', data : { update_or_create: '1', post_content: new_content, post_title: jQuery('#title').val(), pid: jQuery('#post_ID').val(), action : "update_or_save_zen_page" } , success : function(data, textStatus, XMLHttpRequest) { //alert(data); console.log(data); // the data sent to the php file is correct console.log(textStatus); // reads 'success' console.log(XMLHttpRequest); // normal from what I can tell, "readyState: 4" }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert("An unknown error has occurred"); // this does not fire //console.log(data); //console.log(textStatus); //console.log(errorThrown); //console.log(XMLHttpRequest); } }); </code></pre> <p>Here is the php code this is posting to:</p> <pre><code>function pbfcz_save_zen_page() { $pid = ( is_numeric($_POST['pid']) ? $_POST['pid'] : 0); $the_content = sanitize_post_field ('post_content', $_POST['post_content'], $pid); $the_title = sanitize_text_field ( $_POST['post_title'] ); $post_array = array ( 'ID' =&gt; $pid, 'post_title' =&gt; $the_title, 'post_content' =&gt; $the_content, // at this point, $the_content is correct 'post_status' =&gt; 'publish', 'post_type' =&gt; 'zen_page' ); $insert = wp_insert_post( $post_array, true ); // this returns the ID every time, meaning successful update, but it is not always successful //echo $insert; // this is always the post ID, meaning success echo $the_content; // this is still correc wp_die();} </code></pre> <p>When the user selects save, I have tracked the data all the way until the argument for <code>wp_insert_post()</code>. It is ALWAYS correct. The function ALWAYS returns the post ID, meaning is was successful. I don't get a <code>WP_Error</code> returned or any HTML code errors like 404 or 500 or anything like that. </p> <p>I don't get any errors in the chrome developer tools console either. But it updates successfully SOMETIMES - maybe every 1 in 10 tries it works.</p> <p>I have tried using GET instead of POST</p> <p>I have tried removing the <code>'post_status' =&gt; 'publish'</code> from the arguments.</p> <p>I have tried converting the <code>post_content</code> to UTF8 by using <code>utf8_encode()</code>.</p> <p>I have tried using <code>post_content_filtered</code> rather than <code>post_content</code>.</p> <p>Nothing seems to be working, and it works randomly, and I cannot find a pattern. </p> <p>The only other piece of information I have that may be related is that images have a hard time loading on this same page. If there is an image in the page content, I get errors such as </p> <blockquote> <p>"net::ERR_SPDY_PING_FAILED" or "net::ERR_CONNECTION_RESET"</p> </blockquote> <p>or:</p> <blockquote> <p>"net::ERR_CONNECTION_CLOSED"</p> </blockquote> <p>sometimes on page load. The server tries to load the image for over a minute then times out (but the image is already displaying on the page for that entire minute, then when it times out the image disappears).</p> <p>Can anybody suggest why this is not working (with zero errors), but does work sometimes? Thank you all in advance and let me know if you need more code or background.</p>
[ { "answer_id": 278139, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all of this out of the box:</p>\n\n<pre><code>example.com/wp-json/wp/v2/zen_page\n</code></pre>\n\n<p>So lets enqueue a helper script to give us the URL and a security token/nonce:</p>\n\n<pre><code>wp_enqueue_script( 'wp-api' );\n</code></pre>\n\n<p>You will <strong>must</strong> enable the REST API for your custom post type by adding this option when registering your post type. If you don't do this then the <code>zen_page</code> rest endpoints will not be created by core:</p>\n\n<pre><code>'show_in_rest' =&gt; true\n</code></pre>\n\n<p>Then adjust the JS:</p>\n\n<pre><code>var post_id = 1;\njQuery.ajax({\n url: wpApiSettings.root + 'wp/v2/zen_page/'+post_id,\n method: 'POST',\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );\n },\n data : {\n content: 'post content goes here',\n title: 'test post',\n status: 'publish'\n }\n}).fail( function( response ) {\n // failure\n console.log( 'failure' );\n console.log( response );\n}).done( function( response ) {\n // success!\n console.log( 'success' );\n console.log( response );\n}).;\n</code></pre>\n\n<p>WP automatically includes the <code>wpApiSettings</code> object when you enqueue <code>wp-api</code>, and <code>data</code> <a href=\"https://developer.wordpress.org/rest-api/reference/posts/#schema\" rel=\"nofollow noreferrer\">takes these values</a>. You'll need an active login cookie to do this. If that's not an option, you can create new rest endpoints</p>\n\n<p>If you want to create a new one, send a POST request here:</p>\n\n<pre><code>example.com/wp-json/wp/v2/zen_page\n</code></pre>\n\n<p>If you want to update one, send a POST request here:</p>\n\n<pre><code>example.com/wp-json/wp/v2/zen_page/2\n</code></pre>\n\n<p>Where 2 is the post ID you want to update. Send a DELETE request to delete it. In a REST API, you don't pass post IDs or actions, instead you use URLs, the same way different urls load different pages, different endpoints do different things. You can <code>GET</code>/<code>POST</code>/<code>DELETE</code>/<code>PUT</code>, and these are all the standard HTTP request types, not a parameter passed in the request.</p>\n\n<h2>Follow Up Notes</h2>\n\n<h3><code>rest_base</code></h3>\n\n<p>This will let you modify what core uses to create the endpoint, e.g.</p>\n\n<pre><code>'rest_base' =&gt; 'bananas'\n</code></pre>\n\n<p>will change your endpoints URL to <code>wp/v2/bananas</code>. Note that you do not want to name this <code>pages</code> as there is already a <code>pages</code> endpoint provided by core.</p>\n\n<h3><code>zen_page</code></h3>\n\n<p>This might actually be better off if you just used the <code>page</code> post type and used a custom taxonomy to differentiate the zen_page's from normal pages.</p>\n\n<h3>It doesn't work</h3>\n\n<p>The REST API is designed to indicate why it didn't work, e.g. if I try to visit <code>wp-json/wp/v2/skjlfnvlkdjfv</code> I'll get:</p>\n\n<blockquote>\n <p><code>{\"code\":\"rest_no_route\",\"message\":\"No route was found matching the URL and request method\",\"data\":{\"status\":404}}</code></p>\n</blockquote>\n\n<p>and if I try to use the <code>wp-json/wp/v2/settings</code> endpoint in incognito mode:</p>\n\n<blockquote>\n <p><code>{\"code\":\"rest_forbidden\",\"message\":\"Sorry, you are not allowed to do that.\",\"data\":{\"status\":403}}</code></p>\n</blockquote>\n\n<p>Admin AJAX will return <code>0</code> in all of these scenarios, so be thankful but pay attention to failure or error messages. Here we saw I tried to make a request to an endpoint that doesn't exist, then again to an endpoint I didn't have permission for as I was logged out.</p>\n" }, { "answer_id": 278468, "author": "Jeremy Muckel", "author_id": 119050, "author_profile": "https://wordpress.stackexchange.com/users/119050", "pm_score": 0, "selected": false, "text": "<p>Thanks to @TomJNowell, I was able to get around using wp_insert_post(), which would not work, and update my posts with the php version of the REST API.</p>\n\n<p>I had to:</p>\n\n<p>1) Include <code>'show_in_rest' =&gt; true</code> in my custom post type's registration.</p>\n\n<p>2) Enqueue the helper script: <code>wp_enqueue_script( 'wp-api' );</code></p>\n\n<p>3) Use this php to handle the jquery post request</p>\n\n<pre><code>add_action('wp_ajax_update_or_save_zen_page', 'pbfcz_save_zen_page', 99999);\nfunction pbfcz_save_zen_page() {\n $pid = $_POST['pid'];\n $the_content = sanitize_post_field ('post_content', $_POST['post_content'], $pid);\n $the_title = sanitize_text_field ( $_POST['post_title'] ); \n $the_content = str_replace('\\\"', '\"', $the_content);\n\n $_rest = new WP_REST_Request('PUT', '/wp/v2/zen_page/' . $pid);\n $_rest-&gt;set_param( 'title', $the_title);\n $_rest-&gt;set_param( 'status', 'publish');\n $_rest-&gt;set_param( 'content', $the_content);\n\n $response = rest_do_request($_rest);\n echo 'done';\n\n wp_die(); // do not remove\n}\n</code></pre>\n\n<p>My jQuery did not change much from the original question, posting here for clarity:</p>\n\n<pre><code>jQuery.ajax({\n url: ajaxurl,\n method: 'POST',\n data : {\n post_content : new_content,\n post_title : jQuery('#title').val(),\n pid : post_id,\n action : \"update_or_save_zen_page\"\n } , \n success : function(data, textStatus, XMLHttpRequest) {\n //console.log(data); \n },\n error : function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"An unknown error has occurred and the ajax request to create/update the post has failed.\");\n }\n});\n</code></pre>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278136", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119050/" ]
So, I have a plugin that uses Ajax to dynamically build the post content piece by piece for a custom post type. Once the user has build their page, they hit Update/Publish and Ajax sends the entire built page to a the main plugin PHP file where I am attempting to call `wp_insert_post()`. Here is my relevant code (and yes the var `new_content` is set and is correct): ``` jQuery.ajax({ url: ajaxurl, method: 'POST', data : { update_or_create: '1', post_content: new_content, post_title: jQuery('#title').val(), pid: jQuery('#post_ID').val(), action : "update_or_save_zen_page" } , success : function(data, textStatus, XMLHttpRequest) { //alert(data); console.log(data); // the data sent to the php file is correct console.log(textStatus); // reads 'success' console.log(XMLHttpRequest); // normal from what I can tell, "readyState: 4" }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert("An unknown error has occurred"); // this does not fire //console.log(data); //console.log(textStatus); //console.log(errorThrown); //console.log(XMLHttpRequest); } }); ``` Here is the php code this is posting to: ``` function pbfcz_save_zen_page() { $pid = ( is_numeric($_POST['pid']) ? $_POST['pid'] : 0); $the_content = sanitize_post_field ('post_content', $_POST['post_content'], $pid); $the_title = sanitize_text_field ( $_POST['post_title'] ); $post_array = array ( 'ID' => $pid, 'post_title' => $the_title, 'post_content' => $the_content, // at this point, $the_content is correct 'post_status' => 'publish', 'post_type' => 'zen_page' ); $insert = wp_insert_post( $post_array, true ); // this returns the ID every time, meaning successful update, but it is not always successful //echo $insert; // this is always the post ID, meaning success echo $the_content; // this is still correc wp_die();} ``` When the user selects save, I have tracked the data all the way until the argument for `wp_insert_post()`. It is ALWAYS correct. The function ALWAYS returns the post ID, meaning is was successful. I don't get a `WP_Error` returned or any HTML code errors like 404 or 500 or anything like that. I don't get any errors in the chrome developer tools console either. But it updates successfully SOMETIMES - maybe every 1 in 10 tries it works. I have tried using GET instead of POST I have tried removing the `'post_status' => 'publish'` from the arguments. I have tried converting the `post_content` to UTF8 by using `utf8_encode()`. I have tried using `post_content_filtered` rather than `post_content`. Nothing seems to be working, and it works randomly, and I cannot find a pattern. The only other piece of information I have that may be related is that images have a hard time loading on this same page. If there is an image in the page content, I get errors such as > > "net::ERR\_SPDY\_PING\_FAILED" or "net::ERR\_CONNECTION\_RESET" > > > or: > > "net::ERR\_CONNECTION\_CLOSED" > > > sometimes on page load. The server tries to load the image for over a minute then times out (but the image is already displaying on the page for that entire minute, then when it times out the image disappears). Can anybody suggest why this is not working (with zero errors), but does work sometimes? Thank you all in advance and let me know if you need more code or background.
Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all of this out of the box: ``` example.com/wp-json/wp/v2/zen_page ``` So lets enqueue a helper script to give us the URL and a security token/nonce: ``` wp_enqueue_script( 'wp-api' ); ``` You will **must** enable the REST API for your custom post type by adding this option when registering your post type. If you don't do this then the `zen_page` rest endpoints will not be created by core: ``` 'show_in_rest' => true ``` Then adjust the JS: ``` var post_id = 1; jQuery.ajax({ url: wpApiSettings.root + 'wp/v2/zen_page/'+post_id, method: 'POST', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data : { content: 'post content goes here', title: 'test post', status: 'publish' } }).fail( function( response ) { // failure console.log( 'failure' ); console.log( response ); }).done( function( response ) { // success! console.log( 'success' ); console.log( response ); }).; ``` WP automatically includes the `wpApiSettings` object when you enqueue `wp-api`, and `data` [takes these values](https://developer.wordpress.org/rest-api/reference/posts/#schema). You'll need an active login cookie to do this. If that's not an option, you can create new rest endpoints If you want to create a new one, send a POST request here: ``` example.com/wp-json/wp/v2/zen_page ``` If you want to update one, send a POST request here: ``` example.com/wp-json/wp/v2/zen_page/2 ``` Where 2 is the post ID you want to update. Send a DELETE request to delete it. In a REST API, you don't pass post IDs or actions, instead you use URLs, the same way different urls load different pages, different endpoints do different things. You can `GET`/`POST`/`DELETE`/`PUT`, and these are all the standard HTTP request types, not a parameter passed in the request. Follow Up Notes --------------- ### `rest_base` This will let you modify what core uses to create the endpoint, e.g. ``` 'rest_base' => 'bananas' ``` will change your endpoints URL to `wp/v2/bananas`. Note that you do not want to name this `pages` as there is already a `pages` endpoint provided by core. ### `zen_page` This might actually be better off if you just used the `page` post type and used a custom taxonomy to differentiate the zen\_page's from normal pages. ### It doesn't work The REST API is designed to indicate why it didn't work, e.g. if I try to visit `wp-json/wp/v2/skjlfnvlkdjfv` I'll get: > > `{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}` > > > and if I try to use the `wp-json/wp/v2/settings` endpoint in incognito mode: > > `{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":403}}` > > > Admin AJAX will return `0` in all of these scenarios, so be thankful but pay attention to failure or error messages. Here we saw I tried to make a request to an endpoint that doesn't exist, then again to an endpoint I didn't have permission for as I was logged out.
278,148
<p>I've just converted my local development install of wordpress to a network, and everything seems to work, except the parts of the admin panel relating to network management don't have the correct links (I have the core wordpress files in a "wordpress/" subdirectory.) The network related parts get links generated without the "wordpress/" component, but everything else continues to work correctly.</p> <p>Is there a step I missed to get my "network" to play nice with this directory setup?</p>
[ { "answer_id": 278139, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all of this out of the box:</p>\n\n<pre><code>example.com/wp-json/wp/v2/zen_page\n</code></pre>\n\n<p>So lets enqueue a helper script to give us the URL and a security token/nonce:</p>\n\n<pre><code>wp_enqueue_script( 'wp-api' );\n</code></pre>\n\n<p>You will <strong>must</strong> enable the REST API for your custom post type by adding this option when registering your post type. If you don't do this then the <code>zen_page</code> rest endpoints will not be created by core:</p>\n\n<pre><code>'show_in_rest' =&gt; true\n</code></pre>\n\n<p>Then adjust the JS:</p>\n\n<pre><code>var post_id = 1;\njQuery.ajax({\n url: wpApiSettings.root + 'wp/v2/zen_page/'+post_id,\n method: 'POST',\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );\n },\n data : {\n content: 'post content goes here',\n title: 'test post',\n status: 'publish'\n }\n}).fail( function( response ) {\n // failure\n console.log( 'failure' );\n console.log( response );\n}).done( function( response ) {\n // success!\n console.log( 'success' );\n console.log( response );\n}).;\n</code></pre>\n\n<p>WP automatically includes the <code>wpApiSettings</code> object when you enqueue <code>wp-api</code>, and <code>data</code> <a href=\"https://developer.wordpress.org/rest-api/reference/posts/#schema\" rel=\"nofollow noreferrer\">takes these values</a>. You'll need an active login cookie to do this. If that's not an option, you can create new rest endpoints</p>\n\n<p>If you want to create a new one, send a POST request here:</p>\n\n<pre><code>example.com/wp-json/wp/v2/zen_page\n</code></pre>\n\n<p>If you want to update one, send a POST request here:</p>\n\n<pre><code>example.com/wp-json/wp/v2/zen_page/2\n</code></pre>\n\n<p>Where 2 is the post ID you want to update. Send a DELETE request to delete it. In a REST API, you don't pass post IDs or actions, instead you use URLs, the same way different urls load different pages, different endpoints do different things. You can <code>GET</code>/<code>POST</code>/<code>DELETE</code>/<code>PUT</code>, and these are all the standard HTTP request types, not a parameter passed in the request.</p>\n\n<h2>Follow Up Notes</h2>\n\n<h3><code>rest_base</code></h3>\n\n<p>This will let you modify what core uses to create the endpoint, e.g.</p>\n\n<pre><code>'rest_base' =&gt; 'bananas'\n</code></pre>\n\n<p>will change your endpoints URL to <code>wp/v2/bananas</code>. Note that you do not want to name this <code>pages</code> as there is already a <code>pages</code> endpoint provided by core.</p>\n\n<h3><code>zen_page</code></h3>\n\n<p>This might actually be better off if you just used the <code>page</code> post type and used a custom taxonomy to differentiate the zen_page's from normal pages.</p>\n\n<h3>It doesn't work</h3>\n\n<p>The REST API is designed to indicate why it didn't work, e.g. if I try to visit <code>wp-json/wp/v2/skjlfnvlkdjfv</code> I'll get:</p>\n\n<blockquote>\n <p><code>{\"code\":\"rest_no_route\",\"message\":\"No route was found matching the URL and request method\",\"data\":{\"status\":404}}</code></p>\n</blockquote>\n\n<p>and if I try to use the <code>wp-json/wp/v2/settings</code> endpoint in incognito mode:</p>\n\n<blockquote>\n <p><code>{\"code\":\"rest_forbidden\",\"message\":\"Sorry, you are not allowed to do that.\",\"data\":{\"status\":403}}</code></p>\n</blockquote>\n\n<p>Admin AJAX will return <code>0</code> in all of these scenarios, so be thankful but pay attention to failure or error messages. Here we saw I tried to make a request to an endpoint that doesn't exist, then again to an endpoint I didn't have permission for as I was logged out.</p>\n" }, { "answer_id": 278468, "author": "Jeremy Muckel", "author_id": 119050, "author_profile": "https://wordpress.stackexchange.com/users/119050", "pm_score": 0, "selected": false, "text": "<p>Thanks to @TomJNowell, I was able to get around using wp_insert_post(), which would not work, and update my posts with the php version of the REST API.</p>\n\n<p>I had to:</p>\n\n<p>1) Include <code>'show_in_rest' =&gt; true</code> in my custom post type's registration.</p>\n\n<p>2) Enqueue the helper script: <code>wp_enqueue_script( 'wp-api' );</code></p>\n\n<p>3) Use this php to handle the jquery post request</p>\n\n<pre><code>add_action('wp_ajax_update_or_save_zen_page', 'pbfcz_save_zen_page', 99999);\nfunction pbfcz_save_zen_page() {\n $pid = $_POST['pid'];\n $the_content = sanitize_post_field ('post_content', $_POST['post_content'], $pid);\n $the_title = sanitize_text_field ( $_POST['post_title'] ); \n $the_content = str_replace('\\\"', '\"', $the_content);\n\n $_rest = new WP_REST_Request('PUT', '/wp/v2/zen_page/' . $pid);\n $_rest-&gt;set_param( 'title', $the_title);\n $_rest-&gt;set_param( 'status', 'publish');\n $_rest-&gt;set_param( 'content', $the_content);\n\n $response = rest_do_request($_rest);\n echo 'done';\n\n wp_die(); // do not remove\n}\n</code></pre>\n\n<p>My jQuery did not change much from the original question, posting here for clarity:</p>\n\n<pre><code>jQuery.ajax({\n url: ajaxurl,\n method: 'POST',\n data : {\n post_content : new_content,\n post_title : jQuery('#title').val(),\n pid : post_id,\n action : \"update_or_save_zen_page\"\n } , \n success : function(data, textStatus, XMLHttpRequest) {\n //console.log(data); \n },\n error : function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"An unknown error has occurred and the ajax request to create/update the post has failed.\");\n }\n});\n</code></pre>\n" } ]
2017/08/25
[ "https://wordpress.stackexchange.com/questions/278148", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84595/" ]
I've just converted my local development install of wordpress to a network, and everything seems to work, except the parts of the admin panel relating to network management don't have the correct links (I have the core wordpress files in a "wordpress/" subdirectory.) The network related parts get links generated without the "wordpress/" component, but everything else continues to work correctly. Is there a step I missed to get my "network" to play nice with this directory setup?
Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all of this out of the box: ``` example.com/wp-json/wp/v2/zen_page ``` So lets enqueue a helper script to give us the URL and a security token/nonce: ``` wp_enqueue_script( 'wp-api' ); ``` You will **must** enable the REST API for your custom post type by adding this option when registering your post type. If you don't do this then the `zen_page` rest endpoints will not be created by core: ``` 'show_in_rest' => true ``` Then adjust the JS: ``` var post_id = 1; jQuery.ajax({ url: wpApiSettings.root + 'wp/v2/zen_page/'+post_id, method: 'POST', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data : { content: 'post content goes here', title: 'test post', status: 'publish' } }).fail( function( response ) { // failure console.log( 'failure' ); console.log( response ); }).done( function( response ) { // success! console.log( 'success' ); console.log( response ); }).; ``` WP automatically includes the `wpApiSettings` object when you enqueue `wp-api`, and `data` [takes these values](https://developer.wordpress.org/rest-api/reference/posts/#schema). You'll need an active login cookie to do this. If that's not an option, you can create new rest endpoints If you want to create a new one, send a POST request here: ``` example.com/wp-json/wp/v2/zen_page ``` If you want to update one, send a POST request here: ``` example.com/wp-json/wp/v2/zen_page/2 ``` Where 2 is the post ID you want to update. Send a DELETE request to delete it. In a REST API, you don't pass post IDs or actions, instead you use URLs, the same way different urls load different pages, different endpoints do different things. You can `GET`/`POST`/`DELETE`/`PUT`, and these are all the standard HTTP request types, not a parameter passed in the request. Follow Up Notes --------------- ### `rest_base` This will let you modify what core uses to create the endpoint, e.g. ``` 'rest_base' => 'bananas' ``` will change your endpoints URL to `wp/v2/bananas`. Note that you do not want to name this `pages` as there is already a `pages` endpoint provided by core. ### `zen_page` This might actually be better off if you just used the `page` post type and used a custom taxonomy to differentiate the zen\_page's from normal pages. ### It doesn't work The REST API is designed to indicate why it didn't work, e.g. if I try to visit `wp-json/wp/v2/skjlfnvlkdjfv` I'll get: > > `{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}` > > > and if I try to use the `wp-json/wp/v2/settings` endpoint in incognito mode: > > `{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":403}}` > > > Admin AJAX will return `0` in all of these scenarios, so be thankful but pay attention to failure or error messages. Here we saw I tried to make a request to an endpoint that doesn't exist, then again to an endpoint I didn't have permission for as I was logged out.
278,150
<p>I'm currently working on my first theme and am trying to allow the user to edit some text in the customizer. </p> <p>Basically, I've got as far as getting the text the user writes in the customizer to show on the frontend, but the default text isn't showing and I'm not sure how to get it to show.</p> <p>Below is the code I've put on the customizer.php file </p> <pre><code>$wp_customize-&gt;add_section('home_header', array( 'title' =&gt; __('Home Header', 'sincere'), 'description' =&gt; '', 'priority' =&gt; 70, )); $wp_customize-&gt;add_setting( 'home_header_title', array( 'capability' =&gt; 'edit_theme_options', 'default' =&gt; __('Clean. Simple. Sincere', 'sincere'), 'sanitize_callback' =&gt; 'sanitize_text_field', ) ); $wp_customize-&gt;add_control( 'home_header_title', array( 'type' =&gt; 'text', 'section' =&gt; 'home_header', // Add a default or your own section 'label' =&gt; __( 'Header Text' ), ) ); </code></pre> <p>This is the code I've put on my front-page.php file to try and display the text.</p> <pre><code>&lt;section class="feature-image feature-image-home feature-image-default-alt" data-type="background" data-speed="2"&gt; &lt;h1 class="entry-title"&gt;&lt;?php echo get_theme_mod('home_header_title'); ? &gt;&lt;/h1&gt; &lt;/section&gt; </code></pre> <p>Thanks in advance for any help!</p>
[ { "answer_id": 278151, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Setting the default when registering the setting doesn't make it the default on output, it just makes it the default value when the customiser is opened. To provide a default before the customiser is opened/saved you pass it as a second argument to <code>get_theme_mod()</code>:</p>\n\n<pre><code>&lt;?php echo get_theme_mod('home_header_title', __('Clean. Simple. Sincere', 'sincere') ); ?&gt;\n</code></pre>\n\n<p>This can be annoying, since you have to have the defaults written down twice. So one thing you can do is create a function the returns defaults, and use it in both places.</p>\n\n<p>The function would look like this:</p>\n\n<pre><code>function sincere_get_theme_default( $setting ) {\n $defaults = array(\n 'home_header_title' =&gt; __( 'Clean. Simple. Sincere', 'sincere' ),\n );\n\n return $defaults[$setting];\n}\n</code></pre>\n\n<p>Then you'd call it as the default value when registering your setting:</p>\n\n<pre><code>$wp_customize-&gt;add_setting( 'home_header_title', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; sincere_get_theme_default( 'home_header_title' ),\n 'sanitize_callback' =&gt; 'sanitize_text_field',\n) );\n</code></pre>\n\n<p>And also as the default argument for <code>get_theme_mod()</code>:</p>\n\n<pre><code>&lt;?php echo get_theme_mod( 'home_header_title', sincere_get_theme_default( 'home_header_title' ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 278154, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 0, "selected": false, "text": "<p>At my end your code working fine. if default text is not being shown in your text customizer section then try to change setting id or once simple try this code and hard referesh brower(<code>ctrl+F5</code>).Don't forget to try change the setting id.</p>\n\n<pre><code>add_action( 'customize_register', 'mytheme_text_customizer' );\nfunction mytheme_text_customizer($wp_customize){\n $wp_customize-&gt;add_section('home_header', array(\n 'title' =&gt; __('Home Header', 'sincere'),\n 'description' =&gt; '',\n 'priority' =&gt; 70,\n ));\n\n $wp_customize-&gt;add_setting( 'home_header_title', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; __('Clean. Simple. Sincere', 'sincere'),\n 'sanitize_callback' =&gt; 'sanitize_text_field',\n ) );\n\n $wp_customize-&gt;add_control( 'home_header_title', array(\n 'type' =&gt; 'text',\n 'section' =&gt; 'home_header', // Add a default or your own section\n 'label' =&gt; __( 'Header Text' )\n ) );\n}\n</code></pre>\n" } ]
2017/08/26
[ "https://wordpress.stackexchange.com/questions/278150", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108692/" ]
I'm currently working on my first theme and am trying to allow the user to edit some text in the customizer. Basically, I've got as far as getting the text the user writes in the customizer to show on the frontend, but the default text isn't showing and I'm not sure how to get it to show. Below is the code I've put on the customizer.php file ``` $wp_customize->add_section('home_header', array( 'title' => __('Home Header', 'sincere'), 'description' => '', 'priority' => 70, )); $wp_customize->add_setting( 'home_header_title', array( 'capability' => 'edit_theme_options', 'default' => __('Clean. Simple. Sincere', 'sincere'), 'sanitize_callback' => 'sanitize_text_field', ) ); $wp_customize->add_control( 'home_header_title', array( 'type' => 'text', 'section' => 'home_header', // Add a default or your own section 'label' => __( 'Header Text' ), ) ); ``` This is the code I've put on my front-page.php file to try and display the text. ``` <section class="feature-image feature-image-home feature-image-default-alt" data-type="background" data-speed="2"> <h1 class="entry-title"><?php echo get_theme_mod('home_header_title'); ? ></h1> </section> ``` Thanks in advance for any help!
Setting the default when registering the setting doesn't make it the default on output, it just makes it the default value when the customiser is opened. To provide a default before the customiser is opened/saved you pass it as a second argument to `get_theme_mod()`: ``` <?php echo get_theme_mod('home_header_title', __('Clean. Simple. Sincere', 'sincere') ); ?> ``` This can be annoying, since you have to have the defaults written down twice. So one thing you can do is create a function the returns defaults, and use it in both places. The function would look like this: ``` function sincere_get_theme_default( $setting ) { $defaults = array( 'home_header_title' => __( 'Clean. Simple. Sincere', 'sincere' ), ); return $defaults[$setting]; } ``` Then you'd call it as the default value when registering your setting: ``` $wp_customize->add_setting( 'home_header_title', array( 'capability' => 'edit_theme_options', 'default' => sincere_get_theme_default( 'home_header_title' ), 'sanitize_callback' => 'sanitize_text_field', ) ); ``` And also as the default argument for `get_theme_mod()`: ``` <?php echo get_theme_mod( 'home_header_title', sincere_get_theme_default( 'home_header_title' ) ); ?> ```
278,156
<p>Not sure if my assumption is correct regarding running <code>wp-cron</code> from CLI would be slightly faster than calling it via <code>wget</code> or <code>curl</code>, so either way I'm trying this:</p> <pre><code>/usr/bin/php /var/www/mywebsite.com/wp-cron.php?import_key=&lt;keyhere&gt;&amp;import_id=1&amp;action=processing </code></pre> <p>I ensured that path to PHP and the file is correct, but I keep getting this error:</p> <blockquote> <p>Could not open input file: wp-cron.php?import_key=</p> </blockquote> <p>What am I doing wrong?</p>
[ { "answer_id": 278158, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>the CLI PHP interpreter is not exactly the same as the one invoke by the webserver. A lot of enviroment information you expect the webserver to pass will not exist in the CLI, and the CLI is not assuming that its input is a URL.</p>\n\n<p>Since in CLI there is no special meaning to <code>?</code> but there is to <code>&amp;</code>, the shell enviroment passes to php <code>/var/www/mywebsite.com/wp-cron.php?import_key</code> as a parameter which should incicate which file to run.</p>\n\n<p>Instead, you should use <code>wget</code> to invoke the operation via the web server, in a proper web enviroment <code>wget mywebsite.com/wp-cron.php?import_key=&lt;keyhere&gt;&amp;import_id=1&amp;action=processing</code></p>\n\n<p>Side note: In theory you should not not need to pass parameters to cron, and then you can do <code>/usr/bin/php /var/www/mywebsite.com/wp-cron.php</code></p>\n" }, { "answer_id": 278167, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": false, "text": "<p>Or, you could use <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">WP-CLI</a> which was developed for scenarios like these. After a short installation like this</p>\n\n<pre><code>$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar\n$ chmod +x wp-cli.phar\n$ sudo mv wp-cli.phar /usr/local/bin/wp\n</code></pre>\n\n<p>You can run your scheduled tasks like so</p>\n\n<pre><code>$ wp cron event run --due-now --path=/var/www/mywebsite.com/\n</code></pre>\n\n<p>or via <code>crontab</code> (every 5mins)</p>\n\n<pre><code>*/5 * * * * wp cron event run --due-now --path=/var/www/mywebsite.com/\n</code></pre>\n\n<p>You could use a specific hook</p>\n\n<pre><code>$ wp cron event run myhook --due-now --path=/var/www/mywebsite.com/\n</code></pre>\n\n<p>or use the <a href=\"https://developer.wordpress.org/cli/commands/cron/event/run/\" rel=\"noreferrer\"><code>--url</code> parameter</a>.</p>\n" } ]
2017/08/26
[ "https://wordpress.stackexchange.com/questions/278156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16113/" ]
Not sure if my assumption is correct regarding running `wp-cron` from CLI would be slightly faster than calling it via `wget` or `curl`, so either way I'm trying this: ``` /usr/bin/php /var/www/mywebsite.com/wp-cron.php?import_key=<keyhere>&import_id=1&action=processing ``` I ensured that path to PHP and the file is correct, but I keep getting this error: > > Could not open input file: wp-cron.php?import\_key= > > > What am I doing wrong?
Or, you could use [WP-CLI](http://wp-cli.org/) which was developed for scenarios like these. After a short installation like this ``` $ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar $ chmod +x wp-cli.phar $ sudo mv wp-cli.phar /usr/local/bin/wp ``` You can run your scheduled tasks like so ``` $ wp cron event run --due-now --path=/var/www/mywebsite.com/ ``` or via `crontab` (every 5mins) ``` */5 * * * * wp cron event run --due-now --path=/var/www/mywebsite.com/ ``` You could use a specific hook ``` $ wp cron event run myhook --due-now --path=/var/www/mywebsite.com/ ``` or use the [`--url` parameter](https://developer.wordpress.org/cli/commands/cron/event/run/).
278,190
<p>I have a custom search query that return results correctly, but when i tried to paginate the results,it shows the content of the first page. when I click on 'next'or the number of the page the search page reloads and the link changes from localhost/wordpress/search/?search_input=art&amp;search=</p> <p>to </p> <p>localhost/wordpress/search/page/2/?search_input=art&amp;search while number 1 of pages remains unclickable, <a href="https://i.stack.imgur.com/cECkK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cECkK.png" alt="enter image description here"></a> and the content of the page remains the same. I've tried documentation <a href="https://codex.wordpress.org/Pagination" rel="nofollow noreferrer">Codex</a>,YouTube tutorials, <a href="https://wordpress.stackexchange.com/questions/264618/pagination-not-working-for-custom-search-form-custom-result-template">StackExchange</a>, and many other.</p> <p>I have tried modifying the 'paged' argument manually by setting it to 2 then 3 and it displayed the second and 3rd pages correctly while page 1 still unclickable. by the way , i put the search query in a function, and i used a free HTML template for the site (i am in training). can anybody see where is my fault, please. HERE IS THE CODE`</p> <pre><code> &lt;div class="col-sm-9 padding-right"&gt; &lt;div class="features_items"&gt; &lt;?php $book ; $search_text = get_query_var('search_input'); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $book = bbx_search($search_text,$paged); $post_count = $book -&gt;post_count; echo '&lt;h2 class="title text-center"&gt;Search Results : '.$post_count .'&lt;/h2&gt;'; ?&gt; &lt;?php while($book -&gt; have_posts()){ $book-&gt;the_post(); $book_price = get_post_meta( get_the_ID(), 'book_price',true); $author_name = get_post_meta( get_the_ID(), 'author_name',true); echo '&lt;div class="col-sm-4"&gt;'; echo '&lt;div class="product-image-wrapper"&gt;'; echo '&lt;div class="single-products"&gt;'; echo '&lt;div class="productinfo text-center"&gt;'; $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ),'thumbnail' ); // or the_post_thumbnail('medium'); if ($image) : echo '&lt;img src="'. $image[0].'" alt="" /&gt;'; endif; echo '&lt;h2&gt; $'.$book_price .'&lt;/h2&gt;'; echo '&lt;p&gt;'. the_title().'&lt;/p&gt;'; echo '&lt;a href="'.esc_url( add_query_arg( 'book_id', get_the_ID(), site_url('/cart'))).'" class="btn btn-default add-to-cart"&gt;&lt;i class="fa fa-shopping-cart"&gt;&lt;/i&gt;Add to cart&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;'; } ?&gt; &lt;nav class="prev-next-posts"&gt; &lt;?php echo paginate_links(array ( 'total'=&gt; $book-&gt;max_num_pages )); ?&gt; &lt;/nav&gt; &lt;?php new WP_Query(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>//-----------in functions file</p> <pre><code>function bbx_search($search_text, $paged){ $args1 = array( 'post_type' =&gt; 'book', 'post_status'=&gt; 'publish', 'order'=&gt; 'DSC', 'orderby' =&gt; 'publish_date', 'posts_per_page' =&gt; 3, 'paged' =&gt; $paged, 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'author_name', 'value' =&gt; $search_text, 'type' =&gt; 'text','compare' =&gt; 'like'), array( 'key' =&gt; 'book_description','value' =&gt; $search_text, 'type' =&gt; 'text','compare' =&gt; 'like'), array( 'key' =&gt; 'bbx_category','value' =&gt; $search_text, 'type' =&gt; 'text','compare' =&gt; 'like'), array( 'key' =&gt; 'post_tag','value' =&gt; $search_text, 'type' =&gt; 'text','compare' =&gt; 'like'), ) ); return new WP_Query( $args1 ); </code></pre> <p>}</p>
[ { "answer_id": 278198, "author": "inarilo", "author_id": 17923, "author_profile": "https://wordpress.stackexchange.com/users/17923", "pm_score": 0, "selected": false, "text": "<p>You need to pass more values to <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow noreferrer\">paginate_links</a>, it says:</p>\n\n<p>\"Even if the whole arguments array is marked optional, the function will output nothing if you do not specify the needed arguments.\"</p>\n\n<p>So pass all values that you don't want to use the default value for, e.g.:</p>\n\n<pre><code>echo paginate_links(array (\n 'current' =&gt; $paged,\n 'total'=&gt; $book-&gt;max_num_pages\n ));\n</code></pre>\n" }, { "answer_id": 278239, "author": "user283686", "author_id": 126630, "author_profile": "https://wordpress.stackexchange.com/users/126630", "pm_score": 3, "selected": true, "text": "<p>the problem was that the get_query_var('paged')or 'page' couldn't read the value .. I don't know why? .. but it always returns 0; and the check sets $paged to 1 each time ... so I got around it, and got the page number from the URL >>> It worked for me on localhost, but I've no clue if it works on a host... for your info: I work on WordPress 4.8.1, and use PHP server WAMP 3.0.6 X64 >>> replace</p>\n\n<p><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;</code></p>\n\n<p>with</p>\n\n<p><code>$p = explode(\"/\", $_SERVER['REQUEST_URI']);\n $pag = (int)($p[4]*1);\n if ($pag == 0 || $pag== null){$paged =1;} else {$paged=$pag;}</code></p>\n" } ]
2017/08/26
[ "https://wordpress.stackexchange.com/questions/278190", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126630/" ]
I have a custom search query that return results correctly, but when i tried to paginate the results,it shows the content of the first page. when I click on 'next'or the number of the page the search page reloads and the link changes from localhost/wordpress/search/?search\_input=art&search= to localhost/wordpress/search/page/2/?search\_input=art&search while number 1 of pages remains unclickable, [![enter image description here](https://i.stack.imgur.com/cECkK.png)](https://i.stack.imgur.com/cECkK.png) and the content of the page remains the same. I've tried documentation [Codex](https://codex.wordpress.org/Pagination),YouTube tutorials, [StackExchange](https://wordpress.stackexchange.com/questions/264618/pagination-not-working-for-custom-search-form-custom-result-template), and many other. I have tried modifying the 'paged' argument manually by setting it to 2 then 3 and it displayed the second and 3rd pages correctly while page 1 still unclickable. by the way , i put the search query in a function, and i used a free HTML template for the site (i am in training). can anybody see where is my fault, please. HERE IS THE CODE` ``` <div class="col-sm-9 padding-right"> <div class="features_items"> <?php $book ; $search_text = get_query_var('search_input'); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $book = bbx_search($search_text,$paged); $post_count = $book ->post_count; echo '<h2 class="title text-center">Search Results : '.$post_count .'</h2>'; ?> <?php while($book -> have_posts()){ $book->the_post(); $book_price = get_post_meta( get_the_ID(), 'book_price',true); $author_name = get_post_meta( get_the_ID(), 'author_name',true); echo '<div class="col-sm-4">'; echo '<div class="product-image-wrapper">'; echo '<div class="single-products">'; echo '<div class="productinfo text-center">'; $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ),'thumbnail' ); // or the_post_thumbnail('medium'); if ($image) : echo '<img src="'. $image[0].'" alt="" />'; endif; echo '<h2> $'.$book_price .'</h2>'; echo '<p>'. the_title().'</p>'; echo '<a href="'.esc_url( add_query_arg( 'book_id', get_the_ID(), site_url('/cart'))).'" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a> </div> </div> </div> </div>'; } ?> <nav class="prev-next-posts"> <?php echo paginate_links(array ( 'total'=> $book->max_num_pages )); ?> </nav> <?php new WP_Query(); ?> </div> </div> </div> </div> </section> ``` //-----------in functions file ``` function bbx_search($search_text, $paged){ $args1 = array( 'post_type' => 'book', 'post_status'=> 'publish', 'order'=> 'DSC', 'orderby' => 'publish_date', 'posts_per_page' => 3, 'paged' => $paged, 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'author_name', 'value' => $search_text, 'type' => 'text','compare' => 'like'), array( 'key' => 'book_description','value' => $search_text, 'type' => 'text','compare' => 'like'), array( 'key' => 'bbx_category','value' => $search_text, 'type' => 'text','compare' => 'like'), array( 'key' => 'post_tag','value' => $search_text, 'type' => 'text','compare' => 'like'), ) ); return new WP_Query( $args1 ); ``` }
the problem was that the get\_query\_var('paged')or 'page' couldn't read the value .. I don't know why? .. but it always returns 0; and the check sets $paged to 1 each time ... so I got around it, and got the page number from the URL >>> It worked for me on localhost, but I've no clue if it works on a host... for your info: I work on WordPress 4.8.1, and use PHP server WAMP 3.0.6 X64 >>> replace `$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;` with `$p = explode("/", $_SERVER['REQUEST_URI']); $pag = (int)($p[4]*1); if ($pag == 0 || $pag== null){$paged =1;} else {$paged=$pag;}`
278,204
<p>Is it possible to delete a huge number of wordpress posts through SQL query using phpmyadmin by using a permalink list of posts that I want to delete ?</p>
[ { "answer_id": 278368, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 0, "selected": false, "text": "<p>It depends on permalinks. Permalinks can contain more then just the post name (slug). Also, post names don't have to be unique. So, it is possible, but it depends on many other factors.</p>\n" }, { "answer_id": 278379, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 2, "selected": true, "text": "<p>Yes you can.\nTo delete posts with inherit post meta, use following code:</p>\n\n<pre><code>DELETE\np,pm\nFROM wp_posts p\nJOIN wp_postmeta pm ON pm.post_id = p.id\nWHERE p.post_name IN ('post-1', 'post-2', 'post-3')\n</code></pre>\n\n<p>Pass slugs array to WHERE clause.</p>\n\n<p>If you want to delete only posts w/out postmeta (for some reason), use this code:</p>\n\n<pre><code>DELETE\nFROM wp_posts\nWHERE post_name IN ('post-1', 'post-2', 'post-3')\n</code></pre>\n" } ]
2017/08/26
[ "https://wordpress.stackexchange.com/questions/278204", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65292/" ]
Is it possible to delete a huge number of wordpress posts through SQL query using phpmyadmin by using a permalink list of posts that I want to delete ?
Yes you can. To delete posts with inherit post meta, use following code: ``` DELETE p,pm FROM wp_posts p JOIN wp_postmeta pm ON pm.post_id = p.id WHERE p.post_name IN ('post-1', 'post-2', 'post-3') ``` Pass slugs array to WHERE clause. If you want to delete only posts w/out postmeta (for some reason), use this code: ``` DELETE FROM wp_posts WHERE post_name IN ('post-1', 'post-2', 'post-3') ```
278,251
<p>I'm currently trying to resize all the featured images on my theme to 1140 x 500. I've placed this code in my function.php file</p> <pre><code> if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); // Default Post thumbnail dimensions (cropped) set_post_thumbnail_size( 1140, 500, true ); } </code></pre> <p>And this code in my loop.</p> <pre><code>&lt;?php if ( has_post_thumbnail() ) { // check for feature image ?&gt; &lt;div class="post-image"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/div&gt;&lt;!-- post-image --&gt; &lt;?php } ?&gt; </code></pre> <p>Thanks for any help.</p>
[ { "answer_id": 278262, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Setting the size itself does not crop the existing images. You need to regenerate the existing thumbnails too.</p>\n\n<p>There are a couple of plugins for this, but I personally downloaded and used <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">Regenerate Thumbnails</a>. Install the plugin, and head over to <code>Tools &gt; Regenerate Thumbnails</code>. There you can regenerate thumbnails for images that exist in your media library, replacing the old thumbnails.</p>\n" }, { "answer_id": 278290, "author": "Jitender Singh", "author_id": 110753, "author_profile": "https://wordpress.stackexchange.com/users/110753", "pm_score": 0, "selected": false, "text": "<p>very easy steps without plugin:</p>\n\n<p>1) in your functions.php</p>\n\n<pre><code>if ( function_exists( 'add_theme_support' ) ) {\n add_theme_support( 'post-thumbnails' );\n // Default Post thumbnail dimensions (cropped)\n add_image_size( 'banner_image', 1140, 500, true );\n }\n</code></pre>\n\n<p>2) this code in your loop eg. index.php, single.php etc.</p>\n\n<pre><code>&lt;?php if ( has_post_thumbnail() ) { // check for feature image ?&gt;\n&lt;div class=\"post-image\"&gt;\n &lt;?php the_post_thumbnail('banner_image'); ?&gt;\n&lt;/div&gt;&lt;!-- post-image --&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" } ]
2017/08/27
[ "https://wordpress.stackexchange.com/questions/278251", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108692/" ]
I'm currently trying to resize all the featured images on my theme to 1140 x 500. I've placed this code in my function.php file ``` if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); // Default Post thumbnail dimensions (cropped) set_post_thumbnail_size( 1140, 500, true ); } ``` And this code in my loop. ``` <?php if ( has_post_thumbnail() ) { // check for feature image ?> <div class="post-image"> <?php the_post_thumbnail(); ?> </div><!-- post-image --> <?php } ?> ``` Thanks for any help.
Setting the size itself does not crop the existing images. You need to regenerate the existing thumbnails too. There are a couple of plugins for this, but I personally downloaded and used [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/). Install the plugin, and head over to `Tools > Regenerate Thumbnails`. There you can regenerate thumbnails for images that exist in your media library, replacing the old thumbnails.
278,258
<p>I have a multisite installation running in a sub-directory on the server - purely for the reason that it has become my MO to develop a new site for a client in a "WordPress" directory while their old site is live, and then when it is ready, I change the <code>index.php</code> and <code>.htaccess</code> files and voila, the site is live. </p> <p>For the first time I have a multisite (sub-directory not sub-domain) in its own folder (not in the root) and now the process is different to what I was used to. </p> <p>I have googled extensively and found info on the modifications to the <code>.htaccess</code> file - but I get <em>"Error establishing a database connection"</em> error when trying to access the root on my browser. <code>Root.com/wordpress/</code> still works perfectly. </p> <p>I've amended the <code>.htacccess</code> file with this code - as per WordPress.org: </p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>And I've added the name of the subdirectory into the <code>index.php</code> file as per making a single site live - but now the establishing connection with the database error.</p> <p>Could you please help with the next step - I sense I am close!</p>
[ { "answer_id": 278281, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>That's an error with your database credentials, as stored in wp-config.php . Check/fix those credentials to let WP access the database. (As the googles would tell you if you searched on the error message....)</p>\n" }, { "answer_id": 278418, "author": "Carin", "author_id": 126669, "author_profile": "https://wordpress.stackexchange.com/users/126669", "pm_score": 0, "selected": false, "text": "<p>After i was assured that the problem was indeed in the wp-config.php file and nowhere else, all i had to was change, under the /* Multisite */ section:</p>\n\n<pre><code>define('DOMAIN_CURRENT_SITE', 'root.com');\n</code></pre>\n\n<p>to</p>\n\n<pre><code>define('DOMAIN_CURRENT_SITE', 'root.com/wordpress');\n</code></pre>\n\n<p>et voila!</p>\n" } ]
2017/08/27
[ "https://wordpress.stackexchange.com/questions/278258", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126669/" ]
I have a multisite installation running in a sub-directory on the server - purely for the reason that it has become my MO to develop a new site for a client in a "WordPress" directory while their old site is live, and then when it is ready, I change the `index.php` and `.htaccess` files and voila, the site is live. For the first time I have a multisite (sub-directory not sub-domain) in its own folder (not in the root) and now the process is different to what I was used to. I have googled extensively and found info on the modifications to the `.htaccess` file - but I get *"Error establishing a database connection"* error when trying to access the root on my browser. `Root.com/wordpress/` still works perfectly. I've amended the `.htacccess` file with this code - as per WordPress.org: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] </IfModule> # END WordPress ``` And I've added the name of the subdirectory into the `index.php` file as per making a single site live - but now the establishing connection with the database error. Could you please help with the next step - I sense I am close!
That's an error with your database credentials, as stored in wp-config.php . Check/fix those credentials to let WP access the database. (As the googles would tell you if you searched on the error message....)
278,286
<p>I have a custom field for an image, and using it this way:</p> <pre><code>&lt;?php $item_img = get_sub_field('image'); ?&gt; &lt;img src="&lt;?php echo $item_img ?&gt;" /&gt; </code></pre> <p>But I want to use the thumbnail version of the image, as set to 150x150 in wordpress.</p> <p>How do I do that with this type of setup?</p> <p>Do I have to set a custom <code>add_image_size()</code> or does wordpress have duplicated thumbmail size images?</p>
[ { "answer_id": 278271, "author": "sakarya", "author_id": 51376, "author_profile": "https://wordpress.stackexchange.com/users/51376", "pm_score": -1, "selected": false, "text": "<p>I can't say, how do you find out how they did it, but I can say something for security.</p>\n\n<ol>\n<li>Always update your wordpress, themes and plugins.</li>\n<li><p>Disable file edit. in wp-config.php</p>\n\n<p><code>define('DISALLOW_FILE_EDIT', true);</code></p></li>\n<li><p>Deny acces to wp-config.php file. in .htaccess</p></li>\n</ol>\n\n<p><code>&lt;files wp-config.php&gt;\norder allow,deny\ndeny from all\n&lt;/files&gt;</code></p>\n\n<ol start=\"4\">\n<li><p>Deny acces to xmlrpc.php file. in .htaccess</p>\n\n<p><code>&lt;files xmlrpc.php&gt;\norder allow,deny\ndeny from all\n&lt;/files&gt;</code></p></li>\n</ol>\n\n<p>Maybe, you can find the answers, your server logs.</p>\n" }, { "answer_id": 278280, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>There are many things that I do to check a possible hack on the site. Changing FTP users/passwords, reinstalling WP, reinstalling themes/plugins, changing user account passwords (especially admin level), change hosting credentials.</p>\n\n<p>I wrote an entry on my own site to remind me (most of the stuff there is my own 'notes' to myself). May be helpful: <a href=\"http://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">http://securitydawg.com/recovering-from-a-hacked-wordpress-site/</a> (Not trying to promote my site; there are many googles on how to recover from a hacked site. That link is just my personal list.)</p>\n" }, { "answer_id": 278289, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general if a file is being overwritten, it means that your permissions are lacking. in general no one should be able to write to code files, not other user and IMHO not even the webserver (yes, this will make running updates from the admin somewhat harder, you have to select between convenience and security)</p>\n\n<p>As for your assumption that nothing else was changed <strong>that is just false</strong> and you should do a fall restore from a backup. If someone was able to change your code he could easily created an admin user for himself and covered his tracks. Might not have happened this time but better be safe than sorry.</p>\n" } ]
2017/08/28
[ "https://wordpress.stackexchange.com/questions/278286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123346/" ]
I have a custom field for an image, and using it this way: ``` <?php $item_img = get_sub_field('image'); ?> <img src="<?php echo $item_img ?>" /> ``` But I want to use the thumbnail version of the image, as set to 150x150 in wordpress. How do I do that with this type of setup? Do I have to set a custom `add_image_size()` or does wordpress have duplicated thumbmail size images?
There are many things that I do to check a possible hack on the site. Changing FTP users/passwords, reinstalling WP, reinstalling themes/plugins, changing user account passwords (especially admin level), change hosting credentials. I wrote an entry on my own site to remind me (most of the stuff there is my own 'notes' to myself). May be helpful: <http://securitydawg.com/recovering-from-a-hacked-wordpress-site/> (Not trying to promote my site; there are many googles on how to recover from a hacked site. That link is just my personal list.)
278,293
<p>One of my WordPress templates is <strong>completely different</strong> and requires different css and js (but still needs needs the core JQuery as well as the bootstrap 3 css/js).</p> <p>So, how would I go about removing the generic style.css and also a few other css files (and js files) that are site wide? I think that it is a variation of the below?</p> <p>I'm new to WP!</p> <pre><code> // Unique Page Template if (is_page_template(specific-template.php')): // Remove Site-wide CSS wp_dequeue_style('generic styles', get_stylesheet_uri(), array(), '1.2'); // And this would enqueue the unique css wp_enqueue_style( 'unque to this template css', get_template_directory_uri() . '/css/unique-to-this-template.css', array(), '1.0'); endif; </code></pre> <p>Is my logic correct here?</p> <p>Thanks for all direction</p>
[ { "answer_id": 278271, "author": "sakarya", "author_id": 51376, "author_profile": "https://wordpress.stackexchange.com/users/51376", "pm_score": -1, "selected": false, "text": "<p>I can't say, how do you find out how they did it, but I can say something for security.</p>\n\n<ol>\n<li>Always update your wordpress, themes and plugins.</li>\n<li><p>Disable file edit. in wp-config.php</p>\n\n<p><code>define('DISALLOW_FILE_EDIT', true);</code></p></li>\n<li><p>Deny acces to wp-config.php file. in .htaccess</p></li>\n</ol>\n\n<p><code>&lt;files wp-config.php&gt;\norder allow,deny\ndeny from all\n&lt;/files&gt;</code></p>\n\n<ol start=\"4\">\n<li><p>Deny acces to xmlrpc.php file. in .htaccess</p>\n\n<p><code>&lt;files xmlrpc.php&gt;\norder allow,deny\ndeny from all\n&lt;/files&gt;</code></p></li>\n</ol>\n\n<p>Maybe, you can find the answers, your server logs.</p>\n" }, { "answer_id": 278280, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>There are many things that I do to check a possible hack on the site. Changing FTP users/passwords, reinstalling WP, reinstalling themes/plugins, changing user account passwords (especially admin level), change hosting credentials.</p>\n\n<p>I wrote an entry on my own site to remind me (most of the stuff there is my own 'notes' to myself). May be helpful: <a href=\"http://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">http://securitydawg.com/recovering-from-a-hacked-wordpress-site/</a> (Not trying to promote my site; there are many googles on how to recover from a hacked site. That link is just my personal list.)</p>\n" }, { "answer_id": 278289, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general if a file is being overwritten, it means that your permissions are lacking. in general no one should be able to write to code files, not other user and IMHO not even the webserver (yes, this will make running updates from the admin somewhat harder, you have to select between convenience and security)</p>\n\n<p>As for your assumption that nothing else was changed <strong>that is just false</strong> and you should do a fall restore from a backup. If someone was able to change your code he could easily created an admin user for himself and covered his tracks. Might not have happened this time but better be safe than sorry.</p>\n" } ]
2017/08/28
[ "https://wordpress.stackexchange.com/questions/278293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
One of my WordPress templates is **completely different** and requires different css and js (but still needs needs the core JQuery as well as the bootstrap 3 css/js). So, how would I go about removing the generic style.css and also a few other css files (and js files) that are site wide? I think that it is a variation of the below? I'm new to WP! ``` // Unique Page Template if (is_page_template(specific-template.php')): // Remove Site-wide CSS wp_dequeue_style('generic styles', get_stylesheet_uri(), array(), '1.2'); // And this would enqueue the unique css wp_enqueue_style( 'unque to this template css', get_template_directory_uri() . '/css/unique-to-this-template.css', array(), '1.0'); endif; ``` Is my logic correct here? Thanks for all direction
There are many things that I do to check a possible hack on the site. Changing FTP users/passwords, reinstalling WP, reinstalling themes/plugins, changing user account passwords (especially admin level), change hosting credentials. I wrote an entry on my own site to remind me (most of the stuff there is my own 'notes' to myself). May be helpful: <http://securitydawg.com/recovering-from-a-hacked-wordpress-site/> (Not trying to promote my site; there are many googles on how to recover from a hacked site. That link is just my personal list.)
278,296
<p>I'm bulk deleting posts from my WordPress site using the function <code>wp_delete_post</code> and categories using <code>wp_delete_category</code>. That are about 100.000 posts and 4.000 categories, and after a while I get a PHP Error </p> <p><code>PHP Fatal error: Allowed memory size of ... bytes exhausted</code></p> <p>That's what I do inside my code:</p> <pre><code>// get all IDs from the posts and categories $delete_categories = $wpdb-&gt;get_col("SELECT DISTINCT(j.term_id)..."); $delete_posts = $wpdb-&gt;get_col("SELECT DISTINCT(j.post_id)..."); $delete_parent_categories = $wpdb-&gt;get_col("SELECT tt.parent FROM $tbl_term_taxonomy tt ..."); // I removed the SQL statements for a better reading foreach ($delete_posts as $dp) { echo "deleting post ".$dp."\n"; wp_delete_post($dp, true); unset($dp); } unset($delete_posts); foreach ($delete_categories as $dc) { echo "deleting category ".$dc."\n"; wp_delete_category($dc); unset($dc); } unset($delete_categories); foreach ($delete_parent_categories as $dc) { echo "deleting category ".$dc."\n"; wp_delete_category($dc); unset($dc); } unset($delete_parent_categories); </code></pre> <p>Deleting the posts works, deleting some categories also works - but at some point the memory limit is exceeded and the script is terminated. Setting the memory limit to 1024MB doesn't look like a perfect solution for me.</p> <p>Is there a way to free up the memory that the WordPress functions allocated?</p>
[ { "answer_id": 278313, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 2, "selected": false, "text": "<p>The code you use also uses WordPress functions that will first load posts (and other relevant data) in memory first and cache them using object cache. So, to delete 100.000 posts, your code will try to load each post in memory and that can take a lot of memory. I am not sure how high PHP memory is set in your case, but, you can either limit the deletion to 1000 or 5000 posts at once or increase PHP memory.</p>\n" }, { "answer_id": 278345, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>With so many posts to delete it is better to escape the limitations of the webserver and use wp-cli <a href=\"https://wordpress.stackexchange.com/questions/241543/wp-cli-bulk-delete-posts-from-specific-category\">relevant example</a>. The other alternative is to not use a live server, but to offload everything to your local development server, run your code there, and upload things back.</p>\n" }, { "answer_id": 278386, "author": "johnh10", "author_id": 50675, "author_profile": "https://wordpress.stackexchange.com/users/50675", "pm_score": 0, "selected": false, "text": "<p>I recommend your first line of code be</p>\n\n<pre><code>wp_suspend_cache_addition( true );\n</code></pre>\n\n<p>This will stop the data from being added to the cache and bloat filling memory.</p>\n" } ]
2017/08/28
[ "https://wordpress.stackexchange.com/questions/278296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126097/" ]
I'm bulk deleting posts from my WordPress site using the function `wp_delete_post` and categories using `wp_delete_category`. That are about 100.000 posts and 4.000 categories, and after a while I get a PHP Error `PHP Fatal error: Allowed memory size of ... bytes exhausted` That's what I do inside my code: ``` // get all IDs from the posts and categories $delete_categories = $wpdb->get_col("SELECT DISTINCT(j.term_id)..."); $delete_posts = $wpdb->get_col("SELECT DISTINCT(j.post_id)..."); $delete_parent_categories = $wpdb->get_col("SELECT tt.parent FROM $tbl_term_taxonomy tt ..."); // I removed the SQL statements for a better reading foreach ($delete_posts as $dp) { echo "deleting post ".$dp."\n"; wp_delete_post($dp, true); unset($dp); } unset($delete_posts); foreach ($delete_categories as $dc) { echo "deleting category ".$dc."\n"; wp_delete_category($dc); unset($dc); } unset($delete_categories); foreach ($delete_parent_categories as $dc) { echo "deleting category ".$dc."\n"; wp_delete_category($dc); unset($dc); } unset($delete_parent_categories); ``` Deleting the posts works, deleting some categories also works - but at some point the memory limit is exceeded and the script is terminated. Setting the memory limit to 1024MB doesn't look like a perfect solution for me. Is there a way to free up the memory that the WordPress functions allocated?
The code you use also uses WordPress functions that will first load posts (and other relevant data) in memory first and cache them using object cache. So, to delete 100.000 posts, your code will try to load each post in memory and that can take a lot of memory. I am not sure how high PHP memory is set in your case, but, you can either limit the deletion to 1000 or 5000 posts at once or increase PHP memory.
278,354
<p>I have a wordpress site in a language that aligns RTL, but some pages are in English. These pages look terrible, however, because the English text is aligned with the RTL language, and punctuation, etc. appear on the wrong the side.</p> <p>How can I set the language for a single page or several individual pages?</p>
[ { "answer_id": 278355, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/locale\" rel=\"noreferrer\"><code>locale</code></a> filter that allows you to set the locale specifically. You can check the current page, and alter the value based on that.</p>\n\n<pre><code>add_filter('locale', 'change_my_locale');\nfunction change_my_locale( $locale ) {\n if ( is_page('slug-here') ) {\n return 'en_US';\n }\n return $locale;\n}\n</code></pre>\n" }, { "answer_id": 278357, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 2, "selected": false, "text": "<p>You should use <code>locale</code> hook to solve your task. </p>\n\n<p>Important note that you can't add it in theme and use <code>is_page</code> function, because it will define later.</p>\n\n<p>So you have to create <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow noreferrer\">plugin</a> or <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">must use plugin</a> with url parsing this way:</p>\n\n<p>\n\n<pre><code>add_filter('locale', function($locale) {\n $path = trim($_SERVER['REQUEST_URI'], \"/\");\n\n // get last part as slug\n $arr = explode(\"/\", $path);\n $slug = end($arr);\n\n if($slug === 'MY_SLUG')\n return 'ru_RU';\n\n return $locale;\n});\n</code></pre>\n\n<p>Related answer: <a href=\"https://wordpress.stackexchange.com/questions/49451/change-locale-at-runtime\">Change locale at runtime?</a></p>\n" }, { "answer_id": 278573, "author": "maxime schoeni", "author_id": 81094, "author_profile": "https://wordpress.stackexchange.com/users/81094", "pm_score": 0, "selected": false, "text": "<p>Here is a fix for the problem of timing in the solution by @jack-johansson:</p>\n\n<pre><code>add_action('wp', function() {\n if ( is_page('slug-here') ) {\n add_filter('locale', function( $locale ) {\n return 'en_US';\n });\n }\n});\n</code></pre>\n" }, { "answer_id": 356273, "author": "Kenan Hodzic", "author_id": 180976, "author_profile": "https://wordpress.stackexchange.com/users/180976", "pm_score": 1, "selected": false, "text": "<p>I needed something similar for translation &amp; direction purposes.</p>\n\n<p>By defining $direction for each post, 'ltr' or 'rtl'...using <a href=\"https://wordpress.org/plugins/contents-direction/\" rel=\"nofollow noreferrer\">this simple plugin</a> ...\nI edited the plugin by adding following action to plugin.php file:</p>\n\n<pre><code>add_action('wp', function($locale){\n // get post meta from database, which is generated by the plugin\n global $post;\n $direction = get_post_meta($post-&gt;ID, 'os_custom_box_for_rtl', true);\n // set locale language based on post meta\n $locale = ($direction == 'rtl')? 'ar':'en_US'; // ...or use your own locale codes\n // if not admin area, do switch! it will work for frontend only per specific page/post\n is_admin() or switch_to_locale( $locale );\n});\n</code></pre>\n" } ]
2017/08/28
[ "https://wordpress.stackexchange.com/questions/278354", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126536/" ]
I have a wordpress site in a language that aligns RTL, but some pages are in English. These pages look terrible, however, because the English text is aligned with the RTL language, and punctuation, etc. appear on the wrong the side. How can I set the language for a single page or several individual pages?
The [`locale`](https://codex.wordpress.org/Plugin_API/Filter_Reference/locale) filter that allows you to set the locale specifically. You can check the current page, and alter the value based on that. ``` add_filter('locale', 'change_my_locale'); function change_my_locale( $locale ) { if ( is_page('slug-here') ) { return 'en_US'; } return $locale; } ```
278,385
<p>I migrated my WordPress install and DB to another server (same domain). And I am getting this:</p> <p><a href="https://i.stack.imgur.com/KhPai.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhPai.png" alt="enter image description here"></a></p> <p>Also everything is where it should be (including file and db permissions and other specific settings):</p> <p><a href="https://i.stack.imgur.com/LuyrZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LuyrZ.png" alt="enter image description here"></a></p> <p>And I can not just get pass this:</p> <p><a href="https://i.stack.imgur.com/MRq90.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MRq90.png" alt="enter image description here"></a></p> <p>And I can also confirm that everything works just fine with a blank new install. But I need to recover the current DB. Where should I start? What additional info should I provide to you guys?</p> <p><strong>EDIT 1:</strong> Errors info as requested. <a href="https://i.stack.imgur.com/tndvy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tndvy.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/ZwSnb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZwSnb.png" alt="enter image description here"></a></p> <p><strong>EDIT 2</strong> Running Standard WordPress Database repair. <a href="https://i.stack.imgur.com/lq1IO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lq1IO.png" alt="enter image description here"></a></p> <p><strong>EDIT 3</strong> More awkward bugs.</p> <p><a href="https://i.stack.imgur.com/T2RlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T2RlH.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/okjVW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/okjVW.png" alt="enter image description here"></a></p>
[ { "answer_id": 278403, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I always find it easiest to use the WP Clone plugin <a href=\"https://wordpress.org/plugins/wp-clone-by-wp-academy/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-clone-by-wp-academy/</a> . Very easy, takes care of all the manual work, and works every time.</p>\n\n<p>Just install on source and target systems (same WP version, of course). Backup the source, restore to the target. Done.</p>\n\n<p>You can do it manually. But it takes some skill and perseverance. I just use the WP Clone plugin because it works...and I am too lazy to do it the hard way.</p>\n" }, { "answer_id": 279194, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You didn't mention what have you done so far to migrate your installation, but I'm going to write the full procedure.</p>\n\n<h2>Backing Up the Old Database</h2>\n\n<p>You need to create an exact duplicate of your database, to transfer it to your new server. There might be an encoding issue here, so to do this, login into your panel's PhpMyAdmin, and then:</p>\n\n<ol>\n<li>Select the database's name from the left sidebar</li>\n<li>Click the <code>Export</code> button on the top navigation menu</li>\n<li>Click <code>Custom</code> under export method</li>\n<li>Click <code>Select All</code> under the tables</li>\n<li>Choose UTF-8 as encoding, as stated in the screenshot below</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/PksdP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PksdP.jpg\" alt=\"Exporting WordPress database\"></a></p>\n\n<p>Now you can export and save the file.</p>\n\n<h2>Restoring the Back-up</h2>\n\n<p>To restore the backup, you should first create a database with the same name of your previous database. After you did so, choose it from the left sidebar, and click <code>Import</code> from the top navigation menu. Choose the file by clicking the browse button, and then set the encoding to UTF-8. </p>\n\n<p>Click Import to finish the importing (don't forget to remove any existing tables first).</p>\n\n<p>Editing <code>wp-config.php</code></p>\n\n<p>After importing the database, you need to modify the <code>wp-config.php</code> file. If you don't do this, you will be redirected to an installation page, this is why you are getting <em>\"Table Exists\"</em> error instead of directly being redirected to <code>wp-login.php</code>.</p>\n\n<p>These 4 lines need to be modified to match your new database's configuration:</p>\n\n<pre><code>/** The name of the database for WordPress */\ndefine('DB_NAME', 'database_name');\n\n/** MySQL database username */\ndefine('DB_USER', 'username');\n\n/** MySQL database password */\ndefine('DB_PASSWORD', 'password');\n\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n</code></pre>\n\n<p>If you do this properly, you will be redirected to <code>wp-login.php</code> after you try to access <code>/wp-admin/</code>.</p>\n\n<h2>Updating the URLs</h2>\n\n<p>If you have also changed your domain's address, you need to take 2 further steps. First, you should update the core URLs for your blog's home page. To do so, open the <code>wp_options</code> table in PhpMyAdmin, and modify the <code>siteurl</code> and <code>home</code> values to match your new domain. These are the first two options.</p>\n\n<p>Afterward, you have to do a full search and replace in your database to update the old URLs. Since there are serialized data in the database, you should avoid doing this by a plain text editor. Instead, use a plugin such as <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better Search Replace</a>.</p>\n\n<p>Head over to <code>Tools &gt; Better Search Replace</code>, and replace <code>old.com</code> with <code>new.com</code>. Pay attention to spelling and letter cases, this can matter a lot. If you are switching to HTTPS, you should replace <code>http://old.com</code> with <code>https://new.com</code>.</p>\n\n<h2>A Final Note</h2>\n\n<p>I would also use the same WordPress version on the old server for migration. After migrating, you can update to the latest version in the admin panel.</p>\n" }, { "answer_id": 279243, "author": "The Filipino Freelancer", "author_id": 126661, "author_profile": "https://wordpress.stackexchange.com/users/126661", "pm_score": 0, "selected": false, "text": "<p>Changing your WordPress database collation might fix your issue.\nYou may open your wp-config file and find this part</p>\n\n<p>define( 'DB_COLLATE', '' );</p>\n\n<p>Through this, you can let wordpress use the collation that might work for your based on your database.</p>\n\n<p>For reference : <a href=\"https://codex.wordpress.org/Converting_Database_Character_Sets\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Converting_Database_Character_Sets</a></p>\n\n<p>Inmotion :<a href=\"http://www.inmotionhosting.com/support/website/wordpress/database-collation\" rel=\"nofollow noreferrer\">http://www.inmotionhosting.com/support/website/wordpress/database-collation</a></p>\n" }, { "answer_id": 279485, "author": "Jeff Mattson", "author_id": 93714, "author_profile": "https://wordpress.stackexchange.com/users/93714", "pm_score": 0, "selected": false, "text": "<p>When migrating a Wordpress website you must use a plugin if the url changes in anyway. The reason for this is the some data is stored in a serialized array. The data must be un-serialized, url changed, and then re-serialized. Always export the database using a plugin from inside the CMS for best results. I always use: </p>\n\n<pre><code> https://en-ca.wordpress.org/plugins/wp-migrate-db/ \n</code></pre>\n\n<p>It always works. If you simply do a search and replace on your database and do not take into account serialization you will break the site.</p>\n\n<p><strong>Update:</strong>\nYou can use tools to migrate the DB outside of Wordpress as long as they perform the un-serialize and re-serialize function when doing a search and replace.</p>\n" } ]
2017/08/28
[ "https://wordpress.stackexchange.com/questions/278385", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126738/" ]
I migrated my WordPress install and DB to another server (same domain). And I am getting this: [![enter image description here](https://i.stack.imgur.com/KhPai.png)](https://i.stack.imgur.com/KhPai.png) Also everything is where it should be (including file and db permissions and other specific settings): [![enter image description here](https://i.stack.imgur.com/LuyrZ.png)](https://i.stack.imgur.com/LuyrZ.png) And I can not just get pass this: [![enter image description here](https://i.stack.imgur.com/MRq90.png)](https://i.stack.imgur.com/MRq90.png) And I can also confirm that everything works just fine with a blank new install. But I need to recover the current DB. Where should I start? What additional info should I provide to you guys? **EDIT 1:** Errors info as requested. [![enter image description here](https://i.stack.imgur.com/tndvy.png)](https://i.stack.imgur.com/tndvy.png) [![enter image description here](https://i.stack.imgur.com/ZwSnb.png)](https://i.stack.imgur.com/ZwSnb.png) **EDIT 2** Running Standard WordPress Database repair. [![enter image description here](https://i.stack.imgur.com/lq1IO.png)](https://i.stack.imgur.com/lq1IO.png) **EDIT 3** More awkward bugs. [![enter image description here](https://i.stack.imgur.com/T2RlH.png)](https://i.stack.imgur.com/T2RlH.png) [![enter image description here](https://i.stack.imgur.com/okjVW.png)](https://i.stack.imgur.com/okjVW.png)
You didn't mention what have you done so far to migrate your installation, but I'm going to write the full procedure. Backing Up the Old Database --------------------------- You need to create an exact duplicate of your database, to transfer it to your new server. There might be an encoding issue here, so to do this, login into your panel's PhpMyAdmin, and then: 1. Select the database's name from the left sidebar 2. Click the `Export` button on the top navigation menu 3. Click `Custom` under export method 4. Click `Select All` under the tables 5. Choose UTF-8 as encoding, as stated in the screenshot below [![Exporting WordPress database](https://i.stack.imgur.com/PksdP.jpg)](https://i.stack.imgur.com/PksdP.jpg) Now you can export and save the file. Restoring the Back-up --------------------- To restore the backup, you should first create a database with the same name of your previous database. After you did so, choose it from the left sidebar, and click `Import` from the top navigation menu. Choose the file by clicking the browse button, and then set the encoding to UTF-8. Click Import to finish the importing (don't forget to remove any existing tables first). Editing `wp-config.php` After importing the database, you need to modify the `wp-config.php` file. If you don't do this, you will be redirected to an installation page, this is why you are getting *"Table Exists"* error instead of directly being redirected to `wp-login.php`. These 4 lines need to be modified to match your new database's configuration: ``` /** The name of the database for WordPress */ define('DB_NAME', 'database_name'); /** MySQL database username */ define('DB_USER', 'username'); /** MySQL database password */ define('DB_PASSWORD', 'password'); /** MySQL hostname */ define('DB_HOST', 'localhost'); ``` If you do this properly, you will be redirected to `wp-login.php` after you try to access `/wp-admin/`. Updating the URLs ----------------- If you have also changed your domain's address, you need to take 2 further steps. First, you should update the core URLs for your blog's home page. To do so, open the `wp_options` table in PhpMyAdmin, and modify the `siteurl` and `home` values to match your new domain. These are the first two options. Afterward, you have to do a full search and replace in your database to update the old URLs. Since there are serialized data in the database, you should avoid doing this by a plain text editor. Instead, use a plugin such as [Better Search Replace](https://wordpress.org/plugins/better-search-replace/). Head over to `Tools > Better Search Replace`, and replace `old.com` with `new.com`. Pay attention to spelling and letter cases, this can matter a lot. If you are switching to HTTPS, you should replace `http://old.com` with `https://new.com`. A Final Note ------------ I would also use the same WordPress version on the old server for migration. After migrating, you can update to the latest version in the admin panel.
278,393
<p>I need to enqueue a style sheet in my plugin to work on the front end of Wordpress. Here is what I have. Will someone please tell me what I am doing wrong?</p> <pre><code>function add_my_stylesheet1() { wp_enqueue_style( 'myStyles', plugins_url( 'css/styles.css', __FILE__ ) ); } add_action('admin_print_styles', 'add_my_stylesheet1'); </code></pre>
[ { "answer_id": 278394, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 0, "selected": false, "text": "<p>You need to use the <code>admin_enqueue_scripts</code> hook. So your function would be like this...</p>\n\n<pre><code>function add_my_stylesheet1() {\n wp_enqueue_style( 'myStyles', plugins_url( __FILE__ ) . ' css/styles.css' );\n}\nadd_action( 'admin_enqueue_scripts', 'add_my_stylesheet1' );\n</code></pre>\n" }, { "answer_id": 278396, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You're enquing on the <strong>admin</strong>_enqueue_scripts hook, which is why it's only showing up on admin pages</p>\n\n<p>If we look at an example from the official documentation:</p>\n\n<pre><code>/**\n * Proper way to enqueue scripts and styles\n */\nfunction wpdocs_theme_name_scripts() {\n wp_enqueue_style( 'style-name', get_stylesheet_uri() );\n wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>we see the <code>wp_enqueue_scripts</code> hook being used instead. Use that hook instead of <code>admin_print_styles</code> to print on the frontend</p>\n" }, { "answer_id": 278799, "author": "cboy", "author_id": 117793, "author_profile": "https://wordpress.stackexchange.com/users/117793", "pm_score": 0, "selected": false, "text": "<p>Ok, Here is my final solution:</p>\n\n<pre><code>function my_test() {\n wp_enqueue_style( 'shortcode', plugin_dir_url( __FILE__ ) . 'css/shortcodes.css' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_test' );\n</code></pre>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117793/" ]
I need to enqueue a style sheet in my plugin to work on the front end of Wordpress. Here is what I have. Will someone please tell me what I am doing wrong? ``` function add_my_stylesheet1() { wp_enqueue_style( 'myStyles', plugins_url( 'css/styles.css', __FILE__ ) ); } add_action('admin_print_styles', 'add_my_stylesheet1'); ```
You're enquing on the **admin**\_enqueue\_scripts hook, which is why it's only showing up on admin pages If we look at an example from the official documentation: ``` /** * Proper way to enqueue scripts and styles */ function wpdocs_theme_name_scripts() { wp_enqueue_style( 'style-name', get_stylesheet_uri() ); wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); ``` we see the `wp_enqueue_scripts` hook being used instead. Use that hook instead of `admin_print_styles` to print on the frontend
278,399
<p>How do I add a class <code>the_content();</code>?</p> <pre><code>&lt;div class="csoporszoveg"&gt; &lt;h3 class="csoporcim"&gt;&lt;?php if ($settings['enable_link']) { echo '&lt;a href="' . get_permalink($post) . '"&gt;'; } the_title(); if ($settings['enable_link']) { echo '&lt;/a&gt;'; } ?&gt; &lt;/h3&gt; &lt;?php } ?&gt; &lt;?php if ( $content_source == 'excerpt' ) { the_excerpt(); } else { the_content(); } ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 278400, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You don't. You'll need to put an element around it:</p>\n\n<pre><code>&lt;?php if ( $content_source == 'excerpt' ) { ?&gt;\n &lt;div class=\"excerpt\"&gt;\n &lt;?php the_excerpt(); ?&gt;\n &lt;/div&gt;\n&lt;?php } else { ?&gt;\n &lt;div class=\"content\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;\n&lt;?php } ?&gt; \n</code></pre>\n" }, { "answer_id": 294299, "author": "Ramin Jormozeh", "author_id": 136999, "author_profile": "https://wordpress.stackexchange.com/users/136999", "pm_score": -1, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>&lt;p class=\"description\"&gt;&lt;?php echo get_the_content();?&gt;&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 353620, "author": "girishgv21", "author_id": 179110, "author_profile": "https://wordpress.stackexchange.com/users/179110", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\n if ( $content_source == 'excerpt' ) {\n the_excerpt();\n } else {\n ?&gt;\n &lt;div class=&quot;post_content&quot;&gt;&lt;?php the_content(); ?&gt;&lt;div&gt;\n &lt;?php\n }\n?&gt; \n</code></pre>\n<p>Target <code>p</code> inside <code>div.post_content</code></p>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126748/" ]
How do I add a class `the_content();`? ``` <div class="csoporszoveg"> <h3 class="csoporcim"><?php if ($settings['enable_link']) { echo '<a href="' . get_permalink($post) . '">'; } the_title(); if ($settings['enable_link']) { echo '</a>'; } ?> </h3> <?php } ?> <?php if ( $content_source == 'excerpt' ) { the_excerpt(); } else { the_content(); } ?> </div> ```
You don't. You'll need to put an element around it: ``` <?php if ( $content_source == 'excerpt' ) { ?> <div class="excerpt"> <?php the_excerpt(); ?> </div> <?php } else { ?> <div class="content"> <?php the_content(); ?> </div> <?php } ?> ```
278,408
<p>I'm building a website where there are some posts that will be relevant only for users from a specific country, so I would like that the user select his country so that he can view all the content minus (-) the content that is specific to other countries. </p> <p>For example: The user can select between Argentina, Chile, Mexico. He chooses Chile. He will be able to see all the content except the content that is specific from Argentina and Mexico.</p> <p>--more description--</p> <p>I believe 80% of the content will be not country specific.</p> <p>For example, if there is a category named "TV" which has:</p> <ul> <li>general TV posts -> content relevant for everybody (eg: Game of Thrones related posts)</li> <li>TV Argentina -> content relevant only for argentinians (eg.: local soap opera)</li> <li>TV Chile</li> <li>TV Mexico If the user chooses "Argentina" he must be able to see posts all posts in TV category except Chile and Mexico.</li> </ul> <p>I'm not sure how to accomplish this. It would be great if the user can choose his country from a dropdown and this filter gets applied to the whole website.</p> <p>Other info: Language is the same for all countries and there is user-generated content</p> <p>How would you approach this? Thank you for reading</p>
[ { "answer_id": 278400, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You don't. You'll need to put an element around it:</p>\n\n<pre><code>&lt;?php if ( $content_source == 'excerpt' ) { ?&gt;\n &lt;div class=\"excerpt\"&gt;\n &lt;?php the_excerpt(); ?&gt;\n &lt;/div&gt;\n&lt;?php } else { ?&gt;\n &lt;div class=\"content\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;\n&lt;?php } ?&gt; \n</code></pre>\n" }, { "answer_id": 294299, "author": "Ramin Jormozeh", "author_id": 136999, "author_profile": "https://wordpress.stackexchange.com/users/136999", "pm_score": -1, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>&lt;p class=\"description\"&gt;&lt;?php echo get_the_content();?&gt;&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 353620, "author": "girishgv21", "author_id": 179110, "author_profile": "https://wordpress.stackexchange.com/users/179110", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\n if ( $content_source == 'excerpt' ) {\n the_excerpt();\n } else {\n ?&gt;\n &lt;div class=&quot;post_content&quot;&gt;&lt;?php the_content(); ?&gt;&lt;div&gt;\n &lt;?php\n }\n?&gt; \n</code></pre>\n<p>Target <code>p</code> inside <code>div.post_content</code></p>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126752/" ]
I'm building a website where there are some posts that will be relevant only for users from a specific country, so I would like that the user select his country so that he can view all the content minus (-) the content that is specific to other countries. For example: The user can select between Argentina, Chile, Mexico. He chooses Chile. He will be able to see all the content except the content that is specific from Argentina and Mexico. --more description-- I believe 80% of the content will be not country specific. For example, if there is a category named "TV" which has: * general TV posts -> content relevant for everybody (eg: Game of Thrones related posts) * TV Argentina -> content relevant only for argentinians (eg.: local soap opera) * TV Chile * TV Mexico If the user chooses "Argentina" he must be able to see posts all posts in TV category except Chile and Mexico. I'm not sure how to accomplish this. It would be great if the user can choose his country from a dropdown and this filter gets applied to the whole website. Other info: Language is the same for all countries and there is user-generated content How would you approach this? Thank you for reading
You don't. You'll need to put an element around it: ``` <?php if ( $content_source == 'excerpt' ) { ?> <div class="excerpt"> <?php the_excerpt(); ?> </div> <?php } else { ?> <div class="content"> <?php the_content(); ?> </div> <?php } ?> ```
278,429
<p>I use TinyMCE Advance plugin. I've posted a question in the support forum of the the plugin but it seems that the author doesn't provide any support now. As you can see in the picture, the font size 12pt is the default font size. Every time I open the TinyMCE Advance editor, the size 12pt displays in the default state. How can I change the default size to 14pt and remove the size 8pt, 10pt,12pt?</p> <p>I've done some research and it's was recommended that I go to:</p> <pre><code>wp-includes/js/tinymce/skin/wordpress/wp-content.css </code></pre> <p>and change the size in </p> <pre><code>body { font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; font-size: 18px; line-height: 1.5; color: #333; margin: 9px 10px; max-width: 100%; -webkit-font-smoothing: antialiased !important; overflow-wrap: break-word; word-wrap: break-word; /* Old syntax */ } </code></pre> <p>In this case, I've changed it to 18pt, but it doesn't work. The thing is that the default 12pt size is still there. It just changes only when I click inside the text editor area; it will change from the 12pt (that displays as default) to 14pt. But actually when I type a text and publish, the result is the published text still displays 12pt size, not 14pt. So that means I have to select a font size 14pt in the drop-down list anyway in order to get the size 14pt. </p> <p><a href="https://i.stack.imgur.com/r0eYS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r0eYS.png" alt="enter image description here"></a></p>
[ { "answer_id": 295988, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": true, "text": "<p>This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar.</p>\n\n<h1>Style TinyMCE</h1>\n\n<p>WordPress give us a neat little function called <a href=\"https://developer.wordpress.org/reference/functions/add_editor_style/\" rel=\"nofollow noreferrer\"><code>add_editor_style()</code></a> which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest <a href=\"https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97\" rel=\"nofollow noreferrer\">TwentySeventeen theme</a>. First let's create a stylesheet. The name doesn't matter but the location does.</p>\n\n<pre><code>body,\nbutton,\ninput,\nselect,\ntextarea {\n font-size: 14pt;\n}\n</code></pre>\n\n<p>For simplicity we'll call this <code>editor-style.css</code> and save it in the theme:</p>\n\n<pre><code>/assets/css/editor-style.css\n</code></pre>\n\n<p>Next we need to tell WordPress to use our stylesheet so we'll open the themes <code>functions.php</code> file and add in:</p>\n\n<pre><code>/**\n * Theme setup functionality\n *\n * @return void\n */\nfunction prefix_theme_setup() {\n\n // Relative path to the TinyMCE Stylesheet\n add_editor_style( array( 'assets/css/editor-style.css' ) );\n\n}\nadd_action( 'after_setup_theme', 'iqt_theme_setup' );\n</code></pre>\n\n<p>Some plugins could interfere with this such as page builders if they implement their own TinyMCE.</p>\n\n<hr>\n\n<h1>Modify Toolbar</h1>\n\n<p>Next, we can use the <a href=\"https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/\" rel=\"nofollow noreferrer\"><code>tiny_mce_before_init</code></a> <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init\" rel=\"nofollow noreferrer\">filter hook</a> to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your <code>functions.php</code> file:</p>\n\n<pre><code>/**\n * Add Formats to TinyMCE\n * - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/\n * - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init\n *\n * @param array $args - Arguments used to initialize the tinyMCE\n *\n * @return array $args - Modified arguments\n */\nfunction prefix_tinymce_toolbar( $args ) {\n\n $args['fontsize_formats'] = \"14pt 18pt 24pt 36pt\";\n\n return $args;\n\n}\nadd_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' );\n</code></pre>\n\n<p>The <code>$args</code> array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, <code>px</code>, <code>em</code>, <code>rem</code> it doesn't matter, just that the list is separated by a space and is a valid <code>font-size</code> value.</p>\n" }, { "answer_id": 296160, "author": "Topy", "author_id": 125408, "author_profile": "https://wordpress.stackexchange.com/users/125408", "pm_score": 0, "selected": false, "text": "<p>I use only this one. It Works for me. What is the different between this code and your code?</p>\n\n<pre><code>// Customize TinyMCE editor font sizes\nif ( ! function_exists( 'wpex_mce_text_sizes' ) ) {\n function wpex_mce_text_sizes( $initArray ){\n $initArray['fontsize_formats'] = \"14pt 18pt 24pt 36pt\";\n return $initArray;\n }\n}\nadd_filter( 'tiny_mce_before_init', 'wpex_mce_text_sizes' );\n</code></pre>\n" }, { "answer_id": 299151, "author": "Tony Ngo", "author_id": 140640, "author_profile": "https://wordpress.stackexchange.com/users/140640", "pm_score": 0, "selected": false, "text": "<p>This is the Answer, It work for me:</p>\n\n<ol>\n<li><p>Look for <code>functions.php</code> in root of your themes directory inside <code>/wp-content/themes/yourtheme/</code>, open it up and add one line after <code>php</code> tag.</p>\n\n<p>add_editor_style('custom-editor-style.css');</p></li>\n<li><p>In the same directory, create a file called <code>custom-editor-style.css</code> with below lines in it</p>\n\n<pre><code>@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);\n* { font-family: 'Open Sans', sans-serif, Arial, Helvetica;}\n</code></pre></li>\n</ol>\n\n<p>Go ahead, clear your browsers cache and this is what you’ll see.</p>\n\n<p>Refer link: <a href=\"https://blog.phi9.com/wordpress-editor-and-its-font/\" rel=\"nofollow noreferrer\">https://blog.phi9.com/wordpress-editor-and-its-font/</a></p>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125408/" ]
I use TinyMCE Advance plugin. I've posted a question in the support forum of the the plugin but it seems that the author doesn't provide any support now. As you can see in the picture, the font size 12pt is the default font size. Every time I open the TinyMCE Advance editor, the size 12pt displays in the default state. How can I change the default size to 14pt and remove the size 8pt, 10pt,12pt? I've done some research and it's was recommended that I go to: ``` wp-includes/js/tinymce/skin/wordpress/wp-content.css ``` and change the size in ``` body { font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; font-size: 18px; line-height: 1.5; color: #333; margin: 9px 10px; max-width: 100%; -webkit-font-smoothing: antialiased !important; overflow-wrap: break-word; word-wrap: break-word; /* Old syntax */ } ``` In this case, I've changed it to 18pt, but it doesn't work. The thing is that the default 12pt size is still there. It just changes only when I click inside the text editor area; it will change from the 12pt (that displays as default) to 14pt. But actually when I type a text and publish, the result is the published text still displays 12pt size, not 14pt. So that means I have to select a font size 14pt in the drop-down list anyway in order to get the size 14pt. [![enter image description here](https://i.stack.imgur.com/r0eYS.png)](https://i.stack.imgur.com/r0eYS.png)
This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar. Style TinyMCE ============= WordPress give us a neat little function called [`add_editor_style()`](https://developer.wordpress.org/reference/functions/add_editor_style/) which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest [TwentySeventeen theme](https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97). First let's create a stylesheet. The name doesn't matter but the location does. ``` body, button, input, select, textarea { font-size: 14pt; } ``` For simplicity we'll call this `editor-style.css` and save it in the theme: ``` /assets/css/editor-style.css ``` Next we need to tell WordPress to use our stylesheet so we'll open the themes `functions.php` file and add in: ``` /** * Theme setup functionality * * @return void */ function prefix_theme_setup() { // Relative path to the TinyMCE Stylesheet add_editor_style( array( 'assets/css/editor-style.css' ) ); } add_action( 'after_setup_theme', 'iqt_theme_setup' ); ``` Some plugins could interfere with this such as page builders if they implement their own TinyMCE. --- Modify Toolbar ============== Next, we can use the [`tiny_mce_before_init`](https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/) [filter hook](https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init) to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your `functions.php` file: ``` /** * Add Formats to TinyMCE * - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/ * - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init * * @param array $args - Arguments used to initialize the tinyMCE * * @return array $args - Modified arguments */ function prefix_tinymce_toolbar( $args ) { $args['fontsize_formats'] = "14pt 18pt 24pt 36pt"; return $args; } add_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' ); ``` The `$args` array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, `px`, `em`, `rem` it doesn't matter, just that the list is separated by a space and is a valid `font-size` value.
278,450
<p>I want to import into the media library, all the images &amp; videos referenced in my blog posts.</p> <ol> <li>Can I use <a href="https://developer.wordpress.org/reference/functions/get_attached_media/" rel="nofollow noreferrer"><code>get_attached_media()</code></a> to get the images <em>referenced</em> on a page, even if they're not formally attached?</li> <li>Should I use <a href="https://developer.wordpress.org/reference/functions/media_handle_sideload/" rel="nofollow noreferrer"><code>media_handle_sideload()</code></a> to insert the media into the library?</li> </ol> <h3>Background</h3> <p>I've moved hosts, all my blog posts are available and all my images are in <code>/wp-content/uploads/2001/08</code> etc.</p> <p>I have around 13,000 images across ~120 subfolders (10 years of blogging ☺).</p> <p>Here's what I've tried that hasn't worked:</p> <ul> <li>Import WXR - imported the posts, but wouldn't import the images which were on the same server.</li> <li><a href="https://en-gb.wordpress.org/plugins/media-from-ftp/" rel="nofollow noreferrer">Media From FTP</a> - didn't work with the huge number of images.</li> <li><a href="https://wordpress.org/plugins/add-from-server/" rel="nofollow noreferrer">Add from Server</a> - only works on a per-file basis. I couldn't select a whole folder and all its sub-folders.</li> <li>Other plugins seem to suffer from the same issue - they don't deal with nested directories, and they can't cope with thousands of files.</li> </ul> <p>All I want is something to scan my posts, find any <code>&lt;img src="https://example.com/...</code>, then import that into the media library - leaving the media in the same location. Attachment to the post &amp; regeneration of thumbnails would be a bonus, but not essential.</p>
[ { "answer_id": 295988, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": true, "text": "<p>This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar.</p>\n\n<h1>Style TinyMCE</h1>\n\n<p>WordPress give us a neat little function called <a href=\"https://developer.wordpress.org/reference/functions/add_editor_style/\" rel=\"nofollow noreferrer\"><code>add_editor_style()</code></a> which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest <a href=\"https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97\" rel=\"nofollow noreferrer\">TwentySeventeen theme</a>. First let's create a stylesheet. The name doesn't matter but the location does.</p>\n\n<pre><code>body,\nbutton,\ninput,\nselect,\ntextarea {\n font-size: 14pt;\n}\n</code></pre>\n\n<p>For simplicity we'll call this <code>editor-style.css</code> and save it in the theme:</p>\n\n<pre><code>/assets/css/editor-style.css\n</code></pre>\n\n<p>Next we need to tell WordPress to use our stylesheet so we'll open the themes <code>functions.php</code> file and add in:</p>\n\n<pre><code>/**\n * Theme setup functionality\n *\n * @return void\n */\nfunction prefix_theme_setup() {\n\n // Relative path to the TinyMCE Stylesheet\n add_editor_style( array( 'assets/css/editor-style.css' ) );\n\n}\nadd_action( 'after_setup_theme', 'iqt_theme_setup' );\n</code></pre>\n\n<p>Some plugins could interfere with this such as page builders if they implement their own TinyMCE.</p>\n\n<hr>\n\n<h1>Modify Toolbar</h1>\n\n<p>Next, we can use the <a href=\"https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/\" rel=\"nofollow noreferrer\"><code>tiny_mce_before_init</code></a> <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init\" rel=\"nofollow noreferrer\">filter hook</a> to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your <code>functions.php</code> file:</p>\n\n<pre><code>/**\n * Add Formats to TinyMCE\n * - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/\n * - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init\n *\n * @param array $args - Arguments used to initialize the tinyMCE\n *\n * @return array $args - Modified arguments\n */\nfunction prefix_tinymce_toolbar( $args ) {\n\n $args['fontsize_formats'] = \"14pt 18pt 24pt 36pt\";\n\n return $args;\n\n}\nadd_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' );\n</code></pre>\n\n<p>The <code>$args</code> array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, <code>px</code>, <code>em</code>, <code>rem</code> it doesn't matter, just that the list is separated by a space and is a valid <code>font-size</code> value.</p>\n" }, { "answer_id": 296160, "author": "Topy", "author_id": 125408, "author_profile": "https://wordpress.stackexchange.com/users/125408", "pm_score": 0, "selected": false, "text": "<p>I use only this one. It Works for me. What is the different between this code and your code?</p>\n\n<pre><code>// Customize TinyMCE editor font sizes\nif ( ! function_exists( 'wpex_mce_text_sizes' ) ) {\n function wpex_mce_text_sizes( $initArray ){\n $initArray['fontsize_formats'] = \"14pt 18pt 24pt 36pt\";\n return $initArray;\n }\n}\nadd_filter( 'tiny_mce_before_init', 'wpex_mce_text_sizes' );\n</code></pre>\n" }, { "answer_id": 299151, "author": "Tony Ngo", "author_id": 140640, "author_profile": "https://wordpress.stackexchange.com/users/140640", "pm_score": 0, "selected": false, "text": "<p>This is the Answer, It work for me:</p>\n\n<ol>\n<li><p>Look for <code>functions.php</code> in root of your themes directory inside <code>/wp-content/themes/yourtheme/</code>, open it up and add one line after <code>php</code> tag.</p>\n\n<p>add_editor_style('custom-editor-style.css');</p></li>\n<li><p>In the same directory, create a file called <code>custom-editor-style.css</code> with below lines in it</p>\n\n<pre><code>@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);\n* { font-family: 'Open Sans', sans-serif, Arial, Helvetica;}\n</code></pre></li>\n</ol>\n\n<p>Go ahead, clear your browsers cache and this is what you’ll see.</p>\n\n<p>Refer link: <a href=\"https://blog.phi9.com/wordpress-editor-and-its-font/\" rel=\"nofollow noreferrer\">https://blog.phi9.com/wordpress-editor-and-its-font/</a></p>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278450", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81576/" ]
I want to import into the media library, all the images & videos referenced in my blog posts. 1. Can I use [`get_attached_media()`](https://developer.wordpress.org/reference/functions/get_attached_media/) to get the images *referenced* on a page, even if they're not formally attached? 2. Should I use [`media_handle_sideload()`](https://developer.wordpress.org/reference/functions/media_handle_sideload/) to insert the media into the library? ### Background I've moved hosts, all my blog posts are available and all my images are in `/wp-content/uploads/2001/08` etc. I have around 13,000 images across ~120 subfolders (10 years of blogging ☺). Here's what I've tried that hasn't worked: * Import WXR - imported the posts, but wouldn't import the images which were on the same server. * [Media From FTP](https://en-gb.wordpress.org/plugins/media-from-ftp/) - didn't work with the huge number of images. * [Add from Server](https://wordpress.org/plugins/add-from-server/) - only works on a per-file basis. I couldn't select a whole folder and all its sub-folders. * Other plugins seem to suffer from the same issue - they don't deal with nested directories, and they can't cope with thousands of files. All I want is something to scan my posts, find any `<img src="https://example.com/...`, then import that into the media library - leaving the media in the same location. Attachment to the post & regeneration of thumbnails would be a bonus, but not essential.
This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar. Style TinyMCE ============= WordPress give us a neat little function called [`add_editor_style()`](https://developer.wordpress.org/reference/functions/add_editor_style/) which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest [TwentySeventeen theme](https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97). First let's create a stylesheet. The name doesn't matter but the location does. ``` body, button, input, select, textarea { font-size: 14pt; } ``` For simplicity we'll call this `editor-style.css` and save it in the theme: ``` /assets/css/editor-style.css ``` Next we need to tell WordPress to use our stylesheet so we'll open the themes `functions.php` file and add in: ``` /** * Theme setup functionality * * @return void */ function prefix_theme_setup() { // Relative path to the TinyMCE Stylesheet add_editor_style( array( 'assets/css/editor-style.css' ) ); } add_action( 'after_setup_theme', 'iqt_theme_setup' ); ``` Some plugins could interfere with this such as page builders if they implement their own TinyMCE. --- Modify Toolbar ============== Next, we can use the [`tiny_mce_before_init`](https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/) [filter hook](https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init) to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your `functions.php` file: ``` /** * Add Formats to TinyMCE * - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/ * - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init * * @param array $args - Arguments used to initialize the tinyMCE * * @return array $args - Modified arguments */ function prefix_tinymce_toolbar( $args ) { $args['fontsize_formats'] = "14pt 18pt 24pt 36pt"; return $args; } add_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' ); ``` The `$args` array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, `px`, `em`, `rem` it doesn't matter, just that the list is separated by a space and is a valid `font-size` value.
278,452
<p>The error is:</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (output started at C:\wamp64444\www\demoplugin\wp-includes\class.wp-styles.php:237) in C:\wamp64444\www\demoplugin\wp-includes\pluggable.php on line 914</p> </blockquote> <p>code of my plugin that create form for registration and form login </p> <pre><code>&lt;?php /* Plugin Name: Form test Plugin URI: http://co.com Description: a plugin to create a form Version: 1.2 Author: Ghn Author URI: http://co.com License: GPL2 */ function registration_form($username, $password, $email) { echo'&lt;form method="post" action="' . $_SERVER['REQUEST_URI'] . '" &gt; UserName: &lt;input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '"&gt;&lt;br&gt; Email: &lt;input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"&gt;&lt;br&gt; Password: &lt;input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Register"&gt; &lt;/form&gt;'; } function registration_validation( $username, $password, $email ) { global $reg_errors; $reg_errors = new WP_Error; if ( empty( $username ) || empty( $password ) || empty( $email ) ) { $reg_errors-&gt;add('field', 'Required form field is missing'); } if ( 4 &gt; strlen( $username ) ) { $reg_errors-&gt;add( 'username_length', 'Username too short. At least 4 characters is required' ); } if ( username_exists( $username ) ) $reg_errors-&gt;add('user_name', 'Sorry, that username already exists!'); if ( ! validate_username( $username ) ) { $reg_errors-&gt;add( 'username_invalid', 'Sorry, the username you entered is not valid' ); } if ( 5 &gt; strlen( $password ) ) { $reg_errors-&gt;add( 'password', 'Password length must be greater than 5' ); } if ( !is_email( $email ) ) { $reg_errors-&gt;add( 'email_invalid', 'Email is not valid' ); } if ( email_exists( $email ) ) { $reg_errors-&gt;add( 'email', 'Email Already in use' ); } if ( is_wp_error( $reg_errors ) ) { foreach ( $reg_errors-&gt;get_error_messages() as $error ) { echo '&lt;div&gt;'; echo '&lt;strong&gt;ERROR&lt;/strong&gt;:'; echo $error . '&lt;br/&gt;'; echo '&lt;/div&gt;'; } } } function complete_registration() { global $reg_errors, $username, $password, $email; if ( 1 &gt; count( $reg_errors-&gt;get_error_messages() ) ) { $userdata = array( 'user_login' =&gt; $username, 'user_email' =&gt; $email, 'user_pass' =&gt; $password, ); $user = wp_insert_user( $userdata ); echo 'Registration complete. '; } } function custom_registration_function() { if ( isset($_POST['submit'] ) ) { registration_validation( $_POST['username'], $_POST['password'], $_POST['email'] ); // sanitize user form input global $username, $password, $email; $username = sanitize_user( $_POST['username'] ); $password = esc_attr( $_POST['password'] ); $email = sanitize_email( $_POST['email'] ); // call @function complete_registration to create the user // only when no WP_error is found complete_registration( $username, $password, $email ); } registration_form( $username, $password, $email ); } add_shortcode('test', 'form_creation'); // The callback function that will replace [book] function form_creation() { ob_start(); custom_registration_function(); return ob_get_clean(); } function login_form() { echo'&lt;form method="post" action="' . $_SERVER['REQUEST_URI'] . '" &gt; Email: &lt;input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"&gt;&lt;br&gt; Password: &lt;input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Register"&gt; &lt;/form&gt;'; } function dlf_auth( $username, $password ) { global $user; $creds = array(); $creds['user_login'] = $username; $creds['user_password'] = $password; $user = wp_signon( $creds, false ); if ( is_wp_error($user) ) { echo $user-&gt;get_error_message(); } if ( !is_wp_error($user) ) { echo 'login success'; } } function dlf_process() { if (isset($_POST['submit'])) { dlf_auth($_POST['email'], $_POST['password']); } login_form(); } add_shortcode('testlogin', 'login_test'); // The callback function that will replace [book] function login_test() { ob_start(); dlf_process(); return ob_get_clean(); } </code></pre> <p>?> </p>
[ { "answer_id": 295988, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": true, "text": "<p>This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar.</p>\n\n<h1>Style TinyMCE</h1>\n\n<p>WordPress give us a neat little function called <a href=\"https://developer.wordpress.org/reference/functions/add_editor_style/\" rel=\"nofollow noreferrer\"><code>add_editor_style()</code></a> which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest <a href=\"https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97\" rel=\"nofollow noreferrer\">TwentySeventeen theme</a>. First let's create a stylesheet. The name doesn't matter but the location does.</p>\n\n<pre><code>body,\nbutton,\ninput,\nselect,\ntextarea {\n font-size: 14pt;\n}\n</code></pre>\n\n<p>For simplicity we'll call this <code>editor-style.css</code> and save it in the theme:</p>\n\n<pre><code>/assets/css/editor-style.css\n</code></pre>\n\n<p>Next we need to tell WordPress to use our stylesheet so we'll open the themes <code>functions.php</code> file and add in:</p>\n\n<pre><code>/**\n * Theme setup functionality\n *\n * @return void\n */\nfunction prefix_theme_setup() {\n\n // Relative path to the TinyMCE Stylesheet\n add_editor_style( array( 'assets/css/editor-style.css' ) );\n\n}\nadd_action( 'after_setup_theme', 'iqt_theme_setup' );\n</code></pre>\n\n<p>Some plugins could interfere with this such as page builders if they implement their own TinyMCE.</p>\n\n<hr>\n\n<h1>Modify Toolbar</h1>\n\n<p>Next, we can use the <a href=\"https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/\" rel=\"nofollow noreferrer\"><code>tiny_mce_before_init</code></a> <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init\" rel=\"nofollow noreferrer\">filter hook</a> to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your <code>functions.php</code> file:</p>\n\n<pre><code>/**\n * Add Formats to TinyMCE\n * - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/\n * - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init\n *\n * @param array $args - Arguments used to initialize the tinyMCE\n *\n * @return array $args - Modified arguments\n */\nfunction prefix_tinymce_toolbar( $args ) {\n\n $args['fontsize_formats'] = \"14pt 18pt 24pt 36pt\";\n\n return $args;\n\n}\nadd_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' );\n</code></pre>\n\n<p>The <code>$args</code> array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, <code>px</code>, <code>em</code>, <code>rem</code> it doesn't matter, just that the list is separated by a space and is a valid <code>font-size</code> value.</p>\n" }, { "answer_id": 296160, "author": "Topy", "author_id": 125408, "author_profile": "https://wordpress.stackexchange.com/users/125408", "pm_score": 0, "selected": false, "text": "<p>I use only this one. It Works for me. What is the different between this code and your code?</p>\n\n<pre><code>// Customize TinyMCE editor font sizes\nif ( ! function_exists( 'wpex_mce_text_sizes' ) ) {\n function wpex_mce_text_sizes( $initArray ){\n $initArray['fontsize_formats'] = \"14pt 18pt 24pt 36pt\";\n return $initArray;\n }\n}\nadd_filter( 'tiny_mce_before_init', 'wpex_mce_text_sizes' );\n</code></pre>\n" }, { "answer_id": 299151, "author": "Tony Ngo", "author_id": 140640, "author_profile": "https://wordpress.stackexchange.com/users/140640", "pm_score": 0, "selected": false, "text": "<p>This is the Answer, It work for me:</p>\n\n<ol>\n<li><p>Look for <code>functions.php</code> in root of your themes directory inside <code>/wp-content/themes/yourtheme/</code>, open it up and add one line after <code>php</code> tag.</p>\n\n<p>add_editor_style('custom-editor-style.css');</p></li>\n<li><p>In the same directory, create a file called <code>custom-editor-style.css</code> with below lines in it</p>\n\n<pre><code>@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);\n* { font-family: 'Open Sans', sans-serif, Arial, Helvetica;}\n</code></pre></li>\n</ol>\n\n<p>Go ahead, clear your browsers cache and this is what you’ll see.</p>\n\n<p>Refer link: <a href=\"https://blog.phi9.com/wordpress-editor-and-its-font/\" rel=\"nofollow noreferrer\">https://blog.phi9.com/wordpress-editor-and-its-font/</a></p>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126783/" ]
The error is: > > Warning: Cannot modify header information - headers already sent by (output started at > C:\wamp64444\www\demoplugin\wp-includes\class.wp-styles.php:237) in > C:\wamp64444\www\demoplugin\wp-includes\pluggable.php on line 914 > > > code of my plugin that create form for registration and form login ``` <?php /* Plugin Name: Form test Plugin URI: http://co.com Description: a plugin to create a form Version: 1.2 Author: Ghn Author URI: http://co.com License: GPL2 */ function registration_form($username, $password, $email) { echo'<form method="post" action="' . $_SERVER['REQUEST_URI'] . '" > UserName: <input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '"><br> Email: <input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"><br> Password: <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"><br> <input type="submit" name="submit" value="Register"> </form>'; } function registration_validation( $username, $password, $email ) { global $reg_errors; $reg_errors = new WP_Error; if ( empty( $username ) || empty( $password ) || empty( $email ) ) { $reg_errors->add('field', 'Required form field is missing'); } if ( 4 > strlen( $username ) ) { $reg_errors->add( 'username_length', 'Username too short. At least 4 characters is required' ); } if ( username_exists( $username ) ) $reg_errors->add('user_name', 'Sorry, that username already exists!'); if ( ! validate_username( $username ) ) { $reg_errors->add( 'username_invalid', 'Sorry, the username you entered is not valid' ); } if ( 5 > strlen( $password ) ) { $reg_errors->add( 'password', 'Password length must be greater than 5' ); } if ( !is_email( $email ) ) { $reg_errors->add( 'email_invalid', 'Email is not valid' ); } if ( email_exists( $email ) ) { $reg_errors->add( 'email', 'Email Already in use' ); } if ( is_wp_error( $reg_errors ) ) { foreach ( $reg_errors->get_error_messages() as $error ) { echo '<div>'; echo '<strong>ERROR</strong>:'; echo $error . '<br/>'; echo '</div>'; } } } function complete_registration() { global $reg_errors, $username, $password, $email; if ( 1 > count( $reg_errors->get_error_messages() ) ) { $userdata = array( 'user_login' => $username, 'user_email' => $email, 'user_pass' => $password, ); $user = wp_insert_user( $userdata ); echo 'Registration complete. '; } } function custom_registration_function() { if ( isset($_POST['submit'] ) ) { registration_validation( $_POST['username'], $_POST['password'], $_POST['email'] ); // sanitize user form input global $username, $password, $email; $username = sanitize_user( $_POST['username'] ); $password = esc_attr( $_POST['password'] ); $email = sanitize_email( $_POST['email'] ); // call @function complete_registration to create the user // only when no WP_error is found complete_registration( $username, $password, $email ); } registration_form( $username, $password, $email ); } add_shortcode('test', 'form_creation'); // The callback function that will replace [book] function form_creation() { ob_start(); custom_registration_function(); return ob_get_clean(); } function login_form() { echo'<form method="post" action="' . $_SERVER['REQUEST_URI'] . '" > Email: <input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"><br> Password: <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"><br> <input type="submit" name="submit" value="Register"> </form>'; } function dlf_auth( $username, $password ) { global $user; $creds = array(); $creds['user_login'] = $username; $creds['user_password'] = $password; $user = wp_signon( $creds, false ); if ( is_wp_error($user) ) { echo $user->get_error_message(); } if ( !is_wp_error($user) ) { echo 'login success'; } } function dlf_process() { if (isset($_POST['submit'])) { dlf_auth($_POST['email'], $_POST['password']); } login_form(); } add_shortcode('testlogin', 'login_test'); // The callback function that will replace [book] function login_test() { ob_start(); dlf_process(); return ob_get_clean(); } ``` ?>
This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar. Style TinyMCE ============= WordPress give us a neat little function called [`add_editor_style()`](https://developer.wordpress.org/reference/functions/add_editor_style/) which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest [TwentySeventeen theme](https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97). First let's create a stylesheet. The name doesn't matter but the location does. ``` body, button, input, select, textarea { font-size: 14pt; } ``` For simplicity we'll call this `editor-style.css` and save it in the theme: ``` /assets/css/editor-style.css ``` Next we need to tell WordPress to use our stylesheet so we'll open the themes `functions.php` file and add in: ``` /** * Theme setup functionality * * @return void */ function prefix_theme_setup() { // Relative path to the TinyMCE Stylesheet add_editor_style( array( 'assets/css/editor-style.css' ) ); } add_action( 'after_setup_theme', 'iqt_theme_setup' ); ``` Some plugins could interfere with this such as page builders if they implement their own TinyMCE. --- Modify Toolbar ============== Next, we can use the [`tiny_mce_before_init`](https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/) [filter hook](https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init) to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your `functions.php` file: ``` /** * Add Formats to TinyMCE * - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/ * - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init * * @param array $args - Arguments used to initialize the tinyMCE * * @return array $args - Modified arguments */ function prefix_tinymce_toolbar( $args ) { $args['fontsize_formats'] = "14pt 18pt 24pt 36pt"; return $args; } add_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' ); ``` The `$args` array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, `px`, `em`, `rem` it doesn't matter, just that the list is separated by a space and is a valid `font-size` value.
278,476
<p>I am currently trying to change <strong>Woocommerce redirect url</strong> for login only when users logged from a specific page. So first I tried that way in my template page:</p> <pre><code>&lt;?php woocommerce_login_form(array('redirect'=&gt;$_SERVER['REQUEST_URI'])); ?&gt; </code></pre> <p>Then, I saw user is still redirected to default (my-account) so I used the login hook that way:</p> <pre><code>function share_login_redirect( $redirect ) { if( strtr($_SERVER['REQUEST_URI'],array('/partage','/share')) ){ $redirect = get_site_url().$_SERVER['REQUEST_URI']; } return $redirect; } add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 ); </code></pre> <p>All of thoses techniques didn't work for me. Knowing that <code>$redirect = "https://mysite/share/?param=xx"</code> what am I doing wrong there?</p> <p>2017-08-29 EDIT : If anyone had the same problem as I did, it is possible a plugin uses the same hook than you and have an higher priority than yours meaning the redirect will not work until you move up your priority. Please see my answer below.</p>
[ { "answer_id": 278478, "author": "Jeff Mattson", "author_id": 93714, "author_profile": "https://wordpress.stackexchange.com/users/93714", "pm_score": 2, "selected": false, "text": "<p>Try changing <code>strtr</code> to <code>strpos</code>. However, you can not give it an array for needles I don't think. You will have to create another function for that.</p>\n\n<pre><code>function strposa($haystack, $needles=array(), $offset=0) {\n $chr = array();\n foreach($needles as $needle) {\n $res = strpos($haystack, $needle, $offset);\n if ($res !== false) $chr[$needle] = $res;\n }\n if(empty($chr)) return false;\n return min($chr);\n}\n</code></pre>\n\n<p>Use this function instead of <code>strtr</code></p>\n" }, { "answer_id": 278490, "author": "Dynomite", "author_id": 96315, "author_profile": "https://wordpress.stackexchange.com/users/96315", "pm_score": 3, "selected": true, "text": "<p>I found what was my problem is priority. Some other plugin was using a 1000 priority, so I had to boost my priority when declaring the hook. That way:</p>\n\n<pre><code>add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 1100, 2 );\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 );\n</code></pre>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278476", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96315/" ]
I am currently trying to change **Woocommerce redirect url** for login only when users logged from a specific page. So first I tried that way in my template page: ``` <?php woocommerce_login_form(array('redirect'=>$_SERVER['REQUEST_URI'])); ?> ``` Then, I saw user is still redirected to default (my-account) so I used the login hook that way: ``` function share_login_redirect( $redirect ) { if( strtr($_SERVER['REQUEST_URI'],array('/partage','/share')) ){ $redirect = get_site_url().$_SERVER['REQUEST_URI']; } return $redirect; } add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 ); ``` All of thoses techniques didn't work for me. Knowing that `$redirect = "https://mysite/share/?param=xx"` what am I doing wrong there? 2017-08-29 EDIT : If anyone had the same problem as I did, it is possible a plugin uses the same hook than you and have an higher priority than yours meaning the redirect will not work until you move up your priority. Please see my answer below.
I found what was my problem is priority. Some other plugin was using a 1000 priority, so I had to boost my priority when declaring the hook. That way: ``` add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 1100, 2 ); ``` instead of ``` add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 ); ```
278,504
<p>Trying to run a custom script on a single page using is_page in functions.php not working at all. I have a function called load_gh_boards that would enquque a script, only on a certain page (79): </p> <pre><code>function load_gh_boards() { if( is_page(79) ){ wp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true ); }} add_action('wp_enqueue_script', 'load_gh_boards'); </code></pre> <p>This is inside a theme enqueue function that is loading all of my styles and scripts:</p> <pre><code>function theme_enqueue() { if ( ! is_admin() ) { wp_register_style( 'main-style', get_bloginfo( 'template_directory' ) . '/css/style.css?' . time() ); wp_enqueue_style( 'main-style' ); wp_enqueue_script( 'jquery' ); wp_register_script( 'main-vendor', get_bloginfo( 'template_directory' ) . '/js/vendor.js', array(), '1.0', true ); ///etc... wp_enqueue_script( 'main-vendor' ); wp_enqueue_script( 'main-script' ); ///load_gh_boards } </code></pre> <p>No result. Any help or insight at all would be appreciated.</p>
[ { "answer_id": 278505, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>First of all, there is a mistype in your code. It's <code>wp_enqueue_scripts</code>, not <code>wp_enqueue_script</code>. That might be the issue.</p>\n\n<p>Also, you shouldn't use <code>wp_enqueue_scripts</code> inside another <code>wp_enqueue_scripts</code>. Simply add your conditional in the <code>theme_enqueue()</code> function like this:</p>\n\n<pre><code>function theme_enqueue() {\nif ( ! is_admin() ) {\n\n wp_register_style( 'main-style', get_bloginfo( 'template_directory' ) . '/css/style.css?' . time() );\n wp_enqueue_style( 'main-style' );\n wp_enqueue_script( 'jquery' );\n wp_register_script( 'main-vendor', get_bloginfo( 'template_directory' ) . '/js/vendor.js', array(), '1.0', true );\n ///etc...\n\n wp_enqueue_script( 'main-vendor' );\n wp_enqueue_script( 'main-script' );\n\n if( is_page(79) ){\n wp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true );\n }\n}\nadd_action('wp_enqueue_scripts', 'theme_enqueue');\n</code></pre>\n\n<p>I assume that the <code>theme_enqueue()</code> function is hooked to <code>wp_enqueue_scripts</code> itself.</p>\n" }, { "answer_id": 278506, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>You Register the Script, but you don't enqueue it.\nAdd wp_enqueue_script('gh-jobs-board'); to your conditional function.</p>\n" }, { "answer_id": 278509, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p><code>is_page(79)</code> is asking if the current main query is a page, specifically page 79</p>\n\n<p><strong>But the main query hasn't happened yet</strong></p>\n\n<p>This function has to be called inside the main loop or at the very least inside the template, but the <code>init</code> hook is way too early for this.</p>\n\n<p>Instead, make sure you use the body class, and load the script on all pages. Then, check if the body tag has the css class <code>page-id-79</code>.</p>\n\n<h2>Other Notes</h2>\n\n<ul>\n<li>You don't enqueue on the <code>init</code> hook, you're meant to enqueue on the <code>wp_enqueue_scripts</code> hook</li>\n<li>It would be simpler to return early e.g. <code>if ( is_admin() ) return;</code></li>\n<li>Don't enqueue jQuery, instead add it as a dependency so WP knows how to output the scripts in the correct order</li>\n<li>main-style and main-vendor are very generic names, you might encounter clashes, prefix them, e.g. <code>pji-main-vendor</code></li>\n<li><code>theme_enqueue</code> is also a very generic function name, you should prefix that too</li>\n<li>You can register and enqueue at the same time using <code>wp_enqueue_script</code>. If you pass everything to that function there's no need to call <code>wp_register_script</code></li>\n<li>Indent your code, modern code editors will do this automatically for free, zero effort. Sublime or Atom are examples of free software that will do this for you, there really are no excuses</li>\n</ul>\n" }, { "answer_id": 278521, "author": "pjldesign", "author_id": 114585, "author_profile": "https://wordpress.stackexchange.com/users/114585", "pm_score": 1, "selected": false, "text": "<pre><code>function theme_enqueue() {\nif ( ! is_admin() ) {\nwp_register_script( 'main-script', get_bloginfo( 'template_directory' ) . '/js/script.js', array(), '1.0', true );\nwp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true );\n///etc...\nwp_enqueue_script( 'main-vendor' );\nwp_enqueue_script( 'main-script' );\n///etc...\n\nif( is_page(79) ) {\n wp_enqueue_script( 'gh-jobs-board' );\n}\n}\n}\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue' );\n</code></pre>\n" }, { "answer_id": 344634, "author": "Steph", "author_id": 173167, "author_profile": "https://wordpress.stackexchange.com/users/173167", "pm_score": 3, "selected": false, "text": "<p>This is absolutely working for me right now:</p>\n\n<pre><code>add_action('get_header', function() {\n if(is_page('566')) {\n\n function sp_enqueue_script() {\n wp_enqueue_script(\n 'sp-custom-script',\n get_stylesheet_directory_uri() . '/assets/js/sp_script.js',\n array( 'jquery' ), '1.0', true\n );\n }\n\n add_action( 'wp_enqueue_scripts', 'sp_enqueue_script' );\n }\n});\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"noreferrer\">is_page</a> doesn't work in functions.php because the main query hasn't loaded yet, so wait for the header to load.</p>\n\n<p>Last boolean in the <code>wp_enqueue_script</code> hook is for the script to be enqueued in the footer, so it runs faster.</p>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278504", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114585/" ]
Trying to run a custom script on a single page using is\_page in functions.php not working at all. I have a function called load\_gh\_boards that would enquque a script, only on a certain page (79): ``` function load_gh_boards() { if( is_page(79) ){ wp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true ); }} add_action('wp_enqueue_script', 'load_gh_boards'); ``` This is inside a theme enqueue function that is loading all of my styles and scripts: ``` function theme_enqueue() { if ( ! is_admin() ) { wp_register_style( 'main-style', get_bloginfo( 'template_directory' ) . '/css/style.css?' . time() ); wp_enqueue_style( 'main-style' ); wp_enqueue_script( 'jquery' ); wp_register_script( 'main-vendor', get_bloginfo( 'template_directory' ) . '/js/vendor.js', array(), '1.0', true ); ///etc... wp_enqueue_script( 'main-vendor' ); wp_enqueue_script( 'main-script' ); ///load_gh_boards } ``` No result. Any help or insight at all would be appreciated.
`is_page(79)` is asking if the current main query is a page, specifically page 79 **But the main query hasn't happened yet** This function has to be called inside the main loop or at the very least inside the template, but the `init` hook is way too early for this. Instead, make sure you use the body class, and load the script on all pages. Then, check if the body tag has the css class `page-id-79`. Other Notes ----------- * You don't enqueue on the `init` hook, you're meant to enqueue on the `wp_enqueue_scripts` hook * It would be simpler to return early e.g. `if ( is_admin() ) return;` * Don't enqueue jQuery, instead add it as a dependency so WP knows how to output the scripts in the correct order * main-style and main-vendor are very generic names, you might encounter clashes, prefix them, e.g. `pji-main-vendor` * `theme_enqueue` is also a very generic function name, you should prefix that too * You can register and enqueue at the same time using `wp_enqueue_script`. If you pass everything to that function there's no need to call `wp_register_script` * Indent your code, modern code editors will do this automatically for free, zero effort. Sublime or Atom are examples of free software that will do this for you, there really are no excuses
278,527
<p>-I am running a woo commencers shop</p> <p>-Users have the ability to add products using wp insert post</p> <p>-The product gallery multiple image upload will only add the last image to the post but in media they are all attached to the correct post</p> <p>This is my code</p> <p>function.php</p> <pre><code>function my_handle_attachment($file_handler,$post_id,$set_thu=false) { if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attach_id = media_handle_upload( $file_handler, $post_id ); if ( is_numeric( $attach_id ) ) { update_post_meta( $post_id, '_product_image_gallery', $attach_id ); } return $attach_id; } </code></pre> <p>front-end</p> <pre><code>if ( $_FILES ) { $files = $_FILES["my_file_upload"]; foreach ($files['name'] as $key =&gt; $value) { if ($files['name'][$key]) { $file = array( 'name' =&gt; $files['name'][$key], 'type' =&gt; $files['type'][$key], 'tmp_name' =&gt; $files['tmp_name'][$key], 'error' =&gt; $files['error'][$key], 'size' =&gt; $files['size'][$key] ); $_FILES = array ("my_file_upload" =&gt; $file); $newupload = my_handle_attachment( "my_file_upload", $post_id); } } } </code></pre> <p>input</p> <pre><code>&lt;input type="file" name="my_file_upload[]" multiple="multiple" &gt; </code></pre> <p>This will upload all images and attach them to the correct post but only the last image will show up in Products gallery image section. What am i doing wrong?</p>
[ { "answer_id": 330163, "author": "Tcmxc", "author_id": 63922, "author_profile": "https://wordpress.stackexchange.com/users/63922", "pm_score": 1, "selected": true, "text": "<pre><code>if ( ! empty( $_FILES['muti_files'] ) ) {\n $files = $_FILES['muti_files'];\n foreach ($files['name'] as $key =&gt; $value){\n if ($files['name'][$key]){\n $file = array(\n 'name' =&gt; $files['name'][$key],\n 'type' =&gt; $files['type'][$key],\n 'tmp_name' =&gt; $files['tmp_name'][$key],\n 'error' =&gt; $files['error'][$key],\n 'size' =&gt; $files['size'][$key]\n );\n }\n $_FILES = array(\"muti_files\" =&gt; $file);\n $i=1;\n foreach ($_FILES as $file =&gt; $array) {\n if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();\n require_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n $attachment_id = media_handle_upload($file, $post_id);\n $vv .= $attachment_id . \",\";\n $i++;\n }\n update_post_meta($post_id, '_product_image_gallery', $vv);\n }\n }\n</code></pre>\n" }, { "answer_id": 341154, "author": "Darwin", "author_id": 170452, "author_profile": "https://wordpress.stackexchange.com/users/170452", "pm_score": -1, "selected": false, "text": "<p>More optimized!</p>\n\n<pre><code>if ( ! empty( $_FILES['muti_files'] ) ) {\n $files = $_FILES['muti_files'];\n foreach ($files['name'] as $key =&gt; $value){\n if ($files['name'][$key]){\n $file = array(\n 'name' =&gt; $files['name'][$key],\n 'type' =&gt; $files['type'][$key],\n 'tmp_name' =&gt; $files['tmp_name'][$key],\n 'error' =&gt; $files['error'][$key],\n 'size' =&gt; $files['size'][$key]\n );\n }\n $_FILES = array(\"muti_files\" =&gt; $file);\n $i=1;\n\nrequire_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\nrequire_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\nrequire_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n\n foreach ($_FILES as $file =&gt; $array) {\n if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();\n\n $attachment_id = media_handle_upload($file, $post_id);\n $vv .= $attachment_id . \",\";\n $i++;\n }\n update_post_meta($post_id, '_product_image_gallery', $vv);\n }\n }\n</code></pre>\n" } ]
2017/08/29
[ "https://wordpress.stackexchange.com/questions/278527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63922/" ]
-I am running a woo commencers shop -Users have the ability to add products using wp insert post -The product gallery multiple image upload will only add the last image to the post but in media they are all attached to the correct post This is my code function.php ``` function my_handle_attachment($file_handler,$post_id,$set_thu=false) { if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attach_id = media_handle_upload( $file_handler, $post_id ); if ( is_numeric( $attach_id ) ) { update_post_meta( $post_id, '_product_image_gallery', $attach_id ); } return $attach_id; } ``` front-end ``` if ( $_FILES ) { $files = $_FILES["my_file_upload"]; foreach ($files['name'] as $key => $value) { if ($files['name'][$key]) { $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); $_FILES = array ("my_file_upload" => $file); $newupload = my_handle_attachment( "my_file_upload", $post_id); } } } ``` input ``` <input type="file" name="my_file_upload[]" multiple="multiple" > ``` This will upload all images and attach them to the correct post but only the last image will show up in Products gallery image section. What am i doing wrong?
``` if ( ! empty( $_FILES['muti_files'] ) ) { $files = $_FILES['muti_files']; foreach ($files['name'] as $key => $value){ if ($files['name'][$key]){ $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); } $_FILES = array("muti_files" => $file); $i=1; foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attachment_id = media_handle_upload($file, $post_id); $vv .= $attachment_id . ","; $i++; } update_post_meta($post_id, '_product_image_gallery', $vv); } } ```
278,533
<p>When Users create custom post types, the author field does not seem to be passed back to WP posts functions.</p> <p>As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post_type = 'job'.</p> <p>This all LOOKS good in the database - the user, and post are inserted. The post_author is indeed the same as the ID of the user who created it.</p> <p>But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author.</p> <p>I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp_update_post();</p> <p>Here's the code to create the user, and then the post:</p> <pre><code>// Generate the password and create the user $password = wp_generate_password( 12, false ); $user_id = wp_create_user( $email_address, $password, $email_address ); //login wp_clear_auth_cookie(); wp_set_current_user ( $user_id ); wp_set_auth_cookie ( $user_id ); // Set the role $user = new WP_User( $user_id ); $user-&gt;set_role( 'subscriber' ); //Ready data for linked post type creation $new_post = array( 'post_content' =&gt; $email_address, 'post_status' =&gt; 'publish', 'post_date' =&gt; date('Y-m-d H:i:s'), 'post_author' =&gt; $user_id, 'post_title' =&gt; $post_name, 'post_name' =&gt; $post_name, 'post_type' =&gt; $user_type ); //Create the post $account_link_post_id = wp_insert_post($new_post); </code></pre> <p>ANY suggestions here would be great. Thank you in advance.</p>
[ { "answer_id": 330163, "author": "Tcmxc", "author_id": 63922, "author_profile": "https://wordpress.stackexchange.com/users/63922", "pm_score": 1, "selected": true, "text": "<pre><code>if ( ! empty( $_FILES['muti_files'] ) ) {\n $files = $_FILES['muti_files'];\n foreach ($files['name'] as $key =&gt; $value){\n if ($files['name'][$key]){\n $file = array(\n 'name' =&gt; $files['name'][$key],\n 'type' =&gt; $files['type'][$key],\n 'tmp_name' =&gt; $files['tmp_name'][$key],\n 'error' =&gt; $files['error'][$key],\n 'size' =&gt; $files['size'][$key]\n );\n }\n $_FILES = array(\"muti_files\" =&gt; $file);\n $i=1;\n foreach ($_FILES as $file =&gt; $array) {\n if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();\n require_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n $attachment_id = media_handle_upload($file, $post_id);\n $vv .= $attachment_id . \",\";\n $i++;\n }\n update_post_meta($post_id, '_product_image_gallery', $vv);\n }\n }\n</code></pre>\n" }, { "answer_id": 341154, "author": "Darwin", "author_id": 170452, "author_profile": "https://wordpress.stackexchange.com/users/170452", "pm_score": -1, "selected": false, "text": "<p>More optimized!</p>\n\n<pre><code>if ( ! empty( $_FILES['muti_files'] ) ) {\n $files = $_FILES['muti_files'];\n foreach ($files['name'] as $key =&gt; $value){\n if ($files['name'][$key]){\n $file = array(\n 'name' =&gt; $files['name'][$key],\n 'type' =&gt; $files['type'][$key],\n 'tmp_name' =&gt; $files['tmp_name'][$key],\n 'error' =&gt; $files['error'][$key],\n 'size' =&gt; $files['size'][$key]\n );\n }\n $_FILES = array(\"muti_files\" =&gt; $file);\n $i=1;\n\nrequire_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\nrequire_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\nrequire_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n\n foreach ($_FILES as $file =&gt; $array) {\n if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();\n\n $attachment_id = media_handle_upload($file, $post_id);\n $vv .= $attachment_id . \",\";\n $i++;\n }\n update_post_meta($post_id, '_product_image_gallery', $vv);\n }\n }\n</code></pre>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122711/" ]
When Users create custom post types, the author field does not seem to be passed back to WP posts functions. As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post\_type = 'job'. This all LOOKS good in the database - the user, and post are inserted. The post\_author is indeed the same as the ID of the user who created it. But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author. I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp\_update\_post(); Here's the code to create the user, and then the post: ``` // Generate the password and create the user $password = wp_generate_password( 12, false ); $user_id = wp_create_user( $email_address, $password, $email_address ); //login wp_clear_auth_cookie(); wp_set_current_user ( $user_id ); wp_set_auth_cookie ( $user_id ); // Set the role $user = new WP_User( $user_id ); $user->set_role( 'subscriber' ); //Ready data for linked post type creation $new_post = array( 'post_content' => $email_address, 'post_status' => 'publish', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_id, 'post_title' => $post_name, 'post_name' => $post_name, 'post_type' => $user_type ); //Create the post $account_link_post_id = wp_insert_post($new_post); ``` ANY suggestions here would be great. Thank you in advance.
``` if ( ! empty( $_FILES['muti_files'] ) ) { $files = $_FILES['muti_files']; foreach ($files['name'] as $key => $value){ if ($files['name'][$key]){ $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); } $_FILES = array("muti_files" => $file); $i=1; foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attachment_id = media_handle_upload($file, $post_id); $vv .= $attachment_id . ","; $i++; } update_post_meta($post_id, '_product_image_gallery', $vv); } } ```
278,541
<p>I use the bellow template to display the first event from an ascendent list of custom post type events, created by a third party plugin. What I want is to exclude old events, displaying only the one actual, if we have one today, or the nearest. The event start date is saved in a <code>meta_key</code> with a value in the "Y-m-d" format (ex: 2017-10-27). How to accomplish this?</p> <pre><code>&lt;?php wp_reset_query(); $args = array( 'post_type' =&gt; 'events', 'posts_per_page' =&gt; 1, 'meta_key' =&gt; 'event_start_date', 'order' =&gt; 'ASC' ); $featured = new WP_Query($args); if ($featured-&gt;have_posts()): while($featured-&gt;have_posts()): $featured-&gt;the_post(); $featured_event_start = $post-&gt;event_start_date; $featured_event_end = $post-&gt;event_end_date; if (has_post_thumbnail()) : ?&gt; &lt;div class="featured-event-outer"&gt; &lt;div class="featured-event-inner"&gt; &lt;figure&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail('medium_large'); ?&gt;&lt;/a&gt;&lt;/figure&gt; &lt;h3 class="featured-event-title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;h3 class="featured-event-date"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php echo $featured_event_start; if ( $featured_event_end &amp;&amp; $featured_event_end != $featured_event_start ) { echo ' - ' . $featured_event_end; } ?&gt; &lt;/a&gt; &lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; else: ?&gt; &lt;!-- Placeholder content goes here --&gt; &lt;?php endif; wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 278545, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 2, "selected": false, "text": "<p>You need something like the following:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events',\n 'posts_per_page' =&gt; 1,\n 'meta_query' =&gt; array(\n 'meta_key' =&gt; 'event_start_date',\n 'type' =&gt; 'DATETIME', // You can also try changing it to TIME or DATE if it doesn't work\n 'meta_value' =&gt; date( \"Y-m-d\" ),\n 'meta_compare' =&gt; '&gt;',\n ),\n 'order' =&gt; 'ASC'\n);\n</code></pre>\n" }, { "answer_id": 278557, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 2, "selected": true, "text": "<p>OK, with some help from <a href=\"https://wordpress.stackexchange.com/a/12305/25187\">@jonathan-wold</a>, I figured out how to solve my problem. In my initial code I just replaced the <code>$args</code> part, accordingly to mentioned author, and this worked like a charm. This is the code:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events', // Tell WordPress which post type we want\n 'orderby' =&gt; 'meta_value', // We want to organize the events by date \n 'meta_key' =&gt; 'event_start_date', // Grab the \"start date\" field created via \"More Fields\" plugin (stored in YYYY-MM-DD format)\n 'order' =&gt; 'ASC', // ASC is the other option \n 'posts_per_page' =&gt; '1', // Let's show only one / the first event.\n 'meta_query' =&gt; array( // WordPress has all the results, now, return only the events after today's date\n array(\n 'key' =&gt; 'event_start_date', // Check the start date field\n 'value' =&gt; date(\"Y-m-d\"), // Set today's date (note the similar format)\n 'compare' =&gt; '&gt;=', // Return the ones greater than or equal to today's date\n 'type' =&gt; 'DATE' // Let WordPress know we're working with date\n )\n )\n);\n</code></pre>\n" }, { "answer_id": 314178, "author": "Samad", "author_id": 91339, "author_profile": "https://wordpress.stackexchange.com/users/91339", "pm_score": 2, "selected": false, "text": "<p>Update: the code worked for me after replacing event_start_date with _event_start_date in 'meta_key'</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events', // Tell WordPress which post type we want\n 'orderby' =&gt; 'meta_value', // We want to organize the events by date \n 'meta_key' =&gt; '_event_start_date', // Grab the \"start date\" field created via \"More Fields\" plugin (stored in YYYY-MM-DD format)\n 'order' =&gt; 'ASC', // ASC is the other option \n 'posts_per_page' =&gt; '1', // Let's show only one / the first event.\n 'meta_query' =&gt; array( // WordPress has all the results, now, return only the events after today's date\n array(\n 'key' =&gt; '_event_start_date', // Check the start date field\n 'value' =&gt; date(\"Y-m-d\"), // Set today's date (note the similar format)\n 'compare' =&gt; '&gt;=', // Return the ones greater than or equal to today's date\n 'type' =&gt; 'DATE' // Let WordPress know we're working with date\n )\n )\n);\n</code></pre>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I use the bellow template to display the first event from an ascendent list of custom post type events, created by a third party plugin. What I want is to exclude old events, displaying only the one actual, if we have one today, or the nearest. The event start date is saved in a `meta_key` with a value in the "Y-m-d" format (ex: 2017-10-27). How to accomplish this? ``` <?php wp_reset_query(); $args = array( 'post_type' => 'events', 'posts_per_page' => 1, 'meta_key' => 'event_start_date', 'order' => 'ASC' ); $featured = new WP_Query($args); if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post(); $featured_event_start = $post->event_start_date; $featured_event_end = $post->event_end_date; if (has_post_thumbnail()) : ?> <div class="featured-event-outer"> <div class="featured-event-inner"> <figure><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium_large'); ?></a></figure> <h3 class="featured-event-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <h3 class="featured-event-date"> <a href="<?php the_permalink(); ?>"><?php echo $featured_event_start; if ( $featured_event_end && $featured_event_end != $featured_event_start ) { echo ' - ' . $featured_event_end; } ?> </a> </h3> </div> </div> <?php endif; ?> <?php endwhile; else: ?> <!-- Placeholder content goes here --> <?php endif; wp_reset_postdata(); ?> ```
OK, with some help from [@jonathan-wold](https://wordpress.stackexchange.com/a/12305/25187), I figured out how to solve my problem. In my initial code I just replaced the `$args` part, accordingly to mentioned author, and this worked like a charm. This is the code: ``` $args = array( 'post_type' => 'events', // Tell WordPress which post type we want 'orderby' => 'meta_value', // We want to organize the events by date 'meta_key' => 'event_start_date', // Grab the "start date" field created via "More Fields" plugin (stored in YYYY-MM-DD format) 'order' => 'ASC', // ASC is the other option 'posts_per_page' => '1', // Let's show only one / the first event. 'meta_query' => array( // WordPress has all the results, now, return only the events after today's date array( 'key' => 'event_start_date', // Check the start date field 'value' => date("Y-m-d"), // Set today's date (note the similar format) 'compare' => '>=', // Return the ones greater than or equal to today's date 'type' => 'DATE' // Let WordPress know we're working with date ) ) ); ```
278,555
<p>How can I submit pull request to other's plugin, which is hosted at <strong>wordpress.org</strong>?</p>
[ { "answer_id": 278545, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 2, "selected": false, "text": "<p>You need something like the following:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events',\n 'posts_per_page' =&gt; 1,\n 'meta_query' =&gt; array(\n 'meta_key' =&gt; 'event_start_date',\n 'type' =&gt; 'DATETIME', // You can also try changing it to TIME or DATE if it doesn't work\n 'meta_value' =&gt; date( \"Y-m-d\" ),\n 'meta_compare' =&gt; '&gt;',\n ),\n 'order' =&gt; 'ASC'\n);\n</code></pre>\n" }, { "answer_id": 278557, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 2, "selected": true, "text": "<p>OK, with some help from <a href=\"https://wordpress.stackexchange.com/a/12305/25187\">@jonathan-wold</a>, I figured out how to solve my problem. In my initial code I just replaced the <code>$args</code> part, accordingly to mentioned author, and this worked like a charm. This is the code:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events', // Tell WordPress which post type we want\n 'orderby' =&gt; 'meta_value', // We want to organize the events by date \n 'meta_key' =&gt; 'event_start_date', // Grab the \"start date\" field created via \"More Fields\" plugin (stored in YYYY-MM-DD format)\n 'order' =&gt; 'ASC', // ASC is the other option \n 'posts_per_page' =&gt; '1', // Let's show only one / the first event.\n 'meta_query' =&gt; array( // WordPress has all the results, now, return only the events after today's date\n array(\n 'key' =&gt; 'event_start_date', // Check the start date field\n 'value' =&gt; date(\"Y-m-d\"), // Set today's date (note the similar format)\n 'compare' =&gt; '&gt;=', // Return the ones greater than or equal to today's date\n 'type' =&gt; 'DATE' // Let WordPress know we're working with date\n )\n )\n);\n</code></pre>\n" }, { "answer_id": 314178, "author": "Samad", "author_id": 91339, "author_profile": "https://wordpress.stackexchange.com/users/91339", "pm_score": 2, "selected": false, "text": "<p>Update: the code worked for me after replacing event_start_date with _event_start_date in 'meta_key'</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events', // Tell WordPress which post type we want\n 'orderby' =&gt; 'meta_value', // We want to organize the events by date \n 'meta_key' =&gt; '_event_start_date', // Grab the \"start date\" field created via \"More Fields\" plugin (stored in YYYY-MM-DD format)\n 'order' =&gt; 'ASC', // ASC is the other option \n 'posts_per_page' =&gt; '1', // Let's show only one / the first event.\n 'meta_query' =&gt; array( // WordPress has all the results, now, return only the events after today's date\n array(\n 'key' =&gt; '_event_start_date', // Check the start date field\n 'value' =&gt; date(\"Y-m-d\"), // Set today's date (note the similar format)\n 'compare' =&gt; '&gt;=', // Return the ones greater than or equal to today's date\n 'type' =&gt; 'DATE' // Let WordPress know we're working with date\n )\n )\n);\n</code></pre>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278555", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
How can I submit pull request to other's plugin, which is hosted at **wordpress.org**?
OK, with some help from [@jonathan-wold](https://wordpress.stackexchange.com/a/12305/25187), I figured out how to solve my problem. In my initial code I just replaced the `$args` part, accordingly to mentioned author, and this worked like a charm. This is the code: ``` $args = array( 'post_type' => 'events', // Tell WordPress which post type we want 'orderby' => 'meta_value', // We want to organize the events by date 'meta_key' => 'event_start_date', // Grab the "start date" field created via "More Fields" plugin (stored in YYYY-MM-DD format) 'order' => 'ASC', // ASC is the other option 'posts_per_page' => '1', // Let's show only one / the first event. 'meta_query' => array( // WordPress has all the results, now, return only the events after today's date array( 'key' => 'event_start_date', // Check the start date field 'value' => date("Y-m-d"), // Set today's date (note the similar format) 'compare' => '>=', // Return the ones greater than or equal to today's date 'type' => 'DATE' // Let WordPress know we're working with date ) ) ); ```
278,561
<p>Should I able to change URL structure of WordPress blog? (Free WordPress hosted blog) </p> <p>Right now I have this way: (see URL structure)</p> <pre><code>helloworld.wordpress.com/london </code></pre> <p>But I want to use as this way:</p> <pre><code>helloworld.wordpress.com/carhire/uk/london </code></pre> <p>Is this achievable?</p>
[ { "answer_id": 278562, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Yes, this is achievable and quite simple to do so. Go to <strong>Settings</strong> > <strong>Permalinks</strong> in your admin area.</p>\n\n<p>There you should be able to select <strong>Custom</strong> and use a value like (if you want all URLs to start with /carhire/uk/)</p>\n\n<pre><code>/carhire/uk/%postname%/\n</code></pre>\n\n<p>If your logic is more complex, I suggest using a plugin such as <a href=\"https://wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow noreferrer\">Custom Permalinks</a>.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.</p>\n" }, { "answer_id": 278563, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 2, "selected": false, "text": "<p>If you use wordpress.com, you can't change the permalinks. You have to use the original wordpress.org version and host it on your favourite webhoster.</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278561", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126838/" ]
Should I able to change URL structure of WordPress blog? (Free WordPress hosted blog) Right now I have this way: (see URL structure) ``` helloworld.wordpress.com/london ``` But I want to use as this way: ``` helloworld.wordpress.com/carhire/uk/london ``` Is this achievable?
Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area. There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/) ``` /carhire/uk/%postname%/ ``` If your logic is more complex, I suggest using a plugin such as [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/). **Edit:** I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.
278,580
<p>I can't get this line of code translation ready.</p> <pre><code>&lt;?php comment_form(array ('title_reply' =&gt; 'Leave a comment')); ?&gt; </code></pre> <p>Thank you very much! Best wishes, Pierre</p>
[ { "answer_id": 278562, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Yes, this is achievable and quite simple to do so. Go to <strong>Settings</strong> > <strong>Permalinks</strong> in your admin area.</p>\n\n<p>There you should be able to select <strong>Custom</strong> and use a value like (if you want all URLs to start with /carhire/uk/)</p>\n\n<pre><code>/carhire/uk/%postname%/\n</code></pre>\n\n<p>If your logic is more complex, I suggest using a plugin such as <a href=\"https://wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow noreferrer\">Custom Permalinks</a>.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.</p>\n" }, { "answer_id": 278563, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 2, "selected": false, "text": "<p>If you use wordpress.com, you can't change the permalinks. You have to use the original wordpress.org version and host it on your favourite webhoster.</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126835/" ]
I can't get this line of code translation ready. ``` <?php comment_form(array ('title_reply' => 'Leave a comment')); ?> ``` Thank you very much! Best wishes, Pierre
Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area. There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/) ``` /carhire/uk/%postname%/ ``` If your logic is more complex, I suggest using a plugin such as [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/). **Edit:** I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.
278,612
<p>I´am creating a Plugin. For this I wrote my own templates. Now I want to have the templeates files in my Plugin directory. </p> <p>But that doenst work fine. Since I used the Plugin directory, wordpress doesent know that are my templates are wp templeates. What is the best way to let WP know, that these files are a wordpress Templates? </p> <p>Thanks for answer :)</p>
[ { "answer_id": 278562, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Yes, this is achievable and quite simple to do so. Go to <strong>Settings</strong> > <strong>Permalinks</strong> in your admin area.</p>\n\n<p>There you should be able to select <strong>Custom</strong> and use a value like (if you want all URLs to start with /carhire/uk/)</p>\n\n<pre><code>/carhire/uk/%postname%/\n</code></pre>\n\n<p>If your logic is more complex, I suggest using a plugin such as <a href=\"https://wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow noreferrer\">Custom Permalinks</a>.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.</p>\n" }, { "answer_id": 278563, "author": "Sören Wrede", "author_id": 68682, "author_profile": "https://wordpress.stackexchange.com/users/68682", "pm_score": 2, "selected": false, "text": "<p>If you use wordpress.com, you can't change the permalinks. You have to use the original wordpress.org version and host it on your favourite webhoster.</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126872/" ]
I´am creating a Plugin. For this I wrote my own templates. Now I want to have the templeates files in my Plugin directory. But that doenst work fine. Since I used the Plugin directory, wordpress doesent know that are my templates are wp templeates. What is the best way to let WP know, that these files are a wordpress Templates? Thanks for answer :)
Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area. There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/) ``` /carhire/uk/%postname%/ ``` If your logic is more complex, I suggest using a plugin such as [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/). **Edit:** I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.
278,613
<p>I have the following args array</p> <pre><code>{ "ordreby":"meta_value_num", "meta_key":"_price", "posts_per_page":10, "offset":0, "post_type":"product", "post_status":"publish", "order":"asc", "suppress_filters":false, } </code></pre> <p>when i do </p> <pre><code> $myposts = get_posts($args); </code></pre> <p>the order by <strong>_price</strong> (or other meta keys) is not working. </p> <p>any idea?</p>
[ { "answer_id": 278617, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": 1, "selected": false, "text": "<p><code>meta_query</code> should be an array of arrays like:</p>\n\n<pre><code>...\n'meta_query' =&gt; [\n [\n 'key' =&gt; '...',\n 'value' =&gt; '...',\n ],\n],\n...\n</code></pre>\n" }, { "answer_id": 279808, "author": "Miguel Ruiz Bas", "author_id": 122895, "author_profile": "https://wordpress.stackexchange.com/users/122895", "pm_score": 1, "selected": true, "text": "<p>Change </p>\n\n<p><code>\"ordreby\":\"meta_value_num\"</code></p>\n\n<p>for</p>\n\n<pre><code>\"orderby\":\"meta_value_num\"\n</code></pre>\n\n<p>a dyslexic error xD</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122895/" ]
I have the following args array ``` { "ordreby":"meta_value_num", "meta_key":"_price", "posts_per_page":10, "offset":0, "post_type":"product", "post_status":"publish", "order":"asc", "suppress_filters":false, } ``` when i do ``` $myposts = get_posts($args); ``` the order by **\_price** (or other meta keys) is not working. any idea?
Change `"ordreby":"meta_value_num"` for ``` "orderby":"meta_value_num" ``` a dyslexic error xD
278,628
<p>I have created the <strong>Read more</strong> in my posts, but when I add the php tag </p> <pre><code>&lt;?php the_content(); ?&gt; </code></pre> <p>...it shows the post content with <strong>read more</strong> button. I only want to display the button, with no post content.</p> <p>Here is a picture of my design .<img src="https://i.stack.imgur.com/8UYN9.png" alt="Desired design"></p> <p>In the picture, I only display the button without text from the post. How can i do that with WordPress php code?</p>
[ { "answer_id": 278638, "author": "Osama Elzero", "author_id": 126781, "author_profile": "https://wordpress.stackexchange.com/users/126781", "pm_score": 2, "selected": false, "text": "<p>You can achieve this with many ways. First thing you need to use </p>\n\n<pre><code>the_excerpt() \n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>the_content()\n</code></pre>\n\n<p>and in your functions.php file you can add this function to return 0 text from post text.</p>\n\n<pre><code>function custom_excerpt_length($length) {\n if (is_home()) {\n return 0;\n }\n}\n\nadd_filter('excerpt_length', 'custom_excerpt_length');\n</code></pre>\n\n<p>This code check if this is homepage you can change the condition to met your needs.</p>\n" }, { "answer_id": 278646, "author": "Greg Burkett", "author_id": 103916, "author_profile": "https://wordpress.stackexchange.com/users/103916", "pm_score": 0, "selected": false, "text": "<p>If you JUST need the button, there's probably a different way to go about this:</p>\n\n<p><code>&lt;a href=\"&lt;?php the_permalink();?&gt;\" class=\"your-button-class\"&gt;Read More&lt;/a&gt;</code></p>\n\n<p>Only loads what you need (the permalink) and doesn't bother with extra functions, excerpt length, etc.</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126889/" ]
I have created the **Read more** in my posts, but when I add the php tag ``` <?php the_content(); ?> ``` ...it shows the post content with **read more** button. I only want to display the button, with no post content. Here is a picture of my design .![Desired design](https://i.stack.imgur.com/8UYN9.png) In the picture, I only display the button without text from the post. How can i do that with WordPress php code?
You can achieve this with many ways. First thing you need to use ``` the_excerpt() ``` instead of ``` the_content() ``` and in your functions.php file you can add this function to return 0 text from post text. ``` function custom_excerpt_length($length) { if (is_home()) { return 0; } } add_filter('excerpt_length', 'custom_excerpt_length'); ``` This code check if this is homepage you can change the condition to met your needs.
278,631
<p>I am trying to get a child theme to work. At first it didn't load because it didn't recognise it as a child theme. Now it does work but when I activate it, it loads a version of my page seemingly without any css or something. There's only text and images there, but no styling. Is it that it isn't using the parent theme fully or something?</p> <p>I am just starting with Wordpress so I'm sorry if I'm not very clear or using the right terminology. Thanks in advance.</p> <p>This is my functions.php file:</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_style = ‘twenty seventeen-style’; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?&gt; </code></pre>
[ { "answer_id": 278638, "author": "Osama Elzero", "author_id": 126781, "author_profile": "https://wordpress.stackexchange.com/users/126781", "pm_score": 2, "selected": false, "text": "<p>You can achieve this with many ways. First thing you need to use </p>\n\n<pre><code>the_excerpt() \n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>the_content()\n</code></pre>\n\n<p>and in your functions.php file you can add this function to return 0 text from post text.</p>\n\n<pre><code>function custom_excerpt_length($length) {\n if (is_home()) {\n return 0;\n }\n}\n\nadd_filter('excerpt_length', 'custom_excerpt_length');\n</code></pre>\n\n<p>This code check if this is homepage you can change the condition to met your needs.</p>\n" }, { "answer_id": 278646, "author": "Greg Burkett", "author_id": 103916, "author_profile": "https://wordpress.stackexchange.com/users/103916", "pm_score": 0, "selected": false, "text": "<p>If you JUST need the button, there's probably a different way to go about this:</p>\n\n<p><code>&lt;a href=\"&lt;?php the_permalink();?&gt;\" class=\"your-button-class\"&gt;Read More&lt;/a&gt;</code></p>\n\n<p>Only loads what you need (the permalink) and doesn't bother with extra functions, excerpt length, etc.</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278631", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126890/" ]
I am trying to get a child theme to work. At first it didn't load because it didn't recognise it as a child theme. Now it does work but when I activate it, it loads a version of my page seemingly without any css or something. There's only text and images there, but no styling. Is it that it isn't using the parent theme fully or something? I am just starting with Wordpress so I'm sorry if I'm not very clear or using the right terminology. Thanks in advance. This is my functions.php file: ``` <?php function my_theme_enqueue_styles() { $parent_style = ‘twenty seventeen-style’; 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' ); ?> ```
You can achieve this with many ways. First thing you need to use ``` the_excerpt() ``` instead of ``` the_content() ``` and in your functions.php file you can add this function to return 0 text from post text. ``` function custom_excerpt_length($length) { if (is_home()) { return 0; } } add_filter('excerpt_length', 'custom_excerpt_length'); ``` This code check if this is homepage you can change the condition to met your needs.
278,647
<p>I have tried adding this to <code>style.css</code>:</p> <pre><code>.sidebar, .widget-area, .secondary { position: absolute margin-left: 120px; max-width: 250px; } </code></pre> <p>But it won't move. If I remove <code>position:absolute</code>, it is pushed down, getting under all the other content.</p>
[ { "answer_id": 279137, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>there are 2 pieces of code in the css:</p>\n\n<pre><code>.has-sidebar #secondary {\n float: right;\n padding-top: 0;\n width: 36%; //change this to change the sidebar width\n}\n\n.has-sidebar:not(.error404) #primary {\n float: left;\n width: 58%; //counter the changes above with this code (increase this if you decrease the sidebar etc..\n}\n</code></pre>\n\n<p>if you're looking to change the overall width of the content so that the sidebar moves altogether more to the right than increase the overall wrap width by changing this code:</p>\n\n<pre><code>.wrap {\n max-width: 1000px; // increase this number to increase the width of your site.\n padding-left: 3em;\n padding-right: 3em;\n}\n</code></pre>\n\n<p>Of course these changes can be made by adding these to your style.css of your child theme</p>\n" }, { "answer_id": 279138, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>You have 2 options:</p>\n\n<p><strong>Option 1.</strong></p>\n\n<p>Just add negative margin to the sidebar CSS like this:</p>\n\n<pre><code>@media screen and (min-width: 48em){\n #secondary{\n margin-right:-150px;\n }\n}\n</code></pre>\n\n<p><strong>Option 2.</strong></p>\n\n<p>Add more max-width to the wrapper:</p>\n\n<pre><code>@media screen and (min-width: 48em){\n .wrap{\n max-width: 1340px;//the default is 1000\n padding-left: 348px;//you have to add padding left so the left side doesnt move, the amount needs to be proportional to the amount of max-width you are incrementing\n }\n}\n</code></pre>\n\n<p>i added the media query, its needed so this CSS doesnt affect the mobile view.</p>\n" } ]
2017/08/30
[ "https://wordpress.stackexchange.com/questions/278647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126901/" ]
I have tried adding this to `style.css`: ``` .sidebar, .widget-area, .secondary { position: absolute margin-left: 120px; max-width: 250px; } ``` But it won't move. If I remove `position:absolute`, it is pushed down, getting under all the other content.
You have 2 options: **Option 1.** Just add negative margin to the sidebar CSS like this: ``` @media screen and (min-width: 48em){ #secondary{ margin-right:-150px; } } ``` **Option 2.** Add more max-width to the wrapper: ``` @media screen and (min-width: 48em){ .wrap{ max-width: 1340px;//the default is 1000 padding-left: 348px;//you have to add padding left so the left side doesnt move, the amount needs to be proportional to the amount of max-width you are incrementing } } ``` i added the media query, its needed so this CSS doesnt affect the mobile view.
278,655
<p>HTML:</p> <pre><code>&lt;header&gt; &lt;!-- I want to add html code here --&gt; &lt;/header&gt; </code></pre> <p>Function:</p> <pre><code> function add_html_to_header { &lt;b&gt; Hello World &lt;/b&gt; } add_action('','add_html_to_header') </code></pre> <p>Expected Html results:</p> <pre><code>&lt;header id="header"&gt; &lt;b&gt; Hello World &lt;/b&gt; &lt;/header&gt; </code></pre> <p><strong>EDIT:</strong> Is it possible without using <code>Javascript</code>? </p>
[ { "answer_id": 278656, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 2, "selected": false, "text": "<p>You can add html to the site head using this function:</p>\n\n<pre><code>// Add scripts to wp_head()\nfunction add_head_html() { ?&gt;\n &lt;!-- html goes here --&gt;\n &lt;?php }\n add_action( 'wp_head', 'add_head_html' );\n</code></pre>\n\n<p>But if you're talking about the html element <code>&lt;header&gt;</code> (as it sounds like from your edits) it sounds like overcomplicating things, but you might want to look at injecting it with jquery into the right spot using a solution such as this:\n<a href=\"https://stackoverflow.com/a/9866637/3387817\">https://stackoverflow.com/a/9866637/3387817</a></p>\n" }, { "answer_id": 278659, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 2, "selected": false, "text": "<p>You can use action hooks: </p>\n\n<pre><code>&lt;header&gt;\n &lt;!-- I want to add html code here --&gt;\n &lt;?php do_action('wpse_myheader'); ?&gt;\n&lt;/header&gt;\n</code></pre>\n\n<p>Then you can use:</p>\n\n<pre><code>function add_html_to_header { ?&gt;\n &lt;b&gt; Hello World &lt;/b&gt;\n&lt;?php }\n add_action('wpse_myheader','add_html_to_header');\n</code></pre>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278655", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96537/" ]
HTML: ``` <header> <!-- I want to add html code here --> </header> ``` Function: ``` function add_html_to_header { <b> Hello World </b> } add_action('','add_html_to_header') ``` Expected Html results: ``` <header id="header"> <b> Hello World </b> </header> ``` **EDIT:** Is it possible without using `Javascript`?
You can add html to the site head using this function: ``` // Add scripts to wp_head() function add_head_html() { ?> <!-- html goes here --> <?php } add_action( 'wp_head', 'add_head_html' ); ``` But if you're talking about the html element `<header>` (as it sounds like from your edits) it sounds like overcomplicating things, but you might want to look at injecting it with jquery into the right spot using a solution such as this: <https://stackoverflow.com/a/9866637/3387817>
278,662
<p>I'm trying to enqueue a JavaScript file in the header of my website.</p> <p>If I add the following in my main plugin file the JS is included in the header:</p> <pre><code>function wpdocs_theme_name_scripts() { wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js'); wp_enqueue_script('googlesearch'); } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); </code></pre> <p>But I want to include the JS for a specific shortcode only, I add the following in the main plugin file:</p> <pre><code>function wpdocs_theme_name_scripts() { wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js'); } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); </code></pre> <p>And the following in the shortcode:</p> <pre><code>wp_enqueue_script('googlesearch'); </code></pre> <p>Now the JS file is included in the footer of the website.</p> <p>I've tried manually specifying that the JS should be loaded in the header like so but it still loads it in the footer:</p> <pre><code>wp_enqueue_script( 'googlesearch', 'https://maps.googleapis.com/maps/api/js', array(), '1.0.0', false ); </code></pre> <p>Does anyone have any idea why this is happening? Appreciated any help!</p>
[ { "answer_id": 278666, "author": "KAGG Design", "author_id": 108721, "author_profile": "https://wordpress.stackexchange.com/users/108721", "pm_score": 2, "selected": false, "text": "<p>Page is created and output in the following order: header, content, footer. Shorcode is executed during the construction of the page content, when header is already output on the page. So, it is impossible to add any script to header on this stage: it is too late. </p>\n" }, { "answer_id": 278678, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>While it is a pretty \"dirty\" fix, you can achieve the wanted effect like this:</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n\n wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');\n\n if(is_singular()){\n global $wp_query;\n $postid = $wp_query-&gt;get_queried_object_id();\n $mypost = get_post($postid);\n $unfiltered_content = $mypost-&gt;post_content;\n if(has_shortcode($unfiltered_content,'&lt;SHORTCODE WITHOUT BRACKETS&gt;')){\n wp_enqueue_script('googlesearch');\n }\n } \n}\n\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p>Happy Coding, Kuchenundkakao</p>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81594/" ]
I'm trying to enqueue a JavaScript file in the header of my website. If I add the following in my main plugin file the JS is included in the header: ``` function wpdocs_theme_name_scripts() { wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js'); wp_enqueue_script('googlesearch'); } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); ``` But I want to include the JS for a specific shortcode only, I add the following in the main plugin file: ``` function wpdocs_theme_name_scripts() { wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js'); } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); ``` And the following in the shortcode: ``` wp_enqueue_script('googlesearch'); ``` Now the JS file is included in the footer of the website. I've tried manually specifying that the JS should be loaded in the header like so but it still loads it in the footer: ``` wp_enqueue_script( 'googlesearch', 'https://maps.googleapis.com/maps/api/js', array(), '1.0.0', false ); ``` Does anyone have any idea why this is happening? Appreciated any help!
Page is created and output in the following order: header, content, footer. Shorcode is executed during the construction of the page content, when header is already output on the page. So, it is impossible to add any script to header on this stage: it is too late.
278,696
<p>I've been trying to change the title in a dynamic page without any luck.</p> <p>What I did is I created two page-templates from where I load items (occasions) from an external database. In one page-template I load the single-page occasion:</p> <pre><code>&lt;?php include 'Occasions-files/single.php';?&gt; </code></pre> <p>And the second page-template I load an overview of the occasions:</p> <pre><code>&lt;?php include 'Occasions-files/file.php';?&gt; </code></pre> <p>Now the title is default from the SEO plugin. I've tried All-in-One SEO as well as Yoast SEO but can't seem to overwrite the title. What I want is to change the title from single.php into the occasion name but leave all the other pages to the SEO plugin.</p> <p>I'm not quite experienced with this and I'm not sure where to start. For testing purpose I've tried to put test manually before the get_header, then it shows the manually added title, but my header is messed up. When I put the title after the get_header, it loads the header ok but the title isn't shown and is still default</p> <pre><code>&lt;title&gt;test&lt;/title&gt; &lt;?php get_header(); ?&gt; </code></pre> <p>Also, I've tried to add a filter (to the functions.php) but this was also without any results or maybe I have no clue on how to insert it..?</p> <pre><code>function custom_title_function($custom_title) { $custom_title['title'] = "Test Title"; return $custom_title; } add_filter( 'document_title_parts', 'custom_title_function' ); </code></pre> <p>Anyone has an idea on how to resolve this? Many thanks in advanced!</p>
[ { "answer_id": 278724, "author": "James", "author_id": 34484, "author_profile": "https://wordpress.stackexchange.com/users/34484", "pm_score": 1, "selected": false, "text": "<p>Just to make sure, does the title tag in your <code>&lt;head&gt;</code> area (presumably in header.php) look like this?</p>\n\n<pre><code>&lt;title&gt;&lt;?php wp_title(); ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>It has to be like that for Yoast to work with it, and be able to override titles.</p>\n\n<p>Anyway if you add this to your single.php (or at least before <code>get_header()</code> is run for that page) you should be able to modify the page title:</p>\n\n<pre><code>function custom_page_title( $title ){\n $return = $title;\n\n // You can check what the current post is via $wp_query-&gt;post\n global $wp_query;\n if( isset($wp_query-&gt;post) ){\n $id = $wp_query-&gt;post-&gt;ID;\n $post_title = $wp_query-&gt;post-&gt;post_title;\n // etc\n\n $return = $post_title;\n }\n\n // Or just outright change the title\n $return = 'test';\n\n return $return;\n}\nadd_filter('wp_title', 'custom_page_title', 20);\n</code></pre>\n\n<p>Another thing to note here is that if you're using Yoast, you have to make sure that this function runs after Yoast modifies the title, otherwise Yoast will overwrite whatever changes you make. This is where the <code>20</code> comes in, as the third parameter in <code>add_filter()</code>. I think Yoast runs its filter at 15, so running yours at 20 (or any number higher than 15) will make sure your filter runs after Yoast's filter.</p>\n" }, { "answer_id": 325958, "author": "Anis", "author_id": 159277, "author_profile": "https://wordpress.stackexchange.com/users/159277", "pm_score": -1, "selected": false, "text": "<pre><code>if(isset($_GET['v'])) {\n if($_GET['v'] == \"about\") {\n\n $title = \"About Us\";\n}\nelse if ($_GET['v'] == \"contact\") {\n $title = \"Contact Us\";\n}\n}\nelse {\n $title = \"Home\";\n}\n\n&lt;title&gt;&lt;?php echo $title;?&gt;&lt;/title&gt;\n</code></pre>\n" }, { "answer_id": 373634, "author": "Manioo", "author_id": 193612, "author_profile": "https://wordpress.stackexchange.com/users/193612", "pm_score": 0, "selected": false, "text": "<p>if you are using All in one SEO you can use overwrite your dynamic wp titles with the help of the following filter hook</p>\n<pre><code>add_filter( 'aioseop_title', 'change_wordpress_seo_title' );\n\nfunction change_wordpress_seo_title( $title ){\n $title = 'modified title';\n return $title;\n}\n</code></pre>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126415/" ]
I've been trying to change the title in a dynamic page without any luck. What I did is I created two page-templates from where I load items (occasions) from an external database. In one page-template I load the single-page occasion: ``` <?php include 'Occasions-files/single.php';?> ``` And the second page-template I load an overview of the occasions: ``` <?php include 'Occasions-files/file.php';?> ``` Now the title is default from the SEO plugin. I've tried All-in-One SEO as well as Yoast SEO but can't seem to overwrite the title. What I want is to change the title from single.php into the occasion name but leave all the other pages to the SEO plugin. I'm not quite experienced with this and I'm not sure where to start. For testing purpose I've tried to put test manually before the get\_header, then it shows the manually added title, but my header is messed up. When I put the title after the get\_header, it loads the header ok but the title isn't shown and is still default ``` <title>test</title> <?php get_header(); ?> ``` Also, I've tried to add a filter (to the functions.php) but this was also without any results or maybe I have no clue on how to insert it..? ``` function custom_title_function($custom_title) { $custom_title['title'] = "Test Title"; return $custom_title; } add_filter( 'document_title_parts', 'custom_title_function' ); ``` Anyone has an idea on how to resolve this? Many thanks in advanced!
Just to make sure, does the title tag in your `<head>` area (presumably in header.php) look like this? ``` <title><?php wp_title(); ?></title> ``` It has to be like that for Yoast to work with it, and be able to override titles. Anyway if you add this to your single.php (or at least before `get_header()` is run for that page) you should be able to modify the page title: ``` function custom_page_title( $title ){ $return = $title; // You can check what the current post is via $wp_query->post global $wp_query; if( isset($wp_query->post) ){ $id = $wp_query->post->ID; $post_title = $wp_query->post->post_title; // etc $return = $post_title; } // Or just outright change the title $return = 'test'; return $return; } add_filter('wp_title', 'custom_page_title', 20); ``` Another thing to note here is that if you're using Yoast, you have to make sure that this function runs after Yoast modifies the title, otherwise Yoast will overwrite whatever changes you make. This is where the `20` comes in, as the third parameter in `add_filter()`. I think Yoast runs its filter at 15, so running yours at 20 (or any number higher than 15) will make sure your filter runs after Yoast's filter.
278,701
<p>this is my jscript</p> <pre><code> &lt;script&gt; jQuery(document).ready(function($){ $("button").on('click', function(event) { event.preventDefault(); $('html, body').stop().animate({ scrollTop: $("#button").offset().top }, 1000); }); }); &lt;/script&gt; </code></pre> <p>this is my custom button </p> <pre><code> &lt;button name="button" style="margin: 9px 0 20px 0;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" &gt;HAVE A QUESTIONS&lt;/button&gt; </code></pre> <p>and this is scroll bottom location (to scroll top button to this location)</p> <pre><code>&lt;!-- Have Question --&gt; &lt;div class="content-teaser container text-center"&gt; &lt;h3 class="text-red center-block text-center" id="button" &gt;Have Questions?&lt;/h3&gt; &lt;p&gt;Talk with someone on the team We're here to answer question&lt;/p&gt; </code></pre> <p>all is work well but console put this error</p> <p>TypeError: $(...).offset(...) is undefined</p> <p>what is this error i can't understand plz solved this error because this error conflict to other script and my page doesn't work</p>
[ { "answer_id": 278724, "author": "James", "author_id": 34484, "author_profile": "https://wordpress.stackexchange.com/users/34484", "pm_score": 1, "selected": false, "text": "<p>Just to make sure, does the title tag in your <code>&lt;head&gt;</code> area (presumably in header.php) look like this?</p>\n\n<pre><code>&lt;title&gt;&lt;?php wp_title(); ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>It has to be like that for Yoast to work with it, and be able to override titles.</p>\n\n<p>Anyway if you add this to your single.php (or at least before <code>get_header()</code> is run for that page) you should be able to modify the page title:</p>\n\n<pre><code>function custom_page_title( $title ){\n $return = $title;\n\n // You can check what the current post is via $wp_query-&gt;post\n global $wp_query;\n if( isset($wp_query-&gt;post) ){\n $id = $wp_query-&gt;post-&gt;ID;\n $post_title = $wp_query-&gt;post-&gt;post_title;\n // etc\n\n $return = $post_title;\n }\n\n // Or just outright change the title\n $return = 'test';\n\n return $return;\n}\nadd_filter('wp_title', 'custom_page_title', 20);\n</code></pre>\n\n<p>Another thing to note here is that if you're using Yoast, you have to make sure that this function runs after Yoast modifies the title, otherwise Yoast will overwrite whatever changes you make. This is where the <code>20</code> comes in, as the third parameter in <code>add_filter()</code>. I think Yoast runs its filter at 15, so running yours at 20 (or any number higher than 15) will make sure your filter runs after Yoast's filter.</p>\n" }, { "answer_id": 325958, "author": "Anis", "author_id": 159277, "author_profile": "https://wordpress.stackexchange.com/users/159277", "pm_score": -1, "selected": false, "text": "<pre><code>if(isset($_GET['v'])) {\n if($_GET['v'] == \"about\") {\n\n $title = \"About Us\";\n}\nelse if ($_GET['v'] == \"contact\") {\n $title = \"Contact Us\";\n}\n}\nelse {\n $title = \"Home\";\n}\n\n&lt;title&gt;&lt;?php echo $title;?&gt;&lt;/title&gt;\n</code></pre>\n" }, { "answer_id": 373634, "author": "Manioo", "author_id": 193612, "author_profile": "https://wordpress.stackexchange.com/users/193612", "pm_score": 0, "selected": false, "text": "<p>if you are using All in one SEO you can use overwrite your dynamic wp titles with the help of the following filter hook</p>\n<pre><code>add_filter( 'aioseop_title', 'change_wordpress_seo_title' );\n\nfunction change_wordpress_seo_title( $title ){\n $title = 'modified title';\n return $title;\n}\n</code></pre>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124829/" ]
this is my jscript ``` <script> jQuery(document).ready(function($){ $("button").on('click', function(event) { event.preventDefault(); $('html, body').stop().animate({ scrollTop: $("#button").offset().top }, 1000); }); }); </script> ``` this is my custom button ``` <button name="button" style="margin: 9px 0 20px 0;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" >HAVE A QUESTIONS</button> ``` and this is scroll bottom location (to scroll top button to this location) ``` <!-- Have Question --> <div class="content-teaser container text-center"> <h3 class="text-red center-block text-center" id="button" >Have Questions?</h3> <p>Talk with someone on the team We're here to answer question</p> ``` all is work well but console put this error TypeError: $(...).offset(...) is undefined what is this error i can't understand plz solved this error because this error conflict to other script and my page doesn't work
Just to make sure, does the title tag in your `<head>` area (presumably in header.php) look like this? ``` <title><?php wp_title(); ?></title> ``` It has to be like that for Yoast to work with it, and be able to override titles. Anyway if you add this to your single.php (or at least before `get_header()` is run for that page) you should be able to modify the page title: ``` function custom_page_title( $title ){ $return = $title; // You can check what the current post is via $wp_query->post global $wp_query; if( isset($wp_query->post) ){ $id = $wp_query->post->ID; $post_title = $wp_query->post->post_title; // etc $return = $post_title; } // Or just outright change the title $return = 'test'; return $return; } add_filter('wp_title', 'custom_page_title', 20); ``` Another thing to note here is that if you're using Yoast, you have to make sure that this function runs after Yoast modifies the title, otherwise Yoast will overwrite whatever changes you make. This is where the `20` comes in, as the third parameter in `add_filter()`. I think Yoast runs its filter at 15, so running yours at 20 (or any number higher than 15) will make sure your filter runs after Yoast's filter.
278,706
<p>I wanted to set value of <strong>WP option</strong> (more specifically - 'admin_email') by using plugin, <strong>its option</strong> (plugin option) and update_option().</p> <p>I tried using lines like below, but when plugin code contains them - it gets disabled. Any ideas why?</p> <pre><code>$helper = (get_option('plugin-option'); update_option('admin_email', $helper ); </code></pre> <p><strong>EDIT</strong> </p> <pre><code>$helper = get_option('plugin-option'); update_option('admin_email', $helper ); </code></pre> <p>Now it's not disabling (due to bracket), but it still doesn't change option value</p>
[ { "answer_id": 278707, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": -1, "selected": false, "text": "<p>You've got an extra bracket:</p>\n\n<pre><code>$helper = (get_option('plugin-option');\n</code></pre>\n\n<p>Needs to be</p>\n\n<pre><code>$helper = get_option('plugin-option');\n</code></pre>\n" }, { "answer_id": 278709, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>That option is special in that WordPress has code to intercept your call for security reasons:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/update_option_new_admin_email\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/update_option_new_admin_email</a></p>\n\n<blockquote>\n <p>This function intercepts changes to the administrator's email address. It keeps the address from being updated and instead sends the user a confirmation email, with a link to confirm the change.</p>\n</blockquote>\n\n<p>What you're trying to do could be easily abused, and any change of the administrators email should trigger notices as a basic security measure.</p>\n\n<p>Luckily the documentation for that function also includes an example on how to bypass it</p>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278706", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126863/" ]
I wanted to set value of **WP option** (more specifically - 'admin\_email') by using plugin, **its option** (plugin option) and update\_option(). I tried using lines like below, but when plugin code contains them - it gets disabled. Any ideas why? ``` $helper = (get_option('plugin-option'); update_option('admin_email', $helper ); ``` **EDIT** ``` $helper = get_option('plugin-option'); update_option('admin_email', $helper ); ``` Now it's not disabling (due to bracket), but it still doesn't change option value
That option is special in that WordPress has code to intercept your call for security reasons: <https://codex.wordpress.org/Function_Reference/update_option_new_admin_email> > > This function intercepts changes to the administrator's email address. It keeps the address from being updated and instead sends the user a confirmation email, with a link to confirm the change. > > > What you're trying to do could be easily abused, and any change of the administrators email should trigger notices as a basic security measure. Luckily the documentation for that function also includes an example on how to bypass it
278,714
<p>I add my custom fields in genearal settings page. One of them using Wordpress Editor - there i insert my HTML content. I creeated it using simple snippet: </p> <pre><code>add_action( 'admin_init', 'register_settings_wpse_57647' ); function register_settings_wpse_57647() { register_setting( 'general', 'opisproduktyseop', 'esc_html' ); add_settings_section( 'site-guide', 'Publishing Guidelines', '__return_false', 'general' ); add_settings_field( 'opisproduktyseop', 'Enter custom message', 'print_text_editor_wpse_57647', 'general', 'site-guide' ); } function print_text_editor_wpse_57647() { $the_guides = html_entity_decode( get_option( 'opisproduktyseop' ) ); echo wp_editor( $the_guides, 'sitepublishingguidelines', array( 'textarea_name' =&gt; 'opisproduktyseop' ) ); } </code></pre> <p><a href="https://i.stack.imgur.com/L1xfq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L1xfq.png" alt="enter image description here"></a></p> <p>The problem starts when i try display content from this field in my theme. HTML don't works: </p> <p><a href="https://i.stack.imgur.com/nsjzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nsjzu.png" alt="enter image description here"></a></p> <p>I display it using: </p> <pre><code>echo get_option( 'produktyseoopis' ); </code></pre>
[ { "answer_id": 278715, "author": "Patryk Patryk", "author_id": 120726, "author_profile": "https://wordpress.stackexchange.com/users/120726", "pm_score": -1, "selected": false, "text": "<p>Ok. i was solved it right now! When i display it i put it wit html_entity_decode()</p>\n\n<pre><code>echo html_entity_decode( get_option( 'produktyseoopis' ) );\n</code></pre>\n" }, { "answer_id": 278716, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>It's because you're using <code>esc_html</code> to sanitize the setting, which converts all the <code>&lt;</code>,<code>&gt;</code> etc. into HTML entities, like <code>&amp;gt;</code>, which <em>render</em> as <code>&lt;</code> but aren't treated as those characters in terms of HTML, which is why tags aren't rendering correctly. <code>esc_html</code> is supposed to be use for outputting HTML so that the markup is visible to the reader.</p>\n\n<p>If you want to sanitize HTML, use <code>wp_kses_post</code> as the sanitization callback.</p>\n\n<p>EDIT: Suggest <code>wp_kses_post</code>, rather than <code>wp_kses</code>, as per Tom's comment.</p>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120726/" ]
I add my custom fields in genearal settings page. One of them using Wordpress Editor - there i insert my HTML content. I creeated it using simple snippet: ``` add_action( 'admin_init', 'register_settings_wpse_57647' ); function register_settings_wpse_57647() { register_setting( 'general', 'opisproduktyseop', 'esc_html' ); add_settings_section( 'site-guide', 'Publishing Guidelines', '__return_false', 'general' ); add_settings_field( 'opisproduktyseop', 'Enter custom message', 'print_text_editor_wpse_57647', 'general', 'site-guide' ); } function print_text_editor_wpse_57647() { $the_guides = html_entity_decode( get_option( 'opisproduktyseop' ) ); echo wp_editor( $the_guides, 'sitepublishingguidelines', array( 'textarea_name' => 'opisproduktyseop' ) ); } ``` [![enter image description here](https://i.stack.imgur.com/L1xfq.png)](https://i.stack.imgur.com/L1xfq.png) The problem starts when i try display content from this field in my theme. HTML don't works: [![enter image description here](https://i.stack.imgur.com/nsjzu.png)](https://i.stack.imgur.com/nsjzu.png) I display it using: ``` echo get_option( 'produktyseoopis' ); ```
It's because you're using `esc_html` to sanitize the setting, which converts all the `<`,`>` etc. into HTML entities, like `&gt;`, which *render* as `<` but aren't treated as those characters in terms of HTML, which is why tags aren't rendering correctly. `esc_html` is supposed to be use for outputting HTML so that the markup is visible to the reader. If you want to sanitize HTML, use `wp_kses_post` as the sanitization callback. EDIT: Suggest `wp_kses_post`, rather than `wp_kses`, as per Tom's comment.
278,754
<p>I wrote some custom code which I've stuck into the media upload panel using a filter. It does a couple of things. First, it changes the text for the "submit" button for users who add things through the uploader. Second, it makes it so that the contents of the File URL field automatically enters the image upload input for a form I created when an image for it is uploaded through the media uploader. (that's the JQuery). Finally, there's CSS to hide elements of the media uploader that users don't need to see.</p> <p>When this function is in the functions.php file, it causes the media library to stall in loading up the images. It just hangs on the spinning grey ball. But it also works.</p> <p>How can I integrate this code into the site in a way that doesn't keep the media uploader from working?</p> <pre><code>add_filter('attachment_fields_to_edit', 'my_plugin_action_button', 20, 2); function my_plugin_action_button($form_fields, $post) { $send = "&lt;input type='submit' class='button' name='send[$post-&gt;ID]' value='" . esc_attr__( 'Use Photo' ) . "' /&gt;"; $form_fields['buttons'] = array('tr' =&gt; "\t\t&lt;tr class='submit'&gt;&lt;td&gt;&lt;/td&gt;&lt;td class='savesend'&gt;$send&lt;/td&gt;&lt;/tr&gt;\n"); ?&gt; &lt;script&gt; jQuery('.savesend input[type=submit]').click(function(){ var url = jQuery(this).parents('.describe').find('.urlfile').data('link-url'); var field = jQuery(this).parents('.describe').find('.urlfield'); field.val(url); }); &lt;/script&gt; &lt;style&gt; #media-head-125, #imgedit-response-125, .savebutton.ml-submit, .image-size, .align, .post_content, .post_excerpt, .image_alt, .post_title.form-required, .media-types.media-types-required-info, .url { display: none !important; } &lt;/style&gt; &lt;?php return $form_fields; } </code></pre>
[ { "answer_id": 278725, "author": "Abhilash Narayan", "author_id": 123210, "author_profile": "https://wordpress.stackexchange.com/users/123210", "pm_score": -1, "selected": false, "text": "<p>I fixed this by changing the permission of uploads folder to 745 and its working.</p>\n" }, { "answer_id": 278746, "author": "Osama Elzero", "author_id": 126781, "author_profile": "https://wordpress.stackexchange.com/users/126781", "pm_score": 0, "selected": false, "text": "<p>For the permission please read this </p>\n\n<p><a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_File_Permissions</a></p>\n\n<blockquote>\n <p>All directories should be 755 or 750.</p>\n</blockquote>\n" } ]
2017/08/31
[ "https://wordpress.stackexchange.com/questions/278754", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114210/" ]
I wrote some custom code which I've stuck into the media upload panel using a filter. It does a couple of things. First, it changes the text for the "submit" button for users who add things through the uploader. Second, it makes it so that the contents of the File URL field automatically enters the image upload input for a form I created when an image for it is uploaded through the media uploader. (that's the JQuery). Finally, there's CSS to hide elements of the media uploader that users don't need to see. When this function is in the functions.php file, it causes the media library to stall in loading up the images. It just hangs on the spinning grey ball. But it also works. How can I integrate this code into the site in a way that doesn't keep the media uploader from working? ``` add_filter('attachment_fields_to_edit', 'my_plugin_action_button', 20, 2); function my_plugin_action_button($form_fields, $post) { $send = "<input type='submit' class='button' name='send[$post->ID]' value='" . esc_attr__( 'Use Photo' ) . "' />"; $form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send</td></tr>\n"); ?> <script> jQuery('.savesend input[type=submit]').click(function(){ var url = jQuery(this).parents('.describe').find('.urlfile').data('link-url'); var field = jQuery(this).parents('.describe').find('.urlfield'); field.val(url); }); </script> <style> #media-head-125, #imgedit-response-125, .savebutton.ml-submit, .image-size, .align, .post_content, .post_excerpt, .image_alt, .post_title.form-required, .media-types.media-types-required-info, .url { display: none !important; } </style> <?php return $form_fields; } ```
For the permission please read this <https://codex.wordpress.org/Changing_File_Permissions> > > All directories should be 755 or 750. > > >
278,772
<p>I do not have coding experience only what I've learned to be able to modify my WP themes. I am stuck on the following issue. I'd like to add text and a call to action button to the featured image on my static homepage. </p> <p>I'm fine using the page title as the text but I need to be able to add the call to action button button below the text.</p> <p>Is this achievable by simply adding code to my custom CSS and/or one of the php files? If yes, please let me know what code I could use. </p> <p>Thank you in advance for any assistance or feedback.</p>
[ { "answer_id": 278784, "author": "Dexter0015", "author_id": 62134, "author_profile": "https://wordpress.stackexchange.com/users/62134", "pm_score": 1, "selected": false, "text": "<p>If your theme allow you to edit the text displayed on your home page, when you just need to add a a link.</p>\n\n<p>A click to call link is a simple HTML link, except that the value of the <code>href</code> attribute needs to refer to the \"tel\" protocol:</p>\n\n<pre><code>&lt;a href=\"tel:XXXXXXXXXXXXX\"&gt;Call Us&lt;/a&gt;\n</code></pre>\n\n<p>Where \"XXXXXXXXXXXXX\" is your phone number.</p>\n\n<p>If you only use the graphic interface, simply write \"Call Us\", highlight it and click on the button to add a link, and put \"tel:XXXXXXXXXX\" as the url.</p>\n" }, { "answer_id": 321953, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 0, "selected": false, "text": "<p>I might be too late to answer. But there are two different methods for solving your issue. </p>\n\n<p><strong>1. Manual Method</strong> - You can manually add the call to action button to\n your WordPress website by using these codes:</p>\n\n<pre><code> &lt;!--This link will work on Android and iPhone. It will be visible to desktop users but will result in an error when clicked\n--&gt;\n\n &lt;a href=\"tel:+15555551212\"&gt;+1 (555) 555-1212&lt;/a&gt; \n\n &lt;a href=\"tel:15555551212\"&gt;Call Me&lt;/a&gt;\n</code></pre>\n\n<p><strong>2. Plugin Method</strong> - \n You can use a plugin, like <a href=\"https://wordpress.org/plugins/call-now-button/\" rel=\"nofollow noreferrer\">Call Now Button</a>, to add the call to action button. It offers you several useful customization features. You can find the detailed steps for using it <a href=\"https://hostadvice.com/how-to/how-to-add-a-click-to-call-button-to-your-wordpress-website/\" rel=\"nofollow noreferrer\">right here</a>.</p>\n" }, { "answer_id": 321960, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>To include a click to call button on the image you can use the following code </p>\n\n<pre><code>&lt;a href=\"tel:+1234567890\"&gt;&lt;img src=\"image.jpg\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>or for a text button use </p>\n\n<pre><code>&lt;a href=\"tel:+1234567890\"&gt;+123456789&lt;/a&gt;\n</code></pre>\n" } ]
2017/09/01
[ "https://wordpress.stackexchange.com/questions/278772", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126986/" ]
I do not have coding experience only what I've learned to be able to modify my WP themes. I am stuck on the following issue. I'd like to add text and a call to action button to the featured image on my static homepage. I'm fine using the page title as the text but I need to be able to add the call to action button button below the text. Is this achievable by simply adding code to my custom CSS and/or one of the php files? If yes, please let me know what code I could use. Thank you in advance for any assistance or feedback.
If your theme allow you to edit the text displayed on your home page, when you just need to add a a link. A click to call link is a simple HTML link, except that the value of the `href` attribute needs to refer to the "tel" protocol: ``` <a href="tel:XXXXXXXXXXXXX">Call Us</a> ``` Where "XXXXXXXXXXXXX" is your phone number. If you only use the graphic interface, simply write "Call Us", highlight it and click on the button to add a link, and put "tel:XXXXXXXXXX" as the url.
278,780
<p>I have a custom post type functionality defined on my website for a certain action. In order to achieve a specific type of url structure. I removed the constant slug from it and replaced it with category and brand name. </p> <p>The previous url was</p> <p>www.website.com/product/name</p> <p>The new url is</p> <p>www.website.com/category/brand/name</p> <p>You see, I have totally removed the slug. Here is the code for that. Now the issue is that these urls are not working and I am geting a 404 page in return. I have tried flushing the permailinks as well but it is not helping. </p> <p>According to my understanding because of removing the slug, the query is searching in 'Post' not the 'Custom Post Type' but I don't know how to correct it. You response will be highly appreciated.</p> <pre><code>// Register our Custom Post type as aps-products public static function register_cpt_aps_products() { $permalinks = get_aps_settings('permalinks'); $slug = (isset($permalinks['product-slug'])) ? $permalinks['product-slug'] : ''; // labels text for our post type aps-products $labels = array( // post type general name 'name' =&gt; __( 'APS Products', 'aps-text' ), // post type singular name 'singular_name' =&gt; __( 'APS Product', 'aps-text' ), 'name_admin_bar' =&gt; __( 'APS Product', 'aps-text' ), 'menu_name' =&gt; __( 'APS Products', 'aps-text' ), 'add_new' =&gt; __( 'Add New APS Product', 'aps-text' ), 'add_new_item' =&gt; __( 'Add New APS Product', 'aps-text' ), 'edit_item' =&gt; __( 'Edit APS Product', 'aps-text' ), 'new_item' =&gt; __( 'New APS Product', 'aps-text' ), 'view_item' =&gt; __( 'View APS Product', 'aps-text' ), 'archives' =&gt; __( 'APS Products Archives', 'aps-text' ), 'search_items' =&gt; __( 'Search APS Products', 'aps-text' ), 'insert_into_item' =&gt; __( 'Insert into APS Product', 'aps-text' ), 'featured_image' =&gt; __( 'APS Product Image', 'aps-text' ), 'set_featured_image' =&gt; __( 'Set APS Product Image', 'aps-text' ), 'remove_featured_image' =&gt; __( 'Remove APS Product Image', 'aps-text' ), 'use_featured_image' =&gt; __( 'Use as APS Product image', 'aps-text' ), 'not_found' =&gt; __( 'No APS Products found', 'aps-text' ), 'not_found_in_trash' =&gt; __( 'No APS Products found in Trash', 'aps-text' ) ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'publicly_queryable' =&gt; true, 'show_in_nav_menus' =&gt; false, 'menu_icon' =&gt; 'dashicons-products', 'capability_type' =&gt; 'aps-products', 'capabilities' =&gt; array( 'read_post' =&gt; 'read_aps_product', 'edit_post' =&gt; 'edit_aps_product', 'edit_posts' =&gt; 'edit_aps_products', 'delete_posts' =&gt; 'delete_aps_products', 'create_posts' =&gt; 'create_aps_products', 'publish_posts' =&gt; 'publish_aps_products', 'edit_published_posts' =&gt; 'edit_published_aps_products', 'delete_published_posts' =&gt; 'delete_published_aps_products', 'edit_others_posts' =&gt; 'edit_others_aps_products', 'delete_others_posts' =&gt; 'delete_others_aps_products', 'read_private_posts' =&gt; 'read_private_aps_products', 'edit_private_posts' =&gt; 'edit_private_aps_products', 'delete_private_posts' =&gt; 'delete_private_aps_products' ), 'map_meta_cap' =&gt; true, 'hierarchical' =&gt; true, 'taxonomies' =&gt; array('post_tag','aps-cats', 'aps-brands', 'aps-attributes', 'aps-filters', 'aps-rating-bars'), 'has_archive' =&gt; true, 'show_in_menu' =&gt; 'aps-products', 'supports' =&gt; array( 'publicize','title', 'editor', 'thumbnail', 'comments', 'author', 'excerpt' ), 'register_meta_box_cb' =&gt; array(__CLASS__, 'add_aps_products_metabox'), 'rewrite' =&gt; array('slug' =&gt; '/%aps-cats%/%aps-brands%/', 'with_front' =&gt; false) ); </code></pre>
[ { "answer_id": 278784, "author": "Dexter0015", "author_id": 62134, "author_profile": "https://wordpress.stackexchange.com/users/62134", "pm_score": 1, "selected": false, "text": "<p>If your theme allow you to edit the text displayed on your home page, when you just need to add a a link.</p>\n\n<p>A click to call link is a simple HTML link, except that the value of the <code>href</code> attribute needs to refer to the \"tel\" protocol:</p>\n\n<pre><code>&lt;a href=\"tel:XXXXXXXXXXXXX\"&gt;Call Us&lt;/a&gt;\n</code></pre>\n\n<p>Where \"XXXXXXXXXXXXX\" is your phone number.</p>\n\n<p>If you only use the graphic interface, simply write \"Call Us\", highlight it and click on the button to add a link, and put \"tel:XXXXXXXXXX\" as the url.</p>\n" }, { "answer_id": 321953, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 0, "selected": false, "text": "<p>I might be too late to answer. But there are two different methods for solving your issue. </p>\n\n<p><strong>1. Manual Method</strong> - You can manually add the call to action button to\n your WordPress website by using these codes:</p>\n\n<pre><code> &lt;!--This link will work on Android and iPhone. It will be visible to desktop users but will result in an error when clicked\n--&gt;\n\n &lt;a href=\"tel:+15555551212\"&gt;+1 (555) 555-1212&lt;/a&gt; \n\n &lt;a href=\"tel:15555551212\"&gt;Call Me&lt;/a&gt;\n</code></pre>\n\n<p><strong>2. Plugin Method</strong> - \n You can use a plugin, like <a href=\"https://wordpress.org/plugins/call-now-button/\" rel=\"nofollow noreferrer\">Call Now Button</a>, to add the call to action button. It offers you several useful customization features. You can find the detailed steps for using it <a href=\"https://hostadvice.com/how-to/how-to-add-a-click-to-call-button-to-your-wordpress-website/\" rel=\"nofollow noreferrer\">right here</a>.</p>\n" }, { "answer_id": 321960, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>To include a click to call button on the image you can use the following code </p>\n\n<pre><code>&lt;a href=\"tel:+1234567890\"&gt;&lt;img src=\"image.jpg\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>or for a text button use </p>\n\n<pre><code>&lt;a href=\"tel:+1234567890\"&gt;+123456789&lt;/a&gt;\n</code></pre>\n" } ]
2017/09/01
[ "https://wordpress.stackexchange.com/questions/278780", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24020/" ]
I have a custom post type functionality defined on my website for a certain action. In order to achieve a specific type of url structure. I removed the constant slug from it and replaced it with category and brand name. The previous url was www.website.com/product/name The new url is www.website.com/category/brand/name You see, I have totally removed the slug. Here is the code for that. Now the issue is that these urls are not working and I am geting a 404 page in return. I have tried flushing the permailinks as well but it is not helping. According to my understanding because of removing the slug, the query is searching in 'Post' not the 'Custom Post Type' but I don't know how to correct it. You response will be highly appreciated. ``` // Register our Custom Post type as aps-products public static function register_cpt_aps_products() { $permalinks = get_aps_settings('permalinks'); $slug = (isset($permalinks['product-slug'])) ? $permalinks['product-slug'] : ''; // labels text for our post type aps-products $labels = array( // post type general name 'name' => __( 'APS Products', 'aps-text' ), // post type singular name 'singular_name' => __( 'APS Product', 'aps-text' ), 'name_admin_bar' => __( 'APS Product', 'aps-text' ), 'menu_name' => __( 'APS Products', 'aps-text' ), 'add_new' => __( 'Add New APS Product', 'aps-text' ), 'add_new_item' => __( 'Add New APS Product', 'aps-text' ), 'edit_item' => __( 'Edit APS Product', 'aps-text' ), 'new_item' => __( 'New APS Product', 'aps-text' ), 'view_item' => __( 'View APS Product', 'aps-text' ), 'archives' => __( 'APS Products Archives', 'aps-text' ), 'search_items' => __( 'Search APS Products', 'aps-text' ), 'insert_into_item' => __( 'Insert into APS Product', 'aps-text' ), 'featured_image' => __( 'APS Product Image', 'aps-text' ), 'set_featured_image' => __( 'Set APS Product Image', 'aps-text' ), 'remove_featured_image' => __( 'Remove APS Product Image', 'aps-text' ), 'use_featured_image' => __( 'Use as APS Product image', 'aps-text' ), 'not_found' => __( 'No APS Products found', 'aps-text' ), 'not_found_in_trash' => __( 'No APS Products found in Trash', 'aps-text' ) ); $args = array( 'labels' => $labels, 'public' => true, 'show_ui' => true, 'query_var' => true, 'publicly_queryable' => true, 'show_in_nav_menus' => false, 'menu_icon' => 'dashicons-products', 'capability_type' => 'aps-products', 'capabilities' => array( 'read_post' => 'read_aps_product', 'edit_post' => 'edit_aps_product', 'edit_posts' => 'edit_aps_products', 'delete_posts' => 'delete_aps_products', 'create_posts' => 'create_aps_products', 'publish_posts' => 'publish_aps_products', 'edit_published_posts' => 'edit_published_aps_products', 'delete_published_posts' => 'delete_published_aps_products', 'edit_others_posts' => 'edit_others_aps_products', 'delete_others_posts' => 'delete_others_aps_products', 'read_private_posts' => 'read_private_aps_products', 'edit_private_posts' => 'edit_private_aps_products', 'delete_private_posts' => 'delete_private_aps_products' ), 'map_meta_cap' => true, 'hierarchical' => true, 'taxonomies' => array('post_tag','aps-cats', 'aps-brands', 'aps-attributes', 'aps-filters', 'aps-rating-bars'), 'has_archive' => true, 'show_in_menu' => 'aps-products', 'supports' => array( 'publicize','title', 'editor', 'thumbnail', 'comments', 'author', 'excerpt' ), 'register_meta_box_cb' => array(__CLASS__, 'add_aps_products_metabox'), 'rewrite' => array('slug' => '/%aps-cats%/%aps-brands%/', 'with_front' => false) ); ```
If your theme allow you to edit the text displayed on your home page, when you just need to add a a link. A click to call link is a simple HTML link, except that the value of the `href` attribute needs to refer to the "tel" protocol: ``` <a href="tel:XXXXXXXXXXXXX">Call Us</a> ``` Where "XXXXXXXXXXXXX" is your phone number. If you only use the graphic interface, simply write "Call Us", highlight it and click on the button to add a link, and put "tel:XXXXXXXXXX" as the url.
278,813
<p>i have in all of my posts an additional custom field (acf user field) in case the post has a co-author. </p> <p>All users have their own author-page where all their posts are displayed. No problem so far.</p> <p>But what i now want is a query where i get all posts where the author is the actual author and all posts where he/she is just the co-author in the custom field.</p> <p>My code is pretty simple so far, but did not actually work. I guess the 'relation' parameter is only for comparing meta query-subarrays.</p> <pre><code>$args = array( 'post_type' =&gt; array( 'post' ), 'posts_per_page' =&gt; 20, 'relation' =&gt; 'OR', array( 'author' =&gt; $author_ID, ), array( 'meta_key' =&gt; 'authorfeld', 'meta_value' =&gt; $showme[ID], // This is the authors id from the custom field ) ); </code></pre> <p>Thank you</p>
[ { "answer_id": 278842, "author": "James", "author_id": 34484, "author_profile": "https://wordpress.stackexchange.com/users/34484", "pm_score": 0, "selected": false, "text": "<p>Real quick, are you sure you spelled the name of the meta_key correctly? It says \"authorfeld\" in your example, but maybe it's supposed to be \"authorfield\"? Also <code>$showme[ID]</code> would need to be <code>$showme['ID']</code> unless <code>ID</code> is a defined variable.</p>\n\n<p>In any case, your $args array is not quite correct. Try these examples:</p>\n\n<pre><code>// Get the posts from this author, but not this coauthor.\n$author_not_coauthor = array(\n 'post_type' =&gt; array( 'post' ),\n 'posts_per_page' =&gt; 20,\n 'author' =&gt; $author_ID,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'authorfeld',\n 'value' =&gt; $showme['ID'],\n 'compare' =&gt; 'NOT LIKE',\n ),\n ),\n);\n\n// Get the posts from this coauthor, but not this author.\n$coauthor_not_author = array(\n 'post_type' =&gt; array( 'post' ),\n 'posts_per_page' =&gt; 20,\n 'author__not_in' =&gt; array( $author_ID ),\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'authorfeld',\n 'value' =&gt; $showme['ID'],\n ),\n ),\n);\n</code></pre>\n" }, { "answer_id": 279211, "author": "Steve", "author_id": 92874, "author_profile": "https://wordpress.stackexchange.com/users/92874", "pm_score": 4, "selected": true, "text": "<p>I found some hints here: <a href=\"https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s\">Can i merge 2 new WP_Query($variable) &#39;s?</a></p>\n\n<p>So i created two separate queries and merged them into a new array:</p>\n\n<pre><code>$wp_query = new WP_Query();\n$wp_query-&gt;posts = array_merge( $query1-&gt;posts, $query2-&gt;posts ); \n\nforeach($wp_query-&gt;posts as $post) :\nsetup_postdata( $post );\n</code></pre>\n\n<p>And then the usual stuff.</p>\n" } ]
2017/09/01
[ "https://wordpress.stackexchange.com/questions/278813", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92874/" ]
i have in all of my posts an additional custom field (acf user field) in case the post has a co-author. All users have their own author-page where all their posts are displayed. No problem so far. But what i now want is a query where i get all posts where the author is the actual author and all posts where he/she is just the co-author in the custom field. My code is pretty simple so far, but did not actually work. I guess the 'relation' parameter is only for comparing meta query-subarrays. ``` $args = array( 'post_type' => array( 'post' ), 'posts_per_page' => 20, 'relation' => 'OR', array( 'author' => $author_ID, ), array( 'meta_key' => 'authorfeld', 'meta_value' => $showme[ID], // This is the authors id from the custom field ) ); ``` Thank you
I found some hints here: [Can i merge 2 new WP\_Query($variable) 's?](https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s) So i created two separate queries and merged them into a new array: ``` $wp_query = new WP_Query(); $wp_query->posts = array_merge( $query1->posts, $query2->posts ); foreach($wp_query->posts as $post) : setup_postdata( $post ); ``` And then the usual stuff.
278,882
<p>How can I get the email adress from the users by using the REST API? I'm authenticating with nonce, and it seems to be working since I can do POST requests and change stuff. Do I have to add something to make it return all the user info?</p> <p>This is my JS:</p> <pre><code>(function($) { var nonce = WPsettings.nonce; var rest_url = WPsettings.rest_url; $.ajax( { url: rest_url + 'users/', dataType: "json", beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', nonce ); } } ) .done( function ( response ) { console.log( response ); } ); })(jQuery); </code></pre>
[ { "answer_id": 278883, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 4, "selected": true, "text": "<p>To add the user's email address in the REST API response, register an additional field to the <code>user</code> object and add the email address:</p>\n<pre><code>register_rest_field(\n 'user',\n 'user_email',\n [\n 'get_callback' =&gt; static function (array $user): string {\n return get_userdata($user['id'])-&gt;user_email;\n },\n ]\n);\n</code></pre>\n<p>Please note, however, that this is <em>strongly</em> discouraged because anyone can then see the email addresses if the code is running on a publicly accessible website.</p>\n" }, { "answer_id": 376937, "author": "Mohammed", "author_id": 102222, "author_profile": "https://wordpress.stackexchange.com/users/102222", "pm_score": 0, "selected": false, "text": "<p>I think u can return current_user email,</p>\n<pre><code>register_rest_field( 'user', 'user_email',\n array(\n 'get_callback' =&gt; function ( $user ) {\n return wp_get_current_user()-&gt;user_email;\n },\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n);\n</code></pre>\n" }, { "answer_id": 379276, "author": "big_water", "author_id": 121697, "author_profile": "https://wordpress.stackexchange.com/users/121697", "pm_score": 2, "selected": false, "text": "<p>If you're having an issue getting the email using Mostafa's answer, I had better luck swapping out the email retrieval as such:</p>\n<pre><code>register_rest_field( 'user', 'user_email',\n array(\n 'get_callback' =&gt; function ( $user ) {\n return get_userdata($user['id'])-&gt;user_email;\n },\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n</code></pre>\n" } ]
2017/09/02
[ "https://wordpress.stackexchange.com/questions/278882", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5079/" ]
How can I get the email adress from the users by using the REST API? I'm authenticating with nonce, and it seems to be working since I can do POST requests and change stuff. Do I have to add something to make it return all the user info? This is my JS: ``` (function($) { var nonce = WPsettings.nonce; var rest_url = WPsettings.rest_url; $.ajax( { url: rest_url + 'users/', dataType: "json", beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', nonce ); } } ) .done( function ( response ) { console.log( response ); } ); })(jQuery); ```
To add the user's email address in the REST API response, register an additional field to the `user` object and add the email address: ``` register_rest_field( 'user', 'user_email', [ 'get_callback' => static function (array $user): string { return get_userdata($user['id'])->user_email; }, ] ); ``` Please note, however, that this is *strongly* discouraged because anyone can then see the email addresses if the code is running on a publicly accessible website.
278,954
<p>I'm currently trying to download a blob archive file saved in the database</p> <pre><code>$fid = $_GET['fid']; $sel = $wpdb-&gt;get_results( "SELECT * FROM uploads WHERE id = $fid" ); foreach( $sel as $head ) { $name = $head-&gt;name; $type = $head-&gt;type; $size = $head-&gt;size; $content = $head-&gt;content; header("Content-length: $size"); header("Content-type: $type"); header("Content-Transfer-Encoding: Binary"); header("Content-Disposition: attachment; filename=$name"); echo $content; exit; } </code></pre> <p>every time I redirect to <code>/download?id=</code> with int value assigned to <code>id</code> it loads the file. However, instead of the browser prompting for file download location, the page reads the binary contents of the blob and displays it all as a string.</p> <p>any other way of downloading a blob on wordpress?</p>
[ { "answer_id": 278993, "author": "Sebastian Kurzynowski", "author_id": 108925, "author_profile": "https://wordpress.stackexchange.com/users/108925", "pm_score": 2, "selected": false, "text": "<p>There are some security issues. \nPlease sanitize your input because someone can download from Your database something different than archive, or simply drop Your database.</p>\n\n<p><code>$fid = sanitize_text_field( $_GET['fid'] );</code></p>\n" }, { "answer_id": 278994, "author": "Paul G.", "author_id": 41288, "author_profile": "https://wordpress.stackexchange.com/users/41288", "pm_score": 0, "selected": false, "text": "<p>Use the following content-type header in your code:</p>\n\n<pre><code>header( \"Content-type: application/octet-stream\" );\n</code></pre>\n\n<p>If that doesn't work - we successfully do this and though it is unlikely, it may be related to the order of things. Try it in the following order:</p>\n\n<pre><code>Content-type\nContent-disposition\nContent-Transfer-Encoding\nContent-Length\n</code></pre>\n\n<p>And as was mentioned in the other answer - always sanitize input before using it directly in database queries.</p>\n\n<p>Edited: Also add to ensure there's no caching (taken <a href=\"https://stackoverflow.com/questions/8485886/force-file-download-with-php-using-header\">from here</a>)-</p>\n\n<pre><code>header('Connection: Keep-Alive');\nheader('Expires: 0');\nheader('Cache-Control: must-revalidate, post-check=0, pre-check=0');\nheader('Pragma: public');\n</code></pre>\n\n<p>Edited: Wrap up the code into an function to run at 'init' so it's not output in the theme content.</p>\n\n<pre><code>add_action(\n 'init',\n function () {\n global $wpdb;\n\n $fid = sanitize_text_field( $_GET[ 'fid' ] );\n\n $sel = $wpdb-&gt;get_results( \"SELECT * FROM uploads WHERE id = $fid\" );\n foreach ( $sel as $head ) {\n $name = empty( $head-&gt;name ) ? 'myfile.name' : $head-&gt;name;\n $size = empty( $head-&gt;size ) ? strlen( $head-&gt;content ) : $head-&gt;size;\n\n header( 'Content-Type: application/octet-stream' );\n header( \"Content-Disposition: attachment; filename=$name\" );\n header( 'Content-Transfer-Encoding: Binary' );\n header( \"Content-Length: $size\" );\n header( 'Connection: Keep-Alive' );\n header( 'Expires: 0' );\n header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );\n header( 'Pragma: public' );\n\n echo $head-&gt;content;\n\n exit();\n }\n }\n);\n</code></pre>\n" } ]
2017/09/03
[ "https://wordpress.stackexchange.com/questions/278954", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127113/" ]
I'm currently trying to download a blob archive file saved in the database ``` $fid = $_GET['fid']; $sel = $wpdb->get_results( "SELECT * FROM uploads WHERE id = $fid" ); foreach( $sel as $head ) { $name = $head->name; $type = $head->type; $size = $head->size; $content = $head->content; header("Content-length: $size"); header("Content-type: $type"); header("Content-Transfer-Encoding: Binary"); header("Content-Disposition: attachment; filename=$name"); echo $content; exit; } ``` every time I redirect to `/download?id=` with int value assigned to `id` it loads the file. However, instead of the browser prompting for file download location, the page reads the binary contents of the blob and displays it all as a string. any other way of downloading a blob on wordpress?
There are some security issues. Please sanitize your input because someone can download from Your database something different than archive, or simply drop Your database. `$fid = sanitize_text_field( $_GET['fid'] );`
278,986
<p>I am trying to get the updated value of a piece of meta when a post is saved (custom post type) but when I try to grab the updated data on the save_post hook, I get the previous data instead. I tried a separate function with a higher priority, but no luck that way either (below)</p> <p>How do I get the updated meta value right after I save the post?</p> <p>Code:</p> <pre><code>add_action('save_post_space', 'tps_save_space_slots', 20, 3); function tps_save_space_slots($post_id, $post, $updated) { //Don't fire on auto-drafts if (isset($post-&gt;post_status) &amp;&amp; 'auto-draft' == $post-&gt;post_status) { return; } //The new slots being saved $allSlots = tps_generate_space_slots($post_id); //Update the meta $updateSlots = update_post_meta($post_id, 'allSlots', $allSlots); } add_action( 'save_post_space', 'tps_initiate_resend', 30, 3 ); function tps_initiate_resend($post_id, $post, $updated) { tps_resend_code_after_change($post_id);//&lt;----this sends the new meta value in an email, but it's the OLD value } </code></pre>
[ { "answer_id": 278988, "author": "Eckstein", "author_id": 23492, "author_profile": "https://wordpress.stackexchange.com/users/23492", "pm_score": 3, "selected": true, "text": "<p>Apparently in order to get the meta value right after saving the post, you have to either get the $_REQUEST['my_meta_value'] directly, or, if you need to update the database right away, you have to use update_post_meta() in your save_post action.</p>\n" }, { "answer_id": 410517, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 0, "selected": false, "text": "<p>Try <code>edit_post_${post_type}</code> hook</p>\n" } ]
2017/09/04
[ "https://wordpress.stackexchange.com/questions/278986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23492/" ]
I am trying to get the updated value of a piece of meta when a post is saved (custom post type) but when I try to grab the updated data on the save\_post hook, I get the previous data instead. I tried a separate function with a higher priority, but no luck that way either (below) How do I get the updated meta value right after I save the post? Code: ``` add_action('save_post_space', 'tps_save_space_slots', 20, 3); function tps_save_space_slots($post_id, $post, $updated) { //Don't fire on auto-drafts if (isset($post->post_status) && 'auto-draft' == $post->post_status) { return; } //The new slots being saved $allSlots = tps_generate_space_slots($post_id); //Update the meta $updateSlots = update_post_meta($post_id, 'allSlots', $allSlots); } add_action( 'save_post_space', 'tps_initiate_resend', 30, 3 ); function tps_initiate_resend($post_id, $post, $updated) { tps_resend_code_after_change($post_id);//<----this sends the new meta value in an email, but it's the OLD value } ```
Apparently in order to get the meta value right after saving the post, you have to either get the $\_REQUEST['my\_meta\_value'] directly, or, if you need to update the database right away, you have to use update\_post\_meta() in your save\_post action.
279,035
<p>I am new to woo-commerce, can anyone please let me know where the cart items are stored in Database. which tables have cart details?</p>
[ { "answer_id": 279036, "author": "DHL17", "author_id": 125227, "author_profile": "https://wordpress.stackexchange.com/users/125227", "pm_score": 2, "selected": false, "text": "<p>Various information about cart are stored by woocmmerce by two ways:</p>\n\n<ol>\n<li>In $woocommerce object( About session , cart info, subtotal etc)</li>\n<li>In database table named persistent_cart which is dynamic ... it will get destroyed as soon as checkout is done.</li>\n</ol>\n\n<p>So , now how to access all this info ...\nFor the 1st kind just declare global $woocommerce object and use below code to see all details</p>\n\n<pre><code>global $woocommerce;\necho \"&lt;pre&gt;\";\nprint_r($woocommerce);\nexit;\n</code></pre>\n\n<p>For the 2nd kind you have to fetch data from table.. therefore first declare $wpdb wordpress object and write sql query to get result\none thing to note here is... data is stored in serialize manner in <code>woocommerce_persistent_cart</code> table so you have to unserialize it before using it\nonly then you can use it. Below is code to get cart information from table</p>\n\n<pre><code>global $wpdb;\n$array = $wpdb-&gt;get_results(\"select meta_value from \".$wpdb-&gt;prefix.\"usermeta where meta_key='_woocommerce_persistent_cart'\");\n//print_r($array);\n$data =$array[0]-&gt;meta_value;\n$de=unserialize($data); \n</code></pre>\n" }, { "answer_id": 290444, "author": "Harsh Barach", "author_id": 112248, "author_profile": "https://wordpress.stackexchange.com/users/112248", "pm_score": 2, "selected": false, "text": "<p>I think all cart items of WooCommerce are stored <code>session_value</code> column of <code>wp_woocommerce_sessions</code> table.</p>\n" } ]
2017/09/04
[ "https://wordpress.stackexchange.com/questions/279035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127183/" ]
I am new to woo-commerce, can anyone please let me know where the cart items are stored in Database. which tables have cart details?
Various information about cart are stored by woocmmerce by two ways: 1. In $woocommerce object( About session , cart info, subtotal etc) 2. In database table named persistent\_cart which is dynamic ... it will get destroyed as soon as checkout is done. So , now how to access all this info ... For the 1st kind just declare global $woocommerce object and use below code to see all details ``` global $woocommerce; echo "<pre>"; print_r($woocommerce); exit; ``` For the 2nd kind you have to fetch data from table.. therefore first declare $wpdb wordpress object and write sql query to get result one thing to note here is... data is stored in serialize manner in `woocommerce_persistent_cart` table so you have to unserialize it before using it only then you can use it. Below is code to get cart information from table ``` global $wpdb; $array = $wpdb->get_results("select meta_value from ".$wpdb->prefix."usermeta where meta_key='_woocommerce_persistent_cart'"); //print_r($array); $data =$array[0]->meta_value; $de=unserialize($data); ```
279,204
<p>The stock statuses from my woocommerce installation were uploaded by another plugin (square) and so all goods are in stock even if they have quantity 0. Is there a way to get the statuses to reset somehow, so that products with 0 stock, have the stock status "out of stock". </p> <p>I have looked for this and found the following <a href="https://gist.github.com/codearachnid/5943589" rel="nofollow noreferrer">function</a></p> <pre><code>function jolie_theme_child_reset_stock_status(){ global $wpdb; // set all status for products with 0 or less stocked quantity $sql = "UPDATE $wpdb-&gt;postmeta stock, (SELECT DISTINCT post_id FROM $wpdb-&gt;postmeta WHERE meta_key = '_stock' AND meta_value &lt; 1 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';"; // set all status for products with stock. $sql .= "UPDATE $wpdb-&gt;postmeta stock, (SELECT DISTINCT post_id FROM $wpdb-&gt;postmeta WHERE meta_key = '_stock' AND meta_value &gt; 0 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';"; // run queries $wpdb-&gt;query( $sql ); } </code></pre> <p>But if I run this it causes a server 500 error. What is a simple way to reset the stock statuses with or without using the above code?</p>
[ { "answer_id": 279212, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>You can add the following sql command in your database using PHP my admin or anyother DB editor</p>\n\n<pre><code>Update wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status'\n</code></pre>\n" }, { "answer_id": 340983, "author": "Chetan", "author_id": 170333, "author_profile": "https://wordpress.stackexchange.com/users/170333", "pm_score": -1, "selected": false, "text": "<p>Use below query for update Woo-commerce product status change manually. </p>\n\n<p>Query:-\n<code>\nUpdate wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status' \n</code></p>\n\n<p>Note:-\nFirst check your table name before run this query. If your table name prefix not default then change it. </p>\n" } ]
2017/09/06
[ "https://wordpress.stackexchange.com/questions/279204", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127261/" ]
The stock statuses from my woocommerce installation were uploaded by another plugin (square) and so all goods are in stock even if they have quantity 0. Is there a way to get the statuses to reset somehow, so that products with 0 stock, have the stock status "out of stock". I have looked for this and found the following [function](https://gist.github.com/codearachnid/5943589) ``` function jolie_theme_child_reset_stock_status(){ global $wpdb; // set all status for products with 0 or less stocked quantity $sql = "UPDATE $wpdb->postmeta stock, (SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock' AND meta_value < 1 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';"; // set all status for products with stock. $sql .= "UPDATE $wpdb->postmeta stock, (SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock' AND meta_value > 0 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';"; // run queries $wpdb->query( $sql ); } ``` But if I run this it causes a server 500 error. What is a simple way to reset the stock statuses with or without using the above code?
You can add the following sql command in your database using PHP my admin or anyother DB editor ``` Update wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status' ```
279,215
<p>I've created a custom field and selected "Filter by role" to "Subscriber" and assigned the custom field to the post type. Now when I add a new post and assigned the subscriber (ie: created a Test Post and assigned the subscriber to "grade 1") after I click on the update again I changed the subscriber "grade 1" to "grade 2", after that when I viewed the page by login as grade 1 that particular post is viewed. This Happens only if I edit the post and change the subscriber again. </p> <pre><code>$args_events = array( 'post_type' =&gt; 'parents_login', 'post_status' =&gt; 'publish', 'paged' =&gt; $page_num, 'posts_per_page' =&gt; CUSTOM_ROWS_PER_PAGE, 'cat' =&gt; get_cat_id( single_cat_title("",false) ), 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'select_grade', 'value' =&gt; $current_user-&gt;ID, 'compare' =&gt; 'LIKE', ), ), ); </code></pre>
[ { "answer_id": 279212, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>You can add the following sql command in your database using PHP my admin or anyother DB editor</p>\n\n<pre><code>Update wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status'\n</code></pre>\n" }, { "answer_id": 340983, "author": "Chetan", "author_id": 170333, "author_profile": "https://wordpress.stackexchange.com/users/170333", "pm_score": -1, "selected": false, "text": "<p>Use below query for update Woo-commerce product status change manually. </p>\n\n<p>Query:-\n<code>\nUpdate wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status' \n</code></p>\n\n<p>Note:-\nFirst check your table name before run this query. If your table name prefix not default then change it. </p>\n" } ]
2017/09/06
[ "https://wordpress.stackexchange.com/questions/279215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80578/" ]
I've created a custom field and selected "Filter by role" to "Subscriber" and assigned the custom field to the post type. Now when I add a new post and assigned the subscriber (ie: created a Test Post and assigned the subscriber to "grade 1") after I click on the update again I changed the subscriber "grade 1" to "grade 2", after that when I viewed the page by login as grade 1 that particular post is viewed. This Happens only if I edit the post and change the subscriber again. ``` $args_events = array( 'post_type' => 'parents_login', 'post_status' => 'publish', 'paged' => $page_num, 'posts_per_page' => CUSTOM_ROWS_PER_PAGE, 'cat' => get_cat_id( single_cat_title("",false) ), 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'select_grade', 'value' => $current_user->ID, 'compare' => 'LIKE', ), ), ); ```
You can add the following sql command in your database using PHP my admin or anyother DB editor ``` Update wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status' ```
279,230
<p>I am trying to understand how <code>add_theme_support()</code> function works, but at the section of Html5 i tried to use it with gallery and i noticed that the markup has changed for it,and here is what i did</p> <pre><code>add_theme_support( 'html5', array('gallery') ); </code></pre> <p>but for the others like search-form or comment-form for example</p> <pre><code>add_theme_support( 'html5', array( 'comment-form','search-form','gallery', 'caption' ) ); </code></pre> <p>i didn't notice any change in the output, so Am i missing some thing? or how it works?</p>
[ { "answer_id": 279232, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>According to the documentation, you must pass an array of items where you want to enable HTML5 markup:</p>\n\n<pre><code>add_theme_support( 'html5', array(\n // Any or all of these.\n 'comment-list', \n 'comment-form',\n 'search-form',\n 'gallery',\n 'caption',\n) );\n</code></pre>\n\n<p>The documentation also recommends using <code>add_theme_support()</code> on the <code>after_setup_theme</code> hook, stating that the <code>init</code> hook may be too late for some features.</p>\n\n<h2>Reference</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_theme_support/#html5\" rel=\"nofollow noreferrer\">Developer documentation: <code>add_theme_support()</code> » HTML5</a></p>\n" }, { "answer_id": 279277, "author": "Mohamed Omar", "author_id": 102224, "author_profile": "https://wordpress.stackexchange.com/users/102224", "pm_score": 3, "selected": true, "text": "<p>I have figured out why no changes happens, and the problem was that i am calling a custom search form file <code>searchform.php</code> and the function <code>add_theme_support()</code> affects the built in features only. So if you want to use the default search form by calling <code>get_search_form()</code> without having the <code>searchform.php</code> file, then you can use</p>\n\n<pre><code>add_theme_support( 'html5', array( 'search-form' ) );\n</code></pre>\n\n<p>and this will apply an html5 markup to the form. The following are the before and after <code>add_theme_support()</code>(Contains Arabic Text):</p>\n\n<p>Before:</p>\n\n<pre><code>&lt;form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"http://localhost/TB/\"&gt;\n &lt;div&gt;\n &lt;label class=\"screen-reader-text\" for=\"s\"&gt;البحث عن:&lt;/label&gt;\n &lt;input value=\"\" name=\"s\" id=\"s\" type=\"text\"&gt;\n &lt;input id=\"searchsubmit\" value=\"بحث\" type=\"submit\"&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>&lt;form role=\"search\" method=\"get\" class=\"search-form\" action=\"http://localhost/TB/\"&gt;\n &lt;label&gt;\n &lt;span class=\"screen-reader-text\"&gt;البحث عن:&lt;/span&gt;\n &lt;input class=\"search-field\" placeholder=\"بحث …\" value=\"\" name=\"s\" type=\"search\"&gt;\n &lt;/label&gt;\n &lt;input class=\"search-submit\" value=\"بحث\" type=\"submit\"&gt;\n &lt;/form&gt;\n</code></pre>\n" } ]
2017/09/06
[ "https://wordpress.stackexchange.com/questions/279230", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102224/" ]
I am trying to understand how `add_theme_support()` function works, but at the section of Html5 i tried to use it with gallery and i noticed that the markup has changed for it,and here is what i did ``` add_theme_support( 'html5', array('gallery') ); ``` but for the others like search-form or comment-form for example ``` add_theme_support( 'html5', array( 'comment-form','search-form','gallery', 'caption' ) ); ``` i didn't notice any change in the output, so Am i missing some thing? or how it works?
I have figured out why no changes happens, and the problem was that i am calling a custom search form file `searchform.php` and the function `add_theme_support()` affects the built in features only. So if you want to use the default search form by calling `get_search_form()` without having the `searchform.php` file, then you can use ``` add_theme_support( 'html5', array( 'search-form' ) ); ``` and this will apply an html5 markup to the form. The following are the before and after `add_theme_support()`(Contains Arabic Text): Before: ``` <form role="search" method="get" id="searchform" class="searchform" action="http://localhost/TB/"> <div> <label class="screen-reader-text" for="s">البحث عن:</label> <input value="" name="s" id="s" type="text"> <input id="searchsubmit" value="بحث" type="submit"> </div> </form> ``` After: ``` <form role="search" method="get" class="search-form" action="http://localhost/TB/"> <label> <span class="screen-reader-text">البحث عن:</span> <input class="search-field" placeholder="بحث …" value="" name="s" type="search"> </label> <input class="search-submit" value="بحث" type="submit"> </form> ```
279,247
<p>I am using twenty seventeen theme. The theme allows to have different sections on homepage based on site pages. I was wondering how I can add make it so only logged out users see a certain page in one of the sections? Basically I have a new user registration page i want to have as one of my sections but I don't want logged in users to see that section, only logged out users. </p> <p>My page is <a href="http://jonathanmusiclessons.com" rel="nofollow noreferrer">jonathanmusiclessons.com</a></p>
[ { "answer_id": 279255, "author": "Rafael Cavalcante", "author_id": 68359, "author_profile": "https://wordpress.stackexchange.com/users/68359", "pm_score": 0, "selected": false, "text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">is_user_logged_in</a> wordpress function :)</p>\n\n<pre><code>if (!is_user_logged_in()) {\n // content for non-authenticated users\n}\n</code></pre>\n" }, { "answer_id": 279292, "author": "The Filipino Freelancer", "author_id": 126661, "author_profile": "https://wordpress.stackexchange.com/users/126661", "pm_score": 1, "selected": false, "text": "<p>You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.</p>\n\n<p>For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;</p>\n\n<pre><code>.logged_in .menu-class-here{display:none;}\n</code></pre>\n\n<p>That is to hide a menu item.\nNow, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n</code></pre>\n\n<p>If you want to allow access to the page but hide a certain section from logged in users, you can do something like;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; ! is_user_logged_in() ) {\n //add the code here that you want to show to non-logged-in users\n}\n</code></pre>\n\n<p><strong>UPDATE</strong>\nAdd this to functions.php. You need to create a function to redirect and add it</p>\n\n<pre><code>function notallowed() {\n global $post;\nif ( is_page('hire-the-freelancer') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n}\nadd_action( 'template_redirect', 'notallowed' );\n</code></pre>\n" } ]
2017/09/06
[ "https://wordpress.stackexchange.com/questions/279247", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127363/" ]
I am using twenty seventeen theme. The theme allows to have different sections on homepage based on site pages. I was wondering how I can add make it so only logged out users see a certain page in one of the sections? Basically I have a new user registration page i want to have as one of my sections but I don't want logged in users to see that section, only logged out users. My page is [jonathanmusiclessons.com](http://jonathanmusiclessons.com)
You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way. For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css; ``` .logged_in .menu-class-here{display:none;} ``` That is to hide a menu item. Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example; ``` if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } ``` If you want to allow access to the page but hide a certain section from logged in users, you can do something like; ``` if ( is_page('slug') && ! is_user_logged_in() ) { //add the code here that you want to show to non-logged-in users } ``` **UPDATE** Add this to functions.php. You need to create a function to redirect and add it ``` function notallowed() { global $post; if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } } add_action( 'template_redirect', 'notallowed' ); ```
279,279
<p>I'm a newby and don't have much knowledge of programming. My website is <a href="https://www.laraellisphotography.com" rel="nofollow noreferrer">https://www.laraellisphotography.com</a> I'm using the Divina theme and I can't figure out how to remove the search bar. I tried to see if it's a widget but it appears to be hardcoded into the theme. It shows up under the menu I put in. Can somebody explain to me in very specific terms how to fix this? I'm using a plugin called advanced code editor but I really don't know what I'm doing. I tried putting in a show: none phrase in around where I thought the programming was for the search in the css styles sheet but it didn't change anything. Thanks for any help you can give me. :)</p>
[ { "answer_id": 279255, "author": "Rafael Cavalcante", "author_id": 68359, "author_profile": "https://wordpress.stackexchange.com/users/68359", "pm_score": 0, "selected": false, "text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">is_user_logged_in</a> wordpress function :)</p>\n\n<pre><code>if (!is_user_logged_in()) {\n // content for non-authenticated users\n}\n</code></pre>\n" }, { "answer_id": 279292, "author": "The Filipino Freelancer", "author_id": 126661, "author_profile": "https://wordpress.stackexchange.com/users/126661", "pm_score": 1, "selected": false, "text": "<p>You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.</p>\n\n<p>For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;</p>\n\n<pre><code>.logged_in .menu-class-here{display:none;}\n</code></pre>\n\n<p>That is to hide a menu item.\nNow, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n</code></pre>\n\n<p>If you want to allow access to the page but hide a certain section from logged in users, you can do something like;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; ! is_user_logged_in() ) {\n //add the code here that you want to show to non-logged-in users\n}\n</code></pre>\n\n<p><strong>UPDATE</strong>\nAdd this to functions.php. You need to create a function to redirect and add it</p>\n\n<pre><code>function notallowed() {\n global $post;\nif ( is_page('hire-the-freelancer') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n}\nadd_action( 'template_redirect', 'notallowed' );\n</code></pre>\n" } ]
2017/09/06
[ "https://wordpress.stackexchange.com/questions/279279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127381/" ]
I'm a newby and don't have much knowledge of programming. My website is <https://www.laraellisphotography.com> I'm using the Divina theme and I can't figure out how to remove the search bar. I tried to see if it's a widget but it appears to be hardcoded into the theme. It shows up under the menu I put in. Can somebody explain to me in very specific terms how to fix this? I'm using a plugin called advanced code editor but I really don't know what I'm doing. I tried putting in a show: none phrase in around where I thought the programming was for the search in the css styles sheet but it didn't change anything. Thanks for any help you can give me. :)
You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way. For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css; ``` .logged_in .menu-class-here{display:none;} ``` That is to hide a menu item. Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example; ``` if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } ``` If you want to allow access to the page but hide a certain section from logged in users, you can do something like; ``` if ( is_page('slug') && ! is_user_logged_in() ) { //add the code here that you want to show to non-logged-in users } ``` **UPDATE** Add this to functions.php. You need to create a function to redirect and add it ``` function notallowed() { global $post; if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } } add_action( 'template_redirect', 'notallowed' ); ```
279,280
<p>I have a few questions and I don't think the outcome I want is possible without adding a custom taxonomy and redoing a bunch of work.</p> <p>I have registered a custom post type - gallery - with taxonomies set to post_tag and category.</p> <p>I have the permalink structure set to /blog/%postname%/ so Posts can have the /blog/ base set using the default Posts section within WordPress.</p> <p>When I use get_category_link() for a category on the gallery custom post type, it links to /blog/ceremonies/ instead of /gallery/ceremonies/ which is what I'd like for anything on the gallery archive or single gallery page. For the blog, it would need to be /blog/category_name/ as it currently is.</p> <p>I know I can do the work from <a href="https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post">this question</a>, but I have a lot of work done already that I do not want to back track on. </p> <p><strong>My questions:</strong></p> <p>Is there a way have /blog/ceremonies/ and /gallery/ceremonies/ load the same categories, and I can filter them with what the /blog/ or /gallery/ is set to in the URL with $_SERVER['REQUEST_URI'] (or something similar) without creating a custom taxonomy?</p> <p>If not (I don't think there is), is there a way I can strip out the /blog/ out of the custom permalink so it just shows /ceremonies/ and still have /blog/ at the beginning of anything posted in the "Posts" section?</p> <p>Any help is appreciated. Thank you!</p>
[ { "answer_id": 279255, "author": "Rafael Cavalcante", "author_id": 68359, "author_profile": "https://wordpress.stackexchange.com/users/68359", "pm_score": 0, "selected": false, "text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">is_user_logged_in</a> wordpress function :)</p>\n\n<pre><code>if (!is_user_logged_in()) {\n // content for non-authenticated users\n}\n</code></pre>\n" }, { "answer_id": 279292, "author": "The Filipino Freelancer", "author_id": 126661, "author_profile": "https://wordpress.stackexchange.com/users/126661", "pm_score": 1, "selected": false, "text": "<p>You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.</p>\n\n<p>For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;</p>\n\n<pre><code>.logged_in .menu-class-here{display:none;}\n</code></pre>\n\n<p>That is to hide a menu item.\nNow, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n</code></pre>\n\n<p>If you want to allow access to the page but hide a certain section from logged in users, you can do something like;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; ! is_user_logged_in() ) {\n //add the code here that you want to show to non-logged-in users\n}\n</code></pre>\n\n<p><strong>UPDATE</strong>\nAdd this to functions.php. You need to create a function to redirect and add it</p>\n\n<pre><code>function notallowed() {\n global $post;\nif ( is_page('hire-the-freelancer') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n}\nadd_action( 'template_redirect', 'notallowed' );\n</code></pre>\n" } ]
2017/09/06
[ "https://wordpress.stackexchange.com/questions/279280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127382/" ]
I have a few questions and I don't think the outcome I want is possible without adding a custom taxonomy and redoing a bunch of work. I have registered a custom post type - gallery - with taxonomies set to post\_tag and category. I have the permalink structure set to /blog/%postname%/ so Posts can have the /blog/ base set using the default Posts section within WordPress. When I use get\_category\_link() for a category on the gallery custom post type, it links to /blog/ceremonies/ instead of /gallery/ceremonies/ which is what I'd like for anything on the gallery archive or single gallery page. For the blog, it would need to be /blog/category\_name/ as it currently is. I know I can do the work from [this question](https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post), but I have a lot of work done already that I do not want to back track on. **My questions:** Is there a way have /blog/ceremonies/ and /gallery/ceremonies/ load the same categories, and I can filter them with what the /blog/ or /gallery/ is set to in the URL with $\_SERVER['REQUEST\_URI'] (or something similar) without creating a custom taxonomy? If not (I don't think there is), is there a way I can strip out the /blog/ out of the custom permalink so it just shows /ceremonies/ and still have /blog/ at the beginning of anything posted in the "Posts" section? Any help is appreciated. Thank you!
You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way. For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css; ``` .logged_in .menu-class-here{display:none;} ``` That is to hide a menu item. Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example; ``` if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } ``` If you want to allow access to the page but hide a certain section from logged in users, you can do something like; ``` if ( is_page('slug') && ! is_user_logged_in() ) { //add the code here that you want to show to non-logged-in users } ``` **UPDATE** Add this to functions.php. You need to create a function to redirect and add it ``` function notallowed() { global $post; if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } } add_action( 'template_redirect', 'notallowed' ); ```
279,294
<p>I created an image size:</p> <pre><code>add_image_size('slider', 1920, 1080, true); </code></pre> <p>Now, i thought hard cropping meant that WordPress would zoom into the picture until it obtains that size and proportion no matter what. </p> <p>Well, if User enters a vertical image, say 784x1200, What WordPress is doing is getting me an 784x1080 image, so it ignores the asked width because it matches height first?? </p>
[ { "answer_id": 279255, "author": "Rafael Cavalcante", "author_id": 68359, "author_profile": "https://wordpress.stackexchange.com/users/68359", "pm_score": 0, "selected": false, "text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">is_user_logged_in</a> wordpress function :)</p>\n\n<pre><code>if (!is_user_logged_in()) {\n // content for non-authenticated users\n}\n</code></pre>\n" }, { "answer_id": 279292, "author": "The Filipino Freelancer", "author_id": 126661, "author_profile": "https://wordpress.stackexchange.com/users/126661", "pm_score": 1, "selected": false, "text": "<p>You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.</p>\n\n<p>For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;</p>\n\n<pre><code>.logged_in .menu-class-here{display:none;}\n</code></pre>\n\n<p>That is to hide a menu item.\nNow, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n</code></pre>\n\n<p>If you want to allow access to the page but hide a certain section from logged in users, you can do something like;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; ! is_user_logged_in() ) {\n //add the code here that you want to show to non-logged-in users\n}\n</code></pre>\n\n<p><strong>UPDATE</strong>\nAdd this to functions.php. You need to create a function to redirect and add it</p>\n\n<pre><code>function notallowed() {\n global $post;\nif ( is_page('hire-the-freelancer') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n}\nadd_action( 'template_redirect', 'notallowed' );\n</code></pre>\n" } ]
2017/09/07
[ "https://wordpress.stackexchange.com/questions/279294", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124731/" ]
I created an image size: ``` add_image_size('slider', 1920, 1080, true); ``` Now, i thought hard cropping meant that WordPress would zoom into the picture until it obtains that size and proportion no matter what. Well, if User enters a vertical image, say 784x1200, What WordPress is doing is getting me an 784x1080 image, so it ignores the asked width because it matches height first??
You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way. For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css; ``` .logged_in .menu-class-here{display:none;} ``` That is to hide a menu item. Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example; ``` if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } ``` If you want to allow access to the page but hide a certain section from logged in users, you can do something like; ``` if ( is_page('slug') && ! is_user_logged_in() ) { //add the code here that you want to show to non-logged-in users } ``` **UPDATE** Add this to functions.php. You need to create a function to redirect and add it ``` function notallowed() { global $post; if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } } add_action( 'template_redirect', 'notallowed' ); ```
279,321
<p>For my client site, I am planning to enable link post image to post a link on blog list page, the site uses custom WordPress theme developed by the previous developer.</p> <p>For blog post list page he created as content.php and for the single post he created <code>content-page.php</code> </p> <p>Even if I add the featured image I can't able to see that featured image, only the image inside of the post is showing.</p> <p>How to achieve this? </p> <p>Here is the code for content.php</p> <pre><code>&lt;?php /** * Template part for displaying posts * * @link https://codex.wordpress.org/Template_Hierarchy * * @package Blog */ ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;header class="entry-header"&gt; &lt;?php if ( is_single() ) : the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); else : the_title( '&lt;h2 class="entry-title"&gt;&lt;a href="' . esc_url( get_permalink() ) . '" rel="bookmark" &gt;', '&lt;/a&gt;&lt;/h2&gt;' ); endif; if ( 'post' === get_post_type() ) : ?&gt; &lt;h4 class="meta text-muted"&gt; &lt;?php bfablog_posted_on(); ?&gt; &lt;/h4&gt;&lt;!-- .entry-meta --&gt; &lt;?php endif; ?&gt; &lt;!-- AddThis Button BEGIN --&gt; &lt;div class="addthis_inline_share_toolbox_mzc3" style="margin-bottom:20px;" data-title="&lt;?php the_title() ?&gt;" data-url="&lt;?php the_permalink(); ?&gt;" &lt;/div&gt; &lt;!-- AddThis Button END --&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class="entry-content"&gt; &lt;?php the_content( sprintf ( /* translators: %s: Name of current post. */ wp_kses(__( 'Read more', 'bfablog' ), array( 'span' =&gt; array( 'class' =&gt; array() ) ) ), the_title( '&lt;span class="screen-reader-text"&gt;"', '"&lt;/span&gt;', false ) ) ); wp_link_pages( array( 'before' =&gt; '&lt;div class= "page-links"&gt;'. esc_html__('Pages:', 'bfablog' ), 'after' =&gt; '&lt;/div&gt;', ) ); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;footer class="entry-footer"&gt; &lt;?php bfablog_entry_footer(); ?&gt; &lt;/footer&gt;&lt;!-- .entry-footer --&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; &lt;hr&gt; &lt;script type="text/javascript"&gt; var addthis_config = { ui_language: "{{ site.lang }}" }; var addthis_share = { // ... members go here } &lt;/script&gt; &lt;!-- Go to www.addthis.com/dashboard to customize your tools --&gt; &lt;script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-586c401922d76d24"&gt;&lt;/script&gt; </code></pre> <p>Here is the code for content-page.php</p> <pre><code>&lt;?php /** * Template part for displaying page content in page.php * * @link https://codex.wordpress.org/Template_Hierarchy * * @package BfA_Blog */ ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;header class="entry-header"&gt; &lt;?php the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); ?&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class="entry-content"&gt;&lt;hr&gt; &lt;?php the_content(); wp_link_pages(array( 'before' =&gt; '&lt;div class="page-links"&gt;' . esc_html__('Pages:','bfablog'), 'after' =&gt; '&lt;/div&gt;', ) ); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php if ( get_edit_post_link() ) : ?&gt; &lt;footer class="entry-footer"&gt; &lt;?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'bfablog' ), the_title( '&lt;span class="screen-reader-text"&gt;"', '"&lt;/span&gt;', false ) ), '&lt;span class="edit-link"&gt;', '&lt;/span&gt;' ); ?&gt; &lt;/footer&gt;&lt;!-- .entry-footer --&gt; &lt;?php endif; ?&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; </code></pre>
[ { "answer_id": 279255, "author": "Rafael Cavalcante", "author_id": 68359, "author_profile": "https://wordpress.stackexchange.com/users/68359", "pm_score": 0, "selected": false, "text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">is_user_logged_in</a> wordpress function :)</p>\n\n<pre><code>if (!is_user_logged_in()) {\n // content for non-authenticated users\n}\n</code></pre>\n" }, { "answer_id": 279292, "author": "The Filipino Freelancer", "author_id": 126661, "author_profile": "https://wordpress.stackexchange.com/users/126661", "pm_score": 1, "selected": false, "text": "<p>You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.</p>\n\n<p>For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;</p>\n\n<pre><code>.logged_in .menu-class-here{display:none;}\n</code></pre>\n\n<p>That is to hide a menu item.\nNow, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n</code></pre>\n\n<p>If you want to allow access to the page but hide a certain section from logged in users, you can do something like;</p>\n\n<pre><code>if ( is_page('slug') &amp;&amp; ! is_user_logged_in() ) {\n //add the code here that you want to show to non-logged-in users\n}\n</code></pre>\n\n<p><strong>UPDATE</strong>\nAdd this to functions.php. You need to create a function to redirect and add it</p>\n\n<pre><code>function notallowed() {\n global $post;\nif ( is_page('hire-the-freelancer') &amp;&amp; is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users\n wp_redirect( 'http://www.example.com/desired-page/', 301 ); \n exit;\n}\n}\nadd_action( 'template_redirect', 'notallowed' );\n</code></pre>\n" } ]
2017/09/07
[ "https://wordpress.stackexchange.com/questions/279321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127412/" ]
For my client site, I am planning to enable link post image to post a link on blog list page, the site uses custom WordPress theme developed by the previous developer. For blog post list page he created as content.php and for the single post he created `content-page.php` Even if I add the featured image I can't able to see that featured image, only the image inside of the post is showing. How to achieve this? Here is the code for content.php ``` <?php /** * Template part for displaying posts * * @link https://codex.wordpress.org/Template_Hierarchy * * @package Blog */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php if ( is_single() ) : the_title( '<h1 class="entry-title">', '</h1>' ); else : the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark" >', '</a></h2>' ); endif; if ( 'post' === get_post_type() ) : ?> <h4 class="meta text-muted"> <?php bfablog_posted_on(); ?> </h4><!-- .entry-meta --> <?php endif; ?> <!-- AddThis Button BEGIN --> <div class="addthis_inline_share_toolbox_mzc3" style="margin-bottom:20px;" data-title="<?php the_title() ?>" data-url="<?php the_permalink(); ?>" </div> <!-- AddThis Button END --> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content( sprintf ( /* translators: %s: Name of current post. */ wp_kses(__( 'Read more', 'bfablog' ), array( 'span' => array( 'class' => array() ) ) ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ) ); wp_link_pages( array( 'before' => '<div class= "page-links">'. esc_html__('Pages:', 'bfablog' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php bfablog_entry_footer(); ?> </footer><!-- .entry-footer --> </article><!-- #post-## --> <hr> <script type="text/javascript"> var addthis_config = { ui_language: "{{ site.lang }}" }; var addthis_share = { // ... members go here } </script> <!-- Go to www.addthis.com/dashboard to customize your tools --> <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-586c401922d76d24"></script> ``` Here is the code for content-page.php ``` <?php /** * Template part for displaying page content in page.php * * @link https://codex.wordpress.org/Template_Hierarchy * * @package BfA_Blog */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <div class="entry-content"><hr> <?php the_content(); wp_link_pages(array( 'before' => '<div class="page-links">' . esc_html__('Pages:','bfablog'), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <?php if ( get_edit_post_link() ) : ?> <footer class="entry-footer"> <?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'bfablog' ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> <?php endif; ?> </article><!-- #post-## --> ```
You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way. For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css; ``` .logged_in .menu-class-here{display:none;} ``` That is to hide a menu item. Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example; ``` if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } ``` If you want to allow access to the page but hide a certain section from logged in users, you can do something like; ``` if ( is_page('slug') && ! is_user_logged_in() ) { //add the code here that you want to show to non-logged-in users } ``` **UPDATE** Add this to functions.php. You need to create a function to redirect and add it ``` function notallowed() { global $post; if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users wp_redirect( 'http://www.example.com/desired-page/', 301 ); exit; } } add_action( 'template_redirect', 'notallowed' ); ```
279,344
<p>I am customizing the Woocommerce Storefront theme. In the product-list pages (category page, shop page), I would like to display the available sizes of the product when the user hover with its mouse on the image of a product. So I need to add html/php code that will display this on hover:</p> <p><strong>Available sizes:</strong></p> <p><strong>S, M, L, XL</strong></p> <p>or </p> <p><strong>Sold out</strong></p> <p><strong>Notify me when the product is in stock</strong></p> <p>I would like to do this in the functions.php of my child theme.</p> <p>Should I use this hook to add html ?</p> <pre><code>woocommerce_before_shop_loop_item_title </code></pre> <p>I have started to code this, but I need help to go </p> <pre><code>remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10); add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10); /** * WooCommerce Loop Product Thumbs **/ if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) { function woocommerce_template_loop_product_thumbnail() { echo woocommerce_get_product_thumbnail(); } } /** * WooCommerce Product Thumbnail **/ if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) { function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) { global $post, $woocommerce; $output = '&lt;div class="imagewrapper"&gt;'; if ( has_post_thumbnail() ) { $output .= get_the_post_thumbnail( $post-&gt;ID, $size ); } else { $output .= '&lt;img src="'. woocommerce_placeholder_img_src() .'" alt="Placeholder" width="' . $placeholder_width . '" height="' . $placeholder_height . '" /&gt;'; } //$product .= wc_get_product($post-&gt;ID ) ; //$name .= $product-&gt;get_name(); $output .= '&lt;div class="sizeAvailHover"&gt;'; //$output .= $name; $output .= '&lt;/div&gt;'; $output .= '&lt;/div&gt;'; return $output; } } </code></pre>
[ { "answer_id": 279349, "author": "finitesource", "author_id": 127371, "author_profile": "https://wordpress.stackexchange.com/users/127371", "pm_score": 0, "selected": false, "text": "<p>Yes. The <code>woocommerce_template_loop_product_thumbnail</code> is hooked into the <code>woocommerce_before_shop_loop_item_title</code> action, so that would be a good way to go about it.</p>\n" }, { "answer_id": 281257, "author": "Louis", "author_id": 121787, "author_profile": "https://wordpress.stackexchange.com/users/121787", "pm_score": 3, "selected": true, "text": "<p>Here's the code I finally used for those interested:</p>\n\n<pre><code>/* This snippet removes the action that inserts thumbnails to products in the loop\n * and re-adds the function customized with our wrapper in it.\n * It applies to all archives with products.\n *\n * @original plugin: WooCommerce\n * @author of snippet: Brian Krogsard\n */\n\nremove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);\nadd_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);\n\n/**\n * WooCommerce Loop Product Thumbs\n **/\n\n if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {\n function woocommerce_template_loop_product_thumbnail() {\n echo woocommerce_get_product_thumbnail();\n } \n }\n\n/**\n * WooCommerce Product Thumbnail\n **/\n\n if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) {\n\n function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) {\n global $post, $wp_query, $woocommerce, $attributes;\n // if ( ! $placeholder_width ) {\n // $placeholder_width = $woocommerce-&gt;get_image_size( 'shop_catalog_image_width' );\n // }\n // if ( ! $placeholder_height ){\n // $placeholder_height = $woocommerce-&gt;get_image_size( 'shop_catalog_image_height' );\n // }\n\n $output = '&lt;div class=\"imagewrapper\"&gt;';\n if ( has_post_thumbnail() ) {\n\n $output .= get_the_post_thumbnail( $post-&gt;ID, $size ); \n\n } else {\n\n $output .= '&lt;img src=\"'. woocommerce_placeholder_img_src() .'\" alt=\"Placeholder\" width=\"' . $placeholder_width . '\" height=\"' . $placeholder_height . '\" /&gt;';\n\n }\n\n //$product .= wc_get_product($post-&gt;ID ) ;\n //$name .= $product-&gt;get_name();\n\n $output .= '&lt;div class=\"sizeAvailHover\"&gt;';\n //$output .= $name;\n //$product .= wc_get_product($post-&gt;ID ) ;\n $product = wc_get_product( $wp_query-&gt;post );\n\n\n //echo get_post_format();\n\n // echo 'total stock : ';\n // echo $product-&gt;is_in_stock();\n\n\n\n if ( $product-&gt;is_type( 'variable' ) ) {\n // $attributes .= $product-&gt;list_attributes();\n // echo print_r($attributes);\n // $attributes = $product-&gt;get_attributes();\n // echo print_r($attributes);\n // $attributes .= $product-&gt;wc_display_product_attributes();\n // echo print_r($attributes);\n // $attributes .= $product-&gt;get_variation_attributes();\n // echo print_r($attributes);\n\n\n if($product-&gt;is_in_stock()) {\n $output .= ' Available sizes: &lt;br/&gt;';\n $variations = $product-&gt;get_available_variations();\n $i = 0;\n foreach($variations as $variation){\n $variation_id = $variation['variation_id'];\n $variation_obj = new WC_Product_variation($variation_id);\n $stock = $variation_obj-&gt;get_stock_quantity();\n //echo $stock;\n // echo '--';\n //echo $variation_obj-&gt;get_sku();\n //echo print_r($variation_obj-&gt;get_variation_attributes());\n $dummy = $variation_obj-&gt;get_variation_attributes();\n //echo gettype($stock);\n if ((is_int($stock) || ctype_digit($stock)) &amp;&amp; (int)$stock &gt; 0 ) { // int }\n //if ($stock &gt; 0 ) {\n //echo $variation_obj-&gt;get_attributes();\n //echo 'yesssss';\n // echo print_r($dummy['attribute_pa_size']);\n $output .= '&lt;span class=\"availSize\"&gt;' . strtoupper($dummy['attribute_pa_size']) . '&lt;/span&gt;';\n } else {\n // echo print_r($dummy['attribute_pa_size']);\n $output .= '&lt;span class=\"unavailSize\"&gt;' . strtoupper($dummy['attribute_pa_size']) . '&lt;/span&gt;';\n }\n if(++$i !== count($variations)) {\n $output .= ', ';\n }\n\n //echo '&lt;br/&gt;';\n\n }\n } else {\n $output .= ' Sold out&lt;br/&gt;Notify me when the product is back in stock';\n }\n\n\n // if ( ! $attributes ) {\n // echo \"No attributes\";\n // }\n // foreach ( $attributes as $attribute ) {\n\n // echo $attribute['name'] . \": \";\n // $product_attributes = array();\n // $product_attributes = explode('|',$attribute['value']);\n\n // $attributes_dropdown = '&lt;select&gt;';\n\n // foreach ( $product_attributes as $pa ) {\n // $attributes_dropdown .= '&lt;option value=\"' . $pa . '\"&gt;' . $pa . '&lt;/option&gt;';\n // }\n\n // $attributes_dropdown .= '&lt;/select&gt;';\n\n // echo $attributes_dropdown;\n // }\n }\n\n $output .= '&lt;/div&gt;';\n\n $output .= '&lt;/div&gt;';\n\n return $output;\n }\n }\n</code></pre>\n" } ]
2017/09/07
[ "https://wordpress.stackexchange.com/questions/279344", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121787/" ]
I am customizing the Woocommerce Storefront theme. In the product-list pages (category page, shop page), I would like to display the available sizes of the product when the user hover with its mouse on the image of a product. So I need to add html/php code that will display this on hover: **Available sizes:** **S, M, L, XL** or **Sold out** **Notify me when the product is in stock** I would like to do this in the functions.php of my child theme. Should I use this hook to add html ? ``` woocommerce_before_shop_loop_item_title ``` I have started to code this, but I need help to go ``` remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10); add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10); /** * WooCommerce Loop Product Thumbs **/ if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) { function woocommerce_template_loop_product_thumbnail() { echo woocommerce_get_product_thumbnail(); } } /** * WooCommerce Product Thumbnail **/ if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) { function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) { global $post, $woocommerce; $output = '<div class="imagewrapper">'; if ( has_post_thumbnail() ) { $output .= get_the_post_thumbnail( $post->ID, $size ); } else { $output .= '<img src="'. woocommerce_placeholder_img_src() .'" alt="Placeholder" width="' . $placeholder_width . '" height="' . $placeholder_height . '" />'; } //$product .= wc_get_product($post->ID ) ; //$name .= $product->get_name(); $output .= '<div class="sizeAvailHover">'; //$output .= $name; $output .= '</div>'; $output .= '</div>'; return $output; } } ```
Here's the code I finally used for those interested: ``` /* This snippet removes the action that inserts thumbnails to products in the loop * and re-adds the function customized with our wrapper in it. * It applies to all archives with products. * * @original plugin: WooCommerce * @author of snippet: Brian Krogsard */ remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10); add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10); /** * WooCommerce Loop Product Thumbs **/ if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) { function woocommerce_template_loop_product_thumbnail() { echo woocommerce_get_product_thumbnail(); } } /** * WooCommerce Product Thumbnail **/ if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) { function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) { global $post, $wp_query, $woocommerce, $attributes; // if ( ! $placeholder_width ) { // $placeholder_width = $woocommerce->get_image_size( 'shop_catalog_image_width' ); // } // if ( ! $placeholder_height ){ // $placeholder_height = $woocommerce->get_image_size( 'shop_catalog_image_height' ); // } $output = '<div class="imagewrapper">'; if ( has_post_thumbnail() ) { $output .= get_the_post_thumbnail( $post->ID, $size ); } else { $output .= '<img src="'. woocommerce_placeholder_img_src() .'" alt="Placeholder" width="' . $placeholder_width . '" height="' . $placeholder_height . '" />'; } //$product .= wc_get_product($post->ID ) ; //$name .= $product->get_name(); $output .= '<div class="sizeAvailHover">'; //$output .= $name; //$product .= wc_get_product($post->ID ) ; $product = wc_get_product( $wp_query->post ); //echo get_post_format(); // echo 'total stock : '; // echo $product->is_in_stock(); if ( $product->is_type( 'variable' ) ) { // $attributes .= $product->list_attributes(); // echo print_r($attributes); // $attributes = $product->get_attributes(); // echo print_r($attributes); // $attributes .= $product->wc_display_product_attributes(); // echo print_r($attributes); // $attributes .= $product->get_variation_attributes(); // echo print_r($attributes); if($product->is_in_stock()) { $output .= ' Available sizes: <br/>'; $variations = $product->get_available_variations(); $i = 0; foreach($variations as $variation){ $variation_id = $variation['variation_id']; $variation_obj = new WC_Product_variation($variation_id); $stock = $variation_obj->get_stock_quantity(); //echo $stock; // echo '--'; //echo $variation_obj->get_sku(); //echo print_r($variation_obj->get_variation_attributes()); $dummy = $variation_obj->get_variation_attributes(); //echo gettype($stock); if ((is_int($stock) || ctype_digit($stock)) && (int)$stock > 0 ) { // int } //if ($stock > 0 ) { //echo $variation_obj->get_attributes(); //echo 'yesssss'; // echo print_r($dummy['attribute_pa_size']); $output .= '<span class="availSize">' . strtoupper($dummy['attribute_pa_size']) . '</span>'; } else { // echo print_r($dummy['attribute_pa_size']); $output .= '<span class="unavailSize">' . strtoupper($dummy['attribute_pa_size']) . '</span>'; } if(++$i !== count($variations)) { $output .= ', '; } //echo '<br/>'; } } else { $output .= ' Sold out<br/>Notify me when the product is back in stock'; } // if ( ! $attributes ) { // echo "No attributes"; // } // foreach ( $attributes as $attribute ) { // echo $attribute['name'] . ": "; // $product_attributes = array(); // $product_attributes = explode('|',$attribute['value']); // $attributes_dropdown = '<select>'; // foreach ( $product_attributes as $pa ) { // $attributes_dropdown .= '<option value="' . $pa . '">' . $pa . '</option>'; // } // $attributes_dropdown .= '</select>'; // echo $attributes_dropdown; // } } $output .= '</div>'; $output .= '</div>'; return $output; } } ```
279,353
<p>I'm trying to organize my search results page based on an ACF subfield value of a repeater field. I would like a LIKE result rather than =.</p> <p>So far, I got the following (modified with help below, but still not working):</p> <pre><code>// Modify meta key to allow wildcard function add_wildcard_to_meta_key_filter( $where ) { $where = str_replace("meta_key = 'test_repeater_%", "meta_key LIKE 'test_repeater_%", $where); return $where; } add_filter('posts_where', 'add_wildcard_to_meta_key_filter'); //Modify search query function alter_search_query($query) { if ( !$query-&gt;is_search ) return $query; $search = $query-&gt;query; $query-&gt;set('post_type' ,'page'); $query-&gt;set('meta_query', array( array( 'meta_key' =&gt; 'test_repeater_%_test_sub_field', 'meta_value' =&gt; '%'.$search.'%', 'compare' =&gt; 'LIKE', ), )); $query-&gt;set('s', ''); } add_action('pre_get_posts','alter_search_query'); </code></pre> <p>It works fine if I add the exact value, i.e. "beef tenderloin", but if I enter "beef" it fails. How do I get the search to be more generic?</p> <p>I installed the Query Monitor plugin and noticed I got the following SQL</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wpfb_posts.ID FROM wpfb_posts INNER JOIN wpfb_postmeta ON ( wpfb_posts.ID = wpfb_postmeta.post_id ) WHERE 1=1 AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field' AND wpfb_postmeta.meta_value IN ('beef') ) ) AND wpfb_posts.post_type = 'page' AND (wpfb_posts.post_status = 'publish' OR wpfb_posts.post_status = 'acf-disabled' OR wpfb_posts.post_status = 'private') GROUP BY wpfb_posts.ID ORDER BY wpfb_posts.post_date DESC LIMIT 0, 10 </code></pre> <p>If I change this:</p> <pre><code>AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field' AND wpfb_postmeta.meta_value IN ('beef') ) ) </code></pre> <p>To this:</p> <pre><code>AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field' AND wpfb_postmeta.meta_value LIKE '%beef%' ) ) </code></pre> <p>And run that in phpMyAdmin's SQL, I get the desired row. The question is, how can I change the query to look like that using WordPress functions?</p>
[ { "answer_id": 279355, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>You need to add Wildcards to your meta_value.</p>\n\n<p>Change </p>\n\n<pre><code>$query-&gt;set('meta_query', array(\n array(\n 'meta_key' =&gt; 'test_repeater_%_test_sub_field',\n 'meta_value' =&gt; $search,\n 'compare' =&gt; 'LIKE',\n ),\n ));\n</code></pre>\n\n<p>To</p>\n\n<pre><code>$query-&gt;set('meta_query', array(\n array(\n 'meta_key' =&gt; 'test_repeater_%_test_sub_field',\n 'meta_value' =&gt; '%'.$search.'%',\n 'compare' =&gt; 'LIKE',\n ),\n ));\n</code></pre>\n" }, { "answer_id": 371151, "author": "Muhammad Asad", "author_id": 191684, "author_profile": "https://wordpress.stackexchange.com/users/191684", "pm_score": 0, "selected": false, "text": "<p>first you need to loop how many times repeater has values\nexample</p>\n<p>anada_number_0_anada_number <br>\nanada_number_1_anada_number <br>\nanada_number_2_anada_number <br></p>\n<p>In my case i have five times repeater field <br></p>\n<pre><code>for( $i=0; $i&lt;5; $i++ ){ \n $meta_query['anada_number'][] = array(\n 'key' =&gt; 'anada_number_'.$i.'_anada_number',\n 'value' =&gt; $anada_number,\n );\n }\n</code></pre>\n<p>then use it in query arg <br></p>\n<pre><code>$arg = array(\n$meta_query['anada_number']\n);\n\n$wp_query = new WP_Query($arg); \n</code></pre>\n" } ]
2017/09/07
[ "https://wordpress.stackexchange.com/questions/279353", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94213/" ]
I'm trying to organize my search results page based on an ACF subfield value of a repeater field. I would like a LIKE result rather than =. So far, I got the following (modified with help below, but still not working): ``` // Modify meta key to allow wildcard function add_wildcard_to_meta_key_filter( $where ) { $where = str_replace("meta_key = 'test_repeater_%", "meta_key LIKE 'test_repeater_%", $where); return $where; } add_filter('posts_where', 'add_wildcard_to_meta_key_filter'); //Modify search query function alter_search_query($query) { if ( !$query->is_search ) return $query; $search = $query->query; $query->set('post_type' ,'page'); $query->set('meta_query', array( array( 'meta_key' => 'test_repeater_%_test_sub_field', 'meta_value' => '%'.$search.'%', 'compare' => 'LIKE', ), )); $query->set('s', ''); } add_action('pre_get_posts','alter_search_query'); ``` It works fine if I add the exact value, i.e. "beef tenderloin", but if I enter "beef" it fails. How do I get the search to be more generic? I installed the Query Monitor plugin and noticed I got the following SQL ``` SELECT SQL_CALC_FOUND_ROWS wpfb_posts.ID FROM wpfb_posts INNER JOIN wpfb_postmeta ON ( wpfb_posts.ID = wpfb_postmeta.post_id ) WHERE 1=1 AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field' AND wpfb_postmeta.meta_value IN ('beef') ) ) AND wpfb_posts.post_type = 'page' AND (wpfb_posts.post_status = 'publish' OR wpfb_posts.post_status = 'acf-disabled' OR wpfb_posts.post_status = 'private') GROUP BY wpfb_posts.ID ORDER BY wpfb_posts.post_date DESC LIMIT 0, 10 ``` If I change this: ``` AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field' AND wpfb_postmeta.meta_value IN ('beef') ) ) ``` To this: ``` AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field' AND wpfb_postmeta.meta_value LIKE '%beef%' ) ) ``` And run that in phpMyAdmin's SQL, I get the desired row. The question is, how can I change the query to look like that using WordPress functions?
You need to add Wildcards to your meta\_value. Change ``` $query->set('meta_query', array( array( 'meta_key' => 'test_repeater_%_test_sub_field', 'meta_value' => $search, 'compare' => 'LIKE', ), )); ``` To ``` $query->set('meta_query', array( array( 'meta_key' => 'test_repeater_%_test_sub_field', 'meta_value' => '%'.$search.'%', 'compare' => 'LIKE', ), )); ```
279,380
<p>Have a custom post type, where each post is a gallery, and each has an Advanced Custom Fields Gallery field that has say 5-20 images each. Also have a custom post type post template as seen below (stripped out most of the code to focus on parts that are relevant to this.) The comments in the code explain which each part does. Overall it appears to all work, however no matter what post I'm on in this custom post type, such as example.com/gallery/gallery-1, example.com/gallery/gallery-2, example.com/gallery/gallery-3, etc. It shows the same featured image and same thumbnails on each page. It appears to be pulling the first gallery from the first post, rather than on each page checking to pull in the gallery items associated with that page.</p> <p>I'm sure it's simple such as a matter of needing to flush/reset a loop or such, but struggling to find the right way to describe it to find the answer on Google. Had it working originally, but once I had to add loops inside of loops the issue started. If anyone has any idea would great. Will keep researching in the meantime.</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div id="main"&gt; &lt;?php //Checks gallery custom post type and finds the current pages entry $args = array( 'post_type' =&gt; 'customers_gallery', 'posts_per_page' =&gt; 1 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;div&gt; &lt;?php //Looks up the advanced custom field gallery associated with this post $hero = get_field('gallery_images'); ?&gt; &lt;!-- //Show the first image in that gallery --&gt; &lt;img src="&lt;?php echo $hero[0]['url']; ?&gt;" class="main-image" style="width: 484px;"&gt; &lt;!-- //Shows title of this page --&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php //Looks up the advanced custom field gallery associated with this post $images = get_field('gallery_images'); //Loops through all the gallery image showing a thumbnail for each and each is linked to its full size if( $images ): ?&gt; &lt;ul&gt; &lt;?php foreach( $images as $image ): ?&gt; &lt;li&gt; &lt;a href="&lt;?php echo $image['url']; ?&gt;"&gt; &lt;img src="&lt;?php echo $image['sizes']['gallery-landscape-thb']; ?&gt;" alt="&lt;?php echo $image['alt']; ?&gt;" /&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;div&gt; &lt;ul&gt; &lt;?php //Looks up all the pages in this custom post type and lists the titles of the first 12 and linked to respective pages $custom_query = new WP_Query( array( 'post_type' =&gt; 'customers_gallery', 'posts_per_page' =&gt; 12 ) ); if ( $custom_query-&gt;have_posts() ) : while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; endif; wp_reset_query(); ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;!-- /#main --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>UPDATE</p> <p>Some have noted to add a reset, but I'm still thinking the issue is something else. Since I can remove nearly all the code in template and get it down just to the following and it still echos the same title no mater which post im viewing in the gallery custom post type (it shows the first title in the list of posts in the gallery custom post type, where is it should pull in the title for that particular page. The title in the tab is correct.</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'customers_gallery', 'posts_per_page' =&gt; 1 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;?php echo the_title(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>UPDATE 2</p> <p>Returned to the original code that I posted in this message and simply removed the code noted in my second post aka, that $args = array( 'post_type' => 'customers_gallery'... and all works. So seems the issue was I was trying to create a loop for the custom post type but looks like that is not needed when using a single-[custom-post-type-name].php. </p>
[ { "answer_id": 279355, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>You need to add Wildcards to your meta_value.</p>\n\n<p>Change </p>\n\n<pre><code>$query-&gt;set('meta_query', array(\n array(\n 'meta_key' =&gt; 'test_repeater_%_test_sub_field',\n 'meta_value' =&gt; $search,\n 'compare' =&gt; 'LIKE',\n ),\n ));\n</code></pre>\n\n<p>To</p>\n\n<pre><code>$query-&gt;set('meta_query', array(\n array(\n 'meta_key' =&gt; 'test_repeater_%_test_sub_field',\n 'meta_value' =&gt; '%'.$search.'%',\n 'compare' =&gt; 'LIKE',\n ),\n ));\n</code></pre>\n" }, { "answer_id": 371151, "author": "Muhammad Asad", "author_id": 191684, "author_profile": "https://wordpress.stackexchange.com/users/191684", "pm_score": 0, "selected": false, "text": "<p>first you need to loop how many times repeater has values\nexample</p>\n<p>anada_number_0_anada_number <br>\nanada_number_1_anada_number <br>\nanada_number_2_anada_number <br></p>\n<p>In my case i have five times repeater field <br></p>\n<pre><code>for( $i=0; $i&lt;5; $i++ ){ \n $meta_query['anada_number'][] = array(\n 'key' =&gt; 'anada_number_'.$i.'_anada_number',\n 'value' =&gt; $anada_number,\n );\n }\n</code></pre>\n<p>then use it in query arg <br></p>\n<pre><code>$arg = array(\n$meta_query['anada_number']\n);\n\n$wp_query = new WP_Query($arg); \n</code></pre>\n" } ]
2017/09/07
[ "https://wordpress.stackexchange.com/questions/279380", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5465/" ]
Have a custom post type, where each post is a gallery, and each has an Advanced Custom Fields Gallery field that has say 5-20 images each. Also have a custom post type post template as seen below (stripped out most of the code to focus on parts that are relevant to this.) The comments in the code explain which each part does. Overall it appears to all work, however no matter what post I'm on in this custom post type, such as example.com/gallery/gallery-1, example.com/gallery/gallery-2, example.com/gallery/gallery-3, etc. It shows the same featured image and same thumbnails on each page. It appears to be pulling the first gallery from the first post, rather than on each page checking to pull in the gallery items associated with that page. I'm sure it's simple such as a matter of needing to flush/reset a loop or such, but struggling to find the right way to describe it to find the answer on Google. Had it working originally, but once I had to add loops inside of loops the issue started. If anyone has any idea would great. Will keep researching in the meantime. ``` <?php get_header(); ?> <div id="main"> <?php //Checks gallery custom post type and finds the current pages entry $args = array( 'post_type' => 'customers_gallery', 'posts_per_page' => 1 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <div> <?php //Looks up the advanced custom field gallery associated with this post $hero = get_field('gallery_images'); ?> <!-- //Show the first image in that gallery --> <img src="<?php echo $hero[0]['url']; ?>" class="main-image" style="width: 484px;"> <!-- //Shows title of this page --> <h3><?php the_title(); ?></h3> <?php //Looks up the advanced custom field gallery associated with this post $images = get_field('gallery_images'); //Loops through all the gallery image showing a thumbnail for each and each is linked to its full size if( $images ): ?> <ul> <?php foreach( $images as $image ): ?> <li> <a href="<?php echo $image['url']; ?>"> <img src="<?php echo $image['sizes']['gallery-landscape-thb']; ?>" alt="<?php echo $image['alt']; ?>" /> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?> <div> <ul> <?php //Looks up all the pages in this custom post type and lists the titles of the first 12 and linked to respective pages $custom_query = new WP_Query( array( 'post_type' => 'customers_gallery', 'posts_per_page' => 12 ) ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; endif; wp_reset_query(); ?> </ul> </div> </div> <?php endwhile; ?> </div> <!-- /#main --> <?php get_footer(); ?> ``` UPDATE Some have noted to add a reset, but I'm still thinking the issue is something else. Since I can remove nearly all the code in template and get it down just to the following and it still echos the same title no mater which post im viewing in the gallery custom post type (it shows the first title in the list of posts in the gallery custom post type, where is it should pull in the title for that particular page. The title in the tab is correct. ``` <?php get_header(); ?> <?php $args = array( 'post_type' => 'customers_gallery', 'posts_per_page' => 1 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php echo the_title(); ?> <?php endwhile; ?> <?php get_footer(); ?> ``` UPDATE 2 Returned to the original code that I posted in this message and simply removed the code noted in my second post aka, that $args = array( 'post\_type' => 'customers\_gallery'... and all works. So seems the issue was I was trying to create a loop for the custom post type but looks like that is not needed when using a single-[custom-post-type-name].php.
You need to add Wildcards to your meta\_value. Change ``` $query->set('meta_query', array( array( 'meta_key' => 'test_repeater_%_test_sub_field', 'meta_value' => $search, 'compare' => 'LIKE', ), )); ``` To ``` $query->set('meta_query', array( array( 'meta_key' => 'test_repeater_%_test_sub_field', 'meta_value' => '%'.$search.'%', 'compare' => 'LIKE', ), )); ```